trackma 0.6__py3.5.egg → 0.7.4__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 (67) hide show
  1. EGG-INFO/PKG-INFO +1 -1
  2. EGG-INFO/SOURCES.txt +23 -6
  3. EGG-INFO/entry_points.txt +4 -3
  4. EGG-INFO/requires.txt +1 -3
  5. trackma/__pycache__/__init__.cpython-35.pyc +0 -0
  6. trackma/__pycache__/accounts.cpython-35.pyc +0 -0
  7. trackma/__pycache__/data.cpython-35.pyc +0 -0
  8. trackma/__pycache__/engine.cpython-35.pyc +0 -0
  9. trackma/__pycache__/messenger.cpython-35.pyc +0 -0
  10. trackma/__pycache__/utils.cpython-35.pyc +0 -0
  11. trackma/data/kitsu.png +0 -0
  12. trackma/data.py +28 -17
  13. trackma/engine.py +208 -64
  14. trackma/extras/AnimeInfoExtractor.py +14 -5
  15. trackma/extras/__pycache__/AnimeInfoExtractor.cpython-35.pyc +0 -0
  16. trackma/extras/__pycache__/__init__.cpython-35.pyc +0 -0
  17. trackma/lib/__pycache__/__init__.cpython-35.pyc +0 -0
  18. trackma/lib/__pycache__/lib.cpython-35.pyc +0 -0
  19. trackma/lib/__pycache__/libanilist.cpython-35.pyc +0 -0
  20. trackma/lib/__pycache__/libkitsu.cpython-35.pyc +0 -0
  21. trackma/lib/__pycache__/libmal.cpython-35.pyc +0 -0
  22. trackma/lib/__pycache__/libshikimori.cpython-35.pyc +0 -0
  23. trackma/lib/__pycache__/libvndb.cpython-35.pyc +0 -0
  24. trackma/lib/libanilist.py +21 -17
  25. trackma/lib/libkitsu.py +506 -0
  26. trackma/lib/libmal.py +15 -15
  27. trackma/lib/libshikimori.py +3 -3
  28. trackma/lib/libvndb.py +26 -14
  29. trackma/messenger.py +1 -1
  30. trackma/tracker/__init__.py +0 -0
  31. trackma/tracker/__pycache__/__init__.cpython-35.pyc +0 -0
  32. trackma/tracker/__pycache__/inotify.cpython-35.pyc +0 -0
  33. trackma/tracker/__pycache__/inotifyBase.cpython-35.pyc +0 -0
  34. trackma/tracker/__pycache__/plex.cpython-35.pyc +0 -0
  35. trackma/tracker/__pycache__/polling.cpython-35.pyc +0 -0
  36. trackma/tracker/__pycache__/pyinotify.cpython-35.pyc +0 -0
  37. trackma/tracker/__pycache__/tracker.cpython-35.pyc +0 -0
  38. trackma/tracker/__pycache__/win32.cpython-35.pyc +0 -0
  39. trackma/tracker/inotify.py +69 -0
  40. trackma/tracker/inotifyBase.py +107 -0
  41. trackma/tracker/plex.py +139 -0
  42. trackma/tracker/polling.py +55 -0
  43. trackma/tracker/pyinotify.py +90 -0
  44. trackma/tracker/tracker.py +223 -0
  45. trackma/tracker/win32.py +74 -0
  46. trackma/ui/__pycache__/__init__.cpython-35.pyc +0 -0
  47. trackma/ui/__pycache__/cli.cpython-35.pyc +0 -0
  48. trackma/ui/__pycache__/curses.cpython-35.pyc +0 -0
  49. trackma/ui/__pycache__/gtkui.cpython-35.pyc +0 -0
  50. trackma/ui/__pycache__/qt4ui.cpython-35.pyc +0 -0
  51. trackma/ui/__pycache__/qtui.cpython-35.pyc +0 -0
  52. trackma/ui/cli.py +195 -26
  53. trackma/ui/curses.py +133 -66
  54. trackma/ui/gtkui.py +253 -78
  55. trackma/ui/qt4ui.py +25 -0
  56. trackma/ui/qtui.py +357 -186
  57. trackma/utils.py +40 -11
  58. trackma/__pycache__/tracker.cpython-35.pyc +0 -0
  59. trackma/data/hb.jpg +0 -0
  60. trackma/data/melative.jpg +0 -0
  61. trackma/extras/__pycache__/plex.cpython-35.pyc +0 -0
  62. trackma/extras/plex.py +0 -101
  63. trackma/lib/__pycache__/libhb.cpython-35.pyc +0 -0
  64. trackma/lib/__pycache__/libmelative.cpython-35.pyc +0 -0
  65. trackma/lib/libhb.py +0 -237
  66. trackma/lib/libmelative.py +0 -204
  67. trackma/tracker.py +0 -390
