app.py 3.5 KB

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