Tweak use of in memory cache.
[plugin.video.netflix.git] / resources / lib / Navigation.py
index 67a59d343eb0ed209941d563ff13e533b5e79628..2d690af942d4459039cee4bf6fc3a000c0d4f186 100644 (file)
@@ -4,22 +4,21 @@
 # Created on: 13.01.2017
 
 import urllib
-import time
+import urllib2
+import json
+import ast
+from xbmcaddon import Addon
 from urlparse import parse_qsl
-from utils import noop
-from utils import log
+from utils import noop, log
 
 class Navigation:
     """Routes to the correct subfolder, dispatches actions & acts as a controller for the Kodi view & the Netflix model"""
 
-    def __init__ (self, netflix_session, kodi_helper, library, base_url, log_fn=noop):
+    def __init__ (self, kodi_helper, library, base_url, log_fn=noop):
         """Takes the instances & configuration options needed to drive the plugin
 
         Parameters
         ----------
-        netflix_session : :obj:`NetflixSession`
-            instance of the NetflixSession class
-
         kodi_helper : :obj:`KodiHelper`
             instance of the KodiHelper class
 
@@ -32,7 +31,6 @@ class Navigation:
         log_fn : :obj:`fn`
              optional log function
         """
-        self.netflix_session = netflix_session
         self.kodi_helper = kodi_helper
         self.library = library
         self.base_url = base_url
@@ -49,14 +47,18 @@ class Navigation:
         """
         params = self.parse_paramters(paramstring=paramstring)
 
+        # open foreign settings dialog
+        if 'mode' in params.keys() and params['mode'] == 'openSettings':
+            return self.open_settings(params['url'])
+
         # log out the user
         if 'action' in params.keys() and params['action'] == 'logout':
-            return self.netflix_session.logout()
+            return self.call_netflix_service({'method': 'logout'})
 
         # check login & try to relogin if necessary
         account = self.kodi_helper.get_credentials()
         if account['email'] != '' and account['password'] != '':
-            if self.netflix_session.is_logged_in(account=account) != True:
+            if self.call_netflix_service({'method': 'is_logged_in'}) != True:
                 if self.establish_session(account=account) != True:
                     return self.kodi_helper.show_login_failed_notification()
 
@@ -69,7 +71,7 @@ class Navigation:
             return False
         if 'action' not in params.keys():
             # show the profiles
-            self.show_profiles()
+            return self.show_profiles()
         elif params['action'] == 'video_lists':
             # list lists that contain other lists (starting point with recommendations, search, etc.)
             return self.show_video_lists()
@@ -79,10 +81,10 @@ class Navigation:
             return self.show_video_list(video_list_id=params['video_list_id'], type=type)
         elif params['action'] == 'season_list':
             # list of seasons for a show
-            return self.show_seasons(show_id=params['show_id'])
+            return self.show_seasons(show_id=params['show_id'], tvshowtitle=params['tvshowtitle'])
         elif params['action'] == 'episode_list':
             # list of episodes for a season
-            return self.show_episode_list(season_id=params['season_id'])
+            return self.show_episode_list(season_id=params['season_id'], tvshowtitle=params['tvshowtitle'])
         elif params['action'] == 'rating':
             return self.rate_on_netflix(video_id=params['id'])
         elif params['action'] == 'remove_from_list':
@@ -104,13 +106,7 @@ class Navigation:
             # display the lists (recommendations, genres, etc.)
             return self.show_user_list(type=params['type'])
         elif params['action'] == 'play_video':
-            # play a video, check for adult pin if needed
-            adult_pin = None
-            if self.check_for_adult_pin(params=params):
-                adult_pin = self.kodi_helper.show_adult_pin_dialog()
-                if self.netflix_session.send_adult_pin(adult_pin=adult_pin) != True:
-                    return self.kodi_helper.show_wrong_adult_pin_notification()
-            self.play_video(video_id=params['video_id'], start_offset=params['start_offset'])
+            self.play_video(video_id=params['video_id'], start_offset=params.get('start_offset', -1), infoLabels=params['infoLabels'])
         elif params['action'] == 'user-items' and params['type'] == 'search':
             # if the user requested a search, ask for the term
             term = self.kodi_helper.show_search_term_dialog()
@@ -120,7 +116,7 @@ class Navigation:
         return True
 
     @log
-    def play_video (self, video_id, start_offset):
+    def play_video (self, video_id, start_offset, infoLabels):
         """Starts video playback
 
         Note: This is just a dummy, inputstream is needed to play the vids
