-
Notifications
You must be signed in to change notification settings - Fork 28
/
tmdb.py
498 lines (414 loc) · 19.5 KB
/
tmdb.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#author:doganaydin
#project:themoviedb
#repository:http://github.com/doganaydin/themoviedb
#license: LGPLv3 http://www.gnu.org/licenses/lgpl.html
"""An interface to the themoviedb.org API"""
__author__ = "doganaydin"
__version__ = "0.1"
try:
import simplejson
except:
import json as simplejson
import requests
config = {}
def configure(api_key):
config['apikey'] = api_key
config['urls'] = {}
config['urls']['movie.search'] = "http://api.themoviedb.org/3/search/movie?query=%%s&api_key=%(apikey)s&page=%%s" % (config)
config['urls']['movie.info'] = "http://api.themoviedb.org/3/movie/%%s?api_key=%(apikey)s" % (config)
config['urls']['people.search'] = "http://api.themoviedb.org/3/search/person?query=%%s&api_key=%(apikey)s&page=%%s" % (config)
config['urls']['collection.info'] = "http://api.themoviedb.org/3/collection/%%s&api_key=%(apikey)s" % (config)
config['urls']['movie.alternativetitles'] = "http://api.themoviedb.org/3/movie/%%s/alternative_titles?api_key=%(apikey)s" % (config)
config['urls']['movie.casts'] = "http://api.themoviedb.org/3/movie/%%s/casts?api_key=%(apikey)s" % (config)
config['urls']['movie.images'] = "http://api.themoviedb.org/3/movie/%%s/images?api_key=%(apikey)s" % (config)
config['urls']['movie.keywords'] = "http://api.themoviedb.org/3/movie/%%s/keywords?api_key=%(apikey)s" % (config)
config['urls']['movie.releases'] = "http://api.themoviedb.org/3/movie/%%s/releases?api_key=%(apikey)s" % (config)
config['urls']['movie.trailers'] = "http://api.themoviedb.org/3/movie/%%s/trailers?api_key=%(apikey)s" % (config)
config['urls']['movie.translations'] = "http://api.themoviedb.org/3/movie/%%s/translations?api_key=%(apikey)s" % (config)
config['urls']['person.info'] = "http://api.themoviedb.org/3/person/%%s&api_key=%(apikey)s" % (config)
config['urls']['person.credits'] = "http://api.themoviedb.org/3/person/%%s/credits?api_key=%(apikey)s" % (config)
config['urls']['person.images'] = "http://api.themoviedb.org/3/person/%%s/images?api_key=%(apikey)s" % (config)
config['urls']['latestmovie'] = "http://api.themoviedb.org/3/latest/movie?api_key=%(apikey)s" % (config)
config['urls']['config'] = "http://api.themoviedb.org/3/configuration?api_key=%(apikey)s" % (config)
config['urls']['request.token'] = "http://api.themoviedb.org/3/authentication/token/new?api_key=%(apikey)s" % (config)
config['urls']['session.id'] = "http://api.themoviedb.org/3/authentication/session/new?api_key=%(apikey)s&request_token=%%s" % (config)
config['urls']['movie.add.rating'] = "http://api.themoviedb.org/3/movie/%%s/rating?session_id=%%s&api_key=%(apikey)s" % (config)
config['api'] = {}
config['api']['backdrop.sizes'] = ""
config['api']['base.url'] = ""
config['api']['poster.sizes'] = ""
config['api']['profile.sizes'] = ""
config['api']['session.id'] = ""
class TmdbAPIException(Exception):
pass
class Core(object):
def getJSON(self,url,language=None):
if language != None:
if url.find('?') == -1:
url += "?language=%s"
else:
url += "&language=%s"
url = url % (language)
response = requests.get(url)
# check http status code
if not response.status_code == 200:
raise TmdbAPIException, 'received http status code ' + str(response.status_code)
# parse json
page = response.content
try:
json = simplejson.loads(page)
except:
json = simplejson.loads(page.decode('utf-8'))
# check for error response
if 'status_code' in json and 'status_message' in json:
raise TmdbAPIException, json['status_message']
elif 'status_code' in json:
raise TmdbAPIException, 'received tmdb status code ' + str(json['status_code'])
return json
def escape(self,text):
if len(text) > 0:
return requests.utils.quote(text)
return False
def update_configuration(self):
c = self.getJSON(config['urls']['config'])
config['api']['backdrop.sizes'] = c['images']['backdrop_sizes']
config['api']['base.url'] = c['images']['base_url']
config['api']['poster.sizes'] = c['images']['poster_sizes']
config['api']['profile.sizes'] = c['images']['profile_sizes']
return "ok"
def backdrop_sizes(self,img_size):
size_list = {'s':'w300','m':'w780','l':'w1280','o':'original'}
return size_list[img_size]
def poster_sizes(self,img_size):
size_list = {'s':'w92','m':'185','l':'w500','o':'original'}
return size_list[img_size]
def profile_sizes(self,img_size):
size_list = {'s':'w45','m':'185','l':'w632','o':'original'}
return size_list[img_size]
def request_token(self):
req = self.getJSON(config['urls']['request.token'])
r = req["request_token"]
return {"url":"http://themoviedb.org/authenticate/%s" % r,"request_token":r}
def session_id(self,token):
sess = self.getJSON(config['urls']['session.id'] % token)
config['api']['session.id'] = sess["session_id"]
return sess["session_id"]
class Movie(Core):
def __init__(self, title="", id=-1, limit=False, language=None):
self.limit = limit
self.language = language
self.update_configuration()
if id > -1:
self.get_movie(id)
else:
self.search_movie(title, limit)
self.keywords = None
self.releases = None
self.alternative_titles = None
self.translations = None
self.cast = None
self.trailers = None
def get_movie(self, id):
self.full_info(id)
self.movies = {'page': 1, 'results': [self.movies_full], 'total_pages': 1, 'total_results': 1}
def search_movie(self, title, limit=False):
title = self.escape(title)
self.movies = self.getJSON(config['urls']['movie.search'] % (title,str(1)), self.language)
self.movies_full = ""
pages = self.movies["total_pages"]
if not self.limit:
for i in range(2, int(pages)):
self.movies["results"].extend(self.getJSON(config['urls']['movie.search'] % (title,str(i)), self.language)["results"])
def full_info(self,movie_id):
self.movies_full = self.getJSON(config['urls']['movie.info'] % str(movie_id), self.language)
def get_total_results(self):
if self.limit:
return len(self.movies["results"])
return self.movies["total_results"]
def get_id(self,movie_index=0):
return self.movies["results"][movie_index]["id"]
# Sizes = s->w300 m->w780 l->w1280 o->original(default)
def get_backdrop(self,img_size="o",movie_index=0):
img_path = self.movies["results"][movie_index]["backdrop_path"]
return config['api']['base.url']+self.backdrop_size(img_size)+img_path
def get_original_title(self,movie_index=0):
return self.movies["results"][movie_index]["original_title"]
def get_popularity(self,movie_index=0):
return self.movies["results"][movie_index]["popularity"]
def get_release_date(self,movie_index=0):
return self.movies["results"][movie_index]["release_date"]
def get_title(self,movie_index=0):
return self.movies["results"][movie_index]["title"]
# Sizes = s->w92 m->w185 l->w500 o->original(default)
def get_poster(self,img_size="o",movie_index=0):
img_path = self.movies["results"][movie_index]["poster_path"]
return config['api']['base.url']+self.poster_sizes(img_size)+img_path
def get_keywords(self,movie_id=0):
if self.keywords == None:
if movie_id == 0:
movie_id = self.movies_full['id']
self.keywords = self.getJSON(config['urls']['movie.keywords'] % str(movie_id))
return self.keywords['keywords']
def get_trailers(self,movie_id=0):
if self.trailers == None:
if movie_id == 0:
movie_id = self.movies_full['id']
self.trailers = self.getJSON(config['urls']['movie.trailers'] % (str(movie_id)),self.language)
return self.trailers
def get_cast(self,movie_id=0):
if self.cast == None:
if movie_id == 0:
movie_id = self.movies_full['id']
self.cast = self.getJSON(config['urls']['movie.casts'] % str(movie_id))
return self.cast
def get_releases(self,country=None,movie_id=0):
if self.releases == None:
if movie_id == 0:
movie_id = self.movies_full['id']
self.releases = self.getJSON(config['urls']['movie.releases'] % str(movie_id))
if country != None:
country = country.lower()
for release in self.releases['countries']:
if country == release['iso_3166_1'].lower():
return release
return {}
return self.releases['countries']
def get_translations(self,language=None,movie_id=0):
if self.translations == None:
if movie_id == 0:
movie_id = self.movies_full['id']
self.translations = self.getJSON(config['urls']['movie.translations'] % str(movie_id))
if language != None:
language = language.lower()
for translation in self.translations['translations']:
if language == translation['iso_639_1'].lower():
return translation
return {}
return self.translations['translations']
def get_alternative_titles(self,country=None,movie_id=0):
if self.alternative_titles == None:
if movie_id == 0:
movie_id = self.movies_full['id']
self.alternative_titles = self.getJSON(config['urls']['movie.alternativetitles'] % str(movie_id))
if country != None:
country = country.lower()
for title in self.alternative_titles['titles']:
if country == title['iso_3166_1'].lower():
return title
return {}
return self.alternative_titles['titles']
def is_adult(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['adult']
def is_in_collection(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['belongs_to_collection'] != None
def get_collection_id(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['belongs_to_collection']["id"]
def get_collection_name(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['belongs_to_collection']["name"]
# Sizes = s->w300 m->w780 l->w1280 o->original(default)
def get_collection_backdrop(self,img_size="o",movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
img_path = self.movies_full["belongs_to_collection"]["backdrop_path"]
return config['api']['base.url']+self.poster_sizes(img_size)+img_path
# Sizes = s->w92 m->w185 l->w500 o->original(default)
def get_collection_poster(self,img_size="o",movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
img_path = self.movies_full["belongs_to_collection"]["poster_path"]
return config['api']['base.url']+self.poster_sizes(img_size)+img_path
def get_budget(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['budget']
def get_genres(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
genres = []
for i in self.movies_full['genres']:
genres.append({"id":i["id"],"name":i["name"]})
return genres
def get_homepage(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['homepage']
def get_imdb_id(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['imdb_id']
def get_overview(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['overview']
def get_production_companies(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
companies = []
for i in self.movies_full['production_companies']:
companies.append({"id":i["id"],"name":i["name"]})
return companies
def get_productions_countries(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
countries = []
for i in self.movies_full['production_countries']:
countries.append({"iso_3166_1":i["iso_3166_1"],"name":i["name"]})
return countries
def get_revenue(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['revenue']
def get_runtime(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['runtime']
def get_spoken_languages(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
langs = []
for i in self.movies_full['spoken_languages']:
langs.append({"iso_639_1":i["iso_639_1"],"name":i["name"]})
return langs
def get_tagline(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['tagline']
def get_vote_average(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['vote_average']
def get_vote_count(self,movie_id=0):
if movie_id > 0:
self.full_info(movie_id)
return self.movies_full['vote_count']
def add_rating(self,value,movie_id=0):
if isinstance(value,float) or isinstance(value,int):
if movie_id > 0:
self.full_info(movie_id)
if config["api"]["session.id"] == "":
return "PROBLEM_AUTH"
sess_id = config["api"]["session.id"]
data = {"value":float(value)}
req = requests.post(config['urls']['movie.add.rating'] % (movie_id,sess_id),data=data)
res = simplejson.loads(req.content)
if res['status_message'] == "Success":
return True
else:
return False
return "ERROR"
class People(Core):
def __init__(self, people_name, id=-1):
self.update_configuration()
people_name = self.escape(people_name)
self.people = self.getJSON(config['urls']['people.search'] % (people_name,str(1)))
pages = self.people["total_pages"]
self.person = ""
self.images = ""
for i in range(2, int(pages)):
self.people["results"].extend(self.getJSON(config['urls']['people.search'] % (people_name,i))["results"])
if id > -1:
self.person = self.getJSON(config['urls']['person.info'] % id)
self.images = self.getJSON(config['urls']['person.images'] % id)
def full_info(self,person_id):
self.person = self.getJSON(config['urls']['person.info'] % str(person_id))
self.images = self.getJSON(config['urls']['person.images'] % str(person_id))
def get_id(self,people_index=0):
return self.people["results"][people_index]["id"]
def is_adult(self,people_index=0):
return self.people["results"][people_index]["adult"]
def get_name(self,people_index=0):
return self.people["results"][people_index]["name"]
# Sizes = s->w45 m->w185 l->w632 o->original(default)
def get_profile_image(self,img_size="o",people_index=0):
img_path = self.people["results"][people_index]["profile_path"]
return config['api']['base.url']+self.profile_sizes(img_size)+img_path
def get_biography(self,person_id=0):
if person_id > 0:
self.full_info(person_id)
return self.person['biography']
def get_birthday(self,person_id=0):
if person_id > 0:
self.full_info(person_id)
return self.person['birthday']
def get_deathday(self,person_id=0):
if person_id > 0:
self.full_info(person_id)
return self.person['deathday']
def get_place_of_birth(self,person_id=0):
if person_id > 0:
self.full_info(person_id)
return self.person['place_of_birth']
def get_homepage(self,person_id=0):
if person_id > 0:
self.full_info(person_id)
return self.person['homepage']
def get_also_known_as(self,person_id=0):
if person_id > 0:
self.full_info(person_id)
return self.person['also_known_as']
def get_image_aspect_ratio(self,person_id=0,image_index=0):
if person_id > 0:
self.full_info(person_id)
return self.images['profiles'][image_index]['aspect_ratio']
def get_image_height(self,person_id=0,image_index=0):
if person_id > 0:
self.full_info(person_id)
return self.images['profiles'][image_index]['height']
def get_image_width(self,person_id=0,image_index=0):
if person_id > 0:
self.full_info(person_id)
return self.images['profiles'][image_index]['width']
def get_image_iso_639_1(self,person_id=0,image_index=0):
if person_id > 0:
self.full_info(person_id)
return self.images['profiles'][image_index]['iso_639_1']
#Sizes = s->w92 m->w185 l->w500 o->original(default)
def get_image(self,img_size="o",person_id=0,image_index=0):
if person_id > 0:
self.full_info(person_id)
img_path = self.images['profiles'][image_index]['file_path']
return config['api']['base.url']+self.poster_sizes(img_size)+img_path
class Credits(Core):
def __init__(self,person_id,language=None):
self.update_configuration()
self.person = self.getJSON(config['urls']['person.credits'] % person_id, language)
def get_cast_id(self,person_index=0):
return self.person["casts"][person_index]["id"]
def get_cast_character(self,person_index=0):
return self.person["casts"][person_index]["character"]
def get_cast_original_title(self,person_index=0):
return self.person["casts"][person_index]["original_title"]
def get_cast_title(self,person_index=0):
return self.person["casts"][person_index]["title"]
def get_cast_release_date(self,person_index=0):
return self.person["casts"][person_index]["release_date"]
# Sizes = s->w92 m->w185 l->w500 o->original(default)
def get_cast_poster(self,img_size="o",person_index=0):
img_path = self.person["poster_path"]
return config['api']['base.url']+self.poster_sizes(img_size)+img_path
def get_crew_id(self,person_index=0):
return self.person["crew"][person_index]["id"]
def get_crew_department(self,person_index=0):
return self.person["crew"][person_index]["department"]
def get_crew_job(self,person_index=0):
return self.person["crew"][person_index]["job"]
def get_crew_original_title(self,person_index=0):
return self.person["crew"][person_index]["original_title"]
def get_crew_title(self,person_index=0):
return self.person["crew"][person_index]["id"]
def get_crew_release_date(self,person_index=0):
return self.person["crew"][person_index]["release_date"]
# Sizes = s->w92 m->w185 l->w500 o->original(default)
def get_crew_poster(self,img_size="o",person_index=0):
img_path = self.person["poster_path"]
return config['api']['base.url']+self.poster_sizes(img_size)+img_path