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
|
import fastapi
from fastapi.middleware.cors import CORSMiddleware
import sqlite3
from typing import Annotated
import datetime
from pydantic import BaseModel
from apscheduler.schedulers.background import BackgroundScheduler
import secrets
from enum import Enum
from fastapi.responses import PlainTextResponse
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'))
);
""") # block is either 1 or 2, machine (1-4), odd is dryer, even is machine.
class RequestData(BaseModel):
duration: int
block: int
machine: int
class BlockRequestData(BaseModel):
block: int
class Status(Enum):
EMPTY = 0,
FINISHED = 1,
RUNNING = 2,
OUTOFSERVICE = 3,
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]]
def reminder_timer_finished(timer_id):
print("timer almost finished", timer_id)
end_date = datetime.datetime.now() + datetime.timedelta(seconds=5)
scheduler.add_job(final_timer_finished, 'date', run_date=end_date, id=timer_id, args=[timer_id])
cursor.execute(f"SELECT * FROM timers WHERE timer_id = '{timer_id}'")
out = cursor.fetchall()
for row in out:
machine_status[row[3] - 1][row[4] - 1] = Status.FINISHED.name
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()
for row in out:
machine_status[row[3] - 1][row[4] - 1] = Status.EMPTY.name
machine_times[row[3] - 1][row[4] - 1] = None
machine_durations[row[3] - 1][row[4] - 1] = None
cursor.execute(f"DELETE FROM timers WHERE timer_id = {timer_id}")
conn.commit()
def create_session(response: fastapi.Response):
cookie = secrets.token_hex(32)
response.set_cookie(key="session_key", value=cookie)
return cookie
# --- 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):
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)
return "something went wrong during session key creation"
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.block}, {data.machine}, {data.duration * 30}, '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)
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)
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
except Exception as exception:
print("err @ machine_status //", exception)
return "something went wrong during machine_status setting somehow"
return "all good bro timer started"
# --- check whether user has laundry or not
@app.post("/check", response_class=PlainTextResponse)
def check_status(session_key: Annotated[str | None, fastapi.Cookie()] = None):
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(data: BlockRequestData):
block_idx = data.block - 1
return [machine_status[block_idx], machine_times[block_idx], machine_durations[block_idx]]
# --- get laundr(y/ies) information of user
@app.post("/laundry")
def get_laundry_info(session_key: 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",
}
curr_timer["duration"] = row[5]
curr_timer["start_time"] = row[2]
curr_timer["machine"] = row[4]
curr_timer["status"] = row[6]
result.append(curr_timer)
return result
else:
return "you got no session key cookie how am i supposed to identify you"
|