playlists.py
delete(name)
¶
Delete playlist, including m3u file.
Source code in mps_youtube/playlists.py
def delete(name):
""" Delete playlist, including m3u file. """
del g.userpl[name]
os.remove(os.path.join(g.PLFOLDER, name + '.m3u'))
load()
¶
Open playlists. Called once on script invocation.
Source code in mps_youtube/playlists.py
def load():
""" Open playlists. Called once on script invocation. """
_convert_playlist_to_v2()
_convert_playlist_to_m3u()
try:
# Loop through all files ending in '.m3u'
for m3u in [m3u for m3u in os.listdir(g.PLFOLDER) if m3u[-4:] == '.m3u']:
g.userpl[m3u[:-4]] = read_m3u(os.path.join(g.PLFOLDER, m3u))
except FileNotFoundError:
# No playlist folder, create an empty one
if not os.path.isdir(g.PLFOLDER):
g.userpl = {}
os.mkdir(g.PLFOLDER)
save()
# remove any cached urls from playlist file, these are now
# stored in a separate cache file
do_save = False
for k, v in g.userpl.items():
for song in v.songs:
if hasattr(song, "urls"):
util.dbg("remove %s: %s", k, song.urls)
del song.urls
do_save = True
if do_save:
save()
read_m3u(m3u)
¶
Processes an m3u file into a Playlist object.
Source code in mps_youtube/playlists.py
def read_m3u(m3u):
""" Processes an m3u file into a Playlist object. """
name = os.path.basename(m3u)[:-4]
songs = []
expect_ytid = False
with open(m3u, 'r') as plf:
if plf.readline().startswith('#EXTM3U'):
for line in plf:
if line.startswith('#EXTINF:') and not expect_ytid:
duration, title = line.replace('#EXTINF:', '').strip().split(',', 1)
expect_ytid = True
elif not line.startswith('\n') and not line.startswith('#') and expect_ytid:
try:
expect_ytid = False
ytid = pafy.extract_video_id(line).strip()
songs.append(Video(ytid, title, int(duration)))
except ValueError as ex:
util.dbg(c.r + str(ex) + c.w)
# Handles a simple m3u file which should just be a list of urls
else:
plf.seek(0)
for line in plf:
if not line.startswith('#'):
try:
p = util.get_pafy(line)
songs.append(Video(p.videoid, p.title, p.length))
except (IOError, ValueError) as e:
util.dbg(c.r + "Error loading video: " + str(e) + c.w)
return Playlist(name, songs)
save()
¶
Save playlists. Called each time a playlist is saved or deleted.
Source code in mps_youtube/playlists.py
def save():
""" Save playlists. Called each time a playlist is saved or deleted. """
for pl in g.userpl:
with open(os.path.join(g.PLFOLDER, pl+'.m3u'), 'w') as plf:
plf.write('#EXTM3U\n\n')
for song in g.userpl[pl].songs:
plf.write('#EXTINF:%d,%s\n' % (song.length, song.title))
plf.write('https://www.youtube.com/watch?v=%s\n' % song.ytid)
util.dbg(c.r + "Playlist saved\n---" + c.w)