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