scheduled tasks

This commit is contained in:
samerbam 2023-08-27 00:25:56 -04:00
parent eb31eccdc1
commit 8199fe4432
6 changed files with 94 additions and 34 deletions

View File

@ -1,5 +1,6 @@
TODO: TODO:
- check if first run (api call) and show google calendar login button - check if first run (api call) and show google calendar login button
* schedule pypi every().day() or smth like that at (time to print)-5 minutes to update calendar and get ready to print new daily list * schedule pypi every().day() or smth like that at (time to print)-5 minutes to update calendar and get ready to print new daily list
* parse calendar list to database format and call save_todos() with list of Todos - parse calendar list to database format and call save_todos() with list of Todos
- Start uvicorn on device startup (using gunicorn + sysmtectl) - Start uvicorn on device startup (using gunicorn + sysmtectl)
* remove from recurring list api call

View File

@ -11,6 +11,7 @@ from .utils import VerifyToken
from .database import TodoDatabase from .database import TodoDatabase
from .thermal_print import ThermalPrinter from .thermal_print import ThermalPrinter
from .sync_calendar import SyncData from .sync_calendar import SyncData
from .tododatatypes import *
import errno import errno
import os import os
@ -31,35 +32,35 @@ printer = ThermalPrinter(data)
class Todo(BaseModel): # class Todo(BaseModel):
time: str # time: str
task: str # task: str
recurring: bool # recurring: bool
class TodoList(BaseModel): # class TodoList(BaseModel):
date: str #Always selected date OLD TEXT: #Either current date in %Y-%m-%d format or "recurring" for a recurring task # date: str #Always selected date OLD TEXT: #Either current date in %Y-%m-%d format or "recurring" for a recurring task
todos: list[Todo] # todos: list[Todo]
class TodoDate(BaseModel): # class TodoDate(BaseModel):
date: str # date: str
# date: str = datetime.today().strftime('%Y-%m-%d') # # date: str = datetime.today().strftime('%Y-%m-%d')
class PrintAction(BaseModel): # class PrintAction(BaseModel):
date: str = datetime.today().strftime('%Y-%m-%d') # date: str = datetime.today().strftime('%Y-%m-%d')
action: str #Options: # action: str #Options:
# all (pulls current todos from date, needs date) # # all (pulls current todos from date, needs date)
# sudoku (prints a random sudoku) # # sudoku (prints a random sudoku)
# todos (prints only dates todos) # # todos (prints only dates todos)
# wordsearch (prints a random wordsearch) # # wordsearch (prints a random wordsearch)
# quote (prints a random quote) # # quote (prints a random quote)
# greeting (prints a greeting) # # greeting (prints a greeting)
# sentence (prints a custom message) # # sentence (prints a custom message)
sentence: str = "" # sentence: str = ""
class GoogleUpdate(BaseModel): # class GoogleUpdate(BaseModel):
code: str # code: str
# @app.get("/api/public") # @app.get("/api/public")
# def public(): # def public():

View File

