1c6d29e3529082f7954d6145f91c3e4190f07807
[plugin.video.netflix.git] / resources / lib / NetflixHttpSubRessourceHandler.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # Module: NetflixHttpSubRessourceHandler
4 # Created on: 07.03.2017
5
6 class NetflixHttpSubRessourceHandler:
7     """ Represents the callable internal server routes & translates/executes them to requests for Netflix"""
8
9     def __init__ (self, kodi_helper, netflix_session):
10         """Sets up credentials & video_list_cache cache
11         Assigns the netflix_session/kodi_helper instacnes
12         Does the initial login if we have user data
13
14         Parameters
15         ----------
16         kodi_helper : :obj:`KodiHelper`
17             instance of the KodiHelper class
18
19         netflix_session : :obj:`NetflixSession`
20             instance of the NetflixSession class
21         """
22         self.kodi_helper = kodi_helper
23         self.netflix_session = netflix_session
24         self.credentials = self.kodi_helper.get_credentials()
25         self.video_list_cache = {}
26
27         # check if we have stored credentials, if so, do the login before the user requests it
28         # if that is done, we cache the profiles
29         if self.credentials['email'] != '' and self.credentials['password'] != '':
30             if self.netflix_session.is_logged_in(account=self.credentials):
31                 self.netflix_session.refresh_session_data(account=self.credentials)
32             else:
33                 self.netflix_session.login(account=self.credentials)
34             self.profiles = self.netflix_session.profiles
35         else:
36             self.profiles = []
37
38     def is_logged_in (self, params):
39         """Existing login proxy function
40
41         Parameters
42         ----------
43         params : :obj:`dict` of :obj:`str`
44             Request params
45
46         Returns
47         -------
48         :obj:`Requests.Response`
49             Response of the remote call
50         """
51         if self.credentials['email'] == '' or self.credentials['password'] == '':
52             return False
53         return self.netflix_session.is_logged_in(account=self.credentials)
54
55     def logout (self, params):
56         """Logout proxy function
57
58         Parameters
59         ----------
60         params : :obj:`dict` of :obj:`str`
61             Request params
62
63         Returns
64         -------
65         :obj:`Requests.Response`
66             Response of the remote call
67         """
68         self.profiles = []
69         self.credentials = {'email': '', 'password': ''}
70         return self.netflix_session.logout()
71
72     def login (self, params):
73         """Logout proxy function
74
75         Parameters
76         ----------
77         params : :obj:`dict` of :obj:`str`
78             Request params
79
80         Returns
81         -------
82         :obj:`Requests.Response`
83             Response of the remote call
84         """
85         email = params.get('email', [''])[0]
86         password = params.get('password', [''])[0]
87         if email != '' and password != '':
88             self.credentials = {'email': email, 'password': password}
89             _ret = self.netflix_session.login(account=self.credentials)
90             self.profiles = self.netflix_session.profiles
91             return _ret
92         return None
93
94     def list_profiles (self, params):
95         """Returns the cached list of profiles
96
97         Parameters
98         ----------
99         params : :obj:`dict` of :obj:`str`
100             Request params
101
102         Returns
103         -------
104         :obj:`dict` of :obj:`str`
105             List of profiles
106         """
107         return self.profiles
108
109     def get_esn (self, params):
110         """ESN getter function
111
112         Parameters
113         ----------
114         params : :obj:`dict` of :obj:`str`
115             Request params
116
117         Returns
118         -------
119         :obj:`str`
120             Exracted ESN
121         """
122         return self.netflix_session.esn
123
124     def fetch_video_list_ids (self, params):
125         """Video list ids proxy function (caches video lists)
126
127         Parameters
128         ----------
129         params : :obj:`dict` of :obj:`str`
130             Request params
131
132         Returns
133         -------
134         :obj:`list`
135             Transformed response of the remote call
136         """
137         cached_list = self.video_list_cache.get(self.netflix_session.user_data['guid'], None)
138         if cached_list != None:
139             self.kodi_helper.log('Serving cached list for user: ' + self.netflix_session.user_data['guid'])
140             return cached_list
141         video_list_ids_raw = self.netflix_session.fetch_video_list_ids()
142         if 'error' in video_list_ids_raw:
143             return video_list_ids_raw
144         return self.netflix_session.parse_video_list_ids(response_data=video_list_ids_raw)
145
146     def fetch_video_list (self, params):
147         """Video list proxy function
148
149         Parameters
150         ----------
151         params : :obj:`dict` of :obj:`str`
152             Request params
153
154         Returns
155         -------
156         :obj:`list`
157             Transformed response of the remote call
158         """
159         list_id = params.get('list_id', [''])[0]
160         raw_video_list = self.netflix_session.fetch_video_list(list_id=list_id)
161         if 'error' in raw_video_list:
162             return raw_video_list
163         # parse the video list ids
164         if 'videos' in raw_video_list.get('value', {}).keys():
165             return self.netflix_session.parse_video_list(response_data=raw_video_list)
166         return []
167
168     def fetch_episodes_by_season (self, params):
169         """Episodes for season proxy function
170
171         Parameters
172         ----------
173         params : :obj:`dict` of :obj:`str`
174             Request params
175
176         Returns
177         -------
178         :obj:`list`
179             Transformed response of the remote call
180         """
181         raw_episode_list = self.netflix_session.fetch_episodes_by_season(season_id=params.get('season_id')[0])
182         if 'error' in raw_episode_list:
183             return raw_episode_list
184         return self.netflix_session.parse_episodes_by_season(response_data=raw_episode_list)
185
186     def fetch_seasons_for_show (self, params):
187         """Season for show proxy function
188
189         Parameters
190         ----------
191         params : :obj:`dict` of :obj:`str`
192             Request params
193
194         Returns
195         -------
196         :obj:`list`
197             Transformed response of the remote call
198         """
199         show_id = params.get('show_id', [''])[0]
200         raw_season_list = self.netflix_session.fetch_seasons_for_show(id=show_id)
201         if 'error' in raw_season_list:
202             return raw_season_list
203         # check if we have sesons, announced shows that are not available yet have none
204         if 'seasons' not in raw_season_list.get('value', {}):
205               return []
206         return self.netflix_session.parse_seasons(id=show_id, response_data=raw_season_list)
207
208     def rate_video (self, params):
209         """Video rating proxy function
210
211         Parameters
212         ----------
213         params : :obj:`dict` of :obj:`str`
214             Request params
215
216         Returns
217         -------
218         :obj:`Requests.Response`
219             Response of the remote call
220         """
221         video_id = params.get('video_id', [''])[0]
222         rating = params.get('rating', [''])[0]
223         return self.netflix_session.rate_video(video_id=video_id, rating=rating)
224
225     def remove_from_list (self, params):
226         """Remove from my list proxy function
227
228         Parameters
229         ----------
230         params : :obj:`dict` of :obj:`str`
231             Request params
232
233         Returns
234         -------
235         :obj:`Requests.Response`
236             Response of the remote call
237         """
238         video_id = params.get('video_id', [''])[0]
239         return self.netflix_session.remove_from_list(video_id=video_id)
240
241     def add_to_list (self, params):
242         """Add to my list proxy function
243
244         Parameters
245         ----------
246         params : :obj:`dict` of :obj:`str`
247             Request params
248
249         Returns
250         -------
251         :obj:`Requests.Response`
252             Response of the remote call
253         """
254         video_id = params.get('video_id', [''])[0]
255         return self.netflix_session.add_to_list(video_id=video_id)
256
257     def fetch_metadata (self, params):
258         """Metadata proxy function
259
260         Parameters
261         ----------
262         params : :obj:`dict` of :obj:`str`
263             Request params
264
265         Returns
266         -------
267         :obj:`Requests.Response`
268             Response of the remote call
269         """
270         video_id = params.get('video_id', [''])[0]
271         return self.netflix_session.fetch_metadata(id=video_id)
272
273     def switch_profile (self, params):
274         """Switch profile proxy function
275
276         Parameters
277         ----------
278         params : :obj:`dict` of :obj:`str`
279             Request params
280
281         Returns
282         -------
283         :obj:`Requests.Response`
284             Response of the remote call
285         """
286         profile_id = params.get('profile_id', [''])[0]
287         return self.netflix_session.switch_profile(profile_id=profile_id, account=self.credentials)
288
289     def get_user_data (self, params):
290         """User data getter function
291
292         Parameters
293         ----------
294         params : :obj:`dict` of :obj:`str`
295             Request params
296
297         Returns
298         -------
299         :obj:`str`
300             Exracted User Data
301         """
302         return self.netflix_session.user_data
303
304     def search (self, params):
305         """Search proxy function
306
307         Parameters
308         ----------
309         params : :obj:`dict` of :obj:`str`
310             Request params
311
312         Returns
313         -------
314         :obj:`list`
315             Transformed response of the remote call
316         """
317         term = params.get('term', [''])[0]
318         has_search_results = False
319         raw_search_results = self.netflix_session.fetch_search_results(search_str=term)
320         # check for any errors
321         if 'error' in raw_search_results:
322             return raw_search_results
323
324         # determine if we found something
325         if 'search' in raw_search_results['value']:
326             for key in raw_search_results['value']['search'].keys():
327                 if self.netflix_session._is_size_key(key=key) == False:
328                     has_search_results = raw_search_results['value']['search'][key]['titles']['length'] > 0
329                     if has_search_results == False:
330                         if raw_search_results['value']['search'][key].get('suggestions', False) != False:
331                             for entry in raw_search_results['value']['search'][key]['suggestions']:
332                                 if self.netflix_session._is_size_key(key=entry) == False:
333                                     if raw_search_results['value']['search'][key]['suggestions'][entry]['relatedvideos']['length'] > 0:
334                                         has_search_results = True
335
336         # display that we haven't found a thing
337         if has_search_results == False:
338             return []
339
340         # list the search results
341         search_results = self.netflix_session.parse_search_results(response_data=raw_search_results)
342         # add more menaingful data to the search results
343         raw_search_contents = self.netflix_session.fetch_video_list_information(video_ids=search_results.keys())
344         # check for any errors
345         if 'error' in raw_search_contents:
346             return raw_search_contents
347         return self.netflix_session.parse_video_list(response_data=raw_search_contents)