-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.py
586 lines (481 loc) · 22.1 KB
/
app.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
# TODO: Make Asana task tracking smarter, dont just batch delete everything, edit instead or smth, and remember if a task was compelted in todoist.
# IDEA: Store hashes of all tasks that were marked as compelted to file
import os
import shutil
import yaml
from todoist_api import TodoistAPI
from asana_api import AsanaAPI
import string
import tempfile
import requests
import traceback
import sys
import hashlib
import json
import re
import time
import timeago
# easywebdav python3 hack
import easywebdav.client
from datetime import date, datetime, timedelta
from pprint import PrettyPrinter
pp = PrettyPrinter()
easywebdav.basestring = str
easywebdav.client.basestring = str
import easywebdav
appdir = os.path.dirname(os.path.realpath(__file__)) # rp, realpath
datadir = os.path.join(appdir, "data")
if not os.path.exists(datadir):
os.makedirs(datadir)
# Read config
with open(os.path.join(appdir, 'config.yaml'), 'r') as f:
config = yaml.safe_load(f.read())
# Fetch todoist items
todoist_api = TodoistAPI(config['todoist_token'])
labels = {}
for label in todoist_api.get_items("labels"):
labels[label['id']] = label['name']
projects = {}
for project in todoist_api.get_items("projects"):
projects[project['id']] = project['name']
# if config['debug']:
# with open(os.path.join(appdir, "debug.json"), "w+", encoding="utf-8") as f:
# f.write(pprint.pformat(api.state, indent=4))
def debug(text):
if config['debug']:
print(text)
today_path = os.path.join(datadir, datetime.now().strftime("%Y_%m_%d") + ".mem")
if not os.path.exists(today_path):
with open(today_path, "w+", encoding="utf-8") as f:
f.write("")
def today_memory():
with open(today_path, "r", encoding="utf-8") as f:
lines = f.readlines()
return lines
def remember_task(task):
lines = today_memory()
if task not in lines:
with open(today_path, "a+", encoding="utf-8") as f:
f.write(task + "\n")
print(f"Task '{task}' added to memory for today.")
else:
print(f"Task '{task}' already remembered as completed for today.")
def todoist_item_to_txt(item):
if item['checked'] is False:
text = ""
else:
text = "x "
text += f"({string.ascii_uppercase[4 - item['priority']]}) {item['content']}"
if item['project_id'] in projects:
text += f" +{projects[item['project_id']]}"
else:
print("=" * 80)
print(f"WARNING: Project {item['project_id']} not found in projects")
for k, v in projects.items():
print(k, v)
print("=" * 80)
for label_id in item['labels']:
if label_id in labels:
text += f" @{labels[label_id]}"
if config['show_due_date'] is True and item['due'] is not None:
text += f" due:{item['due']['date']}"
return text
def completed_today():
with open(today_path, "r", encoding="utf-8") as f:
lines = f.readlines()
tasks = 0
for line in lines:
if line.strip():
tasks += 1
return tasks
def get_project_id(name):
project_id = None
# Find required project
for project in todoist_api.get_items("projects"):
if project['name'] == name:
project_id = project['id']
break
return project_id
def get_project_items(project_name):
# Filter items
# Filter completed out
project_id = get_project_id(project_name)
items = []
for item in todoist_api.get_items():
# print(item)
select = False
if project_name == "Today":
if item['due'] != None:
try:
due_date = datetime.strptime(item['due']['date'], "%Y-%m-%d").date()
except:
try:
due_date = datetime.strptime(item['due']['date'], "%Y-%m-%dT%H:%M:%S").date()
except:
due_date = datetime.strptime(item['due']['date'], "%Y-%m-%dT%H:%M:%SZ").date()
due_date += timedelta(hours=config['local_timezone_offset'])
now_date = datetime.now().date()
date_check = due_date <= now_date
# debug(f"Check due date: {due_date} <= {now_date} = {date_check};")
if date_check:
select = True
elif item['project_id'] == project_id:
select = True
if select:
if config['max_items'] != 0 and len(items) > int(config['max_items']) - 1:
break
item_text = todoist_item_to_txt(item)
if item['checked'] is False or config['show_completed_tasks']:
items.append(item_text)
return items
def text_from_items(items, filter_out=[], hide_low_priority=False):
# Create output text
output_text = ""
for i in sorted(items):
# print (i)
if i not in filter_out and "(D) " not in i:
output_text += i + "\n"
return output_text
def generate_output_text():
project_items = get_project_items(config['todoist_project'])
output_text = text_from_items(project_items)
inbox_text = text_from_items(get_project_items("Inbox"), filter_out=project_items,
hide_low_priority=config['todoist_inbox_hide_lowpriority'])
if config['todoist_append_inbox']:
output_text = f'TODAY (Done: {completed_today()}):\n\n{output_text}\n\nINBOX:\n\n{inbox_text}'
return output_text
def get_archival_text(api: TodoistAPI):
tasks = []
for item in api.get_items():
tasks.append(todoist_item_to_txt(item))
archival_text = ''
for task in sorted(tasks):
archival_text += task + "\n"
return archival_text
def extract_data_from_description(description):
# print(f"Extracting data from: {description}")
data = ""
extract = False
for line in description.split("\n"):
if line.strip() == "--- TodoistToTxt Data End ---":
extract = False
if extract:
data += line + "\n"
if line.strip() == "--- TodoistToTxt Data ---":
extract = True
if not data:
return_data = None
else:
return_data = yaml.safe_load(data)
# print(f"Extracted data: {return_data}")
return return_data
def data_dumps(data):
data_string = yaml.safe_dump(data)
return f"""
```
--- TodoistToTxt Data ---
{data_string}
--- TodoistToTxt Data End ---
```
"""
from copy import copy
def generate_description(asana_task, task_data, task_type="start"):
task_data = copy(task_data)
task_data['task_type'] = task_type
task_data_string = data_dumps(task_data)
description = f"""{asana_task['notes']}
Link: {asana_task['permalink_url']}
{task_data_string}"""
return description
def send_notification(message, title=None, click_action = None):
print(f"Trying to send notification: {message} | {title} | {click_action}")
try:
url = f"{config['homeassistant']['hass_url']}/api/services/script/turn_on"
headers = {
"Authorization": f"Bearer {config['homeassistant']['hass_token']}",
"content-type": "application/json",
}
variables = {"message": message}
if title:
variables['title'] = title
if click_action:
variables['clickAction'] = click_action
response = requests.post(url, headers=headers, json={
"entity_id": config['homeassistant']['script_entity_id'],
"variables": variables
}
)
return response
except Exception as e:
print("ERROR!", e)
if __name__ == "__main__":
# TODO Make 'type' selection work
# region ical
import icalendar_parser
# ICalendar sync
for id, icalendar_data in enumerate(config['icalendar']):
ical_cache_time_format = r"%Y.%m.%d %H:%M"
ical_mem_path = os.path.join(appdir, "data", f"icalendar_{id}.date")
if not os.path.exists(ical_mem_path):
with open(ical_mem_path, "w+") as f:
f.write((datetime.now() - timedelta(days=1)).strftime(ical_cache_time_format))
with open(ical_mem_path, "r") as f:
last_check = datetime.strptime(f.read(), ical_cache_time_format)
if datetime.now() - last_check > timedelta(minutes=int(icalendar_data['interval'])):
print(f"Checking calendar: {icalendar_data['tag']}")
icalendar_parser.sync_calendar(
calendar_url=icalendar_data['url'],
tag=icalendar_data['tag'],
tags=icalendar_data.get("tags", []),
priority=icalendar_data['priority']
)
with open(ical_mem_path, "w+") as f:
f.write(datetime.now().strftime(ical_cache_time_format))
else:
print(f"Skip checking calendar, too soon: {icalendar_data['tag']}")
# endregion
# region Asana
for id, asana_profile in enumerate(config['asana']):
asana_cache_time_format = r"%Y.%m.%d %H:%M"
asana_mem_path = os.path.join(appdir, "data", f"asana_{id}.date")
if not os.path.exists(asana_mem_path):
with open(asana_mem_path, "w+") as f:
f.write((datetime.now() - timedelta(days=1)).strftime(asana_cache_time_format))
with open(asana_mem_path, "r") as f:
last_check = datetime.strptime(f.read(), asana_cache_time_format)
if datetime.now() - last_check > timedelta(minutes=int(asana_profile['interval'])):
asana_api = AsanaAPI(asana_profile['personal_access_token'])
asana_tag = asana_profile['tag']
asana_tags = asana_profile.get('tags', [])
asana_tags.append(asana_tag)
asana_tasks = asana_api.get_tasks(asana_profile['task_params'])
for asana_task in asana_tasks:
start_date = datetime.strptime(
asana_task['start_on'], r"%Y-%m-%d") if asana_task.get('start_on', False) else None
due_date = datetime.strptime(
asana_task['due_on'], r"%Y-%m-%d") if asana_task.get('due_on', False) else None
if due_date and due_date < datetime.now():
continue
new_task_data = {
"uid": f"asana_{asana_task['gid']}"
}
todoist_tasks = todoist_api.get_items()
# TODO: Remember completed tasks and ignore them later
remove_tasks = []
for todoist_task in todoist_tasks:
task_data = extract_data_from_description(todoist_task['description'])
if task_data and task_data['uid'] == new_task_data['uid']:
print(f"Removing task, part of Asana Sync: {asana_task['name']}")
remove_tasks.append(todoist_task)
print(todoist_api.delete_items(remove_tasks))
if start_date and start_date.date() >= datetime.now().date():
content = f"{asana_tag.upper()} - START TASK: {asana_task['name']}" # @{asana_tag} "
# for _tag in asana_tags:
# content += f"@{_tag} "
# TODO: Use `html_notes` with html to markdown
description = generate_description(asana_task, new_task_data, "start")
todoist_api.add_item(
{
"content": content,
"description": description,
"date_string": start_date.strftime(r"%Y.%m.%d"),
"priority": asana_profile['priority'],
"labels": asana_tags
}
)
if due_date and due_date.date() >= datetime.now().date():
content = f"{asana_tag.upper()} - FINISH TASK: {asana_task['name']} @{asana_tag}"
# TODO: Use `html_notes` with html to markdown
description = generate_description(asana_task, new_task_data, "finish")
todoist_api.add_item(
{
"content": content,
"description": description,
"date_string": due_date.strftime(r"%Y.%m.%d"),
"priority": asana_profile['priority'],
"labels": asana_tags
}
)
if start_date and due_date:
# CREATE "WORK ON TASK:"
delta = due_date - start_date
for i in range(1, delta.days):
day = start_date + timedelta(days=i)
if day.date() >= datetime.now().date():
content = f"{asana_tag.upper()} - WORK ON TASK: {asana_task['name']} @{asana_tag} "
# TODO: Use `html_notes` with html to markdown
description = generate_description(asana_task, new_task_data, "work")
todoist_api.add_item(
{
"content": content,
"description": description,
"date_string": day.strftime(r"%Y.%m.%d"),
"priority": asana_profile['priority'],
"labels": asana_tags
}
)
with open(asana_mem_path, "w+") as f:
f.write(datetime.now().strftime(asana_cache_time_format))
else:
print(f"Skip checking Asana, too soon: {asana_profile['tag']}")
# endregion
# region Notifier
def notifier_task_hash(task, label=""):
string = json.dumps(task)
string += label
return hashlib.sha256(string.encode("utf-8")).hexdigest()
if "homeassistant" in config:
print("Running HomeAssistant notifier...")
notified_filepath = os.path.join(appdir, 'data', 'notified.dat')
if os.path.exists(notified_filepath):
with open(notified_filepath, "r") as f:
notified = f.read().split("\n")
else:
notified = []
for item in todoist_api.get_items():
# print(f"Notify? ({item['content']})")
try:
notify_regex = r"notify(?P<threshold>.+)?"
# if len(item['labels']) == 0:
# print("No labels in this task.")
for label in item['labels']:
match = re.match(notify_regex, label)
if match and item['due'] and item['due'] != None:
threshold = match.groupdict().get("threshold", None)
if threshold is None:
threshold = config['notifier_threshold_minutes']
notify_delta = timedelta(minutes=int(threshold))
item_hash = notifier_task_hash(item, label)
if item_hash in notified:
print(f"Already notified task: {item['content']}")
continue
# TODO This is used twice might need to turn into function, the only difference is .date() in the end
try:
due_date = datetime.strptime(item['due']['date'], "%Y-%m-%d")
except:
try:
due_date = datetime.strptime(item['due']['date'], "%Y-%m-%dT%H:%M:%S")
except:
due_date = datetime.strptime(item['due']['date'], "%Y-%m-%dT%H:%M:%SZ")
due_date += timedelta(hours=config['local_timezone_offset'])
now = datetime.now()
from_date = due_date - notify_delta
if from_date < now < due_date:
print(f"Trying to notify about due task: {item['content']}")
notification_result = send_notification(
item['content'],
f"Todoist Item Due {timeago.format(due_date, datetime.now())}!",
f"https://todoist.com/showTask?id={item['id']}"
)
if notification_result is not None:
with open(notified_filepath, "a+") as f:
f.write(item_hash + "\n")
else:
print(f"Label did not match notify label pattern: {label} ({notify_regex})")
except Exception as e:
print(e)
traceback.print_exc()
delete_ids = []
# region Task Expiration
for item in todoist_api.get_items():
# print(f"Notify? ({item['content']})")
try:
expire_regex = r"expire(?P<hours>.+)?"
# if len(item['labels']) == 0:
# print("No labels in this task.")
for label in item['labels']:
match = re.match(expire_regex, label)
if match:
expire_hours = match.groupdict().get("hours", None)
if expire_hours:
expire_delta = timedelta(hours=int(expire_hours))
try:
due_date = datetime.strptime(item['added_at'], "%Y-%m-%d")
except:
try:
due_date = datetime.strptime(item['added_at'], "%Y-%m-%dT%H:%M:%S")
except:
try:
due_date = datetime.strptime(item['added_at'], "%Y-%m-%dT%H:%M:%SZ")
due_date += timedelta(hours=config['local_timezone_offset'])
except:
due_date = datetime.strptime(item['added_at'], "%Y-%m-%dT%H:%M:%S.%fZ")
due_date += timedelta(hours=config['local_timezone_offset'])
if datetime.now() - due_date > expire_delta:
print(f"Querying task for deletion due to expiration label: '{str(item)}")
delete_ids.append(item['id'])
notification_result = send_notification(
item['content'],
f"Todoist Item Expired.",
f"https://todoist.com/showTask?id={item['id']}"
)
break
else:
print(f"Task is marked to expire, but it's not due yet {label}: {str(item)}")
else:
print(f"Label did not match expire label pattern: {label} ({expire_regex})")
except Exception as e:
print(f"Failed processing expiration for task ({label}): {e}")
# endregion
# endregion
local_filepath = os.path.join(appdir, config['filename_output'])
output_text = generate_output_text()
backup_text = get_archival_text(todoist_api)
debug(output_text)
for item in todoist_api.get_completed_tasks():
if config['remove_completed_tasks']:
remember_task(item['content'])
if config['clean_up_completed_tasks']:
print(f"Deleting task '{item['content']}'")
delete_ids.append(item['task_id'])
else:
print(f"Config tells me to skip clean_up_completed_tasks: {item['content']}")
if len(delete_ids) > 0:
print("RESULT:")
print (todoist_api.delete_items(delete_ids))
# Copy if copy
if config['export_file_as']:
if os.path.exists(config['export_file_as']):
with open(config['export_file_as'], 'r', encoding='utf-8', errors='ignore') as f:
old_text = f.read()
if output_text == old_text:
print("No changes in todo list. Exit.")
sys.exit()
with open(config['export_file_as'], 'w+', encoding='utf-8', errors='ignore') as f:
f.write(output_text)
print(f"TodoistAPI calls made: {todoist_api.api_calls}")
# Upload to webdav
if config['webdav_url']:
webdav = easywebdav.connect(config['webdav_url'], username=config['webdav_login'],
password=config['webdav_password'],
protocol='https', port=443, verify_ssl=False, path=config['webdav_path'])
with tempfile.NamedTemporaryFile(mode="wb+", delete=False) as tmp:
webdav.download("{}/{}".format(config['webdav_directory'], config['filename_output']), tmp)
tmp_fp = tmp.name
with open(tmp_fp, "r", encoding="utf-8") as f:
old_text = f.read()
if output_text == old_text:
print("No changes in todo list. Exit.")
os.remove(tmp_fp)
sys.exit()
# Write filtered file
with tempfile.NamedTemporaryFile(mode="w+", encoding='utf-8', delete=False) as tmp:
tmp.write(output_text)
tmp_fp = tmp.name
webdav.upload(tmp_fp, "{}/{}".format(config['webdav_directory'], config['filename_output']))
os.remove(tmp_fp)
# Write full backup file
with tempfile.NamedTemporaryFile(mode="w+", encoding='utf-8', delete=False) as tmp:
tmp.write(backup_text)
tmp_fp = tmp.name
webdav.upload(tmp_fp, "{}/{}".format(config['webdav_directory'], "todoist_full.txt"))
backups_dir = os.path.join(appdir, "backups")
if not os.path.exists(backups_dir):
os.makedirs(backups_dir)
index = datetime.now().strftime(r"%Y_%m_%d_%H_%M_%S")
backup_fp = os.path.join(backups_dir, f"backup_{index}.txt")
shutil.copy(tmp_fp, backup_fp)
backups = os.listdir(backups_dir)
if len(backups) > config['max_backups']:
os.remove(os.path.join(backups_dir, sorted(backups)[0]))
os.remove(tmp_fp)