2 # -*- coding: utf-8 -*-
4 # Created on: 13.01.2017
8 from urlparse import parse_qsl
13 """Routes to the correct subfolder, dispatches actions & acts as a controller for the Kodi view & the Netflix model"""
15 def __init__ (self, netflix_session, kodi_helper, library, base_url, log_fn=noop):
16 """Takes the instances & configuration options needed to drive the plugin
20 netflix_session : :obj:`NetflixSession`
21 instance of the NetflixSession class
23 kodi_helper : :obj:`KodiHelper`
24 instance of the KodiHelper class
26 library : :obj:`Library`
27 instance of the Library class
35 self.netflix_session = netflix_session
36 self.kodi_helper = kodi_helper
37 self.library = library
38 self.base_url = base_url
42 def router (self, paramstring):
43 """Route to the requested subfolder & dispatch actions along the way
47 paramstring : :obj:`str`
50 params = self.parse_paramters(paramstring=paramstring)
53 if 'action' in params.keys() and params['action'] == 'logout':
54 return self.netflix_session.logout()
56 # check login & try to relogin if necessary
57 account = self.kodi_helper.get_credentials()
58 if self.netflix_session.is_logged_in(account=account) != True:
59 if self.establish_session(account=account) != True:
60 return self.kodi_helper.show_login_failed_notification()
62 # check if we need to execute any actions before the actual routing
63 # gives back a dict of options routes might need
64 options = self.before_routing_action(params=params)
66 # check if one of the before routing options decided to killthe routing
69 if 'action' not in params.keys():
72 elif params['action'] == 'video_lists':
73 # list lists that contain other lists (starting point with recommendations, search, etc.)
74 return self.show_video_lists()
75 elif params['action'] == 'video_list':
76 # show a list of shows/movies
77 type = None if 'type' not in params.keys() else params['type']
78 return self.show_video_list(video_list_id=params['video_list_id'], type=type)
79 elif params['action'] == 'season_list':
80 # list of seasons for a show
81 return self.show_seasons(show_id=params['show_id'])
82 elif params['action'] == 'episode_list':
83 # list of episodes for a season
84 return self.show_episode_list(season_id=params['season_id'])
85 elif params['action'] == 'rating':
86 return self.rate_on_netflix(video_id=params['id'])
87 elif params['action'] == 'remove_from_list':
88 # removes a title from the users list on Netflix
89 return self.remove_from_list(video_id=params['id'])
90 elif params['action'] == 'add_to_list':
91 # adds a title to the users list on Netflix
92 return self.add_to_list(video_id=params['id'])
93 elif params['action'] == 'user-items' and params['type'] != 'search':
94 # display the lists (recommendations, genres, etc.)
95 return self.show_user_list(type=params['type'])
96 elif params['action'] == 'play_video':
97 # play a video, check for adult pin if needed
99 if self.check_for_adult_pin(params=params):
100 adult_pin = self.kodi_helper.show_adult_pin_dialog()
101 if self.netflix_session.send_adult_pin(adult_pin=adult_pin) != True:
102 return self.kodi_helper.show_wrong_adult_pin_notification()
103 self.play_video(video_id=params['video_id'], start_offset=params['start_offset'])
104 elif params['action'] == 'user-items' and params['type'] == 'search':
105 # if the user requested a search, ask for the term
106 term = self.kodi_helper.show_search_term_dialog()
107 return self.show_search_results(term=term)
109 raise ValueError('Invalid paramstring: {0}!'.format(paramstring))
113 def play_video (self, video_id, start_offset):
114 """Starts video playback
116 Note: This is just a dummy, inputstream is needed to play the vids
120 video_id : :obj:`str`
121 ID of the video that should be played
123 start_offset : :obj:`str`
124 Offset to resume playback from (in seconds)
127 esn = self.netflix_session.esn
128 return self.kodi_helper.play_item(esn=esn, video_id=video_id, start_offset=start_offset)
130 def show_search_results (self, term):
131 """Display a list of search results
141 If no results are available
143 has_search_results = False
144 search_results_raw = self.netflix_session.fetch_search_results(term=term)
145 # check for any errors
146 if self._is_dirty_response(response=search_results_raw):
149 # determine if we found something
150 if 'search' in search_results_raw['value']:
151 for key in search_results_raw['value']['search'].keys():
152 if self.netflix_session._is_size_key(key=key) == False:
153 has_search_results = search_results_raw['value']['search'][key]['titles']['length'] > 0
155 # display that we haven't found a thing
156 if has_search_results == False:
157 return self.kodi_helper.build_no_search_results_available(build_url=self.build_url, action='search')
159 # list the search results
160 search_results = self.netflix_session.parse_search_results(response_data=search_results_raw)
161 # add more menaingful data to the search results
162 raw_search_contents = self.netflix_session.fetch_video_list_information(video_ids=search_results.keys())
163 # check for any errors
164 if self._is_dirty_response(response=raw_search_contents):
166 search_contents = self.netflix_session.parse_video_list(response_data=raw_search_contents)
167 actions = {'movie': 'play_video', 'show': 'season_list'}
168 return self.kodi_helper.build_search_result_listing(video_list=search_contents, actions=actions, build_url=self.build_url)
170 def show_user_list (self, type):
171 """List the users lists for shows/movies for recommendations/genres based on the given type
175 user_list_id : :obj:`str`
176 Type of list to display
178 video_list_ids_raw = self.netflix_session.fetch_video_list_ids()
179 # check for any errors
180 if self._is_dirty_response(response=video_list_ids_raw):
182 video_list_ids = self.netflix_session.parse_video_list_ids(response_data=video_list_ids_raw)
183 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)
185 def show_episode_list (self, season_id):
186 """Lists all episodes for a given season
190 season_id : :obj:`str`
191 ID of the season episodes should be displayed for
193 raw_episode_list = self.netflix_session.fetch_episodes_by_season(season_id=season_id)
194 # check for any errors
195 if self._is_dirty_response(response=raw_episode_list):
197 # parse the raw Netflix data
198 episode_list = self.netflix_session.parse_episodes_by_season(response_data=raw_episode_list)
200 # sort seasons by number (they´re coming back unsorted from the api)
202 for episode_id in episode_list:
203 episodes_sorted.append(int(episode_list[episode_id]['episode']))
204 episodes_sorted.sort()
207 return self.kodi_helper.build_episode_listing(episodes_sorted=episodes_sorted, episode_list=episode_list, build_url=self.build_url)
209 def show_seasons (self, show_id):
210 """Lists all seasons for a given show
215 ID of the show seasons should be displayed for
220 If no seasons are available
222 season_list_raw = self.netflix_session.fetch_seasons_for_show(id=show_id);
223 # check for any errors
224 if self._is_dirty_response(response=season_list_raw):
226 # check if we have sesons, announced shows that are not available yet have none
227 if 'seasons' not in season_list_raw['value']:
228 return self.kodi_helper.build_no_seasons_available()
229 # parse the seasons raw response from Netflix
230 season_list = self.netflix_session.parse_seasons(id=show_id, response_data=season_list_raw)
231 # sort seasons by index by default (they´re coming back unsorted from the api)
233 for season_id in season_list:
234 seasons_sorted.append(int(season_list[season_id]['shortName'].split(' ')[1]))
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)
238 def show_video_list (self, video_list_id, type):
239 """List shows/movies based on the given video list id
243 video_list_id : :obj:`str`
244 ID of the video list that should be displayed
247 None or 'queue' f.e. when it´s a special video lists
249 raw_video_list = self.netflix_session.fetch_video_list(list_id=video_list_id)
250 # check for any errors
251 if self._is_dirty_response(response=raw_video_list):
253 # parse the video list ids
254 video_list = self.netflix_session.parse_video_list(response_data=raw_video_list)
255 actions = {'movie': 'play_video', 'show': 'season_list'}
256 return self.kodi_helper.build_video_listing(video_list=video_list, actions=actions, type=type, build_url=self.build_url)
258 def show_video_lists (self):
259 """List the users video lists (recommendations, my list, etc.)"""
261 raw_video_list_ids = self.netflix_session.fetch_video_list_ids()
262 # check for any errors
263 if self._is_dirty_response(response=raw_video_list_ids):
265 # parse the video list ids
266 video_list_ids = self.netflix_session.parse_video_list_ids(response_data=raw_video_list_ids)
267 # defines an order for the user list, as Netflix changes the order at every request
268 user_list_order = ['queue', 'continueWatching', 'topTen', 'netflixOriginals', 'trendingNow', 'newRelease', 'popularTitles']
269 # define where to route the user
270 actions = {'recommendations': 'user-items', 'genres': 'user-items', 'search': 'user-items', 'default': 'video_list'}
271 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)
273 def show_profiles (self):
274 """List the profiles for the active account"""
275 self.netflix_session.refresh_session_data(account=self.kodi_helper.get_credentials())
276 profiles = self.netflix_session.profiles
277 return self.kodi_helper.build_profiles_listing(profiles=profiles, action='video_lists', build_url=self.build_url)
280 def rate_on_netflix (self, video_id):
281 """Rate a show/movie/season/episode on Netflix
285 video_list_id : :obj:`str`
286 ID of the video list that should be displayed
288 rating = self.kodi_helper.show_rating_dialog()
289 return self.netflix_session.rate_video(video_id=video_id, rating=rating)
292 def remove_from_list (self, video_id):
293 """Remove an item from 'My List' & refresh the view
297 video_list_id : :obj:`str`
298 ID of the video list that should be displayed
300 self.netflix_session.remove_from_list(video_id=video_id)
301 return self.kodi_helper.refresh()
304 def add_to_list (self, video_id):
305 """Add an item to 'My List' & refresh the view
309 video_list_id : :obj:`str`
310 ID of the video list that should be displayed
312 self.netflix_session.add_to_list(video_id=video_id)
313 return self.kodi_helper.refresh()
316 def establish_session(self, account):
317 """Checks if we have an cookie with an active sessions, otherwise tries to login the user
321 account : :obj:`dict` of :obj:`str`
322 Dict containing an email & a password property
327 If we don't have an active session & the user couldn't be logged in
329 if self.netflix_session.is_logged_in(account=account):
332 return self.netflix_session.login(account=account)
335 def before_routing_action (self, params):
336 """Executes actions before the actual routing takes place:
338 - Check if account data has been stored, if not, asks for it
339 - Check if the profile should be changed (and changes if so)
340 - Establishes a session if no action route is given
344 params : :obj:`dict` of :obj:`str`
349 :obj:`dict` of :obj:`str`
350 Options that can be provided by this hook & used later in the routing process
353 credentials = self.kodi_helper.get_credentials()
354 # check if we have user settings, if not, set em
355 if credentials['email'] == '':
356 email = self.kodi_helper.show_email_dialog()
357 self.kodi_helper.set_setting(key='email', value=email)
358 if credentials['password'] == '':
359 password = self.kodi_helper.show_password_dialog()
360 self.kodi_helper.set_setting(key='password', value=password)
361 # persist & load main menu selection
363 self.kodi_helper.set_main_menu_selection(type=params['type'])
364 options['main_menu_selection'] = self.kodi_helper.get_main_menu_selection()
365 # check and switch the profile if needed
366 if self.check_for_designated_profile_change(params=params):
367 self.netflix_session.switch_profile(profile_id=params['profile_id'], account=credentials)
368 # check login, in case of main menu
369 if 'action' not in params:
370 self.establish_session(account=credentials)
373 def check_for_designated_profile_change (self, params):
374 """Checks if the profile needs to be switched
378 params : :obj:`dict` of :obj:`str`
384 Profile should be switched or not
386 # check if we need to switch the user
387 if 'guid' not in self.netflix_session.user_data:
389 current_profile_id = self.netflix_session.user_data['guid']
390 return 'profile_id' in params and current_profile_id != params['profile_id']
392 def check_for_adult_pin (self, params):
393 """Checks if an adult pin is given in the query params
397 params : :obj:`dict` of :obj:`str`
403 Adult pin parameter exists or not
405 return (True, False)[params['pin'] == 'True']
407 def parse_paramters (self, paramstring):
408 """Tiny helper to convert a url paramstring into a dictionary
412 paramstring : :obj:`str`
413 Url query params (in url string notation)
417 :obj:`dict` of :obj:`str`
418 Url query params (as a dictionary)
420 return dict(parse_qsl(paramstring))
422 def _is_expired_session (self, response):
423 """Checks if a response error is based on an invalid session
427 response : :obj:`dict` of :obj:`str`
428 Error response object
433 Error is based on an invalid session
435 return 'error' in response and 'code' in response and str(response['code']) == '401'
437 def _is_dirty_response (self, response):
438 """Checks if a response contains an error & if the error is based on an invalid session, it tries a relogin
442 response : :obj:`dict` of :obj:`str`
443 Success response object or Error response object
448 Response contains error or not
450 # check for any errors
451 if 'error' in response:
452 # check if we do not have a valid session, in case that happens: (re)login
453 if self._is_expired_session(response=response):
454 if self.establish_session(account=self.kodi_helper.get_credentials()):
456 self.log(msg='[ERROR]: ' + response['message'] + '::' + str(response['code']))
460 def build_url(self, query):
461 """Tiny helper to transform a dict into a url + querystring
465 query : :obj:`dict` of :obj:`str`
466 List of paramters to be url encoded
471 Url + querystring based on the param
473 return self.base_url + '?' + urllib.urlencode(query)