trackma 0.6.2__py3.4.egg

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. EGG-INFO/PKG-INFO +19 -0
  2. EGG-INFO/SOURCES.txt +50 -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 +10 -0
  7. EGG-INFO/top_level.txt +1 -0
  8. trackma/__init__.py +0 -0
  9. trackma/__pycache__/__init__.cpython-34.pyc +0 -0
  10. trackma/__pycache__/accounts.cpython-34.pyc +0 -0
  11. trackma/__pycache__/data.cpython-34.pyc +0 -0
  12. trackma/__pycache__/engine.cpython-34.pyc +0 -0
  13. trackma/__pycache__/messenger.cpython-34.pyc +0 -0
  14. trackma/__pycache__/tracker.cpython-34.pyc +0 -0
  15. trackma/__pycache__/utils.cpython-34.pyc +0 -0
  16. trackma/accounts.py +145 -0
  17. trackma/data/anilist.jpg +0 -0
  18. trackma/data/hb.jpg +0 -0
  19. trackma/data/icon.png +0 -0
  20. trackma/data/mal.jpg +0 -0
  21. trackma/data/melative.jpg +0 -0
  22. trackma/data/shikimori.jpg +0 -0
  23. trackma/data/vndb.jpg +0 -0
  24. trackma/data.py +598 -0
  25. trackma/engine.py +911 -0
  26. trackma/extras/AnimeInfoExtractor.py +317 -0
  27. trackma/extras/__init__.py +1 -0
  28. trackma/extras/__pycache__/AnimeInfoExtractor.cpython-34.pyc +0 -0
  29. trackma/extras/__pycache__/__init__.cpython-34.pyc +0 -0
  30. trackma/extras/__pycache__/plex.cpython-34.pyc +0 -0
  31. trackma/extras/plex.py +101 -0
  32. trackma/lib/__init__.py +0 -0
  33. trackma/lib/__pycache__/__init__.cpython-34.pyc +0 -0
  34. trackma/lib/__pycache__/lib.cpython-34.pyc +0 -0
  35. trackma/lib/__pycache__/libanilist.cpython-34.pyc +0 -0
  36. trackma/lib/__pycache__/libhb.cpython-34.pyc +0 -0
  37. trackma/lib/__pycache__/libmal.cpython-34.pyc +0 -0
  38. trackma/lib/__pycache__/libmelative.cpython-34.pyc +0 -0
  39. trackma/lib/__pycache__/libshikimori.cpython-34.pyc +0 -0
  40. trackma/lib/__pycache__/libvndb.cpython-34.pyc +0 -0
  41. trackma/lib/lib.py +162 -0
  42. trackma/lib/libanilist.py +410 -0
  43. trackma/lib/libhb.py +239 -0
  44. trackma/lib/libmal.py +707 -0
  45. trackma/lib/libmelative.py +204 -0
  46. trackma/lib/libshikimori.py +340 -0
  47. trackma/lib/libvndb.py +384 -0
  48. trackma/messenger.py +42 -0
  49. trackma/tracker.py +430 -0
  50. trackma/ui/__init__.py +0 -0
  51. trackma/ui/__pycache__/__init__.cpython-34.pyc +0 -0
  52. trackma/ui/__pycache__/cli.cpython-34.pyc +0 -0
  53. trackma/ui/__pycache__/curses.cpython-34.pyc +0 -0
  54. trackma/ui/__pycache__/gtkui.cpython-34.pyc +0 -0
  55. trackma/ui/__pycache__/qt4ui.cpython-34.pyc +0 -0
  56. trackma/ui/__pycache__/qtui.cpython-34.pyc +0 -0
  57. trackma/ui/cli.py +907 -0
  58. trackma/ui/curses.py +1063 -0
  59. trackma/ui/gtkui.py +2672 -0
  60. trackma/ui/qt4ui.py +20 -0
  61. trackma/ui/qtui.py +3092 -0
  62. trackma/utils.py +396 -0
