ThermalTodos/application/database.py
2023-08-28 11:33:56 -04:00

86 lines
2.2 KiB
Python

import json
import requests
# from datetime import datetime
import time
import random
import copy
class TodoDatabase:
def __init__(self, filename="data.json"):
self.filename = filename
self.database = {}
try:
with open(self.filename) as f:
self.database = json.load(f)
except:
pass
def save_todo(self, date, todo, save=True):
if "recurring" not in self.database:
self.database["recurring"] = []
if date not in self.database:
# if not len(self.database[date]) > 0:
self.database[date] = [] #copy.deepcopy(self.database["recurring"])
if todo.recurring:
self.database["recurring"].append(todo.model_dump())
self.database[date].append(todo.model_dump())
if save:
self._save_database()
def save_todos(self, date, todos):
for todo in todos:
self.save_todo(date, todo, save=False)
self._save_database()
def remove_todos(self, date):
if date in self.database:
del self.database[date]
def remove_recurring(self, todo):
if 'recurring' in self.database:
self.database['recurring'] = [i for i in self.database['recurring'] if (i["time"] == todo.time and i['task'] == todo.task)]
# t = [i for i in t if i.name!="Remove me"]
def read_todos(self, date):
# if self.datebase[date] is None:
# return []
if date not in self.database:
if "recurring" not in self.database:
return []
return self.database["recurring"]
if "recurring" in self.database:
return self.database[date] + self.database['recurring']
return self.database[date]
def _update_quotes(self):
r = requests.get("https://zenquotes.io/api/quotes")
res = r.json()
# if "quotes" not in self.database:
self.database["quotes"] = res
self.database["quotes_last_updated"] = time.time()
self._save_database()
def get_random_quote(self):
# print(time.time())
if ("quotes_last_updated" not in self.database) or ("quotes" not in self.database) or (time.time()-self.database["quotes_last_updated"] > 86400):
self._update_quotes()
quote = random.choice(self.database["quotes"])
return [quote['q'], "- " + quote['a']]
def _save_database(self):
with open(self.filename, 'w') as f:
json.dump(self.database, f)
if __name__ == '__main__':
data = TodoDatabase()
# data._update_quotes()
print(data.get_random_quote())