2 # -*- coding: utf-8 -*-
4 # Created on: 13.01.2017
10 from xbmcaddon import Addon
11 from urlparse import parse_qsl
12 from utils import noop, log
15 """Routes to the correct subfolder, dispatches actions & acts as a controller for the Kodi view & the Netflix model"""
17 def __init__ (self, kodi_helper, library, base_url, log_fn=noop):
18 """Takes the instances & configuration options needed to drive the plugin
22 kodi_helper : :obj:`KodiHelper`
23 instance of the KodiHelper class
25 library : :obj:`Library`
26 instance of the Library class
34 self.kodi_helper = kodi_helper
35 self.library = library
36 self.base_url = base_url
40 def router (self, paramstring):
41 """Route to the requested subfolder & dispatch actions along the way
45 paramstring : :obj:`str`
48 params = self.parse_paramters(paramstring=paramstring)
50 # open foreign settings dialog
51 if 'mode' in params.keys() and params['mode'] == 'openSettings':
52 return self.open_settings(params['url'])
55 if 'action' in params.keys() and params['action'] == 'logout':
56 return self.call_netflix_service({'method': 'logout'})
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()
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)
69 # check if one of the before routing options decided to killthe routing
72 if 'action' not in params.keys():
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.get('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)
115 raise ValueError('Invalid paramstring: {0}!'.format(paramstring))
119 def play_video (self, video_id, start_offset, infoLabels):
120 """Starts video playback
122 Note: This is just a dummy, inputstream is needed to play the vids
126 video_id : :obj:`str`
127 ID of the video that should be played
129 start_offset : :obj:`str`
130 Offset to resume playback from (in seconds)
132 infoLabels : :obj:`str`
133 the listitem's infoLabels
136 infoLabels = ast.literal_eval(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)
143 def show_search_results (self, term):
144 """Display a list of search results
154 If no results are available
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):
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)
164 def show_user_list (self, type):
165 """List the users lists for shows/movies for recommendations/genres based on the given type
169 user_list_id : :obj:`str`
170 Type of list to display
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):
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)
180 def show_episode_list (self, season_id, tvshowtitle):
181 """Lists all episodes for a given season
185 season_id : :obj:`str`
186 ID of the season episodes should be displayed for
188 tvshowtitle : :obj:`str`
189 title of the show (for listitems' infolabels)
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):
197 # Extract episode numbers and associated keys.
198 d = [(v['episode'], k) for k, v in episode_list.items()]
200 # sort episodes by number (they´re coming back unsorted from the api)
201 episodes_sorted = [episode_list[k] for (_, k) in sorted(d)]
203 for episode in episodes_sorted:
204 episode['tvshowtitle'] = tvshowtitle
207 return self.kodi_helper.build_episode_listing(episodes_sorted=episodes_sorted, build_url=self.build_url)
209 def show_seasons (self, show_id, tvshowtitle):
210 """Lists all seasons for a given show
215 ID of the show seasons should be displayed for
217 tvshowtitle : :obj:`str`
218 title of the show (for listitems' infolabels)
222 If no seasons are available
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):
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()
233 # Extract episode numbers and associated keys.
234 d = [(v['idx'], k) for k, v in season_list.items()]
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)]
239 for season in seasons_sorted:
240 season['tvshowtitle'] = tvshowtitle
242 return self.kodi_helper.build_season_listing(seasons_sorted=seasons_sorted, build_url=self.build_url)
244 def show_video_list (self, video_list_id, type):
245 """List shows/movies based on the given video list id
249 video_list_id : :obj:`str`
250 ID of the video list that should be displayed
253 None or 'queue' f.e. when it´s a special video lists
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):
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)
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):
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)
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)
285 def rate_on_netflix (self, video_id):
286 """Rate a show/movie/season/episode on Netflix
290 video_list_id : :obj:`str`
291 ID of the video list that should be displayed
293 rating = self.kodi_helper.show_rating_dialog()
294 return self.call_netflix_service({'method': 'rate_video', 'video_id': video_id, 'rating': rating})
297 def remove_from_list (self, video_id):
298 """Remove an item from 'My List' & refresh the view
302 video_list_id : :obj:`str`
303 ID of the video list that should be displayed
305 self.call_netflix_service({'method': 'remove_from_list', 'video_id': video_id})
306 return self.kodi_helper.refresh()
309 def add_to_list (self, video_id):
310 """Add an item to 'My List' & refresh the view
314 video_list_id : :obj:`str`
315 ID of the video list that should be displayed
317 self.call_netflix_service({'method': 'add_to_list', 'video_id': video_id})
318 return self.kodi_helper.refresh()
321 def export_to_library (self, video_id, alt_title):
322 """Adds an item to the local library
326 video_id : :obj:`str`
327 ID of the movie or show
329 alt_title : :obj:`str`
330 Alternative title (for the folder written to disc)
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):
336 video = metadata['video']
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':
342 for season in video['seasons']:
343 for episode in season['episodes']:
344 episodes.append({'season': season['seq'], 'episode': episode['seq'], 'id': episode['id']})
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()
350 def remove_from_library (self, video_id, season=None, episode=None):
351 """Removes an item from the local library
355 video_id : :obj:`str`
356 ID of the movie or show
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):
362 video = metadata['video']
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()
371 def establish_session(self, account):
372 """Checks if we have an cookie with an active sessions, otherwise tries to login the user
376 account : :obj:`dict` of :obj:`str`
377 Dict containing an email & a password property
382 If we don't have an active session & the user couldn't be logged in
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']})
388 def before_routing_action (self, params):
389 """Executes actions before the actual routing takes place:
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
397 params : :obj:`dict` of :obj:`str`
402 :obj:`dict` of :obj:`str`
403 Options that can be provided by this hook & used later in the routing process
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
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)
433 def check_for_designated_profile_change (self, params):
434 """Checks if the profile needs to be switched
438 params : :obj:`dict` of :obj:`str`
444 Profile should be switched or not
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:
451 current_profile_id = user_data['guid']
452 if profiles.get(current_profile_id).get('isKids', False) == True:
454 return 'profile_id' in params and current_profile_id != params['profile_id']
456 def parse_paramters (self, paramstring):
457 """Tiny helper to convert a url paramstring into a dictionary
461 paramstring : :obj:`str`
462 Url query params (in url string notation)
466 :obj:`dict` of :obj:`str`
467 Url query params (as a dictionary)
469 return dict(parse_qsl(paramstring))
471 def _is_expired_session (self, response):
472 """Checks if a response error is based on an invalid session
476 response : :obj:`dict` of :obj:`str`
477 Error response object
482 Error is based on an invalid session
484 return 'error' in response and 'code' in response and str(response['code']) == '401'
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
491 response : :obj:`dict` of :obj:`str`
492 Success response object or Error response object
497 Response contains error or not
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()):
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))
511 def build_url(self, query):
512 """Tiny helper to transform a dict into a url + querystring
516 query : :obj:`dict` of :obj:`str`
517 List of paramters to be url encoded
522 Url + querystring based on the param
524 return self.base_url + '?' + urllib.urlencode(query)
526 def get_netflix_service_url (self):
527 """Returns URL & Port of the internal Netflix HTTP Proxy service
534 return 'http://127.0.0.1:' + str(self.kodi_helper.get_addon().getSetting('netflix_service_port'))
536 def call_netflix_service (self, params):
537 """Makes a GET request to the internal Netflix HTTP proxy and returns the result
541 params : :obj:`dict` of :obj:`str`
542 List of paramters to be url encoded
547 Netflix Service RPC result
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)
554 # Cache lookup successful?
555 if cached_value != None:
556 self.log(msg='Fetched item from cache: (cache_id=' + url_values + ')')
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)
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()