Debian Codegraph @

xl/trax/trackdb.py

raw
1 # Copyright (C) 2008-2010 Adam Olsen
2 #
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2, or (at your option)
6 # any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 #
17 #
18 # The developers of the Exaile media player hereby grant permission
19 # for non-GPL compatible GStreamer and Exaile plugins to be used and
20 # distributed together with GStreamer and Exaile. This permission is
21 # above and beyond the permissions granted by the GPL license by which
22 # Exaile is covered. If you modify this code, you may extend this
23 # exception to your version of the code, but you are not obligated to
24 # do so. If you do not wish to do so, delete this exception statement
25 # from your version.
26
27
28 from copy import deepcopy
29 import logging
30 from time import time
31 from typing import Dict, Iterable, Iterator, List, Optional, Tuple
32
33 from xl import common, event
34 from xl.nls import gettext as _
35 from xl.trax.track import Track
36
37 logger = logging.getLogger(__name__)
38
39
40 class TrackHolder:
41 def __init__(self, track, key, **kwargs):
42 self._track = track
43 self._key = key
44 self._attrs = kwargs
45
46 def __getattr__(self, attr):
47 return getattr(self._track, attr)
48
49
50 class TrackDBIterator:
51 def __init__(self, track_iterator: Iterator[Tuple[str, TrackHolder]]):
52 self.iter = track_iterator
53
54 def __iter__(self):
55 return self
56
57 def __next__(self):
58 return next(self.iter)[1]._track
59
60
61 class TrackDB:
62 """
63 Manages a track database.
64
65 Allows you to add, remove, retrieve, search, save and load
66 Track objects.
67
68 :param name: The name of this :class:`TrackDB`.
69 :param location: Path to a file where this :class:`TrackDB`
70 should be stored.
71 :param pickle_attrs: A list of attributes to store in the
72 pickled representation of this object. All
73 attributes listed must be built-in types, with
74 one exception: If the object contains the phrase
75 'tracks' in its name it may be a list or dict
76 of :class:`Track` objects.
77 :param load_first: Set to True if this collection should be
78 loaded before any tracks are created.
79 """
80
81 def __init__(
82 self,
83 name: str = "",
84 location: str = "",
85 pickle_attrs: List[str] = [],
86 loadfirst: bool = False,
87 ):
88 """
89 Sets up the trackDB.
90 """
91
92 # ensure that the DB is always loaded before any tracks are,
93 # otherwise internal values are not loaded and may be lost/corrupted
94 if loadfirst and Track._get_track_count() != 0:
95 raise RuntimeError(
96 (
97 "Internal error! %d tracks already loaded, "
98 + "TrackDB must be loaded first!"
99 )
100 % Track._get_track_count()
101 )
102
103 self.name = name
104 self.location = location
105 self._dirty = False
106 self.tracks: Dict[str, TrackHolder] = {} # key is URI of the track
107 self.pickle_attrs = pickle_attrs
108 self.pickle_attrs += ['tracks', 'name', '_key']
109 self._saving = False
110 #: Number to use for the next `tracks-*` database key
111 self._key = 0
112 self._dbversion = 2.0
113 self._deleted_keys = []
114 if location:
115 self.load_from_location()
116 self._timeout_save()
117
118 def __iter__(self):
119 """
120 Provide the ability to iterate over a TrackDB.
121 Just as with a dictionary, if tracks are added
122 or removed during iteration, iteration will halt
123 with a RuntimeError.
124 """
125 track_iterator = iter(self.tracks.items())
126 iterator = TrackDBIterator(track_iterator)
127 return iterator
128
129 def __len__(self):
130 """
131 Obtain a count of how many items are in the TrackDB
132 """
133 return len(self.tracks)
134
135 @common.glib_wait_seconds(300)
136 def _timeout_save(self):
137 """
138 Callback for auto-saving.
139 """
140 self.save_to_location()
141 return True
142
143 def set_name(self, name: str) -> None:
144 """
145 Sets the name of this :class:`TrackDB`
146
147 :param name: The new name.
148 """
149 self.name = name
150 self._dirty = True
151
152 def get_name(self) -> str:
153 """
154 Gets the name of this :class:`TrackDB`
155
156 :return: The name.
157 """
158 return self.name
159
160 def set_location(self, location: Optional[str]) -> None:
161 """
162 Sets the location to save to
163
164 :param location: the location to save to
165 """
166 self.location = location
167 self._dirty = True
168
169 @common.synchronized
170 def load_from_location(self, location: Optional[str] = None):
171 """
172 Restores :class:`TrackDB` state from the pickled representation
173 stored at the specified location.
174
175 :param location: the location to load the data from
176 """
177 if not location:
178 location = self.location
179 if not location:
180 raise AttributeError(
181 _("You did not specify a location to load the db from")
182 )
183
184 logger.debug("Loading %s DB from %s.", self.name, location)
185
186 pdata = common.open_shelf(location)
187
188 if "_dbversion" in pdata:
189 if int(pdata['_dbversion']) > int(self._dbversion):
190 raise common.VersionError("DB was created on a newer Exaile version.")
191 elif pdata['_dbversion'] < self._dbversion:
192 logger.info("Upgrading DB format....")
193 import shutil
194
195 shutil.copyfile(location, location + "-%s.bak" % pdata['_dbversion'])
196 import xl.migrations.database as dbmig
197
198 dbmig.handle_migration(
199 self, pdata, pdata['_dbversion'], self._dbversion
200 )
201
202 for attr in self.pickle_attrs:
203 try:
204 if 'tracks' == attr:
205 data = {}
206 for k in (x for x in pdata.keys() if x.startswith("tracks-")):
207 p = pdata[k]
208 tr = Track(_unpickles=p[0])
209 loc = tr.get_loc_for_io()
210 if loc not in data:
211 data[loc] = TrackHolder(tr, p[1], **p[2])
212 else:
213 logger.warning("Duplicate track found: %s", loc)
214 # presumably the second track was written because of an error,
215 # so use the first track found.
216 del pdata[k]
217
218 setattr(self, attr, data)
219 else:
220 setattr(self, attr, pdata.get(attr, getattr(self, attr)))
221 except Exception:
222 # FIXME: Do something about this
223 logger.exception("Exception occurred while loading %s", location)
224
225 pdata.close()
226
227 self._dirty = False
228
229 @common.synchronized
230 def save_to_location(self, location: Optional[str] = None):
231 """
232 Saves a pickled representation of this :class:`TrackDB` to the
233 specified location.
234
235 :param location: the location to save the data to
236 """
237 if not self._dirty:
238 for track in self.tracks.values():
239 if track._track._dirty:
240 self._dirty = True
241 break
242
243 if not self._dirty:
244 return
245
246 if not location:
247 location = self.location
248 if not location:
249 raise AttributeError(_("You did not specify a location to save the db"))
250
251 if self._saving:
252 return
253 self._saving = True
254
255 logger.debug("Saving %s DB to %s.", self.name, location)
256
257 try:
258 pdata = common.open_shelf(location)
259 if pdata.get('_dbversion', self._dbversion) > self._dbversion:
260 raise common.VersionError("DB was created on a newer Exaile.")
261 except Exception:
262 logger.exception("Failed to open music DB for writing.")
263 return
264
265 for attr in self.pickle_attrs:
266 # bad hack to allow saving of lists/dicts of Tracks
267 if 'tracks' == attr:
268 for k, track in self.tracks.items():
269 key = "tracks-%s" % track._key
270 if track._track._dirty or key not in pdata:
271 pdata[key] = (
272 track._track._pickles(),
273 track._key,
274 deepcopy(track._attrs),
275 )
276 else:
277 pdata[attr] = deepcopy(getattr(self, attr))
278
279 pdata['_dbversion'] = self._dbversion
280
281 for key in self._deleted_keys:
282 key = "tracks-%s" % key
283 if key in pdata:
284 del pdata[key]
285
286 pdata.sync()
287 pdata.close()
288
289 for track in self.tracks.values():
290 track._track._dirty = False
291
292 self._dirty = False
293 self._saving = False
294
295 def get_track_by_loc(self, loc: str) -> Optional[Track]:
296 """
297 returns the track having the given loc. if no such track exists,
298 returns None
299 """
300 try:
301 return self.tracks[loc]._track
302 except KeyError:
303 return None
304
305 def loc_is_member(self, loc: str) -> bool:
306 """
307 Returns True if loc is a track in this collection, False
308 if it is not
309 """
310 return loc in self.tracks
311
312 def get_count(self) -> int:
313 """
314 Returns the number of tracks stored in this database
315 """
316 return len(self.tracks)
317
318 def add(self, track: Track) -> None:
319 """
320 Adds a track to the database of tracks
321
322 :param track: The :class:`xl.trax.Track` to add
323 """
324 self.add_tracks([track])
325
326 @common.synchronized
327 def add_tracks(self, tracks: Iterable[Track]) -> None:
328 """
329 Like add(), but takes a list of :class:`xl.trax.Track`
330 """
331 locations = []
332 now = time()
333 for tr in tracks:
334 if not tr.get_tag_raw('__date_added'):
335 tr.set_tags(__date_added=now)
336 location = tr.get_loc_for_io()
337 # Don't add duplicates -- track URLs are unique
338 if location in self.tracks:
339 continue
340 # Don't add unsupported media files
341 if not tr.is_supported():
342 continue
343 locations += [location]
344 self.tracks[location] = TrackHolder(tr, self._key)
345 self._key += 1
346
347 if locations:
348 event.log_event('tracks_added', self, locations)
349 self._dirty = True
350
351 def remove(self, track: Track) -> None:
352 """
353 Removes a track from the database
354
355 :param track: the :class:`xl.trax.Track` to remove
356 """
357 self.remove_tracks([track])
358
359 @common.synchronized
360 def remove_tracks(self, tracks: Iterable[Track]) -> None:
361 """
362 Like remove(), but takes a list of :class:`xl.trax.Track`
363 """
364 locations = []
365
366 for tr in tracks:
367 location = tr.get_loc_for_io()
368 locations += [location]
369 self._deleted_keys.append(self.tracks[location]._key)
370 del self.tracks[location]
371
372 event.log_event('tracks_removed', self, locations)
373
374 self._dirty = True
375
376 def get_tracks(self) -> List[Track]:
377 return list(self)