trackma 0.6.1__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 +207 -63
  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 +193 -24
  53. trackma/ui/curses.py +101 -36
  54. trackma/ui/gtkui.py +253 -78
  55. trackma/ui/qt4ui.py +25 -0
  56. trackma/ui/qtui.py +350 -179
  57. trackma/utils.py +23 -10
  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
@@ -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
@@ -46,8 +46,17 @@ class AnimeInfoExtractor():
46
46
  def getName(self):
47
47
  return self.name
48
48
 
49
- def getEpisodeNumbers(self):
50
- return self.episodeStart, self.episodeEnd
49
+ def getEpisodeNumbers(self, force_numbers=False):
50
+ ep_start = self.episodeStart
51
+ ep_end = self.episodeEnd
52
+ if force_numbers:
53
+ if ep_start is None:
54
+ ep_start = 1
55
+ if ep_end is None:
56
+ ep_end = ep_start
57
+ ep_start = int(ep_start)
58
+ ep_end = int(ep_end)
59
+ return ep_start, ep_end
51
60
 
52
61
  def getEpisode(self):
53
62
  ep = self.episodeStart if self.episodeEnd is None else self.episodeEnd
@@ -209,8 +218,8 @@ class AnimeInfoExtractor():
209
218
  return filename
210
219
 
211
220
  def __extractEpisodeNumbers(self, filename):
212
- # First check for concurrent episodes (with a +)
213
- m = re.search('[^0-9a-zA-Z](?:E\.?|Ep(?:i|isode)?s?(?: |\.)?)?(\d{1,4})\+(\d{1,4})(?:[^0-9a-zA-Z]|$)', filename, flags=re.IGNORECASE)
221
+ # First check for concurrent episodes (with a + or &)
222
+ m = re.search('[^0-9a-zA-Z](?:E\.?|Ep(?:i|isode)?s?(?: |\.)?)?(\d{1,4})[\+\&](\d{1,4})(?:[^0-9a-zA-Z]|$)', filename, flags=re.IGNORECASE)
214
223
  if m:
215
224
  start = int(m.group(1))
216
225
  end = int(m.group(2))
Binary file
trackma/lib/libanilist.py CHANGED
@@ -11,7 +11,7 @@
11
11
  # GNU General Public License for more details.
12
12
  #
13
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/>.
14
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
15
15
  #
16
16
 
17
17
  import json
@@ -28,7 +28,7 @@ class libanilist(lib):
28
28
  """
29
29
  API class to communicate with Anilist
30
30
 
31
- Website: http://anilist.co
31
+ Website: https://anilist.co
32
32
 
33
33
  messenger: Messenger object to send useful messages to
34
34
  """
@@ -86,7 +86,7 @@ class libanilist(lib):
86
86
  # Supported signals for the data handler
87
87
  signals = { 'show_info_changed': None, }
88
88
 
89
- url = "http://anilist.co/api/"
89
+ url = "https://anilist.co/api/"
90
90
  client_id = "z411-gdjc3"
91
91
  _client_secret = "MyzwuYoMqPPglXwCTcexG1i"
92
92
 
@@ -106,7 +106,7 @@ class libanilist(lib):
106
106
  self.airing_str = "publishing_status"
107
107
  self.status_translate = {
108
108
  'publishing': utils.STATUS_AIRING,
109
- 'finished': utils.STATUS_FINISHED,
109
+ 'finished publishing': utils.STATUS_FINISHED,
110
110
  'not yet published': utils.STATUS_NOTYET,
111
111
  'cancelled': utils.STATUS_CANCELLED,
112
112
  }
@@ -252,7 +252,7 @@ class libanilist(lib):
252
252
  'total': self._c(item[self.mediatype][self.total_str]),
253
253
  'image': item[self.mediatype]['image_url_lge'],
254
254
  'image_thumb': item[self.mediatype]['image_url_med'],
255
- 'url': str("http://anilist.co/%s/%d" % (self.mediatype, showid)),
255
+ 'url': str("https://anilist.co/%s/%d" % (self.mediatype, showid)),
256
256
  }
257
257
  show.update({k:v for k,v in showdata.items() if v})
258
258
 
@@ -304,15 +304,19 @@ class libanilist(lib):
304
304
 
305
305
  self.msg.info(self.name, "Searching for {}...".format(criteria))
