-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
384 lines (327 loc) · 10.7 KB
/
main.py
File metadata and controls
384 lines (327 loc) · 10.7 KB
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
import datetime
import multiprocessing
import sys
from fastapi import FastAPI, Depends, HTTPException, Request, Response
import os
import uvicorn
from pydantic import BaseModel
from typing import List, Optional
import aiohttp
from typing import Annotated, Tuple
import asyncio
import threading
import time
from fastapi.middleware.cors import CORSMiddleware
from cron_consumer import refresh_data
from item_to_mp3 import item_to_mp3
from utils import generate_auth_token, generate_content_uid, link_to_md, get_all_from_link
from models import Item, ReadingItemData, Source, User, engine
from sqlalchemy import desc, orm, select
from utils import detect_source_type, link_to_md
import os
import markdownify
async def auth(req: Request):
auth_token = req.headers.get("auth_token", None)
with orm.Session(engine) as session:
if auth_token is None:
raise HTTPException(status_code=401, detail="No auth provided")
if os.environ.get("GLOBAL_AUTH_TOKEN") == auth_token:
return None, True
user = (
session.execute(select(User).where(User.auth_token == auth_token))
.scalars()
.first()
)
if user is None:
raise HTTPException(status_code=401, detail="Unauthorized")
return user.email, user.is_admin
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:5173",
"https://read-nine.vercel.app",
"https://reader.withmeaning.io",
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/get_items")
async def get_items(auth_data: Annotated[tuple[str], Depends(auth)]):
with orm.Session(engine) as session:
reading_item_Data = (
session.execute(
select(ReadingItemData)
.where(
ReadingItemData.user_email == auth_data[0],
ReadingItemData.archived == False,
ReadingItemData.item.has(Item.type.in_(["read", "do"])),
)
.order_by(desc(ReadingItemData.item_order))
)
.scalars()
.all()
)
items = [x.item for x in reading_item_Data]
return {"items": [x.to_dict() for x in items]}
class AddItemBody(BaseModel):
title: Optional[str]
content: Optional[str]
link: str
type: str
author: Optional[str]
@app.post("/add_item")
async def add_item(body: AddItemBody, auth_data: Annotated[tuple[str], Depends(auth)]):
if not body.content and not body.title:
response = get_all_from_link(body.link)
body.title = response["title"]
body.author = response["siteName"]
html = response["html"]
md = markdownify.markdownify(html, heading_style="ATX")
body.content = md
uid = generate_content_uid(
[body.title or "", body.content, body.type, auth_data[0], body.link]
)
uiuid = generate_content_uid([body.title or "", body.content, body.type, body.link])
with orm.Session(engine) as session:
session.add(
Item(
uid=uid,
uiuid=uiuid,
title=body.title,
content=body.content,
link=body.link,
user_email=auth_data[0],
type=body.type,
author=body.author,
)
)
if body.type == "read":
session.add(
ReadingItemData(
item_uid=uid,
item_order=None,
archived=False,
user_email=auth_data[0],
done=False,
)
)
if body.type == "do":
session.add(
ReadingItemData(
item_uid=uid,
item_order=None,
archived=False,
done=False,
user_email=auth_data[0],
)
)
session.commit()
return Item(
uid=uid,
uiuid=uiuid,
title=body.title,
content=body.content,
link=body.link,
user_email=auth_data[0],
type=body.type,
author=body.author,
created_at=datetime.datetime.now(),
)
class CreateUserBody(BaseModel):
email: str
is_admin: bool
@app.post("/create_user")
async def create_user(
body: CreateUserBody, auth_data: Annotated[tuple[str], Depends(auth)]
):
with orm.Session(engine) as session:
new_user_auth_token = generate_auth_token()
if auth_data[1]:
session.add(
User(
email=body.email,
auth_token=new_user_auth_token,
is_admin=body.is_admin,
)
)
session.commit()
return {"email": body.email, "auth_token": new_user_auth_token}
class ArchiveItemBody(BaseModel):
archived: bool
uid: str
@app.post("/archive")
async def archive(
body: ArchiveItemBody, auth_data: Annotated[tuple[str], Depends(auth)]
):
with orm.Session(engine) as session:
reading_item_data = (
session.execute(
select(ReadingItemData).where(
ReadingItemData.item_uid == body.uid,
ReadingItemData.user_email == auth_data[0],
)
)
.scalars()
.first()
)
reading_item_data.archived = body.archived
session.commit()
return {}
class DoneItemBody(BaseModel):
done: bool
uid: str
@app.post("/done")
async def done(body: DoneItemBody, auth_data: Annotated[tuple[str], Depends(auth)]):
with orm.Session(engine) as session:
reading_item_data = (
session.execute(
select(ReadingItemData).where(
ReadingItemData.item_uid == body.uid,
ReadingItemData.user_email == auth_data[0],
)
)
.scalars()
.first()
)
reading_item_data.done = body.done
session.commit()
return {}
class OrderItemBody(BaseModel):
order: int
uid: str
class Order(BaseModel):
items: List[OrderItemBody]
@app.post("/order")
async def order(body: Order, auth_data: Annotated[tuple[str], Depends(auth)]):
print(body)
for item in body.items:
with orm.Session(engine) as session:
reading_item_data = (
session.execute(
select(ReadingItemData).where(
ReadingItemData.item_uid == item.uid,
ReadingItemData.user_email == auth_data[0],
)
)
.scalars()
.first()
)
reading_item_data.item_order = item.order
session.commit()
return {}
class AddSourceBody(BaseModel):
source: str
@app.post("/add_source")
async def add_source(
data: AddSourceBody, auth_data: Annotated[tuple[str], Depends(auth)]
):
source_type = detect_source_type(data.source)
source_uid = generate_content_uid([data.source, source_type, auth_data[0]])
with orm.Session(engine) as session:
session.add(
Source(
uid=source_uid,
source=data.source,
type=source_type,
user_email=auth_data[0],
)
)
session.commit()
return {"status": "ok"}
class DeleteSourceBody(BaseModel):
source: str
@app.post("/delete_source")
async def delete_source(
data: DeleteSourceBody, auth_data: Annotated[tuple[str], Depends(auth)]
):
with orm.Session(engine) as session:
source = (
session.execute(
select(Source).where(
Source.source == data.source, Source.user_email == auth_data[0]
)
)
.scalars()
.first()
)
source.delete()
session.commit()
return {"status": "ok"}
@app.get("/get_sources")
async def get_sources(auth_data: Annotated[tuple[str], Depends(auth)]):
with orm.Session(engine) as session:
sources = (
session.execute(select(Source).where(Source.user_email == auth_data[0]))
.scalars()
.all()
)
return {"sources": [x.to_dict() for x in sources]}
@app.get("/get_feed/{user_email}")
async def get_feed(user_email: str):
# Rules based on which the user recommends stuff to other people @TODO (this endpoint can accept an optional email, so the user can recommend to specific individuals(?))
with orm.Session(engine) as session:
resonance_items = (
session.execute(
select(Item).where(
Item.user_email == user_email, Item.type == "resonance"
)
)
.scalars()
.all()
)
send_item_uids = []
for resonance_item in resonance_items:
if int(resonance_item.content) > 80:
send_item_uids.append(resonance_item.link)
reading_items = (
session.execute(select(Item).where(Item.uid.in_(send_item_uids)))
.scalars()
.all()
)
resp = [{"read": x.to_dict(), "reasons": [{}]} for x in reading_items]
return resp
@app.get("/get_mp3/{uid}")
async def get_mp3(uid: str, auth_data: Annotated[tuple[str], Depends(auth)]):
with orm.Session(engine) as session:
item = (
session.execute(
select(Item).where(Item.uid == uid, Item.user_email == auth_data[0])
)
.scalar()
.item()
)
mp3 = item_to_mp3(item.content, item.uiuid)
headers = {
"content-type": "audio/mpeg",
"content-disposition": "attachment; filename=data.mp3",
}
return Response(content=mp3, headers=headers)
@app.get("/auth_session")
async def auth_session(auth_data: Annotated[tuple[str], Depends(auth)]):
return True
@app.get("/ping")
async def ping():
return "Pong"
@app.on_event("startup")
async def startup():
pass
if __name__ == "__main__":
p = multiprocessing.Process(target=refresh_data)
p.start()
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
try:
if os.environ.get("SPILE_ENV", "development") == "production":
uvicorn.run("main:app", port=port, host="0.0.0.0", workers=4)
else:
uvicorn.run("main:app", port=port, host="0.0.0.0", reload=True)
except KeyboardInterrupt:
print("Stopping server...")
finally:
# Ensure the background process is terminated when the server is stopped
p.terminate()
p.join()