@@ -132,10 +128,16 @@ class Navigation:
 
         start_offset : :obj:`str`
             Offset to resume playback from (in seconds)
+
+        infoLabels : :obj:`str`
+            the listitem's infoLabels
         """
-        # widevine esn
-        esn = self.netflix_session.esn
-        return self.kodi_helper.play_item(esn=esn, video_id=video_id, start_offset=start_offset)
+        try:
+            infoLabels = ast.literal_eval(infoLabels)
+        except:
+            infoLabels= {}
+        esn = self.call_netflix_service({'method': 'get_esn'})
+        return self.kodi_helper.play_item(esn=esn, video_id=video_id, start_offset=start_offset, infoLabels=infoLabels)
 
     @log
     def show_search_results (self, term):
@@ -151,36 +153,11 @@ class Navigation:
         bool
             If no results are available
         """
-        has_search_results = False
-        search_results_raw = self.netflix_session.fetch_search_results(search_str=term)
-        # check for any errors
-        if self._is_dirty_response(response=search_results_raw):
-            return False
-
-        # determine if we found something
-        if 'search' in search_results_raw['value']:
-            for key in search_results_raw['value']['search'].keys():
-                if self.netflix_session._is_size_key(key=key) == False:
-                    has_search_results = search_results_raw['value']['search'][key]['titles']['length'] > 0
-                    if has_search_results == False:
-                        for entry in search_results_raw['value']['search'][key]['suggestions']:
-                            if self.netflix_session._is_size_key(key=entry) == False:
-                                if search_results_raw['value']['search'][key]['suggestions'][entry]['relatedvideos']['length'] > 0:
-                                    has_search_results = True
-
-
-        # display that we haven't found a thing
-        if has_search_results == False:
-            return self.kodi_helper.build_no_search_results_available(build_url=self.build_url, action='search')
-
-        # list the search results
-        search_results = self.netflix_session.parse_search_results(response_data=search_results_raw)
-        # add more menaingful data to the search results
-        raw_search_contents = self.netflix_session.fetch_video_list_information(video_ids=search_results.keys())
+        user_data = self.call_netflix_service({'method': 'get_user_data'})
+        search_contents = self.call_netflix_service({'method': 'search', 'term': term, 'guid': user_data['guid'], 'cache': True})
         # check for any errors
-        if self._is_dirty_response(response=raw_search_contents):
+        if self._is_dirty_response(response=search_contents):
             return False
-        search_contents = self.netflix_session.parse_video_list(response_data=raw_search_contents)
         actions = {'movie': 'play_video', 'show': 'season_list'}
         return self.kodi_helper.build_search_result_listing(video_list=search_contents, actions=actions, build_url=self.build_url)
 
@@ -192,43 +169,41 @@ class Navigation:
         user_list_id : :obj:`str`
             Type of list to display
         """
-        video_list_ids_raw = self.netflix_session.fetch_video_list_ids()
+        # determine if we´re in kids mode
+        user_data = self.call_netflix_service({'method': 'get_user_data'})
+        video_list_ids = self.call_netflix_service({'method': 'fetch_video_list_ids', 'guid': user_data['guid'], 'cache': True})
         # check for any errors
-        if self._is_dirty_response(response=video_list_ids_raw):
+        if self._is_dirty_response(response=video_list_ids):
             return False
-        video_list_ids = self.netflix_session.parse_video_list_ids(response_data=video_list_ids_raw)
         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)
 
-    def show_episode_list (self, season_id):
+    def show_episode_list (self, season_id, tvshowtitle):
         """Lists all episodes for a given season
 
         Parameters
         ----------
         season_id : :obj:`str`
             ID of the season episodes should be displayed for
-        """
-        cache_id = 'episodes_' + season_id
-        if self.kodi_helper.has_cached_item(cache_id=cache_id):
-            episode_list = self.kodi_helper.get_cached_item(cache_id=cache_id)
-        else:
-            raw_episode_list = self.netflix_session.fetch_episodes_by_season(season_id=season_id)
-            # check for any errors
-            if self._is_dirty_response(response=raw_episode_list):
-                return False
-            # parse the raw Netflix data
-            episode_list = self.netflix_session.parse_episodes_by_season(response_data=raw_episode_list)
-            self.kodi_helper.add_cached_item(cache_id=cache_id, contents=episode_list)
 
+        tvshowtitle : :obj:`str`
+            title of the show (for listitems' infolabels)
+        """
+        user_data = self.call_netflix_service({'method': 'get_user_data'})
+        episode_list = self.call_netflix_service({'method': 'fetch_episodes_by_season', 'season_id': season_id, 'guid': user_data['guid'], 'cache': True})
+        # check for any errors
+        if self._is_dirty_response(response=episode_list):
+            return False
         # sort seasons by number (they´re coming back unsorted from the api)
         episodes_sorted = []
         for episode_id in episode_list:
