trackma 0.6.2__py3.4.egg → 0.7.1__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 (65) hide show
  1. EGG-INFO/PKG-INFO +1 -1
  2. EGG-INFO/SOURCES.txt +10 -6
  3. EGG-INFO/requires.txt +0 -2
  4. trackma/__pycache__/__init__.cpython-34.pyc +0 -0
  5. trackma/__pycache__/accounts.cpython-34.pyc +0 -0
  6. trackma/__pycache__/data.cpython-34.pyc +0 -0
  7. trackma/__pycache__/engine.cpython-34.pyc +0 -0
  8. trackma/__pycache__/messenger.cpython-34.pyc +0 -0
  9. trackma/__pycache__/utils.cpython-34.pyc +0 -0
  10. trackma/data/kitsu.png +0 -0
  11. trackma/data.py +26 -16
  12. trackma/engine.py +68 -17
  13. trackma/extras/AnimeInfoExtractor.py +1 -1
  14. trackma/extras/__pycache__/AnimeInfoExtractor.cpython-34.pyc +0 -0
  15. trackma/extras/__pycache__/__init__.cpython-34.pyc +0 -0
  16. trackma/lib/__pycache__/__init__.cpython-34.pyc +0 -0
  17. trackma/lib/__pycache__/lib.cpython-34.pyc +0 -0
  18. trackma/lib/__pycache__/libanilist.cpython-34.pyc +0 -0
  19. trackma/lib/__pycache__/libkitsu.cpython-34.pyc +0 -0
  20. trackma/lib/__pycache__/libmal.cpython-34.pyc +0 -0
  21. trackma/lib/__pycache__/libshikimori.cpython-34.pyc +0 -0
  22. trackma/lib/__pycache__/libvndb.cpython-34.pyc +0 -0
  23. trackma/lib/libanilist.py +3 -3
  24. trackma/lib/libkitsu.py +507 -0
  25. trackma/lib/libmal.py +6 -6
  26. trackma/lib/libshikimori.py +3 -3
  27. trackma/lib/libvndb.py +12 -9
  28. trackma/messenger.py +1 -1
  29. trackma/tracker/__init__.py +0 -0
  30. trackma/tracker/__pycache__/__init__.cpython-34.pyc +0 -0
  31. trackma/tracker/__pycache__/inotify.cpython-34.pyc +0 -0
  32. trackma/tracker/__pycache__/inotifyBase.cpython-34.pyc +0 -0
  33. trackma/tracker/__pycache__/plex.cpython-34.pyc +0 -0
  34. trackma/tracker/__pycache__/polling.cpython-34.pyc +0 -0
  35. trackma/tracker/__pycache__/pyinotify.cpython-34.pyc +0 -0
  36. trackma/tracker/__pycache__/tracker.cpython-34.pyc +0 -0
  37. trackma/tracker/__pycache__/win32.cpython-34.pyc +0 -0
  38. trackma/tracker/inotify.py +69 -0
  39. trackma/tracker/inotifyBase.py +110 -0
  40. trackma/tracker/plex.py +106 -0
  41. trackma/tracker/polling.py +55 -0
  42. trackma/tracker/pyinotify.py +90 -0
  43. trackma/tracker/tracker.py +221 -0
  44. trackma/tracker/win32.py +74 -0
  45. trackma/ui/__pycache__/__init__.cpython-34.pyc +0 -0
  46. trackma/ui/__pycache__/cli.cpython-34.pyc +0 -0
  47. trackma/ui/__pycache__/curses.cpython-34.pyc +0 -0
  48. trackma/ui/__pycache__/gtkui.cpython-34.pyc +0 -0
  49. trackma/ui/__pycache__/qt4ui.cpython-34.pyc +0 -0
  50. trackma/ui/__pycache__/qtui.cpython-34.pyc +0 -0
  51. trackma/ui/cli.py +110 -13
  52. trackma/ui/curses.py +88 -30
  53. trackma/ui/gtkui.py +120 -58
  54. trackma/ui/qtui.py +161 -49
  55. trackma/utils.py +16 -9
  56. trackma/__pycache__/tracker.cpython-34.pyc +0 -0
  57. trackma/data/hb.jpg +0 -0
  58. trackma/data/melative.jpg +0 -0
  59. trackma/extras/__pycache__/plex.cpython-34.pyc +0 -0
  60. trackma/extras/plex.py +0 -101
  61. trackma/lib/__pycache__/libhb.cpython-34.pyc +0 -0
  62. trackma/lib/__pycache__/libmelative.cpython-34.pyc +0 -0
  63. trackma/lib/libhb.py +0 -239
  64. trackma/lib/libmelative.py +0 -204
  65. trackma/tracker.py +0 -430
