This project provides a badge for sharing your current book in your github profile.
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.

67 lines
1.9 KiB

4 years ago
4 years ago
4 years ago
  1. from flask import Flask, Response, jsonify, render_template
  2. from base64 import b64encode
  3. import feedparser
  4. import re
  5. from dotenv import load_dotenv, find_dotenv
  6. load_dotenv(find_dotenv())
  7. import requests
  8. import json
  9. import os
  10. import random
  11. GOODREADS_RSS_URL = os.getenv("GOODREADS_RSS_URL")
  12. PROGRESS_REGEX = r".*<img .* alt=\"([^\"]*) by ([^\"]*)\".*src=\"([^\"]*)\".*.* is on page ([0-9]*) of ([0-9]*) of <a.*"
  13. READ_REGEX = r".*<img .* alt=\"([^\"]*) by ([^\"]*)\".*src=\"([^\"]*)\".*"
  14. def loadImageB64(url):
  15. resposne = requests.get(url)
  16. return b64encode(resposne.content).decode("ascii")
  17. def makeSVG(book, author, progress, img_url):
  18. img = loadImageB64(img_url)
  19. dataDict = {
  20. "progress": progress,
  21. "author": author,
  22. "book_name": book,
  23. "img": img,
  24. }
  25. return render_template("goodreads.html.j2", **dataDict)
  26. app = Flask(__name__)
  27. @app.route("/", defaults={"path": ""})
  28. @app.route("/<path:path>")
  29. def last_activity(path):
  30. activityFeed = feedparser.parse(GOODREADS_RSS_URL)
  31. data = ""
  32. entries = activityFeed.entries
  33. pr = re.compile(PROGRESS_REGEX)
  34. rr = re.compile(READ_REGEX)
  35. for i in entries:
  36. i["summary"] = i["summary"].replace("&lt;","<").replace("&gt;",">").replace("&quot;","\"").replace("\n","")
  37. res = pr.search(i["summary"])
  38. if res:
  39. book, author, img = res.group(1,2,3)
  40. progress = int(100*int(res.group(4))/int(res.group(5)))
  41. else:
  42. res = rr.search(i["summary"])
  43. if res:
  44. book, author, img = res.group(1,2,3)
  45. progress = 100
  46. else:
  47. continue
  48. svg = makeSVG(book, author, progress, img)
  49. resp = Response(svg, mimetype="image/svg+xml")
  50. resp.headers["Cache-Control"] = "s-maxage=1"
  51. return resp
  52. return data
  53. if __name__ == "__main__":
  54. app.run(debug=True)