@@ -0,0 +1,410 @@
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': '1.1', '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
+ 'date_next_ep': True,
50
+ 'status_start': 'watching',
51
+ 'status_finish': 'completed',
52
+ 'statuses': ['watching', 'completed', 'on-hold', 'dropped', 'plan to watch'],
53
+ 'statuses_dict': {
54
+ 'watching': 'Watching',
55
+ 'completed': 'Completed',
56
+ 'on-hold': 'On Hold',
57
+ 'dropped': 'Dropped',
58
+ 'plan to watch': 'Plan to Watch'
59
+ },
60
+ 'score_max': 100,
61
+ 'score_step': 1,
62
+ }
63
+ mediatypes['manga'] = {
64
+ 'has_progress': True,
65
+ 'can_add': True,
66
+ 'can_delete': True,
67
+ 'can_score': True,
68
+ 'can_status': True,
69
+ 'can_update': True,
70
+ 'can_play': False,
71
+ 'status_start': 'reading',
72
+ 'status_finish': 'completed',
73
+ 'statuses': ['reading', 'completed', 'on-hold', 'dropped', 'plan to read'],
74
+ 'statuses_dict': {
75
+ 'reading': 'Reading',
76
+ 'completed': 'Completed',
77
+ 'on-hold': 'On Hold',
78
+ 'dropped': 'Dropped',
79
+ 'plan to read': 'Plan to Read'
80
+ },
81
+ 'score_max': 100,
82
+ 'score_step': 1,
83
+ }
84
+ default_mediatype = 'anime'
85
+
86
+ # Supported signals for the data handler
87
+ signals = { 'show_info_changed': None, }
88
+
89
+ url = "https://anilist.co/api/"
90
+ client_id = "z411-gdjc3"
91
+ _client_secret = "MyzwuYoMqPPglXwCTcexG1i"
92
+
93
+ def __init__(self, messenger, account, userconfig):
94
+ """Initializes the API"""
95
+ super(libanilist, self).__init__(messenger, account, userconfig)
96
+
97
+ self.pin = account['password'].strip()
98
+ self.userid = userconfig['userid']
99
+
100
+ if len(self.pin) != 40:
101
+ raise utils.APIFatal("Invalid PIN.")
102
+
103
+ if self.mediatype == 'manga':
104
+ self.total_str = "total_chapters"
105
+ self.watched_str = "chapters_read"
106
+ self.airing_str = "publishing_status"
107
+ self.status_translate = {
108
+ 'publishing': utils.STATUS_AIRING,
109
+ 'finished publishing': utils.STATUS_FINISHED,
110
+ 'not yet published': utils.STATUS_NOTYET,
111
+ 'cancelled': utils.STATUS_CANCELLED,
112
+ }
113
+ else:
114
+ self.total_str = "total_episodes"
115
+ self.watched_str = "episodes_watched"
116
+ self.airing_str = "airing_status"
117
+ self.status_translate = {
118
+ 'currently airing': utils.STATUS_AIRING,
119
+ 'finished airing': utils.STATUS_FINISHED,
120
+ 'not yet aired': utils.STATUS_NOTYET,
121
+ 'cancelled': utils.STATUS_CANCELLED,
122
+ }
123
+
124
+ #handler=urllib.request.HTTPHandler(debuglevel=1)
125
+ #self.opener = urllib.request.build_opener(handler)
126
+ self.opener = urllib.request.build_opener()
127
+ self.opener.addheaders = [('User-agent', 'Trackma/0.1')]
128
+
129
+ def _request(self, method, url, get=None, post=None, auth=False):
130
+ if get:
131
+ url = "{}?{}".format(url, urllib.parse.urlencode(get))
132
+ if post:
133
+ post = urllib.parse.urlencode(post).encode('utf-8')
134
+
135
+ request = urllib.request.Request(self.url + url, post)
136
+ request.get_method = lambda: method
137
+
138
+ if auth:
139
+ request.add_header('Content-Type', 'application/x-www-form-urlencoded')
140
+ request.add_header('Authorization', '{0} {1}'.format(
141
+ self._get_userconfig('token_type').capitalize(),
142
+ self._get_userconfig('access_token'),
143
+ ))
144
+
145
+ try:
146
+ response = self.opener.open(request, timeout = 10)
147
+ return json.loads(response.read().decode('utf-8'))
148
+ except urllib.request.HTTPError as e:
149
+ if e.code == 400:
150
+ raise utils.APIError("Invalid PIN. It is either probably expired or meant for another application.")
151
+ else:
152
+ raise utils.APIError("Connection error: %s" % e)
153
+ except socket.timeout:
154
+ raise utils.APIError("Connection timed out.")
155
+
156
+ def _request_access_token(self):
157
+ self.msg.info(self.name, 'Requesting access token...')
158
+ param = {
159
+ 'grant_type': 'authorization_pin',
160
+ 'client_id': self.client_id,
161
+ 'client_secret': self._client_secret,
162
+ 'code': self.pin,
163
+ }
164
+ data = self._request("POST", "auth/access_token", get=param)
165
+
166
+ self._set_userconfig('access_token', data['access_token'])
167
+ self._set_userconfig('token_type', data['token_type'])
168
+ self._set_userconfig('expires', data['expires'])
169
+ self._set_userconfig('refresh_token', data['refresh_token'])
170
+
171
+ self.logged_in = True
172
+ self._refresh_user_info()
173
+ self._emit_signal('userconfig_changed')
174
+
175
+ def _refresh_access_token(self):
176
+ self.msg.info(self.name, 'Refreshing access token...')
177
+ param = {
178
+ 'grant_type': 'refresh_token',
179
+ 'client_id': self.client_id,
180
+ 'client_secret': self._client_secret,
181
+ 'refresh_token': self._get_userconfig('refresh_token'),
182
+ }
183
+ data = self._request("POST", "auth/access_token", get=param)
184
+
185
+ self._set_userconfig('access_token', data['access_token'])
186
+ self._set_userconfig('token_type', data['token_type'])
187
+ self._set_userconfig('expires', data['expires'])
188
+
189
+ self.logged_in = True
190
+ self._refresh_user_info()
191
+ self._emit_signal('userconfig_changed')
192
+
193
+ def _refresh_user_info(self):
194
+ self.msg.info(self.name, 'Refreshing user details...')
195
+ param = {'access_token': self._get_userconfig('access_token')}
196
+
197
+ data = self._request("GET", "user", get=param)
198
+
199
+ self._set_userconfig('userid', data['id'])
200
+ self._set_userconfig('username', data['display_name'])
201
+
202
+ self.userid = data['id']
203
+
204
+ def check_credentials(self):
205
+ """
206
+ Log into Anilist. Since it uses OAuth, we either request an access token
207
+ or refresh the current one. If neither is necessary, just continue.
208
+ """
209
+ timestamp = int(time.time())
210
+
211
+ if not self._get_userconfig('access_token'):
212
+ self._request_access_token()
213
+ elif (timestamp+60) > self._get_userconfig('expires'):
214
+ self._refresh_access_token()
215
+ else:
216
+ self.logged_in = True
217
+ return True
218
+
219
+ def fetch_list(self):
220
+ self.check_credentials()
221
+ self.msg.info(self.name, 'Downloading list...')
222
+
223
+ param = {'access_token': self._get_userconfig('access_token')}
224
+ data = self._request("GET", "user/{0}/{1}list".format(self.userid, self.mediatype), get=param)
225
+
226
+ showlist = {}
227
+ airinglist = []
228
+
229
+ #with open('list', 'w') as f:
230
+ # json.dump(data, f, indent=2)
231
+
232
+ if not data["lists"]:
233
+ # No lists returned so no need to continue
234
+ return showlist
235
+
236
+ for remotelist in data["lists"].values():
237
+ for item in remotelist:
238
+ if item['list_status'] not in self.media_info()['statuses']:
239
+ continue
240
+
241
+ show = utils.show()
242
+ showid = item[self.mediatype]['id']
243
+ showdata = {
244
+ 'id': showid,
245
+ 'title': item[self.mediatype]['title_romaji'],
246
+ 'aliases': [item[self.mediatype]['title_english']],
247
+ 'type': item[self.mediatype]['type'],
248
+ 'status': self.status_translate[item[self.mediatype][self.airing_str]],
249
+ 'my_progress': self._c(item[self.watched_str]),
250
+ 'my_status': item['list_status'],
251
+ 'my_score': self._c(item['score']),
252
+ 'total': self._c(item[self.mediatype][self.total_str]),
253
+ 'image': item[self.mediatype]['image_url_lge'],
254
+ 'image_thumb': item[self.mediatype]['image_url_med'],
255
+ 'url': str("https://anilist.co/%s/%d" % (self.mediatype, showid)),
256
+ }
257
+ show.update({k:v for k,v in showdata.items() if v})
258
+
259
+ if show['status'] == 1:
260
+ airinglist.append(showid)
261
+
262
+ showlist[showid] = show
263
+
264
+ if self.mediatype == 'anime': # Airing data unavailable for manga
265
+ if len(airinglist) > 0:
266
+ browseparam = {'access_token': self._get_userconfig('access_token'),
267
+ 'status': 'Currently Airing',
268
+ 'airing_data': 'true',
269
+ 'full_page': 'true'}
270
+ data = self._request("GET", "browse/anime", get=browseparam)
271
+ for item in data:
272
+ id = item['id']
273
+ if id in showlist and 'airing' in item:
274
+ if item['airing']:
275
+ showlist[id].update({
276
+ 'next_ep_number': item['airing']['next_episode'],
277
+ 'next_ep_time': item['airing']['time'],
278
+ })
279
+ return showlist
280
+
281
+ def add_show(self, item):
282
+ self.check_credentials()
283
+ self.msg.info(self.name, "Adding item %s..." % item['title'])
284
+ self._update_entry(item, "POST")
285
+
286
+ def update_show(self, item):
287
+ self.check_credentials()
288
+ self.msg.info(self.name, "Updating item %s..." % item['title'])
289
+ self._update_entry(item, "PUT")
290
+
291
+ def delete_show(self, item):
292
+ self.check_credentials()
293
+ self.msg.info(self.name, "Deleting item %s..." % item['title'])
294
+
295
+ try:
296
+ data = self._request("DELETE", "{}list/{}".format(self.mediatype, item['id']), auth=True)
297
+ except ValueError:
298
+ # An empty document, without any JSON, is returned
299
+ # when the delete worked.
300
+ pass
301
+
302
+ def search(self, criteria):
303
+ self.check_credentials()
304
+
305
+ self.msg.info(self.name, "Searching for {}...".format(criteria))
306
+ param = {'access_token': self._get_userconfig('access_token')}
307
+ data = self._request("GET", "{0}/search/{1}".format(self.mediatype, 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)))
318
+
319
+ showlist = []
320
+ for item in data:
321
+ show = utils.show()
322
+ showid = item['id']
323
+ showdata = {
324
+ 'id': showid,
325
+ 'title': item['title_romaji'],
326
+ 'aliases': [item['title_english']],
327
+ 'type': item['type'],
328
+ 'status': item[self.airing_str],
329
+ 'my_status': self.media_info()['status_start'],
330
+ 'total': item[self.total_str],
331
+ 'image': item['image_url_lge'],
332
+ 'image_thumb': item['image_url_med'],
333
+ 'url': str("https://anilist.co/%s/%d" % (self.mediatype, showid)),
334
+ }
335
+ show.update({k:v for k,v in showdata.items() if v})
336
+
337
+ showlist.append( show )
338
+
339
+ return showlist
340
+
341
+ def request_info(self, itemlist):
342
+ self.check_credentials()
343
+ param = {'access_token': self._get_userconfig('access_token')}
344
+ infolist = []
345
+
346
+ for show in itemlist:
347
+ data = self._request("GET", "{0}/{1}".format(self.mediatype, show['id']), get=param)
348
+ infolist.append( self._parse_info(data) )
349
+
350
+ self._emit_signal('show_info_changed', infolist)
351
+ return infolist
352
+
353
+ def media_info(self):
354
+ """Return information about the currently selected mediatype."""
355
+ return self.mediatypes[self.mediatype]
356
+
357
+ def _update_entry(self, item, method):
358
+ values = { 'id': item['id'] }
359
+ if 'my_progress' in item.keys():
360
+ values[self.watched_str] = item['my_progress']
361
+ if 'my_status' in item.keys():
362
+ values['list_status'] = item['my_status']
363
+ if 'my_score' in item.keys():
364
+ values['score'] = item['my_score']
365
+
366
+ data = self._request(method, "{}list".format(self.mediatype), post=values, auth=True)
367
+ return True
368
+
369
+ def _parse_info(self, item):
370
+ info = utils.show()
371
+ showid = item['id']
372
+ info.update({
373
+ 'id': showid,
374
+ 'title': item['title_romaji'],
375
+ 'status': self.status_translate[item[self.airing_str]],
376
+ 'image': item['image_url_lge'],
377
+ 'url': str("https://anilist.co/%s/%d" % (self.mediatype, showid)),
378
+ 'start_date': self._str2date(item.get('start_date')),
379
+ 'end_date': self._str2date(item.get('end_date')),
380
+ 'extra': [
381
+ ('English', item.get('title_english')),
382
+ ('Japanese', item.get('title_japanese')),
383
+ ('Classification', item.get('classification')),
384
+ ('Genres', item.get('genres')),
385
+ ('Synopsis', item.get('description')),
386
+ ('Type', item.get('type')),
387
+ ('Average score', item.get('average_score')),
388
+ ('Status', item.get(self.airing_str)),
389
+ ('Start Date', item.get('start_date')),
390
+ ('End Date', item.get('end_date')),
391
+ ]
392
+ })
393
+ return info
394
+
395
+ def _str2date(self, string):
396
+ if string is not None:
397
+ try:
398
+ return datetime.datetime.strptime(string[:10], "%Y-%m-%d")
399
+ except ValueError:
400
+ return None # Ignore date if it's invalid
401
+ else:
402
+ return None
403
+
404
+
405
+ def _c(self, s):
406
+ if s is None:
407
+ return 0
408
+ else:
409
+ return s
410
+
trackma/lib/libhb.py ADDED
@@ -0,0 +1,239 @@
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 urllib.parse
20
+ import urllib.request
21
+ import json
22
+
23
+ from trackma.lib.lib import lib
24
+ from trackma import utils
25
+
26
+ class libhb(lib):
27
+ """
28
+ API class to communicate with Hummingbird
29
+ Should inherit a base library interface.
30
+
31
+ Website: https://hummingbird.me/
32
+ API documentation:
33
+ Designed by:
34
+
35
+ """
36
+ name = 'libhb'
37
+
38
+ username = '' # TODO Must be filled by check_credentials
39
+ auth = ''
40
+ logged_in = False
41
+
42
+ api_info = { 'name': 'Hummingbird', 'shortname': 'hb', 'version': 'v0.2', 'merge': False }
43
+
44
+ default_mediatype = 'anime'
45
+ mediatypes = dict()
46
+ mediatypes['anime'] = {
47
+ 'has_progress': True,
48
+ 'can_add': True,
49
+ 'can_delete': True,
50
+ 'can_score': True,
51
+ 'can_status': True,
52
+ 'can_update': True,
53
+ 'can_play': True,
54
+ 'status_start': 'currently-watching',
55
+ 'status_finish': 'completed',
56
+ 'statuses': ['currently-watching', 'completed', 'on-hold', 'dropped', 'plan-to-watch'],
57
+ 'statuses_dict': { 'currently-watching': 'Watching', 'completed': 'Completed', 'on-hold': 'On Hold', 'dropped': 'Dropped', 'plan-to-watch': 'Plan to Watch' },
58
+ 'score_max': 5,
59
+ 'score_step': 0.5,
60
+ }
61
+
62
+ url = "https://hummingbird.me/api/v1"
63
+
64
+ status_translate = {'Currently Airing': utils.STATUS_AIRING,
65
+ 'Finished Airing': utils.STATUS_FINISHED,
66
+ 'Not Yet Aired': utils.STATUS_NOTYET}
67
+
68
+ def __init__(self, messenger, account, userconfig):
69
+ """Initializes the useragent through credentials."""
70
+ super(libhb, self).__init__(messenger, account, userconfig)
71
+
72
+ self.username = account['username']
73
+ self.password = account['password']
74
+
75
+ # Build opener with the mashape API key
76
+ self.opener = urllib.request.build_opener()
77
+
78
+ def _request(self, url, get=None, post=None):
79
+ if get:
80
+ url += "?%s" % urllib.parse.urlencode(get)
81
+ if post:
82
+ post = urllib.parse.urlencode(post).encode('utf-8')
83
+
84
+ try:
85
+ return self.opener.open(self.url + url, post, 10)
86
+ except urllib.request.HTTPError as e:
87
+ if e.code == 401:
88
+ raise utils.APIError("Incorrect credentials.")
89
+ else:
90
+ raise utils.APIError("Connection error: %s" % e)
91
+ except urllib.request.URLError as e:
92
+ raise utils.APIError("URL error: %s" % e)
93
+
94
+ def check_credentials(self):
95
+ """Checks if credentials are correct; returns True or False."""
96
+ if self.logged_in:
97
+ return True # Already logged in
98
+
99
+ self.msg.info(self.name, 'Logging in...')
100
+
101
+ response = self._request( "/users/authenticate", post={'username': self.username, 'password': self.password} ).read().decode('utf-8')
102
+ self.auth = response.strip('"')
103
+ self._set_userconfig('username', self.username)
104
+ self.logged_in = True
105
+ return True
106
+
107
+ def fetch_list(self):
108
+ """Queries the full list from the remote server.
109
+ Returns the list if successful, False otherwise."""
110
+ self.check_credentials()
111
+ self.msg.info(self.name, 'Downloading list...')
112
+
113
+ try:
114
+ data = self._request( "/users/%s/library" % self.username, get={'auth_token': self.auth} )
115
+ shows = json.loads(data.read().decode('utf-8'))
116
+
117
+ showlist = dict()
118
+ infolist = list()
119
+
120
+ for show in shows:
121
+ showid = show['anime']['id']
122
+ status = show['anime']['status']
123
+ rating = show['rating']['value']
124
+ epCount = show['anime']['episode_count']
125
+ alt_titles = []
126
+
127
+ if show['anime']['alternate_title'] is not None:
128
+ alt_titles.append(show['anime']['alternate_title'])
129
+ showlist[showid] = utils.show()
130
+ showlist[showid].update({
131
+ 'id': showid,
132
+ 'title': show['anime']['title'] or show['anime']['alternate_title'] or "",
133
+ 'status': self.status_translate[status],
134
+ 'start_date': self._str2date( show['anime']['started_airing'] ),
135
+ 'end_date': self._str2date( show['anime']['finished_airing'] ),
136
+ 'my_progress': show['episodes_watched'],
137
+ 'my_score': float(rating) if rating is not None else 0.0,
138
+ 'aliases': alt_titles,
139
+ 'my_status': show['status'],
140
+ 'total': int(epCount) if epCount is not None else 0,
141
+ 'image': show['anime']['cover_image'],
142
+ 'url': str("https://hummingbird.me/%s/%d" % (self.mediatype, showid)),
143
+ })
144
+ info = self._parse_info(show['anime'])
145
+ infolist.append(info)
146
+
147
+ self._emit_signal('show_info_changed', infolist)
148
+ return showlist
149
+ except urllib.request.HTTPError as e:
150
+ raise utils.APIError("Error getting list.")
151
+
152
+ def add_show(self, item):
153
+ """Adds a new show in the server"""
154
+ self.update_show(item)
155
+
156
+ def update_show(self, item):
157
+ """Sends a show update to the server"""
158
+ self.check_credentials()
159
+ self.msg.info(self.name, "Updating show %s..." % item['title'])
160
+
161
+ # Send the POST data to the Hummingbird API
162
+ values = {'auth_token': self.auth}
163
+
164
+ # Update necessary keys
165
+ if 'my_progress' in item.keys():
166
+ values['episodes_watched'] = item['my_progress']
167
+ if 'my_status' in item.keys():
168
+ values['status'] = item['my_status']
169
+ if 'my_score' in item.keys():
170
+ values['sane_rating_update'] = item['my_score']
171
+
172
+ try:
173
+ self._request("/libraries/%s" % item['id'], post=values)
174
+ except urllib.request.HTTPError as e:
175
+ raise utils.APIError('Error updating: ' + str(e.code))
176
+
177
+ def delete_show(self, item):
178
+ """Sends a show delete to the server"""
179
+ self.check_credentials()
180
+ self.msg.info(self.name, "Deleting show %s..." % item['title'])
181
+
182
+ values = {'auth_token': self.auth}
183
+ try:
184
+ self._request("/libraries/%s/remove" % item['id'], post=values)
185
+ except urllib.request.HTTPError as e:
186
+ raise utils.APIError('Error deleting: ' + str(e.code))
187
+
188
+ def search(self, query):
189
+ self.msg.info(self.name, "Searching for %s..." % query)
190
+
191
+ values = {'query': query}
192
+ try:
193
+ data = self._request("/search/anime", get=values)
194
+ shows = json.loads(data.read().decode('utf-8'))
195
+
196
+ infolist = []
197
+ for show in shows:
198
+ info = self._parse_info(show)
199
+ info['my_status'] = 'currently-watching' # TODO : Default to watching; this should be changeable
200
+ infolist.append(info)
201
+
202
+ self._emit_signal('show_info_changed', infolist)
203
+
204
+ if not infolist:
205
+ raise utils.APIError('No results.')
206
+
207
+ return infolist
208
+ except urllib.request.HTTPError as e:
209
+ raise utils.APIError('Error searching: ' + str(e.code))
210
+
211
+ def _str2date(self, string):
212
+ if string != '0000-00-00':
213
+ try:
214
+ return datetime.datetime.strptime(string, "%Y-%m-%d")
215
+ except:
216
+ return None # Ignore date if it's invalid
217
+ else:
218
+ return None
219
+
220
+ def _parse_info(self, show):
221
+ info = utils.show()
222
+ alt_titles = []
223
+ if show['alternate_title'] is not None:
224
+ alt_titles.append(show['alternate_title'])
225
+ info.update({
226
+ 'id': show['id'],
227
+ 'title': show['title'] or show['alternate_title'] or "",
228
+ 'status': self.status_translate[show['status']],
229
+ 'image': show['cover_image'],
230
+ 'url': show['url'],
231
+ 'aliases': alt_titles,
232
+ 'extra': [
233
+ ('Alternate title', show['alternate_title']),
234
+ ('Show type', show['show_type']),
235
+ ('Synopsis', show['synopsis']),
236
+ ('Status', show['status']),
237
+ ]
238
+ })
239
+ return info