You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.py 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. from datetime import datetime, timedelta
  2. import json
  3. import traceback
  4. import aiofiles
  5. import fastapi
  6. from fastapi import Cookie, File, Form, Request, UploadFile, WebSocket, WebSocketDisconnect
  7. from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, PlainTextResponse
  8. from fastapi.staticfiles import StaticFiles
  9. from fastapi.templating import Jinja2Templates
  10. from fastapi.middleware.cors import CORSMiddleware
  11. import reporthook
  12. import inventory
  13. import sbenv
  14. import searchlib
  15. MAX_SEARCH_DAYS = 180
  16. MAX_SHOW_DAYS = 20
  17. ################################
  18. # Core configuration
  19. ################################
  20. app = fastapi.FastAPI(docs_url=None)
  21. origins = [
  22. 'https://prograde.gg',
  23. 'http://localhost',
  24. 'http://localhost:5000',
  25. 'http://localhost:8080',
  26. 'http://localhost:8000'
  27. ]
  28. app.add_middleware(
  29. CORSMiddleware,
  30. allow_origins=origins,
  31. allow_credentials=True,
  32. allow_methods=['*'],
  33. allow_headers=['*']
  34. )
  35. app.mount('/static', StaticFiles(directory='static'), name='static')
  36. tmplts = Jinja2Templates(directory='templates') # TODO Get the path correctly.
  37. ################################
  38. # User-facing endpoints
  39. ################################
  40. @app.exception_handler(Exception)
  41. async def handle_exception(req: Request, exc: Exception):
  42. tb = traceback.format_exc()
  43. await reporthook.send_report(tb)
  44. return PlainTextResponse('error', status_code=500)
  45. @app.get('/')
  46. async def render_main(req: Request):
  47. raw_articles = await load_recent_articles()
  48. converted = convert_days_from_articles(raw_articles)
  49. num_days = calc_num_days(converted)
  50. p = {
  51. 'sb': {
  52. 'num_days': num_days,
  53. 'days': converted
  54. },
  55. 'request': req,
  56. }
  57. return tmplts.TemplateResponse('main.htm', p)
  58. ################################
  59. # API endpoints
  60. ################################
  61. @app.post('/api/addarticle')
  62. async def handle_addarticle(req: Request):
  63. if not check_admin_token(req):
  64. return JSONResponse(status_code=403, content={'error': 'forbidden'})
  65. body = await req.json()
  66. await add_article(body['date'], body['desc'])
  67. return {'status': 'OK'}
  68. async def add_article(datestr, adesc):
  69. date = datetime.strptime(datestr, inventory.DATE_FORMAT)
  70. articles = await inventory.load_date_report_async(date)
  71. articles.append(adesc)
  72. await inventory.save_date_report_async(date, articles)
  73. ################################
  74. # Utilities
  75. ################################
  76. def check_admin_token(req: Request):
  77. ak = sbenv.get_admin_key()
  78. if ak is None:
  79. raise RuntimeError('checked api endpoint without key loaded')
  80. if ak == 'UNSAFE_TESTING':
  81. return True
  82. if 'Authorization' in req.headers:
  83. auth = req.headers['Authorization']
  84. if not auth.startswith('Bearer '):
  85. return False
  86. tok = auth[len('Bearer '):]
  87. return tok == sbenv.get_admin_key()
  88. else:
  89. return False
  90. async def load_days_from_file(path):
  91. async with aiofiles.open(path, mode='r') as f:
  92. contents = await f.read()
  93. return json.loads(contents)
  94. async def load_recent_articles():
  95. today = datetime.now()
  96. day_dur = timedelta(days=1)
  97. reports = {}
  98. for i in range(MAX_SEARCH_DAYS):
  99. that_day = today - i * day_dur
  100. report = await inventory.load_date_report_async(that_day)
  101. if len(report) > 0:
  102. reports[that_day.strftime(inventory.DATE_FORMAT)] = report
  103. return reports
  104. def convert_days_from_articles(rarts):
  105. processed = searchlib.process_results(rarts)
  106. output = []
  107. for dstr, arts in processed.items():
  108. day = {
  109. 'date': dstr,
  110. 'links': [convert_article(a) for a in arts['pass']],
  111. 'maybe_links': [convert_article(a) for a in arts['maybe']]
  112. }
  113. if len(day['links']) > 0:
  114. output.append(day)
  115. if len(output) > MAX_SHOW_DAYS:
  116. break
  117. return output
  118. def convert_article(a):
  119. return {
  120. 'url': a['url'],
  121. 'title': a['gtitle'],
  122. 'slug': a['slug'],
  123. }
  124. def calc_num_days(dayslist):
  125. today = datetime.now()
  126. lowest = -1
  127. for d in dayslist:
  128. pd = datetime.strptime(d['date'], inventory.DATE_FORMAT)
  129. diff = today - pd
  130. ndays = diff.days
  131. if ndays < lowest or lowest == -1:
  132. lowest = ndays
  133. return lowest