-
Notifications
You must be signed in to change notification settings - Fork 0
/
steam_db.py
358 lines (297 loc) · 10.1 KB
/
steam_db.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
#!python
# -*- coding: iso-8859-1 -*-
# Steampunk DB
# Stores files and playlists
# Will start with json, enhance to real db
import eyeD3
import os
import json
import pyglet
import random
import time
# TODO: Create a player class
# TODO: Start using multi processing
class Song():
""" A single song
"""
def __init__(self, collection_path):
""" Init a song
@param collectionpath: The path containing the music collection
"""
self.collection_path = collection_path
self.meta = {}
self.source = None
self.player = None
def play(self):
""" Play the song
http://guzalexander.com/2012/08/17/playing-a-sound-with-python.html
"""
self.source = pyglet.media.load(os.path.join(self.collection_path, self.meta["Filename"]))
self.player = pyglet.media.Player()
self.player.queue(self.source)
self.player.play()
pyglet.app.run()
# on ubuntu install libavbin0
def stop(self):
""" Stop a Song
"""
print ("Stopping")
if not self.player is None:
self.player.stop()
def pause(self):
""" Pause a Song
"""
if not self.player is None:
self.player.pause()
def from_data(self, data):
""" Create a song from data
@param data: A dict in meta style
"""
self.meta = data
def from_file(self, filename):
""" Generate entry from a mp3 file
@param filename: The file name relative to the collection path
"""
fullname = os.path.join(self.collection_path, filename)
if eyeD3.isMp3File(fullname):
audioFile = eyeD3.Mp3AudioFile(fullname)
tag = audioFile.getTag()
if tag:
self.meta["Error"] = None
self.meta["Album"] = tag.getAlbum().encode("utf-8")
self.meta["Artist"] = tag.getArtist().encode("utf-8")
self.meta["DiscNum"] = tag.getDiscNum()[0]
self.meta["DiscNumMax"] = tag.getDiscNum()[1]
try:
if tag.getGenre():
self.meta["Genre"] = tag.getGenre().getName().encode("utf-8")
except eyeD3.tag.GenreException:
self.meta["Error"] = "Broken Genre"
pass # Genre string cannot be parsed with '^([A-Z 0-9+/\-\|!&'\.]+)([,;|][A-Z 0-9+/\-\|!&'\.]+)*$': Hörbuch für Kinder
self.meta["Title"] = tag.getTitle().encode("utf-8")
#self.meta["Images"] = tag.getImages()
self.meta["TrackNum"] = tag.getTrackNum()[0]
self.meta["TrackNumMax"] = tag.getTrackNum()[1]
#self.meta["Urls"] = tag.getURLs()
self.meta["Year"] = tag.getYear()
#self.meta["FileIDs"] = tag.getUniqueFileIDs()
self.meta["Filename"] = filename
def __str__(self):
""" Print the song
"""
res = ""
for key in self.meta:
res += "%s %s \n" %(key, self.meta[key])
return res
def get_data(self):
""" Return the meta data
"""
return self.meta
class Playlist():
""" A playlist of several songs
"""
def __init__(self, collection_path, album = None, pid = None):
"""
@param collection_path: Path where the whole collection is stored
@param pid: Playlist id
@param album: The album name as id. Collisions are possible !
"""
self.collection_path = collection_path
self.data = {"songs":[],
"album": album,
"pid": pid}
def get_pid(self):
""" Return Playlist ID
"""
return self.data["pid"]
def create_card(self):
""" Create a card
"""
# Todo Create and print a card
pass
def add_song(self, song):
""" Add a song
"""
self.data["songs"].append(song)
# TODO Sort titles in album by Track number
def load_from_data(self):
""" Load from db file
"""
# TODO: Maybe ? Load a playlist from data
pass
def get_data(self):
""" return data in playlist
"""
res = {"album": self.data["album"],
"pid": self.data["pid"],
"songs": []}
for song in self.data["songs"]:
res["songs"].append(song.get_data())
return res
def from_data(self, data):
""" Generate a playlist from dumped data
"""
self.data = {"album": data["album"],
"pid": data["pid"],
"songs":[]}
for s in data["songs"]:
news = Song(self.collection_path)
news.from_data(s)
self.add_song(news)
class Playlists():
""" All playlists available
"""
def __init__(self, collection_path, filename = None):
"""
@param collection_path: Path where the collection is stored
@param filename: Filename of the DB to store in
"""
self.collection_path = collection_path
self.playlists = {} # id:playlist
self.filename = filename
def load_from_file(self, filename=None):
""" Load playlists from json file
@param: Json db filename. If none, taken from the central object name
"""
if filename is None:
filename = self.filename
with open(filename) as fh:
data = json.load(fh)
for pl in data:
newpl = Playlist(self.collection_path)
newpl.from_data(pl)
self.playlists[newpl.get_pid()] = newpl
def save_to_file(self, filename = None):
""" Save Playlist to json file
@param,filename: Filename for the playlist. If None it is taken from playlist central
"""
if filename is None:
filename = self.filename
sdata = []
for pl in self.playlists:
sdata.append(self.playlists[pl].get_data())
with open(filename, "wt") as fh:
json.dump(sdata, fh, indent = 4)
def get_playlist_by_id(self, pid):
""" Get a playlist by id
@param pid: playlist id
"""
if pid in self.playlists:
return self.playlists[pid]
return None
def get_playlist_by_album(self, album):
""" Get playlist by album title
@param album: album name
"""
for pid in self.playlists:
pl = self.playlists[pid]
if pl.data["album"] == album:
return pl
return None
def generate_new_id(self):
""" Generate a new random, unused id
"""
# TODO: create track ID in 8 Byte style for punchcard holes
r = random.randint(0,10000)
while (self.get_playlist_by_id(r)):
r = random.randint(0,10000)
return r
def new_playlist(self, album = None):
""" Create a new playlist
@param album: Album that is the base for this playlist
"""
pid = self.generate_new_id()
p = Playlist(album = album, pid = pid)
self.playlists[pid] = p
p.album = album
return p
def album_playlist_from_song_db(self, songdb):
""" Take a song db and create all album playlists
@param songdb: The song database class. Albums will be extracted
"""
for song in songdb.db:
try:
al = song.meta["Album"]
except:
pass
else:
pl = self.get_playlist_by_album(al)
if not pl:
pl = self.new_playlist(album = al)
pl.add_song(song)
def __str__(self):
res = ""
res += "Playlists in db: %d" % len(self.playlists)
return res
class SongDB():
""" A List of all songs
"""
def __init__(self, basedir, filename, new = False):
"""
@param basedir: The dir of the collection
@param filename: The name of the json db
@param new: Create new db vs load
"""
self.filename = filename
self.basedir = basedir
if new:
self.db = self.create_new()
else:
self.db = self.load()
def load(self, filename=None):
""" Load song db from json file
@param filename: Filename for loading. If None it will be the central class filename
"""
res = []
if filename is None:
filename = self.filename
with open(filename) as fh:
data = json.load(fh)
for sdata in data:
s = Song(self.basedir)
s.from_data(sdata)
res.append(s)
return res
def create_new(self):
return []
def update_from_dir(self):
""" Update the current database from MP3 files in the directory
"""
for subdir, dirs, files in os.walk(self.basedir):
for file in files:
fullpath = os.path.join(subdir, file)
relpath = os.path.relpath(fullpath, self.basedir)
s = Song(self.basedir)
s.from_file(relpath)
self.db.append(s)
print (len(self.db))
def save(self, filename=None):
""" Save playlist to json file
@param filename: Filename for the db. If None, it will be the central class name
"""
if filename is None:
filename = self.filename
data = []
for asong in self.db:
data.append(asong.get_data())
with open(filename, "wt") as fh:
json.dump(data, fh, indent = 4)
def __str__(self):
res = ""
res += str(len(self.db))
return res
if __name__ == "__main__":
sdb = SongDB("/home/thorsten/Musik", "test.json", False)
print (sdb)
song = sdb.db[0]
song.play()
time.sleep(2)
song.stop()
#sdb.update_from_dir()
#sdb.save()
#sdb.cards()
#p = Playlists("/home/thorsten/Musik", filename="playlist.json")
#p.album_playlist_from_song_db(sdb)
#p.load_from_file()
#print(p)
#p.save_to_file()