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