-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
268 lines (233 loc) · 8.28 KB
/
main.py
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
import os
from datetime import datetime
import json
from uuid import uuid1
from fastapi import FastAPI, Depends, Response
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
from fastapi.middleware.cors import CORSMiddleware
from uvicorn.config import LOGGING_CONFIG
from requests import get
from dateutil.parser import parse
from sqlalchemy.exc import IntegrityError
from sqlmodel import Session
from contextlib import asynccontextmanager
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from db import get_session, Database
from models.forminputmodel import FormInputModel
from models.responsemodel import ResponseModel, PodcastResponseModel
from models.updatemodel import FormUpdateModel
from models.customerror import Detail
from models.custompodcast import CustomPodcastUpdate
from custom_exceptions.no_podcast import NoPodcastException
from utils.xml_reader import createPodcast, extractContents, isValidXML, extractTitleFromRoot
from utils.util import dateListRRule
from cronjob import updateFeeds
DEBUG = os.getenv("DEBUG") == "True"
ENVIRONEMENT_URL = "localhost:8000" if DEBUG else "podshift.net:8080"
LOGGING_CONFIG["formatters"]["access"]["fmt"] = (
"%(asctime)s " + LOGGING_CONFIG["formatters"]["access"]["fmt"]
)
scheduler = BackgroundScheduler()
trigger = (
IntervalTrigger(minutes=10, start_date=datetime.now())
if DEBUG
else IntervalTrigger(hours=2, start_date=datetime.now())
)
scheduler.add_job(updateFeeds, trigger)
scheduler.start()
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
scheduler.shutdown()
docs_url = "/docs" if DEBUG else None
app = FastAPI(title="PodShiftAPI", lifespan=lifespan, docs_url=docs_url)
db = Database()
app.add_middleware(
CORSMiddleware,
allow_origins={"*"},
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.post(
"/PodShift",
response_model=ResponseModel,
responses={400: {"model": Detail}, 409: {
"model": Detail}, 500: {"model": Detail}},
)
async def addFeed(form: FormInputModel, session: Session = Depends(get_session)):
try:
url = get(form.url)
except:
return JSONResponse(
status_code=400, content={"detail": "The given URL isnt valid"}
)
try:
podcastContent = url.content.decode()
isValidXML(podcastContent)
except:
return JSONResponse(
status_code=400,
content={"detail": "The url content wasnt an XML containing RSS"},
)
podcastXML, episodesXMLList = extractContents(podcastContent)
title = extractTitleFromRoot(podcastXML)
try:
podcast = db.createNewPodcast(
podcastXML=podcastXML,
podcastUrl=form.url,
episodeListXML=episodesXMLList,
title=title,
session=session,
)
except IntegrityError as e:
db.rollback(session)
if "UNIQUE" in e.args[0]:
podcast = db.getPodcastXML(podcastXML, session)
else:
return JSONResponse(status_code=409, content={"detail": f"{e.detail}"})
except Exception as e:
return JSONResponse(status_code=500, content={"detail": str(e)})
listDate = dateListRRule(
freq=form.recurrence,
date=datetime.date(datetime.now()),
interval=form.everyX,
nbEpisodes=len(episodesXMLList),
amount=form.amountOfEpisode,
)
jsonDumps = json.dumps(listDate)
uuid = str(uuid1())
customPodcast = db.createCustomPodcast(
jsonDumpDate=jsonDumps,
interval=form.everyX,
freq=form.recurrence,
podcast=podcast,
amount=form.amountOfEpisode,
uuid=uuid,
session=session,
)
return JSONResponse(
content=jsonable_encoder(
ResponseModel(
custom_url=f"http://{ENVIRONEMENT_URL}/PodShift/{customPodcast.UUID}",
url=customPodcast.podcast.url,
UUID=customPodcast.UUID,
title=customPodcast.podcast.title,
frequence=customPodcast.freq,
interval=customPodcast.interval,
amount=customPodcast.amount
)
)
)
@app.get(
"/PodShift/{customPodcastGUID}",
response_class=Response,
responses={200: {"content": {"application/xml": {}}},
404: {"model": Detail}},
)
async def getCustomFeed(customPodcastGUID, session: Session = Depends(get_session)):
customFeed = db.getCustomPodcast(customPodcastGUID, session)
if customFeed is None:
return JSONResponse(status_code=404, content={"detail": "No podcast found"})
content = createPodcast(
podcastContent=customFeed.podcast.xml,
parsedDates=[parse(d) for d in json.loads(customFeed.dateToPostAt)],
amount=customFeed.amount,
listEpisodes=[ep.xml for ep in customFeed.podcast.episodes],
)
return Response(content=content, media_type="application/xml")
@app.put(
"/PodShift/{customPodcastGUID}",
response_model=PodcastResponseModel,
responses={
200: {"content": {}},
404: {"model": Detail},
500: {"model": Detail},
},
)
async def updateCustomFeed(
customPodcastGUID,
updateModel: FormUpdateModel,
session: Session = Depends(get_session),
):
try:
customFeed = db.getCustomPodcast(customPodcastGUID, session)
if customFeed is None:
raise NoPodcastException
newDates = dateListRRule(
freq=updateModel.recurrence,
date=datetime.date(datetime.now()),
interval=updateModel.everyX,
nbEpisodes=len(customFeed.podcast.episodes) -
updateModel.currentEpisode,
amount=updateModel.amountOfEpisode,
)
podcastToUpdate = CustomPodcastUpdate(
podcast_id=customFeed.podcast_id,
dateToPostAt=json.dumps(newDates),
amount=updateModel.amountOfEpisode,
freq=updateModel.recurrence,
interval=updateModel.everyX,
)
customPodcast = db.updateCustomPodcast(
podcastUUID=customPodcastGUID,
updateCustomPodcast=podcastToUpdate,
session=session,
)
if customPodcast is None:
raise NoPodcastException
response = PodcastResponseModel(
UUID=customPodcast.UUID,
freq=customPodcast.freq,
interval=customPodcast.interval,
url=customFeed.podcast.url,
title=customFeed.podcast.title,
amount=customPodcast.amount,
)
return JSONResponse(content=jsonable_encoder(response))
except NoPodcastException:
return JSONResponse(
status_code=404, content={"detail": "The requested podcast was not found"}
)
except Exception as e:
return JSONResponse(status_code=500, content={"detail": str(e)})
@app.delete(
"/PodShift/{customPodcastGUID}",
responses={200: {}, 404: {"model": Detail}, 500: {"model": Detail}},
)
async def deleteCustomPodcast(
customPodcastGUID: str, session: Session = Depends(get_session)
):
try:
db.deleteCustomPodcast(customPodcastGUID, session=session)
except NoPodcastException:
return JSONResponse(
status_code=404, content={"detail": "The requested podcast was not found"}
)
except Exception as e:
return JSONResponse(status_code=500, content={"detail": str(e)})
@app.get(
"/PodShift/{customPodcastGUID}/content",
responses={200: {"model": PodcastResponseModel},
404: {"model": Detail}, 500: {"model": Detail}},
)
async def GetCustomPodcastContent(
customPodcastGUID: str, session: Session = Depends(get_session)
):
customPodcast = db.getCustomPodcast(
customPodcastGUID=customPodcastGUID, session=session)
if customPodcast is None:
return JSONResponse(
status_code=404, content={"detail": "The requested podcast was not found"}
)
response = PodcastResponseModel(
UUID=customPodcast.UUID,
freq=customPodcast.freq,
interval=customPodcast.interval,
amount=customPodcast.amount,
url=customPodcast.podcast.url,
title=customPodcast.podcast.title,
)
return JSONResponse(content=jsonable_encoder(response))