trackma 0.7.5__py3.6.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 (73) hide show
  1. EGG-INFO/PKG-INFO +22 -0
  2. EGG-INFO/SOURCES.txt +55 -0
  3. EGG-INFO/dependency_links.txt +1 -0
  4. EGG-INFO/entry_points.txt +9 -0
  5. EGG-INFO/not-zip-safe +1 -0
  6. EGG-INFO/requires.txt +8 -0
  7. EGG-INFO/top_level.txt +1 -0
  8. trackma/__init__.py +0 -0
  9. trackma/__pycache__/__init__.cpython-36.pyc +0 -0
  10. trackma/__pycache__/accounts.cpython-36.pyc +0 -0
  11. trackma/__pycache__/data.cpython-36.pyc +0 -0
  12. trackma/__pycache__/engine.cpython-36.pyc +0 -0
  13. trackma/__pycache__/messenger.cpython-36.pyc +0 -0
  14. trackma/__pycache__/utils.cpython-36.pyc +0 -0
  15. trackma/accounts.py +145 -0
  16. trackma/data/anilist.jpg +0 -0
  17. trackma/data/icon.png +0 -0
  18. trackma/data/kitsu.png +0 -0
  19. trackma/data/mal.jpg +0 -0
  20. trackma/data/shikimori.jpg +0 -0
  21. trackma/data/vndb.jpg +0 -0
  22. trackma/data.py +620 -0
  23. trackma/engine.py +979 -0
  24. trackma/extras/AnimeInfoExtractor.py +317 -0
  25. trackma/extras/__init__.py +1 -0
  26. trackma/extras/__pycache__/AnimeInfoExtractor.cpython-36.pyc +0 -0
  27. trackma/extras/__pycache__/__init__.cpython-36.pyc +0 -0
  28. trackma/lib/__init__.py +0 -0
  29. trackma/lib/__pycache__/__init__.cpython-36.pyc +0 -0
  30. trackma/lib/__pycache__/lib.cpython-36.pyc +0 -0
  31. trackma/lib/__pycache__/libanilist.cpython-36.pyc +0 -0
  32. trackma/lib/__pycache__/libkitsu.cpython-36.pyc +0 -0
  33. trackma/lib/__pycache__/libmal.cpython-36.pyc +0 -0
  34. trackma/lib/__pycache__/libshikimori.cpython-36.pyc +0 -0
  35. trackma/lib/__pycache__/libvndb.cpython-36.pyc +0 -0
  36. trackma/lib/lib.py +162 -0
  37. trackma/lib/libanilist.py +474 -0
  38. trackma/lib/libkitsu.py +506 -0
  39. trackma/lib/libmal.py +707 -0
  40. trackma/lib/libshikimori.py +340 -0
  41. trackma/lib/libvndb.py +387 -0
  42. trackma/messenger.py +42 -0
  43. trackma/tracker/__init__.py +0 -0
  44. trackma/tracker/__pycache__/__init__.cpython-36.pyc +0 -0
  45. trackma/tracker/__pycache__/inotify.cpython-36.pyc +0 -0
  46. trackma/tracker/__pycache__/inotifyBase.cpython-36.pyc +0 -0
  47. trackma/tracker/__pycache__/plex.cpython-36.pyc +0 -0
  48. trackma/tracker/__pycache__/polling.cpython-36.pyc +0 -0
  49. trackma/tracker/__pycache__/pyinotify.cpython-36.pyc +0 -0
  50. trackma/tracker/__pycache__/tracker.cpython-36.pyc +0 -0
  51. trackma/tracker/__pycache__/win32.cpython-36.pyc +0 -0
  52. trackma/tracker/inotify.py +69 -0
  53. trackma/tracker/inotifyBase.py +107 -0
  54. trackma/tracker/plex.py +144 -0
  55. trackma/tracker/polling.py +55 -0
  56. trackma/tracker/pyinotify.py +90 -0
  57. trackma/tracker/tracker.py +226 -0
  58. trackma/tracker/win32.py +74 -0
  59. trackma/ui/__init__.py +0 -0
  60. trackma/ui/__pycache__/__init__.cpython-36.pyc +0 -0
  61. trackma/ui/__pycache__/cli-single.cpython-36.pyc +0 -0
  62. trackma/ui/__pycache__/cli.cpython-36.pyc +0 -0
  63. trackma/ui/__pycache__/curses.cpython-36.pyc +0 -0
  64. trackma/ui/__pycache__/gtkui.cpython-36.pyc +0 -0
  65. trackma/ui/__pycache__/qt4ui.cpython-36.pyc +0 -0
  66. trackma/ui/__pycache__/qtui.cpython-36.pyc +0 -0
  67. trackma/ui/cli-single.py +3 -0
  68. trackma/ui/cli.py +1035 -0
  69. trackma/ui/curses.py +1156 -0
  70. trackma/ui/gtkui.py +2847 -0
  71. trackma/ui/qt4ui.py +25 -0
  72. trackma/ui/qtui.py +3273 -0
  73. trackma/utils.py +416 -0