306
306
  param = {'access_token': self._get_userconfig('access_token')}
307
- try:
308
- data = self._request("GET", "{0}/search/{1}".format(self.mediatype, criteria), get=param)
309
- except ValueError:
310
- # An empty document, without any JSON, is returned
311
- # when there are no results.
312
- return []
307
+ data = self._request("GET", "{0}/search/{1}".format(self.mediatype, urllib.parse.quote_plus(criteria)), get=param)
308
+
309
+ if type(data) == dict:
310
+ # In case of error API returns a small JSON payload
311
+ # which translates into a dict with the key 'error'
312
+ # instead of a list.
313
+ if data['error']['messages'][0] == 'No Results.':
314
+ data = []
315
+ else:
316
+ raise utils.APIError("Error while searching for \
317
+ {0}: {1}".format(criteria, str(data)))
313
318
 
314
319
  showlist = []
315
-
316
320
  for item in data:
317
321
  show = utils.show()
318
322
  showid = item['id']
@@ -326,7 +330,7 @@ class libanilist(lib):
326
330
  'total': item[self.total_str],
327
331
  'image': item['image_url_lge'],
328
332
  'image_thumb': item['image_url_med'],
329
- 'url': str("http://anilist.co/%s/%d" % (self.mediatype, showid)),
333
+ 'url': str("https://anilist.co/%s/%d" % (self.mediatype, showid)),
330
334
  }
331
335
  show.update({k:v for k,v in showdata.items() if v})
332
336
 
@@ -352,11 +356,11 @@ class libanilist(lib):
352
356
 
353
357
  def _update_entry(self, item, method):
354
358
  values = { 'id': item['id'] }
355
- if 'my_progress' in item.keys():
359
+ if 'my_progress' in item:
356
360
  values[self.watched_str] = item['my_progress']
357
- if 'my_status' in item.keys():
361
+ if 'my_status' in item:
358
362
  values['list_status'] = item['my_status']
359
- if 'my_score' in item.keys():
363
+ if 'my_score' in item:
360
364
  values['score'] = item['my_score']
361
365
 
362
366
  data = self._request(method, "{}list".format(self.mediatype), post=values, auth=True)
@@ -370,7 +374,7 @@ class libanilist(lib):
370
374
  'title': item['title_romaji'],
371
375
  'status': self.status_translate[item[self.airing_str]],
372
376
  'image': item['image_url_lge'],
373
- 'url': str("http://anilist.co/%s/%d" % (self.mediatype, showid)),
377
+ 'url': str("https://anilist.co/%s/%d" % (self.mediatype, showid)),
374
378
  'start_date': self._str2date(item.get('start_date')),
375
379
  'end_date': self._str2date(item.get('end_date')),
