2 # -*- coding: utf-8 -*-
4 # Created on: 13.01.2017
14 import cPickle as pickle
19 """Consumes all the configuration data from Kodi as well as turns data into lists of folders and videos"""
21 def __init__ (self, plugin_handle, base_url):
22 """Fetches all needed info from Kodi & configures the baseline of the plugin
26 plugin_handle : :obj:`int`
32 self.plugin_handle = plugin_handle
33 self.base_url = base_url
34 self.addon = xbmcaddon.Addon()
35 self.plugin = self.addon.getAddonInfo('name')
36 self.base_data_path = xbmc.translatePath(self.addon.getAddonInfo('profile'))
37 self.home_path = xbmc.translatePath('special://home')
38 self.plugin_path = self.addon.getAddonInfo('path')
39 self.cookie_path = self.base_data_path + 'COOKIE'
40 self.data_path = self.base_data_path + 'DATA'
41 self.config_path = os.path.join(self.base_data_path, 'config')
42 self.msl_data_path = xbmc.translatePath('special://profile/addon_data/service.msl').decode('utf-8') + '/'
43 self.verb_log = self.addon.getSetting('logging') == 'true'
44 self.default_fanart = self.addon.getAddonInfo('fanart')
45 self.win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
50 """Refrsh the current list"""
51 return xbmc.executebuiltin('Container.Refresh')
53 def show_rating_dialog (self):
54 """Asks the user for a movie rating
59 Movie rating between 0 & 10
61 dlg = xbmcgui.Dialog()
62 return dlg.numeric(heading=self.get_local_string(string_id=30019) + ' ' + self.get_local_string(string_id=30022), type=0)
64 def show_adult_pin_dialog (self):
65 """Asks the user for the adult pin
70 4 digit adult pin needed for adult movies
72 dlg = xbmcgui.Dialog()
73 return dlg.input(self.get_local_string(string_id=30002), type=xbmcgui.INPUT_NUMERIC)
75 def show_search_term_dialog (self):
76 """Asks the user for a term to query the netflix search for
83 dlg = xbmcgui.Dialog()
84 term = dlg.input(self.get_local_string(string_id=30003), type=xbmcgui.INPUT_ALPHANUM)
89 def show_add_to_library_title_dialog (self, original_title):
90 """Asks the user for an alternative title for the show/movie that gets exported to the local library
94 original_title : :obj:`str`
95 Original title of the show (as suggested by the addon)
102 dlg = xbmcgui.Dialog()
103 return dlg.input(heading=self.get_local_string(string_id=30031), defaultt=original_title, type=xbmcgui.INPUT_ALPHANUM)
105 def show_password_dialog (self):
106 """Asks the user for its Netflix password
113 dlg = xbmcgui.Dialog()
114 return dlg.input(self.get_local_string(string_id=30004), type=xbmcgui.INPUT_ALPHANUM)
116 def show_email_dialog (self):
117 """Asks the user for its Netflix account email
122 Netflix account email
124 dlg = xbmcgui.Dialog()
125 return dlg.input(self.get_local_string(string_id=30005), type=xbmcgui.INPUT_ALPHANUM)
127 def show_wrong_adult_pin_notification (self):
128 """Shows notification that a wrong adult pin was given
135 dialog = xbmcgui.Dialog()
136 dialog.notification(self.get_local_string(string_id=30006), self.get_local_string(string_id=30007), xbmcgui.NOTIFICATION_ERROR, 5000)
139 def show_login_failed_notification (self):
140 """Shows notification that the login failed
147 dialog = xbmcgui.Dialog()
148 dialog.notification(self.get_local_string(string_id=30008), self.get_local_string(string_id=30009), xbmcgui.NOTIFICATION_ERROR, 5000)
151 def show_missing_inputstream_addon_notification (self):
152 """Shows notification that the inputstream addon couldn't be found
159 dialog = xbmcgui.Dialog()
160 dialog.notification(self.get_local_string(string_id=30028), self.get_local_string(string_id=30029), xbmcgui.NOTIFICATION_ERROR, 5000)
163 def set_setting (self, key, value):
164 """Public interface for the addons setSetting method
169 Setting could be set or not
171 return self.addon.setSetting(key, value)
173 def get_credentials (self):
174 """Returns the users stored credentials
178 :obj:`dict` of :obj:`str`
179 The users stored account data
182 'email': self.addon.getSetting('email'),
183 'password': self.addon.getSetting('password')
186 def get_custom_library_settings (self):
187 """Returns the settings in regards to the custom library folder(s)
191 :obj:`dict` of :obj:`str`
192 The users library settings
195 'enablelibraryfolder': self.addon.getSetting('enablelibraryfolder'),
196 'customlibraryfolder': self.addon.getSetting('customlibraryfolder')
199 def get_ssl_verification_setting (self):
200 """Returns the setting that describes if we should verify the ssl transport when loading data
207 return self.addon.getSetting('ssl_verification') == 'true'
209 def set_main_menu_selection (self, type):
210 """Persist the chosen main menu entry in memory
217 self.win.setProperty('main_menu_selection', type)
219 def get_main_menu_selection (self):
220 """Gets the persisted chosen main menu entry from memory
225 The last chosen main menu entry
227 return self.win.getProperty('main_menu_selection')
229 def setup_memcache (self):
230 """Sets up the memory cache if not existant"""
231 cached_items = self.win.getProperty('memcache')
232 # no cache setup yet, create one
233 if len(cached_items) < 1:
234 self.win.setProperty('memcache', pickle.dumps({}))
236 def invalidate_memcache (self):
237 """Invalidates the memory cache"""
238 self.win.setProperty('memcache', pickle.dumps({}))
240 def has_cached_item (self, cache_id):
241 """Checks if the requested item is in memory cache
245 cache_id : :obj:`str`
246 ID of the cache entry
253 cached_items = pickle.loads(self.win.getProperty('memcache'))
254 return cache_id in cached_items.keys()
256 def get_cached_item (self, cache_id):
257 """Returns an item from the in memory cache
261 cache_id : :obj:`str`
262 ID of the cache entry
267 Contents of the requested cache item or none
269 cached_items = pickle.loads(self.win.getProperty('memcache'))
270 if self.has_cached_item(cache_id) != True:
272 return cached_items[cache_id]
274 def add_cached_item (self, cache_id, contents):
275 """Adds an item to the in memory cache
279 cache_id : :obj:`str`
280 ID of the cache entry
285 cached_items = pickle.loads(self.win.getProperty('memcache'))
286 cached_items.update({cache_id: contents})
287 self.win.setProperty('memcache', pickle.dumps(cached_items))
289 def build_profiles_listing (self, profiles, action, build_url):
290 """Builds the profiles list Kodi screen
294 profiles : :obj:`dict` of :obj:`str`
295 List of user profiles
298 Action paramter to build the subsequent routes
300 build_url : :obj:`fn`
301 Function to build the subsequent routes
308 for profile_id in profiles:
309 profile = profiles[profile_id]
310 url = build_url({'action': action, 'profile_id': profile_id})
311 li = xbmcgui.ListItem(label=profile['profileName'], iconImage=profile['avatar'])
312 li.setProperty('fanart_image', self.default_fanart)
313 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True)
314 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
315 xbmcplugin.endOfDirectory(self.plugin_handle)
318 def build_main_menu_listing (self, video_list_ids, user_list_order, actions, build_url):
319 """Builds the video lists (my list, continue watching, etc.) Kodi screen
323 video_list_ids : :obj:`dict` of :obj:`str`
326 user_list_order : :obj:`list` of :obj:`str`
327 Ordered user lists, to determine what should be displayed in the main menue
329 actions : :obj:`dict` of :obj:`str`
330 Dictionary of actions to build subsequent routes
332 build_url : :obj:`fn`
333 Function to build the subsequent routes
341 for category in user_list_order:
342 for video_list_id in video_list_ids['user']:
343 if video_list_ids['user'][video_list_id]['name'] == category:
344 label = video_list_ids['user'][video_list_id]['displayName']
345 if category == 'netflixOriginals':
346 label = label.capitalize()
347 li = xbmcgui.ListItem(label=label)
348 li.setProperty('fanart_image', self.default_fanart)
349 # determine action route
350 action = actions['default']
351 if category in actions.keys():
352 action = actions[category]
353 # determine if the item should be selected
354 preselect_items.append((False, True)[category == self.get_main_menu_selection()])
355 url = build_url({'action': action, 'video_list_id': video_list_id, 'type': category})
356 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True)
358 # add recommendations/genres as subfolders (save us some space on the home page)
360 'recommendations': self.get_local_string(30001),
361 'genres': self.get_local_string(30010)
363 for type in i18n_ids.keys():
364 # determine if the lists have contents
365 if len(video_list_ids[type]) > 0:
366 # determine action route
367 action = actions['default']
368 if type in actions.keys():
369 action = actions[type]
370 # determine if the item should be selected
371 preselect_items.append((False, True)[type == self.get_main_menu_selection()])
372 li_rec = xbmcgui.ListItem(label=i18n_ids[type])
373 li_rec.setProperty('fanart_image', self.default_fanart)
374 url_rec = build_url({'action': action, 'type': type})
375 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url_rec, listitem=li_rec, isFolder=True)
377 # add search as subfolder
378 action = actions['default']
379 if 'search' in actions.keys():
380 action = actions[type]
381 li_rec = xbmcgui.ListItem(label=self.get_local_string(30011))
382 li_rec.setProperty('fanart_image', self.default_fanart)
383 url_rec = build_url({'action': action, 'type': 'search'})
384 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url_rec, listitem=li_rec, isFolder=True)
387 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
388 xbmcplugin.endOfDirectory(self.plugin_handle)
390 # (re)select the previously selected main menu entry
392 for item in preselect_items:
394 preselected_list_item = idx if item else None
395 preselected_list_item = idx + 1 if self.get_main_menu_selection() == 'search' else preselected_list_item
396 if preselected_list_item != None:
397 xbmc.executebuiltin('ActivateWindowAndFocus(%s, %s)' % (str(self.win.getFocusId()), str(preselected_list_item)))
400 def build_video_listing (self, video_list, actions, type, build_url):
401 """Builds the video lists (my list, continue watching, etc.) contents Kodi screen
405 video_list_ids : :obj:`dict` of :obj:`str`
408 actions : :obj:`dict` of :obj:`str`
409 Dictionary of actions to build subsequent routes
412 None or 'queue' f.e. when it´s a special video lists
414 build_url : :obj:`fn`
415 Function to build the subsequent routes
422 for video_list_id in video_list:
423 video = video_list[video_list_id]
424 if type != 'queue' or (type == 'queue' and video['in_my_list'] == True):
425 li = xbmcgui.ListItem(label=video['title'])
426 # add some art to the item
427 li = self._generate_art_info(entry=video, li=li)
428 # it´s a show, so we need a subfolder & route (for seasons)
430 url = build_url({'action': actions[video['type']], 'show_id': video_list_id})
431 # lists can be mixed with shows & movies, therefor we need to check if its a movie, so play it right away
432 if video_list[video_list_id]['type'] == 'movie':
433 # it´s a movie, so we need no subfolder & a route to play it
435 # check maturity index, to determine if we need the adult pin
436 needs_pin = (True, False)[int(video['maturity']['level']) >= 1000]
437 url = build_url({'action': 'play_video', 'video_id': video_list_id, 'pin': needs_pin})
439 li = self._generate_entry_info(entry=video, li=li)
440 li = self._generate_context_menu_items(entry=video, li=li)
441 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=isFolder)
443 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
444 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_TITLE)
445 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_YEAR)
446 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_GENRE)
447 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LASTPLAYED)
448 xbmcplugin.endOfDirectory(self.plugin_handle)
451 def build_search_result_listing (self, video_list, actions, build_url):
452 """Builds the search results list Kodi screen
456 video_list : :obj:`dict` of :obj:`str`
457 List of videos or shows
459 actions : :obj:`dict` of :obj:`str`
460 Dictionary of actions to build subsequent routes
462 build_url : :obj:`fn`
463 Function to build the subsequent routes
470 return self.build_video_listing(video_list=video_list, actions=actions, type='search', build_url=build_url)
472 def build_no_seasons_available (self):
473 """Builds the season list screen if no seasons could be found
480 li = xbmcgui.ListItem(label=self.get_local_string(30012))
481 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url='', listitem=li, isFolder=False)
482 xbmcplugin.endOfDirectory(self.plugin_handle)
485 def build_no_search_results_available (self, build_url, action):
486 """Builds the search results screen if no matches could be found
491 Action paramter to build the subsequent routes
493 build_url : :obj:`fn`
494 Function to build the subsequent routes
501 li = xbmcgui.ListItem(label=self.get_local_string(30013))
502 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=build_url({'action': action}), listitem=li, isFolder=False)
503 xbmcplugin.endOfDirectory(self.plugin_handle)
506 def build_user_sub_listing (self, video_list_ids, type, action, build_url):
507 """Builds the video lists screen for user subfolders (genres & recommendations)
511 video_list_ids : :obj:`dict` of :obj:`str`
515 List type (genre or recommendation)
518 Action paramter to build the subsequent routes
520 build_url : :obj:`fn`
521 Function to build the subsequent routes
528 for video_list_id in video_list_ids:
529 li = xbmcgui.ListItem(video_list_ids[video_list_id]['displayName'])
530 li.setProperty('fanart_image', self.default_fanart)
531 url = build_url({'action': action, 'video_list_id': video_list_id})
532 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True)
534 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
535 xbmcplugin.endOfDirectory(self.plugin_handle)
538 def build_season_listing (self, seasons_sorted, season_list, build_url):
539 """Builds the season list screen for a show
543 seasons_sorted : :obj:`list` of :obj:`str`
544 Sorted season indexes
546 season_list : :obj:`dict` of :obj:`str`
547 List of season entries
549 build_url : :obj:`fn`
550 Function to build the subsequent routes
557 for index in seasons_sorted:
558 for season_id in season_list:
559 season = season_list[season_id]
560 if int(season['id']) == index:
561 li = xbmcgui.ListItem(label=season['text'])
562 # add some art to the item
563 li = self._generate_art_info(entry=season, li=li)
565 li = self._generate_entry_info(entry=season, li=li, base_info={'mediatype': 'season'})
566 li = self._generate_context_menu_items(entry=season, li=li)
567 url = build_url({'action': 'episode_list', 'season_id': season_id})
568 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True)
570 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE)
571 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_YEAR)
572 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
573 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LASTPLAYED)
574 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_TITLE)
575 xbmcplugin.endOfDirectory(self.plugin_handle)
578 def build_episode_listing (self, episodes_sorted, episode_list, build_url):
579 """Builds the episode list screen for a season of a show
583 episodes_sorted : :obj:`list` of :obj:`str`
584 Sorted episode indexes
586 episode_list : :obj:`dict` of :obj:`str`
587 List of episode entries
589 build_url : :obj:`fn`
590 Function to build the subsequent routes
597 for index in episodes_sorted:
598 for episode_id in episode_list:
599 episode = episode_list[episode_id]
600 if int(episode['episode']) == index:
601 li = xbmcgui.ListItem(label=episode['title'])
602 # add some art to the item
603 li = self._generate_art_info(entry=episode, li=li)
605 li = self._generate_entry_info(entry=episode, li=li, base_info={'mediatype': 'episode'})
606 li = self._generate_context_menu_items(entry=episode, li=li)
607 # check maturity index, to determine if we need the adult pin
608 needs_pin = (True, False)[int(episode['maturity']['rating']['maturityLevel']) >= 1000]
609 url = build_url({'action': 'play_video', 'video_id': episode_id, 'pin': needs_pin, 'start_offset': episode['bookmark']})
610 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=False)
612 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_EPISODE)
613 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE)
614 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_YEAR)
615 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
616 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LASTPLAYED)
617 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_TITLE)
618 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_DURATION)
619 xbmcplugin.endOfDirectory(self.plugin_handle)
622 def play_item (self, esn, video_id, start_offset=-1):
628 ESN needed for Widevine/Inputstream
630 video_id : :obj:`str`
631 ID of the video that should be played
633 start_offset : :obj:`str`
634 Offset to resume playback from (in seconds)
641 inputstream_addon = self.get_inputstream_addon()
642 if inputstream_addon == None:
643 self.show_missing_inputstream_addon_notification()
644 self.log(msg='Inputstream addon not found')
647 # inputstream addon properties
648 msl_service_url = 'http://localhost:' + str(self.addon.getSetting('msl_service_port'))
649 play_item = xbmcgui.ListItem(path=msl_service_url + '/manifest?id=' + video_id)
650 play_item.setProperty(inputstream_addon + '.license_type', 'com.widevine.alpha')
651 play_item.setProperty(inputstream_addon + '.manifest_type', 'mpd')
652 play_item.setProperty(inputstream_addon + '.license_key', msl_service_url + '/license?id=' + video_id + '||b{SSM}!b{SID}|')
653 play_item.setProperty(inputstream_addon + '.server_certificate', 'Cr0CCAMSEOVEukALwQ8307Y2+LVP+0MYh/HPkwUijgIwggEKAoIBAQDm875btoWUbGqQD8eAGuBlGY+Pxo8YF1LQR+Ex0pDONMet8EHslcZRBKNQ/09RZFTP0vrYimyYiBmk9GG+S0wB3CRITgweNE15cD33MQYyS3zpBd4z+sCJam2+jj1ZA4uijE2dxGC+gRBRnw9WoPyw7D8RuhGSJ95OEtzg3Ho+mEsxuE5xg9LM4+Zuro/9msz2bFgJUjQUVHo5j+k4qLWu4ObugFmc9DLIAohL58UR5k0XnvizulOHbMMxdzna9lwTw/4SALadEV/CZXBmswUtBgATDKNqjXwokohncpdsWSauH6vfS6FXwizQoZJ9TdjSGC60rUB2t+aYDm74cIuxAgMBAAE6EHRlc3QubmV0ZmxpeC5jb20SgAOE0y8yWw2Win6M2/bw7+aqVuQPwzS/YG5ySYvwCGQd0Dltr3hpik98WijUODUr6PxMn1ZYXOLo3eED6xYGM7Riza8XskRdCfF8xjj7L7/THPbixyn4mULsttSmWFhexzXnSeKqQHuoKmerqu0nu39iW3pcxDV/K7E6aaSr5ID0SCi7KRcL9BCUCz1g9c43sNj46BhMCWJSm0mx1XFDcoKZWhpj5FAgU4Q4e6f+S8eX39nf6D6SJRb4ap7Znzn7preIvmS93xWjm75I6UBVQGo6pn4qWNCgLYlGGCQCUm5tg566j+/g5jvYZkTJvbiZFwtjMW5njbSRwB3W4CrKoyxw4qsJNSaZRTKAvSjTKdqVDXV/U5HK7SaBA6iJ981/aforXbd2vZlRXO/2S+Maa2mHULzsD+S5l4/YGpSt7PnkCe25F+nAovtl/ogZgjMeEdFyd/9YMYjOS4krYmwp3yJ7m9ZzYCQ6I8RQN4x/yLlHG5RH/+WNLNUs6JAZ0fFdCmw=')
654 # TODO: Change when Kodi can handle/trnsfer defaults in hidden values in settings
655 #play_item.setProperty(inputstream_addon + '.server_certificate', self.addon.getSetting('msl_service_certificate'))
656 play_item.setProperty('inputstreamaddon', inputstream_addon)
658 # check if we have a bookmark e.g. start offset position
659 if int(start_offset) > 0:
660 play_item.setProperty('StartOffset', str(start_offset))
661 return xbmcplugin.setResolvedUrl(self.plugin_handle, True, listitem=play_item)
663 def _generate_art_info (self, entry, li):
664 """Adds the art info from an entry to a Kodi list item
668 entry : :obj:`dict` of :obj:`str`
669 Entry that should be turned into a list item
671 li : :obj:`XMBC.ListItem`
672 Kodi list item instance
677 Kodi list item instance
679 art = {'fanart': self.default_fanart}
680 if 'boxarts' in dict(entry).keys():
682 'poster': entry['boxarts']['big'],
683 'landscape': entry['boxarts']['big'],
684 'thumb': entry['boxarts']['small'],
685 'fanart': entry['boxarts']['big']
687 if 'interesting_moment' in dict(entry).keys():
689 'poster': entry['interesting_moment'],
690 'fanart': entry['interesting_moment']
692 if 'thumb' in dict(entry).keys():
693 art.update({'thumb': entry['thumb']})
694 if 'fanart' in dict(entry).keys():
695 art.update({'fanart': entry['fanart']})
696 if 'poster' in dict(entry).keys():
697 art.update({'poster': entry['poster']})
701 def _generate_entry_info (self, entry, li, base_info={}):
702 """Adds the item info from an entry to a Kodi list item
706 entry : :obj:`dict` of :obj:`str`
707 Entry that should be turned into a list item
709 li : :obj:`XMBC.ListItem`
710 Kodi list item instance
712 base_info : :obj:`dict` of :obj:`str`
713 Additional info that overrules the entry info
718 Kodi list item instance
721 entry_keys = entry.keys()
722 if 'cast' in entry_keys and len(entry['cast']) > 0:
723 infos.update({'cast': entry['cast']})
724 if 'creators' in entry_keys and len(entry['creators']) > 0:
725 infos.update({'writer': entry['creators'][0]})
726 if 'directors' in entry_keys and len(entry['directors']) > 0:
727 infos.update({'director': entry['directors'][0]})
728 if 'genres' in entry_keys and len(entry['genres']) > 0:
729 infos.update({'genre': entry['genres'][0]})
730 if 'maturity' in entry_keys:
731 if 'mpaa' in entry_keys:
732 infos.update({'mpaa': entry['mpaa']})
734 infos.update({'mpaa': str(entry['maturity']['board']) + '-' + str(entry['maturity']['value'])})
735 if 'rating' in entry_keys:
736 infos.update({'rating': int(entry['rating']) * 2})
737 if 'synopsis' in entry_keys:
738 infos.update({'plot': entry['synopsis']})
739 if 'plot' in entry_keys:
740 infos.update({'plot': entry['plot']})
741 if 'runtime' in entry_keys:
742 infos.update({'duration': entry['runtime']})
743 if 'duration' in entry_keys:
744 infos.update({'duration': entry['duration']})
745 if 'seasons_label' in entry_keys:
746 infos.update({'season': entry['seasons_label']})
747 if 'season' in entry_keys:
748 infos.update({'season': entry['season']})
749 if 'title' in entry_keys:
750 infos.update({'title': entry['title']})
751 if 'type' in entry_keys:
752 if entry['type'] == 'movie' or entry['type'] == 'episode':
753 li.setProperty('IsPlayable', 'true')
754 if 'mediatype' in entry_keys:
755 if entry['mediatype'] == 'movie' or entry['mediatype'] == 'episode':
756 li.setProperty('IsPlayable', 'true')
757 infos.update({'mediatype': entry['mediatype']})
758 if 'watched' in entry_keys:
759 infos.update({'playcount': (1, 0)[entry['watched']]})
760 if 'index' in entry_keys:
761 infos.update({'episode': entry['index']})
762 if 'episode' in entry_keys:
763 infos.update({'episode': entry['episode']})
764 if 'year' in entry_keys:
765 infos.update({'year': entry['year']})
766 if 'quality' in entry_keys:
767 quality = {'width': '960', 'height': '540'}
768 if entry['quality'] == '720':
769 quality = {'width': '1280', 'height': '720'}
770 if entry['quality'] == '1080':
771 quality = {'width': '1920', 'height': '1080'}
772 li.addStreamInfo('video', quality)
773 li.setInfo('video', infos)
776 def _generate_context_menu_items (self, entry, li):
777 """Adds context menue items to a Kodi list item
781 entry : :obj:`dict` of :obj:`str`
782 Entry that should be turned into a list item
784 li : :obj:`XMBC.ListItem`
785 Kodi list item instance
789 Kodi list item instance
793 entry_keys = entry.keys()
795 # action item templates
796 encoded_title = urllib.urlencode({'title': entry['title'].encode('utf-8')}) if 'title' in entry else ''
797 url_tmpl = 'XBMC.RunPlugin(' + self.base_url + '?action=%action%&id=' + str(entry['id']) + '&' + encoded_title + ')'
799 ['export_to_library', self.get_local_string(30018), 'export'],
800 ['remove_from_library', self.get_local_string(30030), 'remove'],
801 ['rate_on_netflix', self.get_local_string(30019), 'rating'],
802 ['remove_from_my_list', self.get_local_string(30020), 'remove_from_list'],
803 ['add_to_my_list', self.get_local_string(30021), 'add_to_list']
806 # build concrete action items
807 for action_item in actions:
808 action.update({action_item[0]: [action_item[1], url_tmpl.replace('%action%', action_item[2])]})
810 # add or remove the movie/show/season/episode from & to the users "My List"
811 if 'in_my_list' in entry_keys:
812 items.append(action['remove_from_my_list']) if entry['in_my_list'] else items.append(action['add_to_my_list'])
813 elif 'queue' in entry_keys:
814 items.append(action['remove_from_my_list']) if entry['queue'] else items.append(action['add_to_my_list'])
815 elif 'my_list' in entry_keys:
816 items.append(action['remove_from_my_list']) if entry['my_list'] else items.append(action['add_to_my_list'])
817 # rate the movie/show/season/episode on Netflix
818 items.append(action['rate_on_netflix'])
820 # add possibility to export this movie/show/season/episode to a static/local library (and to remove it)
821 if 'type' in entry_keys:
823 if entry['type'] == 'movie':
824 action_type = 'remove_from_library' if self.library.movie_exists(title=entry['title'], year=entry['year']) else 'export_to_library'
825 items.append(action[action_type])
827 if entry['type'] == 'show' and 'title' in entry_keys:
828 action_type = 'remove_from_library' if self.library.show_exists(title=entry['title']) else 'export_to_library'
829 items.append(action[action_type])
832 li.addContextMenuItems(items)
835 def log (self, msg, level=xbmc.LOGDEBUG):
836 """Adds a log entry to the Kodi log
841 Entry that should be turned into a list item
846 if isinstance(msg, unicode):
847 msg = msg.encode('utf-8')
848 xbmc.log('[%s] %s' % (self.plugin, msg.__str__()), level)
850 def get_local_string (self, string_id):
851 """Returns the localized version of a string
855 string_id : :obj:`int`
856 ID of the string that shoudl be fetched
861 Requested string or empty string
863 src = xbmc if string_id < 30000 else self.addon
864 locString = src.getLocalizedString(string_id)
865 if isinstance(locString, unicode):
866 locString = locString.encode('utf-8')
869 def get_inputstream_addon (self):
870 """Checks if the inputstream addon is installed & enabled.
871 Returns the type of the inputstream addon used or None if not found
876 Inputstream addon or None
878 type = 'inputstream.adaptive'
882 'method': 'Addons.GetAddonDetails',
885 'properties': ['enabled']
888 response = xbmc.executeJSONRPC(json.dumps(payload))
889 data = json.loads(response)
890 if not 'error' in data.keys():
891 if data['result']['addon']['enabled'] == True:
895 def set_library (self, library):
896 """Adds an instance of the Library class
900 library : :obj:`Library`
901 instance of the Library class
903 self.library = library