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
@@ -0,0 +1,474 @@
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 <https://www.gnu.org/licenses/>.
15
+ #
16
+
17
+ import json
18
+ import urllib.parse
19
+ import urllib.request
20
+ import socket
21
+ import time
22
+ import datetime
23
+
24
+ from trackma.lib.lib import lib
25
+ from trackma import utils
26
+
27
+ class libanilist(lib):
28
+ """
29
+ API class to communicate with Anilist
30
+
31
+ Website: https://anilist.co
32
+
33
+ messenger: Messenger object to send useful messages to
34
+ """
35
+ name = 'libanilist'
36
+ msg = None
37
+ logged_in = False
38
+
39
+ api_info = { 'name': 'Anilist', 'shortname': 'anilist', 'version': '2.0', 'merge': False }
40
+ mediatypes = dict()
41
+ mediatypes['anime'] = {
42
+ 'has_progress': True,
43
+ 'can_add': True,
44
+ 'can_delete': True,
45
+ 'can_score': True,
46
+ 'can_status': True,
47
+ 'can_update': True,
48
+ 'can_play': True,
49
+ 'can_date': True,
50
+ 'date_next_ep': True,
51
+ 'status_start': 'CURRENT',
52
+ 'status_finish': 'COMPLETED',
53
+ 'statuses': ['CURRENT', 'COMPLETED', 'PAUSED', 'DROPPED', 'PLANNING'],
54
+ 'statuses_dict': {
55
+ 'CURRENT': 'Watching',
56
+ 'COMPLETED': 'Completed',
57
+ 'PAUSED': 'On Hold',
58
+ 'DROPPED': 'Dropped',
59
+ 'PLANNING': 'Plan to Watch'
60
+ },
61
+ 'score_max': 100,
62
+ 'score_step': 1,
63
+ }
64
+ mediatypes['manga'] = {
65
+ 'has_progress': True,
66
+ 'can_add': True,
67
+ 'can_delete': True,
68
+ 'can_score': True,
69
+ 'can_status': True,
70
+ 'can_update': True,
71
+ 'can_play': False,
72
+ 'can_date': True,
73
+ 'status_start': 'CURRENT',
74
+ 'status_finish': 'COMPLETED',
75
+ 'statuses': ['CURRENT', 'COMPLETED', 'PAUSED', 'DROPPED', 'PLANNING'],
76
+ 'statuses_dict': {
77
+ 'CURRENT': 'Watching',
78
+ 'COMPLETED': 'Completed',
79
+ 'PAUSED': 'On Hold',
80
+ 'DROPPED': 'Dropped',
81
+ 'PLANNING': 'Plan to Read'
82
+ },
83
+ 'score_max': 100,
84
+ 'score_step': 1,
85
+ }
86
+ default_mediatype = 'anime'
87
+
88
+ release_formats = ['TV', 'TV_SHORT', 'MOVIE', 'SPECIAL', 'OVA', 'ONA', 'MUSIC', 'MANGA', 'NOVEL', 'ONE_SHOT']
89
+
90
+ # Supported signals for the data handler
91
+ signals = { 'show_info_changed': None, }
92
+
93
+ auth_url = "https://anilist.co/api/v2/"
94
+ query_url = "https://graphql.anilist.co"
95
+ client_id = "537"
96
+ _client_secret = "9Hl31gyz2q9xMhhJwLKRA8DAn0pXl9sOHFf6I1YO"
97
+ user_agent = 'Trackma/{}'.format(utils.VERSION)
98
+
99
+ def __init__(self, messenger, account, userconfig):
100
+ """Initializes the API"""
101
+ super(libanilist, self).__init__(messenger, account, userconfig)
102
+
103
+ self.pin = account['password'].strip()
104
+ self.userid = self._get_userconfig('userid')
105
+
106
+ if len(self.pin) == 40: # Old pins were 40 digits, new ones seem to be 654 digits
107
+ raise utils.APIFatal("This appears to be a V1 API PIN. You need a V2 API PIN to continue using Anilist.")
108
+ #elif len(self.pin) != 654:
109
+ # raise utils.APIFatal("Invalid PIN.")
110
+
111
+ if self.mediatype == 'manga':
112
+ self.total_str = "chapters"
113
+ self.watched_str = "chapters_read"
114
+ else:
115
+ self.total_str = "episodes"
116
+ self.watched_str = "episodes_watched"
117
+ self.status_translate = {
118
+ 'RELEASING': utils.STATUS_AIRING,
119
+ 'FINISHED': utils.STATUS_FINISHED,
120
+ 'NOT_YET_RELEASED': utils.STATUS_NOTYET,
121
+ 'CANCELLED': utils.STATUS_CANCELLED,
122
+ }
123
+
124
+ self.opener = urllib.request.build_opener()
125
+ self.opener.addheaders = [('User-agent', self.user_agent)]
126
+
127
+ def _raw_request(self, method, url, get=None, post=None, jsonpost=None, auth=False):
128
+ if get:
129
+ url = "{}?{}".format(url, urllib.parse.urlencode(get))
130
+ if post:
131
+ post = urllib.parse.urlencode(post).encode('utf-8')
132
+ if jsonpost:
133
+ post = json.dumps(jsonpost, ensure_ascii=False).encode('utf-8')
134
+
135
+ request = urllib.request.Request(url, post)
136
+ request.get_method = lambda: method
137
+
138
+ request.add_header('Content-Type', 'application/json')
139
+ request.add_header('Accept', 'application/json')
140
+
141
+ if auth:
142
+ request.add_header('Authorization', 'Bearer {}'.format(
143
+ self.pin,
144
+ ))
145
+
146
+ try:
147
+ response = self.opener.open(request, timeout = 10)
148
+ return json.load(response)
149
+ except urllib.request.HTTPError as e:
150
+ if e.code == 400:
151
+ raise utils.APIError("Invalid request: %s" % e.read())
152
+ else:
153
+ raise utils.APIError("Connection error: %s" % e.read())
154
+ except socket.timeout:
155
+ raise utils.APIError("Connection timed out.")
156
+
157
+ def _request(self, query, variables=None):
158
+ if variables:
159
+ data = {'query': query, 'variables': variables}
160
+ else:
161
+ data = {'query': query}
162
+
163
+ return self._raw_request('POST', self.query_url, jsonpost=data, auth=True)
164
+
165
+ def check_credentials(self):
166
+ if not self.userid:
167
+ self._refresh_user_info()
168
+
169
+ return True
170
+
171
+ def _refresh_user_info(self):
172
+ self.msg.info(self.name, 'Refreshing user details...')
173
+ query = '{Viewer{ id name avatar{large} options{titleLanguage displayAdultContent} mediaListOptions{scoreFormat} }}'
174
+ data = self._request(query)['data']['Viewer']
175
+
176
+ self._set_userconfig('userid', data['id'])
177
+ self._set_userconfig('username', data['name'])
178
+ self._emit_signal('userconfig_changed')
179
+
180
+ self.userid = data['id']
181
+
182
+ def fetch_list(self):
183
+ self.check_credentials()
184
+ self.msg.info(self.name, 'Downloading list...')
185
+
186
+ query = '''query ($id: Int!, $listType: MediaType) {
187
+ MediaListCollection (userId: $id, type: $listType) {
188
+ lists {
189
+ name
190
+ isCustomList
191
+ isSplitCompletedList
192
+ status
193
+ entries {
194
+ ... mediaListEntry
195
+ }
196
+ }
197
+ user {
198
+ id
199
+ name
200
+ avatar {
201
+ large
202
+ }
203
+ mediaListOptions {
204
+ scoreFormat
205
+ rowOrder
206
+ }
207
+ }
208
+ }
209
+ }
210
+
211
+ fragment mediaListEntry on MediaList {
212
+ id
213
+ score
214
+ progress
215
+ startedAt { year month day }
216
+ completedAt { year month day }
217
+ media {
218
+ id
219
+ title { userPreferred romaji english native }
220
+ coverImage { large medium }
221
+ format
222
+ status
223
+ chapters episodes
224
+ nextAiringEpisode { airingAt episode }
225
+ startDate { year month day }
226
+ endDate { year month day }
227
+ siteUrl
228
+ }
229
+ }'''
230
+ variables = {'id': self.userid, 'listType': self.mediatype.upper()}
231
+ data = self._request(query, variables)['data']['MediaListCollection']
232
+
233
+ showlist = {}
234
+
235
+ if not data['lists']:
236
+ # No lists returned so no need to continue
237
+ return showlist
238
+
239
+ for remotelist in data['lists']:
240
+ my_status = remotelist['status']
241
+ if my_status not in self.media_info()['statuses']:
242
+ continue
243
+ if remotelist['isCustomList']:
244
+ continue # Maybe do something with this later
245
+ if remotelist['isSplitCompletedList']:
246
+ continue # Maybe do something with this later
247
+ for item in remotelist['entries']:
248
+ show = utils.show()
249
+ media = item['media']
250
+ showid = media['id']
251
+ aliases = [a for a in (media['title']['romaji'], media['title']['english'], media['title']['native']) if a]
252
+ showdata = {
253
+ 'my_id': item['id'],
254
+ 'id': showid,
255
+ 'title': media['title']['userPreferred'],
256
+ 'aliases': aliases,
257
+ 'type': media['format'], # Need to reformat output
258
+ 'status': self.status_translate[media['status']],
259
+ 'my_progress': self._c(item['progress']),
260
+ 'my_status': my_status,
261
+ 'my_score': self._c(item['score']),
262
+ 'total': self._c(media[self.total_str]),
263
+ 'image': media['coverImage']['large'],
264
+ 'image_thumb': media['coverImage']['medium'],
265
+ 'url': media['siteUrl'],
266
+ 'start_date': self._dict2date(media['startDate']),
267
+ 'end_date': self._dict2date(media['endDate']),
268
+ 'my_start_date': self._dict2date(item['startedAt']),
269
+ 'my_finish_date': self._dict2date(item['completedAt']),
270
+ }
271
+ if media['nextAiringEpisode']:
272
+ showdata['next_ep_number'] = media['nextAiringEpisode']['episode']
273
+ showdata['next_ep_time'] = self._int2date(media['nextAiringEpisode']['airingAt'])
274
+ show.update({k:v for k,v in showdata.items() if v})
275
+ showlist[showid] = show
276
+ return showlist
277
+
278
+ args_SaveMediaListEntry = {
279
+ 'id': 'Int', # The list entry id, required for updating
280
+ 'mediaId': 'Int', # The id of the media the entry is of
281
+ 'status': 'MediaListStatus', # The watching/reading status
282
+ 'score': 'Float', # The score of the media in the user's chosen scoring method
283
+ 'progress': 'Int', # The amount of episodes/chapters consumed by the user
284
+ 'startedAt': 'FuzzyDateInput', # When the entry was started by the user
285
+ 'completedAt': 'FuzzyDateInput', # When the entry was completed by the user
286
+ }
287
+ def _update_entry(self, item):
288
+ """
289
+ New entries will lack a list entry id, while updates will include one.
290
+ In the case of a new entry, we want to record the new id.
291
+ """
292
+ values = { 'mediaId': item['id'] }
293
+ if 'my_id' in item and item['my_id']:
294
+ values['id'] = item['my_id']
295
+ if 'my_progress' in item:
296
+ values['progress'] = item['my_progress']
297
+ if 'my_status' in item:
298
+ values['status'] = item['my_status']
299
+ if 'my_score' in item:
300
+ values['score'] = item['my_score']
301
+ if 'my_start_date' in item:
302
+ values['startedAt'] = self._date2dict(item['my_start_date'])
303
+ if 'my_finish_date' in item:
304
+ values['completedAt'] = self._date2dict(item['my_finish_date'])
305
+
306
+ vars_defn = ', '.join(['${}: {}'.format(k, self.args_SaveMediaListEntry[k]) for k in values.keys()])
307
+ subs_defn = ', '.join(['{0}: ${0}'.format(k) for k in values.keys()])
308
+ query = 'mutation ({0}) {{ SaveMediaListEntry({1}) {{id}} }}'.format(vars_defn, subs_defn)
309
+
310
+ data = self._request(query, values)['data']
311
+ return data['SaveMediaListEntry']['id']
312
+
313
+ def add_show(self, item):
314
+ self.check_credentials()
315
+ self.msg.info(self.name, "Adding item %s..." % item['title'])
316
+ return self._update_entry(item)
317
+
318
+ def update_show(self, item):
319
+ self.check_credentials()
320
+ self.msg.info(self.name, "Updating item %s..." % item['title'])
321
+ self._update_entry(item)
322
+
323
+ def delete_show(self, item):
324
+ self.check_credentials()
325
+ self.msg.info(self.name, "Deleting item %s..." % item['title'])
326
+ query = 'mutation ($id: Int) {DeleteMediaListEntry(id: $id){deleted} }'
327
+ variables = {'id': item['my_id']}
328
+ self._request(query, variables)
329
+
330
+ def search(self, criteria):
331
+ self.check_credentials()
332
+ self.msg.info(self.name, "Searching for {}...".format(criteria))
333
+
334
+ query = '''query ($query: String, $type: MediaType) {
335
+ Page {
336
+ media(search: $query, type: $type) {
337
+ id
338
+ title { userPreferred romaji english native }
339
+ coverImage { medium large }
340
+ format
341
+ averageScore
342
+ popularity
343
+ chapters episodes
344
+ status
345
+ isAdult
346
+ startDate { year month day }
347
+ endDate { year month day }
348
+ siteUrl
349
+ mediaListEntry { status progress score }
350
+ }
351
+ }
352
+ }'''
353
+ variables = {'query': urllib.parse.quote_plus(criteria), 'type': self.mediatype.upper()}
354
+ data = self._request(query, variables)['data']['Page']['media']
355
+
356
+ showlist = []
357
+ for media in data:
358
+ show = utils.show()
359
+ showid = media['id']
360
+ aliases = [a for a in (media['title']['romaji'], media['title']['english'], media['title']['native']) if a]
361
+ showdata = {
362
+ 'id': showid,
363
+ 'title': media['title']['userPreferred'],
364
+ 'aliases': aliases,
365
+ 'type': media['format'], # Need to reformat output
366
+ 'status': self.status_translate[media['status']],
367
+ 'total': self._c(media[self.total_str]),
368
+ 'image': media['coverImage']['large'],
369
+ 'image_thumb': media['coverImage']['medium'],
370
+ 'url': media['siteUrl'],
371
+ }
372
+ if media['mediaListEntry']:
373
+ showdata['my_progress'] = self._c(media['mediaListEntry']['progress'])
374
+ showdata['my_status'] = media['mediaListEntry']['status']
375
+ showdata['my_score'] = self._c(media['mediaListEntry']['score'])
376
+ show.update({k:v for k,v in showdata.items() if v})
377
+ showlist.append(show)
378
+
379
+ return showlist
380
+
381
+ def request_info(self, itemlist):
382
+ self.check_credentials()
383
+ infolist = []
384
+
385
+ query = '''query ($id: Int!, $type: MediaType) {
386
+ Media(id: $id, type: $type) {
387
+ id
388
+ title { userPreferred romaji english native }
389
+ coverImage { medium large }
390
+ format
391
+ averageScore
392
+ chapters episodes
393
+ status
394
+ startDate { year month day }
395
+ endDate { year month day }
396
+ siteUrl
397
+ description
398
+ genres
399
+ synonyms
400
+ averageScore
401
+ }
402
+ }'''
403
+
404
+ for show in itemlist:
405
+ variables = {'id': show['id'], 'listType': self.mediatype.upper()}
406
+ data = self._request(query, variables)['data']['Media']
407
+ infolist.append(self._parse_info(data))
408
+
409
+ self._emit_signal('show_info_changed', infolist)
410
+ return infolist
411
+
412
+ def media_info(self):
413
+ """Return information about the currently selected mediatype."""
414
+ return self.mediatypes[self.mediatype]
415
+
416
+ def _parse_info(self, item):
417
+ info = utils.show()
418
+ showid = item['id']
419
+ info.update({
420
+ 'id': showid,
421
+ 'title': item['title']['userPreferred'],
422
+ 'status': self.status_translate[item['status']],
423
+ 'image': item['coverImage']['large'],
424
+ 'url': item['siteUrl'],
425
+ 'start_date': self._dict2date(item.get('startDate')),
426
+ 'end_date': self._dict2date(item.get('endDate')),
427
+ 'extra': [
428
+ ('English', item['title'].get('english')),
429
+ ('Romaji', item['title'].get('romaji')),
430
+ ('Japanese', item['title'].get('native')),
431
+ ('Synonyms', item['title'].get('synonyms')),
432
+ #('Classification', item.get('classification')),
433
+ ('Genres', item.get('genres')),
434
+ ('Synopsis', item.get('description')),
435
+ ('Type', item.get('format')),
436
+ ('Average score', item.get('averageScore')),
437
+ ('Status', self.status_translate[item['status']]),
438
+ #('Start Date', item.get('start_date')),
439
+ #('End Date', item.get('end_date')),
440
+ ]
441
+ })
442
+ return info
443
+
444
+ def _dict2date(self, item):
445
+ if not item:
446
+ return None
447
+ try:
448
+ return datetime.datetime(item['year'], item['month'], item['day'])
449
+ except (TypeError, ValueError):
450
+ return None
451
+
452
+ def _date2dict(self, date):
453
+ if not date:
454
+ return {}
455
+ try:
456
+ return {'year': date.year, 'month': date.month, 'day': date.day}
457
+ except (TypeError, ValueError):
458
+ return {}
459
+
460
+
461
+ def _int2date(self, item):
462
+ if not item:
463
+ return None
464
+ try:
465
+ return datetime.datetime.utcfromtimestamp(item)
466
+ except ValueError:
467
+ return None
468
+
469
+ def _c(self, s):
470
+ if s is None:
471
+ return 0
472
+ else:
473
+ return s
474
+