trackma/lib/libvndb.py CHANGED
@@ -17,6 +17,7 @@
17
17
  import socket
18
18
  import json
19
19
  import datetime
20
+ import ssl
20
21
 
21
22
  from trackma.lib.lib import lib
22
23
  from trackma import utils
@@ -26,9 +27,9 @@ class libvndb(lib):
26
27
  API class to communicate with VNDB
27
28
  Implements protocol version 1.
28
29
 
29
- Website: http://www.vndb.org
30
- API documentation: http://vndb.org/d11
31
- Designed by: Yorhel <contact@vndb.org> (http://vndb.org/u2)
30
+ Website: https://www.vndb.org
31
+ API documentation: https://vndb.org/d11
32
+ Designed by: Yorhel <contact@vndb.org> (https://vndb.org/u2)
32
33
 
33
34
  """
34
35
  name = 'libvndb'
@@ -36,11 +37,14 @@ class libvndb(lib):
36
37
  api_info = {
37
38
  'name': 'VNDB',
38
39
  'shortname': 'vndb',
39
- 'version': 'v0.3',
40
+ 'version': 2,
40
41
  'merge': True,
41
42
  }
42
43
 
43
44
  default_mediatype = 'vnlist'
45
+ pagesize_list = 100
46
+ pagesize_details = 25
47
+
44
48
  mediatypes = dict()
45
49
  mediatypes['vnlist'] = {
46
50
  'has_progress': False,
@@ -77,17 +81,25 @@ class libvndb(lib):
77
81
  """Initializes the useragent through credentials."""
78
82
  super(libvndb, self).__init__(messenger, account, userconfig)
79
83
 
84
+ self.hostname = "api.vndb.org"
85
+ self.tls = 19535
86
+ self.tcp = 19534
80
87
  self.username = account['username']
81
88
  self.password = account['password']
82
89
  self.logged_in = False
83
90
 
84
91
  def _connect(self):
85
92
  """Create TCP socket and connect"""
93
+
94
+ self.context = ssl.create_default_context()
86
95
  try:
87
- self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
88
- self.s.connect(("api.vndb.org", 19534))
96
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
97
+ self.s = self.context.wrap_socket(s, server_hostname=self.hostname)
98
+ self.s.connect((self.hostname, self.tls))
89
99
  except socket.error:
90
100
  raise utils.APIError("Connection error.")
101
+ except ssl.CertificateError:
102
+ raise utils.APIError("Insecure connection.")
91
103
 
92
104
  def _disconnect(self):
93
105
  """Shutdown and close the socket"""
@@ -168,7 +180,7 @@ class libvndb(lib):
168
180
 
169
181
  (name, data) = self._sendcmd('get %s basic (uid = 0)' % self.mediatype,
170
182
  {'page': page,
171
- 'results': 25
183
+ 'results': self.pagesize_list
172
184
  })
173
185
 
174
186
  # Something is wrong if we don't get a results response.
@@ -195,7 +207,7 @@ class libvndb(lib):
195
207
 
196
208
  (name, data) = self._sendcmd('get votelist basic (uid = 0)',
197
209
  {'page': page,
198
- 'results': 25
210
+ 'results': self.pagesize_list
199
211
  })
200
212
 
201
213
  # Something is wrong if we don't get a results response.
@@ -225,11 +237,11 @@ class libvndb(lib):
225
237
  remaining = [ show['id'] for show in itemlist ]
226
238
  while True:
227
239
  self.msg.info(self.name, 'Requesting details...(%d)' % start)
228
- end = start + 25
240
+ end = start + self.pagesize_details
229
241
 
230
242
  (name, data) = self._sendcmd('get vn basic,details (id = %s)' % repr(remaining[start:end]),
231
243
  {'page': 1,
232
- 'results': 25,
244
+ 'results': self.pagesize_details,
233
245
  })
234
246
 
235
247
  # Something is wrong if we don't get a results response.
@@ -240,7 +252,7 @@ class libvndb(lib):
240
252
  for item in data['items']:
241
253
  infos.append(self._parse_info(item))
242
254
 
243
- start += 25
255
+ start += self.pagesize_details
244
256
  if start >= len(itemlist):
245
257
  # We're going beyond the list, finish
246
258
  break
@@ -258,7 +270,7 @@ class libvndb(lib):
258
270
  self.check_credentials()
259
271
 
260
272
  # Update status with set vnlist
261
- if 'my_status' in item.keys():
273
+ if 'my_status' in item:
262
274
  self.msg.info(self.name, 'Updating VN %s (status)...' % item['title'])
263
275
 
264
276
  if self.mediatype == 'wishlist':
@@ -272,7 +284,7 @@ class libvndb(lib):
272
284
  raise utils.APIError("Invalid response (%s)" % name)
273
285
 
274
286
  # Update vote with set votelist
275
- if 'my_score' in item.keys():
287
+ if 'my_score' in item:
276
288
  self.msg.info(self.name, 'Updating VN %s (vote)...' % item['title'])
277
289
 
278
290
  if item['my_score'] > 0:
@@ -305,7 +317,7 @@ class libvndb(lib):
305
317
 
306
318
  (name, data) = self._sendcmd('get vn basic,details (search ~ "%s")' % criteria,
307
319
  {'page': 1,
308
- 'results': 25,
320
+ 'results': self.pagesize_details,
309
321
  })
310
322
 
311
323
  # Something is wrong if we don't get a results response.
trackma/messenger.py CHANGED
@@ -1,4 +1,4 @@
1
- # This file is part of wMAL.
1
+ # This file is part of Trackma.
2
2
  #
3
3
  # This program is free software: you can redistribute it and/or modify
4
4
  # it under the terms of the GNU General Public License as published by
File without changes
@@ -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,107 @@
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
+ time.sleep(0.01)
42
+ for p in os.listdir("/proc/"):
43
+ if not p.isdigit(): continue
44
+ d = "/proc/%s/fd/" % p
45
+ try:
46
+ for fd in os.listdir(d):
47
+ f = os.readlink(d+fd)
48
+ if f == filename:
49
+ # Get process name
50
+ with open('/proc/%s/cmdline' % p, 'rb') as f:
51
+ cmdline = f.read()
52
+ pname = cmdline.partition(b'\x00')[0]
53
+ self.msg.debug(self.name, 'Playing process: {} {} ({})'.format(p, pname, cmdline))
54
+
55
+ # Check if it's our process
56
+ if self.re_players.search(pname):
57
+ return p, fd
58
+ else:
59
+ self.msg.debug(self.name, "Not read by player ({})".format(pname))
60
+ except OSError:
61
+ pass
62
+
63
+ self.msg.debug(self.name, "Couldn't find playing process.")
64
+ return None, None
65
+
66
+ def _closed_handle(self, pid, fd):
67
+ """ Check if this pid has closed this handle (or never opened it) """
68
+ d = "/proc/%s/fd/%s" % (pid, fd)
69
+ time.sleep(0.01) # TODO : If we don't wait the filehandle will still be there
70
+ return not os.path.islink(d)
71
+
72
+ def _proc_open(self, path, name):
73
+ self.msg.debug(self.name, 'Got OPEN event: {} {}'.format(path, name))
74
+ pathname = os.path.join(path, name)
75
+
76
+ pid, fd = self._is_being_played(pathname)
77
+
78
+ if pid:
79
+ self._emit_signal('detected', path, name)
80
+ self.open_file = (pathname, pid, fd)
81
+
82
+ (state, show_tuple) = self._get_playing_show(name)
83
+ self.msg.debug(self.name, "Got status: {} {}".format(state, show_tuple))
84
+ self.update_show_if_needed(state, show_tuple)
85
+ else:
86
+ self.msg.debug(self.name, "Not played by player, ignoring.")
87
+
88
+ def _proc_close(self, path, name):
89
+ self.msg.debug(self.name, 'Got CLOSE event: {} {}'.format(path, name))
90
+ pathname = os.path.join(path, name)
91
+
92
+ open_pathname, pid, fd = self.open_file
93
+
94
+ if pathname != open_pathname:
95
+ self.msg.debug(self.name, "A different file was closed.")
96
+ return
97
+
98
+ if not self._closed_handle(pid, fd):
99
+ self.msg.debug(self.name, "Our pid hasn't closed the file.")
100
+ return
101
+
102
+ self._emit_signal('detected', path, name)
103
+ self.open_file = (None, None, None)
104
+
105
+ (state, show_tuple) = self._get_playing_show(None)
106
+ self.update_show_if_needed(state, show_tuple)
107
+
@@ -0,0 +1,139 @@
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.host_port = self.config['plex_host']+":"+self.config['plex_port']
36
+ self.update_wait = update_wait
37
+ self.status_log = [None, None]
38
+ self.token = self._get_plex_token()
39
+ super().__init__(messenger, tracker_list, process_name, watch_dir, interval, update_wait, update_close, not_found_prompt)
40
+
41
+ def get_plex_status(self):
42
+ # returns the plex status of the first active session
43
+ try:
44
+ active = int(self._get_sessions_info("MediaContainer", "size"))
45
+
46
+ if active:
47
+ return ACTIVE
48
+ else:
49
+ return IDLE
50
+ except urllib.request.URLError:
51
+ return NOT_RUNNING
52
+
53
+ def playing_file(self):
54
+ # returns the filename of the currently playing file
55
+ if self.get_plex_status() == IDLE:
56
+ return None
57
+
58
+ meta = self._get_sessions_info("Video", "key")
59
+ meta_url = "http://"+self.host_port+meta
60
+ mres = self._get_xml_info(meta_url, "Part", "file")
61
+ name = urllib.parse.unquote(ntpath.basename(mres))
62
+
63
+ return name
64
+
65
+ def timer_from_file(self):
66
+ # returns 80% of video duration for the update timer,
67
+ # roughly the time of the video minus the OP and ED
68
+ if self.get_plex_status() == IDLE:
69
+ return None
70
+
71
+ duration = int(self._get_sessions_info("Video", "duration"))
72
+
73
+ return round((duration*0.80)/60000)*60
74
+
75
+ def observe(self, watch_dir, interval):
76
+ self.msg.info(self.name, "Using Plex.")
77
+
78
+ while self.active:
79
+ self.status_log.append(self.get_plex_status())
80
+
81
+ if self.status_log[-1] == ACTIVE or self.status_log[-1] == IDLE:
82
+ if self.status_log[-1] == IDLE and self.status_log[-2] == NOT_RUNNING:
83
+ self.msg.info(self.name, "Reconnected to Plex.")
84
+
85
+ if self.config['plex_obey_update_wait_s']:
86
+ self.wait_s = self.update_wait
87
+ else:
88
+ self.wait_s = self.timer_from_file()
89
+
90
+ filename = self.playing_file()
91
+ (state, show_tuple) = self._get_playing_show(filename)
92
+ self.update_show_if_needed(state, show_tuple)
93
+ elif self.status_log[-1] == NOT_RUNNING and self.status_log[-2] == NOT_RUNNING:
94
+ self.msg.warn(self.name, "Plex Media Server is not running.")
95
+
96
+ del self.status_log[0]
97
+
98
+ # Wait for the interval before running check again
99
+ time.sleep(interval)
100
+
101
+ def _get_plex_token(self):
102
+ username = self.config['plex_user']
103
+ password = self.config['plex_passwd']
104
+ uuid = self.config['plex_uuid']
105
+
106
+ if not (username and password):
107
+ return ''
108
+
109
+ body = bytes('user[login]=%s&user[password]=%s' % (username, password), "utf-8")
110
+ headers={'X-Plex-Client-Identifier': uuid,
111
+ 'X-Plex-Product': "Trackma",
112
+ 'X-Plex-Version': utils.VERSION}
113
+
114
+ req = urllib.request.Request('https://plex.tv/users/sign_in.xml', body, headers=headers)
115
+ response = urllib.request.urlopen(req)
116
+ data = response.read().decode("utf-8")
117
+
118
+ tdoc = xdmd.parseString(data)
119
+ token = tdoc.getElementsByTagName("user")[0].getAttribute("authToken")
120
+
121
+ return "?X-Plex-Token="+token
122
+
123
+ def _get_xml_info(self, url, tag, attr):
124
+ try:
125
+ uop = urllib.request.urlopen(url)
126
+ except urllib.request.URLError:
127
+ uop = urllib.request.urlopen(url+self.token)
128
+
129
+ doc = xdmd.parse(uop)
130
+ res = doc.getElementsByTagName(tag)[0].getAttribute(attr)
131
+
132
+ return res
133
+
134
+ def _get_sessions_info(self, tag, attr):
135
+ # Get the required info from the /status/sessions url
136
+ session_url = "http://"+self.host_port+"/status/sessions"
137
+ info = self._get_xml_info(session_url, tag, attr)
138
+
139
+ return info
@@ -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
+