Skip to content

Commit

Permalink
Clean-up warnings.
Browse files Browse the repository at this point in the history
  • Loading branch information
programmerPhysicist committed Aug 3, 2024
1 parent 5d656f4 commit e18a995
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 86 deletions.
17 changes: 9 additions & 8 deletions source/habitica.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,25 @@
from hab_task import HabTask

def get_all_habtasks(auth):
#Todoist tasks are, I think, classes. Let's make Habitica tasks classes, too.
# Todoist tasks are, I think, classes. Let's make Habitica tasks classes, too.
url = 'https://habitica.com/api/v3/tasks/user/'
# TODO: handle error cases for response
response = requests.get(url,headers=auth)
if response.ok == True:
response = requests.get(url, headers=auth)
if response.ok:
hab_raw = response.json()
"""FINALLY getting something I can work with... this will be a list of
dicts I want to turn into a list of objects with class hab_tasks.
Hrm. Weeeelll, if I make a class elsewhere...."""
# FINALLY getting something I can work with... this will be a list of
# dicts I want to turn into a list of objects with class hab_tasks.
# Hrm. Weeeelll, if I make a class elsewhere....
hab_tasklist = hab_raw['data']
else:
hab_tasklist = []
print(response.reason)

#keeping records of all our tasks
# keeping records of all our tasks
hab_tasks = []

#No habits right now, I'm afraid, in hab_tasks--Todoist gets upset. So we're going to make a list of dailies and todos instead...
# No habits right now, I'm afraid, in hab_tasks-Todoist gets upset. So we're going to make a list of dailies and
# todos instead...
for task in hab_tasklist:
item = HabTask(task)
if item.category == 'reward':
Expand Down
46 changes: 20 additions & 26 deletions source/main.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,20 @@
#!/usr/bin/env python

"""
Main.py overdue for an overhaul! Let's see.
"""

"""Here's where we import stuff we need..."""
#import todoist
import requests
import json
from hab_task import HabTask
from todo_task import TodTask
# import json
# from datetime import datetime
# import todoist
# import re
import os
import logging
import configparser

from datetime import datetime
import sys
import requests
from dateutil import parser
import re


"""
Version control, basic paths
"""
from hab_task import HabTask
from todo_task import TodTask

# TODO: Main.py overdue for an overhaul! Let's see.
# Version control, basic paths
VERSION = 'Habitica-Plus-Todoist version 2.1.0'
TASK_VALUE_BASE = 0.9747 # http://habitica.wikia.com/wiki/Task_Value
HABITICA_REQUEST_WAIT_TIME = 0.5 # time to pause between concurrent requests
Expand Down Expand Up @@ -217,21 +209,23 @@ def get_all_habtasks(auth):
hab_tasks.append(item)
return(hab_tasks, response)


def get_hab_fromID(tid):
import requests
import json
auth = get_started('auth.cfg')
url = 'https://habitica.com/api/v3/tasks/'
url += str(tid)
r = requests.get(headers=auth, url=url)
if r.ok == True:
if r.ok:
task = r.json()
hab = HabTask(task['data'])
else:
#TODO: log error
# TODO: log error
hab = HabTask()
return hab


def get_started(configfile):
"""Get Habitica authentication data from the AUTH_CONF file."""

Expand Down Expand Up @@ -267,8 +261,8 @@ def get_started(configfile):
# Return auth data as a dictionnary
return rv

def get_uniqs(matchDict,tod_tasks,hab_tasks):
# TODO: Rename this function
def get_uniqs(matchDict, tod_tasks, hab_tasks):
# TODO: Rename this function
tod_uniq = []
hab_uniq = []

Expand Down Expand Up @@ -483,13 +477,13 @@ def sync_hab2todo(hab, tod):
return new_hab
else:
print("Error! Hab of incorrect type!")
exit(1)
sys.exit(1)

def sync_hab2todo_daily(hab, tod):
from dates import parse_date_utc
from datetime import datetime
# from datetime import datetime
from datetime import timedelta
import pytz
# import pytz
habDict = hab.task_dict
if tod.priority == 4:
habDict['priority'] = 2
Expand All @@ -498,7 +492,7 @@ def sync_hab2todo_daily(hab, tod):
else:
habDict['priority'] = 1

now = datetime.now().replace(tzinfo=pytz.utc).date()
# now = datetime.now().replace(tzinfo=pytz.utc).date()

