utils.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. from datetime import datetime, timedelta
  2. from kddit.settings import HEADERS, TIMESHIFT, YDL_OPTS, CLIENT_ID, CLIENT_SECRET, URL, UA
  3. from kddit.settings import SUBREDDIT_OPTIONS, SAFE_SUBS, USER_OPTIONS
  4. import timeago
  5. import re
  6. import requests
  7. import youtube_dl
  8. from glom import glom as g
  9. from glom import Coalesce
  10. from bs4 import BeautifulSoup
  11. from html import unescape
  12. from bottle import request, abort
  13. import requests.auth
  14. ydl = youtube_dl.YoutubeDL(YDL_OPTS)
  15. def get_query():
  16. return dict(request.query)
  17. def human_format(num):
  18. num = float('{:.3g}'.format(num))
  19. magnitude = 0
  20. while abs(num) >= 1000:
  21. magnitude += 1
  22. num /= 1000.0
  23. return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'T'][magnitude])
  24. def get_time(timestamp):
  25. date = datetime.fromtimestamp(
  26. timestamp) - timedelta(hours=TIMESHIFT)
  27. now = datetime.now()
  28. return timeago.format(date, now)
  29. def get_thumbnail(url):
  30. try:
  31. with ydl:
  32. info = ydl.extract_info(url, download=False)
  33. return info["thumbnail"]
  34. except:
  35. return ""
  36. def replace_tag(bs_tag, html_tag):
  37. tag = html_tag[0] if isinstance(html_tag, tuple) else html_tag
  38. soup = BeautifulSoup(tag.render(), "html.parser")
  39. bs_tag.replace_with(soup)
  40. def get_metadata(data, name):
  41. output = g(data, Coalesce(f"media_metadata.{name}.s.u", f"media_metadata.{name}.s.gif"), default=None)
  42. return unescape(output) if output else None
  43. external_preview_re = re.compile("https://external-preview.redd.it/")
  44. preview_re = re.compile("https://preview.redd.it/")
  45. processing_re = re.compile("Processing img (.*)...")
  46. video_re = re.compile("https://reddit.com/link/.*/video/(.*)/player")
  47. def get_token():
  48. client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
  49. post_data = {"grant_type": "client_credentials"}
  50. response = requests.post("https://www.reddit.com/api/v1/access_token",
  51. auth=client_auth,
  52. data=post_data)
  53. if (response.status_code == 200):
  54. token_json = response.json()
  55. return token_json.get("access_token")
  56. return None
  57. def req_url(url, params=None):
  58. r = requests.get(url, params=params, headers={"User-Agent": UA})
  59. return r
  60. def req(path, params=None):
  61. r = requests.get(URL+path, params=params, headers=HEADERS)
  62. if (r.status_code == 401 or r.status_code == 403) and CLIENT_SECRET and CLIENT_ID:
  63. if token := get_token():
  64. HEADERS.update({"Authorization": "bearer "+token})
  65. r = requests.get(URL+path, params=params, headers=HEADERS)
  66. return r
  67. def success(r):
  68. return r.status_code == 200
  69. def builder(*args):
  70. obj = ()
  71. args = list(args)
  72. last = args.pop()
  73. args.reverse()
  74. for arg in args:
  75. if obj:
  76. obj = (arg(obj),)
  77. else:
  78. obj = (arg(last),)
  79. return obj
  80. def tuplefy(func):
  81. def inner(*args, **kwargs):
  82. result = func(*args, **kwargs)
  83. return (result,)
  84. return inner
  85. def get_subreddit_url():
  86. sub = request.url_args.get("subreddit")
  87. return f"/r/{sub}" if sub else ""
  88. def get_subreddit():
  89. sub = request.url_args.get("subreddit")
  90. return f"r/{sub}" if sub else ""
  91. def get_option():
  92. option = request.url_args.get("option")
  93. return option
  94. def verify_subreddit_option():
  95. option = get_option()
  96. if option and option not in SUBREDDIT_OPTIONS:
  97. return abort(404)
  98. def verify_user_option():
  99. option = get_option()
  100. if option and option not in USER_OPTIONS:
  101. return abort(404)
  102. def nsfw_mode(subreddit):
  103. return not subreddit or subreddit in SAFE_SUBS