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 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. REPORT_HORIZON = 180
  18. MAX_USER_REPORTS_PER_DAY = 3
  19. ################################
  20. # Core configuration
  21. ################################
  22. app = fastapi.FastAPI(docs_url=None)
  23. origins = [
  24. 'https://prograde.gg',
  25. 'http://localhost',
  26. 'http://localhost:5000',
  27. 'http://localhost:8080',
  28. 'http://localhost:8000'
  29. ]
  30. app.add_middleware(
  31. CORSMiddleware,
  32. allow_origins=origins,
  33. allow_credentials=True,
  34. allow_methods=['*'],
  35. allow_headers=['*']
  36. )
  37. app.mount('/static', StaticFiles(directory='static'), name='static')
  38. tmplts = Jinja2Templates(directory='templates') # TODO Get the path correctly.
  39. ################################
  40. # User-facing endpoints
  41. ################################
  42. @app.exception_handler(Exception)
  43. async def handle_exception(req: Request, exc: Exception):
  44. tb = traceback.format_exc()
  45. await reporthook.send_report(tb)
  46. return PlainTextResponse('error', status_code=500)
  47. @app.get('/')
  48. async def render_main(req: Request):
  49. raw_articles = await load_recent_articles()
  50. converted = convert_days_from_articles(raw_articles)
  51. num_days = calc_num_days(converted)
  52. p = {
  53. 'sb': {
  54. 'num_days': num_days,
  55. 'days': converted
  56. },
  57. 'notices': [
  58. {
  59. 'style': 'primary',
  60. 'text': 'There were so many incidents in August 2021 that news sites stopped reporting on it, so there\'s some missing data here.',
  61. }
  62. ],
  63. 'request': req,
  64. }
  65. return tmplts.TemplateResponse('main.htm', p)
  66. @app.post('/action/flag')
  67. async def handle_flag(req: Request, date: str = Form(...), article: str = Form(...)):
  68. ipaddr = req.client.host
  69. try:
  70. today = datetime.now()
  71. pdate = datetime.strptime(date, inventory.DATE_FORMAT)
  72. if pdate > today or (today - pdate).days > REPORT_HORIZON:
  73. raise ValueError('bad date')
  74. except Exception as e:
  75. return JSONResponse({'status': 'error'}, status_code=400)
  76. flags = await inventory.load_date_flags_async(pdate)
  77. # Make sure it's not a duplicate and limit the number of reports
  78. nreporter = 0
  79. for e in flags:
  80. if e['src'] == ipaddr:
  81. if e['url'] == article:
  82. return {'status': 'OK'}
  83. nreporter += 1
  84. if nreporter + 1 >= MAX_USER_REPORTS_PER_DAY:
  85. print('user', ipaddr, 'looking sussy')
  86. await reporthook.send_report('address %s made more reports for %s than allowed' % (ipaddr, date))
  87. return JSONResponse({'status': 'error'}, status_code=429)
  88. await reporthook.send_report('address %s reported url %s' % (ipaddr, article))
  89. flags.append({
  90. 'src': ipaddr,
  91. 'url': article,
  92. })
  93. await inventory.save_date_flags_async(pdate, flags)
  94. return make_html_redirect_response('/')
  95. ################################
  96. # API endpoints
  97. ################################
  98. @app.post('/api/addarticle')
  99. async def handle_addarticle(req: Request):
  100. if not check_admin_token(req):
  101. return JSONResponse(status_code=403, content={'error': 'forbidden'})
  102. body = await req.json()
  103. await add_article(body['date'], body['desc'])
  104. return {'status': 'OK'}
  105. async def add_article(datestr, adesc):
  106. date = datetime.strptime(datestr, inventory.DATE_FORMAT)
  107. articles = await inventory.load_date_report_async(date)
  108. articles.append(adesc)
  109. await inventory.save_date_report_async(date, articles)
  110. ################################
  111. # Utilities
  112. ################################
  113. def check_admin_token(req: Request):
  114. ak = sbenv.get_admin_key()
  115. if ak is None:
  116. raise RuntimeError('checked api endpoint without key loaded')
  117. if ak == 'UNSAFE_TESTING':
  118. return True
  119. if 'Authorization' in req.headers:
  120. auth = req.headers['Authorization']
  121. if not auth.startswith('Bearer '):
  122. return False
  123. tok = auth[len('Bearer '):]
  124. return tok == sbenv.get_admin_key()
  125. else:
  126. return False
  127. async def load_days_from_file(path):
  128. async with aiofiles.open(path, mode='r') as f:
  129. contents = await f.read()
  130. return json.loads(contents)
  131. async def load_recent_articles():
  132. today = datetime.now()
  133. day_dur = timedelta(days=1)
  134. reports = {}
  135. for i in range(MAX_SEARCH_DAYS):
  136. that_day = today - i * day_dur
  137. report = await inventory.load_date_report_async(that_day)
  138. flags = await inventory.load_date_flags_async(that_day)
  139. if len(report) > 0:
  140. reports[that_day.strftime(inventory.DATE_FORMAT)] = {
  141. 'articles': report,
  142. 'flags': flags,
  143. }
  144. return reports
  145. def convert_days_from_articles(days):
  146. output = []
  147. for dstr, parts in days.items():
  148. dr = searchlib.process_day_results(dstr, parts['articles'])
  149. flags = {e['url'] for e in parts['flags']}
  150. day = {
  151. 'date': dstr,
  152. 'links': [],
  153. 'maybe_links': []
  154. }
  155. # Process hard passes.
  156. for a in dr['pass']:
  157. ca = convert_article(a)
  158. if a['url'] not in flags:
  159. day['links'].append(ca)
  160. else:
  161. day['maybe_links'].append(ca)
  162. # Process weak articles.
  163. for a in dr['maybe']:
  164. ca = convert_article(a)
  165. if a['url'] not in flags:
  166. day['maybe_links'].append(ca)
  167. if len(day['links']) > 0:
  168. output.append(day)
  169. if len(output) > MAX_SHOW_DAYS:
  170. break
  171. return output
  172. def convert_article(a):
  173. return {
  174. 'url': a['url'],
  175. 'title': a['gtitle'],
  176. 'slug': a['slug'],
  177. }
  178. def calc_num_days(dayslist):
  179. today = datetime.now()
  180. lowest = -1
  181. for d in dayslist:
  182. pd = datetime.strptime(d['date'], inventory.DATE_FORMAT)
  183. diff = today - pd
  184. ndays = diff.days
  185. if ndays < lowest or lowest == -1:
  186. lowest = ndays
  187. return lowest
  188. def make_html_redirect_response(url):
  189. return HTMLResponse('<head><meta http-equiv="Refresh" content="0; URL=' + url + '"></head>')