if hab.due.date() != (tod.due.date() - timedelta(days=1)):
habDict['startDate'] = str(tod.due.date() - timedelta(days=1))
Expand Down
90 changes: 42 additions & 48 deletions source/oneWaySync.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,20 @@
just not for recurring todo tasks or dailies. I'm workin' on that.
"""

#Python library imports - this will be functionalities I want to shorten
from os import path # will let me call files from a specific path
import requests
# Python library imports - this will be functionalities I want to shorten
# from datetime import datetime, timedelta
import pickle
#import todoist
import time

from todoist_api_python.api import TodoistAPI
from todoist_api_python.endpoints import get_sync_url
from todoist_api_python.http_requests import get
from todoist_api_python.models import CompletedItems
from todoist_api_python.models import Task
import main
import random
import json
from todo_task import TodTask
from datetime import datetime
from datetime import timedelta
# from dateutil import parser
import logging
import configparser
import config
import habitica
import time


def get_tasks(token):
tasks = []
Expand All @@ -38,6 +30,7 @@ def get_tasks(token):
print(error)
return tasks, api


def dict_to_Task(obj, url):
obj['comment_count'] = obj['note_count']
obj['is_completed'] = (obj['completed_at'] != '')
Expand All @@ -48,82 +41,82 @@ def dict_to_Task(obj, url):
obj['url'] = url
return Task.from_dict(obj)


def get_all_completed_items(api):
url = get_sync_url('completed/get_all')
completed_items = get(api._session, url, api._token)
tasks = completed_items['items']
return [dict_to_Task(obj, url) for obj in tasks]


def sync_todoist_to_habitica():
# todayFilter = todoApi.filters.add('todayFilter', 'today')

#Telling the site where the config stuff for Habitica can go and get a list of habitica tasks...
# Telling the site where the config stuff for Habitica can go and get a list of habitica tasks...
auth = config.get_started('auth.cfg')

#Getting all complete and incomplete habitica dailies and todos
# Getting all complete and incomplete habitica dailies and todos
hab_tasks = habitica.get_all_habtasks(auth)

# get token for todoist
todoToken = config.getTodoistToken('auth.cfg')

#Okay, now I need a list of todoist tasks.
# Okay, now I need a list of todoist tasks.
todoist_tasks, todoApi = get_tasks(todoToken) # todoist_tasks used to be tod_tasks

tod_tasks = []
for i in range(0, len(todoist_tasks)):
tod_tasks.append(TodTask(todoist_tasks[i]))

# date stuff
today = datetime.now()
today_str = today.strftime("%Y-%m-%d")
one_day = timedelta(days=1)
yesterday = datetime.now() - one_day
yesterday_str = yesterday.strftime("%Y-%m-%d")

"""
Okay, I want to write a little script that checks whether or not a task is there or not and, if not, ports it.
"""
# today = datetime.now()
# today_str = today.strftime("%Y-%m-%d")
# one_day = timedelta(days=1)
# yesterday = datetime.now() - one_day
# yesterday_str = yesterday.strftime("%Y-%m-%d")

# Okay, I want to write a little script that checks whether or not a task is there or not and, if not, ports it.

matchDict = main.openMatchDict()

#Also, update lists of tasks with matchDict file...
# Also, update lists of tasks with matchDict file...
matchDict = main.update_tod_matchDict(tod_tasks, matchDict)
matchDict = main.update_hab_matchDict(hab_tasks, matchDict)

#We'll want to just... pull all the unmatched completed tasks out of our lists of tasks. Yeah?
# We'll want to just... pull all the unmatched completed tasks out of our lists of tasks. Yeah?
tod_done = [TodTask(task) for task in get_all_completed_items(todoApi)]
tod_uniq, hab_uniq = main.get_uniqs(matchDict, tod_done, hab_tasks)

#Okay, so what if there are two matched tasks in the two uniq lists that really should be paired?
matchDict = main.check_newMatches(matchDict,tod_uniq,hab_uniq)
# Okay, so what if there are two matched tasks in the two uniq lists that really should be paired?
matchDict = main.check_newMatches(matchDict, tod_uniq, hab_uniq)

#Here anything new in todoist gets added to habitica
# Here anything new in todoist gets added to habitica
tod_uniq = []
hab_uniq = []
tod_uniq, hab_uniq = main.getNewTodoTasks(matchDict, tod_tasks, hab_tasks)

tod_uniqSize = len(tod_uniq)
for tod in tod_uniq:
tid = tod.id
if tod.recurring == "Yes":
new_hab = main.make_daily_from_tod(tod)
else:
new_hab = main.make_hab_from_tod(tod)
newDict = new_hab.task_dict
new_dict = new_hab.task_dict

# sleep to stay within rate limits
time.sleep(2)
r = main.write_hab_task(newDict)
if r.ok == False:
#TODO: check ['errors'], due to it sometimes not having it
response = main.write_hab_task(new_dict)
if not response.ok:
# TODO: check ['errors'], due to it sometimes not having it
try:
json = r.json()
json_str = response.json()
except:
print("Unknown json error!")
else:
errMsg = json['errors'][0]['message']
alias = json['errors'][0]['value']
print("Error Code "+str(r.status_code)+": \""
+errMsg+"\", Task alias: "+alias)
err_msg = json_str['errors'][0]['message']
alias = json_str['errors'][0]['value']
msg = "Error Code " + str(response.status_code) + ": \"" + err_msg + "\", Task alias: " + alias
print(msg)
else:
print("Added hab to %s!" % tod.name)
fin_hab = main.get_hab_fromID(tid)
Expand All @@ -139,7 +132,7 @@ def sync_todoist_to_habitica():
else:
matchDict[tid]['duelast'] = 'NA'

#Check that anything which has recently been completed gets updated in habitica
# Check that anything which has recently been completed gets updated in habitica
for tid in matchDict:
tod = matchDict[tid]['tod']
hab = matchDict[tid]['hab']
Expand All @@ -148,9 +141,9 @@ def sync_todoist_to_habitica():
if hab.completed == False:
if tod.dueToday == 'Yes':
matched_hab = main.sync_hab2todo(hab, tod)
r = main.update_hab(matched_hab)
response = main.update_hab(matched_hab)
elif tod.dueToday == 'No':
r = main.complete_hab(hab)
response = main.complete_hab(hab)
print('Completed daily hab %s' % hab.name)
else:
print("error in daily Hab")
Expand All @@ -169,7 +162,7 @@ def sync_todoist_to_habitica():
except:
matchDict[tid]['duelast'] = 'No'
if tod.dueToday == 'Yes':
matchDict[tid]['duelast'] = 'Yes' #this is me keeping a record of recurring tods being completed or not for some of the complicated bits
matchDict[tid]['duelast'] = 'Yes' # this is me keeping a record of recurring tods being completed or not for some of the complicated bits
if hab.completed == False:
if matchDict[tid]['duelast'] == 'Yes':
if tod.dueToday == 'No':
Expand Down Expand Up @@ -198,7 +191,7 @@ def sync_todoist_to_habitica():
print('completed tod %s' % tod.name)
else:
print("ERROR: check HAB %s" % tid)
#matchDict.pop(tid)
# matchDict.pop(tid)
elif tod.complete == 1:
if hab.completed == False:
r = main.complete_hab(hab)
Expand All @@ -214,7 +207,7 @@ def sync_todoist_to_habitica():
print("ERROR: check HAB %s" % tid)
else:
print("ERROR: check TOD %s" % tid)
r = []
response = []
# try:
# dueNow = str(parser.parse(matchDict[tid]['tod'].due_date).date())
# except:
Expand All @@ -227,7 +220,8 @@ def sync_todoist_to_habitica():
pkl_out = pickle.Pickler(pkl_file, -1)
pkl_out.dump(matchDict)
pkl_file.close()
#todoApi.commit()
# todoApi.commit()


if __name__ == "__main__":
sync_todoist_to_habitica()
sync_todoist_to_habitica()
8 changes: 4 additions & 4 deletions source/todo_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,11 +126,10 @@ def due_date(self, date):
def due(self):
from dateutil import parser
import datetime
if self.__task_dict['due'] != None:
if self.__task_dict['due'] is not None:
date = parser.parse(self.__task_dict['due']['date'])
return date
else:
return ''
return ''

@property
#is it due TODAY?
Expand All @@ -141,7 +140,8 @@ def dueToday(self):
import pytz
today = datetime.utcnow().replace(tzinfo=pytz.UTC)
try:
wobble = parser.parse(self.__task_dict['due']) - timedelta(hours=6) #that datetime thing is pulling todoist's due dates to my time zone
# that datetime thing is pulling todoist's due dates to my time zone
wobble = parser.parse(self.__task_dict['due']) - timedelta(hours=6)
dueDate = wobble.date()
except:
dueDate = ""
Expand Down

0 comments on commit e18a995

Please sign in to comment.