-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
225 lines (186 loc) · 6.07 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""
A Happy MPD web service
"""
import subprocess, os, mpd
from flask import Flask, g, abort, request, render_template, jsonify
from functools import wraps
import json
from logging import warn
HOSTNAME = os.getenv("MPD_HOSTNAME", "localhost")
# FIXME: deprecate this in favour of API arguments
PASSWORD = os.getenv('MPD_PASSWORD', None)
app = Flask(__name__)
class APIException(Exception):
"""Raise this exception in API views to return a json error object."""
def __init__(self, message, status_code=500, source=None):
super(APIException, self).__init__(message)
self.message = message
self.status_code = status_code
self.source = source
@app.errorhandler(APIException)
def jsonrequest_errorhandler(ex):
"""Turn APIException into json response message."""
warn('%s: %s' % (ex.message, ex.source))
resp = jsonify({'error':ex.message})
resp.status_code = ex.status_code
return resp
class MPDWrapper:
"""MPDClient wrapper, to delay connection."""
def __init__(self, hostname, password=None, port=6600):
self._hostname = hostname
self._port = port
self._password = password
self._client = mpd.MPDClient()
self._connected = False
def __getattr__(self, attrname):
"""Only connect to server when getting an instance attribute."""
attr = getattr(self._client, attrname)
if not self._connected:
self._connected = True
try:
self._client.connect(self._hostname, self._port)
except Exception as ex:
raise APIException('Unable to reach MPD server', 503, source=ex)
if self._password:
try:
self._client.password(self._password)
except Exception as ex:
raise APIException('Authentication failed', 403, source=ex)
return attr
def needsmpd(func):
"""Create MPDClient as g.client."""
@wraps(func)
def wrapper(*args, **kwargs):
g.client = MPDWrapper(HOSTNAME, password=PASSWORD, port=6600)
return func(*args, **kwargs)
return wrapper
def version_tuple(version):
"""Split version string into tuple of strings."""
return tuple(version.split('.'))
def queue_youtube(url, mpdcli):
"""
Call youtube-dl to get track information and queue a song into MPD.
If python-mpd2 supports it set track metadata
Returns list of mpd song ids
"""
cmd = ["youtube-dl", "-j", "--prefer-insecure", \
"-f", "140/http_mp3_128_url", "-i", url]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
songids = []
while True:
line = proc.stdout.readline()
if not line:
break
song = json.loads(line.decode('utf8'))
songid = mpdcli.addid(song['url'])
if version_tuple(mpdcli.mpd_version) >= version_tuple('0.19.0'):
mpdcli.addtagid(songid, 'Album', 'youtube-dl')
mpdcli.addtagid(songid, 'Title', song['title'])
songids.append(songid)
return songids
@app.route('/addurl', methods=['POST'])
@needsmpd
def addurl():
"""Add URL on the playlist."""
if not request.json.get('url', None):
raise APIException('Invalid Request, need URL', 400)
try:
queue_youtube(request.json.get('url'), g.client)
except APIException as ex:
raise ex
except Exception as ex:
raise APIException('Unable to queue Url', source=ex)
return jsonify({})
@app.route('/playid', methods=['POST'])
@needsmpd
def playid():
"""Play specific song."""
if request.json.get('songid', None) == None:
raise APIException('No songid was given', 400)
g.client.playid(request.json.get('songid'))
return jsonify(g.client.status())
@app.route('/deleteid', methods=['POST'])
@needsmpd
def deleteid():
"""Remove specific song."""
if request.json.get('songid', None) == None:
raise APIException('No songid was given', 400)
g.client.deleteid(request.json.get('songid'))
return jsonify(g.client.status())
@app.route('/setvol', methods=['POST'])
@needsmpd
def setvol():
"""Set the volume."""
if request.json.get('volume', None) == None:
raise APIException('No volume was given', 400)
g.client.setvol(request.json.get('volume'))
return jsonify(g.client.status())
@app.route('/moveid', methods=['POST'])
@needsmpd
def moveid():
"""Move a given song id to a given position."""
if (request.json.get('id', None) and request.json.get('pos', None)) == None:
raise APIException('Missing Id or Position', 400)
g.client.moveid(request.json.get('id'), request.json.get('pos'))
return jsonify(g.client.status())
@app.route('/status')
@needsmpd
def status():
"""Get MPD status."""
return jsonify(g.client.status())
@app.route('/add/<youtubeId>')
@needsmpd
def add(ytid):
url = "http://www.youtube.com/watch?v="+ytid
try:
queue_youtube(url, g.client)
except:
return 'ups'
return 'yay'
@app.route('/previous')
@needsmpd
def previous():
"""Go to the previous song."""
g.client.previous()
return jsonify(g.client.status())
@app.route('/play')
@needsmpd
def play():
"""If stopped, start playback."""
g.client.play()
return jsonify(g.client.status())
@app.route('/pause')
@needsmpd
def pause():
"""Pause the playback."""
g.client.pause()
return jsonify(g.client.status())
@app.route('/next')
@needsmpd
def next():
"""Go to the next song."""
g.client.next()
return jsonify(g.client.status())
@app.route('/stop')
@needsmpd
def stop():
"""Stop playback."""
g.client.stop()
return jsonify(g.client.status())
@app.route('/clear')
@needsmpd
def clear():
"""Clear the playlist."""
g.client.clear()
return jsonify(g.client.status())
@app.route('/playlistinfo')
@needsmpd
def playlistinfo():
"""Return current playlist."""
return jsonify({song['pos']:song for song in g.client.playlistinfo()})
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.debug = os.getenv('DEBUG')
app.run(host='0.0.0.0', port=8080)