forked from phil65/script.extendedinfo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTheMovieDB.py
332 lines (307 loc) · 13.5 KB
/
TheMovieDB.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
import xbmcaddon, os, xbmc, xbmcvfs, time
import simplejson as json
from Utils import log, prettyprint, read_from_file, save_to_file, CompareWithLibrary
import urllib
from urllib2 import Request, urlopen
moviedb_key = '34142515d9d23817496eeb4ff1d223d0'
__addon__ = xbmcaddon.Addon()
__addonid__ = __addon__.getAddonInfo('id')
__language__ = __addon__.getLocalizedString
Addon_Data_Path = os.path.join( xbmc.translatePath("special://profile/addon_data/%s" % __addonid__ ).decode("utf-8") )
base_url = ""
poster_size = ""
fanart_size = ""
def HandleTheMovieDBMovieResult(results):
movies = []
log("starting HandleTheMovieDBMovieResult")
for movie in results:
newmovie = {'Art(fanart)': base_url + fanart_size + str(movie.get('backdrop_path',"")),
'Art(poster)': base_url + poster_size + str(movie.get('poster_path',"")),
'Title': movie.get('title',""),
'OriginalTitle': movie.get('original_title',""),
'ID': movie.get('id',""),
'Path': "",
'Play': "",
'DBID': "",
'Rating': movie.get('vote_average',""),
'Votes': movie.get('vote_count',""),
'Year': movie.get('release_date',"")[:4],
'Premiered': movie.get('release_date',"") }
if not str(movie['id']) in str(movies): ## too dirty
movies.append(newmovie)
movies = CompareWithLibrary(movies)
return movies
def HandleTheMovieDBTVShowResult(results):
tvshows = []
log("starting HandleTheMovieDBTVShowResult")
for tv in results:
newtv = {'Art(fanart)': base_url + fanart_size + str(tv.get('backdrop_path',"")),
'Art(poster)': base_url + poster_size + str(tv.get('poster_path',"")),
'Title': tv.get('name',""),
'OriginalTitle': tv.get('original_name',""),
'ID': tv.get('id',""),
'Path': "",
'Play': "",
'DBID': "",
'Rating': tv.get('vote_average',""),
'Votes': tv.get('vote_count',""),
'Premiered': tv.get('first_air_date',"") }
if not str(tv['id']) in str(tvshows): ## too dirty
tvshows.append(newtv)
tvshows = CompareWithLibrary(tvshows)
return tvshows
def HandleTheMovieDBListResult(results):
lists = []
for list in results["lists"]["results"]:
newlist = {'Art(poster)': base_url + poster_size + str(list.get('poster_path',"")),
'Title': list['name'],
'ID': list['id'],
'Description': list['description']}
lists.append(newlist)
return lists
def HandleTheMovieDBPeopleResult(results):
people = []
for person in results:
newperson = {'adult': person['adult'],
'name': person['name'],
'also_known_as': person['also_known_as'],
'biography': person['biography'],
'birthday': person['birthday'],
'id': person['id'],
'deathday': person['deathday'],
'place_of_birth': person['place_of_birth'],
'thumb': person['profile_path'] }
people.append(newperson)
return people
def HandleTheMovieDBCompanyResult(results):
companies = []
log("starting HandleLastFMCompanyResult")
for company in results:
newcompany = {'parent_company': company['parent_company'],
'name': company['name'],
'description': company['description'],
'headquarters': company['headquarters'],
'homepage': company['homepage'],
'id': company['id'],
'logo_path': company['logo_path'] }
companies.append(newcompany)
return companies
def SearchforCompany(Company):
# Companies = Company.split(" / ")
# Company = Companies[0]
import re
regex = re.compile('\(.+?\)')
Company = regex.sub('', Company)
log(Company)
response = GetMovieDBData("search/company?query=%s&" % urllib.quote_plus(Company),30)
try:
return response["results"][0]["id"]
except:
log("could not find Company ID")
return ""
def GetPersonID(person):
Persons = person.split(" / ")
person = Persons[0]
response = GetMovieDBData("search/person?query=%s&" % urllib.quote_plus(person),30)
try:
return response["results"][0]["id"]
except:
log("could not find Person ID")
return ""
def SearchForSet(setname):
setname = setname.replace("[","").replace("]","").replace("Kollektion","Collection")
response = GetMovieDBData("search/collection?query=%s&language=%s&" % (urllib.quote_plus(setname.encode("utf-8")), __addon__.getSetting("LanguageID")),14)
try:
return response["results"][0]["id"]
except:
return ""
def GetMovieDBData(url = "", cache_days = 14):
from base64 import b64encode
global base_url
global poster_size
global fanart_size
if not base_url:
log("fetching base_url and size (MovieDB config)")
base_url = True
base_url, poster_size, fanart_size = GetMovieDBConfig()
filename = b64encode(url).replace("/","XXXX")
path = Addon_Data_Path + "/" + filename + ".txt"
log("trying to load " + path)
if xbmcvfs.exists(path) and ((time.time() - os.path.getmtime(path)) < (cache_days * 86400)):
return read_from_file(path)
else:
url = "http://api.themoviedb.org/3/" + url + "api_key=%s" % moviedb_key
log("Downloading MovieDB Data: " + url)
headers = {"Accept": "application/json"}
succeed = 0
while succeed < 3:
try:
request = Request(url, headers = headers)
response = urlopen(request).read()
log("saved file " + filename)
response = json.loads(response)
save_to_file(response,filename,Addon_Data_Path)
return response
except:
log("could not get data from %s" % url)
xbmc.sleep(1000)
succeed += 1
return []
def GetMovieDBConfig():
response = GetMovieDBData("configuration?",60)
if response:
return (response["images"]["base_url"],response["images"]["poster_sizes"][-2],response["images"]["backdrop_sizes"][-2])
else:
return ("","")
def GetCompanyInfo(Id):
response = GetMovieDBData("company/%s/movies?append_to_response=movies&" % (Id),30)
if response and "results" in response:
return HandleTheMovieDBMovieResult(response["results"])
else:
return []
def millify(n):
import math
millnames=['','Thousand','Million','Billion','Trillion']
millidx=max(0,min(len(millnames)-1,
int(math.floor(math.log10(abs(n))/3.0))))
return '%.0f %s'%(n/10**(3*millidx),millnames[millidx])
def GetExtendedMovieInfo(Id):
response = GetMovieDBData("movie/%s?append_to_response=trailers,casts,releases,keywords,similar_movies,lists&language=%s&" % (Id, __addon__.getSetting("LanguageID")),30)
prettyprint(response)
if True:
authors = []
directors = []
genres = []
for item in response['genres']:
genres.append(item["name"])
for item in response['casts']['crew']:
if item["job"] == "Author":
authors.append(item["name"])
if item["job"] == "Director":
directors.append(item["name"])
Writer = " / ".join(authors)
Director = " / ".join(directors)
Genre = " / ".join(genres)
if len(response['trailers']['youtube']) > 0:
Trailer = response['trailers']['youtube'][0]['source']
else:
Trailer = ""
if len(response['releases']['countries']) > 0:
mpaa = response['releases']['countries'][0]['certification']
else:
mpaa = ""
if len(response['production_countries']) > 0:
Country = response['production_countries'][0]["name"]
else:
Country = ""
if len(response['production_companies']) > 0:
Studio = response['production_companies'][0]["name"]
else:
Studio = ""
Set = response.get("belongs_to_collection","")
if Set:
SetName = Set.get("name","")
SetID = Set.get("id","")
else:
SetName = ""
SetID = ""
if 'release_date' in response and response.get('release_date') <> None:
year = response.get('release_date',"")[:4]
else:
year = ""
BudgetValue = response.get('budget',"")
if not BudgetValue in [0,""]:
Budget = millify(float(BudgetValue))
else:
Budget = ""
newmovie = {'Art(fanart)': base_url + fanart_size + str(response.get('backdrop_path',"")),
'Fanart': base_url + fanart_size + str(response.get('backdrop_path',"")),
'Art(poster)': base_url + poster_size + str(response.get('poster_path',"")),
'Poster': base_url + poster_size + str(response.get('poster_path',"")),
'Title': response.get('title',""),
'Label': response.get('title',""),
'Tagline': response.get('tagline',""),
'RunningTime': response.get('runtime',""),
'Budget': response.get('budget',""),
'mpaa': mpaa,
'Director': Director,
'Writer': Writer,
'Budget': Budget,
'Homepage': response.get('homepage',""),
'Set': SetName,
'SetId': SetID,
'ID': response.get('id',""),
'Plot': response.get('overview',""),
'OriginalTitle': response.get('original_title',""),
'Genre': Genre,
'Rating': response.get('vote_average',""),
'Play': '',
'Trailer': 'plugin://plugin.video.youtube/?action=play_video&videoid=%s' %Trailer,
'ReleaseDate':response.get('release_date',""),
'Premiered':response.get('release_date',""),
'Country':Country,
'Studio':Studio,
'DiscArt':"",
'VideoResolution':"",
'AudioChannels':"",
'VideoCodec':"",
'VideoAspect':"",
'Logo': "",
'DBID': "",
'Studio':Studio,
'Year': year }
else:
return False
newmovie = CompareWithLibrary([newmovie])
return newmovie[0]
def GetMovieLists(Id):
response = GetMovieDBData("movie/%s?append_to_response=trailers,casts,releases,keywords,similar_movies,lists&language=%s&" % (Id, __addon__.getSetting("LanguageID")),30)
return HandleTheMovieDBListResult(response)
def GetMovieKeywords(Id):
response = GetMovieDBData("movie/%s?append_to_response=trailers,casts,releases,keywords,similar_movies,lists&language=%s&" % (Id, __addon__.getSetting("LanguageID")),30)
keywords = []
if True:
for keyword in response["keywords"]["keywords"]:
newkeyword = {'id': keyword.get('id',""),
'name': keyword['name']}
keywords.append(newkeyword)
else:
pass
return keywords
def GetSimilarMovies(Id):
response = GetMovieDBData("movie/%s?append_to_response=trailers,casts,releases,keywords,similar_movies,lists&language=%s&" % (Id, __addon__.getSetting("LanguageID")),30)
return HandleTheMovieDBMovieResult(response["similar_movies"]["results"])
def GetMovieDBTVShows(type):
response = GetMovieDBData("tv/%s?language=%s&" % ( type, __addon__.getSetting("LanguageID")),2)
return HandleTheMovieDBTVShowResult(response["results"])
def GetMovieDBMovies(type):
response = GetMovieDBData("movie/%s?language=%s&" % ( type, __addon__.getSetting("LanguageID")),2)
return HandleTheMovieDBMovieResult(response["results"])
def GetSetMovies(Id):
response = GetMovieDBData("collection/%s?language=%s&" % (Id, __addon__.getSetting("LanguageID")),14)
return HandleTheMovieDBMovieResult(response["parts"])
def GetDirectorMovies(Id):
response = GetMovieDBData("person/%s/credits?language=%s&" % (Id, __addon__.getSetting("LanguageID")),14)
# return HandleTheMovieDBMovieResult(response["crew"]) + HandleTheMovieDBMovieResult(response["cast"])
return HandleTheMovieDBMovieResult(response["crew"])
def search_movie(medianame,year = ''):
log('TMDB API search criteria: Title[''%s''] | Year[''%s'']' % (medianame, year) )
medianame = urllib.quote_plus(medianame.encode('utf8','ignore'))
response = GetMovieDBData("search/movie?query=%s+%s&language=%s&" % (medianame, year, __addon__.getSetting("LanguageID")),1)
tmdb_id = ''
try:
if response == "Empty":
tmdb_id = ''
else:
for item in response['results']:
if item['id']:
tmdb_id = item['id']
log(tmdb_id)
break
except Exception, e:
log( str( e ), xbmc.LOGERROR )
if tmdb_id == '':
log('TMDB API search found no ID')
else:
log('TMDB API search found ID: %s' %tmdb_id)
return tmdb_id