fix(adult-pin): Remove adult pin as it´s not needed. People should adapt that in...
[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     def __init__ (self, plugin_handle, base_url):
22         """Fetches all needed info from Kodi & configures the baseline of the plugin
23
24         Parameters
25         ----------
26         plugin_handle : :obj:`int`
27             Plugin handle
28
29         base_url : :obj:`str`
30             Plugin base url
31         """
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())
46         self.library = None
47         self.setup_memcache()
48
49     def refresh (self):
50         """Refrsh the current list"""
51         return xbmc.executebuiltin('Container.Refresh')
52
53     def show_rating_dialog (self):
54         """Asks the user for a movie rating
55
56         Returns
57         -------
58         :obj:`int`
59             Movie rating between 0 & 10
60         """
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)
63
64     def show_search_term_dialog (self):
65         """Asks the user for a term to query the netflix search for
66
67         Returns
68         -------
69         :obj:`str`
70             Term to search for
71         """
72         dlg = xbmcgui.Dialog()
73         term = dlg.input(self.get_local_string(string_id=30003), type=xbmcgui.INPUT_ALPHANUM)
74         if len(term) == 0:
75             term = ' '
76         return term
77
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
80
81         Parameters
82         ----------
83         original_title : :obj:`str`
84             Original title of the show (as suggested by the addon)
85
86         Returns
87         -------
88         :obj:`str`
89             Title to persist
90         """
91         dlg = xbmcgui.Dialog()
92         return dlg.input(heading=self.get_local_string(string_id=30031), defaultt=original_title, type=xbmcgui.INPUT_ALPHANUM)
93
94     def show_password_dialog (self):
95         """Asks the user for its Netflix password
96
97         Returns
98         -------
99         :obj:`str`
100             Netflix password
101         """
102         dlg = xbmcgui.Dialog()
103         return dlg.input(self.get_local_string(string_id=30004), type=xbmcgui.INPUT_ALPHANUM)
104
105     def show_email_dialog (self):
106         """Asks the user for its Netflix account email
107
108         Returns
109         -------
110         term : :obj:`str`
111             Netflix account email
112         """
113         dlg = xbmcgui.Dialog()
114         return dlg.input(self.get_local_string(string_id=30005), type=xbmcgui.INPUT_ALPHANUM)
115
116     def show_login_failed_notification (self):
117         """Shows notification that the login failed
118
119         Returns
120         -------
121         bool
122             Dialog shown
123         """
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)
126         return True
127
128     def show_missing_inputstream_addon_notification (self):
129         """Shows notification that the inputstream addon couldn't be found
130
131         Returns
132         -------
133         bool
134             Dialog shown
135         """
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)
138         return True
139
140     def set_setting (self, key, value):
141         """Public interface for the addons setSetting method
142
143         Returns
144         -------
145         bool
146             Setting could be set or not
147         """
148         return self.addon.setSetting(key, value)
149
150     def get_credentials (self):
151         """Returns the users stored credentials
152
153         Returns
154         -------
155         :obj:`dict` of :obj:`str`
156             The users stored account data
157         """
158         return {
159             'email': self.addon.getSetting('email'),
160             'password': self.addon.getSetting('password')
161         }
162
163     def get_custom_library_settings (self):
164         """Returns the settings in regards to the custom library folder(s)
165
166         Returns
167         -------
168         :obj:`dict` of :obj:`str`
169             The users library settings
170         """
171         return {
172             'enablelibraryfolder': self.addon.getSetting('enablelibraryfolder'),
173             'customlibraryfolder': self.addon.getSetting('customlibraryfolder')
174         }
175
176     def get_ssl_verification_setting (self):
177         """Returns the setting that describes if we should verify the ssl transport when loading data
178
179         Returns
180         -------
181         bool
182             Verify or not
183         """
184         return self.addon.getSetting('ssl_verification') == 'true'
185
186     def set_main_menu_selection (self, type):
187         """Persist the chosen main menu entry in memory
188
189         Parameters
190         ----------
191         type : :obj:`str`
192             Selected menu item
193         """
194         self.win.setProperty('main_menu_selection', type)
195
196     def get_main_menu_selection (self):
197         """Gets the persisted chosen main menu entry from memory
198
199         Returns
200         -------
201         :obj:`str`
202             The last chosen main menu entry
203         """
204         return self.win.getProperty('main_menu_selection')
205
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({}))
212
213     def invalidate_memcache (self):
214         """Invalidates the memory cache"""
215         self.win.setProperty('memcache', pickle.dumps({}))
216
217     def has_cached_item (self, cache_id):
218         """Checks if the requested item is in memory cache
219
220         Parameters
221         ----------
222         cache_id : :obj:`str`
223             ID of the cache entry
224
225         Returns
226         -------
227         bool
228             Item is cached
229         """
230         cached_items = pickle.loads(self.win.getProperty('memcache'))
231         return cache_id in cached_items.keys()
232
233     def get_cached_item (self, cache_id):
234         """Returns an item from the in memory cache
235
236         Parameters
237         ----------
238         cache_id : :obj:`str`
239             ID of the cache entry
240
241         Returns
242         -------
243         mixed
244             Contents of the requested cache item or none
245         """
246         cached_items = pickle.loads(self.win.getProperty('memcache'))
247         if self.has_cached_item(cache_id) != True:
248             return None
249         return cached_items[cache_id]
250
251     def add_cached_item (self, cache_id, contents):
252         """Adds an item to the in memory cache
253
254         Parameters
255         ----------
256         cache_id : :obj:`str`
257             ID of the cache entry
258
259         contents : mixed
260             Cache entry contents
261         """
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))
265
266     def build_profiles_listing (self, profiles, action, build_url):
267         """Builds the profiles list Kodi screen
268
269         Parameters
270         ----------
271         profiles : :obj:`dict` of :obj:`str`
272             List of user profiles
273
274         action : :obj:`str`
275             Action paramter to build the subsequent routes
276
277         build_url : :obj:`fn`
278             Function to build the subsequent routes
279
280         Returns
281         -------
282         bool
283             List could be build
284         """
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)
293         return True
294
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
297
298         Parameters
299         ----------
300         video_list_ids : :obj:`dict` of :obj:`str`
301             List of video lists
302
303         user_list_order : :obj:`list` of :obj:`str`
304             Ordered user lists, to determine what should be displayed in the main menue
305
306         actions : :obj:`dict` of :obj:`str`
307             Dictionary of actions to build subsequent routes
308
309         build_url : :obj:`fn`
310             Function to build the subsequent routes
311
312         Returns
313         -------
314         bool
315             List could be build
316         """
317         preselect_items = []
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)
334
335         # add recommendations/genres as subfolders (save us some space on the home page)
336         i18n_ids = {
337             'recommendations': self.get_local_string(30001),
338             'genres': self.get_local_string(30010)
339         }
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)
353
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)
362
363         # no srting & close
364         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
365         xbmcplugin.endOfDirectory(self.plugin_handle)
366
367         # (re)select the previously selected main menu entry
368         idx = 1
369         for item in preselect_items:
370             idx += 1
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)))
375         return True
376
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
379
380         Parameters
381         ----------
382         video_list_ids : :obj:`dict` of :obj:`str`
383             List of video lists
384
385         actions : :obj:`dict` of :obj:`str`
386             Dictionary of actions to build subsequent routes
387
388         type : :obj:`str`
389             None or 'queue' f.e. when it´s a special video lists
390
391         build_url : :obj:`fn`
392             Function to build the subsequent routes
393
394         Returns
395         -------
396         bool
397             List could be build
398         """
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)
406                 isFolder = True
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
411                     isFolder = False
412                     url = build_url({'action': 'play_video', 'video_id': video_list_id})
413                 # add list item info
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)
417
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)
424         return True
425
426     def build_search_result_listing (self, video_list, actions, build_url):
427         """Builds the search results list Kodi screen
428
429         Parameters
430         ----------
431         video_list : :obj:`dict` of :obj:`str`
432             List of videos or shows
433
434         actions : :obj:`dict` of :obj:`str`
435             Dictionary of actions to build subsequent routes
436
437         build_url : :obj:`fn`
438             Function to build the subsequent routes
439
440         Returns
441         -------
442         bool
443             List could be build
444         """
445         return self.build_video_listing(video_list=video_list, actions=actions, type='search', build_url=build_url)
446
447     def build_no_seasons_available (self):
448         """Builds the season list screen if no seasons could be found
449
450         Returns
451         -------
452         bool
453             List could be build
454         """
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)
458         return True
459
460     def build_no_search_results_available (self, build_url, action):
461         """Builds the search results screen if no matches could be found
462
463         Parameters
464         ----------
465         action : :obj:`str`
466             Action paramter to build the subsequent routes
467
468         build_url : :obj:`fn`
469             Function to build the subsequent routes
470
471         Returns
472         -------
473         bool
474             List could be build
475         """
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)
479         return True
480
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)
483
484         Parameters
485         ----------
486         video_list_ids : :obj:`dict` of :obj:`str`
487             List of video lists
488
489         type : :obj:`str`
490             List type (genre or recommendation)
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         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)
508
509         xbmcplugin.addSortMethod(handle=self.plugin_handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)
510         xbmcplugin.endOfDirectory(self.plugin_handle)
511         return True
512
513     def build_season_listing (self, seasons_sorted, season_list, build_url):
514         """Builds the season list screen for a show
515
516         Parameters
517         ----------
518         seasons_sorted : :obj:`list` of :obj:`str`
519             Sorted season indexes
520
521         season_list : :obj:`dict` of :obj:`str`
522             List of season entries
523
524         build_url : :obj:`fn`
525             Function to build the subsequent routes
526
527         Returns
528         -------
529         bool
530             List could be build
531         """
532         for index in seasons_sorted:
533             for season_id in season_list:
534                 season = season_list[season_id]
535                 if int(season['id']) == 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)
539                     # add list item info
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)
544
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)
551         return True
552
553     def build_episode_listing (self, episodes_sorted, episode_list, build_url):
554         """Builds the episode list screen for a season of a show
555
556         Parameters
557         ----------
558         episodes_sorted : :obj:`list` of :obj:`str`
559             Sorted episode indexes
560
561         episode_list : :obj:`dict` of :obj:`str`
562             List of episode entries
563
564         build_url : :obj:`fn`
565             Function to build the subsequent routes
566
567         Returns
568         -------
569         bool
570             List could be build
571         """
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)
579                     # add list item info
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)
584
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)
593         return True
594
595     def play_item (self, esn, video_id, start_offset=-1):
596         """Plays a video
597
598         Parameters
599         ----------
600         esn : :obj:`str`
601             ESN needed for Widevine/Inputstream
602
603         video_id : :obj:`str`
604             ID of the video that should be played
605
606         start_offset : :obj:`str`
607             Offset to resume playback from (in seconds)
608
609         Returns
610         -------
611         bool
612             List could be build
613         """
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')
618             return False
619
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)
630
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)
635
636     def _generate_art_info (self, entry, li):
637         """Adds the art info from an entry to a Kodi list item
638
639         Parameters
640         ----------
641         entry : :obj:`dict` of :obj:`str`
642             Entry that should be turned into a list item
643
644         li : :obj:`XMBC.ListItem`
645             Kodi list item instance
646
647         Returns
648         -------
649         :obj:`XMBC.ListItem`
650             Kodi list item instance
651         """
652         art = {'fanart': self.default_fanart}
653         if 'boxarts' in dict(entry).keys():
654             art.update({
655                 'poster': entry['boxarts']['big'],
656                 'landscape': entry['boxarts']['big'],
657                 'thumb': entry['boxarts']['small'],
658                 'fanart': entry['boxarts']['big']
659             })
660         if 'interesting_moment' in dict(entry).keys():
661             art.update({
662                 'poster': entry['interesting_moment'],
663                 'fanart': entry['interesting_moment']
664             })
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']})
671         li.setArt(art)
672         return li
673
674     def _generate_entry_info (self, entry, li, base_info={}):
675         """Adds the item info from an entry to a Kodi list item
676
677         Parameters
678         ----------
679         entry : :obj:`dict` of :obj:`str`
680             Entry that should be turned into a list item
681
682         li : :obj:`XMBC.ListItem`
683             Kodi list item instance
684
685         base_info : :obj:`dict` of :obj:`str`
686             Additional info that overrules the entry info
687
688         Returns
689         -------
690         :obj:`XMBC.ListItem`
691             Kodi list item instance
692         """
693         infos = base_info
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']})
706             else:
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)
747         return li
748
749     def _generate_context_menu_items (self, entry, li):
750         """Adds context menue items to a Kodi list item
751
752         Parameters
753         ----------
754         entry : :obj:`dict` of :obj:`str`
755             Entry that should be turned into a list item
756
757         li : :obj:`XMBC.ListItem`
758             Kodi list item instance
759         Returns
760         -------
761         :obj:`XMBC.ListItem`
762             Kodi list item instance
763         """
764         items = []
765         action = {}
766         entry_keys = entry.keys()
767
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 + ')'
771         actions = [
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']
777         ]
778
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])]})
782
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'])
792
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:
795             # add/remove movie
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])
799             # add/remove show
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])
803
804         # add it to the item
805         li.addContextMenuItems(items)
806         return li
807
808     def log (self, msg, level=xbmc.LOGNOTICE):
809         """Adds a log entry to the Kodi log
810
811         Parameters
812         ----------
813         msg : :obj:`str`
814             Entry that should be turned into a list item
815
816         level : :obj:`int`
817             Kodi log level
818         """
819         if self.verb_log:
820             if level == xbmc.LOGDEBUG and self.verb_log:
821                 level = xbmc.LOGNOTICE
822             if isinstance(msg, unicode):
823                 msg = msg.encode('utf-8')
824             xbmc.log('[%s] %s' % (self.plugin, msg.__str__()), level)
825
826     def get_local_string (self, string_id):
827         """Returns the localized version of a string
828
829         Parameters
830         ----------
831         string_id : :obj:`int`
832             ID of the string that shoudl be fetched
833
834         Returns
835         -------
836         :obj:`str`
837             Requested string or empty string
838         """
839         src = xbmc if string_id < 30000 else self.addon
840         locString = src.getLocalizedString(string_id)
841         if isinstance(locString, unicode):
842             locString = locString.encode('utf-8')
843         return locString
844
845     def get_inputstream_addon (self):
846         """Checks if the inputstream addon is installed & enabled.
847            Returns the type of the inputstream addon used or None if not found
848
849         Returns
850         -------
851         :obj:`str` or None
852             Inputstream addon or None
853         """
854         type = 'inputstream.adaptive'
855         payload = {
856             'jsonrpc': '2.0',
857             'id': 1,
858             'method': 'Addons.GetAddonDetails',
859             'params': {
860                 'addonid': type,
861                 'properties': ['enabled']
862             }
863         }
864         response = xbmc.executeJSONRPC(json.dumps(payload))
865         data = json.loads(response)
866         if not 'error' in data.keys():
867             if data['result']['addon']['enabled'] == True:
868                 return type
869         return None
870
871     def set_library (self, library):
872         """Adds an instance of the Library class
873
874         Parameters
875         ----------
876         library : :obj:`Library`
877             instance of the Library class
878         """
879         self.library = library