-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
76 lines (58 loc) · 1.95 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from flask import Flask
from flask import request
from werkzeug.utils import secure_filename
from flask_sockets import Sockets
import gevent
import os
HOST = 'https://cpc-curz.herokuapp.com/'
PORT = 443
UPLOAD_PATH = 'static/audio/'
UPLOAD_FOLDER = './%s' % (UPLOAD_PATH)
ALLOWED_EXTENSIONS = set(['m4a', 'mp3'])
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
app = Flask(__name__)
sockets = Sockets(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
speakers = list()
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@sockets.route('/connect')
def connect_socket(ws):
speakers.append(ws)
print 'connected'
while not ws.closed:
gevent.sleep(0.1)
message = ws.receive()
print message
ws.send(message)
def get_file_url(filename):
file_url = '%s%s%s' % (HOST, UPLOAD_PATH, filename)
return file_url
def broadcast_file(file_url):
for speaker in speakers:
if not speaker.closed:
print 'sending to speaker: ' + speaker
speaker.send(file_url)
@app.route('/play_url', methods=['POST'])
def play_url():
file_url = request.form['url']
broadcast_file(file_url)
return 'playing: ' + file_url
@app.route('/play_file', methods=['POST'])
def play_file():
if 'file' not in request.files:
return 'No file found'
received_file = request.files['file']
if received_file and allowed_file(received_file.filename):
filename = secure_filename(received_file.filename)
received_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
file_url = get_file_url(filename)
broadcast_file(file_url)
return 'playing: ' + file_url
if __name__ == "__main__":
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
server = pywsgi.WSGIServer(('', PORT), app, handler_class=WebSocketHandler)
server.serve_forever()