import hashlib import json import logging import os import re import sys from datetime import datetime from email.mime.text import MIMEText from subprocess import PIPE, Popen from uuid import uuid4 from flask import (Flask, abort, make_response, render_template, request, url_for) app = Flask(__name__) if "MESSAGGERIA_SETTING" in os.environ: app.config.from_envvar("MESSAGGERIA_SETTING") UPLOAD_DIR = os.getenv("UPLOAD_DIR", "./uploads/") logging.basicConfig(level=logging.DEBUG) def sendmail(sender, to, subject, body): # msg = MIMEText(body) # msg["From"] = sender # msg["To"] = to # msg["Subject"] = subject # p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE) args = ["/usr/bin/mail", "-s", subject, "--"] + to p = Popen(args, stdin=PIPE) # p.communicate(msg.as_bytes()) p.communicate(body.encode("utf8")) def read_config(): try: cfgname = os.getenv("CONFIG_FILE", "./config.json") with open(cfgname) as buf: cfg = json.load(buf) except: app.logger.exception("Error reading conf") cfg = {} cfg.setdefault("sites", {}) return cfg @app.route("/") def home(): return "casella di destinazione non specificata" @app.route("/") def site(site): try: sitedata = read_config()["sites"][site] except KeyError: sitedata = {} return render_template("index.htm", siteid=site, sitedata=sitedata) @app.route("/upload/", methods=["POST"]) def upload(site): temp_fname = "_%s.ogg" % 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 = request.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.ogg" % 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: sender = os.getenv("MAIL_FROM", "") if not sender: app.logger.info("Not sending email (unconfigured FROM)") else: app.logger.debug("Sending email for `%s` to `%s`", site, ";".join(to)) url = url_for("dl", fname=fname, _external=True, _scheme="https") sendmail( sender, to, subject="Nuovo messaggio (%s)" % site, body="Alle {now:%H:%M} hai ricevuto un messaggio nella segreteria di {site}\n" "Puoi ascoltarlo cliccando su\n{url}\n" "Per scaricare l'audio, troverai un link dentro la pagina" "---\n" "Il servizio รจ gentilmente offerto da degenerazione.xyz".format( now=datetime.now(), site=site, url=url ), ) return fname @app.route("/listen/") def play(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) return render_template("player.html", fname=fname) @app.route("/download/") 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: content = buf.read() r = make_response(content) r.headers["Content-Type"] = "audio/ogg" # TODO: better detect return r @app.route("/info/license") def license(): return render_template("license.html")