forked from shadowgate15/automation-todoist-old
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathautodoist.py
1556 lines (1210 loc) · 58.5 KB
/
autodoist.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
from todoist_api_python.api import TodoistAPI
from todoist_api_python.models import Task
from todoist_api_python.models import Section
from todoist_api_python.models import Project
from todoist_api_python.http_requests import get
from urllib.parse import urljoin
from urllib.parse import quote
import sys
import time
import requests
import argparse
import logging
from datetime import datetime, timedelta
import time
import sqlite3
import os
import re
import json
# Connect to SQLite database
def create_connection(path):
connection = None
try:
connection = sqlite3.connect(path)
logging.debug("Connection to SQLite DB successful!")
except Exception as e:
logging.error(
f"Could not connect to the SQLite database: the error '{e}' occurred")
sys.exit(1)
return connection
# Close conenction to SQLite database
def close_connection(connection):
try:
connection.close()
except Exception as e:
logging.error(
f"Could not close the SQLite database: the error '{e}' occurred")
sys.exit(1)
# Execute any SQLite query passed to it in the form of string
def execute_query(connection, query, *args):
cursor = connection.cursor()
try:
value = args[0]
# Useful to pass None/NULL value correctly
cursor.execute(query, (value,))
except:
cursor.execute(query)
try:
connection.commit()
logging.debug("Query executed: {}".format(query))
except Exception as e:
logging.debug(f"The error '{e}' occurred")
# Pass query to select and read record. Outputs a tuple.
def execute_read_query(connection, query):
cursor = connection.cursor()
result = None
try:
cursor.execute(query)
result = cursor.fetchall()
logging.debug("Query fetched: {}".format(query))
return result
except Exception as e:
logging.debug(f"The error '{e}' occurred")
# Construct query and read a value
def db_read_value(connection, model, column):
try:
if isinstance(model, Task):
db_name = 'tasks'
goal = 'task_id'
elif isinstance(model, Section):
db_name = 'sections'
goal = 'section_id'
elif isinstance(model, Project):
db_name = 'projects'
goal = 'project_id'
query = "SELECT %s FROM %s where %s=%r" % (
column, db_name, goal, model.id)
result = execute_read_query(connection, query)
except Exception as e:
logging.debug(f"The error '{e}' occurred")
return result
# Construct query and update a value
def db_update_value(connection, model, column, value):
try:
if isinstance(model, Task):
db_name = 'tasks'
goal = 'task_id'
elif isinstance(model, Section):
db_name = 'sections'
goal = 'section_id'
elif isinstance(model, Project):
db_name = 'projects'
goal = 'project_id'
query = """UPDATE %s SET %s = ? WHERE %s = %r""" % (
db_name, column, goal, model.id)
result = execute_query(connection, query, value)
return result
except Exception as e:
logging.debug(f"The error '{e}' occurred")
# Check if the id of a model exists, if not, add to database
def db_check_existance(connection, model):
try:
if isinstance(model, Task):
db_name = 'tasks'
goal = 'task_id'
elif isinstance(model, Section):
db_name = 'sections'
goal = 'section_id'
elif isinstance(model, Project):
db_name = 'projects'
goal = 'project_id'
q_check_existence = "SELECT EXISTS(SELECT 1 FROM %s WHERE %s=%r)" % (
db_name, goal, model.id)
existence_result = execute_read_query(connection, q_check_existence)
if existence_result[0][0] == 0:
if isinstance(model, Task):
q_create = """
INSERT INTO
tasks (task_id, task_type, parent_type, due_date, r_tag)
VALUES
(%r, %s, %s, %s, %i);
""" % (model.id, 'NULL', 'NULL', 'NULL', 0)
if isinstance(model, Section):
q_create = """
INSERT INTO
sections (section_id, section_type)
VALUES
(%r, %s);
""" % (model.id, 'NULL')
if isinstance(model, Project):
q_create = """
INSERT INTO
projects (project_id, project_type)
VALUES
(%r, %s);
""" % (model.id, 'NULL')
execute_query(connection, q_create)
except Exception as e:
logging.debug(f"The error '{e}' occurred")
# Initialise new database tables
def initialise_sqlite():
cwd = os.getcwdb()
db_path = os.path.join(cwd, b'metadata.sqlite')
connection = create_connection(db_path)
q_create_projects_table = """
CREATE TABLE IF NOT EXISTS projects (
id INTEGER PRIMARY KEY AUTOINCREMENT,
project_id INTEGER,
project_type TEXT
);
"""
q_create_sections_table = """
CREATE TABLE IF NOT EXISTS sections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER,
section_type
);
"""
q_create_tasks_table = """
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id INTEGER,
task_type TEXT,
parent_type TEXT,
due_date TEXT,
r_tag INTEGER
);
"""
execute_query(connection, q_create_projects_table)
execute_query(connection, q_create_sections_table)
execute_query(connection, q_create_tasks_table)
logging.info("SQLite DB has successfully initialized! \n")
return connection
# Makes --help text wider
def make_wide(formatter, w=120, h=36):
"""Return a wider HelpFormatter, if possible."""
try:
# https://stackoverflow.com/a/5464440
# beware: "Only the name of this class is considered a public API."
kwargs = {'width': w, 'max_help_position': h}
formatter(None, **kwargs)
return lambda prog: formatter(prog, **kwargs)
except TypeError:
logging.error("Argparse help formatter failed, falling back.")
return formatter
# Simple query for yes/no answer
def query_yes_no(question, default="yes"):
# """Ask a yes/no question via raw_input() and return their answer.
# "question" is a string that is presented to the user.
# "default" is the presumed answer if the user just hits <Enter>.
# It must be "yes" (the default), "no" or None (meaning
# an answer is required of the user).
# The "answer" return value is True for "yes" or False for "no".
# """
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
# Check if label exists, if not, create it
def verify_label_existance(api, label_name, prompt_mode):
# Check the regeneration label exists
labels = api.get_labels()
label = [x for x in labels if x.name == label_name]
if len(label) > 0:
next_action_label = label[0].id
logging.debug('Label \'%s\' found as label id %s',
label_name, next_action_label)
else:
# Create a new label in Todoist
logging.info(
"\n\nLabel '{}' doesn't exist in your Todoist\n".format(label_name))
# sys.exit(1)
if prompt_mode == 1:
response = query_yes_no(
'Do you want to automatically create this label?')
else:
response = True
if response:
try:
api.add_label(name=label_name)
except Exception as error:
logging.warning(error)
labels = api.get_labels()
label = [x for x in labels if x.name == label_name]
next_action_label = label[0].id
logging.info("Label '{}' has been created!".format(label_name))
else:
logging.info('Exiting Autodoist.')
exit(1)
return labels
# Initialisation of Autodoist
def initialise_api(args):
# Check we have a API key
if not args.api_key:
logging.error(
"\n\nNo API key set. Run Autodoist with '-a <YOUR_API_KEY>' or set the environment variable TODOIST_API_KEY.\n")
sys.exit(1)
# Check if alternative end of day is used
if args.end is not None:
if args.end < 1 or args.end > 24:
logging.error(
"\n\nPlease choose a number from 1 to 24 to indicate which hour is used as alternative end-of-day time.\n")
sys.exit(1)
else:
pass
# Check if proper regeneration mode has been selected
if args.regeneration is not None:
if not set([0, 1, 2]) & set([args.regeneration]):
logging.error(
'Wrong regeneration mode. Please choose a number from 0 to 2. Check --help for more information on the available modes.')
exit(1)
# Show which modes are enabled:
modes = []
m_num = 0
for x in [args.label, args.regeneration, args.end]:
if x:
modes.append('Enabled')
m_num += 1
else:
modes.append('Disabled')
logging.info("You are running with the following functionalities:\n\n Next action labelling mode: {}\n Regenerate sub-tasks mode: {}\n Shifted end-of-day mode: {}\n".format(*modes))
if m_num == 0:
logging.info(
"\n No functionality has been enabled. Please see --help for the available options.\n")
exit(0)
# Run the initial sync
logging.debug('Connecting to the Todoist API')
try:
api_arguments = {'token': args.api_key}
api = TodoistAPI(**api_arguments)
sync_api = initialise_sync_api(api)
# Save SYNC API token to enable partial syncs
api.sync_token = sync_api['sync_token']
except Exception as e:
logging.error(
f"Could not connect to Todoist: '{e}'")
exit(0)
logging.info("Autodoist has successfully connected to Todoist!")
# Check if labels exist
# If labeling argument is used
if args.label is not None:
# Verify that the next action label exists; ask user if it needs to be created
verify_label_existance(api, args.label, 1)
# TODO: Disabled for now
# # If regeneration mode is used, verify labels
# if args.regeneration is not None:
# # Verify the existance of the regeneraton labels; force creation of label
# regen_labels_id = [verify_label_existance(
# api, regen_label, 2) for regen_label in args.regen_label_names]
# else:
# # Label functionality not needed
# regen_labels_id = [None, None, None]
return api
# Check for Autodoist update
def check_for_update(current_version):
updateurl = 'https://api.github.com/repos/Hoffelhas/autodoist/releases'
try:
r = requests.get(updateurl)
r.raise_for_status()
release_info_json = r.json()
if not current_version == release_info_json[0]['tag_name']:
logging.warning("\n\nYour version is not up-to-date! \nYour version: {}. Latest version: {}\nFind the latest version at: {}\n".format(
current_version, release_info_json[0]['tag_name'], release_info_json[0]['html_url']))
return 1
else:
return 0
except requests.exceptions.ConnectionError as e:
logging.error(
"Error while checking for updates (Connection error): {}".format(e))
return 1
except requests.exceptions.HTTPError as e:
logging.error(
"Error while checking for updates (HTTP error): {}".format(e))
return 1
except requests.exceptions.RequestException as e:
logging.error("Error while checking for updates: {}".format(e))
return 1
# Get all data through the SYNC API. Needed to see e.g. any completed tasks.
def get_all_data(api):
BASE_URL = "https://api.todoist.com"
SYNC_VERSION = "v9"
SYNC_API = urljoin(BASE_URL, f"/sync/{SYNC_VERSION}/")
COMPLETED_GET_ALL = "completed/get_all"
endpoint = urljoin(SYNC_API, COMPLETED_GET_ALL)
data = get(api._session, endpoint, api._token)
return data
def initialise_sync_api(api):
bearer_token = 'Bearer %s' % api._token
headers = {
'Authorization': bearer_token,
'Content-Type': 'application/x-www-form-urlencoded',
}
data = 'sync_token=*&resource_types=["all"]'
try:
response = requests.post(
'https://api.todoist.com/sync/v9/sync', headers=headers, data=data)
except Exception as e:
logging.error(f"Error during initialise_sync_api: '{e}'")
return json.loads(response.text)
# Commit task content change to queue
def commit_content_update(api, task_id, content):
uuid = str(time.perf_counter()) # Create unique request id
data = {"type": "item_update", "uuid": uuid,
"args": {"id": task_id, "content": quote(content)}}
api.queue.append(data)
return api
# Ensure label updates are only issued once per task and commit to queue
def commit_labels_update(api, overview_task_ids, overview_task_labels):
filtered_overview_ids = [
k for k, v in overview_task_ids.items() if v != 0]
for task_id in filtered_overview_ids:
labels = overview_task_labels[task_id]
# api.update_task(task_id=task_id, labels=labels) # Not using REST API, since we would get too many single requests
uuid = str(time.perf_counter()) # Create unique request id
data = {"type": "item_update", "uuid": uuid,
"args": {"id": task_id, "labels": labels}}
api.queue.append(data)
return api
# Update tasks in batch with Todoist Sync API
def sync(api):
# # This approach does not seem to work correctly.
# BASE_URL = "https://api.todoist.com"
# SYNC_VERSION = "v9"
# SYNC_API = urljoin(BASE_URL, f"/sync/{SYNC_VERSION}/")
# SYNC_ENDPOINT = "sync"
# endpoint = urljoin(SYNC_API, SYNC_ENDPOINT)
# task_data = post(api._session, endpoint, api._token, data=data)
try:
bearer_token = 'Bearer %s' % api._token
headers = {
'Authorization': bearer_token,
'Content-Type': 'application/x-www-form-urlencoded',
}
data = 'sync_token=' + api.sync_token + \
'&commands=' + json.dumps(api.queue)
response = requests.post(
'https://api.todoist.com/sync/v9/sync', headers=headers, data=data)
if response.status_code == 200:
return response.json()
response.raise_for_status()
return response.ok
except Exception as e:
logging.exception(
'Error trying to sync with Todoist API: %s' % str(e))
quit()
# Find the type based on name suffix.
def check_name(args, string, num):
try:
# Find inbox or none section as exceptions
if string == None:
current_type = None
pass
elif string == 'Inbox':
current_type = args.inbox
pass
else:
# Find any = or - symbol at the end of the string. Look at last 3 for projects, 2 for sections, and 1 for tasks
regex = '[%s%s]{1,%s}$' % (args.s_suffix, args.p_suffix, str(num))
re_ind = re.search(regex, string)
suffix = re_ind[0]
# Somebody put fewer characters than intended. Take last character and apply for every missing one.
if len(suffix) < num:
suffix += suffix[-1] * (num - len(suffix))
current_type = ''
for s in suffix:
if s == args.s_suffix:
current_type += 's'
elif s == args.p_suffix:
current_type += 'p'
# Always return a three letter string
if len(current_type) == 2:
current_type = 'x' + current_type
elif len(current_type) == 1:
current_type = 'xx' + current_type
except:
logging.debug("String {} not recognised.".format(string))
current_type = None
return current_type
# Scan the end of a name to find what type it is
def get_type(args, connection, model, key):
# model_name = ''
try:
old_type = ''
old_type = db_read_value(connection, model, key)[0][0]
except:
# logging.debug('No defined project_type: %s' % str(e))
old_type = None
if isinstance(model, Task):
current_type = check_name(args, model.content, 1) # Tasks
elif isinstance(model, Section):
current_type = check_name(args, model.name, 2) # Sections
elif isinstance(model, Project):
current_type = check_name(args, model.name, 3) # Projects
# Check if type changed with respect to previous run
if old_type == current_type:
type_changed = 0
else:
type_changed = 1
db_update_value(connection, model, key, current_type)
return current_type, type_changed
# Determine a project type
def get_project_type(args, connection, project):
"""Identifies how a project should be handled."""
project_type, project_type_changed = get_type(
args, connection, project, 'project_type')
if project_type is not None:
logging.debug('Identified \'%s\' as %s type',
project.name, project_type)
return project_type, project_type_changed
# Determine a section type
def get_section_type(args, connection, section, project):
"""Identifies how a section should be handled."""
if section is not None:
section_type, section_type_changed = get_type(
args, connection, section, 'section_type')
else:
section_type = None
section_type_changed = 0
if section_type is not None:
logging.debug("Identified '%s > %s' as %s type",
project.name, section.name, section_type)
return section_type, section_type_changed
# Determine an task type
def get_task_type(args, connection, task, section, project):
"""Identifies how a task with sub tasks should be handled."""
task_type, task_type_changed = get_type(
args, connection, task, 'task_type')
if task_type is not None:
logging.debug("Identified '%s > %s > %s' as %s type",
project.name, section.name, task.content, task_type)
return task_type, task_type_changed
# Logic to track addition of a label to a task
def add_label(task, label, overview_task_ids, overview_task_labels):
if label not in task.labels:
labels = task.labels # To also copy other existing labels
logging.debug('Updating \'%s\' with label', task.content)
labels.append(label)
try:
overview_task_ids[task.id] += 1
except:
overview_task_ids[task.id] = 1
overview_task_labels[task.id] = labels
# Logic to track removal of a label from a task
def remove_label(task, label, overview_task_ids, overview_task_labels):
if label in task.labels:
labels = task.labels
logging.debug('Removing \'%s\' of its label', task.content)
labels.remove(label)
try:
overview_task_ids[task.id] -= 1
except:
overview_task_ids[task.id] = -1
overview_task_labels[task.id] = labels
# Check if header logic needs to be applied
def check_header(api, model):
header_all_in_level = False
unheader_all_in_level = False
regex_a = '(^[*]{2}\s*)(.*)'
regex_b = '(^\-\*\s*)(.*)'
try:
if isinstance(model, Task):
ra = re.search(regex_a, model.content)
rb = re.search(regex_b, model.content)
if ra:
header_all_in_level = True
model.content = ra[2] # Local record
api.update_task(task_id=model.id, content=ra[2])
# overview_updated_ids.append(model.id) # Ignore this one, since else it's count double
if rb:
unheader_all_in_level = True
model.content = rb[2] # Local record
api.update_task(task_id=model.id, content=rb[2])
# overview_updated_ids.append(model.id)
else:
ra = re.search(regex_a, model.name)
rb = re.search(regex_b, model.name)
if isinstance(model, Section):
if ra:
header_all_in_level = True
api.update_section(section_id=model.id, name=ra[2])
api.overview_updated_ids.append(model.id)
if rb:
unheader_all_in_level = True
api.update_section(section_id=model.id, name=rb[2])
api.overview_updated_ids.append(model.id)
elif isinstance(model, Project):
if ra:
header_all_in_level = True
api.update_project(project_id=model.id, name=ra[2])
api.overview_updated_ids.append(model.id)
if rb:
unheader_all_in_level = True
api.update_project(project_id=model.id, name=rb[2])
api.overview_updated_ids.append(model.id)
except:
logging.debug('check_header: no right model found')
return api, header_all_in_level, unheader_all_in_level
# Logic for applying and removing headers
def modify_task_headers(api, task, section_tasks, header_all_in_p, unheader_all_in_p, header_all_in_s, unheader_all_in_s, header_all_in_t, unheader_all_in_t):
if any([header_all_in_p, header_all_in_s]):
if task.content[:2] != '* ':
content = '* ' + task.content
api = commit_content_update(api, task.id, content)
# api.update_task(task_id=task.id, content='* ' + task.content)
# overview_updated_ids.append(task.id)
if any([unheader_all_in_p, unheader_all_in_s]):
if task.content[:2] == '* ':
content = task.content[2:]
api = commit_content_update(api, task.id, content)
# api.update_task(task_id=task.id, content=task.content[2:])
# overview_updated_ids.append(task.id)
if header_all_in_t:
if task.content[:2] != '* ':
content = '* ' + task.content
api = commit_content_update(api, task.id, content)
# api.update_task(task_id=task.id, content='* ' + task.content)
# overview_updated_ids.append(task.id)
api = find_and_headerify_all_children(
api, task, section_tasks, 1)
if unheader_all_in_t:
if task.content[:2] == '* ':
content = task.content[2:]
api = commit_content_update(api, task.id, content)
# api.update_task(task_id=task.id, content=task.content[2:])
# overview_updated_ids.append(task.id)
api = find_and_headerify_all_children(
api, task, section_tasks, 2)
return api
# Check regen mode based on label name
def check_regen_mode(api, item, regen_labels_id):
labels = item.labels
overlap = set(labels) & set(regen_labels_id)
overlap = [val for val in overlap]
if len(overlap) > 1:
logging.warning(
'Multiple regeneration labels used! Please pick only one for item: "{}".'.format(item.content))
return None
try:
regen_next_action_label = overlap[0]
except:
logging.debug(
'No regeneration label for item: %s' % item.content)
regen_next_action_label = [0]
if regen_next_action_label == regen_labels_id[0]:
return 0
elif regen_next_action_label == regen_labels_id[1]:
return 1
elif regen_next_action_label == regen_labels_id[2]:
return 2
else:
# label_name = api.labels.get_by_id(regen_next_action_label)['name']
# logging.debug(
# 'No regeneration label for item: %s' % item.content)
return None
# Recurring lists logic
def run_recurring_lists_logic(args, api, connection, task, task_items, task_items_all, regen_labels_id):
if task.parent_id == 0:
try:
if task.due.is_recurring:
try:
db_task_due_date = db_read_value(
connection, task, 'due_date')[0][0]
if db_task_due_date is None:
# If date has never been saved before, create a new entry
logging.debug(
'New recurring task detected: %s' % task.content)
db_update_value(connection, task,
'due_date', task.due.date)
# Check if the T0 task date has changed, because a user has checked the task
if task.due.date != db_task_due_date:
# TODO: reevaluate regeneration mode. Disabled for now.
# # Mark children for action based on mode
# if args.regeneration is not None:
# # Check if task has a regen label
# regen_mode = check_regen_mode(
# api, item, regen_labels_id)
# # If no label, use general mode instead
# if regen_mode is None:
# regen_mode = args.regeneration
# logging.debug('Using general recurring mode \'%s\' for item: %s',
# regen_mode, item.content)
# else:
# logging.debug('Using recurring label \'%s\' for item: %s',
# regen_mode, item.content)
# # Apply tags based on mode
# give_regen_tag = 0
# if regen_mode == 1: # Regen all
# give_regen_tag = 1
# elif regen_mode == 2: # Regen if all sub-tasks completed
# if not child_items:
# give_regen_tag = 1
# if give_regen_tag == 1:
# for child_item in child_items_all:
# child_item['r_tag'] = 1
# If alternative end of day, fix due date if needed
if args.end is not None:
# Determine current hour
t = datetime.today()
current_hour = t.hour
# Check if current time is before our end-of-day
if (args.end - current_hour) > 0:
# Determine the difference in days set by todoist
nd = [int(x) for x in task.due.date.split('-')]
od = [int(x)
for x in db_task_due_date.split('-')]
new_date = datetime(
nd[0], nd[1], nd[2])
old_date = datetime(
od[0], od[1], od[2])
today = datetime(
t.year, t.month, t.day)
days_difference = (
new_date-today).days
days_overdue = (
today - old_date).days
# Only apply if overdue and if it's a daily recurring tasks
if days_overdue >= 1 and days_difference == 1:
# Find current date in string format
today_str = t.strftime("%Y-%m-%d")
# Update due-date to today
api.update_task(
task_id=task.id, due_date=today_str, due_string=task.due.string)
logging.debug(
"Update date on task: '%s'" % (task.content))
# Save the new date for reference us
db_update_value(connection, task,
'due_date', task.due.date)
except:
# If date has never been saved before, create a new entry
logging.debug(
'New recurring task detected: %s' % task.content)
db_update_value(connection, task,
'due_date', task.due.date)
except:
pass
# TODO: reevaluate regeneration mode. Disabled for now.
# if args.regeneration is not None and item.parent_id != 0:
# try:
# if item['r_tag'] == 1:
# item.update(checked=0)
# item.update(in_history=0)
# item['r_tag'] = 0
# api.items.update(item['id'])
# for child_item in child_items_all:
# child_item['r_tag'] = 1
# except:
# # logging.debug('Child not recurring: %s' %
# # item.content)
# pass
# Find and clean all children under a task
def find_and_clean_all_children(task_ids, task, section_tasks):
child_tasks = list(filter(lambda x: x.parent_id == task.id, section_tasks))
if child_tasks != []:
for child_task in child_tasks:
# Children found, go deeper
task_ids.append(child_task.id)
task_ids = find_and_clean_all_children(
task_ids, child_task, section_tasks)
return task_ids
def find_and_headerify_all_children(api, task, section_tasks, mode):
child_tasks = list(filter(lambda x: x.parent_id == task.id, section_tasks))
if child_tasks != []:
for child_task in child_tasks:
# Children found, go deeper
if mode == 1:
if child_task.content[:2] != '* ':
api = commit_content_update(
api, child_task.id, '* ' + child_task.content)
# api.update_task(task_id=child_task.id,
# content='* ' + child_task.content)
# overview_updated_ids.append(child_task.id)
elif mode == 2:
if child_task.content[:2] == '* ':
api = commit_content_update(
api, child_task.id, child_task.content[2:])
# api.update_task(task_id=child_task.id,
# content=child_task.content[2:])
# overview_updated_ids.append(child_task.id)
find_and_headerify_all_children(
api, child_task, section_tasks, mode)
return 0
# Contains all main autodoist functionalities
def autodoist_magic(args, api, connection):
# Preallocate dictionaries and other values
overview_task_ids = {}
overview_task_labels = {}
next_action_label = args.label
regen_labels_id = args.regen_label_names
first_found = [False, False, False]
api.queue = []
api.overview_updated_ids = []
# Get all todoist info
try:
all_projects = api.get_projects() # To save on request to stay under the limit
all_sections = api.get_sections() # To save on request to stay under the limit
all_tasks = api.get_tasks()
except Exception as error:
logging.error(error)
for project in all_projects:
# Skip processing inbox as intended feature
if project.is_inbox_project:
continue
# Check db existance