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 account['email'] != '' and account['password'] != '':
59 if self.netflix_session.is_logged_in(account=account) != True:
60 if self.establish_session(account=account) != True:
61 return self.kodi_helper.show_login_failed_notification()
63 # check if we need to execute any actions before the actual routing
64 # gives back a dict of options routes might need
65 options = self.before_routing_action(params=params)
67 # check if one of the before routing options decided to killthe routing
70 if 'action' not in params.keys():
73 elif params['action'] == 'video_lists':
74 # list lists that contain other lists (starting point with recommendations, search, etc.)
75 return self.show_video_lists()
76 elif params['action'] == 'video_list':
77 # show a list of shows/movies
78 type = None if 'type' not in params.keys() else params['type']
79 return self.show_video_list(video_list_id=params['video_list_id'], type=type)
80 elif params['action'] == 'season_list':
81 # list of seasons for a show
82 return self.show_seasons(show_id=params['show_id'])
83 elif params['action'] == 'episode_list':
84 # list of episodes for a season
85 return self.show_episode_list(season_id=params['season_id'])
86 elif params['action'] == 'rating':
87 return self.rate_on_netflix(video_id=params['id'])
88 elif params['action'] == 'remove_from_list':
89 # removes a title from the users list on Netflix
90 self.kodi_helper.invalidate_memcache()
91 return self.remove_from_list(video_id=params['id'])
92 elif params['action'] == 'add_to_list':
93 # adds a title to the users list on Netflix
94 self.kodi_helper.invalidate_memcache()
95 return self.add_to_list(video_id=params['id'])
96 elif params['action'] == 'export':
97 # adds a title to the users list on Netflix
98 alt_title = self.kodi_helper.show_add_to_library_title_dialog(original_title=urllib.unquote(params['title']).decode('utf8'))
99 return self.export_to_library(video_id=params['id'], alt_title=alt_title)
100 elif params['action'] == 'remove':
101 # adds a title to the users list on Netflix
102 return self.remove_from_library(video_id=params['id'])
103 elif params['action'] == 'user-items' and params['type'] != 'search':
104 # display the lists (recommendations, genres, etc.)
105 return self.show_user_list(type=params['type'])
106 elif params['action'] == 'play_video':
107 self.play_video(video_id=params['video_id'], start_offset=params.get('start_offset', -1))
108 elif params['action'] == 'user-items' and params['type'] == 'search':
109 # if the user requested a search, ask for the term
110 term = self.kodi_helper.show_search_term_dialog()
111 return self.show_search_results(term=term)
113 raise ValueError('Invalid paramstring: {0}!'.format(paramstring))
117 def play_video (self, video_id, start_offset):
118 """Starts video playback
120 Note: This is just a dummy, inputstream is needed to play the vids
124 video_id : :obj:`str`
125 ID of the video that should be played
127 start_offset : :obj:`str`
128 Offset to resume playback from (in seconds)
131 esn = self.netflix_session.esn
132 return self.kodi_helper.play_item(esn=esn, video_id=video_id, start_offset=start_offset)
135 def show_search_results (self, term):
136 """Display a list of search results
146 If no results are available
148 has_search_results = False
149 search_results_raw = self.netflix_session.fetch_search_results(search_str=term)
150 # check for any errors
151 if self._is_dirty_response(response=search_results_raw):
154 # determine if we found something
155 if 'search' in search_results_raw['value']:
156 for key in search_results_raw['value']['search'].keys():
157 if self.netflix_session._is_size_key(key=key) == False:
158 has_search_results = search_results_raw['value']['search'][key]['titles']['length'] > 0
159 if has_search_results == False:
160 if search_results_raw['value']['search'][key].get('suggestions', False) != False:
161 for entry in search_results_raw['value']['search'][key]['suggestions']:
162 if self.netflix_session._is_size_key(key=entry) == False:
163 if search_results_raw['value']['search'][key]['suggestions'][entry]['relatedvideos']['length'] > 0:
164 has_search_results = True
167 # display that we haven't found a thing
168 if has_search_results == False:
169 return self.kodi_helper.build_no_search_results_available(build_url=self.build_url, action='search')
171 # list the search results
172 search_results = self.netflix_session.parse_search_results(response_data=search_results_raw)
173 # add more menaingful data to the search results
174 raw_search_contents = self.netflix_session.fetch_video_list_information(video_ids=search_results.keys())
175 # check for any errors
176 if self._is_dirty_response(response=raw_search_contents):
178 search_contents = self.netflix_session.parse_video_list(response_data=raw_search_contents)
179 actions = {'movie': 'play_video', 'show': 'season_list'}
180 return self.kodi_helper.build_search_result_listing(video_list=search_contents, actions=actions, build_url=self.build_url)
182 def show_user_list (self, type):
183 """List the users lists for shows/movies for recommendations/genres based on the given type
187 user_list_id : :obj:`str`
188 Type of list to display
190 video_list_ids_raw = self.netflix_session.fetch_video_list_ids()
191 # check for any errors
192 if self._is_dirty_response(response=video_list_ids_raw):
194 video_list_ids = self.netflix_session.parse_video_list_ids(response_data=video_list_ids_raw)
195 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)
197 def show_episode_list (self, season_id):
198 """Lists all episodes for a given season
202 season_id : :obj:`str`
203 ID of the season episodes should be displayed for
205 cache_id = 'episodes_' + season_id
206 if self.kodi_helper.has_cached_item(cache_id=cache_id):
207 episode_list = self.kodi_helper.get_cached_item(cache_id=cache_id)
209 raw_episode_list = self.netflix_session.fetch_episodes_by_season(season_id=season_id)
210 # check for any errors
211 if self._is_dirty_response(response=raw_episode_list):
213 # parse the raw Netflix data
214 episode_list = self.netflix_session.parse_episodes_by_season(response_data=raw_episode_list)
215 self.kodi_helper.add_cached_item(cache_id=cache_id, contents=episode_list)
217 # sort seasons by number (they´re coming back unsorted from the api)
219 for episode_id in episode_list:
220 episodes_sorted.append(int(episode_list[episode_id]['episode']))
221 episodes_sorted.sort()
224 return self.kodi_helper.build_episode_listing(episodes_sorted=episodes_sorted, episode_list=episode_list, build_url=self.build_url)
226 def show_seasons (self, show_id):
227 """Lists all seasons for a given show
232 ID of the show seasons should be displayed for
237 If no seasons are available
239 cache_id = 'season_' + show_id
240 if self.kodi_helper.has_cached_item(cache_id=cache_id):
241 season_list = self.kodi_helper.get_cached_item(cache_id=cache_id)
243 season_list_raw = self.netflix_session.fetch_seasons_for_show(id=show_id);
244 # check for any errors
245 if self._is_dirty_response(response=season_list_raw):
247 # check if we have sesons, announced shows that are not available yet have none
248 if 'seasons' not in season_list_raw['value']:
249 return self.kodi_helper.build_no_seasons_available()
250 # parse the seasons raw response from Netflix
251 season_list = self.netflix_session.parse_seasons(id=show_id, response_data=season_list_raw)
252 self.kodi_helper.add_cached_item(cache_id=cache_id, contents=season_list)
253 # sort seasons by index by default (they´re coming back unsorted from the api)
255 for season_id in season_list:
256 seasons_sorted.append(int(season_list[season_id]['idx']))
257 seasons_sorted.sort()
258 return self.kodi_helper.build_season_listing(seasons_sorted=seasons_sorted, season_list=season_list, build_url=self.build_url)
260 def show_video_list (self, video_list_id, type):
261 """List shows/movies based on the given video list id
265 video_list_id : :obj:`str`
266 ID of the video list that should be displayed
269 None or 'queue' f.e. when it´s a special video lists
271 if self.kodi_helper.has_cached_item(cache_id=video_list_id):
272 video_list = self.kodi_helper.get_cached_item(cache_id=video_list_id)
274 raw_video_list = self.netflix_session.fetch_video_list(list_id=video_list_id)
275 # check for any errors
276 if self._is_dirty_response(response=raw_video_list):
278 # parse the video list ids
279 if 'videos' in raw_video_list['value'].keys():
280 video_list = self.netflix_session.parse_video_list(response_data=raw_video_list)
281 self.kodi_helper.add_cached_item(cache_id=video_list_id, contents=video_list)
284 actions = {'movie': 'play_video', 'show': 'season_list'}
285 return self.kodi_helper.build_video_listing(video_list=video_list, actions=actions, type=type, build_url=self.build_url)
287 def show_video_lists (self):
288 """List the users video lists (recommendations, my list, etc.)"""
290 if self.kodi_helper.has_cached_item(cache_id=cache_id):
291 video_list_ids = self.kodi_helper.get_cached_item(cache_id=cache_id)
294 raw_video_list_ids = self.netflix_session.fetch_video_list_ids()
295 # check for any errors
296 if self._is_dirty_response(response=raw_video_list_ids):
298 # parse the video list ids
299 video_list_ids = self.netflix_session.parse_video_list_ids(response_data=raw_video_list_ids)
300 self.kodi_helper.add_cached_item(cache_id=cache_id, contents=video_list_ids)
301 # defines an order for the user list, as Netflix changes the order at every request
302 user_list_order = ['queue', 'continueWatching', 'topTen', 'netflixOriginals', 'trendingNow', 'newRelease', 'popularTitles']
303 # define where to route the user
304 actions = {'recommendations': 'user-items', 'genres': 'user-items', 'search': 'user-items', 'default': 'video_list'}
305 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)
308 def show_profiles (self):
309 """List the profiles for the active account"""
310 credentials = self.kodi_helper.get_credentials()
311 self.netflix_session.refresh_session_data(account=credentials)
312 profiles = self.netflix_session.profiles
313 return self.kodi_helper.build_profiles_listing(profiles=profiles, action='video_lists', build_url=self.build_url)
316 def rate_on_netflix (self, video_id):
317 """Rate a show/movie/season/episode on Netflix
321 video_list_id : :obj:`str`
322 ID of the video list that should be displayed
324 rating = self.kodi_helper.show_rating_dialog()
325 return self.netflix_session.rate_video(video_id=video_id, rating=rating)
328 def remove_from_list (self, video_id):
329 """Remove an item from 'My List' & refresh the view
333 video_list_id : :obj:`str`
334 ID of the video list that should be displayed
336 self.netflix_session.remove_from_list(video_id=video_id)
337 return self.kodi_helper.refresh()
340 def add_to_list (self, video_id):
341 """Add an item to 'My List' & refresh the view
345 video_list_id : :obj:`str`
346 ID of the video list that should be displayed
348 self.netflix_session.add_to_list(video_id=video_id)
349 return self.kodi_helper.refresh()
352 def export_to_library (self, video_id, alt_title):
353 """Adds an item to the local library
357 video_id : :obj:`str`
358 ID of the movie or show
360 alt_title : :obj:`str`
361 Alternative title (for the folder written to disc)
363 metadata = self.netflix_session.fetch_metadata(id=video_id)
364 # check for any errors
365 if self._is_dirty_response(response=metadata):
367 video = metadata['video']
369 if video['type'] == 'movie':
370 self.library.add_movie(title=video['title'], alt_title=alt_title, year=video['year'], video_id=video_id, build_url=self.build_url)
371 if video['type'] == 'show':
373 for season in video['seasons']:
374 for episode in season['episodes']:
375 episodes.append({'season': season['seq'], 'episode': episode['seq'], 'id': episode['id']})
377 self.library.add_show(title=video['title'], alt_title=alt_title, episodes=episodes, build_url=self.build_url)
378 return self.kodi_helper.refresh()
381 def remove_from_library (self, video_id, season=None, episode=None):
382 """Removes an item from the local library
386 video_id : :obj:`str`
387 ID of the movie or show
389 metadata = self.netflix_session.fetch_metadata(id=video_id)
390 # check for any errors
391 if self._is_dirty_response(response=metadata):
393 video = metadata['video']
395 if video['type'] == 'movie':
396 self.library.remove_movie(title=video['title'], year=video['year'])
397 if video['type'] == 'show':
398 self.library.remove_show(title=video['title'])
399 return self.kodi_helper.refresh()
402 def establish_session(self, account):
403 """Checks if we have an cookie with an active sessions, otherwise tries to login the user
407 account : :obj:`dict` of :obj:`str`
408 Dict containing an email & a password property
413 If we don't have an active session & the user couldn't be logged in
415 return True if self.netflix_session.is_logged_in(account=account) else self.netflix_session.login(account=account)
418 def before_routing_action (self, params):
419 """Executes actions before the actual routing takes place:
421 - Check if account data has been stored, if not, asks for it
422 - Check if the profile should be changed (and changes if so)
423 - Establishes a session if no action route is given
427 params : :obj:`dict` of :obj:`str`
432 :obj:`dict` of :obj:`str`
433 Options that can be provided by this hook & used later in the routing process
436 credentials = self.kodi_helper.get_credentials()
437 # check if we have user settings, if not, set em
438 if credentials['email'] == '':
439 email = self.kodi_helper.show_email_dialog()
440 self.kodi_helper.set_setting(key='email', value=email)
441 credentials['email'] = email
442 if credentials['password'] == '':
443 password = self.kodi_helper.show_password_dialog()
444 self.kodi_helper.set_setting(key='password', value=password)
445 credentials['password'] = password
446 # persist & load main menu selection
448 self.kodi_helper.set_main_menu_selection(type=params['type'])
449 options['main_menu_selection'] = self.kodi_helper.get_main_menu_selection()
450 # check and switch the profile if needed
451 if self.check_for_designated_profile_change(params=params):
452 self.kodi_helper.invalidate_memcache()
453 self.netflix_session.switch_profile(profile_id=params['profile_id'], account=credentials)
454 # check login, in case of main menu
455 if 'action' not in params:
456 self.establish_session(account=credentials)
459 def check_for_designated_profile_change (self, params):
460 """Checks if the profile needs to be switched
464 params : :obj:`dict` of :obj:`str`
470 Profile should be switched or not
472 # check if we need to switch the user
473 if 'guid' not in self.netflix_session.user_data:
475 current_profile_id = self.netflix_session.user_data['guid']
476 return 'profile_id' in params and current_profile_id != params['profile_id']
478 def parse_paramters (self, paramstring):
479 """Tiny helper to convert a url paramstring into a dictionary
483 paramstring : :obj:`str`
484 Url query params (in url string notation)
488 :obj:`dict` of :obj:`str`
489 Url query params (as a dictionary)
491 return dict(parse_qsl(paramstring))
493 def _is_expired_session (self, response):
494 """Checks if a response error is based on an invalid session
498 response : :obj:`dict` of :obj:`str`
499 Error response object
504 Error is based on an invalid session
506 return 'error' in response and 'code' in response and str(response['code']) == '401'
508 def _is_dirty_response (self, response):
509 """Checks if a response contains an error & if the error is based on an invalid session, it tries a relogin
513 response : :obj:`dict` of :obj:`str`
514 Success response object or Error response object
519 Response contains error or not
521 # check for any errors
522 if 'error' in response:
523 # check if we do not have a valid session, in case that happens: (re)login
524 if self._is_expired_session(response=response):
525 if self.establish_session(account=self.kodi_helper.get_credentials()):
527 message = response['message'] if 'message' in response else ''
528 code = response['code'] if 'code' in response else ''
529 self.log(msg='[ERROR]: ' + message + '::' + str(code))
533 def build_url(self, query):
534 """Tiny helper to transform a dict into a url + querystring
538 query : :obj:`dict` of :obj:`str`
539 List of paramters to be url encoded
544 Url + querystring based on the param
546 return self.base_url + '?' + urllib.urlencode(query)