trackma/engine.py ADDED
@@ -0,0 +1,979 @@
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 re
18
+ import os
19
+ import subprocess
20
+ import threading
21
+ import difflib
22
+ import time
23
+ import datetime
24
+ import random
25
+ import shlex
26
+ from decimal import Decimal
27
+
28
+ from trackma import messenger
29
+ from trackma import data
30
+ from trackma import utils
31
+ from trackma.extras import AnimeInfoExtractor
32
+
33
+ class Engine:
34
+ """
35
+ The engine is the controller that handles commands coming from
36
+ the user interface and then queries the Data Handler for the necessary data.
37
+ It doesn't control nor care about how the data is fetched by the Data Handler.
38
+
39
+ After instantiating this class, the :func:`start` must be run to initialize the engine.
40
+ Likewise, the :func:`unload` function must be called when you're done using the engine.
41
+
42
+ The account and mediatype can be changed later on the fly by calling :func:`reload`.
43
+
44
+ The **account** parameter is an account dictionary passed by an Account Manager
45
+ and is used to run the engine.
46
+
47
+ The **message_handler** is a reference to a messaging function for the engine
48
+ to send to. Optional.
49
+ """
50
+ data_handler = None
51
+ tracker = None
52
+ config = {}
53
+ msg = None
54
+ loaded = False
55
+ playing = False
56
+ hooks_available = []
57
+
58
+ name = 'Engine'
59
+
60
+ signals = { 'show_added': None,
61
+ 'show_deleted': None,
62
+ 'episode_changed': None,
63
+ 'score_changed': None,
64
+ 'status_changed': None,
65
+ 'show_synced': None,
66
+ 'sync_complete': None,
67
+ 'queue_changed': None,
68
+ 'playing': None,
69
+ 'prompt_for_update': None,
70
+ 'prompt_for_add': None,
71
+ 'tracker_state': None,
72
+ }
73
+
74
+ def __init__(self, account, message_handler=None):
75
+ """Reads configuration file and asks the data handler for the API info."""
76
+ self.msg = messenger.Messenger(message_handler)
77
+
78
+ self._load(account)
79
+ self._init_data_handler()
80
+
81
+ def _load(self, account):
82
+ self.account = account
83
+
84
+ # Create home directory
85
+ utils.make_dir('')
86
+ self.configfile = utils.get_root_filename('config.json')
87
+
88
+ # Create user directory
89
+ userfolder = "%s.%s" % (account['username'], account['api'])
90
+ utils.make_dir(userfolder)
91
+
92
+ self.msg.info(self.name, 'Trackma v{0} - using account {1}({2}).'.format(
93
+ utils.VERSION, account['username'], account['api']))
94
+ self.msg.info(self.name, 'Reading config files...')
95
+ try:
96
+ self.config = utils.parse_config(self.configfile, utils.config_defaults)
97
+ except IOError:
98
+ raise utils.EngineFatal("Couldn't open config file.")
99
+
100
+ # Load hook files
101
+ hooks_dir = utils.get_root_filename('hooks')
102
+ if os.path.isdir(hooks_dir):
103
+ import sys
104
+ import pkgutil
105
+
106
+ self.msg.info(self.name, "Importing user hooks...")
107
+ for loader, name, ispkg in pkgutil.iter_modules([hooks_dir]):
108
+ # List all the hook files in the hooks folder, import them
109
+ # and call the init() function if they have them
110
+ # We build the list "hooks available" with the loaded modules
111
+ # for later calls.
112
+ try:
113
+ self.msg.debug(self.name, "Importing hook {}...".format(name))
114
+ module = loader.find_module(name).load_module(name)
115
+ if hasattr(module, 'init'):
116
+ module.init(self)
117
+ self.hooks_available.append(module)
118
+ except ImportError:
119
+ self.msg.warn(self.name, "Error importing hook {}.".format(name))
120
+
121
+ def _init_data_handler(self, mediatype=None):
122
+ # Create data handler
123
+ self.data_handler = data.Data(self.msg, self.config, self.account, mediatype)
124
+ self.data_handler.connect_signal('show_synced', self._data_show_synced)
125
+ self.data_handler.connect_signal('sync_complete', self._data_sync_complete)
126
+ self.data_handler.connect_signal('queue_changed', self._data_queue_changed)
127
+
128
+ # Record the API details
129
+ (self.api_info, self.mediainfo) = self.data_handler.get_api_info()
130
+
131
+ def _data_show_synced(self, show, changes):
132
+ self._emit_signal('show_synced', show, changes)
133
+
134
+ def _data_sync_complete(self, items):
135
+ self._emit_signal('sync_complete', items)
136
+
137
+ def _data_queue_changed(self, queue):
138
+ self._emit_signal('queue_changed', queue)
139
+
140
+ def _tracker_detected(self, path, filename):
141
+ self.add_to_library(path, filename)
142
+
143
+ def _tracker_removed(self, path, filename):
144
+ self.remove_from_library(path, filename)
145
+
146
+ def _tracker_playing(self, showid, playing, episode):
147
+ show = self.get_show_info(showid)
148
+ self._emit_signal('playing', show, playing, episode)
149
+
150
+ def _tracker_update(self, showid, episode):
151
+ show = self.get_show_info(showid)
152
+ if self.config['tracker_update_prompt']:
153
+ self._emit_signal('prompt_for_update', show, episode)
154
+ else:
155
+ try:
156
+ self.set_episode(show['id'], episode)
157
+ except utils.TrackmaError as e:
158
+ self.msg.warn(self.name, "Can't update episode: {}".format(e))
159
+
160
+ def _tracker_unrecognised(self, show_title, episode):
161
+ if self.config['tracker_not_found_prompt']:
162
+ self._emit_signal('prompt_for_add', show_title, episode)
163
+
164
+ def _tracker_state(self, state, timer):
165
+ self._emit_signal('tracker_state', state, timer)
166
+
167
+ def _emit_signal(self, signal, *args):
168
+ try:
169
+ # Call the signal function
170
+ if self.signals[signal]:
171
+ self.signals[signal](*args)
172
+ except AttributeError:
173
+ pass
174
+
175
+ # If there are loaded hooks, call the functions in all of them
176
+ for module in self.hooks_available:
177
+ method = getattr(module, signal, None)
178
+ if method is not None:
179
+ self.msg.info(self.name, "Calling hook {}:{}...".format(module.__name__, signal))
180
+ try:
181
+ method(self, *args)
182
+ except Exception as err:
183
+ self.msg.warn(self.name, "Exception on hook {}:{}: {}".format(module.__name__, signal, err))
184
+
185
+ def _get_tracker_list(self, filter_num=None):
186
+ tracker_list = []
187
+ if isinstance(filter_num, type(None)):
188
+ source_list = self.get_list()
189
+ elif isinstance(filter_num, list):
190
+ source_list = []
191
+ for status in filter_num:
192
+ if status is not self.mediainfo['status_finish']:
193
+ self.msg.debug(self.name, "scanning for \
194
+ {}".format(self.mediainfo['statuses_dict'][status]))
195
+ source_list = source_list + self.filter_list(status)
196
+ else:
197
+ source_list = self.filter_list(filter_num)
198
+
199
+ for show in source_list:
200
+ tracker_list.append({'id': show['id'],
201
+ 'title': show['title'],
202
+ 'my_progress': show['my_progress'],
203
+ 'total': show['total'],
204
+ 'type': None,
205
+ 'titles': self.data_handler.get_show_titles(show),
206
+ }) # TODO types
207
+
208
+ return tracker_list
209
+
210
+ def _update_tracker(self):
211
+ if self.tracker:
212
+ self.tracker.update_list(self._get_tracker_list())
213
+
214
+ def _cleanup(self):
215
+ # If the engine wasn't closed for whatever reason, do it
216
+ if self.loaded:
217
+ self.msg.info(self.name, "Forcing exit...")
218
+ self.data_handler.unload(True)
219
+ self.loaded = False
220
+
221
+ def connect_signal(self, signal, callback):
222
+ try:
223
+ self.signals[signal] = callback
224
+ except KeyError:
225
+ raise utils.EngineFatal("Invalid signal.")
226
+
227
+ def set_message_handler(self, message_handler):
228
+ """Changes the message handler function on the fly."""
229
+ self.msg = messenger.Messenger(message_handler)
230
+ self.data_handler.set_message_handler(self.msg)
231
+
232
+ def start(self):
233
+ """
234
+ Starts the engine.
235
+ This function should be called before doing anything with the engine,
236
+ as it initializes the data handler.
237
+ """
238
+ if self.loaded:
239
+ raise utils.TrackmaError("Already loaded.")
240
+
241
+ # Start the data handler
242
+ try:
243
+ (self.api_info, self.mediainfo) = self.data_handler.start()
244
+ except utils.DataError as e:
245
+ raise utils.DataFatal(str(e))
246
+ except utils.APIError as e:
247
+ raise utils.APIFatal(str(e))
248
+
249
+ # Rescan library if necessary
250
+ if self.config['library_autoscan']:
251
+ try:
252
+ self.scan_library()
253
+ except utils.TrackmaError as e:
254
+ self.msg.warn(self.name, "Can't auto-scan library: {}".format(e))
255
+
256
+ # Start tracker
257
+ if self.mediainfo.get('can_play') and self.config['tracker_enabled']:
258
+ # Choose the tracker we want to tart
259
+ if self.config['tracker_type'] == 'plex':
260
+ from trackma.tracker.plex import PlexTracker
261
+ TrackerClass = PlexTracker
262
+ elif os.name == 'nt':
263
+ from trackma.tracker.win32 import Win32Tracker
264
+ TrackerClass = Win32Tracker
265
+ else:
266
+ # Try trackers in this order: pyinotify, inotify, polling
267
+ try:
268
+ from trackma.tracker.pyinotify import pyinotifyTracker
269
+ TrackerClass = pyinotifyTracker
270
+ except ImportError:
271
+ try:
272
+ from trackma.tracker.inotify import inotifyTracker
273
+ TrackerClass = inotifyTracker
274
+ except ImportError:
275
+ from trackma.tracker.polling import PollingTracker
276
+ TrackerClass = PollingTracker
277
+
278
+ self.tracker = TrackerClass(self.msg,
279
+ self._get_tracker_list(),
280
+ self.config['tracker_process'],
281
+ self.config['searchdir'],
282
+ int(self.config['tracker_interval']),
283
+ int(self.config['tracker_update_wait_s']),
284
+ self.config['tracker_update_close'],
285
+ self.config['tracker_not_found_prompt'],
286
+ )
287
+ self.tracker.connect_signal('detected', self._tracker_detected)
288
+ self.tracker.connect_signal('removed', self._tracker_removed)
289
+ self.tracker.connect_signal('playing', self._tracker_playing)
290
+ self.tracker.connect_signal('update', self._tracker_update)
291
+ self.tracker.connect_signal('unrecognised', self._tracker_unrecognised)
292
+ self.tracker.connect_signal('state', self._tracker_state)
293
+
294
+ self.loaded = True
295
+ return True
296
+
297
+ def unload(self):
298
+ """
299
+ Closes the data handler and closes the engine cleanly.
300
+ This should be called when closing the client application, or when you're
301
+ sure you're not going to use the engine anymore. This does all the necessary
302
+ procedures to close the data handler cleanly and then itself.
303
+
304
+ """
305
+ if self.loaded:
306
+ self.msg.info(self.name, "Unloading...")
307
+ self.data_handler.unload()
308
+
309
+ self.loaded = False
310
+
311
+ def reload(self, account=None, mediatype=None):
312
+ """Changes the API and/or mediatype and reloads itself."""
313
+ if self.loaded:
314
+ self.unload()
315
+
316
+ if account:
317
+ self._load(account)
318
+
319
+ self._init_data_handler(mediatype)
320
+ self.start()
321
+
322
+ def get_config(self, key):
323
+ """Returns the specified key from the configuration."""
324
+ return self.config[key]
325
+
326
+ def get_userconfig(self, key):
327
+ return self.data_handler.userconfig[key]
328
+
329
+ def set_config(self, key, value):
330
+ """
331
+ Writes the defined key to the configuration.
332
+ Note that this writes the configuration only to memory; when you're
333
+ done doing all necessary changes, make sure to write the configuration file
334
+ with :func:`save_config`."""
335
+ self.config[key] = value
336
+
337
+ def save_config(self):
338
+ """Writes all configuration files to disk."""
339
+
340
+ # Save config file
341
+ utils.save_config(self.config, self.configfile)
342
+
343
+ def get_list(self):
344
+ """
345
+ Returns the full show list requested from the data handler as a list of show dictionaries.
346
+ If you only need shows in a specified status, use :func:`filter_list`.
347
+ """
348
+ return self.data_handler.get().values()
349
+
350
+ def get_show_info(self, showid):
351
+ """
352
+ Returns the show dictionary for the specified **showid**.
353
+ """
354
+ showdict = self.data_handler.get()
355
+
356
+ try:
357
+ return showdict[showid]
358
+ except KeyError:
359
+ raise utils.EngineError("Show not found.")
360
+
361
+ def get_show_info_title(self, pattern):
362
+ showdict = self.data_handler.get()
363
+ # Do title lookup, slower
364
+ for k, show in showdict.items():
365
+ if show['title'] == pattern:
366
+ return show
367
+ raise utils.EngineError("Show not found.")
368
+
369
+ def get_show_details(self, show):
370
+ """
371
+ Returns detailed information about **show** requested from the data handler.
372
+ """
373
+ return self.data_handler.info_get(show)
374
+
375
+ def regex_list(self, regex):
376
+ """
377
+ It asks the data handler to do a regex search for a show and returns the
378
+ list of show dictionaries with all the matches.
379
+ """
380
+ showlist = self.data_handler.get()
381
+ return list(v for k, v in showlist.items() if re.search(regex, v['title'], re.I))
382
+
383
+ def regex_list_titles(self, pattern):
384
+ # TODO : Temporal hack for the client autocomplete function
385
+ showlist = self.data_handler.get()
386
+ newlist = list()
387
+ for k, v in showlist.items():
388
+ if re.match(pattern, v['title'], re.I):
389
+ if ' ' in v['title']:
390
+ newlist.append('"' + v['title'] + '" ')
391
+ else:
392
+ newlist.append(v['title'] + ' ')
393
+
394
+ return newlist
395
+
396
+ def tracker_status(self):
397
+ """
398
+ Asks the tracker for its current status.
399
+ """
400
+
401
+ if self.tracker:
402
+ return self.tracker.get_status()
403
+ else:
404
+ return None
405
+
406
+ def search(self, criteria):
407
+ """
408
+ Request a remote list of shows matching the criteria
409
+ and returns it as a list of show dictionaries.
410
+ This is useful to add a show.
411
+ """
412
+ return self.data_handler.search(str(criteria).strip())
413
+
414
+ def add_show(self, show, status=None):
415
+ """
416
+ Adds **show** to the list and queues the list update
417
+ for the next sync.
418
+ """
419
+ # Check if operation is supported by the API
420
+ if not self.mediainfo.get('can_add'):
421
+ raise utils.EngineError('Operation not supported by API.')
422
+
423
+ # Set to the requested status
424
+ if status:
425
+ if status not in self.mediainfo['statuses']:
426
+ raise utils.EngineError('Invalid status.')
427
+
428
+ show['my_status'] = status
429
+
430
+ # Add in data handler
431
+ self.data_handler.queue_add(show)
432
+
433
+ # Update the tracker with the new information
434
+ self._update_tracker()
435
+
436
+ # Emit signal
437
+ self._emit_signal('show_added', show)
438
+
439
+ def set_episode(self, showid, newep):
440
+ """
441
+ Updates the progress of the specified **showid** to **newep**
442
+ and queues the list update for the next sync.
443
+ """
444
+ # Check if operation is supported by the API
445
+ if not self.mediainfo.get('can_update'):
446
+ raise utils.EngineError('Operation not supported by API.')
447
+
448
+ # Check for the episode number
449
+ try:
450
+ newep = int(newep)
451
+ except ValueError:
452
+ raise utils.EngineError('Episode must be numeric.')
453
+
454
+ # Get the show info
455
+ show = self.get_show_info(showid)
456
+ # More checks
457
+ if (show['total'] and newep > show['total']) or newep < 0:
458
+ raise utils.EngineError('Episode out of limits.')
459
+ if show['my_progress'] == newep:
460
+ raise utils.EngineError("Show already at episode %d" % newep)
461
+
462
+ # Change episode
463
+ self.msg.info(self.name, "Updating show %s to episode %d..." % (show['title'], newep))
464
+ self.data_handler.queue_update(show, 'my_progress', newep)
465
+
466
+ # Emit signal
467
+ self._emit_signal('episode_changed', show)
468
+
469
+ # Change status if required
470
+ if self.config['auto_status_change'] and self.mediainfo.get('can_status'):
471
+ try:
472
+ if newep == show['total'] and self.mediainfo.get('status_finish'):
473
+ if (
474
+ not self.config['auto_status_change_if_scored'] or
475
+ not self.mediainfo.get('can_score') or
476
+ show['my_score']
477
+ ):
478
+ # Change to finished status
479
+ self.set_status(show['id'], self.mediainfo['status_finish'])
480
+ else:
481
+ self.msg.warn(self.name, "Updated episode but status won't be changed until a score is set.")
482
+ elif newep == 1 and self.mediainfo.get('status_start'):
483
+ # Change to watching status
484
+ self.set_status(show['id'], self.mediainfo['status_start'])
485
+ except utils.EngineError as e:
486
+ # Only warn about engine errors since status change here is not crtical
487
+ self.msg.warn(self.name, 'Updated episode but status wasn\'t changed: %s' % e)
488
+
489
+ # Change dates if required
490
+ if self.config['auto_date_change'] and self.mediainfo.get('can_date'):
491
+ start_date = finish_date = None
492
+
493
+ try:
494
+ if newep == 1:
495
+ start_date = datetime.date.today()
496
+ if newep == show['total']:
497
+ finish_date = datetime.date.today()
498
+
499
+ self.set_dates(show['id'], start_date, finish_date)
500
+ except utils.EngineError as e:
501
+ # Only warn about engine errors since date change here is not crtical
502
+ self.msg.warn(self.name, 'Updated episode but dates weren\'t changed: %s' % e)
503
+
504
+ # Clear neweps flag
505
+ if self.data_handler.get_show_attr(show, 'neweps'):
506
+ self.data_handler.set_show_attr(show, 'neweps', False)
507
+
508
+ # Update the tracker with the new information
509
+ self._update_tracker()
510
+
511
+ return show
512
+
513
+ def set_dates(self, showid, start_date=None, finish_date=None):
514
+ """
515
+ Updates the start date and finish date of a show.
516
+ If any of the two are None, it won't be changed.
517
+ """
518
+ if not self.mediainfo.get('can_date'):
519
+ raise utils.EngineError('Operation not supported by API.')
520
+
521
+ show = self.get_show_info(showid)
522
+
523
+ # Change the start date if required
524
+ if start_date:
525
+ if not isinstance(start_date, datetime.date):
526
+ raise utils.EngineError('start_date must be a Date object.')
527
+ self.data_handler.queue_update(show, 'my_start_date', start_date)
528
+
529
+ if finish_date:
530
+ if not isinstance(finish_date, datetime.date):
531
+ raise utils.EngineError('finish_date must be a Date object.')
532
+ self.data_handler.queue_update(show, 'my_finish_date', finish_date)
533
+
534
+ def set_score(self, showid, newscore):
535
+ """
536
+ Updates the score of the specified **showid** to **newscore**
537
+ and queues the list update for the next sync.
538
+ """
539
+ # Check if operation is supported by the API
540
+ if not self.mediainfo.get('can_score'):
541
+ raise utils.EngineError('Operation not supported by API.')
542
+
543
+ # Check for the correctness of the score
544
+ if (Decimal(str(newscore)) % Decimal(str(self.mediainfo['score_step']))) != 0:
545
+ raise utils.EngineError('Invalid score.')
546
+
547
+ # Convert to proper type
548
+ if isinstance( self.mediainfo['score_step'], int ):
549
+ newscore = int(newscore)
550
+ else:
551
+ newscore = float(newscore)
552
+
553
+ # Get the show and update it
554
+ show = self.get_show_info(showid)
555
+ # More checks
556
+ if newscore > self.mediainfo['score_max']:
557
+ raise utils.EngineError('Score out of limits.')
558
+ if show['my_score'] == newscore:
559
+ raise utils.EngineError("Score already at %s" % newscore)
560
+
561
+ # Change score
562
+ self.msg.info(self.name, "Updating show %s to score %s..." % (show['title'], newscore))
563
+ self.data_handler.queue_update(show, 'my_score', newscore)
564
+
565
+ # Emit signal
566
+ self._emit_signal('score_changed', show)
567
+
568
+ # Change status if required
569
+ if (
570
+ show['total'] and
571
+ show['my_progress'] == show['total'] and
572
+ show['my_score'] and
573
+ self.mediainfo.get('can_status') and
574
+ self.config['auto_status_change'] and
575
+ self.config['auto_status_change_if_scored'] and
576
+ self.mediainfo.get('status_finish')
577
+ ):
578
+ try:
579
+ self.set_status(show['id'], self.mediainfo['status_finish'])
580
+ except utils.EngineError as e:
581
+ # Only warn about engine errors since status change here is not crtical
582
+ self.msg.warn(self.name, 'Updated episode but status wasn\'t changed: %s' % e)
583
+
584
+ return show
585
+
586
+ def set_status(self, showid, newstatus):
587
+ """
588
+ Updates the score of the specified **showid** to **newstatus** (number)
589
+ and queues the list update for the next sync.
590
+ """
591
+ # Check if operation is supported by the API
592
+ if not self.mediainfo.get('can_status'):
593
+ raise utils.EngineError('Operation not supported by API.')
594
+
595
+ try:
596
+ newstatus = int(newstatus)
597
+ except ValueError:
598
+ pass # It's not necessary for it to be an int
599
+
600
+ # Check if the status is valid
601
+ _statuses = self.mediainfo['statuses_dict']
602
+ if newstatus not in _statuses:
603
+ raise utils.EngineError('Invalid status.')
604
+
605
+ # Get the show and update it
606
+ show = self.get_show_info(showid)
607
+ # More checks
608
+ if show['my_status'] == newstatus:
609
+ raise utils.EngineError("Show already in %s." % _statuses[newstatus])
610
+
611
+ # Change status
612
+ old_status = show['my_status']
613
+ self.msg.info(self.name, "Updating show %s status to %s..." % (show['title'], _statuses[newstatus]))
614
+ self.data_handler.queue_update(show, 'my_status', newstatus)
615
+
616
+ # Emit signal
617
+ self._emit_signal('status_changed', show, old_status)
618
+
619
+ return show
620
+
621
+ def set_tags(self, showid, newtags):
622
+ """
623
+ Updates the tags of the specified **showid** to **newtags**
624
+ and queues the list update for the next sync.
625
+ """
626
+ # Check if operation is supported by the API
627
+ if 'can_tag' not in self.mediainfo or not self.mediainfo.get('can_tag'):
628
+ raise utils.EngineError('Operation not supported by API.')
629
+
630
+ # Get the show and update it
631
+ show = self.get_show_info(showid)
632
+ # More checks
633
+ if show['my_tags'] == newtags:
634
+ raise utils.EngineError("Tags already %s" % newtags)
635
+
636
+ # Change score
637
+ self.msg.info(self.name, "Updating show %s to tags '%s'..." % (show['title'], newtags))
638
+ self.data_handler.queue_update(show, 'my_tags', newtags)
639
+
640
+ # Emit signal
641
+ self._emit_signal('tags_changed', show)
642
+
643
+ return show
644
+
645
+ def delete_show(self, show):
646
+ """
647
+ Deletes **show** completely from the list and queues the list update for the next sync.
648
+ """
649
+ if not self.mediainfo.get('can_delete'):
650
+ raise utils.EngineError('Operation not supported by API.')
651
+
652
+ # Add in data handler
653
+ self.data_handler.queue_delete(show)
654
+
655
+ # Update the tracker with the new information
656
+ self._update_tracker()
657
+
658
+ # Emit signal
659
+ self._emit_signal('show_deleted', show)
660
+
661
+ def _search_video(self, titles, episode):
662
+ # DEPRECATED !!!
663
+ self.msg.debug(self.name, "DEPRECATED: _search_video")
664
+
665
+ best_candidate = (None, 0, None)
666
+
667
+ matcher = difflib.SequenceMatcher()
668
+
669
+ # Check over video files and propose our best candidate
670
+ for (fullpath, filename) in utils.regex_find_videos('mkv|mp4|avi', self.config['searchdir']):
671
+ # Analyze what's the title and episode of the file
672
+ aie = AnimeInfoExtractor(filename)
673
+ candidate_title = aie.getName()
674
+ candidate_episode_start, candidate_episode_end = aie.getEpisodeNumbers()
675
+
676
+ # Skip this file if we couldn't analyze it
677
+ if not candidate_title:
678
+ continue
679
+ if candidate_episode_start is None:
680
+ continue
681
+
682
+ # Skip this file if it isn't the episode we want
683
+ if candidate_episode_end is None:
684
+ if episode != candidate_episode_start:
685
+ continue
686
+ else:
687
+ if not (candidate_episode_start <= episode <= candidate_episode_end):
688
+ continue
689
+
690
+ matcher.set_seq1(candidate_title.lower())
691
+
692
+ # We remember to compare all titles (aliases and whatnot)
693
+ for requested_title in titles:
694
+ matcher.set_seq2(requested_title.lower())
695
+ ratio = matcher.ratio()
696
+
697
+ # Propose as our new candidate if its ratio is
698
+ # better than threshold and it's better than
699
+ # what we've seen yet
700
+ if ratio > 0.7 and ratio > best_candidate[1]:
701
+ best_candidate = (fullpath, ratio, aie.getEpisode())
702
+
703
+ return best_candidate[0], best_candidate[2]
704
+
705
+ def get_new_episodes(self, showlist):
706
+ # DEPRECATED !
707
+ self.msg.debug(self.name, "DEPRECATED: get_new_episodes")
708
+
709
+ results = list()
710
+ total = len(showlist)
711
+ t = time.time()
712
+
713
+ for i, show in enumerate(showlist):
714
+ self.msg.info(self.name, "Searching %d/%d..." % (i+1, total))
715
+
716
+ titles = self.data_handler.get_show_titles(show)
717
+
718
+ (filename, ep) = self._search_video(titles, show['my_progress']+1)
719
+ if filename:
720
+ self.data_handler.set_show_attr(show, 'neweps', True)
721
+ results.append(show)
722
+
723
+ self.msg.info(self.name, "Time: %s" % (time.time() - t))
724
+ return results
725
+
726
+ def library(self):
727
+ return self.data_handler.library_get()
728
+
729
+ def scan_library(self, my_status=None, rescan=False):
730
+ # Check if operation is supported by the API
731
+ if not self.mediainfo.get('can_play'):
732
+ raise utils.EngineError('Operation not supported by current site or mediatype.')
733
+ if not self.config['searchdir']:
734
+ raise utils.EngineError('Media directory is not set.')
735
+
736
+ searchdir = utils.expand_path(self.config['searchdir'])
737
+ if not utils.dir_exists(searchdir):
738
+ raise utils.EngineError('The set media directory ({}) doesn\'t exist.'.format(searchdir))
739
+
740
+ t = time.time()
741
+ library = {}
742
+ library_cache = self.data_handler.library_cache_get()
743
+
744
+ if not my_status:
745
+ if self.config['scan_whole_list']:
746
+ my_status = self.mediainfo['statuses']
747
+ else:
748
+ my_status = self.mediainfo['status_start']
749
+
750
+ self.msg.info(self.name, "Scanning local library...")
751
+ self.msg.debug(self.name, "Directory: %s" % searchdir)
752
+ tracker_list = self._get_tracker_list(my_status)
753
+
754
+
755
+ # Do a full listing of the media directory
756
+ for fullpath, filename in utils.regex_find_videos('mkv|mp4|avi', searchdir):
757
+ if self.config['library_full_path']:
758
+ filename = self._get_show_name_from_full_path(fullpath).strip()
759
+ (library, library_cache) = self._add_show_to_library(library, library_cache, rescan, fullpath, filename, tracker_list)
760
+
761
+ self.msg.debug(self.name, "Time: %s" % (time.time() - t))
762
+ self.data_handler.library_save(library)
763
+ self.data_handler.library_cache_save(library_cache)
764
+ return library
765
+
766
+ def remove_from_library(self, path, filename):
767
+ library = self.data_handler.library_get()
768
+ library_cache = self.data_handler.library_cache_get()
769
+ tracker_list = self._get_tracker_list()
770
+ fullpath = path+"/"+filename
771
+ # Only remove if the filename matches library entry
772
+ if filename in library_cache and library_cache[filename]:
773
+ (show_id, show_ep) = library_cache[filename]
774
+ if show_id and show_id in library \
775
+ and show_ep and show_ep in library[show_id].keys():
776
+ if library[show_id][show_ep] == fullpath:
777
+ self.msg.debug(self.name, "File removed from local library: %s" % fullpath)
778
+ library_cache.pop(filename, None)
779
+ library[show_id].pop(show_ep, None)
780
+
781
+ def add_to_library(self, path, filename, rescan=False):
782
+ # The inotify tracker tells us when files are created in
783
+ # or moved within our library directory, so we call this.
784
+ library = self.data_handler.library_get()
785
+ library_cache = self.data_handler.library_cache_get()
786
+ tracker_list = self._get_tracker_list()
787
+ fullpath = path+"/"+filename
788
+ self._add_show_to_library(library, library_cache, rescan, fullpath, filename, tracker_list)
789
+
790
+ def _add_show_to_library(self, library, library_cache, rescan, fullpath, filename, tracker_list):
791
+ show_id = None
792
+ if not rescan and filename in library_cache:
793
+ # If the filename was already seen before
794
+ # use the cached information, if there's no information (None)
795
+ # then it means it doesn't correspond to any show in the list
796
+ # and can be safely skipped.
797
+ if library_cache[filename]:
798
+ (show_id, show_ep) = library_cache[filename]
799
+ if type(show_ep) is tuple:
800
+ (show_ep_start, show_ep_end) = show_ep
801
+ else:
802
+ show_ep_start = show_ep_end = show_ep
803
+ self.msg.debug(self.name, "File in cache: {}".format(fullpath))
804
+ else:
805
+ self.msg.debug(self.name, "File in cache but skipped: {}".format(fullpath))
806
+ return library, library_cache
807
+ else:
808
+ # If the filename has not been seen, extract
809
+ # the information from the filename and do a fuzzy search
810
+ # on the user's list. Cache the information.
811
+ # If it fails, cache it as None.
812
+ aie = AnimeInfoExtractor(filename)
813
+ show_title = aie.getName()
814
+ (show_ep_start, show_ep_end) = aie.getEpisodeNumbers(True)
815
+ if show_title:
816
+ show = utils.guess_show(show_title, tracker_list)
817
+ if show:
818
+ self.msg.debug(self.name, "Adding to library: {}".format(fullpath))
819
+
820
+ show_id = show['id']
821
+ if show_ep_start == show_ep_end:
822
+ library_cache[filename] = (show['id'], show_ep_start)
823
+ else:
824
+ library_cache[filename] = (show['id'], (show_ep_start, show_ep_end))
825
+ else:
826
+ self.msg.debug(self.name, "Not a show, skipping: {}".format(fullpath))
827
+ library_cache[filename] = None
828
+ else:
829
+ self.msg.debug(self.name, "Not recognized, skipping: {}".format(fullpath))
830
+ library_cache[filename] = None
831
+
832
+ # After we got our information, add it to our library
833
+ if show_id:
834
+ if show_id not in library:
835
+ library[show_id] = {}
836
+ for show_ep in range(show_ep_start, show_ep_end+1):
837
+ library[show_id][show_ep] = fullpath
838
+ return library, library_cache
839
+
840
+ def get_episode_path(self, show, episode):
841
+ """
842
+ This function returns the full path of the requested episode from the requested show.
843
+ """
844
+
845
+ library = self.library()
846
+ showid = show['id']
847
+
848
+ if showid not in library:
849
+ raise utils.EngineError('Show not in library.')
850
+ if episode not in library[showid]:
851
+ raise utils.EngineError('Episode not in library.')
852
+
853
+ return library[showid][episode]
854
+
855
+ def play_random(self):
856
+ """
857
+ This function will pick a random show that has a new episode to watch
858
+ and play it.
859
+ """
860
+ library = self.library()
861
+ newep = []
862
+
863
+ self.msg.info(self.name, 'Looking for random episode.')
864
+
865
+ for showid, eps in library.items():
866
+ show = self.get_show_info(showid)
867
+ if show['my_progress'] + 1 in eps:
868
+ newep.append(show)
869
+
870
+ if not newep:
871
+ raise utils.EngineError('No new episodes found to pick from.')
872
+
873
+ show = random.choice(newep)
874
+ ep = self.play_episode(show)
875
+ return (show, ep)
876
+
877
+ def play_episode(self, show, playep=0):
878
+ """
879
+ Does a local search in the hard disk (in the folder specified by the config file)
880
+ for the specified episode (**playep**) for the specified **show**.
881
+
882
+ If no **playep** is specified, the next episode of the show will be played.
883
+ """
884
+ # Check if operation is supported by the API
885
+ if not self.mediainfo.get('can_play'):
886
+ raise utils.EngineError('Operation not supported by current site or mediatype.')
887
+
888
+ try:
889
+ playep = int(playep)
890
+ except ValueError:
891
+ raise utils.EngineError('Episode must be numeric.')
892
+
893
+ if show:
894
+ playing_next = False
895
+ if not playep:
896
+ playep = show['my_progress'] + 1
897
+ playing_next = True
898
+
899
+ if show['total'] and playep > show['total']:
900
+ raise utils.EngineError('Episode beyond limits.')
901
+
902
+ if self.config.get('debug_oldsearch'):
903
+ # Deprecated
904
+ self.msg.info(self.name, "Searching for %s %s..." % (show['title'], playep))
905
+ titles = self.data_handler.get_show_titles(show)
906
+ filename, endep = self._search_video(titles, playep)
907
+ else:
908
+ self.msg.info(self.name, "Getting %s %s from library..." % (show['title'], playep))
909
+ filename = self.get_episode_path(show, playep)
910
+ endep = playep
911
+
912
+ if filename:
913
+ self.msg.info(self.name, 'Found. Starting player...')
914
+ arg_list = shlex.split(self.config['player'])
915
+ arg_list.append(filename)
916
+ try:
917
+ with open(os.devnull, 'wb') as DEVNULL:
918
+ subprocess.Popen(arg_list, stdout=DEVNULL, stderr=DEVNULL)
919
+ except OSError:
920
+ raise utils.EngineError('Player not found, check your config.json')
921
+ return endep
922
+ else:
923
+ raise utils.EngineError('Episode file not found.')
924
+
925
+ def undoall(self):
926
+ """Clears the data handler queue and discards any unsynced change."""
927
+ return self.data_handler.queue_clear()
928
+
929
+ def altname(self, showid, newname=None):
930
+ """
931
+ If **newname** is specified, it gets the alternate name of **showid**.
932
+ Otherwise, it sets the alternate name of **showid** to **newname**.
933
+ """
934
+ if newname is not None:
935
+ if newname == '':
936
+ self.data_handler.altname_clear(showid)
937
+ self.msg.info(self.name, 'Cleared alternate name.')
938
+ else:
939
+ self.data_handler.altname_set(showid, newname)
940
+ self.msg.info(self.name, 'Changed alternate name to %s.' % newname)
941
+ else:
942
+ return self.data_handler.altname_get(showid)
943
+
944
+ def altnames(self):
945
+ """
946
+ Gets a dictionary of all set alternative names.
947
+ """
948
+ return self.data_handler.altnames_get()
949
+
950
+ def filter_list(self, status_num):
951
+ """
952
+ Returns a show list with the shows in the specified **status_num** status.
953
+ If you need a list with all the shows, use :func:`get_list`.
954
+ """
955
+ showlist = self.data_handler.get()
956
+ return list(v for k, v in showlist.items() if v['my_status'] == status_num)
957
+
958
+ def list_download(self):
959
+ """Asks the data handler to download the remote list."""
960
+ self.undoall()
961
+ self.data_handler.download_data()
962
+ self._update_tracker()
963
+
964
+ def list_upload(self):
965
+ """Asks the data handler to upload the unsynced changes in the queue."""
966
+ result = self.data_handler.process_queue()
967
+ #for show in result:
968
+ # self._emit_signal('episode_changed', show)
969
+
970
+ def get_queue(self):
971
+ """Asks the data handler for the items in the current queue."""
972
+ return self.data_handler.queue
973
+
974
+ def _get_show_name_from_full_path(self, fullpath):
975
+ """Joins the directory name with the file name to return the show name."""
976
+ searchdir = utils.expand_path(self.config['searchdir'])
977
+ relative = fullpath[len(searchdir):]
978
+
979
+ return relative.replace(os.path.sep, " ")