trackma 0.7.5__py3.6.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 (73) hide show
  1. EGG-INFO/PKG-INFO +22 -0
  2. EGG-INFO/SOURCES.txt +55 -0
  3. EGG-INFO/dependency_links.txt +1 -0
  4. EGG-INFO/entry_points.txt +9 -0
  5. EGG-INFO/not-zip-safe +1 -0
  6. EGG-INFO/requires.txt +8 -0
  7. EGG-INFO/top_level.txt +1 -0
  8. trackma/__init__.py +0 -0
  9. trackma/__pycache__/__init__.cpython-36.pyc +0 -0
  10. trackma/__pycache__/accounts.cpython-36.pyc +0 -0
  11. trackma/__pycache__/data.cpython-36.pyc +0 -0
  12. trackma/__pycache__/engine.cpython-36.pyc +0 -0
  13. trackma/__pycache__/messenger.cpython-36.pyc +0 -0
  14. trackma/__pycache__/utils.cpython-36.pyc +0 -0
  15. trackma/accounts.py +145 -0
  16. trackma/data/anilist.jpg +0 -0
  17. trackma/data/icon.png +0 -0
  18. trackma/data/kitsu.png +0 -0
  19. trackma/data/mal.jpg +0 -0
  20. trackma/data/shikimori.jpg +0 -0
  21. trackma/data/vndb.jpg +0 -0
  22. trackma/data.py +620 -0
  23. trackma/engine.py +979 -0
  24. trackma/extras/AnimeInfoExtractor.py +317 -0
  25. trackma/extras/__init__.py +1 -0
  26. trackma/extras/__pycache__/AnimeInfoExtractor.cpython-36.pyc +0 -0
  27. trackma/extras/__pycache__/__init__.cpython-36.pyc +0 -0
  28. trackma/lib/__init__.py +0 -0
  29. trackma/lib/__pycache__/__init__.cpython-36.pyc +0 -0
  30. trackma/lib/__pycache__/lib.cpython-36.pyc +0 -0
  31. trackma/lib/__pycache__/libanilist.cpython-36.pyc +0 -0
  32. trackma/lib/__pycache__/libkitsu.cpython-36.pyc +0 -0
  33. trackma/lib/__pycache__/libmal.cpython-36.pyc +0 -0
  34. trackma/lib/__pycache__/libshikimori.cpython-36.pyc +0 -0
  35. trackma/lib/__pycache__/libvndb.cpython-36.pyc +0 -0
  36. trackma/lib/lib.py +162 -0
  37. trackma/lib/libanilist.py +474 -0
  38. trackma/lib/libkitsu.py +506 -0
  39. trackma/lib/libmal.py +707 -0
  40. trackma/lib/libshikimori.py +340 -0
  41. trackma/lib/libvndb.py +387 -0
  42. trackma/messenger.py +42 -0
  43. trackma/tracker/__init__.py +0 -0
  44. trackma/tracker/__pycache__/__init__.cpython-36.pyc +0 -0
  45. trackma/tracker/__pycache__/inotify.cpython-36.pyc +0 -0
  46. trackma/tracker/__pycache__/inotifyBase.cpython-36.pyc +0 -0
  47. trackma/tracker/__pycache__/plex.cpython-36.pyc +0 -0
  48. trackma/tracker/__pycache__/polling.cpython-36.pyc +0 -0
  49. trackma/tracker/__pycache__/pyinotify.cpython-36.pyc +0 -0
  50. trackma/tracker/__pycache__/tracker.cpython-36.pyc +0 -0
  51. trackma/tracker/__pycache__/win32.cpython-36.pyc +0 -0
  52. trackma/tracker/inotify.py +69 -0
  53. trackma/tracker/inotifyBase.py +107 -0
  54. trackma/tracker/plex.py +144 -0
  55. trackma/tracker/polling.py +55 -0
  56. trackma/tracker/pyinotify.py +90 -0
  57. trackma/tracker/tracker.py +226 -0
  58. trackma/tracker/win32.py +74 -0
  59. trackma/ui/__init__.py +0 -0
  60. trackma/ui/__pycache__/__init__.cpython-36.pyc +0 -0
  61. trackma/ui/__pycache__/cli-single.cpython-36.pyc +0 -0
  62. trackma/ui/__pycache__/cli.cpython-36.pyc +0 -0
  63. trackma/ui/__pycache__/curses.cpython-36.pyc +0 -0
  64. trackma/ui/__pycache__/gtkui.cpython-36.pyc +0 -0
  65. trackma/ui/__pycache__/qt4ui.cpython-36.pyc +0 -0
  66. trackma/ui/__pycache__/qtui.cpython-36.pyc +0 -0
  67. trackma/ui/cli-single.py +3 -0
  68. trackma/ui/cli.py +1035 -0
  69. trackma/ui/curses.py +1156 -0
  70. trackma/ui/gtkui.py +2847 -0
  71. trackma/ui/qt4ui.py +25 -0
  72. trackma/ui/qtui.py +3273 -0
  73. trackma/utils.py +416 -0
