2 # -*- coding: utf-8 -*-
4 # Created on: 13.01.2017
9 from urlparse import parse_qsl
10 from utils import noop, log
13 """Routes to the correct subfolder, dispatches actions & acts as a controller for the Kodi view & the Netflix model"""
15 def __init__ (self, kodi_helper, library, base_url, log_fn=noop):
16 """Takes the instances & configuration options needed to drive the plugin
20 kodi_helper : :obj:`KodiHelper`
21 instance of the KodiHelper class
23 library : :obj:`Library`
24 instance of the Library class
32 self.kodi_helper = kodi_helper
33 self.library = library
34 self.base_url = base_url
38 def router (self, paramstring):
39 """Route to the requested subfolder & dispatch actions along the way
43 paramstring : :obj:`str`
46 params = self.parse_paramters(paramstring=paramstring)
49 if 'action' in params.keys() and params['action'] == 'logout':
50 return self.call_netflix_service({'method': 'logout'})
52 # check login & try to relogin if necessary
53 account = self.kodi_helper.get_credentials()
54 if account['email'] != '' and account['password'] != '':
55 if self.call_netflix_service({'method': 'is_logged_in'}) != True:
56 if self.establish_session(account=account) != True:
57 return self.kodi_helper.show_login_failed_notification()
59 # check if we need to execute any actions before the actual routing
60 # gives back a dict of options routes might need
61 options = self.before_routing_action(params=params)
63 # check if one of the before routing options decided to killthe routing
66 if 'action' not in params.keys():
68 return self.show_profiles()
69 elif params['action'] == 'video_lists':
70 # list lists that contain other lists (starting point with recommendations, search, etc.)
71 return self.show_video_lists()
72 elif params['action'] == 'video_list':
73 # show a list of shows/movies
74 type = None if 'type' not in params.keys() else params['type']
75 return self.show_video_list(video_list_id=params['video_list_id'], type=type)
76 elif params['action'] == 'season_list':
77 # list of seasons for a show
78 return self.show_seasons(show_id=params['show_id'])
79 elif params['action'] == 'episode_list':
80 # list of episodes for a season
81 return self.show_episode_list(season_id=params['season_id'])
82 elif params['action'] == 'rating':
83 return self.rate_on_netflix(video_id=params['id'])
84 elif params['action'] == 'remove_from_list':
85 # removes a title from the users list on Netflix
86 self.kodi_helper.invalidate_memcache()
87 return self.remove_from_list(video_id=params['id'])
88 elif params['action'] == 'add_to_list':
89 # adds a title to the users list on Netflix
90 self.kodi_helper.invalidate_memcache()
91 return self.add_to_list(video_id=params['id'])
92 elif params['action'] == 'export':
93 # adds a title to the users list on Netflix
94 alt_title = self.kodi_helper.show_add_to_library_title_dialog(original_title=urllib.unquote(params['title']).decode('utf8'))
95 return self.export_to_library(video_id=params['id'], alt_title=alt_title)
96 elif params['action'] == 'remove':
97 # adds a title to the users list on Netflix
98 return self.remove_from_library(video_id=params['id'])
99 elif params['action'] == 'user-items' and params['type'] != 'search':
100 # display the lists (recommendations, genres, etc.)
101 return self.show_user_list(type=params['type'])
102 elif params['action'] == 'play_video':
103 self.play_video(video_id=params['video_id'], start_offset=params.get('start_offset', -1))
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)
126 esn = self.call_netflix_service({'method': 'get_esn'})
127 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 search_contents = self.call_netflix_service({'method': 'search', 'term': term})
144 # check for any errors
145 if self._is_dirty_response(response=search_contents):
147 actions = {'movie': 'play_video', 'show': 'season_list'}
148 return self.kodi_helper.build_search_result_listing(video_list=search_contents, actions=actions, build_url=self.build_url)
150 def show_user_list (self, type):
151 """List the users lists for shows/movies for recommendations/genres based on the given type
155 user_list_id : :obj:`str`
156 Type of list to display
158 video_list_ids = self.call_netflix_service({'method': 'fetch_video_list_ids', 'type': type})
159 # check for any errors
160 if self._is_dirty_response(response=video_list_ids):
162 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)
164 def show_episode_list (self, season_id):
165 """Lists all episodes for a given season
169 season_id : :obj:`str`
170 ID of the season episodes should be displayed for
172 cache_id = 'episodes_' + season_id
173 if self.kodi_helper.has_cached_item(cache_id=cache_id):
174 episode_list = self.kodi_helper.get_cached_item(cache_id=cache_id)
176 episode_list = self.call_netflix_service({'method': 'fetch_episodes_by_season', 'season_id': season_id})
177 # check for any errors
178 if self._is_dirty_response(response=episode_list):
180 # parse the raw Netflix data
181 self.kodi_helper.add_cached_item(cache_id=cache_id, contents=episode_list)
183 # sort seasons by number (they´re coming back unsorted from the api)
185 for episode_id in episode_list:
186 episodes_sorted.append(int(episode_list[episode_id]['episode']))
187 episodes_sorted.sort()
190 return self.kodi_helper.build_episode_listing(episodes_sorted=episodes_sorted, episode_list=episode_list, build_url=self.build_url)
192 def show_seasons (self, show_id):
193 """Lists all seasons for a given show
198 ID of the show seasons should be displayed for
203 If no seasons are available
205 cache_id = 'season_' + show_id
206 if self.kodi_helper.has_cached_item(cache_id=cache_id):
207 season_list = self.kodi_helper.get_cached_item(cache_id=cache_id)
209 season_list = self.call_netflix_service({'method': 'fetch_seasons_for_show', 'show_id': show_id})
210 # check for any errors
211 if self._is_dirty_response(response=season_list):
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 # parse the seasons raw response from Netflix
217 self.kodi_helper.add_cached_item(cache_id=cache_id, contents=season_list)
218 # sort seasons by index by default (they´re coming back unsorted from the api)
220 for season_id in season_list:
221 seasons_sorted.append(int(season_list[season_id]['idx']))
222 seasons_sorted.sort()
223 return self.kodi_helper.build_season_listing(seasons_sorted=seasons_sorted, season_list=season_list, build_url=self.build_url)
225 def show_video_list (self, video_list_id, type):
226 """List shows/movies based on the given video list id
230 video_list_id : :obj:`str`
231 ID of the video list that should be displayed
234 None or 'queue' f.e. when it´s a special video lists
236 if self.kodi_helper.has_cached_item(cache_id=video_list_id):
237 video_list = self.kodi_helper.get_cached_item(cache_id=video_list_id)
239 video_list = self.call_netflix_service({'method': 'fetch_video_list', 'list_id': video_list_id})
240 # check for any errors
241 if self._is_dirty_response(response=video_list):
243 # parse the video list ids
244 if len(video_list) > 0:
245 self.kodi_helper.add_cached_item(cache_id=video_list_id, contents=video_list)
246 actions = {'movie': 'play_video', 'show': 'season_list'}
247 return self.kodi_helper.build_video_listing(video_list=video_list, actions=actions, type=type, build_url=self.build_url)
249 def show_video_lists (self):
250 """List the users video lists (recommendations, my list, etc.)"""
252 if self.kodi_helper.has_cached_item(cache_id=cache_id):
253 video_list_ids = self.kodi_helper.get_cached_item(cache_id=cache_id)
256 video_list_ids = self.call_netflix_service({'method': 'fetch_video_list_ids'})
257 # check for any errors
258 if self._is_dirty_response(response=video_list_ids):
260 # parse the video list ids
261 self.kodi_helper.add_cached_item(cache_id=cache_id, contents=video_list_ids)
262 # defines an order for the user list, as Netflix changes the order at every request
263 user_list_order = ['queue', 'continueWatching', 'topTen', 'netflixOriginals', 'trendingNow', 'newRelease', 'popularTitles']
264 # define where to route the user
265 actions = {'recommendations': 'user-items', 'genres': 'user-items', 'search': 'user-items', 'default': 'video_list'}
266 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)
269 def show_profiles (self):
270 """List the profiles for the active account"""
271 profiles = self.call_netflix_service({'method': 'list_profiles'})
272 if len(profiles) == 0:
273 return self.kodi_helper.show_login_failed_notification()
274 return self.kodi_helper.build_profiles_listing(profiles=profiles, action='video_lists', build_url=self.build_url)
277 def rate_on_netflix (self, video_id):
278 """Rate a show/movie/season/episode on Netflix
282 video_list_id : :obj:`str`
283 ID of the video list that should be displayed
285 rating = self.kodi_helper.show_rating_dialog()
286 return self.call_netflix_service({'method': 'rate_video', 'video_id': video_id, 'rating': rating})
289 def remove_from_list (self, video_id):
290 """Remove an item from 'My List' & refresh the view
294 video_list_id : :obj:`str`
295 ID of the video list that should be displayed
297 self.call_netflix_service({'method': 'remove_from_list', 'video_id': video_id})
298 return self.kodi_helper.refresh()
301 def add_to_list (self, video_id):
302 """Add an item to 'My List' & refresh the view
306 video_list_id : :obj:`str`
307 ID of the video list that should be displayed
309 self.call_netflix_service({'method': 'add_to_list', 'video_id': video_id})
310 return self.kodi_helper.refresh()
313 def export_to_library (self, video_id, alt_title):
314 """Adds an item to the local library
318 video_id : :obj:`str`
319 ID of the movie or show
321 alt_title : :obj:`str`
322 Alternative title (for the folder written to disc)
324 metadata = self.call_netflix_service({'method': 'fetch_metadata', 'video_id': video_id})
325 # check for any errors
326 if self._is_dirty_response(response=metadata):
328 video = metadata['video']
330 if video['type'] == 'movie':
331 self.library.add_movie(title=video['title'], alt_title=alt_title, year=video['year'], video_id=video_id, build_url=self.build_url)
332 if video['type'] == 'show':
334 for season in video['seasons']:
335 for episode in season['episodes']:
336 episodes.append({'season': season['seq'], 'episode': episode['seq'], 'id': episode['id']})
338 self.library.add_show(title=video['title'], alt_title=alt_title, episodes=episodes, build_url=self.build_url)
339 return self.kodi_helper.refresh()
342 def remove_from_library (self, video_id, season=None, episode=None):
343 """Removes an item from the local library
347 video_id : :obj:`str`
348 ID of the movie or show
350 metadata = self.call_netflix_service({'method': 'fetch_metadata', 'video_id': video_id})
351 # check for any errors
352 if self._is_dirty_response(response=metadata):
354 video = metadata['video']
356 if video['type'] == 'movie':
357 self.library.remove_movie(title=video['title'], year=video['year'])
358 if video['type'] == 'show':
359 self.library.remove_show(title=video['title'])
360 return self.kodi_helper.refresh()
363 def establish_session(self, account):
364 """Checks if we have an cookie with an active sessions, otherwise tries to login the user
368 account : :obj:`dict` of :obj:`str`
369 Dict containing an email & a password property
374 If we don't have an active session & the user couldn't be logged in
376 is_logged_in = self.call_netflix_service({'method': 'is_logged_in'})
377 return True if is_logged_in else self.call_netflix_service({'method': 'login', 'email': account['email'], 'password': account['password']})
380 def before_routing_action (self, params):
381 """Executes actions before the actual routing takes place:
383 - Check if account data has been stored, if not, asks for it
384 - Check if the profile should be changed (and changes if so)
385 - Establishes a session if no action route is given
389 params : :obj:`dict` of :obj:`str`
394 :obj:`dict` of :obj:`str`
395 Options that can be provided by this hook & used later in the routing process
398 credentials = self.kodi_helper.get_credentials()
399 # check if we have user settings, if not, set em
400 if credentials['email'] == '':
401 email = self.kodi_helper.show_email_dialog()
402 self.kodi_helper.set_setting(key='email', value=email)
403 credentials['email'] = email
404 if credentials['password'] == '':
405 password = self.kodi_helper.show_password_dialog()
406 self.kodi_helper.set_setting(key='password', value=password)
407 credentials['password'] = password
408 # persist & load main menu selection
410 self.kodi_helper.set_main_menu_selection(type=params['type'])
411 options['main_menu_selection'] = self.kodi_helper.get_main_menu_selection()
412 # check and switch the profile if needed
413 if self.check_for_designated_profile_change(params=params):
414 self.kodi_helper.invalidate_memcache()
415 self.call_netflix_service({'method': 'switch_profile', 'profile_id': params['profile_id']})
416 # check login, in case of main menu
417 if 'action' not in params:
418 self.kodi_helper.log('ES Called - Zeile 428')
419 self.establish_session(account=credentials)
422 def check_for_designated_profile_change (self, params):
423 """Checks if the profile needs to be switched
427 params : :obj:`dict` of :obj:`str`
433 Profile should be switched or not
435 # check if we need to switch the user
436 user_data = self.call_netflix_service({'method': 'get_user_data'})
437 if 'guid' not in user_data:
439 current_profile_id = user_data['guid']
440 return 'profile_id' in params and current_profile_id != params['profile_id']
442 def parse_paramters (self, paramstring):
443 """Tiny helper to convert a url paramstring into a dictionary
447 paramstring : :obj:`str`
448 Url query params (in url string notation)
452 :obj:`dict` of :obj:`str`
453 Url query params (as a dictionary)
455 return dict(parse_qsl(paramstring))
457 def _is_expired_session (self, response):
458 """Checks if a response error is based on an invalid session
462 response : :obj:`dict` of :obj:`str`
463 Error response object
468 Error is based on an invalid session
470 return 'error' in response and 'code' in response and str(response['code']) == '401'
472 def _is_dirty_response (self, response):
473 """Checks if a response contains an error & if the error is based on an invalid session, it tries a relogin
477 response : :obj:`dict` of :obj:`str`
478 Success response object or Error response object
483 Response contains error or not
485 # check for any errors
486 if 'error' in response:
487 # check if we do not have a valid session, in case that happens: (re)login
488 if self._is_expired_session(response=response):
489 self.kodi_helper.log('ES Called - Zeile 499')
490 if self.establish_session(account=self.kodi_helper.get_credentials()):
492 message = response['message'] if 'message' in response else ''
493 code = response['code'] if 'code' in response else ''
494 self.log(msg='[ERROR]: ' + message + '::' + str(code))
498 def build_url(self, query):
499 """Tiny helper to transform a dict into a url + querystring
503 query : :obj:`dict` of :obj:`str`
504 List of paramters to be url encoded
509 Url + querystring based on the param
511 return self.base_url + '?' + urllib.urlencode(query)
513 def get_netflix_service_url (self):
514 """Returns URL & Port of the internal Netflix HTTP Proxy service
521 return 'http://localhost:' + str(self.kodi_helper.addon.getSetting('netflix_service_port'))
523 def call_netflix_service (self, params):
524 """Makes a GET request to the internal Netflix HTTP proxy and returns the result
528 params : :obj:`dict` of :obj:`str`
529 List of paramters to be url encoded
534 Netflix Service RPC result
536 url_values = urllib.urlencode(params)
537 url = self.get_netflix_service_url()
538 full_url = url + '?' + url_values
539 data = urllib2.urlopen(full_url).read()
540 parsed_json = json.loads(data)
541 return parsed_json.get('result', None)