1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
|
import fastapi
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import PlainTextResponse
from apscheduler.schedulers.background import BackgroundScheduler
import onesignal
from onesignal.model.rate_limit_error import RateLimitError
from onesignal.model.generic_error import GenericError
from onesignal.model.notification import Notification
from onesignal.model.create_notification_success_response import CreateNotificationSuccessResponse
from onesignal.api import default_api
import sqlite3
from typing import Annotated
import datetime
from pydantic import BaseModel
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()
scheduler = BackgroundScheduler()
scheduler.start()
origins = [
"http://localhost",
"http://localhost:998",
"http://localhost:5173",
"http://127.0.0.1",
"http://127.0.0.1:998",
"http://127.0.0.1:5173",
"https://laundryweb.altafcreator.com"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
cursor.execute("""
CREATE TABLE IF NOT EXISTS timers (
timer_id INTEGER PRIMARY KEY,
user_id VARCHAR(64) NOT NULL,
start_time TEXT NOT NULL,
duration INT NOT NULL,
block INT NOT NULL,
machine INT NOT NULL,
status TEXT NOT NULL CHECK(status IN ('RUNNING', 'FINISHED')),
subscription_id TEXT NOT NULL
);""") # 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"h2-{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
machine_id: str
class InformationRequestData(BaseModel):
machine_id: str
class BlockRequestData(BaseModel):
block: int
class FinishRequestData(BaseModel):
id: int
class Status(Enum):
EMPTY = 0,
FINISHED = 1,
RUNNING = 2,
OUTOFSERVICE = 3,
URI_TO_MACHINES = {
"h0": [1, None],
"h1-dryer1": [1, 1],
"h1-washer1": [1, 2],
"h1-dryer2": [1, 3],
"h1-washer2": [1, 4],
"hf": [2, None],
"h2-dryer1": [2, 1],
"h2-washer1": [2, 2],
"h2-dryer2": [2, 3],
"h2-washer2": [2, 4],
}
# ## 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],
[None, None, None, None]]
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():
cursor.execute("SELECT * FROM timers;")
out = cursor.fetchall()
print("unfinished timers: " + str(len(out)))
for row in out:
print(row)
end_date = datetime.datetime.fromisoformat(row[2]) + datetime.timedelta(minutes=row[3])
now = datetime.datetime.now()
if now > end_date:
print("unfinished timer was long gone")
scheduler.add_job(final_timer_finished, 'date', run_date=(now + datetime.timedelta(seconds=1)), id=str(row[0]), args=[row[0]])
elif now + datetime.timedelta(minutes=5) > end_date:
print("unfinished timer ends in less than five mins")
scheduler.add_job(final_timer_finished, 'date', run_date=end_date, id=str(row[0]), args=[row[0]])
else:
print("unfinished timer scheduler started")
print(row[0])
scheduler.add_job(reminder_timer_finished, 'date', run_date=end_date, id=str(row[0]), args=[row[0]])
print("setting internal array information")
machine_status[row[4] - 1][row[5] - 1] = Status.RUNNING.name
machine_times[row[4] - 1][row[5] - 1] = row[2]
machine_durations[row[4] - 1][row[5] - 1] = row[3]
print(machine_status, machine_times, machine_durations)
def reminder_timer_finished(timer_id):
print("timer almost 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'})
try:
api_response = api_instance.create_notification(notification)
except Exception as e:
print(e)
def final_timer_finished(timer_id):
print("timer finished!1", 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'})
try:
api_response = api_instance.create_notification(notification)
except Exception as e:
print(e)
for row in out:
machine_status[row[4] - 1][row[5] - 1] = Status.FINISHED.name
def create_session(response: fastapi.Response):
cookie = secrets.token_hex(32)
response.set_cookie(key="session_key", value=cookie)
return cookie
def authenticate_block(response: fastapi.Response, machine_id: str = None, block: int = None):
if machine_id:
blk = URI_TO_MACHINES[qr_uri[machine_id]][0]
response.set_cookie(key="auth_block", value=blk)
return blk
elif block:
blk = block
response.set_cookie(key="auth_block", value=blk)
return block
else:
return "FAIL"
# ## beginning
print("Hello, world!")
restart_terminated_schedules()
# ## api endpoints
# --- starting new timer
# eugh. too complex. TODO: refactor perhaps
# it's so complex even the linter is complaining
@app.post("/start", response_class=PlainTextResponse)
def start_new_timer(data: RequestData, response: fastapi.Response, session_key: Annotated[str | None, fastapi.Cookie()] = None, auth_block: Annotated[str | None, fastapi.Cookie()] = None):
now = datetime.datetime.now()
try:
if not session_key:
print("no session key, creating.")
session_key = create_session(response)
except Exception as exception:
print("err @ key creation //", exception)
response.status_code = fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR
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"
if auth_block:
if str(auth_block) != str(block):
response.status_code = fastapi.status.HTTP_403_FORBIDDEN
return "mismatch in block authentication cookie and requested block machine. forbidden."
else:
authenticate_block(response, machine_id=data.machine_id)
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}, {block}, {machine}, 'RUNNING')
""")
conn.commit()
cursor.execute("SELECT * FROM timers;")
out = cursor.fetchall()
for row in out:
print(row)
end_date = now + datetime.timedelta(minutes=(data.duration * 30) - 5)
timer_id = str(out[len(out) - 1][0])
print("timer id", timer_id)
except Exception as exception:
print("err @ sql stuff //", exception)
response.status_code = fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR
return "something went wrong during sql stuff"
try:
scheduler.add_job(reminder_timer_finished, 'date', run_date=end_date, id=timer_id, args=[timer_id])
except Exception as exception:
print("err @ scheduler //", exception)
response.status_code = fastapi.status.HTTP_500_INTERNAL_SERVER_ERROR
return "something went wrong during scheduler stuff"
try:
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
return "something went wrong during machine_status setting somehow"
# HTTP 200
return "all good bro timer started"
# --- check whether user has laundry or not
@app.post("/check", response_class=PlainTextResponse)
def check_status(response: fastapi.Response, session_key: Annotated[str | None, fastapi.Cookie()] = None):
if not session_key:
print("no session key, creating.")
session_key = create_session(response)
cursor.execute(f"SELECT * FROM timers WHERE user_id = '{session_key}'")
out = cursor.fetchall()
for row in out:
print(row)
if len(out) > 0:
return "you got laundry"
else:
return "no got laundry"
# --- fetch machine status for block
@app.post("/status")
def get_machine_status(response: fastapi.Response, auth_block: Annotated[str | None, fastapi.Cookie()] = None):
if auth_block:
block = int(auth_block) - 1
return [machine_status[block], machine_times[block], machine_durations[block]]
else:
response.status_code = fastapi.status.HTTP_401_UNAUTHORIZED
return "block cookie needed. unauthorised"
# --- get laundr(y/ies) information of user
@app.post("/laundry")
def get_laundry_info(response: fastapi.Response, session_key: Annotated[str | None, fastapi.Cookie()] = None, auth_block: Annotated[str | None, fastapi.Cookie()] = None):
if session_key:
result = []
cursor.execute(f"SELECT * FROM timers WHERE user_id = '{session_key}'")
out = cursor.fetchall()
for row in out:
curr_timer = {
"duration": 0,
"start_time": 0,
"machine": 0,
"status": "RUNNING",
"id": -1,
}
curr_timer["duration"] = row[3]
curr_timer["start_time"] = row[2]
curr_timer["machine"] = row[5]
curr_timer["status"] = row[6]
curr_timer["id"] = row[0]
result.append(curr_timer)
return result
else:
response.status_code = fastapi.status.HTTP_401_UNAUTHORIZED
return "you got no session key cookie how am i supposed to identify you"
# --- finish one's laundry
@app.post("/finish", response_class=PlainTextResponse)
def finish_laundry(data: FinishRequestData, response: fastapi.Response, session_key: Annotated[str | None, fastapi.Cookie()] = None):
if session_key:
cursor.execute(f"SELECT * FROM timers WHERE timer_id = '{data.id}'")
row = cursor.fetchall()[0]
machine_status[row[4] - 1][row[5] - 1] = Status.EMPTY.name
machine_times[row[4] - 1][row[5] - 1] = None
machine_durations[row[4] - 1][row[5] - 1] = None
cursor.execute(f"DELETE FROM timers WHERE timer_id = {row[0]}")
conn.commit()
print(f"timer of id {data.id} has been finished by {session_key}")
return "laundry finished"
if session_key != row[1]:
response.status_code = fastapi.status.HTTP_403_FORBIDDEN
return "session key mismatch with timer id, dubious!"
else:
response.status_code = fastapi.status.HTTP_401_UNAUTHORIZED
return "you got no session key, cannot"
# --- get information from uri search query
@app.post("/info")
def uri_to_information(data: InformationRequestData, response: fastapi.Response, auth_block: Annotated[str | None, fastapi.Cookie()] = None):
info = None
try:
if len(data.machine_id) > 0:
info = URI_TO_MACHINES[data.machine_id]
except KeyError:
response.status_code = fastapi.status.HTTP_404_NOT_FOUND
return "INVALID machine ID/URI"
print(auth_block)
if auth_block:
if info:
if str(auth_block) != str(info[0]):
response.status_code = fastapi.status.HTTP_403_FORBIDDEN
return "UNAUTHORISED to view information of block " + str(info[0])
else:
info = [auth_block, None]
else:
if info:
authenticate_block(response, block=info[0])
else:
response.status_code = fastapi.status.HTTP_401_UNAUTHORIZED
return "NO INFORMATION PROVIDED. NO AUTH COOKIE."
return {"block": info[0], "machine": info[1]}
|