trackma/lib/libvndb.py ADDED
@@ -0,0 +1,387 @@
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 socket
18
+ import json
19
+ import datetime
20
+ import ssl
21
+
22
+ from trackma.lib.lib import lib
23
+ from trackma import utils
24
+
25
+ class libvndb(lib):
26
+ """
27
+ API class to communicate with VNDB
28
+ Implements protocol version 1.
29
+
30
+ Website: https://www.vndb.org
31
+ API documentation: https://vndb.org/d11
32
+ Designed by: Yorhel <contact@vndb.org> (https://vndb.org/u2)
33
+
34
+ """
35
+ name = 'libvndb'
36
+
37
+ api_info = {
38
+ 'name': 'VNDB',
39
+ 'shortname': 'vndb',
40
+ 'version': 2,
41
+ 'merge': True,
42
+ }
43
+
44
+ default_mediatype = 'vnlist'
45
+ pagesize_list = 100
46
+ pagesize_details = 25
47
+
48
+ mediatypes = dict()
49
+ mediatypes['vnlist'] = {
50
+ 'has_progress': False,
51
+ 'can_score': True,
52
+ 'can_status': True,
53
+ 'can_add': True,
54
+ 'can_delete': True,
55
+ 'can_update': False,
56
+ 'can_play': False,
57
+ 'statuses': [1, 2, 3, 4, 0],
58
+ 'statuses_dict': { 1: 'Playing', 2: 'Finished', 3: 'Stalled', 4: 'Dropped', 0: 'Unknown' },
59
+ 'score_max': 10,
60
+ 'score_step': 0.1,
61
+ 'status_start': 1,
62
+ 'status_finish': 2,
63
+ }
64
+ mediatypes['wishlist'] = {
65
+ 'has_progress': False,
66
+ 'can_score': True,
67
+ 'can_status': True,
68
+ 'can_add': True,
69
+ 'can_delete': True,
70
+ 'can_update': False,
71
+ 'can_play': False,
72
+ 'statuses': [0, 1, 2, 3],
73
+ 'statuses_dict': { 0: 'High', 1: 'Medium', 2: 'Low', 3: 'Blacklist' },
74
+ 'score_max': 10,
75
+ 'score_step': 0.1,
76
+ 'status_start': None,
77
+ 'status_finish': None,
78
+ }
79
+
80
+ def __init__(self, messenger, account, userconfig):
81
+ """Initializes the useragent through credentials."""
82
+ super(libvndb, self).__init__(messenger, account, userconfig)
83
+
84
+ self.hostname = "api.vndb.org"
85
+ self.tls = 19535
86
+ self.tcp = 19534
87
+ self.username = account['username']
88
+ self.password = account['password']
89
+ self.logged_in = False
90
+
91
+ def _connect(self):
92
+ """Create TCP socket and connect"""
93
+
94
+ self.context = ssl.create_default_context()
95
+ try:
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))
99
+ except socket.error:
100
+ raise utils.APIError("Connection error.")
101
+ except ssl.CertificateError:
102
+ raise utils.APIError("Insecure connection.")
103
+
104
+ def _disconnect(self):
105
+ """Shutdown and close the socket"""
106
+ self.s.shutdown(socket.SHUT_RDWR)
107
+ self.s.close()
108
+
109
+ def _sendcmd(self, cmd, options=None):
110
+ """Send a VNDB compatible command and return the response data"""
111
+ msg = cmd
112
+ if options:
113
+ msg += " " + json.dumps(options, separators=(',',':'))
114
+ msg = msg.encode('utf-8')
115
+ msg += b"\x04" # EOT
116
+
117
+ # Send message
118
+ self.s.sendall(msg)
119
+
120
+ # Construct response
121
+ lines = []
122
+ while True:
123
+ line = self.s.recv(65536)
124
+ if line.endswith(b"\x04"):
125
+ line = line.strip(b"\x04")
126
+ lines.append(line)
127
+ response = b"".join(lines).decode('utf-8')
128
+ break
129
+ else:
130
+ lines.append(line)
131
+
132
+ # Separate into response name and JSON data
133
+ _resp = response.split(' ', 1)
134
+ name = _resp[0]
135
+ try:
136
+ data = json.loads(_resp[1])
137
+ except IndexError:
138
+ data = None
139
+
140
+ # Treat error as an exception
141
+ if name == 'error':
142
+ raise utils.APIError(data['msg'])
143
+
144
+ return (name, data)
145
+
146
+ def check_credentials(self):
147
+ """Checks if credentials are correct; returns True or False."""
148
+ if self.logged_in:
149
+ return True
150
+
151
+ self.msg.info(self.name, 'Connecting...')
152
+ self._connect()
153
+
154
+ self.msg.info(self.name, 'Logging in...')
155
+ (name, data) = self._sendcmd('login',
156
+ {'protocol': 1,
157
+ 'client': 'Trackma',
158
+ 'clientver': self.api_info['version'],
159
+ 'username': self.username,
160
+ 'password': self.password,
161
+ })
162
+
163
+ if name == 'ok':
164
+ self.logged_in = True
165
+ self._set_userconfig('username', self.username)
166
+ return True
167
+ else:
168
+ return False
169
+
170
+ def fetch_list(self):
171
+ """Queries the full list from the remote server.
172
+ Returns the list if successful, False otherwise."""
173
+ self.check_credentials()
174
+
175
+ # Retrieve VNs per pages
176
+ page = 1
177
+ vns = dict()
178
+ while True:
179
+ self.msg.info(self.name, 'Downloading list... (%d)' % page)
180
+
181
+ (name, data) = self._sendcmd('get %s basic (uid = 0)' % self.mediatype,
182
+ {'page': page,
183
+ 'results': self.pagesize_list
184
+ })
185
+
186
+ # Something is wrong if we don't get a results response.
187
+ if name != 'results':
188
+ raise utils.APIFatal("Invalid response (%s)" % name)
189
+
190
+ # Process list
191
+ for item in data['items']:
192
+ vnid = item['vn']
193
+ vns[vnid] = utils.show()
194
+ vns[vnid]['id'] = vnid
195
+ vns[vnid]['url'] = self._get_url(vnid)
196
+ vns[vnid]['my_status'] = item.get('status', item.get('priority'))
197
+
198
+ if not data['more']:
199
+ # No more VNs, finish
200
+ break
201
+ page += 1
202
+
203
+ # Retrieve scores per pages
204
+ page = 1
205
+ while True:
206
+ self.msg.info(self.name, 'Downloading votes... (%d)' % page)
207
+
208
+ (name, data) = self._sendcmd('get votelist basic (uid = 0)',
209
+ {'page': page,
210
+ 'results': self.pagesize_list
211
+ })
212
+
213
+ # Something is wrong if we don't get a results response.
214
+ if name != 'results':
215
+ raise utils.APIFatal("Invalid response (%s)" % name)
216
+
217
+ for item in data['items']:
218
+ vnid = item['vn']
219
+ try:
220
+ vns[vnid]['my_score'] = (item['vote'] / 10.0)
221
+ except KeyError:
222
+ # Ghost vote; ignore it
223
+ pass
224
+
225
+ if not data['more']:
226
+ # No more VNs, finish
227
+ break
228
+ page += 1
229
+
230
+ return vns
231
+
232
+ def request_info(self, itemlist):
233
+ self.check_credentials()
234
+
235
+ start = 0
236
+ infos = list()
237
+ remaining = [ show['id'] for show in itemlist ]
238
+ while True:
239
+ self.msg.info(self.name, 'Requesting details...(%d)' % start)
240
+ end = start + self.pagesize_details
241
+
242
+ (name, data) = self._sendcmd('get vn basic,details (id = %s)' % repr(remaining[start:end]),
243
+ {'page': 1,
244
+ 'results': self.pagesize_details,
245
+ })
246
+
247
+ # Something is wrong if we don't get a results response.
248
+ if name != 'results':
249
+ raise utils.APIFatal("Invalid response (%s)" % name)
250
+
251
+ # Process list
252
+ for item in data['items']:
253
+ infos.append(self._parse_info(item))
254
+
255
+ start += self.pagesize_details
256
+ if start >= len(itemlist):
257
+ # We're going beyond the list, finish
258
+ break
259
+
260
+ self._emit_signal('show_info_changed', infos)
261
+ return infos
262
+
263
+ def add_show(self, item):
264
+ # When we try to "update" a VN that isn't in the list, the
265
+ # VNDB API automatically inserts it, so we can use the same
266
+ # command.
267
+ self.update_show(item)
268
+
269
+ def update_show(self, item):
270
+ self.check_credentials()
271
+
272
+ # Update status with set vnlist
273
+ if 'my_status' in item:
274
+ self.msg.info(self.name, 'Updating VN %s (status)...' % item['title'])
275
+
276
+ if self.mediatype == 'wishlist':
277
+ values = {'priority': item['my_status']}
278
+ else:
279
+ values = {'status': item['my_status']}
280
+
281
+ (name, data) = self._sendcmd('set %s %d' % (self.mediatype, item['id']), values)
282
+
283
+ if name != 'ok':
284
+ raise utils.APIError("Invalid response (%s)" % name)
285
+
286
+ # Update vote with set votelist
287
+ if 'my_score' in item:
288
+ self.msg.info(self.name, 'Updating VN %s (vote)...' % item['title'])
289
+
290
+ if item['my_score'] > 0:
291
+ # Add or update vote
292
+ values = {'vote': item['my_score'] * 10}
293
+ else:
294
+ # Delete vote if it's 0
295
+ values = None
296
+
297
+ (name, data) = self._sendcmd('set votelist %d' % item['id'], values)
298
+
299
+ if name != 'ok':
300
+ raise utils.APIError("Invalid response (%s)" % name)
301
+
302
+ def delete_show(self, item):
303
+ self.check_credentials()
304
+
305
+ self.msg.info(self.name, 'Deleting VN %s...' % item['title'])
306
+
307
+ (name, data) = self._sendcmd('set %s %d' % (self.mediatype, item['id']))
308
+
309
+ if name != 'ok':
310
+ raise utils.APIError("Invalid response (%s)" % name)
311
+
312
+ def search(self, criteria):
313
+ self.check_credentials()
314
+
315
+ results = list()
316
+ self.msg.info(self.name, 'Searching for %s...' % criteria)
317
+
318
+ (name, data) = self._sendcmd('get vn basic,details (search ~ "%s")' % criteria,
319
+ {'page': 1,
320
+ 'results': self.pagesize_details,
321
+ })
322
+
323
+ # Something is wrong if we don't get a results response.
324
+ if name != 'results':
325
+ raise utils.APIFatal("Invalid response (%s)" % name)
326
+
327
+ # Process list
328
+ for item in data['items']:
329
+ results.append(self._parse_info(item))
330
+
331
+ self._emit_signal('show_info_changed', results)
332
+
333
+ if not results:
334
+ raise utils.APIError('No results.')
335
+
336
+ return results
337
+
338
+ def logout(self):
339
+ self.msg.info(self.name, 'Disconnecting...')
340
+ self._disconnect()
341
+ self.logged_in = False
342
+
343
+ def merge(self, show, info):
344
+ show['title'] = info['title']
345
+ show['image'] = info.get('image')
346
+ show['start_date'] = info.get('start_date')
347
+ if show['start_date'] and show['start_date'] > datetime.datetime.now():
348
+ show['status'] = utils.STATUS_NOTYET
349
+ else:
350
+ show['status'] = utils.STATUS_FINISHED
351
+
352
+ def _parse_info(self, item):
353
+ start_date = self._str2date(item['released'])
354
+
355
+ info = utils.show()
356
+ info.update({'id': item['id'],
357
+ 'title': item['title'],
358
+ 'image': item['image'],
359
+ 'url': self._get_url(item['id']),
360
+ 'start_date': self._str2date(item['released']),
361
+ 'extra': [
362
+ ('Original Name', item['original']),
363
+ ('Released', item['released']),
364
+ ('Languages', ','.join(item['languages'])),
365
+ ('Original Language', ','.join(item['orig_lang'])),
366
+ ('Platforms', ','.join(item['platforms'])),
367
+ ('Aliases', item['aliases']),
368
+ ('Length', item['length']),
369
+ ('Description', item['description']),
370
+ ('Links', item['links']),
371
+ ]
372
+ })
373
+ return info
374
+
375
+ def _get_url(self, vnid):
376
+ return "http://vndb.org/v%d" % vnid
377
+
378
+ def _str2date(self, string):
379
+ if string != '0000-00-00':
380
+ try:
381
+ return datetime.datetime.strptime(string, "%Y-%m-%d")
382
+ except ValueError:
383
+ return None # Ignore date if it's invalid
384
+ else:
385
+ return None
386
+
387
+
trackma/messenger.py ADDED
@@ -0,0 +1,42 @@
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
+ TYPE_DEBUG = 1
18
+ TYPE_INFO = 2
19
+ #TYPE_ERROR = 3
20
+ #TYPE_FATAL = 4
21
+ TYPE_WARN = 5
22
+
23
+ class Messenger():
24
+ _handler = None
25
+
26
+ def __init__(self, handler):
27
+ self._handler = handler
28
+
29
+ def set_handler(self, handler):
30
+ self._handler = handler
31
+
32
+ def debug(self, classname, msg):
33
+ if self._handler:
34
+ self._handler(classname, TYPE_DEBUG, msg)
35
+
36
+ def info(self, classname, msg):
37
+ if self._handler:
38
+ self._handler(classname, TYPE_INFO, msg)
39
+
40
+ def warn(self, classname, msg):
41
+ if self._handler:
42
+ self._handler(classname, TYPE_WARN, msg)
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
+