feat(core): Adds library export for movies & shows, fixes for search, fixes for displ...
[plugin.video.netflix.git] / resources / lib / KodiHelper.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # Module: KodiHelper
4 # Created on: 13.01.2017
5
6 import os
7 import urllib
8 import xbmcplugin
9 import xbmcgui
10 import xbmcaddon
11 import xbmc
12 import json
13 try:
14    import cPickle as pickle
15 except:
16    import pickle
17
18 class KodiHelper:
19     """Consumes all the configuration data from Kodi as well as turns data into lists of folders and videos"""
20
21     msl_service_server_url = 'http://localhost:%PORT%'
22     """str: MSL service url"""
23
24     def __init__ (self, plugin_handle, base_url):
25         """Fetches all needed info from Kodi & configures the baseline of the plugin
26
27         Parameters
28         ----------
29         plugin_handle : :obj:`int`
30             Plugin handle
31
32         base_url : :obj:`str`
33             Plugin base url
34         """
35         self.plugin_handle = plugin_handle
36         self.base_url = base_url
37         self.addon = xbmcaddon.Addon()
38         self.plugin = self.addon.getAddonInfo('name')
39         self.base_data_path = xbmc.translatePath(self.addon.getAddonInfo('profile'))
40         self.home_path = xbmc.translatePath('special://home')
41         self.plugin_path = self.addon.getAddonInfo('path')
42         self.cookie_path = self.base_data_path + 'COOKIE'
43         self.data_path = self.base_data_path + 'DATA'
44         self.config_path = os.path.join(self.base_data_path, 'config')
45         self.verb_log = self.addon.getSetting('logging') == 'true'
46         self.default_fanart = self.addon.getAddonInfo('fanart')
47         self.win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
48         self.library = None
49         self.setup_memcache()
50
51     def refresh (self):
52         """Refrsh the current list"""
53         return xbmc.executebuiltin('Container.Refresh')
54
55     def show_rating_dialog (self):
56         """Asks the user for a movie rating
57
58         Returns
59         -------
60         :obj:`int`
61             Movie rating between 0 & 10
62         """
63         dlg = xbmcgui.Dialog()
64         return dlg.numeric(heading=self.get_local_string(string_id=30019) + ' ' + self.get_local_string(string_id=30022), type=0)
65
66     def show_adult_pin_dialog (self):
67         """Asks the user for the adult pin
68
69         Returns
70         -------
71         :obj:`int`
72             4 digit adult pin needed for adult movies
73         """
74         dlg = xbmcgui.Dialog()
75         return dlg.input(self.get_local_string(string_id=30002), type=xbmcgui.INPUT_NUMERIC)
76
77     def show_search_term_dialog (self):
78         """Asks the user for a term to query the netflix search for
79
80         Returns
81         -------
82         :obj:`str`
83             Term to search for
84         """
85         dlg = xbmcgui.Dialog()
86         term = dlg.input(self.get_local_string(string_id=30003), type=xbmcgui.INPUT_ALPHANUM)
87         if len(term) == 0:
88             term = ' '
89         return term
90
91     def show_add_to_library_title_dialog (self, original_title):
92         """Asks the user for an alternative title for the show/movie that gets exported to the local library
93
94         Parameters
95         ----------
96         original_title : :obj:`str`
97             Original title of the show (as suggested by the addon)
98
99         Returns
100         -------
101         :obj:`str`
102             Title to persist
103         """
104         dlg = xbmcgui.Dialog()
105         return dlg.input(heading=self.get_local_string(string_id=30031), defaultt=original_title, type=xbmcgui.INPUT_ALPHANUM)
106
107     def show_password_dialog (self):
108         """Asks the user for its Netflix password
109
110         Returns
111         -------
112         :obj:`str`
113             Netflix password
114         """
115         dlg = xbmcgui.Dialog()
116         return dlg.input(self.get_local_string(string_id=30004), type=xbmcgui.INPUT_ALPHANUM)
117
118     def show_email_dialog (self):
119         """Asks the user for its Netflix account email
120
121         Returns
122         -------
123         term : :obj:`str`
124             Netflix account email
125         """
126         dlg = xbmcgui.Dialog()
127         return dlg.input(self.get_local_string(string_id=30005), type=xbmcgui.INPUT_ALPHANUM)
128
129     def show_wrong_adult_pin_notification (self):
130         """Shows notification that a wrong adult pin was given
131
132         Returns
133         -------
134         bool
135             Dialog shown
136         """
137         dialog = xbmcgui.Dialog()
138         dialog.notification(self.get_local_string(string_id=30006), self.get_local_string(string_id=30007), xbmcgui.NOTIFICATION_ERROR, 5000)
139         return True
140
141     def show_login_failed_notification (self):
142         """Shows notification that the login failed
143
144         Returns
145         -------
146         bool
147             Dialog shown
148         """
149         dialog = xbmcgui.Dialog()
150         dialog.notification(self.get_local_string(string_id=30008), self.get_local_string(string_id=30009), xbmcgui.NOTIFICATION_ERROR, 5000)
151         return True
152
153     def show_missing_inputstream_addon_notification (self):
154         """Shows notification that the inputstream addon couldn't be found
155
156         Returns
157         -------
158         bool
159             Dialog shown
160         """
161         dialog = xbmcgui.Dialog()
162         dialog.notification(self.get_local_string(string_id=30028), self.get_local_string(string_id=30029), xbmcgui.NOTIFICATION_ERROR, 5000)
163         return True
164
165     def set_setting (self, key, value):
166         """Public interface for the addons setSetting method
167
168         Returns
169         -------
170         bool
171             Setting could be set or not
172         """
173         return self.addon.setSetting(key, value)
174
175     def get_credentials (self):
176         """Returns the users stored credentials
177
178         Returns
179         -------
180         :obj:`dict` of :obj:`str`
181             The users stored account data
182         """
183         return {
184             'email': self.addon.getSetting('email'),
185             'password': self.addon.getSetting('password')
186         }
187
188     def get_custom_library_settings (self):
189         """Returns the settings in regards to the custom library folder(s)
190
191         Returns
192         -------
193         :obj:`dict` of :obj:`str`
194             The users library settings
195         """
196         return {
197             'enablelibraryfolder': self.addon.getSetting('enablelibraryfolder'),
198             'customlibraryfolder': self.addon.getSetting('customlibraryfolder')
199         }
200
201     def get_ssl_verification_setting (self):
202         """Returns the setting that describes if we should verify the ssl transport when loading data
203
204         Returns
205         -------
206         bool
207             Verify or not
208         """
209         return self.addon.getSetting('ssl_verification') == 'true'
210
211     def set_main_menu_selection (self, type):
212         """Persist the chosen main menu entry in memory
213
214         Parameters
215         ----------
216         type : :obj:`str`
217             Selected menu item
218         """
219         self.win.setProperty('main_menu_selection', type)
220
221     def get_main_menu_selection (self):
222         """Gets the persisted chosen main menu entry from memory
223
224         Returns
225         -------
226         :obj:`str`
227             The last chosen main menu entry
228         """
229         return self.win.getProperty('main_menu_selection')
230
231     def setup_memcache (self):
232         """Sets up the memory cache if not existant"""
233         cached_items = self.win.getProperty('memcache')
234         # no cache setup yet, create one
235         if len(cached_items) < 1:
236             self.win.setProperty('memcache', pickle.dumps({}))
237
238     def invalidate_memcache (self):
239         """Invalidates the memory cache"""
240         self.win.setProperty('memcache', pickle.dumps({}))
241
242     def has_cached_item (self, cache_id):
243         """Checks if the requested item is in memory cache
244
245         Parameters
246         ----------
247         cache_id : :obj:`str`
248             ID of the cache entry
249
250         Returns
251         -------
252         bool
253             Item is cached
254         """
255         cached_items = pickle.loads(self.win.getProperty('memcache'))
256         return cache_id in cached_items.keys()
257
258     def get_cached_item (self, cache_id):
259         """Returns an item from the in memory cache
260
261         Parameters
262         ----------
263         cache_id : :obj:`str`
264             ID of the cache entry
265
266         Returns
267         -------
268         mixed
269             Contents of the requested cache item or none
270         """
271         cached_items = pickle.loads(self.win.getProperty('memcache'))
272         if self.has_cached_item(cache_id) != True:
273             return None
274         return cached_items[cache_id]
275
276     def add_cached_item (self, cache_id, contents):
277         """Adds an item to the in memory cache
278
279         Parameters
280         ----------
281         cache_id : :obj:`str`
282             ID of the cache entry
283
284         contents : mixed
285             Cache entry contents
286         """
287         cached_items = pickle.loads(self.win.getProperty('memcache'))
288         cached_items.update({cache_id: contents})
289         self.win.setProperty('memcache', pickle.dumps(cached_items))
290
291     def build_profiles_listing (self, profiles, action, build_url):
292         """Builds the profiles list Kodi screen
293
294         Parameters
295         ----------
296         profiles : :obj:`dict` of :obj:`str`
297             List of user profiles
298
299         action : :obj:`str`
300             Action paramter to build the subsequent routes
301
302         build_url : :obj:`fn`
303             Function to build the subsequent routes
304
305         Returns
306         -------
307         bool
308             List could be build
309         """
310         for profile_id in profiles:
311             profile = profiles[profile_id]
312             url = build_url({'action': action, 'profile_id': profile_id})
313             li = xbmcgui.ListItem(label=profile['profileName'], iconImage=profile['avatar'])
314             li.setProperty('fanart_image', self.default_fanart)
315             xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True)
316             xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
317         xbmcplugin.endOfDirectory(self.plugin_handle)
318         return True
319
320     def build_main_menu_listing (self, video_list_ids, user_list_order, actions, build_url):
321         """Builds the video lists (my list, continue watching, etc.) Kodi screen
322
323         Parameters
324         ----------
325         video_list_ids : :obj:`dict` of :obj:`str`
326             List of video lists
327
328         user_list_order : :obj:`list` of :obj:`str`
329             Ordered user lists, to determine what should be displayed in the main menue
330
331         actions : :obj:`dict` of :obj:`str`
332             Dictionary of actions to build subsequent routes
333
334         build_url : :obj:`fn`
335             Function to build the subsequent routes
336
337         Returns
338         -------
339         bool
340             List could be build
341         """
342         preselect_items = []
343         for category in user_list_order:
344             for video_list_id in video_list_ids['user']:
345                 if video_list_ids['user'][video_list_id]['name'] == category:
346                     label = video_list_ids['user'][video_list_id]['displayName']
347                     if category == 'netflixOriginals':
348                         label = label.capitalize()
349                     li = xbmcgui.ListItem(label=label)
350                     li.setProperty('fanart_image', self.default_fanart)
351                     # determine action route
352                     action = actions['default']
353                     if category in actions.keys():
354                         action = actions[category]
355                     # determine if the item should be selected
356                     preselect_items.append((False, True)[category == self.get_main_menu_selection()])
357                     url = build_url({'action': action, 'video_list_id': video_list_id, 'type': category})
358                     xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True)
359
360         # add recommendations/genres as subfolders (save us some space on the home page)
361         i18n_ids = {
362             'recommendations': self.get_local_string(30001),
363             'genres': self.get_local_string(30010)
364         }
365         for type in i18n_ids.keys():
366             # determine if the lists have contents
367             if len(video_list_ids[type]) > 0:
368                 # determine action route
369                 action = actions['default']
370                 if type in actions.keys():
371                     action = actions[type]
372                 # determine if the item should be selected
373                 preselect_items.append((False, True)[type == self.get_main_menu_selection()])
374                 li_rec = xbmcgui.ListItem(label=i18n_ids[type])
375                 li_rec.setProperty('fanart_image', self.default_fanart)
376                 url_rec = build_url({'action': action, 'type': type})
377                 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url_rec, listitem=li_rec, isFolder=True)
378
379         # add search as subfolder
380         action = actions['default']
381         if 'search' in actions.keys():
382             action = actions[type]
383         li_rec = xbmcgui.ListItem(label=self.get_local_string(30011))
384         li_rec.setProperty('fanart_image', self.default_fanart)
385         url_rec = build_url({'action': action, 'type': 'search'})
386         xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url_rec, listitem=li_rec, isFolder=True)
387
388         # no srting & close
389         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
390         xbmcplugin.endOfDirectory(self.plugin_handle)
391
392         # (re)select the previously selected main menu entry
393         idx = 1
394         for item in preselect_items:
395             idx += 1
396             preselected_list_item = idx if item else None
397         preselected_list_item = idx + 1 if self.get_main_menu_selection() == 'search' else preselected_list_item
398         if preselected_list_item != None:
399             xbmc.executebuiltin('ActivateWindowAndFocus(%s, %s)' % (str(self.win.getFocusId()), str(preselected_list_item)))
400         return True
401
402     def build_video_listing (self, video_list, actions, type, build_url):
403         """Builds the video lists (my list, continue watching, etc.) contents Kodi screen
404
405         Parameters
406         ----------
407         video_list_ids : :obj:`dict` of :obj:`str`
408             List of video lists
409
410         actions : :obj:`dict` of :obj:`str`
411             Dictionary of actions to build subsequent routes
412
413         type : :obj:`str`
414             None or 'queue' f.e. when it´s a special video lists
415
416         build_url : :obj:`fn`
417             Function to build the subsequent routes
418
419         Returns
420         -------
421         bool
422             List could be build
423         """
424         for video_list_id in video_list:
425             video = video_list[video_list_id]
426             if type != 'queue' or (type == 'queue' and video['in_my_list'] == True):
427                 li = xbmcgui.ListItem(label=video['title'])
428                 # add some art to the item
429                 li = self._generate_art_info(entry=video, li=li)
430                 # it´s a show, so we need a subfolder & route (for seasons)
431                 isFolder = True
432                 url = build_url({'action': actions[video['type']], 'show_id': video_list_id})
433                 # lists can be mixed with shows & movies, therefor we need to check if its a movie, so play it right away
434                 if video_list[video_list_id]['type'] == 'movie':
435                     # it´s a movie, so we need no subfolder & a route to play it
436                     isFolder = False
437                     # check maturity index, to determine if we need the adult pin
438                     needs_pin = (True, False)[int(video['maturity']['level']) >= 1000]
439                     url = build_url({'action': 'play_video', 'video_id': video_list_id, 'pin': needs_pin})
440                 # add list item info
441                 li = self._generate_entry_info(entry=video, li=li)
442                 li = self._generate_context_menu_items(entry=video, li=li)
443                 xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=isFolder)
444
445         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
446         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_TITLE)
447         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_YEAR)
448         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_GENRE)
449         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LASTPLAYED)
450         xbmcplugin.endOfDirectory(self.plugin_handle)
451         return True
452
453     def build_search_result_listing (self, video_list, actions, build_url):
454         """Builds the search results list Kodi screen
455
456         Parameters
457         ----------
458         video_list : :obj:`dict` of :obj:`str`
459             List of videos or shows
460
461         actions : :obj:`dict` of :obj:`str`
462             Dictionary of actions to build subsequent routes
463
464         build_url : :obj:`fn`
465             Function to build the subsequent routes
466
467         Returns
468         -------
469         bool
470             List could be build
471         """
472         return self.build_video_listing(video_list=video_list, actions=actions, type='search', build_url=build_url)
473
474     def build_no_seasons_available (self):
475         """Builds the season list screen if no seasons could be found
476
477         Returns
478         -------
479         bool
480             List could be build
481         """
482         li = xbmcgui.ListItem(label=self.get_local_string(30012))
483         xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url='', listitem=li, isFolder=False)
484         xbmcplugin.endOfDirectory(self.plugin_handle)
485         return True
486
487     def build_no_search_results_available (self, build_url, action):
488         """Builds the search results screen if no matches could be found
489
490         Parameters
491         ----------
492         action : :obj:`str`
493             Action paramter to build the subsequent routes
494
495         build_url : :obj:`fn`
496             Function to build the subsequent routes
497
498         Returns
499         -------
500         bool
501             List could be build
502         """
503         li = xbmcgui.ListItem(label=self.get_local_string(30013))
504         xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=build_url({'action': action}), listitem=li, isFolder=False)
505         xbmcplugin.endOfDirectory(self.plugin_handle)
506         return True
507
508     def build_user_sub_listing (self, video_list_ids, type, action, build_url):
509         """Builds the video lists screen for user subfolders (genres & recommendations)
510
511         Parameters
512         ----------
513         video_list_ids : :obj:`dict` of :obj:`str`
514             List of video lists
515
516         type : :obj:`str`
517             List type (genre or recommendation)
518
519         action : :obj:`str`
520             Action paramter to build the subsequent routes
521
522         build_url : :obj:`fn`
523             Function to build the subsequent routes
524
525         Returns
526         -------
527         bool
528             List could be build
529         """
530         for video_list_id in video_list_ids:
531             li = xbmcgui.ListItem(video_list_ids[video_list_id]['displayName'])
532             li.setProperty('fanart_image', self.default_fanart)
533             url = build_url({'action': action, 'video_list_id': video_list_id})
534             xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True)
535
536         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
537         xbmcplugin.endOfDirectory(self.plugin_handle)
538         return True
539
540     def build_season_listing (self, seasons_sorted, season_list, build_url):
541         """Builds the season list screen for a show
542
543         Parameters
544         ----------
545         seasons_sorted : :obj:`list` of :obj:`str`
546             Sorted season indexes
547
548         season_list : :obj:`dict` of :obj:`str`
549             List of season entries
550
551         build_url : :obj:`fn`
552             Function to build the subsequent routes
553
554         Returns
555         -------
556         bool
557             List could be build
558         """
559         for index in seasons_sorted:
560             for season_id in season_list:
561                 season = season_list[season_id]
562                 if int(season['shortName'].split(' ')[1]) == index:
563                     li = xbmcgui.ListItem(label=season['text'])
564                     # add some art to the item
565                     li = self._generate_art_info(entry=season, li=li)
566                     # add list item info
567                     li = self._generate_entry_info(entry=season, li=li, base_info={'mediatype': 'season'})
568                     li = self._generate_context_menu_items(entry=season, li=li)
569                     url = build_url({'action': 'episode_list', 'season_id': season_id})
570                     xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=True)
571
572         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE)
573         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_YEAR)
574         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
575         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LASTPLAYED)
576         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_TITLE)
577         xbmcplugin.endOfDirectory(self.plugin_handle)
578         return True
579
580     def build_episode_listing (self, episodes_sorted, episode_list, build_url):
581         """Builds the episode list screen for a season of a show
582
583         Parameters
584         ----------
585         episodes_sorted : :obj:`list` of :obj:`str`
586             Sorted episode indexes
587
588         episode_list : :obj:`dict` of :obj:`str`
589             List of episode entries
590
591         build_url : :obj:`fn`
592             Function to build the subsequent routes
593
594         Returns
595         -------
596         bool
597             List could be build
598         """
599         for index in episodes_sorted:
600             for episode_id in episode_list:
601                 episode = episode_list[episode_id]
602                 if int(episode['episode']) == index:
603                     li = xbmcgui.ListItem(label=episode['title'])
604                     # add some art to the item
605                     li = self._generate_art_info(entry=episode, li=li)
606                     # add list item info
607                     li = self._generate_entry_info(entry=episode, li=li, base_info={'mediatype': 'episode'})
608                     li = self._generate_context_menu_items(entry=episode, li=li)
609                     # check maturity index, to determine if we need the adult pin
610                     needs_pin = (True, False)[int(episode['maturity']['rating']['maturityLevel']) >= 1000]
611                     url = build_url({'action': 'play_video', 'video_id': episode_id, 'pin': needs_pin, 'start_offset': episode['bookmark']})
612                     xbmcplugin.addDirectoryItem(handle=self.plugin_handle, url=url, listitem=li, isFolder=False)
613
614         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_EPISODE)
615         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_NONE)
616         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_VIDEO_YEAR)
617         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
618         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LASTPLAYED)
619         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_TITLE)
620         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_DURATION)
621         xbmcplugin.endOfDirectory(self.plugin_handle)
622         return True
623
624     def play_item (self, esn, video_id, start_offset=-1):
625         """Plays a video
626
627         Parameters
628         ----------
629         esn : :obj:`str`
630             ESN needed for Widevine/Inputstream
631
632         video_id : :obj:`str`
633             ID of the video that should be played
634
635         start_offset : :obj:`str`
636             Offset to resume playback from (in seconds)
637
638         Returns
639         -------
640         bool
641             List could be build
642         """
643         inputstream_addon = self.get_inputstream_addon()
644         if inputstream_addon == None:
645             self.show_missing_inputstream_addon_notification()
646             self.log(msg='Inputstream addon not found')
647             return False
648
649         # inputstream addon properties
650         msl_service_url = self.msl_service_server_url.replace('%PORT%', str(self.addon.getSetting('msl_service_port')))
651         play_item = xbmcgui.ListItem(path=msl_service_url + '/manifest?id=' + video_id)
652         play_item.setProperty(inputstream_addon + '.license_type', 'com.widevine.alpha')
653         play_item.setProperty(inputstream_addon + '.manifest_type', 'mpd')
654         play_item.setProperty(inputstream_addon + '.license_key', msl_service_url + '/license?id=' + video_id + '||b{SSM}!b{SID}|')
655         play_item.setProperty(inputstream_addon + '.server_certificate', self.addon.getSetting('msl_service_certificate'))
656         play_item.setProperty('inputstreamaddon', inputstream_addon)
657
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)
662
663     def _generate_art_info (self, entry, li):
664         """Adds the art info from an entry to a Kodi list item
665
666         Parameters
667         ----------
668         entry : :obj:`dict` of :obj:`str`
669             Entry that should be turned into a list item
670
671         li : :obj:`XMBC.ListItem`
672             Kodi list item instance
673
674         Returns
675         -------
676         :obj:`XMBC.ListItem`
677             Kodi list item instance
678         """
679         art = {'fanart': self.default_fanart}
680         if 'boxarts' in dict(entry).keys():
681             art.update({
682                 'poster': entry['boxarts']['big'],
683                 'landscape': entry['boxarts']['big'],
684                 'thumb': entry['boxarts']['small'],
685                 'fanart': entry['boxarts']['big']
686             })
687         if 'interesting_moment' in dict(entry).keys():
688             art.update({
689                 'poster': entry['interesting_moment'],
690                 'fanart': entry['interesting_moment']
691             })
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']})
698         li.setArt(art)
699         return li
700
701     def _generate_entry_info (self, entry, li, base_info={}):
702         """Adds the item info from an entry to a Kodi list item
703
704         Parameters
705         ----------
706         entry : :obj:`dict` of :obj:`str`
707             Entry that should be turned into a list item
708
709         li : :obj:`XMBC.ListItem`
710             Kodi list item instance
711
712         base_info : :obj:`dict` of :obj:`str`
713             Additional info that overrules the entry info
714
715         Returns
716         -------
717         :obj:`XMBC.ListItem`
718             Kodi list item instance
719         """
720         infos = base_info
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']})
733             else:
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)
774         return li
775
776     def _generate_context_menu_items (self, entry, li):
777         """Adds context menue items to a Kodi list item
778
779         Parameters
780         ----------
781         entry : :obj:`dict` of :obj:`str`
782             Entry that should be turned into a list item
783
784         li : :obj:`XMBC.ListItem`
785             Kodi list item instance
786         Returns
787         -------
788         :obj:`XMBC.ListItem`
789             Kodi list item instance
790         """
791         items = []
792         action = {}
793         entry_keys = entry.keys()
794
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 + ')'
798         actions = [
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']
804         ]
805
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])]})
809
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'])
819
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:
822             # add/remove movie
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])
826             # add/remove show
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])
830
831         # add it to the item
832         li.addContextMenuItems(items)
833         return li
834
835     def log (self, msg, level=xbmc.LOGNOTICE):
836         """Adds a log entry to the Kodi log
837
838         Parameters
839         ----------
840         msg : :obj:`str`
841             Entry that should be turned into a list item
842
843         level : :obj:`int`
844             Kodi log level
845         """
846         if self.verb_log:
847             if level == xbmc.LOGDEBUG and self.verb_log:
848                 level = xbmc.LOGNOTICE
849             if isinstance(msg, unicode):
850                 msg = msg.encode('utf-8')
851             xbmc.log('[%s] %s' % (self.plugin, msg.__str__()), level)
852
853     def get_local_string (self, string_id):
854         """Returns the localized version of a string
855
856         Parameters
857         ----------
858         string_id : :obj:`int`
859             ID of the string that shoudl be fetched
860
861         Returns
862         -------
863         :obj:`str`
864             Requested string or empty string
865         """
866         src = xbmc if string_id < 30000 else self.addon
867         locString = src.getLocalizedString(string_id)
868         if isinstance(locString, unicode):
869             locString = locString.encode('utf-8')
870         return locString
871
872     def get_inputstream_addon (self):
873         """Checks if the inputstream addon is installed & enabled.
874            Returns the type of the inputstream addon used or None if not found
875
876         Returns
877         -------
878         :obj:`str` or None
879             Inputstream addon or None
880         """
881         type = 'inputstream.adaptive'
882         payload = {
883             'jsonrpc': '2.0',
884             'id': 1,
885             'method': 'Addons.GetAddonDetails',
886             'params': {
887                 'addonid': type,
888                 'properties': ['enabled']
889             }
890         }
891         response = xbmc.executeJSONRPC(json.dumps(payload))
892         data = json.loads(response)
893         if not 'error' in data.keys():
894             if data['result']['addon']['enabled'] == True:
895                 return type
896         return None
897
898     def set_library (self, library):
899         """Adds an instance of the Library class
900
901         Parameters
902         ----------
903         library : :obj:`Library`
904             instance of the Library class
905         """
906         self.library = library