123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- import os
- import hashlib
- import sys
- import json
- import re
- import logging
- 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, make_response
- 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("/<site>")
- def site(site):
- try:
- sitedata = read_config()["sites"][site]
- except KeyError:
- sitedata = {}
- return render_template("index.htm", siteid=site, sitedata=sitedata)
- @app.route("/upload/<site>", 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="Ascoltalo su\n%s" % url)
- return fname
- @app.route("/listen/<fname>")
- 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/<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:
- 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')
|