Basic labelling functionality working again. Still need to fix metadata storage

pull/30/head
Hoffelhas 2023-01-02 16:28:16 +01:00
parent 95a71524cd
commit 2625547002
3 changed files with 276 additions and 247 deletions

View File

@ -1 +0,0 @@
nextaction: python nextaction.py -a $TODOIST_API_KEY -l $TODOIST_NEXT_ACTION_LABEL $DEBUG --nocache

View File

@ -8,6 +8,8 @@ import argparse
import logging import logging
from datetime import datetime, timedelta from datetime import datetime, timedelta
import time import time
import sqlite3
from sqlite3 import Error
# Makes --help text wider # Makes --help text wider
@ -79,9 +81,9 @@ def verify_label_existance(api, label_name, prompt_mode):
label = [x for x in labels if x.name == label_name] label = [x for x in labels if x.name == label_name]
if len(label) > 0: if len(label) > 0:
label_id = label[0].id next_action_label = label[0].id
logging.debug('Label \'%s\' found as label id %d', logging.debug('Label \'%s\' found as label id %d',
label_name, label_id) label_name, next_action_label)
else: else:
# Create a new label in Todoist # Create a new label in Todoist
logging.info( logging.info(
@ -101,15 +103,14 @@ def verify_label_existance(api, label_name, prompt_mode):
labels = api.get_labels() labels = api.get_labels()
label = [x for x in labels if x.name == label_name] label = [x for x in labels if x.name == label_name]
label_id = label[0].id next_action_label = label[0].id
logging.info("Label '{}' has been created!".format(label_name)) logging.info("Label '{}' has been created!".format(label_name))
else: else:
logging.info('Exiting Autodoist.') logging.info('Exiting Autodoist.')
exit(1) exit(1)
return label_id return 0
# Initialisation of Autodoist # Initialisation of Autodoist
def initialise(args): def initialise(args):
@ -171,11 +172,7 @@ def initialise(args):
if args.label is not None: if args.label is not None:
# Verify that the next action label exists; ask user if it needs to be created # Verify that the next action label exists; ask user if it needs to be created
label_id = verify_label_existance(api, args.label, 1) verify_label_existance(api, args.label, 1)
else:
# Label functionality not needed
label_id = None
# If regeneration mode is used, verify labels # If regeneration mode is used, verify labels
if args.regeneration is not None: if args.regeneration is not None:
@ -188,7 +185,7 @@ def initialise(args):
# Label functionality not needed # Label functionality not needed
regen_labels_id = [None, None, None] regen_labels_id = [None, None, None]
return api, label_id, regen_labels_id return api
# Check for Autodoist update # Check for Autodoist update
@ -232,19 +229,20 @@ def check_name(args, name):
current_type = 'parallel' current_type = 'parallel'
elif name[-len_suffix[1]:] == args.ss_suffix: elif name[-len_suffix[1]:] == args.ss_suffix:
current_type = 'sequential' current_type = 'sequential'
elif name[-len_suffix[1]:] == args.ps_suffix: elif name[-len_suffix[2]:] == args.ps_suffix:
current_type = 'p-s' current_type = 'p-s'
elif name[-len_suffix[1]:] == args.sp_suffix: elif name[-len_suffix[3]:] == args.sp_suffix:
current_type = 's-p' current_type = 's-p'
# Workaround for section names, which don't allow / symbol. #TODO: Remove below workarounds if standard notation is changing. Just messy and no longer needed.
elif args.ps_suffix == '/-' and name[-2:] == '_-': # # Workaround for section names, which don't allow '/' symbol.
current_type = 'p-s' # elif args.ps_suffix == '/-' and name[-2:] == '_-':
# Workaround for section names, which don't allow / symbol. # current_type = 'p-s'
elif args.sp_suffix == '-/' and name[-2:] == '-_': # # Workaround for section names, which don't allow '/' symbol.
current_type = 's-p' # elif args.sp_suffix == '-/' and name[-2:] == '-_':
# Workaround for section names, which don't allow / symbol. # current_type = 's-p'
elif args.pp_suffix == '//' and name[-1:] == '_': # # Workaround for section names, which don't allow '/' symbol.
current_type = 'parallel' # elif args.pp_suffix == '//' and name[-1:] == '_':
# current_type = 'parallel'
else: else:
current_type = None current_type = None
@ -253,42 +251,45 @@ def check_name(args, name):
# Scan the end of a name to find what type it is # Scan the end of a name to find what type it is
def get_type(args, object, key): def get_type(args, model, key):
object_name = '' model_name = ''
try: try:
old_type = object[key] old_type = model[key] #TODO: METADATA: this information used to be part of the metadata, needs to be retreived from own database
except: except:
# logging.debug('No defined project_type: %s' % str(e)) # logging.debug('No defined project_type: %s' % str(e))
old_type = None old_type = None
try: try:
object_name = object['name'].strip() model_name = model.name.strip()
except: except:
try: #TODO: Old support for legacy tag in v1 API, can likely be removed since moving to v2.
object_name = object['content'].strip() # try:
except: #
pass # object_name = object['content'].strip()
# except:
# pass
pass
current_type = check_name(args, object_name) current_type = check_name(args, model_name)
# Check if project type changed with respect to previous run # Check if project type changed with respect to previous run
if old_type == current_type: if old_type == current_type:
type_changed = 0 type_changed = 0
else: else:
type_changed = 1 type_changed = 1
object[key] = current_type # model.key = current_type #TODO: METADATA: this information used to be part of the metadata, needs to be retreived from own database
return current_type, type_changed return current_type, type_changed
# Determine a project type # Determine a project type
def get_project_type(args, project_object): def get_project_type(args, project_model):
"""Identifies how a project should be handled.""" """Identifies how a project should be handled."""
project_type, project_type_changed = get_type( project_type, project_type_changed = get_type(
args, project_object, 'project_type') args, project_model, 'project_type')
return project_type, project_type_changed return project_type, project_type_changed
@ -306,65 +307,67 @@ def get_section_type(args, section_object):
return section_type, section_type_changed return section_type, section_type_changed
# Determine an item type # Determine an task type
def get_item_type(args, item, project_type): def get_task_type(args, task, project_type):
"""Identifies how an item with sub items should be handled.""" """Identifies how a task with sub tasks should be handled."""
if project_type is None and item['parent_id'] != 0: if project_type is None and task.parent_id != 0:
try: try:
item_type = item['parent_type'] task_type = task.parent_type #TODO: METADATA
item_type_changed = 1 task_type_changed = 1
item['item_type'] = item_type task.task_type = task_type
except: except:
item_type, item_type_changed = get_type(args, item, 'item_type') task_type, task_type_changed = get_type(args, task, 'task_type') #TODO: METADATA
else: else:
item_type, item_type_changed = get_type(args, item, 'item_type') task_type, task_type_changed = get_type(args, task, 'task_type') #TODO: METADATA
return item_type, item_type_changed return task_type, task_type_changed
# Logic to add a label to an item # Logic to track addition of a label to a task
def add_label(item, label, overview_item_ids, overview_item_labels): def add_label(task, label, overview_task_ids, overview_task_labels):
if label not in item['labels']: if label not in task.labels:
labels = item['labels'] labels = task.labels # Copy other existing labels
logging.debug('Updating \'%s\' with label', item['content']) logging.debug('Updating \'%s\' with label', task.content)
labels.append(label) labels.append(label)
try: try:
overview_item_ids[str(item['id'])] += 1 overview_task_ids[task.id] += 1
except: except:
overview_item_ids[str(item['id'])] = 1 overview_task_ids[task.id] = 1
overview_item_labels[str(item['id'])] = labels overview_task_labels[task.id] = labels
# Logic to remove a label from an item # Logic to track removal of a label from a task
def remove_label(item, label, overview_item_ids, overview_item_labels): def remove_label(task, label, overview_task_ids, overview_task_labels):
if label in item['labels']: if label in task.labels:
labels = item['labels'] labels = task.labels
logging.debug('Removing \'%s\' of its label', item['content']) logging.debug('Removing \'%s\' of its label', task.content)
labels.remove(label) labels.remove(label)
try: try:
overview_item_ids[str(item['id'])] -= 1 overview_task_ids[task.id] -= 1
except: except:
overview_item_ids[str(item['id'])] = -1 overview_task_ids[task.id] = -1
overview_item_labels[str(item['id'])] = labels overview_task_labels[task.id] = labels
# Ensure labels are only issued once per item # Ensure label updates are only issued once per task
def update_labels(api, label_id, overview_item_ids, overview_item_labels): def update_labels(api, overview_task_ids, overview_task_labels):
filtered_overview_ids = [ filtered_overview_ids = [
k for k, v in overview_item_ids.items() if v != 0] k for k, v in overview_task_ids.items() if v != 0]
for item_id in filtered_overview_ids: for task_id in filtered_overview_ids:
labels = overview_item_labels[item_id] labels = overview_task_labels[task_id]
api.items.update(item_id, labels=labels) api.update_task(task_id=task_id, labels=labels)
# To handle items which have no sections return filtered_overview_ids
# To handle tasks which have no sections
def create_none_section(): def create_none_section():
@ -390,7 +393,7 @@ def check_header(level):
except: except:
try: try:
# Current structure # Current structure
content = level['content'] content = level.content
method = 2 method = 2
except: except:
pass pass
@ -414,38 +417,54 @@ def check_header(level):
return header_all_in_level, unheader_all_in_level return header_all_in_level, unheader_all_in_level
# Logic for applying and removing headers
def modify_headers(task, child_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, header_all_in_t]):
if task.content[0] != '*':
task.update(content='* ' + task.content)
for ci in child_tasks:
if not ci.content.startswith('*'):
ci.update(content='* ' + ci.content)
if any([unheader_all_in_p, unheader_all_in_s]):
if task.content[0] == '*':
task.update(content=task.content[2:])
if unheader_all_in_t:
[ci.update(content=ci.content[2:])
for ci in child_tasks]
# Check regen mode based on label name # Check regen mode based on label name
def check_regen_mode(api, item, regen_labels_id): def check_regen_mode(api, item, regen_labels_id):
labels = item['labels'] labels = item.labels
overlap = set(labels) & set(regen_labels_id) overlap = set(labels) & set(regen_labels_id)
overlap = [val for val in overlap] overlap = [val for val in overlap]
if len(overlap) > 1: if len(overlap) > 1:
logging.warning( logging.warning(
'Multiple regeneration labels used! Please pick only one for item: "{}".'.format(item['content'])) 'Multiple regeneration labels used! Please pick only one for item: "{}".'.format(item.content))
return None return None
try: try:
regen_label_id = overlap[0] regen_next_action_label = overlap[0]
except: except:
logging.debug( logging.debug(
'No regeneration label for item: %s' % item['content']) 'No regeneration label for item: %s' % item.content)
regen_label_id = [0] regen_next_action_label = [0]
if regen_label_id == regen_labels_id[0]: if regen_next_action_label == regen_labels_id[0]:
return 0 return 0
elif regen_label_id == regen_labels_id[1]: elif regen_next_action_label == regen_labels_id[1]:
return 1 return 1
elif regen_label_id == regen_labels_id[2]: elif regen_next_action_label == regen_labels_id[2]:
return 2 return 2
else: else:
# label_name = api.labels.get_by_id(regen_label_id)['name'] # label_name = api.labels.get_by_id(regen_next_action_label)['name']
# logging.debug( # logging.debug(
# 'No regeneration label for item: %s' % item['content']) # 'No regeneration label for item: %s' % item.content)
return None return None
@ -472,10 +491,10 @@ def run_recurring_lists_logic(args, api, item, child_items, child_items_all, reg
if regen_mode is None: if regen_mode is None:
regen_mode = args.regeneration regen_mode = args.regeneration
logging.debug('Using general recurring mode \'%s\' for item: %s', logging.debug('Using general recurring mode \'%s\' for item: %s',
regen_mode, item['content']) regen_mode, item.content)
else: else:
logging.debug('Using recurring label \'%s\' for item: %s', logging.debug('Using recurring label \'%s\' for item: %s',
regen_mode, item['content']) regen_mode, item.content)
# Apply tags based on mode # Apply tags based on mode
give_regen_tag = 0 give_regen_tag = 0
@ -519,7 +538,7 @@ def run_recurring_lists_logic(args, api, item, child_items, child_items_all, reg
# Only apply if overdue and if it's a daily recurring tasks # Only apply if overdue and if it's a daily recurring tasks
if days_overdue >= 1 and days_difference == 1: if days_overdue >= 1 and days_difference == 1:
# Find curreny date in string format # Find current date in string format
today_str = [str(x) for x in [ today_str = [str(x) for x in [
today.year, today.month, today.day]] today.year, today.month, today.day]]
if len(today_str[1]) == 1: if len(today_str[1]) == 1:
@ -540,13 +559,13 @@ def run_recurring_lists_logic(args, api, item, child_items, child_items_all, reg
except: except:
# If date has never been saved before, create a new entry # If date has never been saved before, create a new entry
logging.debug( logging.debug(
'New recurring task detected: %s' % item['content']) 'New recurring task detected: %s' % item.content)
item['date_old'] = item['due']['date'][:10] item['date_old'] = item['due']['date'][:10]
api.items.update(item['id']) api.items.update(item['id'])
except: except:
# logging.debug( # logging.debug(
# 'Parent not recurring: %s' % item['content']) # 'Parent not recurring: %s' % item.content)
pass pass
if args.regeneration is not None and item['parent_id'] != 0: if args.regeneration is not None and item['parent_id'] != 0:
@ -561,17 +580,17 @@ def run_recurring_lists_logic(args, api, item, child_items, child_items_all, reg
child_item['r_tag'] = 1 child_item['r_tag'] = 1
except: except:
# logging.debug('Child not recurring: %s' % # logging.debug('Child not recurring: %s' %
# item['content']) # item.content)
pass pass
# Contains all main autodoist functionalities # Contains all main autodoist functionalities
def autodoist_magic(args, api, label_id, regen_labels_id): def autodoist_magic(args, api, next_action_label, regen_labels_id):
# Preallocate dictionaries # Preallocate dictionaries
overview_item_ids = {} overview_task_ids = {}
overview_item_labels = {} overview_task_labels = {}
try: try:
projects = api.get_projects() projects = api.get_projects()
@ -586,25 +605,29 @@ def autodoist_magic(args, api, label_id, regen_labels_id):
# Check if we need to (un)header entire project # Check if we need to (un)header entire project
header_all_in_p, unheader_all_in_p = check_header(project) header_all_in_p, unheader_all_in_p = check_header(project)
if label_id is not None: # Get project type
# Get project type if next_action_label is not None:
project_type, project_type_changed = get_project_type( project_type, project_type_changed = get_project_type(
args, project) args, project)
if project_type is not None: if project_type is not None:
logging.debug('Identified \'%s\' as %s type', logging.debug('Identified \'%s\' as %s type',
project['name'], project_type) project.name, project_type)
# Get all items for the project # Get all tasks for the project
try: try:
project_tasks = api.get_tasks(project_id = project.id) project_tasks = api.get_tasks(project_id = project.id)
except Exception as error: except Exception as error:
print(error) print(error)
# Run for both none-sectioned and sectioned items # Run for both non-sectioned and sectioned tasks
# Get completed tasks: get(api._session, endpoint, api._token, '0')['items'] # Get completed tasks:
# endpoint = 'https://api.todoist.com/sync/v9/completed/get_all'
# get(api._session, endpoint, api._token, '0')['items']
# $ curl https://api.todoist.com/sync/v9/sync-H "Authorization: Bearer e2f750b64e8fc06ae14383d5e15ea0792a2c1bf3" -d commands='[ {"type": "item_add", "temp_id": "63f7ed23-a038-46b5-b2c9-4abda9097ffa", "uuid": "997d4b43-55f1-48a9-9e66-de5785dfd69b", "args": {"content": "Buy Milk", "project_id": "2203306141","labels": ["Food", "Shopping"]}}]'
# for s in [0, 1]: # TEMP SECTION ONLY # for s in [0, 1]: # TODO: TEMPORARELY SKIP SECTIONLESS TASKS
for s in [1]: for s in [1]:
if s == 0: if s == 0:
sections = [create_none_section()] # TODO: Rewrite sections = [create_none_section()] # TODO: Rewrite
@ -627,208 +650,199 @@ def autodoist_magic(args, api, label_id, regen_labels_id):
args, section) args, section)
if section_type is not None: if section_type is not None:
logging.debug('Identified \'%s\' as %s type', logging.debug('Identified \'%s\' as %s type',
section['name'], section_type) section.name, section_type)
# Get all items for the section # Get all tasks for the section
tasks = [x for x in project_tasks if x.section_id tasks = [x for x in project_tasks if x.section_id
== section.id] == section.id]
# Change top parents_id in order to numerically sort later on # Change top tasks parents_id from 'None' to '0' in order to numerically sort later on
for task in tasks: for task in tasks:
if not task.parent_id: if not task.parent_id:
task.parent_id = 0 task.parent_id = 0
# Sort by parent_id and filter for completable items # Sort by parent_id and child order
items = sorted(items, key=lambda x: ( # In the past, Todoist used to screw up the tasks orders, so originally I processed parentless tasks first such that children could properly inherit porperties.
x['parent_id'], x['child_order'])) # With the new API this seems to be in order, but I'm keeping this just in case for now. TODO: Could be used for optimization in the future.
tasks = sorted(tasks, key=lambda x: (
int(x.parent_id), x.order))
# If a type has changed, clean label for good measure # If a type has changed, clean all task labels for good measure
if label_id is not None: if next_action_label is not None:
if project_type_changed == 1 or section_type_changed == 1: if project_type_changed == 1 or section_type_changed == 1:
# Remove labels # Remove labels
[remove_label(item, label_id, overview_item_ids, [remove_label(task, next_action_label, overview_task_ids,
overview_item_labels) for item in items] overview_task_labels) for task in tasks]
# Remove parent types # Remove parent types
for item in items: # for task in tasks:
item['parent_type'] = None # task.parent_type = None #TODO: METADATA
# For all items in this section # For all tasks in this section
for item in items: for task in tasks:
active_type = None # Reset dominant_type = None # Reset
# Possible nottes routine for the future # Possible nottes routine for the future
# notes = api.notes.all() TODO: Quick notes test to see what the impact is? # notes = api.notes.all() TODO: Quick notes test to see what the impact is?
# note_content = [x['content'] for x in notes if x['item_id'] == item['id']] # note_content = [x['content'] for x in notes if x['item_id'] == item['id']]
# print(note_content) # print(note_content)
# Determine which child_items exist, both all and the ones that have not been checked yet # Determine which child_tasks exist, both all and the ones that have not been checked yet
non_checked_items = list( non_completed_tasks = list(
filter(lambda x: x['checked'] == 0, items)) filter(lambda x: not x.is_completed, tasks))
child_items_all = list( child_tasks_all = list(
filter(lambda x: x['parent_id'] == item['id'], items)) filter(lambda x: x.parent_id == task.id, tasks))
child_items = list( child_tasks = list(
filter(lambda x: x['parent_id'] == item['id'], non_checked_items)) filter(lambda x: x.parent_id == task.id, non_completed_tasks))
# Check if we need to (un)header entire item tree # Check if we need to (un)header entire task tree
header_all_in_i, unheader_all_in_i = check_header(item) header_all_in_t, unheader_all_in_t = check_header(task)
# Logic for applying and removing headers # Modify headers where needed
if any([header_all_in_p, header_all_in_s, header_all_in_i]): #TODO: DISABLED FOR NOW, FIX LATER
if item['content'][0] != '*': # modify_headers(header_all_in_p, unheader_all_in_p, header_all_in_s, unheader_all_in_s, header_all_in_t, unheader_all_in_t)
item.update(content='* ' + item['content'])
for ci in child_items:
if not ci['content'].startswith('*'):
ci.update(content='* ' + ci['content'])
if any([unheader_all_in_p, unheader_all_in_s]):
if item['content'][0] == '*':
item.update(content=item['content'][2:])
if unheader_all_in_i:
[ci.update(content=ci['content'][2:])
for ci in child_items]
#TODO: Check is regeneration is still needed, now that it's part of core Todoist. Disabled for now.
# Logic for recurring lists # Logic for recurring lists
if not args.regeneration: # if not args.regeneration:
try: # try:
# If old label is present, reset it # # If old label is present, reset it
if item['r_tag'] == 1: # if item.r_tag == 1: #TODO: METADATA
item['r_tag'] = 0 # item.r_tag = 0 #TODO: METADATA
api.items.update(item['id']) # api.items.update(item.id)
except: # except:
pass # pass
# If options turned on, start recurring lists logic # # If options turned on, start recurring lists logic
if args.regeneration is not None or args.end: # if args.regeneration is not None or args.end:
run_recurring_lists_logic( # run_recurring_lists_logic(
args, api, item, child_items, child_items_all, regen_labels_id) # args, api, item, child_items, child_items_all, regen_labels_id)
# If options turned on, start labelling logic # If options turned on, start labelling logic
if label_id is not None: if next_action_label is not None:
# Skip processing an item if it has already been checked or is a header # Skip processing a task if it has already been checked or is a header
if item['checked'] == 1: if task.is_completed:
continue continue
if item['content'].startswith('*'): if task.content.startswith('*'):
# Remove next action label if it's still present # Remove next action label if it's still present
remove_label(item, label_id, overview_item_ids,overview_item_labels) remove_label(task, next_action_label, overview_task_ids, overview_task_labels)
continue continue
# Check item type # Check task type
item_type, item_type_changed = get_item_type( task_type, task_type_changed = get_task_type(
args, item, project_type) args, task, project_type)
if item_type is not None: if task_type is not None:
logging.debug('Identified \'%s\' as %s type', logging.debug('Identified \'%s\' as %s type',
item['content'], item_type) task.content, task_type)
# Determine hierarchy types for logic # Determine hierarchy types for logic
hierarchy_types = [item_type, hierarchy_types = [task_type,
section_type, project_type] section_type, project_type]
active_types = [type(x) != type(None) hierarchy_boolean = [type(x) != type(None)
for x in hierarchy_types] for x in hierarchy_types]
# If it is a parentless task # If it is a parentless task
if item['parent_id'] == 0: if task.parent_id == 0:
if active_types[0]: if hierarchy_boolean[0]:
# Do item types # Inherit task type
active_type = item_type dominant_type = task_type
add_label( add_label(
item, label_id, overview_item_ids, overview_item_labels) task, next_action_label, overview_task_ids, overview_task_labels)
elif active_types[1]: elif hierarchy_boolean[1]:
# Do section types # Inherit section type
active_type = section_type dominant_type = section_type
if section_type == 'sequential' or section_type == 's-p': if section_type == 'sequential' or section_type == 's-p':
if not first_found_section: if not first_found_section:
add_label( add_label(
item, label_id, overview_item_ids, overview_item_labels) task, next_action_label, overview_task_ids, overview_task_labels)
first_found_section = True first_found_section = True
elif section_type == 'parallel' or section_type == 'p-s': elif section_type == 'parallel' or section_type == 'p-s':
add_label( add_label(
item, label_id, overview_item_ids, overview_item_labels) task, next_action_label, overview_task_ids, overview_task_labels)
elif active_types[2]: elif hierarchy_boolean[2]:
# Do project types # Inherit project type
active_type = project_type dominant_type = project_type
if project_type == 'sequential' or project_type == 's-p': if project_type == 'sequential' or project_type == 's-p':
if not first_found_project: if not first_found_project:
add_label( add_label(
item, label_id, overview_item_ids, overview_item_labels) task, next_action_label, overview_task_ids, overview_task_labels)
first_found_project = True first_found_project = True
elif project_type == 'parallel' or project_type == 'p-s': elif project_type == 'parallel' or project_type == 'p-s':
add_label( add_label(
item, label_id, overview_item_ids, overview_item_labels) task, next_action_label, overview_task_ids, overview_task_labels)
# Mark other conditions too # Mark other conditions too
if first_found_section == False and active_types[1]: if first_found_section == False and hierarchy_boolean[1]:
first_found_section = True first_found_section = True
if first_found_project is False and active_types[2]: if first_found_project is False and hierarchy_boolean[2]:
first_found_project = True first_found_project = True
# If there are children # If there are children
if len(child_items) > 0: if len(child_tasks) > 0:
# Check if item state has changed, if so clean children for good measure # Check if task state has changed, if so clean children for good measure
if item_type_changed == 1: if task_type_changed == 1:
[remove_label(child_item, label_id, overview_item_ids, overview_item_labels) [remove_label(child_task, next_action_label, overview_task_ids, overview_task_labels)
for child_item in child_items] for child_task in child_tasks]
# If a sub-task, inherit parent task type # If a sub-task, inherit parent task type
if item['parent_id'] !=0: if task.parent_id !=0:
try: try:
active_type = item['parent_type'] dominant_type = task.parent_type #TODO: METADATA
except: except:
pass pass
# Process sequential tagged items (item_type can overrule project_type) # Process sequential tagged tasks (task_type can overrule project_type)
if active_type == 'sequential' or active_type == 'p-s': if dominant_type == 'sequential' or dominant_type == 'p-s':
for child_item in child_items: for child_task in child_tasks:
# Ignore headered children # Ignore headered children
if child_item['content'].startswith('*'): if child_task.content.startswith('*'):
continue continue
# Pass item_type down to the children # Pass task_type down to the children
child_item['parent_type'] = active_type child_task.parent_type = dominant_type
# Pass label down to the first child # Pass label down to the first child
if child_item['checked'] == 0 and label_id in item['labels']: if not child_task.is_completed and next_action_label in task.labels:
add_label( add_label(
child_item, label_id, overview_item_ids, overview_item_labels) child_task, next_action_label, overview_task_ids, overview_task_labels)
remove_label( remove_label(
item, label_id, overview_item_ids, overview_item_labels) task, next_action_label, overview_task_ids, overview_task_labels)
else: else:
# Clean for good measure # Clean for good measure
remove_label( remove_label(
child_item, label_id, overview_item_ids, overview_item_labels) child_task, next_action_label, overview_task_ids, overview_task_labels)
# Process parallel tagged items or untagged parents # Process parallel tagged tasks or untagged parents
elif active_type == 'parallel' or (active_type == 's-p' and label_id in item['labels']): elif dominant_type == 'parallel' or (dominant_type == 's-p' and next_action_label in task.labels):
remove_label( remove_label(
item, label_id, overview_item_ids, overview_item_labels) task, next_action_label, overview_task_ids, overview_task_labels)
for child_item in child_items: for child_task in child_tasks:
# Ignore headered children # Ignore headered children
if child_item['content'].startswith('*'): if child_task.content.startswith('*'):
continue continue
child_item['parent_type'] = active_type child_task.parent_type = dominant_type #TODO: METADATA
if child_item['checked'] == 0: if not child_task.is_completed:
# child_first_found = True
add_label( add_label(
child_item, label_id, overview_item_ids, overview_item_labels) child_task, next_action_label, overview_task_ids, overview_task_labels)
# Remove labels based on start / due dates # Remove labels based on start / due dates
# If item is too far in the future, remove the next_action tag and skip # If task is too far in the future, remove the next_action tag and skip #TODO: FIX THIS
try: try:
if args.hide_future > 0 and 'due' in item.data and item['due'] is not None: if args.hide_future > 0 and 'due' in task.data and task.due is not None:
due_date = datetime.strptime( due_date = datetime.strptime(
item['due']['date'][:10], "%Y-%m-%d") task.due['date'][:10], "%Y-%m-%d")
future_diff = ( future_diff = (
due_date - datetime.today()).days due_date - datetime.today()).days
if future_diff >= args.hide_future: if future_diff >= args.hide_future:
remove_label( remove_label(
item, label_id, overview_item_ids, overview_item_labels) task, next_action_label, overview_task_ids, overview_task_labels)
continue continue
except: except:
# Hide-future not set, skip # Hide-future not set, skip
@ -836,15 +850,15 @@ def autodoist_magic(args, api, label_id, regen_labels_id):
# If start-date has not passed yet, remove label # If start-date has not passed yet, remove label
try: try:
f1 = item['content'].find('start=') f1 = task.content.find('start=')
f2 = item['content'].find('start=due-') f2 = task.content.find('start=due-')
if f1 > -1 and f2 == -1: if f1 > -1 and f2 == -1:
f_end = item['content'][f1+6:].find(' ') f_end = task.content[f1+6:].find(' ')
if f_end > -1: if f_end > -1:
start_date = item['content'][f1 + start_date = task.content[f1 +
6:f1+6+f_end] 6:f1+6+f_end]
else: else:
start_date = item['content'][f1+6:] start_date = task.content[f1+6:]
# If start-date hasen't passed, remove all labels # If start-date hasen't passed, remove all labels
start_date = datetime.strptime( start_date = datetime.strptime(
@ -853,39 +867,39 @@ def autodoist_magic(args, api, label_id, regen_labels_id):
datetime.today()-start_date).days datetime.today()-start_date).days
if future_diff < 0: if future_diff < 0:
remove_label( remove_label(
item, label_id, overview_item_ids, overview_item_labels) task, next_action_label, overview_task_ids, overview_task_labels)
[remove_label(child_item, label_id, overview_item_ids, [remove_label(child_task, next_action_label, overview_task_ids,
overview_item_labels) for child_item in child_items] overview_task_labels) for child_task in child_tasks]
continue continue
except: except:
logging.warning( logging.warning(
'Wrong start-date format for item: "%s". Please use "start=<DD-MM-YYYY>"', item['content']) 'Wrong start-date format for task: "%s". Please use "start=<DD-MM-YYYY>"', task.content)
continue continue
# Recurring task friendly - remove label with relative change from due date # Recurring task friendly - remove label with relative change from due date #TODO Fix this logic
try: try:
f = item['content'].find('start=due-') f = task.content.find('start=due-')
if f > -1: if f > -1:
f1a = item['content'].find( f1a = task.content.find(
'd') # Find 'd' from 'due' 'd') # Find 'd' from 'due'
f1b = item['content'].rfind( f1b = task.content.rfind(
'd') # Find 'd' from days 'd') # Find 'd' from days
f2 = item['content'].find('w') f2 = task.content.find('w')
f_end = item['content'][f+10:].find(' ') f_end = task.content[f+10:].find(' ')
if f_end > -1: if f_end > -1:
offset = item['content'][f+10:f+10+f_end-1] offset = task.content[f+10:f+10+f_end-1]
else: else:
offset = item['content'][f+10:-1] offset = task.content[f+10:-1]
try: try:
item_due_date = item['due']['date'][:10] task_due_date = task.due['date'][:10]
item_due_date = datetime.strptime( task_due_date = datetime.strptime(
item_due_date, '%Y-%m-%d') task_due_date, '%Y-%m-%d')
except: except:
logging.warning( logging.warning(
'No due date to determine start date for item: "%s".', item['content']) 'No due date to determine start date for task: "%s".', task.content)
continue continue
if f1a != f1b and f1b > -1: # To make sure it doesn't trigger if 'w' is chosen if f1a != f1b and f1b > -1: # To make sure it doesn't trigger if 'w' is chosen
@ -894,22 +908,35 @@ def autodoist_magic(args, api, label_id, regen_labels_id):
td = timedelta(weeks=int(offset)) td = timedelta(weeks=int(offset))
# If we're not in the offset from the due date yet, remove all labels # If we're not in the offset from the due date yet, remove all labels
start_date = item_due_date - td start_date = task_due_date - td
future_diff = ( future_diff = (
datetime.today()-start_date).days datetime.today()-start_date).days
if future_diff < 0: if future_diff < 0:
remove_label( remove_label(
item, label_id, overview_item_ids, overview_item_labels) task, next_action_label, overview_task_ids, overview_task_labels)
[remove_label(child_item, label_id, overview_item_ids, [remove_label(child_task, next_action_label, overview_task_ids,
overview_item_labels) for child_item in child_items] overview_task_labels) for child_task in child_tasks]
continue continue
except: except:
logging.warning( logging.warning(
'Wrong start-date format for item: %s. Please use "start=due-<NUM><d or w>"', item['content']) 'Wrong start-date format for task: %s. Please use "start=due-<NUM><d or w>"', task.content)
continue continue
return overview_item_ids, overview_item_labels return overview_task_ids, overview_task_labels
# Connect to SQLite database
def create_connection(path):
connection = None
try:
connection = sqlite3.connect(path)
print("Connection to SQLite DB successful")
except Error as e:
print(f"The error '{e}' occurred")
return connection
# Main # Main
@ -933,13 +960,13 @@ def main():
parser.add_argument( parser.add_argument(
'-d', '--delay', help='specify the delay in seconds between syncs (default 5).', default=5, type=int) '-d', '--delay', help='specify the delay in seconds between syncs (default 5).', default=5, type=int)
parser.add_argument( parser.add_argument(
'-pp', '--pp_suffix', help='change suffix for parallel-parallel labeling (default "//").', default='//') '-pp', '--pp_suffix', help='change suffix for parallel-parallel labeling (default "==").', default='==')
parser.add_argument( parser.add_argument(
'-ss', '--ss_suffix', help='change suffix for sequential-sequential labeling (default "--").', default='--') '-ss', '--ss_suffix', help='change suffix for sequential-sequential labeling (default "--").', default='--')
parser.add_argument( parser.add_argument(
'-ps', '--ps_suffix', help='change suffix for parallel-sequential labeling (default "/-").', default='/-') '-ps', '--ps_suffix', help='change suffix for parallel-sequential labeling (default "=-").', default='=-')
parser.add_argument( parser.add_argument(
'-sp', '--sp_suffix', help='change suffix for sequential-parallel labeling (default "-/").', default='-/') '-sp', '--sp_suffix', help='change suffix for sequential-parallel labeling (default "-=").', default='-=')
parser.add_argument( parser.add_argument(
'-df', '--dateformat', help='strptime() format of starting date (default "%%d-%%m-%%Y").', default='%d-%m-%Y') '-df', '--dateformat', help='strptime() format of starting date (default "%%d-%%m-%%Y").', default='%d-%m-%Y')
parser.add_argument( parser.add_argument(
@ -955,6 +982,9 @@ def main():
args = parser.parse_args() args = parser.parse_args()
# #TODO: Temporary disable this feature for now. Find a way to see completed tasks first, since REST API v2 lost this funcionality.
args.regeneration = 0
# Addition of regeneration labels # Addition of regeneration labels
args.regen_label_names = ('Regen_off', 'Regen_all', args.regen_label_names = ('Regen_off', 'Regen_all',
'Regen_all_if_completed') 'Regen_all_if_completed')
@ -977,25 +1007,25 @@ def main():
check_for_update(current_version) check_for_update(current_version)
# Initialise api # Initialise api
api, label_id, regen_labels_id = initialise(args) api = initialise(args)
# Start main loop # Start main loop
while True: while True:
start_time = time.time() start_time = time.time()
# sync(api) # sync(api)
# Evaluate projects, sections, and items # Evaluate projects, sections, and tasks
overview_item_ids, overview_item_labels = autodoist_magic( overview_task_ids, overview_task_labels = autodoist_magic(
args, api, label_id, regen_labels_id) args, api, args.label, args.regen_label_names)
# Commit the queue with changes # Commit next action label changes
if label_id is not None: if args.label is not None:
update_labels(api, label_id, overview_item_ids, updated_ids = update_labels(api, overview_task_ids,
overview_item_labels) overview_task_labels)
if len(updated_ids):
len_api_q = len(updated_ids)
if len(api.queue):
len_api_q = len(api.queue)
api.commit()
if len_api_q == 1: if len_api_q == 1:
logging.info( logging.info(
'%d change committed to Todoist.', len_api_q) '%d change committed to Todoist.', len_api_q)

View File

@ -1,2 +1,2 @@
requests>=2.25.1 requests>=2.28.1
todoist_python>=8.1.3 todoist_api_python>=2.0.2