trackma 0.4__py2.7.egg

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. EGG-INFO/PKG-INFO +19 -0
  2. EGG-INFO/SOURCES.txt +35 -0
  3. EGG-INFO/dependency_links.txt +1 -0
  4. EGG-INFO/entry_points.txt +8 -0
  5. EGG-INFO/not-zip-safe +1 -0
  6. EGG-INFO/requires.txt +10 -0
  7. EGG-INFO/top_level.txt +1 -0
  8. trackma/__init__.py +0 -0
  9. trackma/__init__.pyc +0 -0
  10. trackma/accounts.py +110 -0
  11. trackma/accounts.pyc +0 -0
  12. trackma/data/anilist.jpg +0 -0
  13. trackma/data/hb.jpg +0 -0
  14. trackma/data/icon.png +0 -0
  15. trackma/data/mal.jpg +0 -0
  16. trackma/data/melative.jpg +0 -0
  17. trackma/data/vndb.jpg +0 -0
  18. trackma/data.py +585 -0
  19. trackma/data.pyc +0 -0
  20. trackma/engine.py +742 -0
  21. trackma/engine.pyc +0 -0
  22. trackma/extras/AnimeInfoExtractor.py +308 -0
  23. trackma/extras/AnimeInfoExtractor.pyc +0 -0
  24. trackma/extras/__init__.py +0 -0
  25. trackma/extras/__init__.pyc +0 -0
  26. trackma/extras/plex.py +100 -0
  27. trackma/extras/plex.pyc +0 -0
  28. trackma/lib/__init__.py +0 -0
  29. trackma/lib/__init__.pyc +0 -0
  30. trackma/lib/lib.py +162 -0
  31. trackma/lib/lib.pyc +0 -0
  32. trackma/lib/libanilist.py +355 -0
  33. trackma/lib/libanilist.pyc +0 -0
  34. trackma/lib/libhb.py +248 -0
  35. trackma/lib/libhb.pyc +0 -0
  36. trackma/lib/libmal.py +705 -0
  37. trackma/lib/libmal.pyc +0 -0
  38. trackma/lib/libmelative.py +213 -0
  39. trackma/lib/libmelative.pyc +0 -0
  40. trackma/lib/libvndb.py +373 -0
  41. trackma/lib/libvndb.pyc +0 -0
  42. trackma/messenger.py +42 -0
  43. trackma/messenger.pyc +0 -0
  44. trackma/tracker.py +301 -0
  45. trackma/tracker.pyc +0 -0
  46. trackma/ui/__init__.py +0 -0
  47. trackma/ui/__init__.pyc +0 -0
  48. trackma/ui/cli.py +712 -0
  49. trackma/ui/cli.pyc +0 -0
  50. trackma/ui/curses.py +1049 -0
  51. trackma/ui/curses.pyc +0 -0
  52. trackma/ui/gtkui.py +2360 -0
  53. trackma/ui/gtkui.pyc +0 -0
  54. trackma/ui/qtui.py +2120 -0
  55. trackma/ui/qtui.pyc +0 -0
  56. trackma/utils.py +299 -0
  57. trackma/utils.pyc +0 -0