+            episode_list[episode_id]['tvshowtitle'] = tvshowtitle
             episodes_sorted.append(int(episode_list[episode_id]['episode']))
             episodes_sorted.sort()
 
         # list the episodes
         return self.kodi_helper.build_episode_listing(episodes_sorted=episodes_sorted, episode_list=episode_list, build_url=self.build_url)
 
-    def show_seasons (self, show_id):
+    def show_seasons (self, show_id, tvshowtitle):
         """Lists all seasons for a given show
 
         Parameters
@@ -236,29 +211,26 @@ class Navigation:
         show_id : :obj:`str`
             ID of the show seasons should be displayed for
 
+        tvshowtitle : :obj:`str`
+            title of the show (for listitems' infolabels)
         Returns
         -------
         bool
             If no seasons are available
         """
-        cache_id = 'season_' + show_id
-        if self.kodi_helper.has_cached_item(cache_id=cache_id):
-            season_list = self.kodi_helper.get_cached_item(cache_id=cache_id)
-        else:
-            season_list_raw = self.netflix_session.fetch_seasons_for_show(id=show_id);
-            # check for any errors
-            if self._is_dirty_response(response=season_list_raw):
-                return False
-            # check if we have sesons, announced shows that are not available yet have none
-            if 'seasons' not in season_list_raw['value']:
-                return self.kodi_helper.build_no_seasons_available()
-            # parse the seasons raw response from Netflix
-            season_list = self.netflix_session.parse_seasons(id=show_id, response_data=season_list_raw)
-            self.kodi_helper.add_cached_item(cache_id=cache_id, contents=season_list)
+        user_data = self.call_netflix_service({'method': 'get_user_data'})
+        season_list = self.call_netflix_service({'method': 'fetch_seasons_for_show', 'show_id': show_id, 'guid': user_data['guid'], 'cache': True})
+        # check for any errors
+        if self._is_dirty_response(response=season_list):
+            return False
+        # check if we have sesons, announced shows that are not available yet have none
+        if len(season_list) == 0:
+            return self.kodi_helper.build_no_seasons_available()
         # sort seasons by index by default (they´re coming back unsorted from the api)
         seasons_sorted = []
         for season_id in season_list:
-            seasons_sorted.append(int(season_list[season_id]['shortName'].split(' ')[1]))
+            season_list[season_id]['tvshowtitle'] = tvshowtitle
+            seasons_sorted.append(int(season_list[season_id]['idx']))
             seasons_sorted.sort()
         return self.kodi_helper.build_season_listing(seasons_sorted=seasons_sorted, season_list=season_list, build_url=self.build_url)
 