@ -8,10 +8,11 @@ from googleapiclient.errors import HttpError
import os import os
import json import json
import datetime import datetime
import schedule
from .database import TodoDatabase from .database import TodoDatabase
from .tododatatypes import Todo
data = TodoDatabase() data = TodoDatabase()
@ -52,6 +53,7 @@ class SyncData():
self.get_new_creds() self.get_new_creds()
self.get_calendar_events() self.get_calendar_events()
schedule.every(1).day.at("07:55").do(self.get_calendar_events)
def get_new_creds(self, code=""): def get_new_creds(self, code=""):
@ -127,11 +129,11 @@ class SyncData():
day_end_for = day_end.astimezone(ZoneInfo("UTC")).strftime('%Y-%m-%dT%H:%M:%S.%fZ') day_end_for = day_end.astimezone(ZoneInfo("UTC")).strftime('%Y-%m-%dT%H:%M:%S.%fZ')
# print(day_start.tzname()) # print(day_start.tzname())
print(day_start) # print(day_start)
print(day_end) # print(day_end)
print(day_start.astimezone(ZoneInfo("UTC")).strftime('%Y-%m-%dT%H:%M:%S.%fZ')) # print(day_start.astimezone(ZoneInfo("UTC")).strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
print(day_end.astimezone(ZoneInfo("UTC")).strftime('%Y-%m-%dT%H:%M:%S.%fZ')) # print(day_end.astimezone(ZoneInfo("UTC")).strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
print(datetime.utcnow().isoformat() + 'Z') # print(datetime.utcnow().isoformat() + 'Z')
try: try:
@ -148,13 +150,33 @@ class SyncData():
print('No upcoming events found.') print('No upcoming events found.')
return return
print(str(len(events)) + " events found")
# Prints the start and name of the next 10 events # Prints the start and name of the next 10 events
# event format: {'kind': 'calendar#event', 'etag': '"3386046190326000"', 'id': '0migcv6t729ph1kirhiauej3eh', 'status': 'confirmed', 'htmlLink': 'https://www.google.com/calendar/event?eid=MG1pZ2N2NnQ3MjlwaDFraXJoaWF1ZWozZWggYmFtLmltLnNhbUBt', 'created': '2023-08-26T04:11:35.000Z', 'updated': '2023-08-26T04:11:35.163Z', 'summary': 'test', 'creator': {'email': 'bam.im.sam@gmail.com', 'self': True}, 'organizer': {'email': 'bam.im.sam@gmail.com', 'self': True}, 'start': {'dateTime': '2023-08-27T14:30:00-04:00', 'timeZone': 'America/Toronto'}, 'end': {'dateTime': '2023-08-27T15:30:00-04:00', 'timeZone': 'America/Toronto'}, 'iCalUID': '0migcv6t729ph1kirhiauej3eh@google.com', 'sequence': 0, 'reminders': {'useDefault': True}, 'eventType': 'default'} # event format: {'kind': 'calendar#event', 'etag': '"3386046190326000"', 'id': '0migcv6t729ph1kirhiauej3eh', 'status': 'confirmed', 'htmlLink': 'https://www.google.com/calendar/event?eid=MG1pZ2N2NnQ3MjlwaDFraXJoaWF1ZWozZWggYmFtLmltLnNhbUBt', 'created': '2023-08-26T04:11:35.000Z', 'updated': '2023-08-26T04:11:35.163Z', 'summary': 'test', 'creator': {'email': 'bam.im.sam@gmail.com', 'self': True}, 'organizer': {'email': 'bam.im.sam@gmail.com', 'self': True}, 'start': {'dateTime': '2023-08-27T14:30:00-04:00', 'timeZone': 'America/Toronto'}, 'end': {'dateTime': '2023-08-27T15:30:00-04:00', 'timeZone': 'America/Toronto'}, 'iCalUID': '0migcv6t729ph1kirhiauej3eh@google.com', 'sequence': 0, 'reminders': {'useDefault': True}, 'eventType': 'default'}
formatted_todo_list = []
# print(events)
for event in events: for event in events:
print(event) # print(event)
start = event['start'].get('dateTime', event['start'].get('date')) start = event['start'].get('dateTime', event['start'].get('date'))
end = event['end'].get('dateTime', event['end'].get('date')) end = event['end'].get('dateTime', event['end'].get('date'))
print(start, "->", end, event['summary']) # print(event)
# print(start, "->", end, event['summary'])
start_parsed = datetime.strptime(start, "%Y-%m-%dT%H:%M:%S%z").strftime("%-I:%M%p") #2023-08-26T15:30:00-04:00
end_parsed = datetime.strptime(end, "%Y-%m-%dT%H:%M:%S%z").strftime("%-I:%M%p") #2023-08-26T15:30:00-04:00
# print("parsed: ", start_parsed, "to", end_parsed, event['summary'])
if 'summary' in event:
# {"time": start_parsed + " to " + end_parsed, "task": event['summary'], "recurring": False}
formatted_todo_list.append(Todo(time=start_parsed + " to " + end_parsed, task=event['summary'], recurring=False))
# formatted_todo_list.append({"time": start_parsed + " to " + end_parsed, "task": event['summary'], "recurring": False})
else:
formatted_todo_list.append(Todo(time=start_parsed + " to " + end_parsed, task='No Title', recurring=False))
# formatted_todo_list.append({"time": start_parsed + " to " + end_parsed, "task": 'No Title', "recurring": False})
# print(formatted_todo_list)
data.save_todos(day_start.strftime("%Y-%m-%d"), formatted_todo_list)
except HttpError as error: except HttpError as error:
print('An error occurred: %s' % error) print('An error occurred: %s' % error)

View File

@ -35,6 +35,7 @@ import usb
from wonderwords import RandomWord from wonderwords import RandomWord
from datetime import datetime from datetime import datetime
import textwrap import textwrap
import schedule
from .sudoku_generator import * from .sudoku_generator import *
@ -56,6 +57,7 @@ class ThermalPrinter():
self.p = Dummy() self.p = Dummy()
print("Try running `export DYLD_LIBRARY_PATH=/opt/homebrew/lib` if on m1 mac. source: https://github.com/pyusb/pyusb/issues/355#issuecomment-1062798576") print("Try running `export DYLD_LIBRARY_PATH=/opt/homebrew/lib` if on m1 mac. source: https://github.com/pyusb/pyusb/issues/355#issuecomment-1062798576")
# raise # raise
schedule.every().day.at("08:00").do(self.print_default)
def print_custom(self, text=""): def print_custom(self, text=""):
self.p.set(align="left") self.p.set(align="left")

View File

@ -0,0 +1,32 @@
from pydantic import BaseModel
from datetime import datetime
class Todo(BaseModel):
time: str
task: str
recurring: bool
class TodoList(BaseModel):
date: str #Always selected date OLD TEXT: #Either current date in %Y-%m-%d format or "recurring" for a recurring task
todos: list[Todo]
class TodoDate(BaseModel):
date: str
# date: str = datetime.today().strftime('%Y-%m-%d')
class PrintAction(BaseModel):
date: str = datetime.today().strftime('%Y-%m-%d')
action: str #Options:
# all (pulls current todos from date, needs date)
# sudoku (prints a random sudoku)
# todos (prints only dates todos)
# wordsearch (prints a random wordsearch)
# quote (prints a random quote)
# greeting (prints a greeting)
# sentence (prints a custom message)
sentence: str = ""
class GoogleUpdate(BaseModel):
code: str

View File

@ -22,4 +22,6 @@ wonderwords
google-api-python-client google-api-python-client
google-auth google-auth
google-auth-oauthlib google-auth-oauthlib
google-auth-httplib2 google-auth-httplib2
gunicorn
schedule