376
380
  'extra': [
@@ -0,0 +1,506 @@
1
+ # -*- coding: utf-8 -*-
2
+ # This file is part of Trackma.
3
+ #
4
+ # This program is free software: you can redistribute it and/or modify
5
+ # it under the terms of the GNU General Public License as published by
6
+ # the Free Software Foundation, either version 3 of the License, or
7
+ # (at your option) any later version.
8
+ #
9
+ # This program is distributed in the hope that it will be useful,
10
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ # GNU General Public License for more details.
13
+ #
14
+ # You should have received a copy of the GNU General Public License
15
+ # along with this program. If not, see <https://www.gnu.org/licenses/>.
16
+ #
17
+
18
+ import datetime
19
+ import time
20
+ import urllib.parse
21
+ import urllib.request
22
+ import json
23
+ import gzip
24
+ import socket
25
+
26
+ #import http.client
27
+ #http.client.HTTPConnection.debuglevel = 1
28
+
29
+ from trackma.lib.lib import lib
30
+ from trackma import utils
31
+
32
+
33
+ class libkitsu(lib):
34
+ """
35
+ API class to communicate with Kitsu
36
+ Should inherit a base library interface.
37
+
38
+ Website: https://kitsu.io/
39
+ API documentation:
40
+ Designed by:
41
+
42
+ """
43
+ name = 'libkitsu'
44
+ user_agent = 'Trackma/{}'.format(utils.VERSION)
45
+
46
+ auth = ''
47
+ logged_in = False
48
+
49
+ api_info = {
50
+ 'name': 'Kitsu',
51
+ 'shortname': 'kitsu',
52
+ 'version': 'v0.3',
53
+ 'merge': True
54
+ }
55
+
56
+ default_mediatype = 'anime'
57
+ default_statuses = ['current', 'completed', 'on_hold', 'dropped', 'planned']
58
+ default_statuses_dict = {
59
+ 'current': 'Watching',
60
+ 'completed': 'Completed',
61
+ 'on_hold': 'On Hold',
62
+ 'dropped': 'Dropped',
63
+ 'planned': 'Plan to Watch'
64
+ }
65
+
66
+ mediatypes = dict()
67
+ mediatypes['anime'] = {
68
+ 'has_progress': True,
69
+ 'can_add': True,
70
+ 'can_delete': True,
71
+ 'can_score': True,
72
+ 'can_status': True,
73
+ 'can_update': True,
74
+ 'can_play': True,
75
+ 'status_start': 'current',
76
+ 'status_finish': 'completed',
77
+ 'statuses': default_statuses,
78
+ 'statuses_dict': default_statuses_dict,
79
+ 'score_max': 5,
80
+ 'score_step': 0.5,
81
+ }
82
+ mediatypes['manga'] = {
83
+ 'has_progress': True,
84
+ 'can_add': True,
85
+ 'can_delete': True,
86
+ 'can_score': True,
87
+ 'can_status': True,
88
+ 'can_update': True,
89
+ 'can_play': False,
90
+ 'status_start': 'current',
91
+ 'status_finish': 'completed',
92
+ 'statuses': default_statuses,
93
+ 'statuses_dict': default_statuses_dict,
94
+ 'score_max': 5,
95
+ 'score_step': 0.5,
96
+ }
97
+ mediatypes['drama'] = {
98
+ 'has_progress': True,
99
+ 'can_add': True,
100
+ 'can_delete': True,
101
+ 'can_score': True,
102
+ 'can_status': True,
103
+ 'can_update': True,
104
+ 'can_play': True,
105
+ 'status_start': 'current',
106
+ 'status_finish': 'completed',
107
+ 'statuses': default_statuses,
108
+ 'statuses_dict': default_statuses_dict,
109
+ 'score_max': 5,
110
+ 'score_step': 0.5,
111
+ }
112
+
113
+ url = 'https://kitsu.io/api'
114
+ prefix = 'https://kitsu.io/api/edge'
115
+
116
+ # TODO : These values are previsional.
117
+ _client_id = 'dd031b32d2f56c990b1425efe6c42ad847e7fe3ab46bf1299f05ecd856bdb7dd'
118
+ _client_secret = '54d7307928f63414defd96399fc31ba847961ceaecef3a5fd93144e960c0e151'
119
+
120
+ status_translate = {'Currently Airing': utils.STATUS_AIRING,
121
+ 'Finished Airing': utils.STATUS_FINISHED,
122
+ 'Not Yet Aired': utils.STATUS_NOTYET}
123
+
124
+ def __init__(self, messenger, account, userconfig):
125
+ """Initializes the useragent through credentials."""
126
+ super(libkitsu, self).__init__(messenger, account, userconfig)
127
+
128
+ self.username = account['username']
129
+ self.password = account['password']
130
+
131
+ # Build opener with the mashape API key
132
+ self.opener = urllib.request.build_opener()
133
+ self.opener.addheaders = [
134
+ ('User-Agent', self.user_agent),
135
+ ('Accept', 'application/vnd.api+json'),
136
+ ('Accept-Encoding', 'gzip'),
137
+ ('Accept-Charset', 'utf-8'),
138
+ ]
139
+
140
+ def _request(self, method, url, get=None, post=None, body=None, auth=False):
141
+ content_type = None
142
+
143
+ if get:
144
+ url += "?%s" % urllib.parse.urlencode(get)
145
+ if post:
146
+ post = urllib.parse.urlencode(post).encode('utf-8')
147
+ content_type = 'application/x-www-form-urlencoded'
148
+ if body:
149
+ post = body.encode('utf-8')
150
+ content_type = 'application/vnd.api+json'
151
+
152
+ request = urllib.request.Request(url, post)
153
+ request.get_method = lambda: method
154
+
155
+ if content_type:
156
+ request.add_header('Content-Type', content_type)
157
+
158
+ if auth:
159
+ request.add_header('Authorization', '{0} {1}'.format(
160
+ self._get_userconfig('token_type').capitalize(),
161
+ self._get_userconfig('access_token'),
162
+ ))
163
+
164
+ try:
165
+ response = self.opener.open(request)
166
+
167
+ # The response most probably will be gzipped so we
168
+ # have to take care of that first
169
+ if response.info().get('content-encoding') == 'gzip':
170
+ return gzip.GzipFile(fileobj=response).read().decode('utf-8')
171
+ else:
172
+ return response.read().decode('utf-8')
173
+ except urllib.request.HTTPError as e:
174
+ if e.code == 401:
175
+ raise utils.APIError("Incorrect credentials.")
176
+ else:
177
+ api_error = self._parse_errors(e)
178
+ if api_error:
179
+ raise utils.APIError("API error: %s" % api_error)
180
+ else:
181
+ raise utils.APIError("Connection error: %s" % e)
182
+ except urllib.request.URLError as e:
183
+ raise utils.APIError("URL error: %s" % e)
184
+ except socket.timeout:
185
+ raise utils.APIError("Operation timed out.")
186
+
187
+ def _parse_errors(self, e):
188
+ try:
189
+ data = json.loads(e.read().decode('utf-8'))
190
+ errors = ""
191
+ for error in data['errors']:
192
+ errors += "{}: {}".format(error['code'], error['detail'])
193
+
194
+ return errors
195
+ except:
196
+ return None
197
+
198
+ def _request_access_token(self, refresh=False):
199
+ params = {
200
+ 'client_id': self._client_id,
201
+ 'client_secret': self._client_secret,
202
+ }
203
+
204
+ if refresh:
205
+ self.msg.info(self.name, 'Refreshing access token...')
206
+
207
+ params['grant_type'] = 'refresh_token'
208
+ params['refresh_token'] = self._get_userconfig('refresh_token')
209
+ else:
210
+ self.msg.info(self.name, 'Requesting access token...')
211
+
212
+ params['grant_type'] = 'password'
213
+ params['username'] = self.username
214
+ params['password'] = self.password
215
+
216
+ response = self._request('POST', self.url + '/oauth/token', post=params)
217
+ data = json.loads(response)
218
+
219
+ timestamp = int(time.time())
220
+
221
+ self._set_userconfig('access_token', data['access_token'])
222
+ self._set_userconfig('token_type', data['token_type'])
223
+ self._set_userconfig('expires', timestamp + data['expires_in'])
224
+ self._set_userconfig('refresh_token', data['refresh_token'])
225
+
226
+ self.logged_in = True
227
+ self._refresh_user_info()
228
+ self._emit_signal('userconfig_changed')
229
+
230
+ def _refresh_user_info(self):
231
+ self.msg.info(self.name, 'Refreshing user details...')
232
+ params = {
233
+ "filter[self]": 'true',
234
+ }
235
+ data = self._request('GET', self.prefix + "/users", get=params, auth=True)
236
+ json_data = json.loads(data)
237
+ user = json_data['data'][0]
238
+
239
+ # Parse user information
240
+ self._set_userconfig('userid', user['id'])
241
+ self._set_userconfig('username', user['attributes']['name'])
242
+
243
+ def check_credentials(self):
244
+ """
245
+ Log into Kitsu. If there isn't an acess token, request it, or
246
+ refresh it if necessary.
247
+ """
248
+ timestamp = int(time.time())
249
+
250
+ if not self._get_userconfig('access_token'):
251
+ self._request_access_token(False)
252
+ elif (timestamp+60) > self._get_userconfig('expires'):
253
+ self._request_access_token(True)
254
+ else:
255
+ self.logged_in = True
256
+
257
+ return True
258
+
259
+ def fetch_list(self):
260
+ """Queries the full list from the remote server.
261
+ Returns the list if successful, False otherwise."""
262
+ self.check_credentials()
263
+ self.msg.info(self.name, 'Downloading list...')
264
+
265
+ try:
266
+ showlist = dict()
267
+ infolist = list()
268
+
269
+ # Get first page and continue from there
270
+ params = {
271
+ "filter[user_id]": self._get_userconfig('userid'),
272
+ "filter[kind]": self.mediatype,
273
+ #"include": self.mediatype, # TODO : This returns a 500 for some reason.
274
+ "include": "media",
275
+ # TODO : List for manga should be different
276
+ "fields[anime]": "id,slug,canonicalTitle,titles,episodeCount,synopsis,subtype,posterImage,startDate,endDate",
277
+ "page[limit]": "250",
278
+ }
279
+
280
+ url = "{}/library-entries?{}".format(self.prefix, urllib.parse.urlencode(params))
281
+ i = 1
282
+
283
+ while url:
284
+ self.msg.info(self.name, 'Getting page {}...'.format(i))
285
+
286
+ data = self._request('GET', url)
287
+ data_json = json.loads(data)
288
+
289
+ #print(json.dumps(data_json, sort_keys=True, indent=2))
290
+ #return []
291
+
292
+ entries = data_json['data']
293
+ links = data_json['links']
294
+
295
+ for entry in entries:
296
+ # TODO : Including the mediatype returns a 500 for some reason.
297
+ #showid = int(entry['relationships'][self.mediatype]['data']['id'])
298
+ showid = int(entry['relationships']['media']['data']['id'])
299
+ status = entry['attributes']['status']
300
+ rating = entry['attributes']['rating']
301
+
302
+ showlist[showid] = utils.show()
303
+ showlist[showid].update({
304
+ 'id': showid,
305
+ 'my_id': entry['id'],
306
+ 'my_progress': entry['attributes']['progress'],
307
+ 'my_score': float(rating) if rating is not None else 0.0,
308
+ 'my_status': entry['attributes']['status'],
309
+ })
310
+
311
+ if 'included' in data_json:
312
+ medias = data_json['included']
313
+ for media in medias:
314
+ info = self._parse_info(media)
315
+ infolist.append(info)
316
+
317
+ self._emit_signal('show_info_changed', infolist)
318
+
319
+ url = links.get('next')
320
+ i += 1
321
+
322
+ return showlist
323
+ except urllib.request.HTTPError as e:
324
+ raise utils.APIError("Error getting list.")
325
+
326
+ def merge(self, show, info):
327
+ show['title'] = info['title']
328
+ show['aliases'] = info['aliases']
329
+ show['url'] = info['url']
330
+ show['total'] = info['total']
331
+ show['image'] = info['image']
332
+
333
+ show['image_thumb'] = info['image_thumb']
334
+
335
+ show['start_date'] = info['start_date']
336
+ show['end_date'] = info['end_date']
337
+ show['status'] = info['status']
338
+
339
+ def request_info(self, item_list):
340
+ print("These are missing: " + repr(item_list))
341
+ # TODO implement
342
+ raise NotImplementedError
343
+
344
+ def add_show(self, item):
345
+ """Adds a new show in the server"""
346
+ self.check_credentials()
347
+ self.msg.info(self.name, "Adding show %s..." % item['title'])
348
+
349
+ data = self._build_data(item)
350
+
351
+ try:
352
+ data = self._request('POST', self.prefix + "/library-entries", body=data, auth=True)
353
+
354
+ data_json = json.loads(data)
355
+ return int(data_json['data']['id'])
356
+ except urllib.request.HTTPError as e:
357
+ raise utils.APIError('Error adding: ' + str(e.code))
358
+
359
+ def update_show(self, item):
360
+ """Sends a show update to the server"""
361
+ self.check_credentials()
362
+ self.msg.info(self.name, "Updating show %s..." % item['title'])
363
+
364
+ data = self._build_data(item)
365
+
366
+ try:
367
+ self._request('PATCH', self.prefix + "/library-entries/%s" % item['my_id'], body=data, auth=True)
368
+ except urllib.request.HTTPError as e:
369
+ raise utils.APIError('Error updating: ' + str(e.code))
370
+
371
+ def delete_show(self, item):
372
+ """Sends a show delete to the server"""
373
+ self.check_credentials()
374
+ self.msg.info(self.name, "Deleting show %s..." % item['title'])
375
+
376
+ try:
377
+ self._request('DELETE', self.prefix + "/library-entries/%s" % item['my_id'], auth=True)
378
+ except urllib.request.HTTPError as e:
379
+ raise utils.APIError('Error deleting: ' + str(e.code))
380
+
381
+ def search(self, query):
382
+ self.msg.info(self.name, "Searching for %s..." % query)
383
+
384
+ values = {
385
+ "filter[text]": query,
386
+ "page[limit]": 20,
387
+ }
388
+
389
+ try:
390
+ data = self._request('GET', self.prefix + "/" + self.mediatype, get=values)
391
+ shows = json.loads(data)
392
+
393
+ infolist = []
394
+ for media in shows['data']:
395
+ info = self._parse_info(media)
396
+ infolist.append(info)
397
+
398
+ self._emit_signal('show_info_changed', infolist)
399
+
400
+ if not infolist:
401
+ raise utils.APIError('No results.')
402
+
403
+ return infolist
404
+ except urllib.request.HTTPError as e:
405
+ raise utils.APIError('Error searching: ' + str(e.code))
406
+
407
+ def _build_data(self, item):
408
+ values = {'data': {
409
+ 'type': 'libraryEntries',
410
+ 'attributes': {},
411
+ 'relationships': {
412
+ 'media': {
413
+ 'data': {
414
+ 'type': self.mediatype,
415
+ 'id': item['id'],
416
+ }
417
+ },
418
+ 'user': {
419
+ 'data': {
420
+ 'type': 'users',
421
+ 'id': self._get_userconfig('userid'),
422
+ }
423
+ },
424
+ }
425
+ }
426
+ }
427
+
428
+ # Update necessary keys
429
+ if item['my_id']:
430
+ values['data']['id'] = str(item['my_id'])
431
+ if 'my_progress' in item:
432
+ values['data']['attributes']['progress'] = item['my_progress']
433
+ if 'my_status' in item:
434
+ values['data']['attributes']['status'] = item['my_status']
435
+ if 'my_score' in item:
436
+ values['data']['attributes']['rating'] = item['my_score'] or None
437
+
438
+ return json.dumps(values)
439
+
440
+ def _str2date(self, string):
441
+ if string is None:
442
+ return None
443
+
444
+ try:
445
+ return datetime.datetime.strptime(string, "%Y-%m-%d")
446
+ except:
447
+ self.msg.debug(self.name, 'Invalid date {}'.format(string))
448
+ return None # Ignore date if it's invalid
449
+
450
+ def _guess_status(self, start_date, end_date):
451
+ # Try to guess show status by checking start and end dates
452
+ now = datetime.datetime.now()
453
+
454
+ if end_date and end_date < now:
455
+ return utils.STATUS_FINISHED
456
+
457
+ if start_date:
458
+ if start_date > now:
459
+ return utils.STATUS_NOTYET
460
+ else:
461
+ return utils.STATUS_AIRING
462
+
463
+ # Safe to assume dates haven't even been announced yet
464
+ return utils.STATUS_NOTYET
465
+
466
+ def _parse_info(self, media):
467
+ info = utils.show()
468
+ attr = media['attributes']
469
+
470
+ #print(json.dumps(media, indent=2))
471
+ #raise NotImplementedError
472
+
473
+ if media['type'] == 'anime':
474
+ total = attr['episodeCount']
475
+ elif media['type'] == 'manga':
476
+ total = attr['chapterCount']
477
+ elif media['type'] == 'drama':
478
+ total = attr['episodeCount'] # TODO Unconfirmed
479
+
480
+ info.update({
481
+ 'id': int(media['id']),
482
+ # TODO : Some shows actually don't have a canonicalTitle; this should be fixed in the future.
483
+ # For now I'm just picking the romaji title in these cases.
484
+ 'title': attr['titles'].get('en_jp') or attr.get('canonicalTitle') or attr['titles'].get('en'),
485
+ 'total': total or 0,
486
+ 'image': attr['posterImage']['small'],
487
+ 'image_thumb': attr['posterImage']['tiny'],
488
+ 'start_date': self._str2date(attr['startDate']),
489
+ 'end_date': self._str2date(attr['endDate']),
490
+ 'url': "https://kitsu.io/{}/{}".format(self.mediatype, attr['slug']),
491
+ 'aliases': list(filter(None, attr['titles'].values())),
492
+ 'extra': [
493
+ ('Synopsis', attr['synopsis']),
494
+ ('Type', attr['subtype']),
495
+ ]
496
+ })
497
+
498
+ # WORKAROUND: Shows with 1 episode (TVs, SPs, OVAs) end the same day they start
499
+ if total == 1:
500
+ info['end_date'] = info['start_date']
501
+
502
+ # WORKAROUND: Since there's no way to get the formal status,
503
+ # use the helper function to guess it.
504
+ info['status'] = self._guess_status(info['start_date'], info['end_date'])
505
+
506
+ return info