@@ -273,36 +245,21 @@ class Navigation:
         type : :obj:`str`
             None or 'queue' f.e. when it´s a special video lists
         """
-        if self.kodi_helper.has_cached_item(cache_id=type):
-            video_list = self.kodi_helper.get_cached_item(cache_id=type)
-        else:
-            raw_video_list = self.netflix_session.fetch_video_list(list_id=video_list_id)
-            # check for any errors
-            if self._is_dirty_response(response=raw_video_list):
-                return False
-            # parse the video list ids
-            if 'videos' in raw_video_list['value'].keys():
-                video_list = self.netflix_session.parse_video_list(response_data=raw_video_list)
-                self.kodi_helper.add_cached_item(cache_id=type, contents=video_list)
-            else:
-                video_list = []
+        user_data = self.call_netflix_service({'method': 'get_user_data'})
+        video_list = self.call_netflix_service({'method': 'fetch_video_list', 'list_id': video_list_id, 'guid': user_data['guid'] ,'cache': True})
+        # check for any errors
+        if self._is_dirty_response(response=video_list):
+            return False
         actions = {'movie': 'play_video', 'show': 'season_list'}
         return self.kodi_helper.build_video_listing(video_list=video_list, actions=actions, type=type, build_url=self.build_url)
 
     def show_video_lists (self):
         """List the users video lists (recommendations, my list, etc.)"""
-        cache_id='main_menu'
-        if self.kodi_helper.has_cached_item(cache_id=cache_id):
-            video_list_ids = self.kodi_helper.get_cached_item(cache_id=cache_id)
-        else:
-            # fetch video lists
-            raw_video_list_ids = self.netflix_session.fetch_video_list_ids()
-            # check for any errors
-            if self._is_dirty_response(response=raw_video_list_ids):
-                return False
-            # parse the video list ids
-            video_list_ids = self.netflix_session.parse_video_list_ids(response_data=raw_video_list_ids)
-            self.kodi_helper.add_cached_item(cache_id=cache_id, contents=video_list_ids)
+        user_data = self.call_netflix_service({'method': 'get_user_data'})
+        video_list_ids = self.call_netflix_service({'method': 'fetch_video_list_ids', 'guid': user_data['guid'], 'cache': True})
+        # check for any errors
+        if self._is_dirty_response(response=video_list_ids):
+            return False
         # defines an order for the user list, as Netflix changes the order at every request
         user_list_order = ['queue', 'continueWatching', 'topTen', 'netflixOriginals', 'trendingNow', 'newRelease', 'popularTitles']
         # define where to route the user
@@ -312,9 +269,9 @@ class Navigation:
     @log
     def show_profiles (self):
         """List the profiles for the active account"""
-        credentials = self.kodi_helper.get_credentials()
-        self.netflix_session.refresh_session_data(account=credentials)
-        profiles = self.netflix_session.profiles
+        profiles = self.call_netflix_service({'method': 'list_profiles'})
+        if len(profiles) == 0:
+            return self.kodi_helper.show_login_failed_notification()
         return self.kodi_helper.build_profiles_listing(profiles=profiles, action='video_lists', build_url=self.build_url)
 
     @log
@@ -327,7 +284,7 @@ class Navigation:
             ID of the video list that should be displayed
         """
         rating = self.kodi_helper.show_rating_dialog()
-        return self.netflix_session.rate_video(video_id=video_id, rating=rating)
+        return self.call_netflix_service({'method': 'rate_video', 'video_id': video_id, 'rating': rating})
 
     @log
     def remove_from_list (self, video_id):
@@ -338,7 +295,7 @@ class Navigation:
         video_list_id : :obj:`str`
             ID of the video list that should be displayed
         """
-        self.netflix_session.remove_from_list(video_id=video_id)
+        self.call_netflix_service({'method': 'remove_from_list', 'video_id': video_id})
         return self.kodi_helper.refresh()
 
     @log
@@ -350,7 +307,7 @@ class Navigation:
         video_list_id : :obj:`str`
             ID of the video list that should be displayed
         """
-        self.netflix_session.add_to_list(video_id=video_id)
+        self.call_netflix_service({'method': 'add_to_list', 'video_id': video_id})
         return self.kodi_helper.refresh()
 
     @log
@@ -365,19 +322,19 @@ class Navigation:
         alt_title : :obj:`str`
             Alternative title (for the folder written to disc)
         """
-        metadata = self.netflix_session.fetch_metadata(id=video_id)
+        metadata = self.call_netflix_service({'method': 'fetch_metadata', 'video_id': video_id})
         # check for any errors
         if self._is_dirty_response(response=metadata):
             return False
         video = metadata['video']
 
         if video['type'] == 'movie':
-            self.library.add_movie(title=video['title'], alt_title=alt_title, year=video['year'], video_id=video_id, pin=video['requiresPin'], build_url=self.build_url)
+            self.library.add_movie(title=video['title'], alt_title=alt_title, year=video['year'], video_id=video_id, build_url=self.build_url)
         if video['type'] == 'show':
             episodes = []
             for season in video['seasons']:
                 for episode in season['episodes']:
-                    episodes.append({'season': season['seq'], 'episode': episode['seq'], 'id': episode['id'], 'pin': episode['requiresAdultVerification']})
+                    episodes.append({'season': season['seq'], 'episode': episode['seq'], 'id': episode['id']})
 
             self.library.add_show(title=video['title'], alt_title=alt_title, episodes=episodes, build_url=self.build_url)
         return self.kodi_helper.refresh()
@@ -391,7 +348,7 @@ class Navigation:
         video_id : :obj:`str`
             ID of the movie or show
         """
