]> git.0d.be Git - botaradio.git/blob - interface.py
let's release the kraken
[botaradio.git] / interface.py
1 #!/usr/bin/python3
2
3 from functools import wraps
4 from flask import Flask, render_template, request, redirect, send_file, Response, jsonify, abort
5 import variables as var
6 import util
7 import os
8 import os.path
9 import shutil
10 from werkzeug.utils import secure_filename
11 import errno
12 import media
13 from media.cache import get_cached_wrapper_from_scrap, get_cached_wrapper_by_id, get_cached_wrappers_by_tags
14 import logging
15 import time
16
17
18 class ReverseProxied(object):
19     """Wrap the application in this middleware and configure the
20     front-end server to add these headers, to let you quietly bind
21     this to a URL other than / and to an HTTP scheme that is
22     different than what is used locally.
23
24     In nginx:
25     location /myprefix {
26         proxy_pass http://192.168.0.1:5001;
27         proxy_set_header Host $host;
28         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
29         proxy_set_header X-Scheme $scheme;
30         proxy_set_header X-Script-Name /myprefix;
31         }
32
33     :param app: the WSGI application
34     """
35
36     def __init__(self, app):
37         self.app = app
38
39     def __call__(self, environ, start_response):
40         script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
41         if script_name:
42             environ['SCRIPT_NAME'] = script_name
43             path_info = environ['PATH_INFO']
44             if path_info.startswith(script_name):
45                 environ['PATH_INFO'] = path_info[len(script_name):]
46
47         scheme = environ.get('HTTP_X_SCHEME', '')
48         if scheme:
49             environ['wsgi.url_scheme'] = scheme
50         real_ip = environ.get('HTTP_X_REAL_IP', '')
51         if real_ip:
52             environ['REMOTE_ADDR'] = real_ip
53         return self.app(environ, start_response)
54
55
56 web = Flask(__name__)
57 log = logging.getLogger("bot")
58 user = 'Remote Control'
59
60
61 def init_proxy():
62     global web
63     if var.is_proxified:
64         web.wsgi_app = ReverseProxied(web.wsgi_app)
65
66 # https://stackoverflow.com/questions/29725217/password-protect-one-webpage-in-flask-app
67
68
69 def check_auth(username, password):
70     """This function is called to check if a username /
71     password combination is valid.
72     """
73     return username == var.config.get("webinterface", "user") and password == var.config.get("webinterface", "password")
74
75
76 def authenticate():
77     """Sends a 401 response that enables basic auth"""
78     global log
79     return Response('Could not verify your access level for that URL.\n'
80                     'You have to login with proper credentials', 401,
81                     {'WWW-Authenticate': 'Basic realm="Login Required"'})
82
83
84 def requires_auth(f):
85     @wraps(f)
86     def decorated(*args, **kwargs):
87         global log
88         auth = request.authorization
89         if var.config.getboolean("webinterface", "require_auth") and (not auth or not check_auth(auth.username, auth.password)):
90             if auth:
91                 log.info("web: Failed login attempt, user: %s" % auth.username)
92             return authenticate()
93         return f(*args, **kwargs)
94     return decorated
95
96
97 def tag_color(tag):
98     num = hash(tag) % 8
99     if num == 0:
100         return "primary"
101     elif num == 1:
102         return "secondary"
103     elif num == 2:
104         return "success"
105     elif num == 3:
106         return "danger"
107     elif num == 4:
108         return "warning"
109     elif num == 5:
110         return "info"
111     elif num == 6:
112         return "light"
113     elif num == 7:
114         return "dark"
115
116
117 def build_tags_color_lookup():
118     color_lookup = {}
119     for tag in var.music_db.query_all_tags():
120         color_lookup[tag] = tag_color(tag)
121
122     return color_lookup
123
124
125 def build_path_tags_lookup():
126     path_tags_lookup = {}
127     ids = list(var.cache.file_id_lookup.values())
128     if len(ids) > 0:
129         id_tags_lookup = var.music_db.query_tags_by_ids(ids)
130
131         for path, id in var.cache.file_id_lookup.items():
132             path_tags_lookup[path] = id_tags_lookup[id]
133
134     return path_tags_lookup
135
136
137 def recur_dir(dirobj):
138     for name, dir in dirobj.get_subdirs().items():
139         print(dirobj.fullpath + "/" + name)
140         recur_dir(dir)
141
142
143 @web.route("/", methods=['GET'])
144 @requires_auth
145 def index():
146     while var.cache.dir_lock.locked():
147         time.sleep(0.1)
148
149     tags_color_lookup = build_tags_color_lookup()
150     path_tags_lookup = build_path_tags_lookup()
151
152     return render_template('index.html',
153                            all_files=var.cache.files,
154                            tags_lookup=path_tags_lookup,
155                            tags_color_lookup=tags_color_lookup,
156                            music_library=var.cache.dir,
157                            os=os,
158                            playlist=var.playlist,
159                            user=var.user,
160                            paused=var.bot.is_pause,
161                            )
162
163
164 @web.route("/playlist", methods=['GET'])
165 @requires_auth
166 def playlist():
167     if len(var.playlist) == 0:
168         return jsonify({'items': [render_template('playlist.html',
169                                                   m=False,
170                                                   index=-1
171                                                   )]
172                         })
173
174     tags_color_lookup = build_tags_color_lookup()
175     items = []
176
177     for index, item_wrapper in enumerate(var.playlist):
178         items.append(render_template('playlist.html',
179                                      index=index,
180                                      tags_color_lookup=tags_color_lookup,
181                                      m=item_wrapper.item(),
182                                      playlist=var.playlist
183                                      )
184                      )
185
186     return jsonify({'items': items})
187
188
189 def status():
190     if len(var.playlist) > 0:
191         return jsonify({'ver': var.playlist.version,
192                         'empty': False,
193                         'play': not var.bot.is_pause,
194                         'mode': var.playlist.mode})
195     else:
196         return jsonify({'ver': var.playlist.version,
197                         'empty': True,
198                         'play': False,
199                         'mode': var.playlist.mode})
200
201
202 @web.route("/post", methods=['POST'])
203 @requires_auth
204 def post():
205     global log
206
207     if request.method == 'POST':
208         if request.form:
209             log.debug("web: Post request from %s: %s" % (request.remote_addr, str(request.form)))
210         if 'add_file_bottom' in request.form and ".." not in request.form['add_file_bottom']:
211             path = var.music_folder + request.form['add_file_bottom']
212             if os.path.isfile(path):
213                 music_wrapper = get_cached_wrapper_by_id(var.bot, var.cache.file_id_lookup[request.form['add_file_bottom']], user)
214
215                 var.playlist.append(music_wrapper)
216                 log.info('web: add to playlist(bottom): ' + music_wrapper.format_debug_string())
217
218         elif 'add_file_next' in request.form and ".." not in request.form['add_file_next']:
219             path = var.music_folder + request.form['add_file_next']
220             if os.path.isfile(path):
221                 music_wrapper = get_cached_wrapper_by_id(var.bot, var.cache.file_id_lookup[request.form['add_file_next']], user)
222                 var.playlist.insert(var.playlist.current_index + 1, music_wrapper)
223                 log.info('web: add to playlist(next): ' + music_wrapper.format_debug_string())
224
225         elif ('add_folder' in request.form and ".." not in request.form['add_folder']) or ('add_folder_recursively' in request.form and ".." not in request.form['add_folder_recursively']):
226             try:
227                 folder = request.form['add_folder']
228             except:
229                 folder = request.form['add_folder_recursively']
230
231             if not folder.endswith('/'):
232                 folder += '/'
233
234             if os.path.isdir(var.music_folder + folder):
235                 dir = var.cache.dir
236                 if 'add_folder_recursively' in request.form:
237                     files = dir.get_files_recursively(folder)
238                 else:
239                     files = dir.get_files(folder)
240
241                 music_wrappers = list(map(
242                     lambda file:
243                     get_cached_wrapper_by_id(var.bot, var.cache.file_id_lookup[folder + file], user), files))
244
245                 var.playlist.extend(music_wrappers)
246
247                 for music_wrapper in music_wrappers:
248                     log.info('web: add to playlist: ' + music_wrapper.format_debug_string())
249
250         elif 'add_url' in request.form:
251             music_wrapper = get_cached_wrapper_from_scrap(var.bot, type='url', url=request.form['add_url'], user=user)
252             var.playlist.append(music_wrapper)
253
254             log.info("web: add to playlist: " + music_wrapper.format_debug_string())
255             if len(var.playlist) == 2:
256                 # If I am the second item on the playlist. (I am the next one!)
257                 var.bot.async_download_next()
258
259         elif 'add_radio' in request.form:
260             url = request.form['add_radio']
261             music_wrapper = get_cached_wrapper_from_scrap(var.bot, type='radio', url=url, user=user)
262             var.playlist.append(music_wrapper)
263
264             log.info("cmd: add to playlist: " + music_wrapper.format_debug_string())
265
266         elif 'delete_music' in request.form:
267             music_wrapper = var.playlist[int(request.form['delete_music'])]
268             log.info("web: delete from playlist: " + music_wrapper.format_debug_string())
269
270             if len(var.playlist) >= int(request.form['delete_music']):
271                 index = int(request.form['delete_music'])
272
273                 if index == var.playlist.current_index:
274                     var.playlist.remove(index)
275
276                     if index < len(var.playlist):
277                         if not var.bot.is_pause:
278                             var.bot.interrupt()
279                             var.playlist.current_index -= 1
280                             # then the bot will move to next item
281
282                     else:  # if item deleted is the last item of the queue
283                         var.playlist.current_index -= 1
284                         if not var.bot.is_pause:
285                             var.bot.interrupt()
286                 else:
287                     var.playlist.remove(index)
288
289         elif 'play_music' in request.form:
290             music_wrapper = var.playlist[int(request.form['play_music'])]
291             log.info("web: jump to: " + music_wrapper.format_debug_string())
292
293             if len(var.playlist) >= int(request.form['play_music']):
294                 var.playlist.point_to(int(request.form['play_music']) - 1)
295                 var.bot.interrupt()
296                 time.sleep(0.1)
297
298         elif 'delete_music_file' in request.form and ".." not in request.form['delete_music_file']:
299             path = var.music_folder + request.form['delete_music_file']
300             if os.path.isfile(path):
301                 log.info("web: delete file " + path)
302                 os.remove(path)
303
304         elif 'delete_folder' in request.form and ".." not in request.form['delete_folder']:
305             path = var.music_folder + request.form['delete_folder']
306             if os.path.isdir(path):
307                 log.info("web: delete folder " + path)
308                 shutil.rmtree(path)
309                 time.sleep(0.1)
310
311         elif 'add_tag' in request.form:
312             music_wrappers = get_cached_wrappers_by_tags(var.bot, [request.form['add_tag']], user)
313             for music_wrapper in music_wrappers:
314                 log.info("cmd: add to playlist: " + music_wrapper.format_debug_string())
315             var.playlist.extend(music_wrappers)
316
317         elif 'action' in request.form:
318             action = request.form['action']
319             if action == "randomize":
320                 if var.playlist.mode != "random":
321                     var.playlist = media.playlist.get_playlist("random", var.playlist)
322                 else:
323                     var.playlist.randomize()
324                 var.bot.interrupt()
325                 var.db.set('playlist', 'playback_mode', "random")
326                 log.info("web: playback mode changed to random.")
327             if action == "one-shot":
328                 var.playlist = media.playlist.get_playlist("one-shot", var.playlist)
329                 var.db.set('playlist', 'playback_mode', "one-shot")
330                 log.info("web: playback mode changed to one-shot.")
331             if action == "repeat":
332                 var.playlist = media.playlist.get_playlist("repeat", var.playlist)
333                 var.db.set('playlist', 'playback_mode', "repeat")
334                 log.info("web: playback mode changed to repeat.")
335             if action == "autoplay":
336                 var.playlist = media.playlist.get_playlist("autoplay", var.playlist)
337                 var.db.set('playlist', 'playback_mode', "autoplay")
338                 log.info("web: playback mode changed to autoplay.")
339             if action == "rescan":
340                 var.cache.build_dir_cache(var.bot)
341                 log.info("web: Local file cache refreshed.")
342             elif action == "stop":
343                 var.bot.stop()
344             elif action == "pause":
345                 var.bot.pause()
346             elif action == "resume":
347                 var.bot.resume()
348             elif action == "clear":
349                 var.bot.clear()
350             elif action == "volume_up":
351                 if var.bot.volume_set + 0.03 < 1.0:
352                     var.bot.volume_set = var.bot.volume_set + 0.03
353                 else:
354                     var.bot.volume_set = 1.0
355                 var.db.set('bot', 'volume', str(var.bot.volume_set))
356                 log.info("web: volume up to %d" % (var.bot.volume_set * 100))
357             elif action == "volume_down":
358                 if var.bot.volume_set - 0.03 > 0:
359                     var.bot.volume_set = var.bot.volume_set - 0.03
360                 else:
361                     var.bot.volume_set = 0
362                 var.db.set('bot', 'volume', str(var.bot.volume_set))
363                 log.info("web: volume up to %d" % (var.bot.volume_set * 100))
364
365     return status()
366
367
368 @web.route('/upload', methods=["POST"])
369 def upload():
370     global log
371
372     files = request.files.getlist("file[]")
373     if not files:
374         return redirect("./", code=406)
375
376     # filename = secure_filename(file.filename).strip()
377     for file in files:
378         filename = file.filename
379         if filename == '':
380             return redirect("./", code=406)
381
382         targetdir = request.form['targetdir'].strip()
383         if targetdir == '':
384             targetdir = 'uploads/'
385         elif '../' in targetdir:
386             return redirect("./", code=406)
387
388         log.info('web: Uploading file from %s:' % request.remote_addr)
389         log.info('web: - filename: ' + filename)
390         log.info('web: - targetdir: ' + targetdir)
391         log.info('web: - mimetype: ' + file.mimetype)
392
393         if "audio" in file.mimetype:
394             storagepath = os.path.abspath(os.path.join(var.music_folder, targetdir))
395             print('storagepath:', storagepath)
396             if not storagepath.startswith(os.path.abspath(var.music_folder)):
397                 return redirect("./", code=406)
398
399             try:
400                 os.makedirs(storagepath)
401             except OSError as ee:
402                 if ee.errno != errno.EEXIST:
403                     return redirect("./", code=500)
404
405             filepath = os.path.join(storagepath, filename)
406             log.info(' - filepath: ' + filepath)
407             if os.path.exists(filepath):
408                 continue
409
410             file.save(filepath)
411         else:
412             continue
413
414     var.cache.build_dir_cache(var.bot)
415     log.info("web: Local file cache refreshed.")
416
417     return redirect("./", code=302)
418
419
420 @web.route('/download', methods=["GET"])
421 def download():
422     global log
423
424     if 'file' in request.args:
425         requested_file = request.args['file']
426         log.info('web: Download of file %s requested from %s:' % (requested_file, request.remote_addr))
427         if '../' not in requested_file:
428             folder_path = var.music_folder
429             files = var.cache.files
430
431             if requested_file in files:
432                 filepath = os.path.join(folder_path, requested_file)
433                 try:
434                     return send_file(filepath, as_attachment=True)
435                 except Exception as e:
436                     log.exception(e)
437                     abort(404)
438     elif 'directory' in request.args:
439         requested_dir = request.args['directory']
440         folder_path = var.music_folder
441         requested_dir_fullpath = os.path.abspath(os.path.join(folder_path, requested_dir)) + '/'
442         if requested_dir_fullpath.startswith(folder_path):
443             if os.path.samefile(requested_dir_fullpath, folder_path):
444                 prefix = 'all'
445             else:
446                 prefix = secure_filename(os.path.relpath(requested_dir_fullpath, folder_path))
447             zipfile = util.zipdir(requested_dir_fullpath, prefix)
448             try:
449                 return send_file(zipfile, as_attachment=True)
450             except Exception as e:
451                 log.exception(e)
452                 abort(404)
453
454     return redirect("./", code=400)
455
456
457 if __name__ == '__main__':
458     web.run(port=8181, host="127.0.0.1")