diff options
| author | altaf-creator <dev@altafcreator.com> | 2025-11-30 22:11:40 +0700 |
|---|---|---|
| committer | altaf-creator <dev@altafcreator.com> | 2025-11-30 22:11:40 +0700 |
| commit | b0ff8d088466c431553b82cbd4ab79800b917b4e (patch) | |
| tree | 0685e7902756ba07f11a209de80fde689881732a /backend | |
| parent | 9ce09c77d8be414969911d3b5a3387516637a6c1 (diff) | |
url params start
Diffstat (limited to 'backend')
| -rw-r--r-- | backend/__pycache__/main.cpython-314.pyc | bin | 17955 -> 18547 bytes | |||
| -rw-r--r-- | backend/config.yaml | 14 | ||||
| -rw-r--r-- | backend/main.py | 90 |
3 files changed, 83 insertions, 21 deletions
diff --git a/backend/__pycache__/main.cpython-314.pyc b/backend/__pycache__/main.cpython-314.pyc Binary files differindex e0857df..b53b159 100644 --- a/backend/__pycache__/main.cpython-314.pyc +++ b/backend/__pycache__/main.cpython-314.pyc diff --git a/backend/config.yaml b/backend/config.yaml new file mode 100644 index 0000000..a72ad85 --- /dev/null +++ b/backend/config.yaml @@ -0,0 +1,14 @@ +--- +qr_uri: + h1: + status: "h0" + dryer1: "NVw19NPugIpaSxIy" + washer1: "S9DxQLUgTXxWc0W3" + dryer2: "UGRQyHkVeESw2ADv" + washer2: "hHtjZL2gNThxrhix" + h2: + status: "h4" + dryer1: "TnYnXbqHRuaYWBHy" + washer1: "Z2Vp4Tpzxs1nYe7Q" + dryer2: "isltjtipJGCBeZrI" + washer2: "wmY8BYBafi4kAc2Z" diff --git a/backend/main.py b/backend/main.py index 719c835..a667439 100644 --- a/backend/main.py +++ b/backend/main.py @@ -16,7 +16,9 @@ import secrets from enum import Enum from dotenv import load_dotenv from os import getenv +import yaml +# ## API, db, and scheduler initialisation app = fastapi.FastAPI(title="Victoria Hall LaundryWeb", description="LaundryWeb Backend API", version="0.1") conn = sqlite3.connect("db.db", check_same_thread=False) cursor = conn.cursor() @@ -24,18 +26,6 @@ cursor = conn.cursor() scheduler = BackgroundScheduler() scheduler.start() -load_dotenv() - -onesignal_configuration = onesignal.Configuration( - rest_api_key=getenv("REST_API_KEY"), - organization_api_key=getenv("ORGANIZATION_API_KEY"), -) - -api_client = onesignal.ApiClient(onesignal_configuration) -api_instance = default_api.DefaultApi(api_client) - -ONESIGNAL_APP_ID = "83901cc7-d964-475a-90ec-9f854df4ba52" - origins = [ "http://localhost", "http://localhost:998", @@ -67,10 +57,44 @@ CREATE TABLE IF NOT EXISTS timers ( """) # block is either 1 or 2, machine (1-4), odd is dryer, even is machine. +# ## yaml configuration initialisation + +qr_uri = {} + +stream = open("config.yaml", 'r') +yaml_dict = yaml.load(stream, yaml.Loader) + +# inverting the key-value pair for the dict to act as a map +# easy matching for the users' scanned obscure uri and the supposed +for k, v in yaml_dict["qr_uri"]["h1"].items(): + qr_uri[v] = f"h1-{k}" +for k, v in yaml_dict["qr_uri"]["h2"].items(): + qr_uri[v] = f"h1-{k}" + +print("config.yaml loaded, qr_uri:") +for k,v in qr_uri.items(): + print(k, v) + + +# ## onesignal initialisation +load_dotenv() + +onesignal_configuration = onesignal.Configuration( + rest_api_key=getenv("REST_API_KEY"), + organization_api_key=getenv("ORGANIZATION_API_KEY"), +) + +api_client = onesignal.ApiClient(onesignal_configuration) +api_instance = default_api.DefaultApi(api_client) + +ONESIGNAL_APP_ID = "83901cc7-d964-475a-90ec-9f854df4ba52" + + +# ## class / data struct definitions + class RequestData(BaseModel): duration: int - block: int - machine: int + machine_id: str class BlockRequestData(BaseModel): @@ -88,6 +112,8 @@ class Status(Enum): OUTOFSERVICE = 3, +# ## global vars for user-end + machine_status = [[Status.EMPTY.name, Status.EMPTY.name, Status.EMPTY.name, Status.EMPTY.name], [Status.EMPTY.name, Status.EMPTY.name, Status.EMPTY.name, Status.EMPTY.name]] machine_times = [[None, None, None, None], @@ -96,6 +122,8 @@ machine_durations = [[None, None, None, None], [None, None, None, None]] +# ## some non-api endpoint method definitions + # this method checks for any entry, and starts the previously-terminated schedules # useful if you're restarting the server def restart_terminated_schedules(): @@ -129,7 +157,7 @@ def reminder_timer_finished(timer_id): end_date = datetime.datetime.now() + datetime.timedelta(minutes=5) scheduler.add_job(final_timer_finished, 'date', run_date=end_date, id=str(timer_id), args=[timer_id]) - notification = Notification(app_id=ONESIGNAL_APP_ID, included_segments=['All'], contents={'en':'get ready to get your bloody laundry'}, headings={'en':'laundry almost finished'}) + notification = Notification(app_id=ONESIGNAL_APP_ID, included_segments=['All'], contents={'en': 'get ready to get your bloody laundry'}, headings={'en': 'laundry almost finished'}) try: api_response = api_instance.create_notification(notification) @@ -142,8 +170,8 @@ def final_timer_finished(timer_id): cursor.execute(f"SELECT * FROM timers WHERE timer_id = '{timer_id}'") out = cursor.fetchall() - notification = Notification(app_id=ONESIGNAL_APP_ID, included_segments=['All'], contents={'en':'get your bloody laundry'}, headings={'en':'laundry finished'}) - + notification = Notification(app_id=ONESIGNAL_APP_ID, included_segments=['All'], contents={'en' : 'get your bloody laundry'}, headings={'en': 'laundry finished'}) + try: api_response = api_instance.create_notification(notification) except Exception as e: @@ -167,6 +195,19 @@ restart_terminated_schedules() # ## api endpoints +# this is a constant, mapping uri keys to block-machine pair +URI_TO_MACHINES = { + "h1-dryer1": [1, 1], + "h1-washer1": [1, 2], + "h1-dryer2": [1, 3], + "h1-washer2": [1, 4], + "h2-dryer1": [2, 1], + "h2-washer1": [2, 2], + "h2-dryer2": [2, 3], + "h2-washer2": [2, 4], +} + + # --- starting new timer @app.post("/start", response_class=PlainTextResponse) async def start_new_timer(data: RequestData, response: fastapi.Response, session_key: Annotated[str | None, fastapi.Cookie()] = None): @@ -181,10 +222,17 @@ async def start_new_timer(data: RequestData, response: fastapi.Response, session return "something went wrong during session key creation" try: + block = URI_TO_MACHINES[qr_uri[data.machine_id]][0] + machine = URI_TO_MACHINES[qr_uri[data.machine_id]][1] + except KeyError: + response.status_code = fastapi.status.HTTP_401_UNAUTHORIZED + return "invalid uri; you are unauthorised" + + try: print("session key valid", session_key) cursor.execute(f""" INSERT INTO timers (user_id, start_time, duration, block, machine, status) - VALUES ('{session_key}', '{now.isoformat()}', {data.duration * 30}, {data.block}, {data.machine}, 'RUNNING') + VALUES ('{session_key}', '{now.isoformat()}', {data.duration * 30}, {block}, {machine}, 'RUNNING') """) conn.commit() cursor.execute("SELECT * FROM timers;") @@ -210,9 +258,9 @@ async def start_new_timer(data: RequestData, response: fastapi.Response, session return "something went wrong during scheduler stuff" try: - machine_status[data.block - 1][data.machine - 1] = Status.RUNNING.name - machine_times[data.block - 1][data.machine - 1] = now.isoformat() - machine_durations[data.block - 1][data.machine - 1] = data.duration * 30 + machine_status[block - 1][machine - 1] = Status.RUNNING.name + machine_times[block - 1][machine - 1] = now.isoformat() + machine_durations[block - 1][machine - 1] = data.duration * 30 except Exception as exception: print("err @ machine_status //", exception) response.status_code = fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR |
