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/tracker.py ADDED
@@ -0,0 +1,390 @@
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 subprocess
18
+ import threading
19
+ import re
20
+ import time
21
+ import os
22
+ import difflib
23
+
24
+ import ctypes
25
+
26
+ from trackma import messenger
27
+ from trackma import utils
28
+ from trackma.extras import plex
29
+ from trackma.extras import AnimeInfoExtractor
30
+
31
+ inotify_available = 0
32
+ INOTIFY_PYINOTIFY = 1 # seb-m/pyinotify - pyinotify on PyPi
33
+ INOTIFY_INOTIFY = 2 # dsoprea/PyInotify - inotify on PyPi
34
+
35
+ STATE_PLAYING = 0
36
+ STATE_NOVIDEO = 1
37
+ STATE_UNRECOGNIZED = 2
38
+ STATE_NOT_FOUND = 3
39
+
40
+ try:
41
+ import inotify.adapters
42
+ import inotify.constants
43
+ inotify_available = INOTIFY_INOTIFY
44
+ except ImportError:
45
+ try:
46
+ import pyinotify
47
+ inotify_available = INOTIFY_PYINOTIFY
48
+ except:
49
+ pass # If we ignore this the tracker will just use lsof
50
+
51
+
52
+ class Tracker():
53
+ msg = None
54
+ active = True
55
+ list = None
56
+ last_show_tuple = None
57
+ last_filename = None
58
+ last_state = STATE_NOVIDEO
59
+ last_time = 0
60
+ last_updated = False
61
+ last_close_queue = False
62
+ plex_enabled = False
63
+ plex_log = [None, None]
64
+
65
+ name = 'Tracker'
66
+
67
+ signals = {'playing': None,
68
+ 'update': None, }
69
+
70
+ def __init__(self, messenger, tracker_list, process_name, watch_dir, interval, update_wait, update_close):
71
+ self.msg = messenger
72
+ self.msg.info(self.name, 'Initializing...')
73
+
74
+ self.list = tracker_list
75
+ self.process_name = process_name
76
+ self.plex_enabled = plex.get_config()[0]
77
+
78
+ tracker_args = (watch_dir, interval)
79
+ self.wait_s = update_wait
80
+ self.wait_close = update_close
81
+ tracker_t = threading.Thread(target=self._tracker, args=tracker_args)
82
+ tracker_t.daemon = True
83
+ self.msg.debug(self.name, 'Enabling tracker...')
84
+ tracker_t.start()
85
+
86
+ def set_message_handler(self, message_handler):
87
+ """Changes the message handler function on the fly."""
88
+ self.msg = message_handler
89
+
90
+ def disable(self):
91
+ self.active = False
92
+
93
+ def enable(self):
94
+ self.active = True
95
+
96
+ def update_list(self, tracker_list):
97
+ self.list = tracker_list
98
+
99
+ def connect_signal(self, signal, callback):
100
+ try:
101
+ self.signals[signal] = callback
102
+ except KeyError:
103
+ raise utils.EngineFatal("Invalid signal.")
104
+
105
+ def _emit_signal(self, signal, *args):
106
+ try:
107
+ if self.signals[signal]:
108
+ self.signals[signal](*args)
109
+ except KeyError:
110
+ raise Exception("Call to undefined signal.")
111
+
112
+ def _get_playing_file_lsof(self, players):
113
+ try:
114
+ lsof = subprocess.Popen(['lsof', '+w', '-n', '-c', ''.join(['/', players, '/']), '-Fn'], stdout=subprocess.PIPE)
115
+ except OSError:
116
+ self.msg.warn(self.name, "Couldn't execute lsof. Disabling tracker.")
117
+ self.disable()
118
+ return False
119
+
120
+ output = lsof.communicate()[0].decode('utf-8')
121
+ fileregex = re.compile("n(.*(\.mkv|\.mp4|\.avi))")
122
+
123
+ for line in output.splitlines():
124
+ match = fileregex.match(line)
125
+ if match is not None:
126
+ return os.path.basename(match.group(1))
127
+
128
+ return False
129
+
130
+ def _foreach_window(self, hwnd, lParam):
131
+ # Get class name and window title of the current hwnd
132
+ # and add it to the list of the found windows
133
+ length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
134
+
135
+ buff_class = ctypes.create_unicode_buffer(32)
136
+ buff_title = ctypes.create_unicode_buffer(length + 1)
137
+
138
+ ctypes.windll.user32.GetClassNameW(hwnd, buff_class, 32)
139
+ ctypes.windll.user32.GetWindowTextW(hwnd, buff_title, length + 1)
140
+
141
+ self.win32_hwnd_list.append( (buff_class.value, buff_title.value) )
142
+ return True
143
+
144
+ def _get_playing_file_win32(self):
145
+ # Enumerate all windows using the win32 API
146
+ # This will call _foreach_window for each window handle
147
+ # Then return the window title if the class name matches
148
+ # Currently supporting MPC(-HC) and mpv
149
+
150
+ self.win32_hwnd_list = []
151
+ self.EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
152
+ ctypes.windll.user32.EnumWindows(self.EnumWindowsProc(self._foreach_window), 0)
153
+ winregex = re.compile("(\.mkv|\.mp4|\.avi)")
154
+
155
+ for classname, title in self.win32_hwnd_list:
156
+ if classname == 'MediaPlayerClassicW' and winregex.search(title) is not None:
157
+ return title
158
+ elif classname == 'mpv' and winregex.search(title) is not None:
159
+ return title.replace('mpv - ', '')
160
+
161
+ return False
162
+
163
+ def _get_plex_file(self):
164
+ playing_file = plex.playing_file()
165
+ return playing_file
166
+
167
+ def _poll_lsof(self):
168
+ filename = self._get_playing_file_lsof(self.process_name)
169
+ (state, show_tuple) = self._get_playing_show(filename)
170
+ self.update_show_if_needed(state, show_tuple)
171
+
172
+ def _observe_inotify(self, watch_dir):
173
+ self.msg.info(self.name, 'Using inotify.')
174
+ mask = inotify.constants.IN_OPEN | inotify.constants.IN_CLOSE
175
+ i = inotify.adapters.InotifyTree(watch_dir, mask=mask)
176
+ try:
177
+ for event in i.event_gen():
178
+ if event is not None:
179
+ # With inotifyx impl., only the event type was used,
180
+ # such that it only served to poll lsof when an
181
+ # open or close event was received.
182
+ (header, types, path, ev_filename) = event
183
+ if 'IN_ISDIR' not in types\
184
+ and ('IN_OPEN' in types
185
+ or 'IN_CLOSE_NOWRITE' in types
186
+ or 'IN_CLOSE_WRITE' in types):
187
+ self._poll_lsof()
188
+ elif self.last_state != STATE_NOVIDEO:
189
+ # Default blocking duration is 1 second
190
+ # This will count down like inotifyx impl. did
191
+ self.update_show_if_needed(self.last_state, self.last_show_tuple)
192
+ finally:
193
+ self.msg.info(self.name, 'Tracker has stopped.')
194
+ # inotify resource is cleaned-up automatically
195
+
196
+ def _observe_pyinotify(self, watch_dir):
197
+ self.msg.info(self.name, 'Using pyinotify.')
198
+ wm = pyinotify.WatchManager() # Watch Manager
199
+ mask = pyinotify.IN_OPEN | pyinotify.IN_CLOSE_NOWRITE | pyinotify.IN_CLOSE_WRITE
200
+
201
+ class EventHandler(pyinotify.ProcessEvent):
202
+ def my_init(self, parent=None):
203
+ self.parent = parent
204
+
205
+ def process_IN_OPEN(self, event):
206
+ if not event.mask & pyinotify.IN_ISDIR:
207
+ self.parent._poll_lsof()
208
+
209
+ def process_IN_CLOSE_NOWRITE(self, event):
210
+ if not event.mask & pyinotify.IN_ISDIR:
211
+ self.parent._poll_lsof()
212
+
213
+ def process_IN_CLOSE_WRITE(self, event):
214
+ if not event.mask & pyinotify.IN_ISDIR:
215
+ self.parent._poll_lsof()
216
+
217
+ handler = EventHandler(parent=self)
218
+ notifier = pyinotify.Notifier(wm, handler)
219
+ wdd = wm.add_watch(watch_dir, mask, rec=True, auto_add=True)
220
+
221
+ try:
222
+ #notifier.loop()
223
+ timeout = None
224
+ while True:
225
+ if notifier.check_events(timeout):
226
+ notifier.read_events()
227
+ notifier.process_events()
228
+ if self.last_state == STATE_NOVIDEO:
229
+ timeout = None # Block indefinitely
230
+ else:
231
+ timeout = 1000 # Check each second for counting
232
+ else:
233
+ self.update_show_if_needed(self.last_state, self.last_show_tuple)
234
+ finally:
235
+ notifier.stop()
236
+ self.msg.info(self.name, 'Tracker has stopped.')
237
+
238
+ def _observe_polling(self, interval):
239
+ self.msg.info(self.name, "pyinotify not available; using polling (slow).")
240
+ while True:
241
+ # This runs the tracker and update the playing show if necessary
242
+ self._poll_lsof()
243
+
244
+ # Wait for the interval before running check again
245
+ time.sleep(interval)
246
+
247
+ def _observe_win32(self, interval):
248
+ self.msg.info(self.name, "Using Win32.")
249
+
250
+ while True:
251
+ # This runs the tracker and update the playing show if necessary
252
+ filename = self._get_playing_file_win32()
253
+ (state, show_tuple) = self._get_playing_show(filename)
254
+ self.update_show_if_needed(state, show_tuple)
255
+
256
+ # Wait for the interval before running check again
257
+ time.sleep(1)
258
+
259
+ def _observe_plex(self, interval):
260
+ self.msg.info(self.name, "Using Plex.")
261
+
262
+ while True:
263
+ # This stores the last two states of the plex server and only
264
+ # updates if it's ACTIVE.
265
+ plex_status = plex.status()
266
+ self.plex_log.append(plex_status)
267
+
268
+ if self.plex_log[-1] == "ACTIVE" or self.plex_log[-1] == "IDLE":
269
+ self.wait_s = plex.timer_from_file()
270
+ filename = self._get_plex_file()
271
+ (state, show_tuple) = self._get_playing_show(filename)
272
+ self.update_show_if_needed(state, show_tuple)
273
+ elif (self.plex_log[-2] != "NOT_RUNNING" and self.plex_log[-1] == "NOT_RUNNING"):
274
+ self.msg.warn(self.name, "Plex Media Server is not running.")
275
+
276
+ del self.plex_log[0]
277
+ # Wait for the interval before running check again
278
+ time.sleep(30)
279
+
280
+ def _tracker(self, watch_dir, interval):
281
+ if self.plex_enabled:
282
+ self._observe_plex(interval)
283
+ else:
284
+ if os.name == 'nt':
285
+ self._observe_win32(interval)
286
+ elif inotify_available == INOTIFY_INOTIFY:
287
+ self._observe_inotify(watch_dir.encode('utf-8'))
288
+ elif inotify_available == INOTIFY_PYINOTIFY:
289
+ self._observe_pyinotify(watch_dir)
290
+ else:
291
+ self._observe_polling(interval)
292
+
293
+ def update_show_if_needed(self, state, show_tuple):
294
+ if show_tuple:
295
+ (show, episode) = show_tuple
296
+
297
+ if not self.last_show_tuple or show['id'] != self.last_show_tuple[0]['id'] or episode != self.last_show_tuple[1]:
298
+ # There's a new show detected, so
299
+ # let's save the show information and
300
+ # the time we detected it first
301
+
302
+ # But if we're watching a new show, let's make sure turn off
303
+ # the Playing flag on that one first
304
+ if self.last_show_tuple and self.last_show_tuple[0] != show:
305
+ self._emit_signal('playing', self.last_show_tuple[0]['id'], False, 0)
306
+
307
+ self.last_show_tuple = (show, episode)
308
+ self._emit_signal('playing', show['id'], True, episode)
309
+
310
+ self.last_time = time.time()
311
+ self.last_updated = False
312
+
313
+ if not self.last_updated:
314
+ # Check if we need to update the show yet
315
+ if episode == (show['my_progress'] + 1):
316
+ timedif = time.time() - self.last_time
317
+
318
+ if timedif > self.wait_s:
319
+ # Time has passed, let's update
320
+ if self.wait_close:
321
+ # Queue update for when the player closes
322
+ self.msg.info(self.name, 'Waiting for the player to close.')
323
+ self.last_close_queue = True
324
+ self.last_updated = True
325
+ else:
326
+ # Update now
327
+ self._emit_signal('update', show['id'], episode)
328
+ self.last_updated = True
329
+ else:
330
+ self.msg.info(self.name, 'Will update %s %d in %d seconds' % (show['title'], episode, self.wait_s-timedif+1))
331
+ else:
332
+ # We shouldn't update to this episode!
333
+ self.msg.warn(self.name, 'Player is not playing the next episode of %s. Ignoring.' % show['title'])
334
+ self.last_updated = True
335
+ else:
336
+ # The episode was updated already. do nothing
337
+ pass
338
+ elif self.last_state != state:
339
+ # React depending on state
340
+ # STATE_NOVIDEO : No video is playing anymroe
341
+ # STATE_UNRECOGNIZED : There's a new video playing but the regex didn't recognize the format
342
+ # STATE_NOT_FOUND : There's a new video playing but an associated show wasn't found
343
+ if state == STATE_NOVIDEO and self.last_show_tuple:
344
+ # Update now if there's an update queued
345
+ if self.last_close_queue:
346
+ self._emit_signal('update', self.last_show_tuple[0]['id'], self.last_show_tuple[1])
347
+ elif not self.last_updated:
348
+ self.msg.info(self.name, 'Player was closed before update.')
349
+ elif state == STATE_UNRECOGNIZED:
350
+ self.msg.warn(self.name, 'Found video but the file name format couldn\'t be recognized.')
351
+ elif state == STATE_NOT_FOUND:
352
+ self.msg.warn(self.name, 'Found player but show not in list.')
353
+
354
+ # Clear any show previously playing
355
+ if self.last_show_tuple:
356
+ self._emit_signal('playing', self.last_show_tuple[0]['id'], False, self.last_show_tuple[1])
357
+ self.last_updated = False
358
+ self.last_close_queue = False
359
+ self.last_time = 0
360
+ self.last_show_tuple = None
361
+
362
+ self.last_state = state
363
+
364
+ def _get_playing_show(self, filename):
365
+ if not self.active:
366
+ # Don't do anything if the Tracker is disabled
367
+ return (STATE_NOVIDEO, None)
368
+
369
+ if filename:
370
+ if filename == self.last_filename:
371
+ # It's the exact same filename, there's no need to do the processing again
372
+ return (4, self.last_show_tuple)
373
+
374
+ self.last_filename = filename
375
+
376
+ # Do a regex to the filename to get
377
+ # the show title and episode number
378
+ aie = AnimeInfoExtractor(filename)
379
+ (show_title, show_ep) = (aie.getName(), aie.getEpisode())
380
+ if not show_title:
381
+ return (STATE_UNRECOGNIZED, None) # Format not recognized
382
+
383
+ playing_show = utils.guess_show(show_title, self.list)
384
+ if playing_show:
385
+ return (STATE_PLAYING, (playing_show, show_ep))
386
+ else:
387
+ return (STATE_NOT_FOUND, None) # Show not in list
388
+ else:
389
+ self.last_filename = None
390
+ return (STATE_NOVIDEO, None) # Not playing
trackma/ui/__init__.py ADDED
File without changes