Browse Source

configurazione e https

boyska 4 years ago
parent
commit
83d2dfe8df
1 changed files with 25 additions and 10 deletions
  1. 25 10
      app.py

+ 25 - 10
app.py

@@ -1,4 +1,5 @@
 import os
+import hashlib
 import sys
 import json
 import re
@@ -7,9 +8,12 @@ from uuid import uuid4
 from email.mime.text import MIMEText
 from subprocess import Popen, PIPE
 
-from flask import Flask, request, render_template, abort, url_for
+from flask import Flask, request, render_template, abort, url_for, make_response
 
 app = Flask(__name__)
+if 'MESSAGGERIA_SETTING' in os.environ:
+    app.config.from_envvar('MESSAGGERIA_SETTING')
+
 
 UPLOAD_DIR = os.getenv("UPLOAD_DIR", "./uploads/")
 
@@ -55,36 +59,47 @@ def site(site):
 @app.route("/upload/<site>", methods=["POST"])
 def upload(site):
     stream = request.files["audio_data"].stream
-    fname = uuid4().hex + ".wav"
-    fpath = os.path.join(UPLOAD_DIR, fname)
-    with open(fpath, "wb") as buf:
+    temp_fname = '_%s.wav' % uuid4().hex
+    temp_fpath = os.path.join(UPLOAD_DIR, temp_fname)
+    # prima scrivi su un file temporaneo, poi fai rename
+    h = hashlib.new('sha1')
+    with open(temp_fpath, "wb") as buf:
         while True:
             some_data = stream.read(1024)
             if not some_data:
                 break
             buf.write(some_data)
+            h.update(some_data)
+    # rinomina con l'hash
+    app.logger.info('hash = %s', h.hexdigest())
+    fname = '%s.wav' % h.hexdigest()
+    os.rename(temp_fpath, os.path.join(UPLOAD_DIR, fname))
     if site in read_config()["sites"]:
         to = read_config()["sites"][site].get("email", [])
         if to:
-            url = url_for("dl", fname=fname, _external=True)
-
             sender = os.getenv('MAIL_FROM', '')
             if not sender:
-                app.logger.info('Not sending email (unconfigured FROM')
+                app.logger.info('Not sending email (unconfigured FROM)')
             else:
                 app.logger.debug('Sending email for `%s` to `%s`',
                         site, ';'.join(to))
-                sendmail(sender, to, subject='Nuovo messaggio!',
-                        body="Ascoltalo su\n%s" % url)
+                url = url_for("dl", fname=fname, _external=True, _scheme='https')
+                sendmail(sender, to,
+                         subject='Nuovo messaggio (%s)' % site,
+                         body="Ascoltalo su\n%s" % url)
     return fname
 
 
 @app.route("/listen/<fname>")
 def dl(fname):
+    # prevent path traversal or any other trick
     if "/" in fname or not re.match(r"^[a-z0-9]*.(ogg|wav)", fname):
         abort(400)
     fpath = os.path.join(UPLOAD_DIR, fname)
     if not os.path.exists(fpath):
         abort(404)
     with open(fpath, "rb") as buf:
-        return buf.read()
+        content = buf.read()
+    r = make_response(content)
+    r.headers['Content-Type'] = 'audio/wav'  # TODO: better detect
+    return r