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_search_term_dialog (self):
65 """Asks the user for a term to query the netflix search for
72 dlg = xbmcgui.Dialog()
73 term = dlg.input(self.get_local_string(string_id=30003), type=xbmcgui.INPUT_ALPHANUM)
78 def show_add_to_library_title_dialog (self, original_title):
79 """Asks the user for an alternative title for the show/movie that gets exported to the local library
83 original_title : :obj:`str`
84 Original title of the show (as suggested by the addon)
91 dlg = xbmcgui.Dialog()
92 return dlg.input(heading=self.get_local_string(string_id=30031), defaultt=original_title, type=xbmcgui.INPUT_ALPHANUM)
94 def show_password_dialog (self):
95 """Asks the user for its Netflix password
102 dlg = xbmcgui.Dialog()
103 return dlg.input(self.get_local_string(string_id=30004), type=xbmcgui.INPUT_ALPHANUM)
105 def show_email_dialog (self):
106 """Asks the user for its Netflix account email
111 Netflix account email
113 dlg = xbmcgui.Dialog()
114 return dlg.input(self.get_local_string(string_id=30005), type=xbmcgui.INPUT_ALPHANUM)
116 def show_login_failed_notification (self):
117 """Shows notification that the login failed
124 dialog = xbmcgui.Dialog()
125 dialog.notification(self.get_local_string(string_id=30008), self.get_local_string(string_id=30009), xbmcgui.NOTIFICATION_ERROR, 5000)
128 def show_missing_inputstream_addon_notification (self):
129 """Shows notification that the inputstream addon couldn't be found
136 dialog = xbmcgui.Dialog()
137 dialog.notification(self.get_local_string(string_id=30028), self.get_local_string(string_id=30029), xbmcgui.NOTIFICATION_ERROR, 5000)
140 def set_setting (self, key, value):
141 """Public interface for the addons setSetting method
146 Setting could be set or not
148 return self.addon.setSetting(key, value)
150 def get_credentials (self):
151 """Returns the users stored credentials
155 :obj:`dict` of :obj:`str`
156 The users stored account data
159 'email': self.addon.getSetting('email'),
160 'password': self.addon.getSetting('password')
163 def get_custom_library_settings (self):
164 """Returns the settings in regards to the custom library folder(s)
168 :obj:`dict` of :obj:`str`
169 The users library settings
172 'enablelibraryfolder': self.addon.getSetting('enablelibraryfolder'),
173 'customlibraryfolder': self.addon.getSetting('customlibraryfolder')
176 def get_ssl_verification_setting (self):
177 """Returns the setting that describes if we should verify the ssl transport when loading data
184 return self.addon.getSetting('ssl_verification') == 'true'
186 def set_main_menu_selection (self, type):
187 """Persist the chosen main menu entry in memory
194 self.win.setProperty('main_menu_selection', type)
196 def get_main_menu_selection (self):
197 """Gets the persisted chosen main menu entry from memory
202 The last chosen main menu entry
204 return self.win.getProperty('main_menu_selection')
206 def setup_memcache (self):
207 """Sets up the memory cache if not existant"""
208 cached_items = self.win.getProperty('memcache')
209 # no cache setup yet, create one
210 if len(cached_items) < 1:
211 self.win.setProperty('memcache', pickle.dumps({}))
213 def invalidate_memcache (self):
214 """Invalidates the memory cache"""
215 self.win.setProperty('memcache', pickle.dumps({}))
217 def has_cached_item (self, cache_id):
218 """Checks if the requested item is in memory cache
222 cache_id : :obj:`str`
223 ID of the cache entry
230 cached_items = pickle.loads(self.win.getProperty('memcache'))
231 return cache_id in cached_items.keys()
233 def get_cached_item (self, cache_id):
234 """Returns an item from the in memory cache
238 cache_id : :obj:`str`
239 ID of the cache entry
244 Contents of the requested cache item or none
246 cached_items = pickle.loads(self.win.getProperty('memcache'))
247 if self.has_cached_item(cache_id) != True:
249 return cached_items[cache_id]
251 def add_cached_item (self, cache_id, contents):
252 """Adds an item to the in memory cache
256 cache_id : :obj:`str`
257 ID of the cache entry
262 cached_items = pickle.loads(self.win.getProperty('memcache'))
263 cached_items.update({cache_id: contents})
264 self.win.setProperty('memcache', pickle.dumps(cached_items))
266 def build_profiles_listing (self, profiles, action, build_url):
267 """Builds the profiles list Kodi screen
271 profiles : :obj:`dict` of :obj:`str`
272 List of user profiles
275 Action paramter to build the subsequent routes
277 build_url : :obj:`fn`
278 Function to build the subsequent routes
285 for profile_id in profiles:
286 profile = profiles[profile_id]
287 url = build_url({'action': action, 'profile_id': profile_id})
288 li = xbmcgui.ListItem(label=profile['profileName'], iconImage=profile['avatar'])
289 li.setProperty('fanart_image', self.default_fanart)
290 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True)
291 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
292 xbmcplugin.endOfDirectory(self.plugin_handle)
295 def build_main_menu_listing (self, video_list_ids, user_list_order, actions, build_url):
296 """Builds the video lists (my list, continue watching, etc.) Kodi screen
300 video_list_ids : :obj:`dict` of :obj:`str`
303 user_list_order : :obj:`list` of :obj:`str`
304 Ordered user lists, to determine what should be displayed in the main menue
306 actions : :obj:`dict` of :obj:`str`
307 Dictionary of actions to build subsequent routes
309 build_url : :obj:`fn`
310 Function to build the subsequent routes
318 for category in user_list_order:
319 for video_list_id in video_list_ids['user']:
320 if video_list_ids['user'][video_list_id]['name'] == category:
321 label = video_list_ids['user'][video_list_id]['displayName']
322 if category == 'netflixOriginals':
323 label = label.capitalize()
324 li = xbmcgui.ListItem(label=label)
325 li.setProperty('fanart_image', self.default_fanart)
326 # determine action route
327 action = actions['default']
328 if category in actions.keys():
329 action = actions[category]
330 # determine if the item should be selected
331 preselect_items.append((False, True)[category == self.get_main_menu_selection()])
332 url = build_url({'action': action, 'video_list_id': video_list_id, 'type': category})
333 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True)
335 # add recommendations/genres as subfolders (save us some space on the home page)
337 'recommendations': self.get_local_string(30001),
338 'genres': self.get_local_string(30010)
340 for type in i18n_ids.keys():
341 # determine if the lists have contents
342 if len(video_list_ids[type]) > 0:
343 # determine action route
344 action = actions['default']
345 if type in actions.keys():
346 action = actions[type]
347 # determine if the item should be selected
348 preselect_items.append((False, True)[type == self.get_main_menu_selection()])
349 li_rec = xbmcgui.ListItem(label=i18n_ids[type])
350 li_rec.setProperty('fanart_image', self.default_fanart)
351 url_rec = build_url({'action': action, 'type': type})
352 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url_rec, listitem=li_rec, isFolder=True)
354 # add search as subfolder
355 action = actions['default']
356 if 'search' in actions.keys():
357 action = actions[type]
358 li_rec = xbmcgui.ListItem(label=self.get_local_string(30011))
359 li_rec.setProperty('fanart_image', self.default_fanart)
360 url_rec = build_url({'action': action, 'type': 'search'})
361 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url_rec, listitem=li_rec, isFolder=True)
364 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
365 xbmcplugin.endOfDirectory(self.plugin_handle)
367 # (re)select the previously selected main menu entry
369 for item in preselect_items:
371 preselected_list_item = idx if item else None
372 preselected_list_item = idx + 1 if self.get_main_menu_selection() == 'search' else preselected_list_item
373 if preselected_list_item != None:
374 xbmc.executebuiltin('ActivateWindowAndFocus(%s, %s)' % (str(self.win.getFocusId()), str(preselected_list_item)))
377 def build_video_listing (self, video_list, actions, type, build_url):
378 """Builds the video lists (my list, continue watching, etc.) contents Kodi screen
382 video_list_ids : :obj:`dict` of :obj:`str`
385 actions : :obj:`dict` of :obj:`str`
386 Dictionary of actions to build subsequent routes
389 None or 'queue' f.e. when it´s a special video lists
391 build_url : :obj:`fn`
392 Function to build the subsequent routes
399 for video_list_id in video_list:
400 video = video_list[video_list_id]
401 if type != 'queue' or (type == 'queue' and video['in_my_list'] == True):
402 li = xbmcgui.ListItem(label=video['title'])
403 # add some art to the item
404 li = self._generate_art_info(entry=video, li=li)
405 # it´s a show, so we need a subfolder & route (for seasons)
407 url = build_url({'action': actions[video['type']], 'show_id': video_list_id})
408 # lists can be mixed with shows & movies, therefor we need to check if its a movie, so play it right away
409 if video_list[video_list_id]['type'] == 'movie':
410 # it´s a movie, so we need no subfolder & a route to play it
412 url = build_url({'action': 'play_video', 'video_id': video_list_id})
414 li = self._generate_entry_info(entry=video, li=li)
415 li = self._generate_context_menu_items(entry=video, li=li)
416 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=isFolder)
418 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
419 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_TITLE)
420 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_YEAR)
421 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_GENRE)
422 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LASTPLAYED)
423 xbmcplugin.endOfDirectory(self.plugin_handle)
426 def build_search_result_listing (self, video_list, actions, build_url):
427 """Builds the search results list Kodi screen
431 video_list : :obj:`dict` of :obj:`str`
432 List of videos or shows
434 actions : :obj:`dict` of :obj:`str`
435 Dictionary of actions to build subsequent routes
437 build_url : :obj:`fn`
438 Function to build the subsequent routes
445 return self.build_video_listing(video_list=video_list, actions=actions, type='search', build_url=build_url)
447 def build_no_seasons_available (self):
448 """Builds the season list screen if no seasons could be found
455 li = xbmcgui.ListItem(label=self.get_local_string(30012))
456 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url='', listitem=li, isFolder=False)
457 xbmcplugin.endOfDirectory(self.plugin_handle)
460 def build_no_search_results_available (self, build_url, action):
461 """Builds the search results screen if no matches could be found
466 Action paramter to build the subsequent routes
468 build_url : :obj:`fn`
469 Function to build the subsequent routes
476 li = xbmcgui.ListItem(label=self.get_local_string(30013))
477 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=build_url({'action': action}), listitem=li, isFolder=False)
478 xbmcplugin.endOfDirectory(self.plugin_handle)
481 def build_user_sub_listing (self, video_list_ids, type, action, build_url):
482 """Builds the video lists screen for user subfolders (genres & recommendations)
486 video_list_ids : :obj:`dict` of :obj:`str`
490 List type (genre or recommendation)
493 Action paramter to build the subsequent routes
495 build_url : :obj:`fn`
496 Function to build the subsequent routes
503 for video_list_id in video_list_ids:
504 li = xbmcgui.ListItem(video_list_ids[video_list_id]['displayName'])
505 li.setProperty('fanart_image', self.default_fanart)
506 url = build_url({'action': action, 'video_list_id': video_list_id})
507 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True)
509 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
510 xbmcplugin.endOfDirectory(self.plugin_handle)
513 def build_season_listing (self, seasons_sorted, season_list, build_url):
514 """Builds the season list screen for a show
518 seasons_sorted : :obj:`list` of :obj:`str`
519 Sorted season indexes
521 season_list : :obj:`dict` of :obj:`str`
522 List of season entries
524 build_url : :obj:`fn`
525 Function to build the subsequent routes
532 for index in seasons_sorted:
533 for season_id in season_list:
534 season = season_list[season_id]
535 if int(season['idx']) == index:
536 li = xbmcgui.ListItem(label=season['text'])
537 # add some art to the item
538 li = self._generate_art_info(entry=season, li=li)
540 li = self._generate_entry_info(entry=season, li=li, base_info={'mediatype': 'season'})
541 li = self._generate_context_menu_items(entry=season, li=li)
542 url = build_url({'action': 'episode_list', 'season_id': season_id})
543 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True)
545 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE)
546 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_YEAR)
547 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
548 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LASTPLAYED)
549 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_TITLE)
550 xbmcplugin.endOfDirectory(self.plugin_handle)
553 def build_episode_listing (self, episodes_sorted, episode_list, build_url):
554 """Builds the episode list screen for a season of a show
558 episodes_sorted : :obj:`list` of :obj:`str`
559 Sorted episode indexes
561 episode_list : :obj:`dict` of :obj:`str`
562 List of episode entries
564 build_url : :obj:`fn`
565 Function to build the subsequent routes
572 for index in episodes_sorted:
573 for episode_id in episode_list:
574 episode = episode_list[episode_id]
575 if int(episode['episode']) == index:
576 li = xbmcgui.ListItem(label=episode['title'])
577 # add some art to the item
578 li = self._generate_art_info(entry=episode, li=li)
580 li = self._generate_entry_info(entry=episode, li=li, base_info={'mediatype': 'episode'})
581 li = self._generate_context_menu_items(entry=episode, li=li)
582 url = build_url({'action': 'play_video', 'video_id': episode_id, 'start_offset': episode['bookmark']})
583 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=False)
585 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_EPISODE)
586 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE)
587 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_YEAR)
588 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
589 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LASTPLAYED)
590 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_TITLE)
591 xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_DURATION)
592 xbmcplugin.endOfDirectory(self.plugin_handle)
595 def play_item (self, esn, video_id, start_offset=-1):
601 ESN needed for Widevine/Inputstream
603 video_id : :obj:`str`
604 ID of the video that should be played
606 start_offset : :obj:`str`
607 Offset to resume playback from (in seconds)
614 inputstream_addon = self.get_inputstream_addon()
615 if inputstream_addon == None:
616 self.show_missing_inputstream_addon_notification()
617 self.log(msg='Inputstream addon not found')
620 # inputstream addon properties
621 msl_service_url = 'http://localhost:' + str(self.addon.getSetting('msl_service_port'))
622 play_item = xbmcgui.ListItem(path=msl_service_url + '/manifest?id=' + video_id)
623 play_item.setProperty(inputstream_addon + '.license_type', 'com.widevine.alpha')
624 play_item.setProperty(inputstream_addon + '.manifest_type', 'mpd')
625 play_item.setProperty(inputstream_addon + '.license_key', msl_service_url + '/license?id=' + video_id + '||b{SSM}!b{SID}|')
626 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=')
627 # TODO: Change when Kodi can handle/trnsfer defaults in hidden values in settings
628 #play_item.setProperty(inputstream_addon + '.server_certificate', self.addon.getSetting('msl_service_certificate'))
629 play_item.setProperty('inputstreamaddon', inputstream_addon)
631 # check if we have a bookmark e.g. start offset position
632 if int(start_offset) > 0:
633 play_item.setProperty('StartOffset', str(start_offset) + '.0')
634 return xbmcplugin.setResolvedUrl(self.plugin_handle, True, listitem=play_item)
636 def _generate_art_info (self, entry, li):
637 """Adds the art info from an entry to a Kodi list item
641 entry : :obj:`dict` of :obj:`str`
642 Entry that should be turned into a list item
644 li : :obj:`XMBC.ListItem`
645 Kodi list item instance
650 Kodi list item instance
652 art = {'fanart': self.default_fanart}
653 if 'boxarts' in dict(entry).keys():
655 'poster': entry['boxarts']['big'],
656 'landscape': entry['boxarts']['big'],
657 'thumb': entry['boxarts']['small'],
658 'fanart': entry['boxarts']['big']
660 if 'interesting_moment' in dict(entry).keys():
662 'poster': entry['interesting_moment'],
663 'fanart': entry['interesting_moment']
665 if 'thumb' in dict(entry).keys():
666 art.update({'thumb': entry['thumb']})
667 if 'fanart' in dict(entry).keys():
668 art.update({'fanart': entry['fanart']})
669 if 'poster' in dict(entry).keys():
670 art.update({'poster': entry['poster']})
674 def _generate_entry_info (self, entry, li, base_info={}):
675 """Adds the item info from an entry to a Kodi list item
679 entry : :obj:`dict` of :obj:`str`
680 Entry that should be turned into a list item
682 li : :obj:`XMBC.ListItem`
683 Kodi list item instance
685 base_info : :obj:`dict` of :obj:`str`
686 Additional info that overrules the entry info
691 Kodi list item instance
694 entry_keys = entry.keys()
695 if 'cast' in entry_keys and len(entry['cast']) > 0:
696 infos.update({'cast': entry['cast']})
697 if 'creators' in entry_keys and len(entry['creators']) > 0:
698 infos.update({'writer': entry['creators'][0]})
699 if 'directors' in entry_keys and len(entry['directors']) > 0:
700 infos.update({'director': entry['directors'][0]})
701 if 'genres' in entry_keys and len(entry['genres']) > 0:
702 infos.update({'genre': entry['genres'][0]})
703 if 'maturity' in entry_keys:
704 if 'mpaa' in entry_keys:
705 infos.update({'mpaa': entry['mpaa']})
707 infos.update({'mpaa': str(entry['maturity']['board']) + '-' + str(entry['maturity']['value'])})
708 if 'rating' in entry_keys:
709 infos.update({'rating': int(entry['rating']) * 2})
710 if 'synopsis' in entry_keys:
711 infos.update({'plot': entry['synopsis']})
712 if 'plot' in entry_keys:
713 infos.update({'plot': entry['plot']})
714 if 'runtime' in entry_keys:
715 infos.update({'duration': entry['runtime']})
716 if 'duration' in entry_keys:
717 infos.update({'duration': entry['duration']})
718 if 'seasons_label' in entry_keys:
719 infos.update({'season': entry['seasons_label']})
720 if 'season' in entry_keys:
721 infos.update({'season': entry['season']})
722 if 'title' in entry_keys:
723 infos.update({'title': entry['title']})
724 if 'type' in entry_keys:
725 if entry['type'] == 'movie' or entry['type'] == 'episode':
726 li.setProperty('IsPlayable', 'true')
727 if 'mediatype' in entry_keys:
728 if entry['mediatype'] == 'movie' or entry['mediatype'] == 'episode':
729 li.setProperty('IsPlayable', 'true')
730 infos.update({'mediatype': entry['mediatype']})
731 if 'watched' in entry_keys:
732 infos.update({'playcount': (1, 0)[entry['watched']]})
733 if 'index' in entry_keys:
734 infos.update({'episode': entry['index']})
735 if 'episode' in entry_keys:
736 infos.update({'episode': entry['episode']})
737 if 'year' in entry_keys:
738 infos.update({'year': entry['year']})
739 if 'quality' in entry_keys:
740 quality = {'width': '960', 'height': '540'}
741 if entry['quality'] == '720':
742 quality = {'width': '1280', 'height': '720'}
743 if entry['quality'] == '1080':
744 quality = {'width': '1920', 'height': '1080'}
745 li.addStreamInfo('video', quality)
746 li.setInfo('video', infos)
749 def _generate_context_menu_items (self, entry, li):
750 """Adds context menue items to a Kodi list item
754 entry : :obj:`dict` of :obj:`str`
755 Entry that should be turned into a list item
757 li : :obj:`XMBC.ListItem`
758 Kodi list item instance
762 Kodi list item instance
766 entry_keys = entry.keys()
768 # action item templates
769 encoded_title = urllib.urlencode({'title': entry['title'].encode('utf-8')}) if 'title' in entry else ''
770 url_tmpl = 'XBMC.RunPlugin(' + self.base_url + '?action=%action%&id=' + str(entry['id']) + '&' + encoded_title + ')'
772 ['export_to_library', self.get_local_string(30018), 'export'],
773 ['remove_from_library', self.get_local_string(30030), 'remove'],
774 ['rate_on_netflix', self.get_local_string(30019), 'rating'],
775 ['remove_from_my_list', self.get_local_string(30020), 'remove_from_list'],
776 ['add_to_my_list', self.get_local_string(30021), 'add_to_list']
779 # build concrete action items
780 for action_item in actions:
781 action.update({action_item[0]: [action_item[1], url_tmpl.replace('%action%', action_item[2])]})
783 # add or remove the movie/show/season/episode from & to the users "My List"
784 if 'in_my_list' in entry_keys:
785 items.append(action['remove_from_my_list']) if entry['in_my_list'] else items.append(action['add_to_my_list'])
786 elif 'queue' in entry_keys:
787 items.append(action['remove_from_my_list']) if entry['queue'] else items.append(action['add_to_my_list'])
788 elif 'my_list' in entry_keys:
789 items.append(action['remove_from_my_list']) if entry['my_list'] else items.append(action['add_to_my_list'])
790 # rate the movie/show/season/episode on Netflix
791 items.append(action['rate_on_netflix'])
793 # add possibility to export this movie/show/season/episode to a static/local library (and to remove it)
794 if 'type' in entry_keys:
796 if entry['type'] == 'movie':
797 action_type = 'remove_from_library' if self.library.movie_exists(title=entry['title'], year=entry['year']) else 'export_to_library'
798 items.append(action[action_type])
800 if entry['type'] == 'show' and 'title' in entry_keys:
801 action_type = 'remove_from_library' if self.library.show_exists(title=entry['title']) else 'export_to_library'
802 items.append(action[action_type])
805 li.addContextMenuItems(items)
808 def log (self, msg, level=xbmc.LOGDEBUG):
809 """Adds a log entry to the Kodi log
814 Entry that should be turned into a list item
819 if isinstance(msg, unicode):
820 msg = msg.encode('utf-8')
821 xbmc.log('[%s] %s' % (self.plugin, msg.__str__()), level)
823 def get_local_string (self, string_id):
824 """Returns the localized version of a string
828 string_id : :obj:`int`
829 ID of the string that shoudl be fetched
834 Requested string or empty string
836 src = xbmc if string_id < 30000 else self.addon
837 locString = src.getLocalizedString(string_id)
838 if isinstance(locString, unicode):
839 locString = locString.encode('utf-8')
842 def get_inputstream_addon (self):
843 """Checks if the inputstream addon is installed & enabled.
844 Returns the type of the inputstream addon used or None if not found
849 Inputstream addon or None
851 type = 'inputstream.adaptive'
855 'method': 'Addons.GetAddonDetails',
858 'properties': ['enabled']
861 response = xbmc.executeJSONRPC(json.dumps(payload))
862 data = json.loads(response)
863 if not 'error' in data.keys():
864 if data['result']['addon']['enabled'] == True:
868 def set_library (self, library):
869 """Adds an instance of the Library class
873 library : :obj:`Library`
874 instance of the Library class
876 self.library = library