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