-        metadata = self.netflix_session.fetch_metadata(id=video_id)
+        metadata = self.call_netflix_service({'method': 'fetch_metadata', 'video_id': video_id})
         # check for any errors
         if self._is_dirty_response(response=metadata):
             return False
@@ -417,7 +374,8 @@ class Navigation:
         bool
             If we don't have an active session & the user couldn't be logged in
         """
-        return True if self.netflix_session.is_logged_in(account=account) else self.netflix_session.login(account=account)
+        is_logged_in = self.call_netflix_service({'method': 'is_logged_in'})
+        return True if is_logged_in else self.call_netflix_service({'method': 'login', 'email': account['email'], 'password': account['password']})
 
     @log
     def before_routing_action (self, params):
@@ -455,7 +413,11 @@ class Navigation:
         # check and switch the profile if needed
         if self.check_for_designated_profile_change(params=params):
             self.kodi_helper.invalidate_memcache()
-            self.netflix_session.switch_profile(profile_id=params['profile_id'], account=credentials)
+            profile_id = params.get('profile_id', None)
+            if profile_id == None:
+                user_data = self.call_netflix_service({'method': 'get_user_data'})
+                profile_id = user_data['guid']
+            self.call_netflix_service({'method': 'switch_profile', 'profile_id': profile_id})
         # check login, in case of main menu
         if 'action' not in params:
             self.establish_session(account=credentials)
@@ -475,26 +437,15 @@ class Navigation:
             Profile should be switched or not
         """
         # check if we need to switch the user
-        if 'guid' not in self.netflix_session.user_data:
+        user_data = self.call_netflix_service({'method': 'get_user_data'})
+        profiles = self.call_netflix_service({'method': 'list_profiles'})
+        if 'guid' not in user_data:
             return False
-        current_profile_id = self.netflix_session.user_data['guid']
+        current_profile_id = user_data['guid']
+        if profiles.get(current_profile_id).get('isKids', False) == True:
+            return True
         return 'profile_id' in params and current_profile_id != params['profile_id']
 
-    def check_for_adult_pin (self, params):
-        """Checks if an adult pin is given in the query params
-
-        Parameters
-        ----------
-        params : :obj:`dict` of :obj:`str`
-            Url query params
-
-        Returns
-        -------
-        bool
-            Adult pin parameter exists or not
-        """
-        return (True, False)[params['pin'] == 'True']
-
     def parse_paramters (self, paramstring):
         """Tiny helper to convert a url paramstring into a dictionary
 
@@ -564,3 +515,52 @@ class Navigation:
             Url + querystring based on the param
         """
         return self.base_url + '?' + urllib.urlencode(query)
+
+    def get_netflix_service_url (self):
+        """Returns URL & Port of the internal Netflix HTTP Proxy service
+
+        Returns
+        -------
+        str
+            Url + Port
+        """
+        return 'http://127.0.0.1:' + str(self.kodi_helper.get_addon().getSetting('netflix_service_port'))
+
+    def call_netflix_service (self, params):
+        """Makes a GET request to the internal Netflix HTTP proxy and returns the result
+
+        Parameters
+        ----------
+        params : :obj:`dict` of  :obj:`str`
+            List of paramters to be url encoded
+
+        Returns
+        -------
+        :obj:`dict`
+            Netflix Service RPC result
+        """
+        url_values = urllib.urlencode(params)
+        # check for cached items
+        if params.get('cache', False) == True:
+            cached_value = self.kodi_helper.get_cached_item(cache_id=url_values)
+
+            # Cache lookup successful?
+            if cached_value != None:
+                self.log(msg='Fetched item from cache: (cache_id=' + url_values + ')')
+                return cached_value
+
+        url = self.get_netflix_service_url()
+        full_url = url + '?' + url_values
+        data = urllib2.urlopen(full_url).read()
+        parsed_json = json.loads(data)
+        result = parsed_json.get('result', None)
+        if params.get('cache', False) == True:
+            self.log(msg='Adding item to cache: (cache_id=' + url_values + ')')
+            self.kodi_helper.add_cached_item(cache_id=url_values, contents=result)
+        return result
+
+    def open_settings(self, url):
+        """Opens a foreign settings dialog"""
+        is_addon = self.kodi_helper.get_inputstream_addon()
+        url = is_addon if url == 'is' else url
+        return Addon(url).openSettings()