-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmoosicWebGUI.py
More file actions
executable file
·1911 lines (1681 loc) · 76.7 KB
/
moosicWebGUI.py
File metadata and controls
executable file
·1911 lines (1681 loc) · 76.7 KB
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: Latin-1 -*-
#:tabSize=4:indentSize=4:noTabs=true:mode=python:encoding=ISO-8859-1:
#
########################################################################
#
# moosicWebGUI -- web GUI for controlling the moosicd daemon
#
# Copyright (C) 2004, 2005 Eckhard Licher, Frankfurt, Germany.
#
# This program is free software; you can redistribute it
# and/or modify it under the terms of version 2 of the GNU
# General Public License as published by the Free Software
# Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License (contained in file COPYING) for more
# details.
#
########################################################################
"""
moosicWebGUI(1)
=============
Eckhard Licher <develf@online.de>
v0.9, Dec03 2005
NAME
----
moosicWebGUI - web GUI for controlling the moosicd daemon
SYNOPSIS
--------
'moosicWebGUI.py' [-p number] [-s] [-i] [-j name] [-a host]
[-n net] [-h] [-m] [-d] [-c configdir] [-t template]
[--port=number] [--server-only] [--ignore-exit]
[--jukebox-dir=name] [--add-host=host] [--add-network=net]
[--help] [--manual] [--debug] [--config=configdir]
[--template=template]
DESCRIPTION
-----------
'moosicWebGUI' is a web GUI based on a simple HTTP server with
special built-in commands for controlling the moosicd daemon.
The HTTP server implementation only handles GET and HEAD
requests. POST requests are not implemented.
OPTIONS
-------
'-p number, --port=number'::
set the server's portnumber to number
'-s, --server-only'::
server-only mode, no browser is launched
'-i', '--ignore-exit'::
ignore exit request via HTTP request
'-j, --jukebox-dir'::
select directory containing music files
'-a, --add-host'::
add host to list of allowed hosts (ip address or host name)
'-n, --add-network'::
add network to list of allowed networks;
network is specified with CIDR notation, e.g. 192.168.0.0/24
'-h, --help'::
display help message and exit
'-m, --manual'::
display this manual page and exit
'-d, --debug'::
include debug information in HTML pages
'-c configdir, --config=configdir'::
take moosic configuration from configdir
'-t template, --template=template'::
use specified template file
Options specified at the command line are evaluated from left
to right.
When invoked without options, 'moosicWebGUI' serves HTTP
requests through port 8000. In case port 8000 is already in
use the server searches for an unused port by subsequently
incrementing the port number and trying to bind to the port
unless option '-p' is specified. If option '-p' is specified
the port auto-search function is turned off.
Unless option '-s' is specified 'moosicWebGUI' tries to
launch the system's web browser with the initial URL pointing
to the internal web server.
'moosicWebGUI' can be terminated with a HTTP request to '/exit'.
This exit request can be disabled with option '-i'.
The directory containing music files is assumed to be $HOME.
In case $HOME is not set /tmp is assumed to be the jukebox
directory. It may be explicitly specified by option '-j'.
For security reasons only requests originating from the local
machine are being served by default. Other hosts need to be
included explicitly to the access control list by means of
option '-a'. Option '-a' may be used more than once in order
to allow access from several hosts. Additionally, entire
networks may be specified using option '-n'; network addresses
shall be specified using CIDR format (e.g. 192.168.0.0/24).
Incorrect invocation of the program as well as option '-h'
display a brief help message. The full manual page, i.e. this
document, is printed through option '-m'. In either case
program execution terminates regardless of other options
possibly specified.
If option '-d' is specified some debug information and a link
to the wdg's html validator is included in the generated HTML
pages. To validate pages package wdg-html-validator needs to
be installed.
The moosic configuration is read from the default directory
($HOME/.moosic/ or /tmp/.moosic/) unless option '-c' is
specified.
An alternate template may be specified by means of option '-t'.
FILES
-----
template.html::
Page template file used for content generation.
COPYING::
License text (GPL version 2).
ENVIRONMENT
-----------
HOME::
The user's home directory is taken as the default jukebox
directory. Overridden by the -j option.
DIAGNOSTICS
-----------
The following diagnostics may be issued on stderr:
DNS lookup for host <host> failed.::
The host's IP address could not be resolved -- check spelling.
<network> is not a valid network specification.::
The network specification is not valid -- it shall be in CIDR
format, e.g. 192.168.0.0/24.
The moosicd server doesn't seem to be running, and it could not ...::
For some reason it was not possible to start the moosicd server.
An attempt was made to start the moosic server, but ...::
An attempt was made to start the moosic server, but for some strange
reason it was not possible to start the moosicd server.
Moosic api version <version> is not supported (must be 1.7 or later).::
Use a moosic version >= 1.5.
Can not connect to port <port>::
The webserver could not connect to port <port> -- use a free port
higher than port number 1024.
Can not start new server, giving up. Sorry.::
The webserver terminated due to a weird error and could not
be restarted.
AVAILABILITY
------------
'moosicWebGUI' is available on all platforms supporting Python 2.2
or later.
CAVEATS
-------
This is alpha software, so beware.
The jukebox directory may any directory other than '/'. This should
be considered to be a feature :-)
BUGS
----
Please send bug reports to the author.
AUTHOR
------
2005 Eckhard Licher, Frankfurt, Germany. <develf at online dot de>
ACKNOWLEDGEMENTS
----------------
The code for the initiation of the connection to moosicd and the
easter egg was adapted from the moosic client written by Daniel
Pearson <daniel at nanoo dot org>.
Options -n, -c and -t: the code for access control list for entire
networks, scanning of moosic config file for supported file types
and the use of alternate template file (introduced in version 0.8.1)
was contributed by Forest Bond <forest at alittletooquiet dot net>.
SEE ALSO
--------
moosic(1), moosicd(1), validate(1)
"""
#######################################################################
# NOTE
#######################################################################
# The text contained in the preceding docstring contains the program's
# man page in asciidoc format. The asciidoc source can be converted to
# HTML and/or docbook-sgml (for docbook2man post-processing).
#
# Extract the docstring with the following command and post-process
# with asciidoc (and possibly docbook2man) as desired:
# $ python moosicWebGUI.py -m > moosicWebGUI.asc
#######################################################################
# Import needed python modules
import getopt, os, os.path, socket, string, sys, time
import urllib, errno, random, re, fileinput, base64, marshal
import BaseHTTPServer, SimpleHTTPServer, webbrowser
import moosic.client.factory
from xmlrpclib import Binary
# Request Handler for HTTP requests to our server
class moosicWebGUIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""
Complete HTTP server with GET and HEAD commands.
GET and HEAD support for special moosicWebGUI built-in functions.
The POST command is not implemented.
"""
def do_HEAD(self):
"""send headers"""
if not allowed_to_connect(self.client_address[0]):
self.send_response(403)
else:
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def do_GET(self):
"""Execute a moosicWebGUI function"""
# make sure we are connected from an allowed host
if not allowed_to_connect(self.client_address[0]):
self.send_response(403, 'Forbidden')
self.wfile.write('Content-type: text/html\n\n')
self.wfile.write('''
<h1>Forbidden</h1><p>Access denied. Your host is neither
included in ACL 'allowed_hosts' nor in ACL 'allowed_networks'.</p>
''')
return
self.message = ""
self.dyn_content = ''
form = {}
# favicon.ico requested ?
if self.path == "/favicon.ico":
self.send_response(200, 'OK')
self.wfile.write('Content-type: image/x-ms-bmp\n\n')
try:
image = open(os.path.join(mydir, "favicon.ico"),"rb").read()
self.wfile.write(image)
except IOError:
pass
return
# favicon.ico requested ?
if self.path.endswith(".html"):
print mydir
print self.path
fname = os.path.join(mydir, self.path[1:])
try:
text = open(fname,"rb").read()
self.send_response(200, 'OK')
self.wfile.write('Content-type: text/html\n\n')
self.wfile.write(text)
except IOError:
self.send_response(404, 'not found')
self.wfile.write('Content-type: text/html\n\n')
self.wfile.write("<h1>file '%s' not found</h1>" % fname)
return
# extract information from request
command = self.path[1:] # we don't need the initial '/'
pos = string.find(command,"?")
if pos > -1:
# strip off additional request parameters and store in 'form' variable
params = command[pos+1:]
command=command[:pos]
# extract additional request parameters
parlist = string.split(params,"&")
for par in parlist:
chunks = string.split(par,"=")
if len(chunks)>1:
form[urllib.unquote_plus(chunks[0])] = urllib.unquote_plus(chunks[1])
else:
form[urllib.unquote_plus(chunks[0])] = None
# check existance and/or validity parameters supplied with request:
if not command:
command = "index"
# view type
self.view = form.get("view", "")
if self.view not in ("history", "playlist", "files", "tree", "search"):
self.view = "standard"
# search pattern
self.pattern = form.get("pattern", "")
# load mode for stored playlists
self.lmode = form.get("lmode", "append")
# "current working directory"
self.mypath = form.get("path", myroot)
if string.find(self.mypath, myroot) != 0 or string.find(self.mypath,"/..") >= 0:
self.mypath = myroot
# directory argument (files to append, mixin...)
self.dir = form.get("dir", "")
if string.find(self.dir, myroot) != 0 or string.find(self.dir,"/..") >= 0:
self.dir = myroot
# filename argument
self.file = form.get("file", "")
if string.find(self.file, myroot) != 0 or string.find(self.file,"/..") >= 0:
self.file = myroot
# number argument (for skip etc.)
self.count = 0
if form.has_key("count"):
try:
self.count = int(form["count"])
except ValueError:
pass
# position in playlist
self.pos = 0
if form.has_key("pos"):
try:
self.pos = int(form["pos"])
except ValueError:
pass
# get current moosicd status
self.is_queue_running = proxy.is_queue_running()
self.is_looping = proxy.is_looping()
self.is_paused = proxy.is_paused()
self.queue_length = proxy.queue_length()
#####################
# command dispatcher.
#####################
if hasattr(self, "_do__" + command):
# execute functions which return special pages -- processing ends here
if debug:
print "executing _do__" + command
meth = getattr(self, "_do__" + command)
meth()
return
elif hasattr(self, "_do_" + command):
# execute functions which return standard pages
if debug:
print "executing _do_" + command
meth = getattr(self, "_do_" + command)
meth()
else:
self.message += '<font color="#aa0000">Command "%s" is not (yet) implemented. </font>' % command
# if the function called by the dispatcher did not produce a message
# we just say which function was executed
if not self.message:
self.message += "Command '%s' executed. " % command
# moosicd has some latency time for some commands, so we just wait a bit
time.sleep(0.05)
# if the function called by the dispatcher did not produce its own content
# we create content for the selected view type
if not self.dyn_content:
meth = getattr(self, "cont_" + self.view)
self.dyn_content = meth()
# get current moosicd status (again)
is_queue_running = proxy.is_queue_running()
is_looping = proxy.is_looping()
is_paused = proxy.is_paused()
queue_length = proxy.queue_length()
time.sleep(0.05)
current_track = proxy.current().data
current_time = proxy.current_time()
# write headers
self.send_response(200, 'Script output follows')
self.wfile.write('Content-type: text/html\n\n')
# build result page from template
content = template
if debug:
content = string.replace(content, "@@debug", "<hr><pre>\n%s\n%s</pre><hr>" % (self.path,form))
else:
content = string.replace(content, "@@debug", "")
if is_looping:
txt = "<b>looping</b>"
content = string.replace(content, "@@P1@@", "phigh")
if current_track:
content = string.replace(content, '@@del_current', '<a href="del_current?@@params"><i>remove</i></a>')
else:
content = string.replace(content, "@@del_current", " ")
else:
txt = "not looping"
content = string.replace(content, "@@P1@@", "pnorm")
content = string.replace(content, "@@del_current", " ")
content = string.replace(content, "@@looping", '<a href="loop?@@params">%s</a>' % txt)
if is_queue_running:
txt = "advancing"
content = string.replace(content, "@@P2@@", "pnorm")
else:
txt= "<b>not advancing</b>"
content = string.replace(content, "@@P2@@", "phigh")
content = string.replace(content, "@@advancing", '<a href="advance?@@params">%s</a>' % txt)
if is_paused:
txt = "<b>pause</b>"
content = string.replace(content, "@@P3@@", "phigh")
else:
txt = "not paused"
content = string.replace(content, "@@P3@@", "pnorm")
content = string.replace(content, "@@pause", '<a href="pause?@@params">%s</a>' % txt)
content = string.replace(content, "@@message", "%s" % self.message)
content = string.replace(content, "@@time", "%s" % current_time)
content = string.replace(content, "@@current_track", format_name(current_track))
content = string.replace(content, "@@remaining", "<b>%d</b> remaining" % queue_length)
if ignore_exit:
content = string.replace(content, "@@exit", '')
else:
content = string.replace(content, "@@exit", '<a href="exit?@@params">exit moosicWebGUI</a>')
if debug:
url = "http://localhost:%d%s" % (port, self.path)
url = string.replace(url, "&", "&")
url = "?url=" + url + "&input=yes&warnings=yes"
url = "http://localhost/cgi-bin/validate.cgi" + url
content = string.replace(content, "@@validate", \
'<a target="val" href="%s">validate page</a>' % url)
else:
content = string.replace(content, "@@validate", "")
content = string.replace(content, "@@content", "%s" % self.dyn_content)
# @@params shall be last (@@content and @@exeit use @@params)
content = string.replace(content, "@@cform", clear_form % \
(self.view, self.mypath))
content = string.replace(content, "@@sform", search_form % \
("search", "search", self.mypath, self.pattern, "search music files"))
content = string.replace(content, "@@params", 'path=%s&view=%s&pattern=%s' % \
(urllib.quote(self.mypath), urllib.quote(self.view),
urllib.quote(self.pattern)))
# write page
self.wfile.write(content)
#-------------------------------------------
def _do__list2(self):
"""write current state of playlist to text file/plain page in .m3u format"""
playlist = [i.data for i in proxy.list()]
self.send_response(200, 'Script output follows')
self.wfile.write('Content-type: text/plain\n\n')
self.wfile.write('#EXTM3U\n')
for item in playlist:
pos1 = string.rfind(item, '/')
pos2 = string.rfind(item, '.')
self.wfile.write('#EXTINF:-1,%s\n' % item[pos1+1:pos2].replace('_',' '))
self.wfile.write('%s\n' % item)
#-------------------------------------------
def _do_add_bottom(self):
"""add all files from directory tree to bottom of playlist"""
if self.dir:
dir = self.dir
#files = os.popen('find "%s" -type f -print' % dir).readlines()
files = getfiles(dir)
files.sort()
count = 0
proxy.halt_queue()
for file in files:
if file_is_moosical(file) and string.find(file, "/.") < 0:
proxy.append([Binary(file)])
count += 1
if self.is_queue_running:
proxy.run_queue()
self.message += "%d files added to bottom of playlist from directory '%s'. " % (count, dir[len(myroot)+1:])
else:
self.message += "Weird error -- no directory name given. "
def _do_add_top(self):
"""add all files from directory tree to top of playlist"""
if self.dir:
dir = self.dir
files = getfiles(dir)
files.sort()
files.reverse()
count = 0
proxy.halt_queue()
for file in files:
if file_is_moosical(file) and string.find(file, "/.") < 0:
proxy.prepend([Binary(file)])
count += 1
if self.is_queue_running:
proxy.run_queue()
self.message += "%d files added to top of playlist from directory '%s'. " % (count, dir[len(myroot)+1:])
else:
self.message += "Weird error -- no directory name given. "
def _do_advance(self):
"""toggle advance mode"""
if self.is_queue_running:
proxy.halt_queue()
else:
proxy.run_queue()
def _do_append(self):
"""add single file to bottom of playlist"""
proxy.append([Binary(self.file)])
self.message += "File '%s' appended to playlist. " % format_name(self.file)
def _do_chdir(self):
"""change current working directory"""
try:
if self.dir != myroot and os.path.islink(self.dir):
self.message += "For security reasons I will not follow symlinks. "
else:
entries = os.listdir(self.dir)
self.mypath = self.dir
except OSError:
self.message += "You do not have permission to access directory '%s'. " % (self.dir[len(myroot)+1:])
self.view = "files"
def _do_clear(self):
"""prepare confirmation page for clear playlist command"""
self.message += " "
self.dyn_content += '''<p> </p>
<p>Click <a href="clear2?@@params"><strong>here</strong></a> to confirm:
clear (remove all items from) playlist. </p>
<p> </p>
'''
def _do_clear2(self):
"""clear playlist"""
proxy.clear()
def _do_clearmemo(self):
"""prepare confirmation page for clear memo command"""
self.message += " "
self.dyn_content += '''<p> </p>
<p>Click <a href="clearmemo2?@@params"><strong>here</strong></a> to confirm:
clear MEMO (playlist '%s'). </p>
<p> </p>
''' % memo_file
def _do_clearmemo2(self):
"""clear memo"""
try:
file = open(memo_file, "w")
file.write('#EXTM3U\n')
file.close()
self.message += "MEMO cleared, playlist '%s' is now empty. " % memo_file
except IOError:
self.message += "can not access MEMO (playlist '%s'). " % memo_file
def _do_del_current(self):
"""stop current track, remove it from playlist and play next song, if any"""
current_track = proxy.current().data
if not current_track:
self.message += "There is currently no track playing that can be removed. "
else:
proxy.stop()
playlist = [i.data for i in proxy.list()]
del playlist[0]
proxy.replace([Binary(i) for i in playlist])
proxy.run_queue()
# wait a bit for moosicd...
time.sleep(0.05)
if self.is_paused:
proxy.pause()
def _do_deldup(self):
"""delete all duplicate entries in playlist"""
oldlist = [i.data for i in proxy.list()]
newlist = []
temp = {}
for track in oldlist:
if not temp.has_key(track):
temp[track]=None
newlist.append(track)
proxy.replace([Binary(i) for i in newlist])
self.message += "%d items deleted from playlist. " % (self.queue_length - proxy.queue_length())
def _do_exit(self):
"""write good-bye message and exit program"""
global end_flag, ignore_exit
if not ignore_exit:
self.message += 'Oh well. '
self.dyn_content += '''
<p> </p>
<p>Click <a href="exit2"><strong>here</strong></a> to exit moosicWebGUI (moosicd will keep running).</p>
<p> </p>
'''
else:
self.message += 'Exit requests are ignored, moosicWebGUI still running... '
def _do_exit2(self):
"""write good-bye message and exit program"""
global end_flag, ignore_exit
if not ignore_exit:
end_flag = True
self.dyn_content += '<br><h1>moosicWebGUI terminated (moosicd still running). Good-bye.</h1><br>'
else:
self.message += 'Exit requests are ignored, moosicWebGUI still running... '
def _do_files(self):
"""switch to file view mode"""
self.view = "files"
def _do_history(self):
"""swtitch to history view mode"""
self.view = "history"
def _do_index(self):
"""initial page"""
self.message += "Welcome to moosicWebGUI. "
def _do_license(self):
"""display license (file COPYING)"""
try:
license = open(os.path.join(mydir, "COPYING"),"r").read()
self.dyn_content += "<pre>\n" + license + "\n</pre>\n"
self.message += "Please respect the GPL. "
except IOError:
self.message += 'File COPYING seems to be missing. The <a href="http://www.fsf.org/">FSF</a> certainly has a copy...\n'
def _do_list(self):
"""display instructions for save playlist command"""
self.dyn_content += """
<p> </p>
<p>Save the next screen (opens in new window) with your browser's save command
to a file in directory '%s' or one of its subdirectories. The filename should have
the extension '.m3u'.</p>
<p>When done you might wish to re-scan the jukebox directory so your newly created
playlist file shows up in the 'load playlist from file' menu.</p>
<p>Click <a target="moosic2" href="list2?@@params"><strong>here</strong></a>
to proceed. </p>
<p> </p>
""" % myroot
self.message += "Please follow the instructions. "
def _do_list_memo(self):
"""show content of MEMO playlist"""
self.listPL(memo_file)
def _do_list_pl(self):
"""show content of playlist"""
self.listPL(self.file)
def _do_load(self):
"""display stored playlists"""
global playlists
content = ['<table class="menu" border="0" width="100%" cellspacing="0">\n']
content.append('<tr><th colspan="6" align="left">Stored playlists</th></tr>\n')
count = 0
for file in playlists:
content.append('<tr>')
content.append('<td class="%s">%s</td>\n' % (klass[count&1], format_name(file)))
content.append('<td class="%s"><a href="list_pl?@@params&file=%s">show content</a></td>\n' % (klass[count&1],urllib.quote(file)))
content.append('<td class="%s"><a href="load_pl?@@params&file=%s&lmode=replace">replace PL</a></td>\n' % (klass[count&1],urllib.quote(file)))
content.append('<td class="%s"><a href="load_pl?@@params&file=%s&lmode=mixin">mixin</a></td>\n' % (klass[count&1],urllib.quote(file)))
content.append('<td class="%s"><a href="load_pl?@@params&file=%s&lmode=prepend">prepend</a></td>\n' % (klass[count&1],urllib.quote(file)))
content.append('<td class="%s"><a href="load_pl?@@params&file=%s&lmode=append">append</a></td>' % (klass[count&1],urllib.quote(file)))
content.append('</tr>\n')
count += 1
if not playlists:
content.append('<tr><td colspan="5">(There are no stored playlists).</td></tr>\n')
content.append("</table>\n")
self.message += "Found %d stored playlists. " % len(playlists)
self.dyn_content = ''.join(content)
def _do_load_pl(self):
"""load playlist from file"""
if self.file:
try:
files = open(self.file).readlines()
except IOError:
self.message += "Can't open playlist file '%s'. " % self.file
return
count = 0
result = []
files = [string.strip(file) for file in files]
files = [file for file in files if file and file[:1] != '#']
for file in files:
if file_is_moosical(file) and string.find(file, "/.") < 0:
result.append(file)
count += 1
playlist = [i.data for i in proxy.list()]
if self.lmode == "mixin":
playlist = mixin(playlist, result)
msg = "%d files mixed into playlist " % count
elif self.lmode == "replace":
playlist = result
msg = "playlist replaced with %d files " % count
elif self.lmode == "prepend":
playlist = result + playlist
msg = "%d files prepended to playlist " % count
else:
playlist = playlist + result
msg = "%d files appended to playlist " % count
proxy.replace([Binary(i) for i in playlist])
self.message += msg + "from stored playlist '%s'. " % self.file
else:
self.message += "Weird error -- no filename name given. "
def _do_loop(self):
"""toggle loop mode"""
proxy.toggle_loop_mode()
def _do_main(self):
"""switch to main view"""
self.view = "standard"
def _do_manual(self):
"""help command: display module docstring"""
self.dyn_content += "<pre>\n" + __doc__ + "\n</pre>\n"
def _do_memo(self):
"""memorize current track"""
current_track = proxy.current().data
if not current_track:
self.message += "There is currently no track playing that can be memorized. "
else:
try:
file = open(memo_file, "a")
# seek end of file
file.seek(0,2)
except IOError:
self.message += "Can not access MEMO file '%s'. " % memo_file
return
display = current_track.split('/')
display = display[-1:]
file.write('#EXTINF:-1,%s\n' % display)
file.write("%s\n" % current_track)
file.close()
self.message += "Track '%s' added to memo file (%s). " % (current_track.replace('/', ' / '), memo_file)
def _do_mixin(self):
"""mix all files from directory tree into playlist"""
if self.dir:
dir = self.dir
#files = os.popen('find "%s" -type f -print' % dir).readlines()
files = getfiles(dir)
files.sort()
count = 0
result = []
for file in files:
file = string.strip(file)
if file_is_moosical(file) and string.find(file, "/.") < 0:
result.append(file)
count += 1
playlist = [i.data for i in proxy.list()]
playlist = mixin(playlist, result)
proxy.replace([Binary(i) for i in playlist])
self.message += "%d files mixed into playlist from directory '%s'. " % (count,dir[len(myroot)+1:])
else:
self.message += "Weird error -- no directory name given. "
def _do_moo(self):
"""moo command"""
self.message += ";-)"
self.dyn_content += "<pre>\n%s\n</pre>\n" % moo()
def _do_move_top(self):
"""move selected file to top of playlist"""
self.move_helper(-1)
def _do_move_bottom(self):
"""move selected file to bottom of playlist"""
self.move_helper(1)
def _do_pause(self):
"""toggle pause state"""
if self.is_paused:
proxy.unpause()
else:
proxy.pause()
def _do_play(self):
"""play command"""
proxy.run_queue()
proxy.unpause()
def _do_play_last(self):
"""add selected file to bottom of playlist"""
proxy.prepend([Binary(self.file)])
self.message += "Track '%s' appended to playlist. " % format_name(self.file)
def _do_play_next(self):
"""add selected file to top of playlist"""
proxy.prepend([Binary(self.file)])
self.message += "Playing next track '%s'. " % format_name(self.file)
def _do_play_now(self):
"""play immediately selected file"""
proxy.stop()
proxy.prepend([Binary(self.file)])
proxy.run_queue()
self.message += "Now playing track '%s'. " % format_name(self.file)
def _do_playlist(self):
"""switch to playlist view mode"""
self.view = "playlist"
def _do_prepend(self):
"""add selected file to top of playlist"""
proxy.prepend([Binary(self.file)])
self.message += "Track '%s' prepended to playlist. " % format_name(self.file)
def _do_refresh(self):
"""do nothing but refresh current page"""
pass
def _do_remove(self):
"""remove selected file from playlist"""
self.move_helper(0)
def _do_rescan(self):
"""rescan jukebox directory"""
global tree, playlists, parent, length
tree, playlists, parent = recurse(myroot, {}, [], {myroot : None})
tree, length, playlists = cleanup(tree, playlists)
dump_data()
self.message += '''Scan of jukebox directory '%s' completed. <br>
Found %d music files in %d directories and %d playlists. ''' % \
(myroot, length[myroot], len(tree), len(playlists))
def _do_reset_form(self):
"""clear search form"""
self.pattern=""
def _do_reverse(self):
"""reverse playlist"""
proxy.reverse()
def _do_search(self):
"""switch to search view mode"""
self.view="search"
def _do_shuffle(self):
"""randomize playlist order"""
oldlist = [i.data for i in proxy.list()]
newlist = []
while oldlist:
index = random.randint(0,len(oldlist)-1)
newlist.append(oldlist[index])
del oldlist[index]
proxy.replace([Binary(i) for i in newlist])
def _do_skip(self):
"""skip forward/backward a given number of tracks"""
if self.is_looping and not self.queue_length:
self.message += "The playlist is currently empty. "
elif self.count > 0:
self.next(self.count)
self.message += "Command 'skip(%s)' executed. " % (self.count)
elif self.count < 0:
self.previous(-self.count)
self.message += "Command 'skip(%s)' executed. " % (self.count)
else:
self.message += "Weird error -- no count given for skip. "
def _do_sort(self):
"""sort playlist"""
proxy.sort()
def _do_stop(self):
"""stop command"""
proxy.stop()
def _do_tree(self):
"""switch to tree view mode"""
self.view = "tree"
def _do_tskip(self):
"""
Skip forward or backward a given number of positions.
Take precaution if moosicd advanced one or more tracks
since the page that generated this request was generated.
"""
if self.count and self.file:
# stop forwarding in order no to mess things up
proxy.halt_queue()
count = self.count
file = self.file
if count > 0:
# seek new offset in case playlist changed
offset = self.offset_plist(count-1, file)
if offset >= 0:
self.next(offset+1)
self.message += "Skipped forward to track '%s'. " % format_name(file)
else:
self.message += """<font color="#880000">The requested track '%s' is not
available at the assumed position in the playlist and
seems to have been played recently. </font>""" % format_name(file)
elif count < 0:
# seek new offset in case check history changed
offset = self.offset_hist(-1-count, file)
if offset >= 0:
self.previous(offset+1)
self.message += "Skipped back to track '%s'. " % format_name(file)
else:
self.message += """<font color="#880000">The history buffer
is outdated. File '%s' is not available in the history. </font>""" % format_name(file)
else:
self.message += "No tracks skipped. How did you come here anyway? "
# start forwarding if it was previously enabled
if self.is_queue_running:
proxy.run_queue()
time.sleep(0.05)
else:
self.message += "Weird error -- no count or filename given for skip. "
#-------------------------------------------
def cont_standard(self):
"""prepare contents for standard view mode: playlist and history"""
playlist = [i.data for i in proxy.list()[:10]]
content = ['<table border="0" width="100%" cellspacing="0" cellpadding="0"><tr><td width="50%" valign="top">\n']
content.append('<table class="menu" border="0" width="100%" cellspacing="0">\n')
content.append('<tr><th colspan="2" align="left">Playlist</th></tr>\n')
i=1
for f in playlist:
content.append('<tr><td class="%s" valign="top" align="right">[%d] </td><td class="%s" width="95%%">%s</td></tr>\n' % (klass[i & 1], i, klass[i & 1], format_name("%s" % f)))
i += 1
if not playlist:
content.append('<tr><td colspan="2">(The playlist is currently empty.)</td></tr>\n')
content.append("</table>\n")
content.append('</td><td width="1%"> </td>\n')
history = proxy.history(10)
history.reverse()
content.append('<td width="49%" valign="top"><table class="menu" border="0" width="100%" cellspacing="0">\n')
content.append('<tr><th colspan="2" align="left">History</th></tr>\n')
i=-1
for f in history:
content.append('<tr><td class="%s" valign="top" align="right">[%d] </td><td class="%s" width="95%%">%s</td></tr>\n' % (klass[i & 1],i,klass[i & 1],format_name("%s" % f[0])))
i -=1
if not history:
content.append('<tr><td colspan="2">(The history buffer is currently empty.)</td></tr>\n')
content.append("</table>\n")
content.append("</td></tr></table>\n")
return ''.join(content)
def cont_history(self):
"""prepare contents for history view mode"""
history = proxy.history()
history.reverse()
content = ['<table class="menu" border="0" width="100%" cellspacing="0">\n']
content.append('<tr><th width="90%" align="left" valign="middle">History</th>\n')
content.append('<th align="right" valign="middle">%s</th><th valign="middle">@@cform</th></tr>\n' % (search_form % ("refresh", self.view, self.mypath, self.pattern,"search history")))
content.append("</table>\n")
content.append('<table class="menu" border="0" width="100%" cellspacing="0">\n')
i=-1
count = 0
files = [str(f[0]) for f in history]
looping = proxy.is_looping()
for f in files:
if match(f[len(myroot):], string.translate(self.pattern, xlat)):
content.append('<tr>')
content.append('<td class="%s" valign="top" align="right">[%d] </td>\n' % (klass[count & 1],i))
if looping:
content.append('<td colspan="5" class="%s" width="90%%" valign="top">%s</td>\n' % (klass[count & 1],format_name(f)))
else:
content.append('<td class="%s" width="60%%" valign="top">%s</td>\n' % (klass[count & 1],format_name(f)))
content.append('<td class="%s" valign="top"><a href="tskip?@@params&count=%d&file=%s">skip</a> </td>\n' % (klass[count & 1],i, urllib.quote(f)))
content.append('<td class="%s" valign="top"><a href="play_now?@@params&file=%s">play</a> </td>\n' % (klass[count & 1],urllib.quote(f)))