add 'tvshowtitle' to listitem's infoLabels
[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'], tvshowtitle=params['tvshowtitle'])
84         elif params['action'] == 'episode_list':
85             # list of episodes for a season
86             return self.show_episode_list(season_id=params['season_id'], tvshowtitle=params['tvshowtitle'])
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         user_data = self.call_netflix_service({'method': 'get_user_data'})
149         search_contents = self.call_netflix_service({'method': 'search', 'term': term, 'guid': user_data['guid'], 'cache': True})
150         # check for any errors
151         if self._is_dirty_response(response=search_contents):
152             return False
153         actions = {'movie': 'play_video', 'show': 'season_list'}
154         return self.kodi_helper.build_search_result_listing(video_list=search_contents, actions=actions, build_url=self.build_url)
155
156     def show_user_list (self, type):
157         """List the users lists for shows/movies for recommendations/genres based on the given type
158
159         Parameters
160         ----------
161         user_list_id : :obj:`str`
162             Type of list to display
163         """
164         # determine if we´re in kids mode
165         user_data = self.call_netflix_service({'method': 'get_user_data'})
166         video_list_ids = self.call_netflix_service({'method': 'fetch_video_list_ids', 'guid': user_data['guid'], 'cache': True})
167         # check for any errors
168         if self._is_dirty_response(response=video_list_ids):
169             return False
170         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)
171
172     def show_episode_list (self, season_id, tvshowtitle):
173         """Lists all episodes for a given season
174
175         Parameters
176         ----------
177         season_id : :obj:`str`
178             ID of the season episodes should be displayed for
179         """
180         user_data = self.call_netflix_service({'method': 'get_user_data'})
181         episode_list = self.call_netflix_service({'method': 'fetch_episodes_by_season', 'season_id': season_id, 'guid': user_data['guid'], 'cache': True})
182         # check for any errors
183         if self._is_dirty_response(response=episode_list):
184             return False
185         # sort seasons by number (they´re coming back unsorted from the api)
186         episodes_sorted = []
187         for episode_id in episode_list:
188             episode_list[episode_id]['tvshowtitle'] = tvshowtitle
189             episodes_sorted.append(int(episode_list[episode_id]['episode']))
190             episodes_sorted.sort()
191
192         # list the episodes
193         return self.kodi_helper.build_episode_listing(episodes_sorted=episodes_sorted, episode_list=episode_list, build_url=self.build_url)
194
195     def show_seasons (self, show_id, tvshowtitle):
196         """Lists all seasons for a given show
197
198         Parameters
199         ----------
200         show_id : :obj:`str`
201             ID of the show seasons should be displayed for
202
203         Returns
204         -------
205         bool
206             If no seasons are available
207         """
208         user_data = self.call_netflix_service({'method': 'get_user_data'})
209         season_list = self.call_netflix_service({'method': 'fetch_seasons_for_show', 'show_id': show_id, 'guid': user_data['guid'], 'cache': True})
210         # check for any errors
211         if self._is_dirty_response(response=season_list):
212             return False
213         # check if we have sesons, announced shows that are not available yet have none
214         if len(season_list) == 0:
215             return self.kodi_helper.build_no_seasons_available()
216         # sort seasons by index by default (they´re coming back unsorted from the api)
217         seasons_sorted = []
218         for season_id in season_list:
219             season_list[season_id]['tvshowtitle'] = tvshowtitle
220             seasons_sorted.append(int(season_list[season_id]['idx']))
221             seasons_sorted.sort()
222         return self.kodi_helper.build_season_listing(seasons_sorted=seasons_sorted, season_list=season_list, build_url=self.build_url)
223
224     def show_video_list (self, video_list_id, type):
225         """List shows/movies based on the given video list id
226
227         Parameters
228         ----------
229         video_list_id : :obj:`str`
230             ID of the video list that should be displayed
231
232         type : :obj:`str`
233             None or 'queue' f.e. when it´s a special video lists
234         """
235         user_data = self.call_netflix_service({'method': 'get_user_data'})
236         video_list = self.call_netflix_service({'method': 'fetch_video_list', 'list_id': video_list_id, 'guid': user_data['guid'] ,'cache': True})
237         # check for any errors
238         if self._is_dirty_response(response=video_list):
239             return False
240         actions = {'movie': 'play_video', 'show': 'season_list'}
241         return self.kodi_helper.build_video_listing(video_list=video_list, actions=actions, type=type, build_url=self.build_url)
242
243     def show_video_lists (self):
244         """List the users video lists (recommendations, my list, etc.)"""
245         user_data = self.call_netflix_service({'method': 'get_user_data'})
246         video_list_ids = self.call_netflix_service({'method': 'fetch_video_list_ids', 'guid': user_data['guid'], 'cache': True})
247         # check for any errors
248         if self._is_dirty_response(response=video_list_ids):
249             return False
250         # defines an order for the user list, as Netflix changes the order at every request
251         user_list_order = ['queue', 'continueWatching', 'topTen', 'netflixOriginals', 'trendingNow', 'newRelease', 'popularTitles']
252         # define where to route the user
253         actions = {'recommendations': 'user-items', 'genres': 'user-items', 'search': 'user-items', 'default': 'video_list'}
254         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)
255
256     @log
257     def show_profiles (self):
258         """List the profiles for the active account"""
259         profiles = self.call_netflix_service({'method': 'list_profiles'})
260         if len(profiles) == 0:
261             return self.kodi_helper.show_login_failed_notification()
262         return self.kodi_helper.build_profiles_listing(profiles=profiles, action='video_lists', build_url=self.build_url)
263
264     @log
265     def rate_on_netflix (self, video_id):
266         """Rate a show/movie/season/episode on Netflix
267
268         Parameters
269         ----------
270         video_list_id : :obj:`str`
271             ID of the video list that should be displayed
272         """
273         rating = self.kodi_helper.show_rating_dialog()
274         return self.call_netflix_service({'method': 'rate_video', 'video_id': video_id, 'rating': rating})
275
276     @log
277     def remove_from_list (self, video_id):
278         """Remove an item from 'My List' & refresh the view
279
280         Parameters
281         ----------
282         video_list_id : :obj:`str`
283             ID of the video list that should be displayed
284         """
285         self.call_netflix_service({'method': 'remove_from_list', 'video_id': video_id})
286         return self.kodi_helper.refresh()
287
288     @log
289     def add_to_list (self, video_id):
290         """Add an item to 'My List' & refresh the view
291
292         Parameters
293         ----------
294         video_list_id : :obj:`str`
295             ID of the video list that should be displayed
296         """
297         self.call_netflix_service({'method': 'add_to_list', 'video_id': video_id})
298         return self.kodi_helper.refresh()
299
300     @log
301     def export_to_library (self, video_id, alt_title):
302         """Adds an item to the local library
303
304         Parameters
305         ----------
306         video_id : :obj:`str`
307             ID of the movie or show
308
309         alt_title : :obj:`str`
310             Alternative title (for the folder written to disc)
311         """
312         metadata = self.call_netflix_service({'method': 'fetch_metadata', 'video_id': video_id})
313         # check for any errors
314         if self._is_dirty_response(response=metadata):
315             return False
316         video = metadata['video']
317
318         if video['type'] == 'movie':
319             self.library.add_movie(title=video['title'], alt_title=alt_title, year=video['year'], video_id=video_id, build_url=self.build_url)
320         if video['type'] == 'show':
321             episodes = []
322             for season in video['seasons']:
323                 for episode in season['episodes']:
324                     episodes.append({'season': season['seq'], 'episode': episode['seq'], 'id': episode['id']})
325
326             self.library.add_show(title=video['title'], alt_title=alt_title, episodes=episodes, build_url=self.build_url)
327         return self.kodi_helper.refresh()
328
329     @log
330     def remove_from_library (self, video_id, season=None, episode=None):
331         """Removes an item from the local library
332
333         Parameters
334         ----------
335         video_id : :obj:`str`
336             ID of the movie or show
337         """
338         metadata = self.call_netflix_service({'method': 'fetch_metadata', 'video_id': video_id})
339         # check for any errors
340         if self._is_dirty_response(response=metadata):
341             return False
342         video = metadata['video']
343
344         if video['type'] == 'movie':
345             self.library.remove_movie(title=video['title'], year=video['year'])
346         if video['type'] == 'show':
347             self.library.remove_show(title=video['title'])
348         return self.kodi_helper.refresh()
349
350     @log
351     def establish_session(self, account):
352         """Checks if we have an cookie with an active sessions, otherwise tries to login the user
353
354         Parameters
355         ----------
356         account : :obj:`dict` of :obj:`str`
357             Dict containing an email & a password property
358
359         Returns
360         -------
361         bool
362             If we don't have an active session & the user couldn't be logged in
363         """
364         is_logged_in = self.call_netflix_service({'method': 'is_logged_in'})
365         return True if is_logged_in else self.call_netflix_service({'method': 'login', 'email': account['email'], 'password': account['password']})
366
367     @log
368     def before_routing_action (self, params):
369         """Executes actions before the actual routing takes place:
370
371             - Check if account data has been stored, if not, asks for it
372             - Check if the profile should be changed (and changes if so)
373             - Establishes a session if no action route is given
374
375         Parameters
376         ----------
377         params : :obj:`dict` of :obj:`str`
378             Url query params
379
380         Returns
381         -------
382         :obj:`dict` of :obj:`str`
383             Options that can be provided by this hook & used later in the routing process
384         """
385         options = {}
386         credentials = self.kodi_helper.get_credentials()
387         # check if we have user settings, if not, set em
388         if credentials['email'] == '':
389             email = self.kodi_helper.show_email_dialog()
390             self.kodi_helper.set_setting(key='email', value=email)
391             credentials['email'] = email
392         if credentials['password'] == '':
393             password = self.kodi_helper.show_password_dialog()
394             self.kodi_helper.set_setting(key='password', value=password)
395             credentials['password'] = password
396         # persist & load main menu selection
397         if 'type' in params:
398             self.kodi_helper.set_main_menu_selection(type=params['type'])
399         options['main_menu_selection'] = self.kodi_helper.get_main_menu_selection()
400         # check and switch the profile if needed
401         if self.check_for_designated_profile_change(params=params):
402             self.kodi_helper.invalidate_memcache()
403             profile_id = params.get('profile_id', None)
404             if profile_id == None:
405                 user_data = self.call_netflix_service({'method': 'get_user_data'})
406                 profile_id = user_data['guid']
407             self.call_netflix_service({'method': 'switch_profile', 'profile_id': profile_id})
408         # check login, in case of main menu
409         if 'action' not in params:
410             self.establish_session(account=credentials)
411         return options
412
413     def check_for_designated_profile_change (self, params):
414         """Checks if the profile needs to be switched
415
416         Parameters
417         ----------
418         params : :obj:`dict` of :obj:`str`
419             Url query params
420
421         Returns
422         -------
423         bool
424             Profile should be switched or not
425         """
426         # check if we need to switch the user
427         user_data = self.call_netflix_service({'method': 'get_user_data'})
428         profiles = self.call_netflix_service({'method': 'list_profiles'})
429         if 'guid' not in user_data:
430             return False
431         current_profile_id = user_data['guid']
432         if profiles.get(current_profile_id).get('isKids', False) == True:
433             return True
434         return 'profile_id' in params and current_profile_id != params['profile_id']
435
436     def parse_paramters (self, paramstring):
437         """Tiny helper to convert a url paramstring into a dictionary
438
439         Parameters
440         ----------
441         paramstring : :obj:`str`
442             Url query params (in url string notation)
443
444         Returns
445         -------
446         :obj:`dict` of :obj:`str`
447             Url query params (as a dictionary)
448         """
449         return dict(parse_qsl(paramstring))
450
451     def _is_expired_session (self, response):
452         """Checks if a response error is based on an invalid session
453
454         Parameters
455         ----------
456         response : :obj:`dict` of :obj:`str`
457             Error response object
458
459         Returns
460         -------
461         bool
462             Error is based on an invalid session
463         """
464         return 'error' in response and 'code' in response and str(response['code']) == '401'
465
466     def _is_dirty_response (self, response):
467         """Checks if a response contains an error & if the error is based on an invalid session, it tries a relogin
468
469         Parameters
470         ----------
471         response : :obj:`dict` of :obj:`str`
472             Success response object or Error response object
473
474         Returns
475         -------
476         bool
477             Response contains error or not
478         """
479         # check for any errors
480         if 'error' in response:
481             # check if we do not have a valid session, in case that happens: (re)login
482             if self._is_expired_session(response=response):
483                 if self.establish_session(account=self.kodi_helper.get_credentials()):
484                     return True
485             message = response['message'] if 'message' in response else ''
486             code = response['code'] if 'code' in response else ''
487             self.log(msg='[ERROR]: ' + message + '::' + str(code))
488             return True
489         return False
490
491     def build_url(self, query):
492         """Tiny helper to transform a dict into a url + querystring
493
494         Parameters
495         ----------
496         query : :obj:`dict` of  :obj:`str`
497             List of paramters to be url encoded
498
499         Returns
500         -------
501         str
502             Url + querystring based on the param
503         """
504         return self.base_url + '?' + urllib.urlencode(query)
505
506     def get_netflix_service_url (self):
507         """Returns URL & Port of the internal Netflix HTTP Proxy service
508
509         Returns
510         -------
511         str
512             Url + Port
513         """
514         return 'http://127.0.0.1:' + str(self.kodi_helper.get_addon().getSetting('netflix_service_port'))
515
516     def call_netflix_service (self, params):
517         """Makes a GET request to the internal Netflix HTTP proxy and returns the result
518
519         Parameters
520         ----------
521         params : :obj:`dict` of  :obj:`str`
522             List of paramters to be url encoded
523
524         Returns
525         -------
526         :obj:`dict`
527             Netflix Service RPC result
528         """
529         url_values = urllib.urlencode(params)
530         # check for cached items
531         if self.kodi_helper.has_cached_item(cache_id=url_values) and params.get('cache', False) == True:
532             self.log(msg='Fetching item from cache: (cache_id=' + url_values + ')')
533             return self.kodi_helper.get_cached_item(cache_id=url_values)
534         url = self.get_netflix_service_url()
535         full_url = url + '?' + url_values
536         data = urllib2.urlopen(full_url).read()
537         parsed_json = json.loads(data)
538         result = parsed_json.get('result', None)
539         if params.get('cache', False) == True:
540             self.log(msg='Adding item to cache: (cache_id=' + url_values + ')')
541             self.kodi_helper.add_cached_item(cache_id=url_values, contents=result)
542         return result
543
544     def open_settings(self, url):
545         """Opens a foreign settings dialog"""
546         is_addon = self.kodi_helper.get_inputstream_addon()
547         url = is_addon if url == 'is' else url
548         return Addon(url).openSettings()