forked from mps-youtube/yewtube
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmpsyt
More file actions
executable file
·2942 lines (2134 loc) · 84.2 KB
/
mpsyt
File metadata and controls
executable file
·2942 lines (2134 loc) · 84.2 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
"""
mps-youtube.
https://github.com/np1/mps-youtube
Copyright (C) 2014 nagev
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from __future__ import print_function
from math import ceil
__version__ = "0.01.38"
__author__ = "nagev"
__license__ = "GPLv3"
import unicodedata
import collections
import subprocess
import threading
import tempfile
import logging
import random
import locale
import socket
import time
import pafy
import json
import sys
import re
import os
try:
# pylint: disable=F0401
from colorama import init as init_colorama, Fore, Style
has_colorama = True
except ImportError:
has_colorama = False
try:
import readline
readline.set_history_length(2000)
has_readline = True
except ImportError:
has_readline = False
# Python 3 compatibility hack
if sys.version_info[:2] >= (3, 0):
# pylint: disable=E0611,F0401
import pickle
from urllib.request import build_opener
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
py2utf8_encode = lambda x: x
py2utf8_decode = lambda x: x
compat_input = input
else:
from urllib2 import build_opener, HTTPError, URLError
import cPickle as pickle
from urllib import urlencode
py2utf8_encode = lambda x: x.encode("utf8")
py2utf8_decode = lambda x: x.decode("utf8")
compat_input = raw_input
mswin = os.name == "nt"
non_utf8 = mswin or not "UTF-8" in os.environ.get("LANG", "")
member_var = lambda x: not(x.startswith("__") or callable(x))
locale.setlocale(locale.LC_ALL, "") # for date formatting
def non_utf8_encode(txt):
""" Encoding for non UTF8 environments. """
if non_utf8:
sse = sys.stdout.encoding
txt = txt.encode(sse, "replace").decode("utf8", "ignore")
return txt
def mswinfn(filename):
""" Fix filename for Windows. """
if mswin:
filename = non_utf8_encode(filename)
allowed = re.compile(r'[^\\/?*$\'"%&:<>|]')
filename = "".join(x if allowed.match(x) else "_" for x in filename)
return filename
def get_default_ddir():
""" Get system default Download directory, append mps dir. """
user_home = os.path.expanduser("~")
join, exists = os.path.join, os.path.exists
if mswin:
return join(user_home, "Downloads", "mps")
USER_DIRS = join(user_home, ".config", "user-dirs.dirs")
DOWNLOAD_HOME = join(user_home, "Downloads")
# define ddir by (1) env var, (2) user-dirs.dirs file,
# (3) existing ~/Downloads dir (4) ~
if 'XDG_DOWNLOAD_DIR' in os.environ:
ddir = os.environ['XDG_DOWNLOAD_DIR']
elif exists(USER_DIRS):
lines = open(USER_DIRS).readlines()
defn = [x for x in lines if x.startswith("XDG_DOWNLOAD_DIR")]
if len(defn) == 1:
ddir = defn[0].split("=")[1].replace('"', '')
ddir = ddir.replace("$HOME", user_home).strip()
else:
ddir = DOWNLOAD_HOME if exists(DOWNLOAD_HOME) else user_home
else:
ddir = DOWNLOAD_HOME if exists(DOWNLOAD_HOME) else user_home
ddir = py2utf8_decode(ddir)
return os.path.join(ddir, "mps")
def get_config_dir():
""" Get user's configuration directory. Migrate to new mps name if old."""
if mswin:
confdir = os.environ["APPDATA"]
elif 'XDG_CONFIG_HOME' in os.environ:
confdir = os.environ['XDG_CONFIG_HOME']
else:
confdir = os.path.join(os.path.expanduser("~"), '.config')
mps_confdir = os.path.join(confdir, "mps-youtube")
old_confdir = os.path.join(confdir, "pms-youtube")
if os.path.exists(old_confdir) and not os.path.exists(mps_confdir):
os.rename(old_confdir, mps_confdir)
elif not os.path.exists(mps_confdir):
os.makedirs(mps_confdir)
return mps_confdir
class Video(object):
""" Class to represent a YouTube video. """
def __init__(self, ytid=None, title=None, length=None):
self.ytid = ytid
self.title = title
self.length = int(length)
self.urls = dict(v={}, a={})
def is_valid(video):
""" Check with Video object has unexpired links. """
last = video.urls['v'].get("last") # 'v' and 'a' are fetched together
valid = last and time.time() < last + g.expiry
return valid
def reset_video(video):
""" Clear url data of a Video object. """
video.urls["v"]["last"] = 0
video.urls["v"]["url"] = ""
video.urls["a"]["last"] = 0
video.urls["a"]["url"] = ""
def populate_video(video, callback=None):
""" Populate Video object with pafy data. Fetches new Pafy object. """
nullf = lambda x: None
callback = callback if callback else nullf
callback("Fetching video...")
try:
dbg(" - pafy fetch for %s", video.title)
g.pafs[video.ytid] = pafy.new(video.ytid, callback=callback)
p = g.pafs[video.ytid]
except (ValueError, IndexError):
raise IOError("Can't fetch this stream")
while len(g.pafs) > g.max_pafy_objects:
g.pafs.popitem(last=False) # store maximum 500 objects
v = p.getbest()
preftype = "ogg" if Config.PLAYER == "mplayer" else "m4a"
strict = Config.PLAYER == "mplayer"
a = p.getbestaudio(preftype=preftype, ftypestrict=strict)
video.urls['v'] = dict(url=v.url, last=time.time(), ext=v.extension)
if a: # audio streams may not be available
video.urls['a'] = dict(url=a.url, last=time.time(), ext=a.extension)
def get_streams(video, force=False, future=False):
""" Check a video is valid, if not fetch new data. Return video. """
if force or not is_valid(video):
nullf = lambda x: None
callback = nullf if future else writestatus
populate_video(video, callback=callback)
return video
def get_content_length(url):
""" Return content length of a url. """
dbg("getting content-length header")
response = g.urlopen(url)
headers = response.headers
cl = headers['content-length']
return int(cl)
def get_pafy(video):
""" Get valid pafy object for song. """
p = g.pafs.get(video.ytid) # try to get pafy object from memory
if not p or not is_valid(video):
# fetch new pafy object if links expired or no pafy available
populate_video(video)
return g.pafs.get(video.ytid)
def get_size(video, is_video):
""" Get size of item. Store it in Video object. """
key = "v" if is_video else "a"
size = video.urls[key].get('size')
if size:
pass
elif not is_valid(video):
populate_video(video)
if is_video:
size = g.pafs[video.ytid].getbest().get_filesize()
else:
preftype = "ogg" if Config.PLAYER == "mplayer" else "m4a"
strict = Config.PLAYER == "mplayer"
a = g.pafs[video.ytid].getbestaudio(preftype=preftype,
ftypestrict=strict)
size = a.get_filesize() if a else 0
else:
url = video.urls[key].get("url")
try:
size = get_content_length(url) if url else 0
except HTTPError:
size = 0
video.urls[key]['size'] = size
return size
class Config(object):
""" Holds various configuration values. """
PLAYER = "mplayer"
PLAYERARGS = "-nolirc -prefer-ipv4 -really-quiet".split()
COLOURS = False if mswin and not has_colorama else True
CHECKUPDATE = True
SHOW_MPLAYER_KEYS = True
FULLSCREEN = False
SHOW_STATUS = True
DDIR = get_default_ddir()
SHOW_VIDEO = False
SEARCH_MUSIC = True
class Playlist(object):
""" Representation of a playist, has list of songs. """
def __init__(self, name=None, songs=None):
self.name = name
self.creation = time.time()
self.songs = songs or []
@property
def is_empty(self):
""" Return True / False if songs are populated or not. """
return bool(not self.songs)
@property
def size(self):
""" Return number of tracks. """
return len(self.songs)
@property
def duration(self):
""" Sum duration of the playlist. """
duration = sum(s.length for s in self.songs)
duration = time.strftime('%H:%M:%S', time.gmtime(int(duration)))
return duration
class g(object):
""" Class for holding globals that are needed throught the module. """
command_line = False
debug_mode = False
urlopen = None
ytpls = []
browse_mode = "normal"
preloading = []
expiry = 5 * 60 * 60 # 5 hours
blank_text = "\n" * 200
helptext = []
max_results = 19
max_retries = 3
max_pafy_objects = 500
url_memo = {}
model = Playlist(name="model")
last_search_query = {}
current_page = 1
active = Playlist(name="active")
noblank = False
text = {}
userpl = {}
ytpl = {}
pafs = collections.OrderedDict()
last_opened = message = content = ""
config = [x for x in sorted(dir(Config)) if member_var(x)]
configbool = [x for x in config if type(getattr(Config, x)) is bool]
defaults = {setting: getattr(Config, setting) for setting in config}
suffix = "3" if sys.version_info[:2] >= (3, 0) else ""
CFFILE = os.path.join(get_config_dir(), "config")
OLD_PLFILE = os.path.join(get_config_dir(), "playlist" + suffix)
PLFILE = os.path.join(get_config_dir(), "playlist_v2")
READLINE_FILE = None
playerargs_defaults = {
"mpv": {"def": "--really-quiet".split(),
"title": "--title",
"fs": "--fs",
"novid": "--no-video",
"ignidx": "--demuxer-lavf-o=fflags=+ignidx".split()
},
"mplayer": {"def": ("-prefer-ipv4 -nolirc -really-quiet").split(),
"title": "-title",
"fs": "-fs",
"novid": "-novideo",
#"ignidx": "-lavfdopts o=fflags=+ignidx".split()
"ignidx": [],
}
}
def get_version_info():
""" Return version and platform info. """
import platform
out = ("\nmpsyt version : %s " % __version__)
out += ("\npafy version : %s" % pafy.__version__)
out += ("\nPython version : %s" % sys.version)
out += ("\nProcessor : %s" % platform.processor())
out += ("\nMachine type : %s" % platform.machine())
out += ("\nArchitecture : %s, %s" % platform.architecture())
out += ("\nPlatform : %s" % platform.platform())
return out
def process_cl_args(args):
""" Process command line arguments. """
if "--version" in args:
print(get_version_info())
print("")
sys.exit()
if "--help" in args:
for x in g.helptext:
print(x[2])
sys.exit()
g.command_line = "playurl" in args or "dlurl" in args
g.blank_text = "" if g.command_line else g.blank_text
def init():
""" Initial setup. """
init_text()
init_readline()
init_opener()
if not has_config() and has_exefile("mpv"):
Config.PLAYER = "mpv"
set_playerargs(default=True)
saveconfig()
else:
import_config()
# setup colorama
if has_colorama and mswin:
init_colorama()
process_cl_args(sys.argv)
def init_readline():
""" Enable readline for input history. """
if g.command_line:
return
if has_readline:
g.READLINE_FILE = os.path.join(get_config_dir(), "input_history")
if os.path.exists(g.READLINE_FILE):
readline.read_history_file(g.READLINE_FILE)
dbg("Read history file")
def init_opener():
""" Set up url opener. """
opener = build_opener()
ua = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; "
ua += "Trident/5.0)"
opener.addheaders = [("User-Agent", ua)]
g.urlopen = opener.open
def set_playerargs(playername=None, default=True):
""" Set default arguments for player. """
if not playername:
playername = Config.PLAYER
gpd = g.playerargs_defaults
for player in gpd:
# set player defaults
if player in playername and default:
Config.PLAYERARGS = gpd[player]["def"]
# set fullscreen
fsarg = gpd[player]["fs"]
if player in playername:
if Config.FULLSCREEN:
if not fsarg in Config.PLAYERARGS:
Config.PLAYERARGS.append(fsarg)
else:
if fsarg in Config.PLAYERARGS:
Config.PLAYERARGS.pop(Config.PLAYERARGS.index(fsarg))
break
else:
Config.PLAYERARGS = []
def has_config():
""" Check whether config file has been saved before. """
return os.path.exists(g.CFFILE)
def has_known_player():
""" Return true if the set player is known. """
for allowed_player in g.playerargs_defaults:
regex = r'(?:^%s$)|(?:\b%s$)' % ((allowed_player,) * 2)
match = re.search(regex, Config.PLAYER)
if mswin:
match = re.search(regex, Config.PLAYER, re.IGNORECASE)
if match:
return True
return False
def has_exefile(filename):
""" Check whether file exists in path and is executable. """
paths = os.environ.get("PATH", []).split(os.pathsep)
dbg("searching path for %s", filename)
for path in paths:
exepath = os.path.join(path, filename)
if os.path.exists(exepath):
if os.path.isfile(exepath):
if os.access(exepath, os.X_OK):
dbg("found at %s", exepath)
return exepath
return False
def showconfig(_):
""" Dump config data. """
s = " %s%-17s%s : %s\n"
out = " %s%-17s %s%s%s\n" % (c.ul, "Key", "Value", " " * 40, c.w)
for setting in g.config:
val = getattr(Config, setting)
# don't show playerargs as a list
if setting == "PLAYERARGS":
val = " ".join(val)
# don't show fullscreen if unknown player
if not has_known_player() and setting == "FULLSCREEN":
continue
out += s % (c.g, setting.lower(), c.w, val)
g.content = out
g.message = "Enter %sset <key> <value>%s to change\n" % (c.g, c.w)
g.message += "Enter %sset all default%s to reset all" % (c.g, c.w)
def saveconfig():
""" Save current config to file. """
config = {setting: getattr(Config, setting) for setting in g.config}
pickle.dump(config, open(g.CFFILE, "wb"), protocol=2)
def import_config():
""" Override config if config file exists. """
if os.path.exists(g.CFFILE):
saved_config = pickle.load(open(g.CFFILE, "rb"))
for k, v in saved_config.items():
setattr(Config, k, v)
# Update config files from versions <= 0.01.08
# pylint: disable=E1103
if type(Config.PLAYERARGS) == str:
Config.PLAYERARGS = Config.PLAYERARGS.split(" ")
saveconfig()
class c(object):
""" Class for holding colour code values. """
if mswin and has_colorama:
white = Style.RESET_ALL
ul = Style.DIM + Fore.YELLOW
red, green, yellow = Fore.RED, Fore.GREEN, Fore.YELLOW
blue, pink = Fore.CYAN, Fore.MAGENTA
elif mswin:
Config.COLOURS = False
else:
white = "\x1b[%sm" % 0
ul = "\x1b[%sm" * 3 % (2, 4, 33)
cols = ["\x1b[%sm" % n for n in range(91, 96)]
red, green, yellow, blue, pink = cols
if not Config.COLOURS:
ul = red = green = yellow = blue = pink = white = ""
r, g, y, b, p, w = red, green, yellow, blue, pink, white
def setconfig(key, val):
""" Set configuration variable. """
# pylint: disable=R0912
success_msg = fail_msg = ""
key = key.upper()
val_orig = val
val = val.upper()
TRUE = (Config, key, True)
FALSE = (Config, key, False)
falses = "0 FALSE OFF NO".split()
# set all default
if key == "ALL" and val == "DEFAULT":
for k, v in g.defaults.items():
setattr(Config, k, v)
success_msg = "Default configuration reinstated"
elif key == "PLAYER" and val == "DEFAULT":
player = "mpv" if has_exefile("mpv") else g.defaults['PLAYER']
setattr(Config, key, player)
set_playerargs()
success_msg = "PLAYER has been set to %s" % val
elif key == "COLOURS" and mswin and not has_colorama:
fail_msg = "Can't enable colours, colorama not found"
elif key == "PLAYER":
setattr(Config, key, val_orig)
set_playerargs(default=True)
success_msg = "PLAYER has been set to %s" % val_orig
elif key == "PLAYERARGS" and not val == "DEFAULT":
setattr(Config, key, val_orig.split())
success_msg = "PLAYERARGS set to %s" % val_orig
elif key == "PLAYERARGS" and val == "DEFAULT":
set_playerargs(default=True)
success_msg = "PLAYERARGS set to %s" % val
elif key == "FULLSCREEN" and not has_known_player():
fail_msg = "Unknown player %s, set fullscreen manually."
fail_msg = fail_msg % Config.PLAYER
elif key == "FULLSCREEN" and val == "DEFAULT":
setattr(*FALSE)
set_playerargs()
success_msg = "FULLSCREEN set to disabled (default)"
elif key == "DDIR" and not val == "DEFAULT":
valid = os.path.exists(val_orig) and os.path.isdir(val_orig)
if valid:
setattr(Config, key, val_orig)
success_msg = "Downloads will be saved to %s%s%s"
success_msg = success_msg % (c.y, val_orig, c.w)
else:
fail_msg = "Invalid path: %s%s%s" % (c.r, val, c.w)
elif key in g.configbool and not val == "DEFAULT":
boolval = val not in falses
if key == "FULLSCREEN":
if boolval:
setattr(*TRUE)
else:
setattr(*FALSE)
set_playerargs(default=False)
success_msg = "FULLSCREEN set to %s" % boolval
elif not boolval:
setattr(*FALSE)
success_msg = "%s set to disabled (restart may be required)" % key
else:
setattr(*TRUE)
success_msg = "%s set to enabled (restart may be required)" % key
elif key in g.configbool and val == "DEFAULT":
boolval = val not in falses
setattr(Config, key, boolval)
success_msg = "%s set to %s (restart may be required)" % (key, boolval)
elif key in g.config:
if val == "DEFAULT":
val = g.defaults[key]
if key == "FULLSCREEN":
set_playerargs(default=False)
setattr(Config, key, val)
success_msg = "%s has been set to %s" % (key.upper(), val)
else:
fail_msg = "Unknown config item: %s%s%s" % (c.r, key, c.w)
showconfig(1)
if success_msg:
saveconfig()
g.message = success_msg
elif fail_msg:
g.message = fail_msg
def F(key, nb=0, na=0, percent=r"\*", nums=r"\*\*", textlib=None):
"""Format text.
nb, na indicate newlines before and after to return
percent is the delimter for %s
nums is the delimiter for the str.format command (**1 will become {1})
textlib is the dictionary to use (defaults to g.text if not given)
"""
textlib = textlib or g.text
assert key in textlib
text = textlib[key]
percent_fmt = textlib.get(key + "_")
number_fmt = textlib.get("_" + key)
if number_fmt:
text = re.sub(r"(%s(\d))" % nums, "{\\2}", text)
text = text.format(*number_fmt)
if percent_fmt:
text = re.sub(r"%s" % percent, r"%s", text)
text = text % percent_fmt
text = re.sub(r"&&", r"%s", text)
return "\n" * nb + text + c.w + "\n" * na
def init_text():
""" Set up text. """
g.text = {
"exitmsg": ("**0mps-youtube - **1https://github.com/np1/mps-youtube**0"
"\nReleased under the GPLv3 license\n"
"(c) 2014 nagev**2\n"""),
"_exitmsg": (c.r, c.b, c.w),
# Error / Warning messages
'no playlists': "*No saved playlists found!*",
'no playlists_': (c.r, c.w),
'pl bad name': '*&&* is not valid a valid name. Ensure it starts with'
' a letter or _',
'pl bad name_': (c.r, c.w),
'pl not found': 'Playlist *&&* unknown. Saved playlists are shown '
'above',
'pl not found_': (c.r, c.w),
'pl not found advise ls': 'Playlist "*&&*" not found. Use *ls* to '
'list',
'pl not found advise ls_': (c.y, c.w, c.g, c.w),
'pl empty': 'Playlist is empty!',
'advise add': 'Use *add N* to add a track',
'advise add_': (c.g, c.w),
'advise search': 'Search for items and then use *add* to add them',
'advise search_': (c.g, c.w),
'no data': 'Error fetching data. Possible network issue.'
'\n*&&*',
'no data_': (c.r, c.w),
'use dot': 'Start your query with a *.* to perform a search',
'use dot_': (c.g, c.w),
'cant get track': 'Problem fetching this item: *&&*',
'cant get track_': (c.r, c.w),
'track unresolved': 'Sorry, this track is not available',
'no player': '*&&* was not found on this system',
'no player_': (c.y, c.w),
'no pl match for rename': '*Couldn\'t find matching playlist to '
'rename*',
'no pl match for rename_': (c.r, c.w),
'invalid range': "*Invalid item / range entered!*",
'invalid range_': (c.r, c.w),
'-audio': "*Warning* - the filetype you selected (m4v) has no audio!",
'-audio_': (c.y, c.w),
# Info messages
'select mux': ("Select [*&&*] to mux audio or [*Enter*] to download "
"without audio\nThis feature is experimental!"),
'select mux_': (c.y, c.w, c.y, c.w),
'pl renamed': 'Playlist *&&* renamed to *&&*',
'pl renamed_': (c.y, c.w, c.y, c.w),
'pl saved': 'Playlist saved as *&&*. Use *ls* to list playlists',
'pl saved_': (c.y, c.w, c.g, c.w),
'pl loaded': 'Loaded playlist *&&* as current playlist',
'pl loaded_': (c.y, c.w),
'pl viewed': 'Showing playlist *&&*',
'pl viewed_': (c.y, c.w),
'pl help': 'Enter *open <name or ID>* to load a playlist',
'pl help_': (c.g, c.w),
'added to pl': '*&&* tracks added (*&&* total [*&&*]). Use *vp* to '
'view',
'added to pl_': (c.y, c.w, c.y, c.w, c.y, c.w, c.g, c.w),
'added to saved pl': '*&&* tracks added to *&&* (*&&* total [*&&*])',
'added to saved pl_': (c.y, c.w, c.y, c.w, c.y, c.w, c.y, c.w),
'song move': 'Moved *&&* to position *&&*',
'song move_': (c.y, c.w, c.y, c.w),
'song sw': ("Switched item *&&* with *&&*"),
'song sw_': (c.y, c.w, c.y, c.w),
'current pl': "This is the current playlist. Use *save <name>* to save"
" it",
'current pl_': (c.g, c.w),
'help topic': (" Enter *help <topic>* for specific help:"),
'help topic_': (c.y, c.w),
'songs rm': '*&&* tracks removed &&',
'songs rm_': (c.y, c.w)}
def save_to_file():
""" Save playlists. Called each time a playlist is saved or deleted. """
f = open(g.PLFILE, "wb")
pickle.dump(g.userpl, f, protocol=2)
dbg("Playlist saved\n---")
def open_from_file():
""" Open playlists. Called once on script invocation. """
try:
with open(g.PLFILE, "rb") as plf:
g.userpl = pickle.load(plf)
except IOError:
# no playlist found, create a blank one
if not os.path.isfile(g.PLFILE):
g.userpl = {}
save_to_file()
def convert_playlist_to_v2():
""" Convert previous playlist file to v2 playlist. """
# skip if previously done
if os.path.isfile(g.PLFILE):
return
# skip if no playlist files exist
elif not os.path.isfile(g.OLD_PLFILE):
return
try:
with open(g.OLD_PLFILE, "rb") as plf:
old_playlists = pickle.load(plf)
except IOError:
sys.exit("Couldn't open old playlist file")
#rename old playlist file
backup = g.OLD_PLFILE + "_v1_backup"
if os.path.isfile(backup):
sys.exit("Error, backup exists but new playlist exists not!")
os.rename(g.OLD_PLFILE, backup)
# do the conversion
for plname, plitem in old_playlists.items():
songs = []
for video in plitem.songs:
v = Video(video['link'], video['title'], video['duration'])
songs.append(v)
g.userpl[plname] = Playlist(plname, songs)
# save as v2
save_to_file()
def logo(col=None, version=""):
""" Return text logo. """
col = col if col else random.choice((c.g, c.r, c.y, c.b, c.p, c.w))
LOGO = col + ("""\
88888b.d88b. 88888b. .d8888b
888 "888 "88b 888 "88b 88K
888 888 888 888 888 "Y8888b.
888 888 888 888 d88P X88
888 888 888 88888P" 88888P'
888
888 %s%s
888%s%s"""
% (c.w + "v" + version + " (YouTube)" if version else "",
col, c.w, "\n\n"))
return LOGO + c.w
def playlists_display():
""" Produce a list of all playlists. """
if not g.userpl:
g.message = F("no playlists")
return logo(c.y) + "\n\n" if g.model.is_empty else \
generate_songlist_display()
maxname = max(len(a) for a in g.userpl)
out = " {0}Saved Playlists{1}\n".format(c.ul, c.w)
start = " "
fmt = "%s%s%-3s %-" + str(maxname + 3) + "s%s %s%-7s%s %-5s%s"
head = (start, c.b, "ID", "Name", c.b, c.b, "Count", c.b, "Duration", c.w)
out += "\n" + fmt % head + "\n\n"
for v, z in enumerate(sorted(g.userpl)):
n, p = z, g.userpl[z]
l = fmt % (start, c.g, v + 1, n, c.w, c.y, str(p.size), c.y,
p.duration, c.w) + "\n"
out += l
return out
def mplayer_help(short=True):
""" Mplayer help. """
volume = "[{0}9{1}] volume [{0}0{1}]"
volume = volume if short else volume + " [{0}ctrl-c{1}] return"
seek = u"[{0}\u2190{1}] seek [{0}\u2192{1}]"
pause = u"[{0}\u2193{1}] SEEK [{0}\u2191{1}] [{0}space{1}] pause"
if non_utf8:
seek = "[{0}<-{1}] seek [{0}->{1}]"
pause = "[{0}DN{1}] SEEK [{0}UP{1}] [{0}space{1}] pause"
ret = "[{0}q{1}] %s" % ("return" if short else "next track")
fmt = " %-20s %-20s"
lines = fmt % (seek, volume) + "\n" + fmt % (pause, ret)
return lines.format(c.g, c.w)
def fmt_time(seconds):
""" Format number of seconds to %H:%M:%S. """
hms = time.strftime('%H:%M:%S', time.gmtime(int(seconds)))
H, M, S = hms.split(":")
if H == "00":
hms = M + ":" + S
elif H == "01" and int(M) < 40:
hms = str(int(M) + 60) + ":" + S
elif H.startswith("0"):
hms = ":".join([H[1], M, S])
return hms
def get_tracks_from_json(jsons):
""" Get search results from web page. """
try:
items = jsons['data']['items']
except KeyError:
items = []
songs = []
for item in items:
cursong = Video(ytid=item['id'], title=item['title'].strip(),
length=int(item['duration']))
songs.append(cursong)
if not items:
dbg("got unexpected data or no search results")
return False