app.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. import hashlib
  2. import json
  3. import logging
  4. import os
  5. import re
  6. import sys
  7. from datetime import datetime
  8. from email.mime.text import MIMEText
  9. from subprocess import PIPE, Popen
  10. from uuid import uuid4
  11. from flask import (Flask, abort, make_response, render_template, request,
  12. url_for)
  13. app = Flask(__name__)
  14. if "MESSAGGERIA_SETTING" in os.environ:
  15. app.config.from_envvar("MESSAGGERIA_SETTING")
  16. UPLOAD_DIR = os.getenv("UPLOAD_DIR", "./uploads/")
  17. logging.basicConfig(level=logging.DEBUG)
  18. def sendmail(sender, to, subject, body):
  19. # msg = MIMEText(body)
  20. # msg["From"] = sender
  21. # msg["To"] = to
  22. # msg["Subject"] = subject
  23. # p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
  24. args = ["/usr/bin/mail", "-s", subject, "--"] + to
  25. p = Popen(args, stdin=PIPE)
  26. # p.communicate(msg.as_bytes())
  27. p.communicate(body.encode("utf8"))
  28. def read_config():
  29. try:
  30. cfgname = os.getenv("CONFIG_FILE", "./config.json")
  31. with open(cfgname) as buf:
  32. cfg = json.load(buf)
  33. except:
  34. app.logger.exception("Error reading conf")
  35. cfg = {}
  36. cfg.setdefault("sites", {})
  37. return cfg
  38. @app.route("/")
  39. def home():
  40. return "casella di destinazione non specificata"
  41. @app.route("/<site>")
  42. def site(site):
  43. try:
  44. sitedata = read_config()["sites"][site]
  45. except KeyError:
  46. sitedata = {}
  47. return render_template("index.htm", siteid=site, sitedata=sitedata)
  48. @app.route("/upload/<site>", methods=["POST"])
  49. def upload(site):
  50. temp_fname = "_%s.ogg" % uuid4().hex
  51. temp_fpath = os.path.join(UPLOAD_DIR, temp_fname)
  52. # prima scrivi su un file temporaneo, poi fai rename
  53. h = hashlib.new("sha1")
  54. with open(temp_fpath, "wb") as buf:
  55. while True:
  56. some_data = request.stream.read(1024)
  57. if not some_data:
  58. break
  59. buf.write(some_data)
  60. h.update(some_data)
  61. # rinomina con l'hash
  62. app.logger.info("hash = %s", h.hexdigest())
  63. fname = "%s.ogg" % h.hexdigest()
  64. os.rename(temp_fpath, os.path.join(UPLOAD_DIR, fname))
  65. if site in read_config()["sites"]:
  66. to = read_config()["sites"][site].get("email", [])
  67. if to:
  68. sender = os.getenv("MAIL_FROM", "")
  69. if not sender:
  70. app.logger.info("Not sending email (unconfigured FROM)")
  71. else:
  72. app.logger.debug("Sending email for `%s` to `%s`", site, ";".join(to))
  73. url = url_for("dl", fname=fname, _external=True, _scheme="https")
  74. sendmail(
  75. sender,
  76. to,
  77. subject="Nuovo messaggio (%s)" % site,
  78. body="Alle {now:%H:%M} hai ricevuto un messaggio nella segreteria di {site}\n"
  79. "Puoi ascoltarlo cliccando su\n{url}\n"
  80. "Per scaricare l'audio, troverai un link dentro la pagina"
  81. "---\n"
  82. "Il servizio è gentilmente offerto da degenerazione.xyz".format(
  83. now=datetime.now(), site=site, url=url
  84. ),
  85. )
  86. return fname
  87. @app.route("/listen/<fname>")
  88. def play(fname):
  89. # prevent path traversal or any other trick
  90. if "/" in fname or not re.match(r"^[a-z0-9]*.(ogg|wav)", fname):
  91. abort(400)
  92. fpath = os.path.join(UPLOAD_DIR, fname)
  93. if not os.path.exists(fpath):
  94. abort(404)
  95. return render_template("player.html", fname=fname)
  96. @app.route("/download/<fname>")
  97. def dl(fname):
  98. # prevent path traversal or any other trick
  99. if "/" in fname or not re.match(r"^[a-z0-9]*.(ogg|wav)", fname):
  100. abort(400)
  101. fpath = os.path.join(UPLOAD_DIR, fname)
  102. if not os.path.exists(fpath):
  103. abort(404)
  104. with open(fpath, "rb") as buf:
  105. content = buf.read()
  106. r = make_response(content)
  107. r.headers["Content-Type"] = "audio/ogg" # TODO: better detect
  108. return r
  109. @app.route("/info/license")
  110. def license():
  111. return render_template("license.html")