forked from vicwomg/pikaraoke
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
540 lines (465 loc) · 14.9 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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import argparse
import json
import logging
import os
import signal
import sys
import threading
import time
from urllib import quote, unquote
from flask import (
Flask,
flash,
redirect,
render_template,
request,
send_file,
send_from_directory,
url_for,
)
import cherrypy
import karaoke
import psutil
app = Flask(__name__)
app.secret_key = "HjI981293u99as811lll"
site_name = "PiKaraoke"
def filename_from_path(file_path, remove_youtube_id=True):
rc = os.path.basename(file_path)
rc = os.path.splitext(rc)[0]
if remove_youtube_id:
rc = rc.split("---")[0] # removes youtube id if present
return rc
def url_escape(filename):
return quote(filename.encode("utf8"))
@app.route("/")
def home():
return render_template("home.html", site_title=site_name, title="Home")
@app.route("/nowplaying")
def nowplaying():
if len(k.queue) >= 2:
next_song = filename_from_path(k.queue[1])
else:
next_song = None
rc = {"now_playing": k.now_playing, "up_next": next_song, "is_pause": k.is_pause}
return json.dumps(rc)
@app.route("/queue")
def queue():
return render_template(
"queue.html", queue=k.queue, site_title=site_name, title="Queue"
)
@app.route("/queue/addrandom", methods=["GET"])
def add_random():
amount = int(request.args["amount"])
rc = k.queue_add_random(amount)
if rc:
flash("Added %s random tracks" % amount, "is-success")
else:
flash("Ran out of songs!", "is-warning")
return redirect(url_for("queue"))
@app.route("/queue/edit", methods=["GET"])
def queue_edit():
action = request.args["action"]
if action == "clear":
k.queue_clear()
flash("Cleared the queue!", "is-warning")
return redirect(url_for("queue"))
else:
song = request.args["song"]
song = unquote(song)
if action == "down":
result = k.queue_edit(song, "down")
if result:
flash("Moved down in queue: " + song, "is-success")
else:
flash("Error moving down in queue: " + song, "is-danger")
elif action == "up":
result = k.queue_edit(song, "up")
if result:
flash("Moved up in queue: " + song, "is-success")
else:
flash("Error moving up in queue: " + song, "is-danger")
elif action == "delete":
result = k.queue_edit(song, "delete")
if result:
flash("Deleted from queue: " + song, "is-success")
else:
flash("Error deleting from queue: " + song, "is-danger")
return redirect(url_for("queue"))
@app.route("/enqueue", methods=["POST", "GET"])
def enqueue():
if request.args.has_key("song"):
song = request.args["song"]
else:
d = request.form.to_dict()
song = d["song_to_add"]
rc = k.enqueue(song)
if rc:
flash("Song added to queue: " + filename_from_path(song), "is-success")
else:
flash("Song is already in queue: " + filename_from_path(song), "is-danger")
return redirect(url_for("home"))
@app.route("/skip")
def skip():
k.skip()
return redirect(url_for("home"))
@app.route("/pause")
def pause():
k.pause()
return redirect(url_for("home"))
@app.route("/restart")
def restart():
rc = k.restart()
return redirect(url_for("home"))
@app.route("/vol_up")
def vol_up():
rc = k.vol_up()
return redirect(url_for("home"))
@app.route("/vol_down")
def vol_down():
k.vol_down()
return redirect(url_for("home"))
@app.route("/search", methods=["GET"])
def search():
if request.args.has_key("search_string"):
search_string = request.args["search_string"]
search_results = k.get_karaoke_search_results(search_string)
else:
search_string = None
search_results = None
return render_template(
"search.html",
site_title=site_name,
title="Search",
songs=k.available_songs,
search_results=search_results,
search_string=search_string,
)
@app.route("/browse", methods=["GET"])
def browse():
if request.args.has_key("sort") and request.args["sort"] == "date":
songs = sorted(k.available_songs, key=lambda x: os.path.getctime(x))
songs.reverse()
sort_order = "Date"
else:
songs = k.available_songs
sort_order = "Alphabetical"
return render_template(
"files.html",
sort_order=sort_order,
site_title=site_name,
title="Browse",
songs=songs,
)
@app.route("/download", methods=["POST"])
def download():
d = request.form.to_dict()
song = d["song-url"]
if d.has_key("queue") and d["queue"] == "on":
queue = True
else:
queue = False
# download in the background since this can take a few minutes
t = threading.Thread(target=k.download_video, args=[song, queue])
t.daemon = True
t.start()
flash_message = (
"Download started: '"
+ song
+ "'. This may take a couple of minutes to complete. "
)
if queue:
flash_message += "Song will be added to queue."
else:
flash_message += 'Song will appear in the "available songs" list.'
flash(flash_message, "is-info")
return redirect(url_for("search"))
@app.route("/qrcode")
def qrcode():
return send_file(k.generate_qr_code(), mimetype="image/png")
@app.route("/files/delete", methods=["GET"])
def delete_file():
if request.args.has_key("song"):
song_path = request.args["song"]
if song_path in k.queue:
flash(
"Error: Can't delete this song because it is in the current queue: "
+ song_path,
"is-danger",
)
else:
k.delete(song_path)
flash("Song deleted: " + song_path, "is-warning")
else:
flash("Error: No song parameter specified!", "is-danger")
return redirect(url_for("browse"))
@app.route("/files/edit", methods=["GET", "POST"])
def edit_file():
queue_error_msg = "Error: Can't edit this song because it is in the current queue: "
if request.args.has_key("song"):
song_path = request.args["song"]
# print "SONG_PATH" + song_path
if song_path in k.queue:
flash(queue_error_msg + song_path, "is-danger")
return redirect(url_for("browse"))
else:
return render_template(
"edit.html",
site_title=site_name,
title="Song File Edit",
song=song_path.encode("utf-8"),
)
else:
d = request.form.to_dict()
if d.has_key("new_file_name") and d.has_key("old_file_name"):
new_name = d["new_file_name"]
old_name = d["old_file_name"]
if old_name in k.queue:
# check one more time just in case someone added it during editing
flash(queue_error_msg + song_path, "is-danger")
else:
# check if new_name already exist
file_name, file_extension = os.path.splitext(old_name)
if os.path.isfile(
os.path.join(k.download_path, new_name + file_extension)
):
flash(
"Error Renaming file: '%s' to '%s'. Filename already exists."
% (old_name, new_name + file_extension),
"is-danger",
)
else:
k.rename(old_name, new_name)
flash(
"Renamed file: '%s' to '%s'." % (old_name, new_name),
"is-warning",
)
else:
flash("Error: No filename parameters were specified!", "is-danger")
return redirect(url_for("browse"))
@app.route("/info")
def info():
url = "http://" + request.host
# cpu
cpu = str(psutil.cpu_percent()) + "%"
# mem
memory = psutil.virtual_memory()
available = round(memory.available / 1024.0 / 1024.0, 1)
total = round(memory.total / 1024.0 / 1024.0, 1)
memory = (
str(available)
+ "MB free / "
+ str(total)
+ "MB total ( "
+ str(memory.percent)
+ "% )"
)
# disk
disk = psutil.disk_usage("/")
# Divide from Bytes -> KB -> MB -> GB
free = round(disk.free / 1024.0 / 1024.0 / 1024.0, 1)
total = round(disk.total / 1024.0 / 1024.0 / 1024.0, 1)
disk = (
str(free)
+ "GB free / "
+ str(total)
+ "GB total ( "
+ str(disk.percent)
+ "% )"
)
# youtube-dl
youtubedl_version = k.youtubedl_version
return render_template(
"info.html",
site_title=site_name,
title="Info",
url=url,
memory=memory,
cpu=cpu,
disk=disk,
youtubedl_version=youtubedl_version,
)
# Delay system commands to allow redirect to render first
def delayed_halt(cmd):
time.sleep(3)
k.queue_clear() # stop all pending omxplayer processes
if cmd == 0:
cherrypy.engine.exit()
sys.exit()
if cmd == 1:
os.system("shutdown now")
if cmd == 2:
os.system("reboot")
update_log_path = "/tmp/youtube-dl-update.log"
def update_youtube_dl():
time.sleep(3)
log_path = "/tmp/youtube-dl-update.log"
os.system('echo "Current youtube-dl version: " > %s' % update_log_path)
os.system("youtube-dl --version >> %s" % update_log_path)
os.system("pip install --upgrade youtube_dl >> %s" % update_log_path)
os.system('echo "New youtube-dl version: " >> %s' % update_log_path)
os.system("youtube-dl --version >> %s" % update_log_path)
k.get_youtubedl_version()
@app.route("/update_ytdl")
def update_ytdl():
flash(
"Updating youtube-dl! Should take a minute or two... (log output at: %s)"
% update_log_path,
"is-warning",
)
th = threading.Thread(target=update_youtube_dl)
th.start()
return redirect(url_for("home"))
@app.route("/quit")
def quit():
flash("Quitting to console now!", "is-warning")
th = threading.Thread(target=delayed_halt, args=[0])
th.start()
return redirect(url_for("home"))
@app.route("/shutdown")
def shutdown():
flash("Shutting down system now!", "is-danger")
th = threading.Thread(target=delayed_halt, args=[1])
th.start()
return redirect(url_for("home"))
@app.route("/reboot")
def reboot():
flash("Rebooting system now!", "is-danger")
th = threading.Thread(target=delayed_halt, args=[2])
th.start()
return redirect(url_for("home"))
# Handle sigterm, apparently cherrypy won't shut down without explicit handling
signal.signal(signal.SIGTERM, lambda signum, stack_frame: sys.exit(1))
if __name__ == "__main__":
default_port = 5000
default_volume = 0
default_splash_delay = 5
default_log_level = logging.INFO
default_dl_dir = "/usr/lib/pikaraoke/songs"
default_omxplayer_path = "/usr/bin/omxplayer"
default_youtubedl_path = "/usr/local/bin/youtube-dl"
# parse CLI args
parser = argparse.ArgumentParser()
parser.add_argument(
"-p",
"--port",
help="Desired http port (default: %d)" % default_port,
default=default_port,
required=False,
)
parser.add_argument(
"-d",
"--download-path",
help="Desired path for downloaded songs. (default: %s)" % default_dl_dir,
default=default_dl_dir,
required=False,
)
parser.add_argument(
"-o",
"--omxplayer-path",
help="Path of omxplayer. (default: %s)" % default_omxplayer_path,
default=default_omxplayer_path,
required=False,
)
parser.add_argument(
"-y",
"--youtubedl-path",
help="Path of youtube-dl. (default: %s)" % default_youtubedl_path,
default=default_youtubedl_path,
required=False,
)
parser.add_argument(
"-v",
"--volume",
help="Initial player volume in millibels. Negative values ok. (default: %s , Note: 100 millibels = 1 decibel)"
% default_volume,
default=default_volume,
required=False,
)
parser.add_argument(
"-s",
"--splash-delay",
help="Delay during splash screen between songs (in secs). (default: %s )"
% default_splash_delay,
default=default_splash_delay,
required=False,
)
parser.add_argument(
"-l",
"--log-level",
help="Logging level int value (DEBUG: 10, INFO: 20, WARNING: 30, ERROR: 40, CRITICAL: 50). (default: %s )"
% default_log_level,
default=default_log_level,
required=False,
)
parser.add_argument(
"--show-overlay",
action="store_true",
help="Show overlay in omxplayer with song title and IP. (feature is broken on Pi 4 omxplayer 12/24/2019)",
required=False,
)
parser.add_argument(
"--hide-ip",
action="store_true",
help="Hide IP address from the screen.",
required=False,
)
parser.add_argument(
"--hide-splash-screen",
action="store_true",
help="Hide splash screen before/between songs.",
required=False,
)
parser.add_argument(
"--alsa-fix",
action="store_true",
help="Add this if you are using a USB soundcard or Hifi audio hat and cannot hear audio.",
required=False,
)
parser.add_argument(
"--dual-screen",
action="store_true",
help="Output video to both HDMI ports (raspberry pi 4 only)",
required=False,
)
parser.add_argument(
"--high-quality",
action="store_true",
help="Download higher quality video. Note: requires ffmpeg and may cause CPU, download speed, and other performance issues",
required=False,
),
args = parser.parse_args()
app.jinja_env.globals.update(filename_from_path=filename_from_path)
app.jinja_env.globals.update(url_escape=quote)
# Start karaoke process
global k
k = karaoke.Karaoke(
port=args.port,
download_path=args.download_path,
omxplayer_path=args.omxplayer_path,
youtubedl_path=args.youtubedl_path,
splash_delay=args.splash_delay,
log_level=args.log_level,
volume=args.volume,
hide_overlay=not args.show_overlay,
hide_ip=args.hide_ip,
hide_splash_screen=args.hide_splash_screen,
alsa_fix=args.alsa_fix,
dual_screen=args.dual_screen,
high_quality=args.high_quality,
)
t = threading.Thread(target=k.run)
t.daemon = True
t.start()
cherrypy.tree.graft(app, "/")
# Set the configuration of the web server
cherrypy.config.update(
{
"engine.autoreload.on": False,
"log.screen": True,
"server.socket_port": int(args.port),
"server.socket_host": "0.0.0.0",
}
)
# Start the CherryPy WSGI web server
cherrypy.engine.start()
cherrypy.engine.block()