3 from functools import wraps
4 from flask import Flask, render_template, request, redirect, send_file, Response, jsonify, abort
5 import variables as var
10 from werkzeug.utils import secure_filename
13 from media.cache import get_cached_wrapper_from_scrap, get_cached_wrapper_by_id, get_cached_wrappers_by_tags
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.
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;
33 :param app: the WSGI application
36 def __init__(self, app):
39 def __call__(self, environ, start_response):
40 script_name = environ.get('HTTP_X_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):]
47 scheme = environ.get('HTTP_X_SCHEME', '')
49 environ['wsgi.url_scheme'] = scheme
50 real_ip = environ.get('HTTP_X_REAL_IP', '')
52 environ['REMOTE_ADDR'] = real_ip
53 return self.app(environ, start_response)
57 log = logging.getLogger("bot")
58 user = 'Remote Control'
64 web.wsgi_app = ReverseProxied(web.wsgi_app)
66 # https://stackoverflow.com/questions/29725217/password-protect-one-webpage-in-flask-app
69 def check_auth(username, password):
70 """This function is called to check if a username /
71 password combination is valid.
73 return username == var.config.get("webinterface", "user") and password == var.config.get("webinterface", "password")
77 """Sends a 401 response that enables basic auth"""
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"'})
86 def decorated(*args, **kwargs):
88 auth = request.authorization
89 if var.config.getboolean("webinterface", "require_auth") and (not auth or not check_auth(auth.username, auth.password)):
91 log.info("web: Failed login attempt, user: %s" % auth.username)
93 return f(*args, **kwargs)
117 def build_tags_color_lookup():
119 for tag in var.music_db.query_all_tags():
120 color_lookup[tag] = tag_color(tag)
125 def build_path_tags_lookup():
126 path_tags_lookup = {}
127 ids = list(var.cache.file_id_lookup.values())
129 id_tags_lookup = var.music_db.query_tags_by_ids(ids)
131 for path, id in var.cache.file_id_lookup.items():
132 path_tags_lookup[path] = id_tags_lookup[id]
134 return path_tags_lookup
137 def recur_dir(dirobj):
138 for name, dir in dirobj.get_subdirs().items():
139 print(dirobj.fullpath + "/" + name)
143 @web.route("/", methods=['GET'])
146 while var.cache.dir_lock.locked():
149 tags_color_lookup = build_tags_color_lookup()
150 path_tags_lookup = build_path_tags_lookup()
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,
158 playlist=var.playlist,
160 paused=var.bot.is_pause,
164 @web.route("/playlist", methods=['GET'])
167 if len(var.playlist) == 0:
168 return jsonify({'items': [render_template('playlist.html',
174 tags_color_lookup = build_tags_color_lookup()
177 for index, item_wrapper in enumerate(var.playlist):
178 items.append(render_template('playlist.html',
180 tags_color_lookup=tags_color_lookup,
181 m=item_wrapper.item(),
182 playlist=var.playlist
186 return jsonify({'items': items})
190 if len(var.playlist) > 0:
191 return jsonify({'ver': var.playlist.version,
193 'play': not var.bot.is_pause,
194 'mode': var.playlist.mode})
196 return jsonify({'ver': var.playlist.version,
199 'mode': var.playlist.mode})
202 @web.route("/post", methods=['POST'])
207 if request.method == 'POST':
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)
215 var.playlist.append(music_wrapper)
216 log.info('web: add to playlist(bottom): ' + music_wrapper.format_debug_string())
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())
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']):
227 folder = request.form['add_folder']
229 folder = request.form['add_folder_recursively']
231 if not folder.endswith('/'):
234 if os.path.isdir(var.music_folder + folder):
236 if 'add_folder_recursively' in request.form:
237 files = dir.get_files_recursively(folder)
239 files = dir.get_files(folder)
241 music_wrappers = list(map(
243 get_cached_wrapper_by_id(var.bot, var.cache.file_id_lookup[folder + file], user), files))
245 var.playlist.extend(music_wrappers)
247 for music_wrapper in music_wrappers:
248 log.info('web: add to playlist: ' + music_wrapper.format_debug_string())
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)
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()
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)
264 log.info("cmd: add to playlist: " + music_wrapper.format_debug_string())
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())
270 if len(var.playlist) >= int(request.form['delete_music']):
271 index = int(request.form['delete_music'])
273 if index == var.playlist.current_index:
274 var.playlist.remove(index)
276 if index < len(var.playlist):
277 if not var.bot.is_pause:
279 var.playlist.current_index -= 1
280 # then the bot will move to next item
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:
287 var.playlist.remove(index)
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())
293 if len(var.playlist) >= int(request.form['play_music']):
294 var.playlist.point_to(int(request.form['play_music']) - 1)
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)
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)
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)
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)
323 var.playlist.randomize()
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":
344 elif action == "pause":
346 elif action == "resume":
348 elif action == "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
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
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))
368 @web.route('/upload', methods=["POST"])
372 files = request.files.getlist("file[]")
374 return redirect("./", code=406)
376 # filename = secure_filename(file.filename).strip()
378 filename = file.filename
380 return redirect("./", code=406)
382 targetdir = request.form['targetdir'].strip()
384 targetdir = 'uploads/'
385 elif '../' in targetdir:
386 return redirect("./", code=406)
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)
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)
400 os.makedirs(storagepath)
401 except OSError as ee:
402 if ee.errno != errno.EEXIST:
403 return redirect("./", code=500)
405 filepath = os.path.join(storagepath, filename)
406 log.info(' - filepath: ' + filepath)
407 if os.path.exists(filepath):
414 var.cache.build_dir_cache(var.bot)
415 log.info("web: Local file cache refreshed.")
417 return redirect("./", code=302)
420 @web.route('/download', methods=["GET"])
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
431 if requested_file in files:
432 filepath = os.path.join(folder_path, requested_file)
434 return send_file(filepath, as_attachment=True)
435 except Exception as e:
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):
446 prefix = secure_filename(os.path.relpath(requested_dir_fullpath, folder_path))
447 zipfile = util.zipdir(requested_dir_fullpath, prefix)
449 return send_file(zipfile, as_attachment=True)
450 except Exception as e:
454 return redirect("./", code=400)
457 if __name__ == '__main__':
458 web.run(port=8181, host="127.0.0.1")