fix(kids-profiles): Reenables Kids profiles after NEtflix API changes
[plugin.video.netflix.git] / resources / lib / Navigation.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # Module: Navigation
4 # Created on: 13.01.2017
5
6 import urllib
7 import urllib2
8 import json
9 from xbmcaddon import Addon
10 from urlparse import parse_qsl
11 from utils import noop, log
12
13 class Navigation:
14     """Routes to the correct subfolder, dispatches actions & acts as a controller for the Kodi view & the Netflix model"""
15
16     def __init__ (self, kodi_helper, library, base_url, log_fn=noop):
17         """Takes the instances & configuration options needed to drive the plugin
18
19         Parameters
20         ----------
21         kodi_helper : :obj:`KodiHelper`
22             instance of the KodiHelper class
23
24         library : :obj:`Library`
25             instance of the Library class
26
27         base_url : :obj:`str`
28             plugin base url
29
30         log_fn : :obj:`fn`
31              optional log function
32         """
33         self.kodi_helper = kodi_helper
34         self.library = library
35         self.base_url = base_url
36         self.log = log_fn
37
38     @log
39     def router (self, paramstring):
40         """Route to the requested subfolder & dispatch actions along the way
41
42         Parameters
43         ----------
44         paramstring : :obj:`str`
45             Url query params
46         """
47         params = self.parse_paramters(paramstring=paramstring)
48
49         # open foreign settings dialog
50         if 'mode' in params.keys() and params['mode'] == 'openSettings':
51             return self.open_settings(params['url'])
52
53         # log out the user
54         if 'action' in params.keys() and params['action'] == 'logout':
55             return self.call_netflix_service({'method': 'logout'})
56
57         # check login & try to relogin if necessary
58         account = self.kodi_helper.get_credentials()
59         if account['email'] != '' and account['password'] != '':
60             if self.call_netflix_service({'method': 'is_logged_in'}) != True:
61                 if self.establish_session(account=account) != True:
62                     return self.kodi_helper.show_login_failed_notification()
63
64         # check if we need to execute any actions before the actual routing
65         # gives back a dict of options routes might need
66         options = self.before_routing_action(params=params)
67
68         # check if one of the before routing options decided to killthe routing
69         if 'exit' in options:
70             return False
71         if 'action' not in params.keys():
72             # show the profiles
73             return self.show_profiles()
74         elif params['action'] == 'video_lists':
75             # list lists that contain other lists (starting point with recommendations, search, etc.)
76             return self.show_video_lists()
77         elif params['action'] == 'video_list':
78             # show a list of shows/movies
79             type = None if 'type' not in params.keys() else params['type']
80             return self.show_video_list(video_list_id=params['video_list_id'], type=type)
81         elif params['action'] == 'season_list':
82             # list of seasons for a show
83             return self.show_seasons(show_id=params['show_id'])
84         elif params['action'] == 'episode_list':
85             # list of episodes for a season
86             return self.show_episode_list(season_id=params['season_id'])
87         elif params['action'] == 'rating':
88             return self.rate_on_netflix(video_id=params['id'])
89         elif params['action'] == 'remove_from_list':
90             # removes a title from the users list on Netflix
91             self.kodi_helper.invalidate_memcache()
92             return self.remove_from_list(video_id=params['id'])
93         elif params['action'] == 'add_to_list':
94             # adds a title to the users list on Netflix
95             self.kodi_helper.invalidate_memcache()
96             return self.add_to_list(video_id=params['id'])
97         elif params['action'] == 'export':
98             # adds a title to the users list on Netflix
99             alt_title = self.kodi_helper.show_add_to_library_title_dialog(original_title=urllib.unquote(params['title']).decode('utf8'))
100             return self.export_to_library(video_id=params['id'], alt_title=alt_title)
101         elif params['action'] == 'remove':
102             # adds a title to the users list on Netflix
103             return self.remove_from_library(video_id=params['id'])
104         elif params['action'] == 'user-items' and params['type'] != 'search':
105             # display the lists (recommendations, genres, etc.)
106             return self.show_user_list(type=params['type'])
107         elif params['action'] == 'play_video':
108             self.play_video(video_id=params['video_id'], start_offset=params.get('start_offset', -1))
109         elif params['action'] == 'user-items' and params['type'] == 'search':
110             # if the user requested a search, ask for the term
111             term = self.kodi_helper.show_search_term_dialog()
112             return self.show_search_results(term=term)
113         else:
114             raise ValueError('Invalid paramstring: {0}!'.format(paramstring))
115         return True
116
117     @log
118     def play_video (self, video_id, start_offset):
119         """Starts video playback
120
121         Note: This is just a dummy, inputstream is needed to play the vids
122
123         Parameters
124         ----------
125         video_id : :obj:`str`
126             ID of the video that should be played
127
128         start_offset : :obj:`str`
129             Offset to resume playback from (in seconds)
130         """
131         esn = self.call_netflix_service({'method': 'get_esn'})
132         return self.kodi_helper.play_item(esn=esn, video_id=video_id, start_offset=start_offset)
133
134     @log
135     def show_search_results (self, term):
136         """Display a list of search results
137
138         Parameters
139         ----------
140         term : :obj:`str`
141             String to lookup
142
143         Returns
144         -------
145         bool
146             If no results are available
147         """
148         search_contents = self.call_netflix_service({'method': 'search', 'term': term})
149         # check for any errors
150         if self._is_dirty_response(response=search_contents):
151             return False
152         actions = {'movie': 'play_video', 'show': 'season_list'}
153         return self.kodi_helper.build_search_result_listing(video_list=search_contents, actions=actions, build_url=self.build_url)
154
155     def show_user_list (self, type):
156         """List the users lists for shows/movies for recommendations/genres based on the given type
157
158         Parameters
159         ----------
160         user_list_id : :obj:`str`
161             Type of list to display
162         """
163         # determine if we´re in kids mode
164         user_data = self.call_netflix_service({'method': 'get_user_data'})
165         profiles = self.call_netflix_service({'method': 'list_profiles'})
166         is_kids = profiles.get(user_data['guid']).get('isKids', False)
167         # fetch video lists
168         if is_kids == True:
169             video_list_ids = self.call_netflix_service({'method': 'fetch_video_list_ids_for_kids'})
170         else:
171             video_list_ids = self.call_netflix_service({'method': 'fetch_video_list_ids', 'type': type})
172         # check for any errors
173         if self._is_dirty_response(response=video_list_ids):
174             return False
175         return self.kodi_helper.build_user_sub_listing(video_list_ids=video_list_ids[type], type=type, action='video_list', build_url=self.build_url)
176
177     def show_episode_list (self, season_id):
178         """Lists all episodes for a given season
179
180         Parameters
181         ----------
182         season_id : :obj:`str`
183             ID of the season episodes should be displayed for
184         """
185         cache_id = 'episodes_' + season_id
186         if self.kodi_helper.has_cached_item(cache_id=cache_id):
187             episode_list = self.kodi_helper.get_cached_item(cache_id=cache_id)
188         else:
189             episode_list = self.call_netflix_service({'method': 'fetch_episodes_by_season', 'season_id': season_id})
190             # check for any errors
191             if self._is_dirty_response(response=episode_list):
192                 return False
193             # parse the raw Netflix data
194             self.kodi_helper.add_cached_item(cache_id=cache_id, contents=episode_list)
195
196         # sort seasons by number (they´re coming back unsorted from the api)
197         episodes_sorted = []
198         for episode_id in episode_list:
199             episodes_sorted.append(int(episode_list[episode_id]['episode']))
200             episodes_sorted.sort()
201
202         # list the episodes
203         return self.kodi_helper.build_episode_listing(episodes_sorted=episodes_sorted, episode_list=episode_list, build_url=self.build_url)
204
205     def show_seasons (self, show_id):
206         """Lists all seasons for a given show
207
208         Parameters
209         ----------
210         show_id : :obj:`str`
211             ID of the show seasons should be displayed for
212
213         Returns
214         -------
215         bool
216             If no seasons are available
217         """
218         cache_id = 'season_' + show_id
219         if self.kodi_helper.has_cached_item(cache_id=cache_id):
220             season_list = self.kodi_helper.get_cached_item(cache_id=cache_id)
221         else:
222             season_list = self.call_netflix_service({'method': 'fetch_seasons_for_show', 'show_id': show_id})
223             # check for any errors
224             if self._is_dirty_response(response=season_list):
225                 return False
226             # check if we have sesons, announced shows that are not available yet have none
227             if len(season_list) == 0:
228                 return self.kodi_helper.build_no_seasons_available()
229             # parse the seasons raw response from Netflix
230             self.kodi_helper.add_cached_item(cache_id=cache_id, contents=season_list)
231         # sort seasons by index by default (they´re coming back unsorted from the api)
232         seasons_sorted = []
233         for season_id in season_list:
234             seasons_sorted.append(int(season_list[season_id]['idx']))
235             seasons_sorted.sort()
236         return self.kodi_helper.build_season_listing(seasons_sorted=seasons_sorted, season_list=season_list, build_url=self.build_url)
237
238     def show_video_list (self, video_list_id, type):
239         """List shows/movies based on the given video list id
240
241         Parameters
242         ----------
243         video_list_id : :obj:`str`
244             ID of the video list that should be displayed
245
246         type : :obj:`str`
247             None or 'queue' f.e. when it´s a special video lists
248         """
249         if self.kodi_helper.has_cached_item(cache_id=video_list_id):
250             video_list = self.kodi_helper.get_cached_item(cache_id=video_list_id)
251         else:
252             video_list = self.call_netflix_service({'method': 'fetch_video_list', 'list_id': video_list_id})
253             # check for any errors
254             if self._is_dirty_response(response=video_list):
255                 return False
256             # parse the video list ids
257             if len(video_list) > 0:
258                 self.kodi_helper.add_cached_item(cache_id=video_list_id, contents=video_list)
259         actions = {'movie': 'play_video', 'show': 'season_list'}
260         return self.kodi_helper.build_video_listing(video_list=video_list, actions=actions, type=type, build_url=self.build_url)
261
262     def show_video_lists (self):
263         """List the users video lists (recommendations, my list, etc.)"""
264         cache_id='main_menu'
265         if self.kodi_helper.has_cached_item(cache_id=cache_id):
266             video_list_ids = self.kodi_helper.get_cached_item(cache_id=cache_id)
267         else:
268             # determine if we´re in Kids profile mode
269             user_data = self.call_netflix_service({'method': 'get_user_data'})
270             profiles = self.call_netflix_service({'method': 'list_profiles'})
271             is_kids = profiles.get(user_data['guid']).get('isKids', False)
272             # fetch video lists
273             if is_kids == True:
274                 video_list_ids = self.call_netflix_service({'method': 'fetch_video_list_ids_for_kids'})
275             else:
276                 video_list_ids = self.call_netflix_service({'method': 'fetch_video_list_ids'})
277
278             # check for any errors
279             if self._is_dirty_response(response=video_list_ids):
280                 return False
281             # cache the video list ids
282             #self.kodi_helper.add_cached_item(cache_id=cache_id, contents=video_list_ids)
283         # defines an order for the user list, as Netflix changes the order at every request
284         user_list_order = ['queue', 'continueWatching', 'topTen', 'netflixOriginals', 'trendingNow', 'newRelease', 'popularTitles']
285         # define where to route the user
286         actions = {'recommendations': 'user-items', 'genres': 'user-items', 'search': 'user-items', 'default': 'video_list'}
287         return self.kodi_helper.build_main_menu_listing(video_list_ids=video_list_ids, user_list_order=user_list_order, actions=actions, build_url=self.build_url)
288
289     @log
290     def show_profiles (self):
291         """List the profiles for the active account"""
292         profiles = self.call_netflix_service({'method': 'list_profiles'})
293         if len(profiles) == 0:
294             return self.kodi_helper.show_login_failed_notification()
295         return self.kodi_helper.build_profiles_listing(profiles=profiles, action='video_lists', build_url=self.build_url)
296
297     @log
298     def rate_on_netflix (self, video_id):
299         """Rate a show/movie/season/episode on Netflix
300
301         Parameters
302         ----------
303         video_list_id : :obj:`str`
304             ID of the video list that should be displayed
305         """
306         rating = self.kodi_helper.show_rating_dialog()
307         return self.call_netflix_service({'method': 'rate_video', 'video_id': video_id, 'rating': rating})
308
309     @log
310     def remove_from_list (self, video_id):
311         """Remove an item from 'My List' & refresh the view
312
313         Parameters
314         ----------
315         video_list_id : :obj:`str`
316             ID of the video list that should be displayed
317         """
318         self.call_netflix_service({'method': 'remove_from_list', 'video_id': video_id})
319         return self.kodi_helper.refresh()
320
321     @log
322     def add_to_list (self, video_id):
323         """Add an item to 'My List' & refresh the view
324
325         Parameters
326         ----------
327         video_list_id : :obj:`str`
328             ID of the video list that should be displayed
329         """
330         self.call_netflix_service({'method': 'add_to_list', 'video_id': video_id})
331         return self.kodi_helper.refresh()
332
333     @log
334     def export_to_library (self, video_id, alt_title):
335         """Adds an item to the local library
336
337         Parameters
338         ----------
339         video_id : :obj:`str`
340             ID of the movie or show
341
342         alt_title : :obj:`str`
343             Alternative title (for the folder written to disc)
344         """
345         metadata = self.call_netflix_service({'method': 'fetch_metadata', 'video_id': video_id})
346         # check for any errors
347         if self._is_dirty_response(response=metadata):
348             return False
349         video = metadata['video']
350
351         if video['type'] == 'movie':
352             self.library.add_movie(title=video['title'], alt_title=alt_title, year=video['year'], video_id=video_id, build_url=self.build_url)
353         if video['type'] == 'show':
354             episodes = []
355             for season in video['seasons']:
356                 for episode in season['episodes']:
357                     episodes.append({'season': season['seq'], 'episode': episode['seq'], 'id': episode['id']})
358
359             self.library.add_show(title=video['title'], alt_title=alt_title, episodes=episodes, build_url=self.build_url)
360         return self.kodi_helper.refresh()
361
362     @log
363     def remove_from_library (self, video_id, season=None, episode=None):
364         """Removes an item from the local library
365
366         Parameters
367         ----------
368         video_id : :obj:`str`
369             ID of the movie or show
370         """
371         metadata = self.call_netflix_service({'method': 'fetch_metadata', 'video_id': video_id})
372         # check for any errors
373         if self._is_dirty_response(response=metadata):
374             return False
375         video = metadata['video']
376
377         if video['type'] == 'movie':
378             self.library.remove_movie(title=video['title'], year=video['year'])
379         if video['type'] == 'show':
380             self.library.remove_show(title=video['title'])
381         return self.kodi_helper.refresh()
382
383     @log
384     def establish_session(self, account):
385         """Checks if we have an cookie with an active sessions, otherwise tries to login the user
386
387         Parameters
388         ----------
389         account : :obj:`dict` of :obj:`str`
390             Dict containing an email & a password property
391
392         Returns
393         -------
394         bool
395             If we don't have an active session & the user couldn't be logged in
396         """
397         is_logged_in = self.call_netflix_service({'method': 'is_logged_in'})
398         return True if is_logged_in else self.call_netflix_service({'method': 'login', 'email': account['email'], 'password': account['password']})
399
400     @log
401     def before_routing_action (self, params):
402         """Executes actions before the actual routing takes place:
403
404             - Check if account data has been stored, if not, asks for it
405             - Check if the profile should be changed (and changes if so)
406             - Establishes a session if no action route is given
407
408         Parameters
409         ----------
410         params : :obj:`dict` of :obj:`str`
411             Url query params
412
413         Returns
414         -------
415         :obj:`dict` of :obj:`str`
416             Options that can be provided by this hook & used later in the routing process
417         """
418         options = {}
419         credentials = self.kodi_helper.get_credentials()
420         # check if we have user settings, if not, set em
421         if credentials['email'] == '':
422             email = self.kodi_helper.show_email_dialog()
423             self.kodi_helper.set_setting(key='email', value=email)
424             credentials['email'] = email
425         if credentials['password'] == '':
426             password = self.kodi_helper.show_password_dialog()
427             self.kodi_helper.set_setting(key='password', value=password)
428             credentials['password'] = password
429         # persist & load main menu selection
430         if 'type' in params:
431             self.kodi_helper.set_main_menu_selection(type=params['type'])
432         options['main_menu_selection'] = self.kodi_helper.get_main_menu_selection()
433         # check and switch the profile if needed
434         if self.check_for_designated_profile_change(params=params):
435             self.kodi_helper.invalidate_memcache()
436             self.call_netflix_service({'method': 'switch_profile', 'profile_id': params['profile_id']})
437         # check login, in case of main menu
438         if 'action' not in params:
439             self.establish_session(account=credentials)
440         return options
441
442     def check_for_designated_profile_change (self, params):
443         """Checks if the profile needs to be switched
444
445         Parameters
446         ----------
447         params : :obj:`dict` of :obj:`str`
448             Url query params
449
450         Returns
451         -------
452         bool
453             Profile should be switched or not
454         """
455         # check if we need to switch the user
456         user_data = self.call_netflix_service({'method': 'get_user_data'})
457         if 'guid' not in user_data:
458             return False
459         current_profile_id = user_data['guid']
460         return 'profile_id' in params and current_profile_id != params['profile_id']
461
462     def parse_paramters (self, paramstring):
463         """Tiny helper to convert a url paramstring into a dictionary
464
465         Parameters
466         ----------
467         paramstring : :obj:`str`
468             Url query params (in url string notation)
469
470         Returns
471         -------
472         :obj:`dict` of :obj:`str`
473             Url query params (as a dictionary)
474         """
475         return dict(parse_qsl(paramstring))
476
477     def _is_expired_session (self, response):
478         """Checks if a response error is based on an invalid session
479
480         Parameters
481         ----------
482         response : :obj:`dict` of :obj:`str`
483             Error response object
484
485         Returns
486         -------
487         bool
488             Error is based on an invalid session
489         """
490         return 'error' in response and 'code' in response and str(response['code']) == '401'
491
492     def _is_dirty_response (self, response):
493         """Checks if a response contains an error & if the error is based on an invalid session, it tries a relogin
494
495         Parameters
496         ----------
497         response : :obj:`dict` of :obj:`str`
498             Success response object or Error response object
499
500         Returns
501         -------
502         bool
503             Response contains error or not
504         """
505         # check for any errors
506         if 'error' in response:
507             # check if we do not have a valid session, in case that happens: (re)login
508             if self._is_expired_session(response=response):
509                 if self.establish_session(account=self.kodi_helper.get_credentials()):
510                     return True
511             message = response['message'] if 'message' in response else ''
512             code = response['code'] if 'code' in response else ''
513             self.log(msg='[ERROR]: ' + message + '::' + str(code))
514             return True
515         return False
516
517     def build_url(self, query):
518         """Tiny helper to transform a dict into a url + querystring
519
520         Parameters
521         ----------
522         query : :obj:`dict` of  :obj:`str`
523             List of paramters to be url encoded
524
525         Returns
526         -------
527         str
528             Url + querystring based on the param
529         """
530         return self.base_url + '?' + urllib.urlencode(query)
531
532     def get_netflix_service_url (self):
533         """Returns URL & Port of the internal Netflix HTTP Proxy service
534
535         Returns
536         -------
537         str
538             Url + Port
539         """
540         return 'http://localhost:' + str(self.kodi_helper.addon.getSetting('netflix_service_port'))
541
542     def call_netflix_service (self, params):
543         """Makes a GET request to the internal Netflix HTTP proxy and returns the result
544
545         Parameters
546         ----------
547         params : :obj:`dict` of  :obj:`str`
548             List of paramters to be url encoded
549
550         Returns
551         -------
552         :obj:`dict`
553             Netflix Service RPC result
554         """
555         url_values = urllib.urlencode(params)
556         url = self.get_netflix_service_url()
557         full_url = url + '?' + url_values
558         data = urllib2.urlopen(full_url).read()
559         parsed_json = json.loads(data)
560         return parsed_json.get('result', None)
561
562     def open_settings(self, url):
563         """Opens a foreign settings dialog"""
564         is_addon = self.kodi_helper.get_inputstream_addon()
565         url = is_addon if url == 'is' else url
566         return Addon(url).openSettings()