fix(login): Enables hot login functionality, as well as proper login failed verification
[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 urlparse import parse_qsl
10 from utils import noop, log
11
12 class Navigation:
13     """Routes to the correct subfolder, dispatches actions & acts as a controller for the Kodi view & the Netflix model"""
14
15     def __init__ (self, kodi_helper, library, base_url, log_fn=noop):
16         """Takes the instances & configuration options needed to drive the plugin
17
18         Parameters
19         ----------
20         kodi_helper : :obj:`KodiHelper`
21             instance of the KodiHelper class
22
23         library : :obj:`Library`
24             instance of the Library class
25
26         base_url : :obj:`str`
27             plugin base url
28
29         log_fn : :obj:`fn`
30              optional log function
31         """
32         self.kodi_helper = kodi_helper
33         self.library = library
34         self.base_url = base_url
35         self.log = log_fn
36
37     @log
38     def router (self, paramstring):
39         """Route to the requested subfolder & dispatch actions along the way
40
41         Parameters
42         ----------
43         paramstring : :obj:`str`
44             Url query params
45         """
46         params = self.parse_paramters(paramstring=paramstring)
47
48         # log out the user
49         if 'action' in params.keys() and params['action'] == 'logout':
50             return self.call_netflix_service({'method': 'logout'})
51
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()
58
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)
62
63         # check if one of the before routing options decided to killthe routing
64         if 'exit' in options:
65             return False
66         if 'action' not in params.keys():
67             # show the profiles
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)
108         else:
109             raise ValueError('Invalid paramstring: {0}!'.format(paramstring))
110         return True
111
112     @log
113     def play_video (self, video_id, start_offset):
114         """Starts video playback
115
116         Note: This is just a dummy, inputstream is needed to play the vids
117
118         Parameters
119         ----------
120         video_id : :obj:`str`
121             ID of the video that should be played
122
123         start_offset : :obj:`str`
124             Offset to resume playback from (in seconds)
125         """
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)
128
129     @log
130     def show_search_results (self, term):
131         """Display a list of search results
132
133         Parameters
134         ----------
135         term : :obj:`str`
136             String to lookup
137
138         Returns
139         -------
140         bool
141             If no results are available
142         """
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):
146             return False
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)
149
150     def show_user_list (self, type):
151         """List the users lists for shows/movies for recommendations/genres based on the given type
152
153         Parameters
154         ----------
155         user_list_id : :obj:`str`
156             Type of list to display
157         """
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):
161             return False
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)
163
164     def show_episode_list (self, season_id):
165         """Lists all episodes for a given season
166
167         Parameters
168         ----------
169         season_id : :obj:`str`
170             ID of the season episodes should be displayed for
171         """
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)
175         else:
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):
179                 return False
180             # parse the raw Netflix data
181             self.kodi_helper.add_cached_item(cache_id=cache_id, contents=episode_list)
182
183         # sort seasons by number (they´re coming back unsorted from the api)
184         episodes_sorted = []
185         for episode_id in episode_list:
186             episodes_sorted.append(int(episode_list[episode_id]['episode']))
187             episodes_sorted.sort()
188
189         # list the episodes
190         return self.kodi_helper.build_episode_listing(episodes_sorted=episodes_sorted, episode_list=episode_list, build_url=self.build_url)
191
192     def show_seasons (self, show_id):
193         """Lists all seasons for a given show
194
195         Parameters
196         ----------
197         show_id : :obj:`str`
198             ID of the show seasons should be displayed for
199
200         Returns
201         -------
202         bool
203             If no seasons are available
204         """
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)
208         else:
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):
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             # 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)
219         seasons_sorted = []
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)
224
225     def show_video_list (self, video_list_id, type):
226         """List shows/movies based on the given video list id
227
228         Parameters
229         ----------
230         video_list_id : :obj:`str`
231             ID of the video list that should be displayed
232
233         type : :obj:`str`
234             None or 'queue' f.e. when it´s a special video lists
235         """
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)
238         else:
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):
242                 return False
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)
248
249     def show_video_lists (self):
250         """List the users video lists (recommendations, my list, etc.)"""
251         cache_id='main_menu'
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)
254         else:
255             # fetch video lists
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):
259                 return False
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)
267
268     @log
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)
275
276     @log
277     def rate_on_netflix (self, video_id):
278         """Rate a show/movie/season/episode on Netflix
279
280         Parameters
281         ----------
282         video_list_id : :obj:`str`
283             ID of the video list that should be displayed
284         """
285         rating = self.kodi_helper.show_rating_dialog()
286         return self.call_netflix_service({'method': 'rate_video', 'video_id': video_id, 'rating': rating})
287
288     @log
289     def remove_from_list (self, video_id):
290         """Remove an item from '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': 'remove_from_list', 'video_id': video_id})
298         return self.kodi_helper.refresh()
299
300     @log
301     def add_to_list (self, video_id):
302         """Add an item to 'My List' & refresh the view
303
304         Parameters
305         ----------
306         video_list_id : :obj:`str`
307             ID of the video list that should be displayed
308         """
309         self.call_netflix_service({'method': 'add_to_list', 'video_id': video_id})
310         return self.kodi_helper.refresh()
311
312     @log
313     def export_to_library (self, video_id, alt_title):
314         """Adds an item to the local library
315
316         Parameters
317         ----------
318         video_id : :obj:`str`
319             ID of the movie or show
320
321         alt_title : :obj:`str`
322             Alternative title (for the folder written to disc)
323         """
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):
327             return False
328         video = metadata['video']
329
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':
333             episodes = []
334             for season in video['seasons']:
335                 for episode in season['episodes']:
336                     episodes.append({'season': season['seq'], 'episode': episode['seq'], 'id': episode['id']})
337
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()
340
341     @log
342     def remove_from_library (self, video_id, season=None, episode=None):
343         """Removes an item from the local library
344
345         Parameters
346         ----------
347         video_id : :obj:`str`
348             ID of the movie or show
349         """
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):
353             return False
354         video = metadata['video']
355
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()
361
362     @log
363     def establish_session(self, account):
364         """Checks if we have an cookie with an active sessions, otherwise tries to login the user
365
366         Parameters
367         ----------
368         account : :obj:`dict` of :obj:`str`
369             Dict containing an email & a password property
370
371         Returns
372         -------
373         bool
374             If we don't have an active session & the user couldn't be logged in
375         """
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']})
378
379     @log
380     def before_routing_action (self, params):
381         """Executes actions before the actual routing takes place:
382
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
386
387         Parameters
388         ----------
389         params : :obj:`dict` of :obj:`str`
390             Url query params
391
392         Returns
393         -------
394         :obj:`dict` of :obj:`str`
395             Options that can be provided by this hook & used later in the routing process
396         """
397         options = {}
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
409         if 'type' in params:
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)
420         return options
421
422     def check_for_designated_profile_change (self, params):
423         """Checks if the profile needs to be switched
424
425         Parameters
426         ----------
427         params : :obj:`dict` of :obj:`str`
428             Url query params
429
430         Returns
431         -------
432         bool
433             Profile should be switched or not
434         """
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:
438             return False
439         current_profile_id = user_data['guid']
440         return 'profile_id' in params and current_profile_id != params['profile_id']
441
442     def parse_paramters (self, paramstring):
443         """Tiny helper to convert a url paramstring into a dictionary
444
445         Parameters
446         ----------
447         paramstring : :obj:`str`
448             Url query params (in url string notation)
449
450         Returns
451         -------
452         :obj:`dict` of :obj:`str`
453             Url query params (as a dictionary)
454         """
455         return dict(parse_qsl(paramstring))
456
457     def _is_expired_session (self, response):
458         """Checks if a response error is based on an invalid session
459
460         Parameters
461         ----------
462         response : :obj:`dict` of :obj:`str`
463             Error response object
464
465         Returns
466         -------
467         bool
468             Error is based on an invalid session
469         """
470         return 'error' in response and 'code' in response and str(response['code']) == '401'
471
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
474
475         Parameters
476         ----------
477         response : :obj:`dict` of :obj:`str`
478             Success response object or Error response object
479
480         Returns
481         -------
482         bool
483             Response contains error or not
484         """
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()):
491                     return True
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))
495             return True
496         return False
497
498     def build_url(self, query):
499         """Tiny helper to transform a dict into a url + querystring
500
501         Parameters
502         ----------
503         query : :obj:`dict` of  :obj:`str`
504             List of paramters to be url encoded
505
506         Returns
507         -------
508         str
509             Url + querystring based on the param
510         """
511         return self.base_url + '?' + urllib.urlencode(query)
512
513     def get_netflix_service_url (self):
514         """Returns URL & Port of the internal Netflix HTTP Proxy service
515
516         Returns
517         -------
518         str
519             Url + Port
520         """
521         return 'http://localhost:' + str(self.kodi_helper.addon.getSetting('netflix_service_port'))
522
523     def call_netflix_service (self, params):
524         """Makes a GET request to the internal Netflix HTTP proxy and returns the result
525
526         Parameters
527         ----------
528         params : :obj:`dict` of  :obj:`str`
529             List of paramters to be url encoded
530
531         Returns
532         -------
533         :obj:`dict`
534             Netflix Service RPC result
535         """
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)