trackma/data.py ADDED
@@ -0,0 +1,585 @@
1
+ # This file is part of Trackma.
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 3 of the License, or
6
+ # (at your option) 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, see <http://www.gnu.org/licenses/>.
15
+ #
16
+
17
+ import os.path
18
+
19
+ import messenger
20
+ import utils
21
+
22
+ import sys
23
+ import threading
24
+ import time
25
+
26
+ class Data(object):
27
+ """
28
+ Data Handler Class
29
+
30
+ Class for keeping data in memory, handling list cache and
31
+ update queues. This module cares about keeping the data
32
+ safe and up to date, and it handles commands given by the engine,
33
+ and communicates with the API whenever it's necessary.
34
+
35
+ messenger: Messenger object to send useful messages to
36
+ config: Parsed configuration dictionary (given by the engine)
37
+
38
+ """
39
+ name = 'Data'
40
+ version = 1
41
+
42
+ msg = None
43
+ api = None
44
+ showlist = None
45
+ infocache = dict()
46
+ queue = list()
47
+ config = dict()
48
+ meta = {'lastget': 0, 'lastsend': 0, 'version': '', 'altnames': {}, 'library': {}, 'library_cache': {}, }
49
+
50
+ autosend_timer = None
51
+
52
+ signals = {
53
+ 'show_synced': None,
54
+ 'queue_changed': None,
55
+ }
56
+
57
+ def __init__(self, messenger, config, account, mediatype):
58
+ """Checks if the config is correct and creates an API object."""
59
+ self.msg = messenger
60
+ self.config = config
61
+ self.msg.info(self.name, "Initializing...")
62
+
63
+ # Get filenames
64
+ userfolder = "%s.%s" % (account['username'], account['api'])
65
+ self.userconfig_file = utils.get_filename(userfolder, 'user.json')
66
+
67
+ # Handle userconfig and media type to load
68
+ self._load_userconfig()
69
+ if mediatype:
70
+ self.userconfig['mediatype'] = mediatype
71
+ self._save_userconfig()
72
+
73
+ # Import the API
74
+ libbase = account['api']
75
+ libname = "lib{0}".format(libbase)
76
+ try:
77
+ modulename = "trackma.lib.{0}".format(libname)
78
+ __import__(modulename)
79
+ apimodule = sys.modules[modulename]
80
+ except ImportError, e:
81
+ raise utils.DataFatal("Couldn't import API module: %s" % e.message)
82
+
83
+ # Instance API
84
+ libclass = getattr(apimodule, libname)
85
+ self.api = libclass(self.msg, account, self.userconfig)
86
+
87
+ # Set mediatype
88
+ mediatype = self.userconfig.get('mediatype')
89
+ self.msg.info(self.name, "Using %s (%s)" % (libname, mediatype))
90
+
91
+ # Get filenames
92
+ self.queue_file = utils.get_filename(userfolder, '%s.queue' % mediatype)
93
+ self.info_file = utils.get_filename(userfolder, '%s.info' % mediatype)
94
+ self.cache_file = utils.get_filename(userfolder, '%s.list' % mediatype)
95
+ self.meta_file = utils.get_filename(userfolder, '%s.meta' % mediatype)
96
+ self.lock_file = utils.get_filename(userfolder, 'lock')
97
+
98
+ # Connect signals
99
+ self.api.connect_signal('show_info_changed', self.info_update)
100
+ self.api.connect_signal('userconfig_changed', self.userconfig_update)
101
+
102
+ def _emit_signal(self, signal, *args):
103
+ try:
104
+ if self.signals[signal]:
105
+ self.signals[signal](*args)
106
+ except KeyError:
107
+ raise Exception("Call to undefined signal.")
108
+
109
+ def connect_signal(self, signal, callback):
110
+ try:
111
+ self.signals[signal] = callback
112
+ except KeyError:
113
+ raise utils.DataFatal("Invalid signal.")
114
+
115
+ def set_message_handler(self, message_handler):
116
+ self.msg = message_handler
117
+ self.api.set_message_handler(self.msg)
118
+
119
+ def start(self):
120
+ """
121
+ Does all necessary tasks to start the data handler
122
+
123
+ This should be called before doing any other operation with the data handler,
124
+ as it loads the list cache (or downloads it if necessary) and queue.
125
+
126
+ """
127
+ # Lock the database
128
+ self.msg.debug(self.name, "Locking database...")
129
+ self._lock()
130
+
131
+ # Load different caches
132
+ if self._meta_exists():
133
+ self._load_meta()
134
+
135
+ if self._queue_exists():
136
+ self._load_queue()
137
+
138
+ if self._info_exists():
139
+ self._load_info()
140
+
141
+ # If there is a list cache, load from it
142
+ # otherwise query the API for a remote list
143
+ if self._cache_exists():
144
+ # Auto-send: Process the queue if we're beyond the auto-send time limit for some reason
145
+ if self.config['autosend'] == 'hours' and time.time() - self.meta['lastsend'] > self.config['autosend_hours'] * 3600:
146
+ self.process_queue()
147
+
148
+ # Auto-retrieve: Redownload list if any autoretrieve condition is met
149
+ if (self.config['autoretrieve'] == 'always' or
150
+ (self.config['autoretrieve'] == 'days' and time.time() - self.meta['lastget'] > self.config['autoretrieve_days'] * 84600) or
151
+ self.meta.get('version') != self.version):
152
+ try:
153
+ # Make sure we process the queue first before overwriting the list
154
+ # We don't want users losing their changes
155
+ self.process_queue()
156
+ self.download_data()
157
+ except utils.APIError, e:
158
+ self.msg.warn(self.name, "Couldn't download list! Using cache.")
159
+ self._load_cache()
160
+ elif not self.showlist:
161
+ # If the cache wasn't loaded before, do it now
162
+ self._load_cache()
163
+ else:
164
+ try:
165
+ self.download_data()
166
+ except utils.APIError, e:
167
+ raise utils.APIFatal(e.message)
168
+
169
+ # Create autosend thread if needed
170
+ if self.config['autosend'] == 'hours':
171
+ self.autosend()
172
+
173
+ return (self.api.api_info, self.api.media_info())
174
+
175
+ def unload(self, force=False):
176
+ """
177
+ Does unloading of the data handler
178
+
179
+ This should be called whenever the data handler won't be used anymore,
180
+ as it does necessary operations to close the API and the data handler itself.
181
+
182
+ """
183
+ self.msg.debug(self.name, "Unloading...")
184
+
185
+ # Cancel autosend thread
186
+ if self.autosend_timer:
187
+ self.autosend_timer.cancel()
188
+
189
+ # We push changes if specified on config file
190
+ if not force:
191
+ if self.config['autosend_at_exit']:
192
+ self.process_queue()
193
+
194
+ self._save_meta()
195
+
196
+ self._unlock()
197
+
198
+ def get(self):
199
+ """Get list from memory"""
200
+ return self.showlist
201
+
202
+ def search(self, criteria):
203
+ # Tell API to search
204
+ results = self.api.search(criteria)
205
+ self.api.logout()
206
+ if results:
207
+ return results
208
+ else:
209
+ raise utils.DataError('No results.')
210
+
211
+ def queue_add(self, show):
212
+ """
213
+ Queues a show add
214
+
215
+ Calls this to add a show to the list, and the remote add
216
+ will be queued.
217
+
218
+ show: Show dictionary
219
+
220
+ """
221
+ showid = show['id']
222
+
223
+ # Add to the list
224
+ if self.showlist.get(showid):
225
+ raise utils.DataError("Show already in the list.")
226
+
227
+ self.showlist[showid] = show
228
+
229
+ # Check if the show add is already in queue
230
+ exists = False
231
+ for q in self.queue:
232
+ if q['id'] == showid and q['action'] == 'add':
233
+ # This shouldn't happen
234
+ raise utils.DataError("Show already in the queue.")
235
+
236
+ if not exists:
237
+ # Use the whole show as a queue item
238
+ item = show
239
+ item['action'] = 'add'
240
+ self.queue.append(item)
241
+
242
+ show['queued'] = True
243
+
244
+ self._save_queue()
245
+ self._save_cache()
246
+ self._emit_signal('queue_changed', len(self.queue))
247
+ self.msg.info(self.name, "Queued add for %s" % show['title'])
248
+
249
+ def queue_update(self, show, key, value):
250
+ """
251
+ Queues a show update
252
+
253
+ Call this to change anything of an item in the list, as it will be
254
+ modified locally and queued for update in the next remote sync.
255
+
256
+ show: Show dictionary
257
+ key: The key that will be modified (it must exist beforehand)
258
+ value: The value that it should be changed to
259
+ """
260
+ if key not in show.keys():
261
+ raise utils.DataError('Invalid key for queue update.')
262
+
263
+ # Do update on memory
264
+ show[key] = value
265
+
266
+ # Check if the show update is already in queue
267
+ exists = False
268
+ for q in self.queue:
269
+ if q['id'] == show['id'] and q['action'] in ['add', 'update']:
270
+ # Add the changed value to the already existing queue item
271
+ q[key] = value
272
+ exists = True
273
+ break
274
+
275
+ if not exists:
276
+ # Create queue item and append it
277
+ item = {'id': show['id'], 'action': 'update', 'title': show['title']}
278
+ item[key] = value
279
+ self.queue.append(item)
280
+
281
+ show['queued'] = True
282
+
283
+ self._save_queue()
284
+ self._save_cache()
285
+ self._emit_signal('queue_changed', len(self.queue))
286
+ self.msg.info(self.name, "Queued update for %s" % show['title'])
287
+
288
+ # Immediately process the action if necessary
289
+ if (self.config['autosend'] == 'always' or
290
+ (self.config['autosend'] == 'hours' and time.time() - self.meta['lastsend'] >= self.config['autosend_hours']*3600) or
291
+ (self.config['autosend'] == 'size' and len(self.queue) >= self.config['autosend_size'])):
292
+ self.process_queue()
293
+
294
+ def queue_delete(self, show):
295
+ """
296
+ Queues a show delete
297
+
298
+ Calls this to delete a show from the list, and the remote delete
299
+ will be queued.
300
+
301
+ show: Show dictionary
302
+
303
+ """
304
+ showid = show['id']
305
+
306
+ # Delete from the list
307
+ if not self.showlist.get(showid):
308
+ raise utils.DataError("Show not in the list.")
309
+
310
+ item = self.showlist.pop(showid)
311
+
312
+ # Check if the show add is already in queue
313
+ exists = False
314
+ for q in self.queue:
315
+ if q['id'] == showid and q['action'] == 'delete':
316
+ # This shouldn't happen
317
+ raise utils.DataError("Show delete already in the queue.")
318
+
319
+ if not exists:
320
+ # Use the whole show as a queue item
321
+ item['action'] = 'delete'
322
+ self.queue.append(item)
323
+
324
+ show['queued'] = True
325
+
326
+ self._save_queue()
327
+ self._save_cache()
328
+ self._emit_signal('queue_changed', len(self.queue))
329
+ self.msg.info(self.name, "Queued delete for %s" % item['title'])
330
+
331
+ def queue_clear(self):
332
+ """Clears the queue completely."""
333
+ if self.queue:
334
+ self.queue = []
335
+ self._save_queue()
336
+ self._emit_signal('queue_changed', len(self.queue))
337
+ self.msg.info(self.name, "Cleared queue.")
338
+
339
+ def process_queue(self):
340
+ """
341
+ Send updates in queue to the API
342
+
343
+ It starts sending all the queued updates to the API for it to update
344
+ the remote list. Any successful updates get removed from the queue,
345
+ and failed updates stay there to be processed the next time.
346
+
347
+ """
348
+ if len(self.queue):
349
+ self.msg.info(self.name, 'Processing queue...')
350
+
351
+ # Load the cache if it wasn't loaded for some reason
352
+ if not self.showlist:
353
+ self._load_cache()
354
+
355
+ # Check log-in TODO
356
+ #try:
357
+ # self.api.check_credentials()
358
+ #except utils.APIError, e:
359
+ # raise utils.DataError("Can't process queue, will leave unsynced. Reason: %s" % e.message)
360
+
361
+ # Run through queue
362
+ for i in xrange(len(self.queue)):
363
+ show = self.queue.pop(0)
364
+ showid = show['id']
365
+
366
+ try:
367
+ # Call the API to do the requested operation
368
+ operation = show.get('action')
369
+ if operation == 'add':
370
+ self.api.add_show(show)
371
+ elif operation == 'update':
372
+ self.api.update_show(show)
373
+ elif operation == 'delete':
374
+ self.api.delete_show(show)
375
+ else:
376
+ self.msg.warn(self.name, "Unknown operation in queue, skipping...")
377
+
378
+ if self.showlist.get(showid):
379
+ self.showlist[showid]['queued'] = False
380
+ self._emit_signal('show_synced', self.showlist[showid])
381
+
382
+ self._emit_signal('queue_changed', len(self.queue))
383
+ except utils.APIError, e:
384
+ self.msg.warn(self.name, "Can't process %s, will leave unsynced." % show['title'])
385
+ self.msg.debug(self.name, "Info: %s" % e.message)
386
+ self.queue.append(show)
387
+ except NotImplementedError:
388
+ self.msg.warn(self.name, "Operation not implemented in API. Skipping...")
389
+ self.queue.append(show)
390
+ #except TypeError:
391
+ # self.msg.warn(self.name, "%s not in list, unexpected. Not changing queued status." % showid)
392
+
393
+ self.api.logout()
394
+ self._save_cache()
395
+ self._save_queue()
396
+
397
+ else:
398
+ self.msg.debug(self.name, 'No items in queue.')
399
+
400
+ self.meta['lastsend'] = time.time()
401
+
402
+ def info_get(self, show):
403
+ try:
404
+ showid = show['id']
405
+ return self.infocache[showid]
406
+ except KeyError:
407
+ return self.api.request_info([show])[0]
408
+
409
+ def info_update(self, shows):
410
+ for show in shows:
411
+ showid = show['id']
412
+ self.infocache[showid] = show
413
+
414
+ self._save_info()
415
+
416
+ def userconfig_update(self):
417
+ self._save_userconfig()
418
+
419
+ def altname_get(self, showid):
420
+ return self.meta['altnames'].get(showid, '')
421
+
422
+ def altname_set(self, showid, altname):
423
+ self.meta['altnames'][showid] = altname
424
+
425
+ def altname_clear(self, showid):
426
+ del self.meta['altnames'][showid]
427
+
428
+ def altnames_get(self):
429
+ return self.meta['altnames']
430
+
431
+ def library_get(self):
432
+ return self.meta['library']
433
+
434
+ def library_save(self, library):
435
+ self.meta['library'] = library
436
+
437
+ def library_cache_get(self):
438
+ return self.meta['library_cache']
439
+
440
+ def library_cache_save(self, library_cache):
441
+ self.meta['library_cache'] = library_cache
442
+
443
+ def get_show_attr(self, show, key):
444
+ return show.get(key)
445
+
446
+ def set_show_attr(self, show, key, value):
447
+ show[key] = value
448
+
449
+ def get_show_titles(self, show):
450
+ if self.altname_get(show['id']):
451
+ return [ self.altname_get(show['id']) ]
452
+ else:
453
+ return [show['title']] + show['aliases']
454
+
455
+ def autosend(self):
456
+ # Check if we should autosend now
457
+ if time.time() - self.meta['lastsend'] >= self.config['autosend_hours'] * 3600:
458
+ self.process_queue()
459
+
460
+ # Repeat check only if the settings are still on 'hours'
461
+ if self.config['autosend'] == 'hours':
462
+ self.autosend_timer = threading.Timer(3600, self.autosend)
463
+ self.autosend_timer.daemon = True
464
+ self.autosend_timer.start()
465
+
466
+ def _load_cache(self):
467
+ self.msg.debug(self.name, "Reading cache...")
468
+ self.showlist = utils.load_data(self.cache_file)
469
+
470
+ def _save_cache(self):
471
+ self.msg.debug(self.name, "Saving cache...")
472
+ utils.save_data(self.showlist, self.cache_file)
473
+
474
+ def _load_info(self):
475
+ self.msg.debug(self.name, "Reading info DB...")
476
+ self.infocache = utils.load_data(self.info_file)
477
+
478
+ def _save_info(self):
479
+ self.msg.debug(self.name, "Saving info DB...")
480
+ utils.save_data(self.infocache, self.info_file)
481
+
482
+ def _load_userconfig(self):
483
+ self.msg.debug(self.name, "Reading userconfig...")
484
+ self.userconfig = utils.parse_config(self.userconfig_file, utils.userconfig_defaults)
485
+
486
+ def _save_userconfig(self):
487
+ self.msg.debug(self.name, "Saving userconfig...")
488
+ utils.save_config(self.userconfig, self.userconfig_file)
489
+
490
+ def _load_queue(self):
491
+ self.msg.debug(self.name, "Reading queue...")
492
+ self.queue = utils.load_data(self.queue_file)
493
+
494
+ def _save_queue(self):
495
+ self.msg.debug(self.name, "Saving queue...")
496
+ utils.save_data(self.queue, self.queue_file)
497
+
498
+ def _load_meta(self):
499
+ self.msg.debug(self.name, "Reading metadata...")
500
+ loadedmeta = utils.load_data(self.meta_file)
501
+ self.meta.update(loadedmeta)
502
+
503
+ def _save_meta(self):
504
+ self.msg.debug(self.name, "Saving metadata...")
505
+ utils.save_data(self.meta, self.meta_file)
506
+
507
+ def download_data(self):
508
+ """Downloads the remote list and overwrites the cache"""
509
+ self.showlist = self.api.fetch_list()
510
+
511
+ if self.api.api_info['merge']:
512
+ # The API needs information to be merged from the
513
+ # info database
514
+ missing = []
515
+ for k, show in self.showlist.iteritems():
516
+ # Here we search the information in the local
517
+ # info database. If it isn't available, add it
518
+ # to the missing list for them to be requested
519
+ # to the API later.
520
+ showid = show['id']
521
+
522
+ try:
523
+ info = self.infocache[showid]
524
+ except KeyError:
525
+ missing.append(show)
526
+ continue
527
+
528
+ self.api.merge(show, info)
529
+ #show['title'] = info['title']
530
+ #show['image'] = info['image']
531
+
532
+ # Here we request the missing items and merge them
533
+ # immedately with the list.
534
+ if len(missing) > 0:
535
+ infos = self.api.request_info(missing)
536
+ for info in infos:
537
+ showid = info['id']
538
+ self.api.merge(self.showlist[showid], info)
539
+
540
+ #self.showlist[showid]['title'] = info['title']
541
+ #self.showlist[showid]['image'] = info['image']
542
+
543
+ self._save_cache()
544
+ self.api.logout()
545
+
546
+ # Update last retrieved time
547
+ self.meta['lastget'] = time.time()
548
+ self.meta['version'] = self.version
549
+ self._save_meta()
550
+
551
+ def _cache_exists(self):
552
+ return os.path.isfile(self.cache_file)
553
+
554
+ def _info_exists(self):
555
+ return os.path.isfile(self.info_file)
556
+
557
+ def _queue_exists(self):
558
+ return os.path.isfile(self.queue_file)
559
+
560
+ def _meta_exists(self):
561
+ return os.path.isfile(self.meta_file)
562
+
563
+ def _lock(self):
564
+ """Creates the database lock, returns an exception if it
565
+ already exists"""
566
+ if self.config['debug_disable_lock']:
567
+ return
568
+
569
+ if os.path.isfile(self.lock_file):
570
+ raise utils.DataFatal("Database is locked by another process. "
571
+ "If you\'re sure there's no other process is using it, "
572
+ "remove the file ~/.trackma/lock")
573
+
574
+ f = open(self.lock_file, 'w')
575
+ f.close()
576
+
577
+ def _unlock(self):
578
+ """Removes the database lock"""
579
+ if self.config['debug_disable_lock']:
580
+ return
581
+
582
+ os.unlink(self.lock_file)
583
+
584
+ def get_api_info(self):
585
+ return (self.api.api_info, self.api.media_info())
trackma/data.pyc ADDED
Binary file