@@ -0,0 +1,69 @@
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
+
18
+ import inotify.adapters
19
+ import inotify.constants
20
+
21
+ from trackma.tracker import inotifyBase
22
+ from trackma import utils
23
+
24
+ class inotifyTracker(inotifyBase.inotifyBase):
25
+ name = 'Tracker (inotify)'
26
+
27
+ def observe(self, watch_dir, interval):
28
+ # Note that this lib uses bytestrings for filenames and paths.
29
+ self.msg.info(self.name, 'Using inotify.')
30
+
31
+ watch_dir = watch_dir.encode('utf-8')
32
+ mask = (inotify.constants.IN_OPEN
33
+ | inotify.constants.IN_CLOSE
34
+ | inotify.constants.IN_CREATE
35
+ | inotify.constants.IN_MOVE
36
+ | inotify.constants.IN_DELETE)
37
+
38
+ i = inotify.adapters.InotifyTree(watch_dir, mask=mask)
39
+
40
+ try:
41
+ for event in i.event_gen():
42
+ if event is not None:
43
+ # With inotifyx impl., only the event type was used,
44
+ # such that it only served to poll lsof when an
45
+ # open or close event was received.
46
+ (header, types, path, filename) = event
47
+ if 'IN_ISDIR' not in types:
48
+ # If the file is gone, we remove from library
49
+ if ('IN_MOVED_FROM' in types
50
+ or 'IN_DELETE' in types):
51
+ self._emit_signal('removed', str(path, 'utf-8'), str(filename, 'utf-8'))
52
+ # Otherwise we attempt to add it to library
53
+ # Would check for IN_MOVED_TO or IN_CREATE but no need
54
+ else:
55
+ self._emit_signal('detected', str(path, 'utf-8'), str(filename, 'utf-8'))
56
+
57
+ if 'IN_OPEN' in types:
58
+ self._proc_open(str(path, 'utf-8'), str(filename, 'utf-8'))
59
+ elif ('IN_CLOSE_NOWRITE' in types
60
+ or 'IN_CLOSE_WRITE' in types):
61
+ self._proc_close(str(path, 'utf-8'), str(filename, 'utf-8'))
62
+ elif self.last_state != utils.TRACKER_NOVIDEO and not self.last_updated:
63
+ # Default blocking duration is 1 second
64
+ # This will count down like inotifyx impl. did
65
+ self.update_show_if_needed(self.last_state, self.last_show_tuple)
66
+ finally:
67
+ self.msg.info(self.name, 'Tracker has stopped.')
68
+ # inotify resource is cleaned-up automatically
69
+
@@ -0,0 +1,110 @@
1
+ # This file is part of Trackma.
2
+ #
3
+ # This program is free software: you can redistribute it and/or modify
4
+ # it under the terms of the GNU General Public License as published by
5
+ # the Free Software Foundation, either version 3 of the License, or
6
+ # (at your option) any later version.
7
+ #
8
+ # This program is distributed in the hope that it will be useful,
9
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
+ # GNU General Public License for more details.
12
+ #
13
+ # You should have received a copy of the GNU General Public License
14
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
15
+ #
16
+
17
+ import os
18
+ import re
19
+ import time
20
+
21
+ from trackma.tracker import tracker
22
+ from trackma import utils
23
+
24
+ class inotifyBase(tracker.TrackerBase):
25
+ open_file = (None, None, None)
26
+
27
+ def __init__(self, messenger, tracker_list, process_name, watch_dir, interval, update_wait, update_close, not_found_prompt):
28
+ super().__init__(messenger, tracker_list, process_name, watch_dir, interval, update_wait, update_close, not_found_prompt)
29
+
30
+ self.re_players = re.compile(self.process_name.encode('utf-8'))
31
+
32
+ def _is_being_played(self, filename):
33
+ """
34
+ This function makes sure that the filename is being played
35
+ by the player specified in players.
36
+
37
+ It uses procfs so if we're using inotify that means we're using Linux
38
+ thus we should be safe.
39
+ """
40
+
41
+ for p in os.listdir("/proc/"):
42
+ if not p.isdigit(): continue
43
+ d = "/proc/%s/fd/" % p
44
+ try:
45
+ for fd in os.listdir(d):
46
+ f = os.readlink(d+fd)
47
+ if f == filename:
48
+ # Get process name
49
+ with open('/proc/%s/cmdline' % p, 'rb') as f:
50
+ cmdline = f.read()
51
+ pname = cmdline.partition(b'\x00')[0]
52
+ self.msg.debug(self.name, 'Playing process: {} {} ({})'.format(p, pname, cmdline))
53
+
54
+ # Check if it's our process
55
+ if self.re_players.search(pname):
56
+ return p, fd
57
+ else:
58
+ self.msg.debug(self.name, "Not read by player ({})".format(pname))
59
+ except OSError:
60
+ pass
61
+
62
+ self.msg.debug(self.name, "Couldn't find playing process.")
63
+ return None, None
64
+
65
+ def _closed_handle(self, pid, fd):
66
+ """ Check if this pid has closed this handle (or never opened it) """
67
+ d = "/proc/%s/fd/%s" % (pid, fd)
68
+ return not os.path.islink(d)
69
+
70
+ def _proc_open(self, path, name):
71
+ self.msg.debug(self.name, 'Got OPEN event: {} {}'.format(path, name))
72
+ pathname = os.path.join(path, name)
73
+
74
+ if self.open_file[0]:
75
+ self.msg.debug(self.name, "There's already a tracked open file.")
76
+ return
77
+
78
+ pid, fd = self._is_being_played(pathname)
79
+
80
+ if pid:
81
+ self._emit_signal('detected', path, name)
82
+ self.open_file = (pathname, pid, fd)
83
+
84
+ (state, show_tuple) = self._get_playing_show(name)
85
+ self.msg.debug(self.name, "Got status: {} {}".format(state, show_tuple))
86
+ self.update_show_if_needed(state, show_tuple)
87
+ else:
88
+ self.msg.debug(self.name, "Not played by player, ignoring.")
89
+
90
+ def _proc_close(self, path, name):
91
+ self.msg.debug(self.name, 'Got CLOSE event: {} {}'.format(path, name))
92
+ pathname = os.path.join(path, name)
93
+
94
+ open_pathname, pid, fd = self.open_file
95
+ time.sleep(0.1) # TODO : If we don't wait the filehandle will still be there
96
+
97
+ if pathname != open_pathname:
98
+ self.msg.debug(self.name, "A different file was closed.")
99
+ return
100
+
101
+ if not self._closed_handle(pid, fd):
102
+ self.msg.debug(self.name, "Our pid hasn't closed the file.")
103
+ return
104
+
105
+ self._emit_signal('detected', path, name)
106
+ self.open_file = (None, None, None)
107
+
108
+ (state, show_tuple) = self._get_playing_show(None)
109
+ self.update_show_if_needed(state, show_tuple)
110
+
@@ -0,0 +1,106 @@
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 ntpath
18
+ import time
19
+ import urllib.parse
20
+ import urllib.request
21
+ import xml.dom.minidom as xdmd
22
+
23
+ import trackma.utils as utils
24
+ from trackma.tracker import tracker
25
+
26
+ NOT_RUNNING = 0
27
+ ACTIVE = 1
28
+ IDLE = 2
29
+
30
+ class PlexTracker(tracker.TrackerBase):
31
+ name = 'Tracker (Plex)'
32
+
33
+ def __init__(self, messenger, tracker_list, process_name, watch_dir, interval, update_wait, update_close, not_found_prompt):
34
+ self.config = utils.parse_config(utils.get_root_filename('config.json'), utils.config_defaults)
35
+ self.update_wait = update_wait
36
+ self.status_log = [None, None]
37
+ super().__init__(messenger, tracker_list, process_name, watch_dir, interval, update_wait, update_close, not_found_prompt)
38
+
39
+ def get_plex_status(self):
40
+ # returns the plex status of the first active session
41
+ try:
42
+ active = int(self._get_xml_info("MediaContainer", "size"))
43
+
44
+ if active:
45
+ return ACTIVE
46
+ else:
47
+ return IDLE
48
+ except urllib.request.URLError:
49
+ return NOT_RUNNING
50
+
51
+ def playing_file(self):
52
+ # returns the filename of the currently playing file
53
+ if self.get_plex_status() == IDLE:
54
+ return None
55
+
56
+ attr = self._get_xml_info("Part", "file")
57
+ name = urllib.parse.unquote(ntpath.basename(attr))
58
+
59
+ return name
60
+
61
+ def timer_from_file(self):
62
+ # returns 80% of video duration for the update timer,
63
+ # roughly the time of the video minus the OP and ED
64
+ if self.get_plex_status() == IDLE:
65
+ return None
66
+
67
+ duration = int(self._get_xml_info("Video", "duration"))
68
+
69
+ return round((duration*0.80)/60000)*60
70
+
71
+ def observe(self, watch_dir, interval):
72
+ self.msg.info(self.name, "Using Plex.")
73
+
74
+ while self.active:
75
+ self.status_log.append(self.get_plex_status())
76
+
77
+ if self.status_log[-1] == ACTIVE or self.status_log[-1] == IDLE:
78
+ if self.status_log[-1] == IDLE and self.status_log[-2] == NOT_RUNNING:
79
+ self.msg.info(self.name, "Reconnected to Plex.")
80
+
81
+ if self.config['plex_obey_update_wait_s']:
82
+ self.wait_s = self.update_wait
83
+ else:
84
+ self.wait_s = self.timer_from_file()
85
+
86
+ filename = self.playing_file()
87
+ (state, show_tuple) = self._get_playing_show(filename)
88
+ self.update_show_if_needed(state, show_tuple)
89
+ elif self.status_log[-1] == NOT_RUNNING and self.status_log[-2] == NOT_RUNNING:
90
+ self.msg.warn(self.name, "Plex Media Server is not running.")
91
+
92
+ del self.status_log[0]
93
+
94
+ # Wait for the interval before running check again
95
+ time.sleep(interval)
96
+
97
+ def _get_xml_info(self, tag, attr):
98
+ # Get the required info from the /status/sessions url
99
+ host_port = self.config['plex_host']+":"+self.config['plex_port']
100
+
101
+ session_url = "http://"+host_port+"/status/sessions"
102
+ sdoc = xdmd.parse(urllib.request.urlopen(session_url))
103
+
104
+ res = sdoc.getElementsByTagName(tag)[0].getAttribute(attr)
105
+
106
+ return res
@@ -0,0 +1,55 @@
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 time
18
+ import re
19
+ import os
20
+ import subprocess
21
+
22
+ from trackma.tracker import tracker
23
+
24
+ class PollingTracker(tracker.TrackerBase):
25
+ name = 'Tracker (polling)'
26
+
27
+ def get_playing_file(self, watch_dir, players):
28
+ try:
29
+ lsof = subprocess.Popen(['lsof', '+w', '-n', '-c', ''.join(['/', players, '/']), '-Fn', watch_dir], stdout=subprocess.PIPE)
30
+ except OSError:
31
+ self.msg.warn(self.name, "Couldn't execute lsof. Disabling tracker.")
32
+ self.disable()
33
+ return None
34
+
35
+ output = lsof.communicate()[0].decode('utf-8')
36
+ fileregex = re.compile("n(.*(\.mkv|\.mp4|\.avi))")
37
+
38
+ for line in output.splitlines():
39
+ match = fileregex.match(line)
40
+ if match is not None:
41
+ return os.path.basename(match.group(1))
42
+
43
+ return None
44
+
45
+ def observe(self, watch_dir, interval):
46
+ self.msg.info(self.name, "pyinotify not available; using polling (slow).")
47
+ while self.active:
48
+ # This runs the tracker and update the playing show if necessary
49
+ filename = self.get_playing_file(watch_dir, self.process_name)
50
+ (state, show_tuple) = self._get_playing_show(filename)
51
+ self.update_show_if_needed(state, show_tuple)
52
+
53
+ # Wait for the interval before running check again
54
+ time.sleep(interval)
55
+
@@ -0,0 +1,90 @@
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 pyinotify
18
+
19
+ from trackma.tracker import inotifyBase
20
+ from trackma import utils
21
+
22
+ class pyinotifyTracker(inotifyBase.inotifyBase):
23
+ name = 'Tracker (pyinotify)'
24
+
25
+ def observe(self, watch_dir, interval):
26
+ self.msg.info(self.name, 'Using pyinotify.')
27
+ wm = pyinotify.WatchManager() # Watch Manager
28
+ mask = (pyinotify.IN_OPEN
29
+ | pyinotify.IN_CLOSE_NOWRITE
30
+ | pyinotify.IN_CLOSE_WRITE
31
+ | pyinotify.IN_CREATE
32
+ | pyinotify.IN_MOVED_FROM
33
+ | pyinotify.IN_MOVED_TO
34
+ | pyinotify.IN_DELETE)
35
+
36
+ class EventHandler(pyinotify.ProcessEvent):
37
+ def my_init(self, parent=None):
38
+ self.parent = parent
39
+
40
+ def process_IN_OPEN(self, event):
41
+ if not event.mask & pyinotify.IN_ISDIR:
42
+ self.parent._proc_open(event.path, event.name)
43
+
44
+ def process_IN_CLOSE_NOWRITE(self, event):
45
+ if not event.mask & pyinotify.IN_ISDIR:
46
+ self.parent._proc_close(event.path, event.name)
47
+
48
+ def process_IN_CLOSE_WRITE(self, event):
49
+ if not event.mask & pyinotify.IN_ISDIR:
50
+ self.parent._proc_close(event.path, event.name)
51
+
52
+ def process_IN_CREATE(self, event):
53
+ if not event.mask & pyinotify.IN_ISDIR:
54
+ self.parent._emit_signal('detected', event.path, event.name)
55
+
56
+ def process_IN_MOVED_TO(self, event):
57
+ if not event.mask & pyinotify.IN_ISDIR:
58
+ self.parent._emit_signal('detected', event.path, event.name)
59
+
60
+ def process_IN_MOVED_FROM(self, event):
61
+ if not event.mask & pyinotify.IN_ISDIR:
62
+ self.parent._emit_signal('removed', event.path, event.name)
63
+
64
+ def process_IN_DELETE(self, event):
65
+ if not event.mask & pyinotify.IN_ISDIR:
66
+ self.parent._emit_signal('removed', event.path, event.name)
67
+
68
+ handler = EventHandler(parent=self)
69
+ notifier = pyinotify.Notifier(wm, handler)
70
+ self.msg.debug(self.name, 'Watching directory {}'.format(watch_dir))
71
+ wdd = wm.add_watch(watch_dir, mask, rec=True, auto_add=True)
72
+
73
+ try:
74
+ #notifier.loop()
75
+ timeout = None
76
+ while self.active:
77
+ if notifier.check_events(timeout):
78
+ notifier.read_events()
79
+ notifier.process_events()
80
+ if self.last_state == utils.TRACKER_NOVIDEO or self.last_updated:
81
+ timeout = None # Block indefinitely
82
+ else:
83
+ timeout = 1000 # Check each second for counting
84
+ else:
85
+ self.msg.debug(self.name, "Sending last state {} {}".format(self.last_state, self.last_show_tuple))
86
+ self.update_show_if_needed(self.last_state, self.last_show_tuple)
87
+ finally:
88
+ notifier.stop()
89
+ self.msg.info(self.name, 'Tracker has stopped.')
90
+
@@ -0,0 +1,221 @@
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 threading
18
+ import re
19
+ import time
20
+ import os
21
+
22
+ import ctypes
23
+
24
+ from trackma import messenger
25
+ from trackma import utils
26
+ from trackma.extras import AnimeInfoExtractor
27
+
28
+ class TrackerBase(object):
29
+ msg = None
30
+ active = True
31
+ list = None
32
+ last_show_tuple = None
33
+ last_filename = None
34
+ last_state = utils.TRACKER_NOVIDEO
35
+ last_time = 0
36
+ last_updated = False
37
+ last_close_queue = None
38
+ timer = None
39
+
40
+ name = 'Tracker'
41
+
42
+ signals = {
43
+ 'state': None,
44
+ 'detected': None,
45
+ 'playing': None,
46
+ 'removed': None,
47
+ 'update': None,
48
+ 'unrecognised': None,
49
+ }
50
+
51
+ def __init__(self, messenger, tracker_list, process_name, watch_dir, interval, update_wait, update_close, not_found_prompt):
52
+ self.msg = messenger
53
+ self.msg.info(self.name, 'Initializing...')
54
+
55
+ self.list = tracker_list
56
+ self.process_name = process_name
57
+
58
+ tracker_args = (watch_dir, interval)
59
+ self.wait_s = update_wait
60
+ self.wait_close = update_close
61
+ self.not_found_prompt = not_found_prompt
62
+ tracker_t = threading.Thread(target=self.observe, args=tracker_args)
63
+ tracker_t.daemon = True
64
+ self.msg.debug(self.name, 'Enabling tracker...')
65
+ tracker_t.start()
66
+
67
+ def set_message_handler(self, message_handler):
68
+ """Changes the message handler function on the fly."""
69
+ self.msg = message_handler
70
+
71
+ def disable(self):
72
+ self.active = False
73
+
74
+ def enable(self):
75
+ self.active = True
76
+
77
+ def update_list(self, tracker_list):
78
+ self.list = tracker_list
79
+
80
+ def connect_signal(self, signal, callback):
81
+ try:
82
+ self.signals[signal] = callback
83
+ except KeyError:
84
+ raise utils.EngineFatal("Invalid signal.")
85
+
86
+ def observe(self, watch_dir, interval):
87
+ raise NotImplementedError
88
+
89
+ def get_status(self):
90
+ return {
91
+ 'state': self.last_state,
92
+ 'timer': self.timer,
93
+ 'show': self.last_show_tuple,
94
+ 'filename': self.last_filename,
95
+ }
96
+
97
+ def _emit_signal(self, signal, *args):
98
+ try:
99
+ if self.signals[signal]:
100
+ self.signals[signal](*args)
101
+ except KeyError:
102
+ raise Exception("Call to undefined signal.")
103
+
104
+ def _update_show(self, state, show_tuple):
105
+ (show, episode) = show_tuple
106
+ self.timer = int(1 + self.wait_s - (time.time() - self.last_time))
107
+ self._emit_signal('state', state, self.timer)
108
+
109
+ if self.timer <= 0:
110
+ # Perform show update
111
+ self.last_updated = True
112
+ action = None
113
+ if state == utils.TRACKER_PLAYING:
114
+ action = lambda: self._emit_signal('update', show['id'], episode)
115
+ elif state == utils.TRACKER_NOT_FOUND:
116
+ action = lambda: self._emit_signal('unrecognised', show, episode)
117
+
118
+ if self.wait_close:
119
+ self.msg.info(self.name, 'Waiting for the player to close.')
120
+ self.last_close_queue = action
121
+ elif action:
122
+ action()
123
+
124
+ def _ignore_current(self):
125
+ # Stops attempt to update current episode
126
+ self.last_updated = True
127
+ self.last_state = utils.TRACKER_IGNORED
128
+ self._emit_signal('state', utils.TRACKER_IGNORED, None)
129
+
130
+ def _update_state(self, state):
131
+ # Call when show or state is changed. Perform queued update if any, and clear playing flag.
132
+ if self.last_close_queue:
133
+ self.last_close_queue()
134
+ self.last_close_queue = None
135
+ self.last_time = time.time()
136
+ if self.last_show_tuple and self.last_state == utils.TRACKER_PLAYING:
137
+ (last_show, last_show_ep) = self.last_show_tuple
138
+ self._emit_signal('playing', last_show['id'], False, last_show_ep)
139
+
140
+ def update_show_if_needed(self, state, show_tuple):
141
+ # If the state and show are unchanged, skip to countdown
142
+ if show_tuple and state == self.last_state and show_tuple == self.last_show_tuple and not self.last_updated:
143
+ self._update_show(state, show_tuple)
144
+ return
145
+
146
+ if show_tuple and show_tuple != self.last_show_tuple:
147
+ (show, episode) = show_tuple
148
+ self._update_state(state)
149
+ # There's a new show/ep detected, so let's save the show information
150
+ self.last_show_tuple = show_tuple
151
+ if state == utils.TRACKER_PLAYING:
152
+ self._emit_signal('playing', show['id'], True, episode)
153
+ # Check if we shouldn't update the show
154
+ if episode != (show['my_progress'] + 1):
155
+ self.msg.warn(self.name, 'Not playing the next episode of %s. Ignoring.' % show['title'])
156
+ self._ignore_current()
157
+ return
158
+ if episode < 1 or (show['total'] and episode > show['total']):
159
+ self.msg.warn(self.name, 'Playing an invalid episode of %s. Ignoring.' % show['title'])
160
+ self._ignore_current()
161
+ return
162
+
163
+ # Start our countdown
164
+ (show, episode) = show_tuple
165
+ if state == utils.TRACKER_PLAYING:
166
+ self.msg.info(self.name, 'Will update %s %d in %d seconds' % (show['title'], episode, self.wait_s))
167
+ elif state == utils.TRACKER_NOT_FOUND:
168
+ self.msg.info(self.name, 'Will add %s %d in %d seconds' % (show, episode, self.wait_s))
169
+ self._update_show(state, show_tuple)
170
+
171
+ elif self.last_state != state:
172
+ self._update_state(state)
173
+
174
+ # React depending on state
175
+ if state == utils.TRACKER_NOVIDEO: # No video is playing
176
+ # Video didn't get to update phase before it was closed
177
+ if self.last_state == utils.TRACKER_PLAYING and not self.last_updated:
178
+ self.msg.info(self.name, 'Player was closed before update.')
179
+ elif state == utils.TRACKER_UNRECOGNIZED: # There's a new video playing but the regex didn't recognize the format
180
+ self.msg.warn(self.name, 'Found video but the file name format couldn\'t be recognized.')
181
+ elif state == utils.TRACKER_NOT_FOUND: # There's a new video playing but an associated show wasn't found
182
+ self.msg.warn(self.name, 'Found player but show not in list.')
183
+
184
+ self.last_show_tuple = None
185
+ self.last_updated = False
186
+ self.timer = None
187
+ self._emit_signal('state', state, None)
188
+
189
+ self.last_state = state
190
+
191
+ def _get_playing_show(self, filename):
192
+ if not self.active:
193
+ # Don't do anything if the Tracker is disabled
194
+ return (utils.TRACKER_NOVIDEO, None)
195
+
196
+ if filename:
197
+ if filename == self.last_filename:
198
+ # It's the exact same filename, there's no need to do the processing again
199
+ return (self.last_state, self.last_show_tuple)
200
+
201
+ self.last_filename = filename
202
+
203
+ # Do a regex to the filename to get
204
+ # the show title and episode number
205
+ aie = AnimeInfoExtractor(filename)
206
+ (show_title, show_ep) = (aie.getName(), aie.getEpisode())
207
+ if not show_title:
208
+ return (utils.TRACKER_UNRECOGNIZED, None) # Format not recognized
209
+
210
+ playing_show = utils.guess_show(show_title, self.list)
211
+ if playing_show:
212
+ return (utils.TRACKER_PLAYING, (playing_show, show_ep))
213
+ else:
214
+ # Show not in list
215
+ if self.not_found_prompt:
216
+ return (utils.TRACKER_NOT_FOUND, (show_title, show_ep))
217
+ else:
218
+ return (utils.TRACKER_NOT_FOUND, None)
219
+ else:
220
+ self.last_filename = None
221
+ return (utils.TRACKER_NOVIDEO, None) # Not playing