author
int64 658
755k
| date
stringlengths 19
19
| timezone
int64 -46,800
43.2k
| hash
stringlengths 40
40
| message
stringlengths 5
490
| mods
list | language
stringclasses 20
values | license
stringclasses 3
values | repo
stringlengths 5
68
| original_message
stringlengths 12
491
|
---|---|---|---|---|---|---|---|---|---|
105,989 | 09.08.2018 17:38:01 | -7,200 | a056e32a1854b079261fbe82300ee482e08d5b99 | Fixes for dialogs, properly setup subtitle handling | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/Navigation.py",
"new_path": "resources/lib/Navigation.py",
"diff": "@@ -26,8 +26,8 @@ import resources.lib.NetflixSession as Netflix\nfrom resources.lib.utils import log, find_episode\nfrom resources.lib.KodiHelper import KodiHelper\nfrom resources.lib.Library import Library\n-from resources.lib.section_skipping import (\n- SKIPPABLE_SECTIONS, OFFSET_CREDITS, OFFSET_WATCHED_TO_END)\n+from resources.lib.playback.section_skipping import SKIPPABLE_SECTIONS, OFFSET_CREDITS\n+from resources.lib.playback.bookmarks import OFFSET_WATCHED_TO_END\ndef _get_offset_markers(metadata):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/playback/__init__.py",
"new_path": "resources/lib/playback/__init__.py",
"diff": "@@ -60,7 +60,10 @@ class PlaybackController(xbmc.Monitor, LoggingComponent):\nCallback for addon signal when this addon has initiated a playback\n\"\"\"\nself.tracking = True\n+ try:\nself._notify_all(PlaybackActionManager.initialize, data)\n+ except RuntimeError as exc:\n+ self.log('RuntimeError: {}'.format(exc), xbmc.LOGERROR)\ndef onNotification(self, sender, method, data):\n# pylint: disable=unused-argument, invalid-name\n@@ -69,11 +72,14 @@ class PlaybackController(xbmc.Monitor, LoggingComponent):\nstarted and playback stopped events.\n\"\"\"\nif self.tracking:\n+ try:\nif method == 'Player.OnAVStart':\nself._on_playback_started(\njson.loads(unicode(data, 'utf-8', errors='ignore')))\nelif method == 'Player.OnStop':\nself._on_playback_stopped()\n+ except RuntimeError as exc:\n+ self.log('RuntimeError: {}'.format(exc), xbmc.LOGERROR)\ndef on_playback_tick(self):\n\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/playback/section_skipping.py",
"new_path": "resources/lib/playback/section_skipping.py",
"diff": "import xbmc\nimport xbmcgui\n-import resources.lib.ui as ui\n+from resources.lib.ui import xmldialogs, show_modal_dialog\nfrom resources.lib.playback import PlaybackActionManager\nSKIPPABLE_SECTIONS = {'credit': 30076, 'recap': 30077}\n@@ -75,7 +75,7 @@ class SectionSkipper(PlaybackActionManager):\nself.markers[section]['start'])\nseconds = dialog_duration % 60\nminutes = (dialog_duration - seconds) / 60\n- ui.show_modal_dialog(ui.xmldialogs.Skip,\n+ show_modal_dialog(xmldialogs.Skip,\n\"plugin-video-netflix-Skip.xml\",\nself.addon.getAddonInfo('path'),\nminutes=minutes,\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/playback/stream_continuity.py",
"new_path": "resources/lib/playback/stream_continuity.py",
"diff": "@@ -11,17 +11,21 @@ episodes of a tv show\n\"\"\"\nimport xbmc\n-import resources.lib.ui as ui\n+from resources.lib.ui import xmldialogs, show_modal_dialog\nfrom resources.lib.playback import PlaybackActionManager\nSTREAMS = {\n'audio': {\n- 'attribute_current': 'currentaudiostream',\n- 'setter': xbmc.Player.setAudioStream\n+ 'current': 'currentaudiostream',\n+ 'setter': xbmc.Player.setAudioStream,\n},\n'subtitle': {\n- 'attribute_current': 'currentsubtitle',\n- 'setter': xbmc.Player.setSubtitleStream\n+ 'current': 'currentsubtitle',\n+ 'setter': xbmc.Player.setSubtitleStream,\n+ },\n+ 'subtitleenabled': {\n+ 'current': 'subtitleenabled',\n+ 'setter': xbmc.Player.showSubtitles\n}\n}\n@@ -39,22 +43,22 @@ class StreamContinuityManager(PlaybackActionManager):\nself.player = xbmc.Player()\nself.did_restore = False\n- def __str__(self):\n- return ('enabled={}, current_show={}'\n- .format(self.enabled, self.current_show))\n+ @property\n+ def show_settings(self):\n+ \"\"\"Stored stream settings for the current show\"\"\"\n+ return self.storage.get(self.current_show, {})\ndef _initialize(self, data):\nself.did_restore = False\n+ # let this throw a KeyError to disable this instance if the playback is\n+ # not a TV show\nself.current_show = data['dbinfo']['tvshowid']\ndef _on_playback_started(self, player_state):\n- for stype, stream in STREAMS.iteritems():\n- current_player_stream = player_state[stream['attribute_current']]\n- if current_player_stream:\n- self.current_streams.update({\n- stype: current_player_stream['index']\n- })\n- self._restore_stream(stype, stream['setter'])\n+ xbmc.sleep(1000)\n+ for stype in STREAMS:\n+ self._set_current_stream(stype, player_state)\n+ self._restore_stream(stype)\nself.did_restore = True\ndef _on_tick(self, player_state):\n@@ -62,39 +66,48 @@ class StreamContinuityManager(PlaybackActionManager):\nself.log('Did not restore streams yet, ignoring tick')\nreturn\n- for stype in self.current_streams:\n- stream = STREAMS[stype]\n- current_player_stream = player_state[stream['attribute_current']]\n- if (self.current_streams[stype] !=\n- current_player_stream['index']):\n- self.log('{} stream has changed from {} to {}'\n- .format(stype,\n- self.current_streams[stype],\n- current_player_stream))\n- self._ask_to_save(\n- stype, current_player_stream['index'])\n- self.current_streams[stype] = current_player_stream['index']\n+ for stype in STREAMS:\n+ current_stream = self.current_streams[stype]\n+ player_stream = player_state.get(STREAMS[stype]['current'])\n+ if player_stream != current_stream:\n+ self.log('{} has changed from {} to {}'\n+ .format(stype, current_stream, player_stream))\n+ self._set_current_stream(stype, player_state)\n+ self._ask_to_save(stype, player_stream)\n+\n+ def _set_current_stream(self, stype, player_state):\n+ self.current_streams.update({\n+ stype: player_state.get(STREAMS[stype]['current'])\n+ })\n- def _restore_stream(self, stype, stream_setter):\n+ def _restore_stream(self, stype):\nself.log('Trying to restore {}...'.format(stype))\n- stored_streams = self.storage.get(self.current_show, {})\n- if (stype in stored_streams and\n- (stored_streams[stype] != self.current_streams[stype] or\n- stype not in self.current_streams)):\n- self.current_streams[stype] = stored_streams[stype]\n- getattr(self.player, stream_setter.__name__)(\n- self.current_streams[stype])\n- self.log('Restored {}'.format(stype))\n+ set_stream = STREAMS[stype]['setter']\n+ stored_stream = self.show_settings.get(stype)\n+ if (stored_stream is not None and\n+ self.current_streams[stype] != stored_stream):\n+ # subtitleenabled is boolean and not a dict\n+ set_stream(self.player, (stored_stream['index']\n+ if isinstance(stored_stream, dict)\n+ else stored_stream))\n+ self.current_streams[stype] = stored_stream\n+ self.log('Restored {} to {}'.format(stype, stored_stream))\n- def _ask_to_save(self, stype, index):\n- self.log('Asking to save {} stream #{}'.format(stype, index))\n- stream_settings = self.storage.get(self.current_show, {})\n- stream_settings[stype] = index\n- ui.show_modal_dialog(ui.xmldialogs.SaveStreamSettings,\n+ def _ask_to_save(self, stype, stream):\n+ self.log('Asking to save {} for {}'.format(stream, stype))\n+ new_show_settings = self.show_settings.copy()\n+ new_show_settings[stype] = stream\n+ show_modal_dialog(\n+ xmldialogs.SaveStreamSettings,\n\"plugin-video-netflix-SaveStreamSettings.xml\",\nself.addon.getAddonInfo('path'),\nminutes=0,\nseconds=5,\n- stream_settings=stream_settings,\n+ new_show_settings=new_show_settings,\ntvshowid=self.current_show,\nstorage=self.storage)\n+\n+\n+ def __str__(self):\n+ return ('enabled={}, current_show={}'\n+ .format(self.enabled, self.current_show))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/ui/xmldialogs.py",
"new_path": "resources/lib/ui/xmldialogs.py",
"diff": "@@ -8,22 +8,17 @@ ACTION_PLAYER_STOP = 13\nOS_MACHINE = machine()\n-class XMLDialog(xbmcgui.WindowXMLDialog):\n- def __init__(self, *args, **kwargs):\n- if OS_MACHINE[0:5] == 'armv7':\n- xbmcgui.WindowXMLDialog.__init__(self)\n- else:\n- xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)\n-\n-\n-class Skip(XMLDialog):\n+class Skip(xbmcgui.WindowXMLDialog):\n\"\"\"\nDialog for skipping video parts (intro, recap, ...)\n\"\"\"\ndef __init__(self, *args, **kwargs):\n- super(Skip, self).__init__(*args, **kwargs)\nself.skip_to = kwargs['skip_to']\nself.label = kwargs['label']\n+ if OS_MACHINE[0:5] == 'armv7':\n+ xbmcgui.WindowXMLDialog.__init__(self)\n+ else:\n+ xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)\ndef onInit(self):\nself.action_exitkeys_id = [10, 13]\n@@ -36,13 +31,14 @@ class Skip(XMLDialog):\nself.close()\n+\nclass SaveStreamSettings(xbmcgui.WindowXMLDialog):\n\"\"\"\nDialog for skipping video parts (intro, recap, ...)\n\"\"\"\ndef __init__(self, *args, **kwargs):\nsuper(SaveStreamSettings, self).__init__(*args, **kwargs)\n- self.stream_settings = kwargs['stream_settings']\n+ self.new_show_settings = kwargs['new_show_settings']\nself.tvshowid = kwargs['tvshowid']\nself.storage = kwargs['storage']\n@@ -51,5 +47,5 @@ class SaveStreamSettings(xbmcgui.WindowXMLDialog):\ndef onClick(self, controlID):\nif controlID == 6012:\n- self.storage[self.tvshowid] = self.stream_settings\n+ self.storage[self.tvshowid] = self.new_show_settings\nself.close()\n"
},
{
"change_type": "MODIFY",
"old_path": "service.py",
"new_path": "service.py",
"diff": "@@ -17,11 +17,10 @@ import xbmc\nfrom resources.lib.NetflixCommon import NetflixCommon\nfrom resources.lib.MSLHttpRequestHandler import MSLTCPServer\nfrom resources.lib.NetflixHttpRequestHandler import NetflixTCPServer\n-from resources.lib.playback_controlling import PlaybackController\n-from resources.lib.playback_controlling.bookmarks import BookmarkManager\n-from resources.lib.playback_controlling.stream_continuity import (\n- StreamContinuityManager)\n-from resources.lib.playback_controlling.section_skipping import SectionSkipper\n+from resources.lib.playback import PlaybackController\n+from resources.lib.playback.bookmarks import BookmarkManager\n+from resources.lib.playback.stream_continuity import StreamContinuityManager\n+from resources.lib.playback.section_skipping import SectionSkipper\ndef select_unused_port():\n@@ -181,10 +180,9 @@ class NetflixService(object):\n]\nplayer = xbmc.Player()\nwhile not controller.abortRequested():\n+ try:\nif player.isPlayingVideo():\ncontroller.on_playback_tick()\n-\n- try:\nif self.library_update_scheduled() and self._is_idle():\nself.update_library()\nexcept RuntimeError as exc:\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fixes for dialogs, properly setup subtitle handling |
105,989 | 09.08.2018 17:43:48 | -7,200 | ce6043fe4b347ab566fac35c3923128c74ace8e6 | Fix for mixed mode | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/NetflixSession.py",
"new_path": "resources/lib/NetflixSession.py",
"diff": "@@ -303,12 +303,13 @@ class NetflixSession(object):\ncontent=page.content)\nlogin_payload = {\n'userLoginId': account.get('email'),\n+ 'email': account.get('email'),\n'password': account.get('password'),\n'rememberMe': 'true',\n'flow': 'websiteSignUp',\n'mode': 'login',\n'action': 'loginAction',\n- 'withFields': 'rememberMe,nextPage,userLoginId,password',\n+ 'withFields': 'rememberMe,nextPage,userLoginId,password,email',\n'authURL': user_data.get('authURL'),\n'nextPage': '',\n'showPassword': ''\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix for mixed mode |
105,989 | 09.08.2018 18:02:49 | -7,200 | 85de7da70254da708913298c7297e7e00947cff8 | Localize, fix up dialogs | [
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -339,3 +339,15 @@ msgstr \"\"\nmsgctxt \"#30080\"\nmsgid \"Don't pause when skipping\"\nmsgstr \"\"\n+\n+msgctxt \"#30081\"\n+msgid \"Save audio/subtitle preferences for this show\"\n+msgstr \"\"\n+\n+msgctxt \"#30082\"\n+msgid \"Save audio / subtitle settings for TV shows\"\n+msgstr \"\"\n+\n+msgctxt \"#30083\"\n+msgid \"Save bookmarks for library items / mark as watched\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/settings.xml",
"new_path": "resources/settings.xml",
"diff": "<setting id=\"viewmodeexported\" type=\"number\" label=\"30074\" enable=\"eq(-7,true)\" default=\"504\"/>\n</category>\n<category label=\"30078\">\n- <setting id=\"BookmarkManager_enabled\" type=\"bool\" label=\"Save bookmarks\" default=\"true\"/>\n- <setting id=\"StreamContinuityManager_enabled\" type=\"bool\" label=\"Remember audio/subtitle streams\" default=\"true\"/>\n+ <setting id=\"BookmarkManager_enabled\" type=\"bool\" label=\"30083\" default=\"true\"/>\n+ <setting id=\"StreamContinuityManager_enabled\" type=\"bool\" label=\"30082\" default=\"true\"/>\n<setting id=\"SectionSkipper_enabled\" type=\"bool\" label=\"30075\" default=\"true\"/>\n<setting id=\"auto_skip_credits\" type=\"bool\" label=\"30079\" default=\"false\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n<setting id=\"pause_on_skip\" type=\"bool\" label=\"30080\" default=\"false\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/skins/default/1080i/plugin-video-netflix-SaveStreamSettings.xml",
"new_path": "resources/skins/default/1080i/plugin-video-netflix-SaveStreamSettings.xml",
"diff": "<control type=\"group\">\n<control type=\"button\" id=\"6012\">\n<description>Save stream settings</description>\n- <width>180</width>\n+ <width>400</width>\n<height>80</height>\n<font>font12</font>\n- <label>Save these settings?</label>\n+ <label>$ADDON[plugin.video.netflix 30081]</label>\n<textcolor>FFededed</textcolor>\n<focusedcolor>FFededed</focusedcolor>\n<selectedcolor>FFededed</selectedcolor>\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/skins/default/1080i/plugin-video-netflix-Skip.xml",
"new_path": "resources/skins/default/1080i/plugin-video-netflix-Skip.xml",
"diff": "<control type=\"group\">\n<control type=\"button\" id=\"6012\">\n<description>Skip intro</description>\n- <width>180</width>\n+ <width>250</width>\n<height>80</height>\n<font>font12</font>\n<label></label>\n"
},
{
"change_type": "MODIFY",
"old_path": "service.py",
"new_path": "service.py",
"diff": "@@ -187,7 +187,7 @@ class NetflixService(object):\nself.update_library()\nexcept RuntimeError as exc:\nself.nx_common.log(\n- 'RuntimeError: {}'.format(exc), xbmc.LOGERROR)\n+ 'RuntimeError in main loop: {}'.format(exc), xbmc.LOGERROR)\nif controller.waitForAbort(1):\nbreak\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Localize, fix up dialogs |
105,989 | 20.08.2018 10:23:53 | -7,200 | 5fdcb70662e8e20e3fb536f03b52d1c2879be8d5 | Safe get if no fanart images are returned | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/NetflixSession.py",
"new_path": "resources/lib/NetflixSession.py",
"diff": "@@ -838,7 +838,7 @@ class NetflixSession(object):\nbx_big = boxarts.get(ART_BOX_SIZE_LARGE, {}).get('jpg', {}).get('url')\nbx_poster = boxarts.get(ART_BOX_SIZE_POSTER, {}).get('jpg', {}).get('url')\nmoment = video.get('interestingMoment', {}).get(ART_MOMENT_SIZE_LARGE, {}).get('jpg', {}).get('url')\n- artwork = video.get('BGImages', {}).get(ART_FANART_SIZE, {}).get('jpg', [{}])[0].get('url')\n+ artwork = next(iter(video.get('BGImages', {}).get(ART_FANART_SIZE, {}).get('jpg', [{}])), {}).get('url')\nlogo = video.get('bb2OGLogo', {}).get(ART_LOGO_SIZE, {}).get('png', {}).get('url')\nreturn {\n@@ -1193,7 +1193,7 @@ class NetflixSession(object):\nbx_big = boxarts.get(ART_BOX_SIZE_LARGE, {}).get('jpg', {}).get('url')\nbx_poster = boxarts.get(ART_BOX_SIZE_POSTER, {}).get('jpg', {}).get('url')\nmoment = video.get('interestingMoment', {}).get(ART_MOMENT_SIZE_LARGE, {}).get('jpg', {}).get('url')\n- artwork = video.get('BGImages', {}).get(ART_FANART_SIZE, {}).get('jpg', [{}])[0].get('url')\n+ artwork = next(iter(video.get('BGImages', {}).get(ART_FANART_SIZE, {}).get('jpg', [{}])), {}).get('url')\nlogo = video.get('bb2OGLogo', {}).get(ART_LOGO_SIZE, {}).get('png', {}).get('url')\nreturn {\nseason['summary']['id']: {\n@@ -1339,7 +1339,7 @@ class NetflixSession(object):\nbx_big = boxarts.get(ART_BOX_SIZE_LARGE, {}).get('jpg', {}).get('url')\nbx_poster = boxarts.get(ART_BOX_SIZE_POSTER, {}).get('jpg', {}).get('url')\nmoment = episode.get('interestingMoment', {}).get(ART_MOMENT_SIZE_LARGE, {}).get('jpg', {}).get('url')\n- artwork = episode.get('BGImages', {}).get(ART_FANART_SIZE_EPISODE, {}).get('jpg', [{}])[0].get('url')\n+ artwork = next(iter(episode.get('BGImages', {}).get(ART_FANART_SIZE_EPISODE, {}).get('jpg', [{}])), {}).get('url')\nlogo = episode.get('bb2OGLogo', {}).get(ART_LOGO_SIZE, {}).get('png', {}).get('url')\nreturn {\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Safe get if no fanart images are returned |
105,989 | 20.08.2018 18:26:49 | -7,200 | a587574b20b8a7687f8e6a9a97ee8adad6f3c8f6 | version bump 0.13.11 | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.10\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.11\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n<email>public at asciidisco dot com</email>\n<forum>https://www.kodinerds.net/index.php/Thread/55612-PreRelease-Plugin-Netflix-Inputstream/</forum>\n<source>https://github.com/asciidisco/plugin.video.netflix</source>\n- <news>v0.12.9 (2018-04-16)\n-- View for exported\n-- Support for inputstreamhelper\n-- Grab metadate for episodes on export\n-- Auto export new episodes for exported shows\n-- Auto update watched status inside kodi library\n+ <news>\n+v0.13.11 (2018-08-20)\n+- Fix login issues\n+- Fix fanarts for non-netflix originals\n+- Add Korean translation\n+- Update Italian translation\n+- Add query parameter widget_display to suppress setting custom view modes when called from a widget\n+- Skip intro and recap\n+- Remember audio settings across all episodes of a show\n-v0.13.0 (2018-04-26)\n-- Android support WIDEVINE Cryptosession for MSL\n-\n-v0.13.7 (2018-05-28)\n-- rework of login info parsing\n+v0.13.9 (2018-06-14)\n+- fix login issues after typo fix in netflix login page\nv0.13.8 (2018-06-07)\n- fix proxy communication\n- fix folder definition for image resources\n-v0.13.9 (2018-06-14)\n-- fix login issues after typo fix in netflix login page\n+v0.13.7 (2018-05-28)\n+- rework of login info parsing\n+\n+v0.13.0 (2018-04-26)\n+- Android support WIDEVINE Cryptosession for MSL\n+\n+v0.12.9 (2018-04-16)\n+- View for exported\n+- Support for inputstreamhelper\n+- Grab metadate for episodes on export\n+- Auto export new episodes for exported shows\n+- Auto update watched status inside kodi library\n</news>\n</extension>\n</addon>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | version bump 0.13.11 |
105,989 | 21.08.2018 09:51:28 | -7,200 | 0bf52c68b0202d61c799480f2c9d047f55c433e0 | Fix issues with timeline markers. Version bump 0.13.12 | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.11\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.12\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n<forum>https://www.kodinerds.net/index.php/Thread/55612-PreRelease-Plugin-Netflix-Inputstream/</forum>\n<source>https://github.com/asciidisco/plugin.video.netflix</source>\n<news>\n+v0.13.12 (2018-08-21)\n+- Fix issues with timeline markers\n+\nv0.13.11 (2018-08-20)\n- Fix login issues\n- Fix fanarts for non-netflix originals\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/Navigation.py",
"new_path": "resources/lib/Navigation.py",
"diff": "@@ -35,7 +35,7 @@ def _get_offset_markers(metadata):\nreturn {\nmarker: metadata[marker]\nfor marker in [OFFSET_CREDITS, OFFSET_WATCHED_TO_END]\n- if metadata[marker] is not None\n+ if metadata.get(marker) is not None\n}\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix issues with timeline markers. Version bump 0.13.12 |
105,989 | 11.09.2018 17:29:11 | -7,200 | bccee6d04524fb4b556ba6ae2d1ecca4215a7809 | Fix Get enabled setting for action manager as bool. | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/playback/__init__.py",
"new_path": "resources/lib/playback/__init__.py",
"diff": "@@ -154,7 +154,7 @@ class PlaybackActionManager(LoggingComponent):\n\"\"\"\nif self._enabled is None:\nself.log('Loading enabled setting from store')\n- self._enabled = self.addon.getSetting(\n+ self._enabled = self.addon.getSettingBool(\n'{}_enabled'.format(self.__class__.__name__))\nreturn self._enabled\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix #469. Get enabled setting for action manager as bool. |
105,989 | 13.09.2018 20:53:49 | -7,200 | ea057f4e947952179ff20c5079f4c6ec10017c16 | Version bump (0.13.13) | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.12\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.13\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n<forum>https://www.kodinerds.net/index.php/Thread/55612-PreRelease-Plugin-Netflix-Inputstream/</forum>\n<source>https://github.com/asciidisco/plugin.video.netflix</source>\n<news>\n+v0.13.13 (2018-09-13)\n+- Fix disabling of intro skipping not working\n+\nv0.13.12 (2018-08-21)\n- Fix issues with timeline markers\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Version bump (0.13.13) |
105,989 | 22.09.2018 15:33:05 | -7,200 | 62b63ebd1beb18c307979c5f45a6c421ecda43b3 | Fix automatic intro skipping | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/playback/section_skipping.py",
"new_path": "resources/lib/playback/section_skipping.py",
"diff": "@@ -59,7 +59,8 @@ class SectionSkipper(PlaybackActionManager):\nself.log('Auto-skipping {}'.format(section))\nplayer = xbmc.Player()\nxbmcgui.Dialog().notification(\n- 'Netflix', '{}...'.format(label), xbmcgui.NOTIFICATION_INFO, 5000)\n+ 'Netflix', '{}...'.format(label.encode('utf-8')),\n+ xbmcgui.NOTIFICATION_INFO, 5000)\nif self.pause_on_skip:\nplayer.pause()\nxbmc.sleep(1000) # give kodi the chance to execute\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix automatic intro skipping |
105,989 | 22.09.2018 15:33:28 | -7,200 | 270ca8b9698f11b14c71b2fb6dc09e82ac8b8dd8 | Remember audio and subtitles for ALL shows (not just those in library) | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/KodiHelper.py",
"new_path": "resources/lib/KodiHelper.py",
"diff": "@@ -885,7 +885,7 @@ class KodiHelper(object):\nself.set_custom_view(VIEW_EPISODE)\nreturn True\n- def play_item(self, video_id, start_offset=-1, infoLabels={}, timeline_markers={}):\n+ def play_item(self, video_id, start_offset=-1, infoLabels={}, tvshow_video_id=None, timeline_markers={}):\n\"\"\"Plays a video\nParameters\n@@ -954,6 +954,9 @@ class KodiHelper(object):\nsignal_data = {'timeline_markers': timeline_markers}\n+ if tvshow_video_id is not None:\n+ signal_data.update({'tvshow_video_id': tvshow_video_id})\n+\n# check for content in kodi db\nif str(infoLabels) != 'None':\nif infoLabels['mediatype'] == 'episode':\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/Navigation.py",
"new_path": "resources/lib/Navigation.py",
"diff": "@@ -299,21 +299,26 @@ class Navigation(object):\nexcept:\ninfoLabels = {}\n+ try:\n+ metadata, tvshow_video_id = self._get_single_metadata(video_id)\n+ except KeyError:\n+ metadata = {}\n+ tvshow_video_id = None\n+\nreturn self.kodi_helper.play_item(\nvideo_id=video_id,\nstart_offset=start_offset,\ninfoLabels=infoLabels,\n- timeline_markers=self._get_timeline_markers(video_id))\n+ tvshow_video_id=tvshow_video_id,\n+ timeline_markers=self._get_timeline_markers(metadata))\n@log\n- def _get_timeline_markers(self, video_id):\n+ def _get_timeline_markers(self, metadata):\ntry:\n- metadata = self._get_single_metadata(video_id)\n- except KeyError:\n- return {}\n-\nmarkers = _get_offset_markers(metadata)\nmarkers.update(_get_section_markers(metadata))\n+ except KeyError:\n+ return {}\nreturn markers\n@@ -327,9 +332,11 @@ class Navigation(object):\n})\n) or {}\n)['video']\n- return (find_episode(video_id, metadata['seasons'])\n- if metadata['type'] == 'show'\n- else metadata)\n+\n+ if metadata['type'] == 'show':\n+ return find_episode(video_id, metadata['seasons']), metadata['id']\n+\n+ return metadata, None\n@log\ndef show_search_results(self, term):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/playback/stream_continuity.py",
"new_path": "resources/lib/playback/stream_continuity.py",
"diff": "@@ -52,7 +52,7 @@ class StreamContinuityManager(PlaybackActionManager):\nself.did_restore = False\n# let this throw a KeyError to disable this instance if the playback is\n# not a TV show\n- self.current_show = data['dbinfo']['tvshowid']\n+ self.current_show = data['tvshow_video_id']\ndef _on_playback_started(self, player_state):\nxbmc.sleep(1000)\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Remember audio and subtitles for ALL shows (not just those in library) |
105,989 | 22.09.2018 15:38:54 | -7,200 | 743a74a1a16d9379fc5a46ded6ecc9eeeec4afda | Version bump (0.13.14) | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.13\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.14\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Version bump (0.13.14) |
105,992 | 10.10.2018 09:33:26 | -7,200 | 813cb420479c1ff7c315f6d9b11bb60d6a9c1e60 | Make HDR / DolbyVision optional | [
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -351,3 +351,11 @@ msgstr \"\"\nmsgctxt \"#30083\"\nmsgid \"Save bookmarks for library items / mark as watched\"\nmsgstr \"\"\n+\n+msgctxt \"#30084\"\n+msgid \"Enable HDR profiles\"\n+msgstr \"\"\n+\n+msgctxt \"#30085\"\n+msgid \"Enable DolbyVision profiles\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/KodiHelper.py",
"new_path": "resources/lib/KodiHelper.py",
"diff": "@@ -917,6 +917,8 @@ class KodiHelper(object):\nmsl_manifest_url = msl_service_url + '/manifest?id=' + video_id\nmsl_manifest_url += '&dolby=' + self.nx_common.get_setting('enable_dolby_sound')\nmsl_manifest_url += '&hevc=' + self.nx_common.get_setting('enable_hevc_profiles')\n+ msl_manifest_url += '&hdr=' + self.nx_common.get_setting('enable_hdr_profiles')\n+ msl_manifest_url += '&dolbyvision=' + self.nx_common.get_setting('enable_dolbyvision_profiles')\nplay_item = xbmcgui.ListItem(path=msl_manifest_url)\nplay_item.setContentLookup(False)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSL.py",
"new_path": "resources/lib/MSL.py",
"diff": "@@ -63,7 +63,7 @@ class MSL(object):\nself.crypto.fromDict(None)\nself.__perform_key_handshake()\n- def load_manifest(self, viewable_id, dolby, hevc):\n+ def load_manifest(self, viewable_id, dolby, hevc, hdr, dolbyvision):\n\"\"\"\nLoads the manifets for the given viewable_id and\nreturns a mpd-XML-Manifest\n@@ -118,9 +118,6 @@ class MSL(object):\nprk = 'dash-cenc-prk'\ncenc = 'dash-cenc'\nctl = 'dash-cenc-tl'\n- hdr = 'hevc-hdr-main10-'\n- dv = 'hevc-dv-main10-'\n- dv5 = 'hevc-dv5-main10-'\nmanifest_request_data['profiles'].append(main10 + 'L41-' + cenc)\nmanifest_request_data['profiles'].append(main10 + 'L50-' + cenc)\nmanifest_request_data['profiles'].append(main10 + 'L51-' + cenc)\n@@ -148,18 +145,9 @@ class MSL(object):\nmanifest_request_data['profiles'].append(main10 + 'L31-L40-' + ctl)\nmanifest_request_data['profiles'].append(main10 + 'L40-L41-' + ctl)\nmanifest_request_data['profiles'].append(main10 + 'L50-L51-' + ctl)\n- manifest_request_data['profiles'].append(dv + 'L30-' + cenc)\n- manifest_request_data['profiles'].append(dv + 'L31-' + cenc)\n- manifest_request_data['profiles'].append(dv + 'L40-' + cenc)\n- manifest_request_data['profiles'].append(dv + 'L41-' + cenc)\n- manifest_request_data['profiles'].append(dv + 'L50-' + cenc)\n- manifest_request_data['profiles'].append(dv + 'L51-' + cenc)\n- manifest_request_data['profiles'].append(dv5 + 'L30-' + prk)\n- manifest_request_data['profiles'].append(dv5 + 'L31-' + prk)\n- manifest_request_data['profiles'].append(dv5 + 'L40-' + prk)\n- manifest_request_data['profiles'].append(dv5 + 'L41-' + prk)\n- manifest_request_data['profiles'].append(dv5 + 'L50-' + prk)\n- manifest_request_data['profiles'].append(dv5 + 'L51-' + prk)\n+\n+ if hdr is True:\n+ hdr = 'hevc-hdr-main10-'\nmanifest_request_data['profiles'].append(hdr + 'L30-' + cenc)\nmanifest_request_data['profiles'].append(hdr + 'L31-' + cenc)\nmanifest_request_data['profiles'].append(hdr + 'L40-' + cenc)\n@@ -173,6 +161,23 @@ class MSL(object):\nmanifest_request_data['profiles'].append(hdr + 'L50-' + prk)\nmanifest_request_data['profiles'].append(hdr + 'L51-' + prk)\n+\n+ if dolbyvision is True:\n+ dv = 'hevc-dv-main10-'\n+ dv5 = 'hevc-dv5-main10-'\n+ manifest_request_data['profiles'].append(dv + 'L30-' + cenc)\n+ manifest_request_data['profiles'].append(dv + 'L31-' + cenc)\n+ manifest_request_data['profiles'].append(dv + 'L40-' + cenc)\n+ manifest_request_data['profiles'].append(dv + 'L41-' + cenc)\n+ manifest_request_data['profiles'].append(dv + 'L50-' + cenc)\n+ manifest_request_data['profiles'].append(dv + 'L51-' + cenc)\n+ manifest_request_data['profiles'].append(dv5 + 'L30-' + prk)\n+ manifest_request_data['profiles'].append(dv5 + 'L31-' + prk)\n+ manifest_request_data['profiles'].append(dv5 + 'L40-' + prk)\n+ manifest_request_data['profiles'].append(dv5 + 'L41-' + prk)\n+ manifest_request_data['profiles'].append(dv5 + 'L50-' + prk)\n+ manifest_request_data['profiles'].append(dv5 + 'L51-' + prk)\n+\n# Check if dolby sound is enabled and add to profles\nif dolby:\nmanifest_request_data['profiles'].append('ddplus-2.0-dash')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSLHttpRequestHandler.py",
"new_path": "resources/lib/MSLHttpRequestHandler.py",
"diff": "@@ -57,10 +57,14 @@ class MSLHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\nparams['dolby'][0].lower() == 'true' else 'false')\nhevc = (True if 'hevc' in params and\nparams['hevc'][0].lower() == 'true' else 'false')\n+ hdr = (True if 'hdr' in params and\n+ params['hdr'][0].lower() == 'true' else 'false')\n+ dolbyvision = (True if 'dolbyvision' in params and\n+ params['dolbyvision'][0].lower() == 'true' else 'false')\ndata = self.server.msl_handler.load_manifest(\nint(params['id'][0]),\n- dolby, hevc)\n+ dolby, hevc, hdr, dolbyvision)\nself.send_response(200)\nself.send_header('Content-type', 'application/xml')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/settings.xml",
"new_path": "resources/settings.xml",
"diff": "<category label=\"30023\">\n<setting id=\"enable_dolby_sound\" type=\"bool\" label=\"30033\" default=\"true\"/>\n<setting id=\"enable_hevc_profiles\" type=\"bool\" label=\"30060\" default=\"false\"/>\n+ <setting id=\"enable_hdr_profiles\" type=\"bool\" label=\"30084\" default=\"false\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n+ <setting id=\"enable_dolbyvision_profiles\" type=\"bool\" label=\"30085\" default=\"false\" visible=\"eq(-2,true)\" subsetting=\"true\"/>\n<setting id=\"ssl_verification\" type=\"bool\" label=\"30024\" default=\"true\"/>\n<setting id=\"enable_tracking\" type=\"bool\" label=\"30032\" default=\"true\"/>\n<setting id=\"esn\" type=\"text\" label=\"30034\" value=\"\" default=\"\"/>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Make HDR / DolbyVision optional |
105,992 | 10.10.2018 09:35:02 | -7,200 | 5b36874e15e260ec754e0418713a28f159ae2ceb | Version bump 0.13.15 | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.14\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.15\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Version bump 0.13.15 |
105,992 | 12.11.2018 16:54:24 | -3,600 | 58c85cf21fb8f1e2d1ec5738e6036643a22c3e01 | WebVTT subtitles for inputstream version >= 2.3.8 | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSL.py",
"new_path": "resources/lib/MSL.py",
"diff": "@@ -19,6 +19,8 @@ from datetime import datetime\nimport requests\nimport xml.etree.ElementTree as ET\n+import xbmcaddon\n+\n#check if we are on Android\nimport subprocess\ntry:\n@@ -85,9 +87,9 @@ class MSL(object):\n# Audio\n'heaac-2-dash',\n- # Subtiltes\n+ # Subtiltes (handled separately)\n# 'dfxp-ls-sdh',\n- 'simplesdh',\n+ # 'simplesdh',\n# 'nflx-cmisc',\n# Unkown\n@@ -111,6 +113,13 @@ class MSL(object):\n'uiVersion': 'akira'\n}\n+ # subtitles\n+ addon = xbmcaddon.Addon('inputstream.adaptive')\n+ if addon and addon.getAddonInfo('version') >= '2.3.8':\n+ manifest_request_data['profiles'].append('webvtt-lssdh-ios8')\n+ else:\n+ manifest_request_data['profiles'].append('simplesdh')\n+\n# add hevc profiles if setting is set\nif hevc is True:\nhevc = 'hevc-main-'\n@@ -445,14 +454,16 @@ class MSL(object):\nis_downloadables = 'downloadables' not in text_track\nif is_downloadables or text_track.get('downloadables') is None:\ncontinue\n+ # Only one subtitle representation per adaptationset\n+ downloadable = text_track['downloadables'][0]\n+\nsubtiles_adaption_set = ET.SubElement(\nparent=period,\ntag='AdaptationSet',\nlang=text_track.get('bcp47'),\n- codecs='stpp',\n+ codecs='wvtt' if downloadable.get('contentProfile') == 'webvtt-lssdh-ios8' else 'stpp',\ncontentType='text',\n- mimeType='application/ttml+xml')\n- for downloadable in text_track['downloadables']:\n+ mimeType='text/vtt' if downloadable.get('contentProfile') == 'webvtt-lssdh-ios8' else 'application/ttml+xml')\nrep = ET.SubElement(\nparent=subtiles_adaption_set,\ntag='Representation',\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | WebVTT subtitles for inputstream version >= 2.3.8 |
105,992 | 13.11.2018 15:51:23 | -3,600 | 6e6c4263a02c9162e1ce63015edc0c6432be619b | [MSL] write Role for forced subtitles | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSL.py",
"new_path": "resources/lib/MSL.py",
"diff": "@@ -464,6 +464,11 @@ class MSL(object):\ncodecs='wvtt' if downloadable.get('contentProfile') == 'webvtt-lssdh-ios8' else 'stpp',\ncontentType='text',\nmimeType='text/vtt' if downloadable.get('contentProfile') == 'webvtt-lssdh-ios8' else 'application/ttml+xml')\n+ role = ET.SubElement(\n+ parent=subtiles_adaption_set,\n+ tag = 'Role',\n+ schemeIdUri = 'urn:mpeg:dash:role:2011',\n+ value = 'forced' if text_track.get('isForced') == True else 'main')\nrep = ET.SubElement(\nparent=subtiles_adaption_set,\ntag='Representation',\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | [MSL] write Role for forced subtitles |
105,992 | 13.11.2018 20:53:34 | -3,600 | 63a79bb1e70f9b0c8430237cd6f94585f7cc82f6 | Version bump 0.13.16 | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.15\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.16\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n<forum>https://www.kodinerds.net/index.php/Thread/55612-PreRelease-Plugin-Netflix-Inputstream/</forum>\n<source>https://github.com/asciidisco/plugin.video.netflix</source>\n<news>\n+v0.13.16 (2018-11-13)\n+- WebVTT subtitles\n+\nv0.13.13 (2018-09-13)\n- Fix disabling of intro skipping not working\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Version bump 0.13.16 |
105,992 | 14.11.2018 16:12:43 | -3,600 | e63aaef75c0c9ac5bafd3d5ae65d2589ac228c85 | ESN generation for android extended | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/NetflixSession.py",
"new_path": "resources/lib/NetflixSession.py",
"diff": "@@ -2088,21 +2088,26 @@ class NetflixSession(object):\n\"\"\"\n# we generate an esn from device strings for android\nimport subprocess\n+ import re\ntry:\nmanufacturer = subprocess.check_output(\n['/system/bin/getprop', 'ro.product.manufacturer'])\nif manufacturer:\n- esn = 'NFANDROID1-PRV-'\n+ esn = 'NFANDROID1-PRV-' if subprocess.check_output(\n+ ['/system/bin/getprop', 'ro.build.characteristics']\n+ ).strip(' \\t\\n\\r') != 'tv' else 'NFANDROID2-PRV-'\ninput = subprocess.check_output(\n- ['/system/bin/getprop', 'ro.nrdp.modelgroup'])\n+ ['/system/bin/getprop', 'ro.nrdp.modelgroup']\n+ ).strip(' \\t\\n\\r')\nif not input:\nesn += 'T-L3-'\nelse:\n- esn += input.strip(' \\t\\n\\r') + '-'\n- esn += '{:5}'.format(manufacturer.strip(' \\t\\n\\r').upper())\n+ esn += input + '-'\n+ esn += '{:=<5}'.format(manufacturer.strip(' \\t\\n\\r').upper())\ninput = subprocess.check_output(\n['/system/bin/getprop', 'ro.product.model'])\nesn += input.strip(' \\t\\n\\r').replace(' ', '=').upper()\n+ esn = re.sub(r'[^A-Za-z0-9=-]', '=', esn)\nself.nx_common.log(msg='Android generated ESN:' + esn)\nreturn esn\nexcept OSError as e:\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | ESN generation for android extended |
105,992 | 16.11.2018 10:36:59 | -3,600 | 3d6f86e4fbab1ec8b7857e8d09fa7587249f32cc | Add VP9 profies to fix PRK exception | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSL.py",
"new_path": "resources/lib/MSL.py",
"diff": "@@ -79,10 +79,12 @@ class MSL(object):\n'viewableIds': [viewable_id],\n'profiles': [\n# Video\n- \"playready-h264bpl30-dash\",\n- \"playready-h264mpl30-dash\",\n- \"playready-h264mpl31-dash\",\n- \"playready-h264mpl40-dash\",\n+ 'playready-h264bpl30-dash',\n+ 'playready-h264mpl30-dash',\n+ 'playready-h264mpl31-dash',\n+ 'playready-h264mpl40-dash',\n+ 'vp9-profile0-L30-dash-cenc',\n+ 'vp9-profile0-L31-dash-cenc',\n# Audio\n'heaac-2-dash',\n@@ -126,7 +128,7 @@ class MSL(object):\nmain10 = 'hevc-main10-'\nprk = 'dash-cenc-prk'\ncenc = 'dash-cenc'\n- ctl = 'dash-cenc-tl'\n+ ctl = 'dash-cenc-ctl'\nmanifest_request_data['profiles'].append(main10 + 'L41-' + cenc)\nmanifest_request_data['profiles'].append(main10 + 'L50-' + cenc)\nmanifest_request_data['profiles'].append(main10 + 'L51-' + cenc)\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add VP9 profies to fix PRK exception |
105,992 | 16.11.2018 13:42:17 | -3,600 | a01342d443fa2a72ddad1f92e62c2f31df8bedef | Version bump 0.13.17 | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.16\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.17\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n<forum>https://www.kodinerds.net/index.php/Thread/55612-PreRelease-Plugin-Netflix-Inputstream/</forum>\n<source>https://github.com/asciidisco/plugin.video.netflix</source>\n<news>\n+v0.13.17 (2018-11-16)\n+- Add VP9 profiles to avoid PRK exception while downloading manifest\n+- Android ESN generation enhanced\n+\nv0.13.16 (2018-11-13)\n- WebVTT subtitles\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Version bump 0.13.17 |
105,992 | 16.11.2018 15:29:13 | -3,600 | 05f0fbe55cb4e9d69f93d38ecbf88f1ac48e01f5 | Write correct codec into VP9 MPEG DAS profiles | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSL.py",
"new_path": "resources/lib/MSL.py",
"diff": "@@ -367,6 +367,10 @@ class MSL(object):\ncodec = 'h264'\nif 'hevc' in downloadable['contentProfile']:\ncodec = 'hevc'\n+ elif downloadable['contentProfile'] == 'vp9-profile0-L30-dash-cenc':\n+ codec = 'vp9.0.30'\n+ elif downloadable['contentProfile'] == 'vp9-profile0-L31-dash-cenc':\n+ codec = 'vp9.0.31'\nhdcp_versions = '0.0'\nfor hdcp in downloadable['hdcpVersions']:\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Write correct codec into VP9 MPEG DAS profiles |
105,992 | 17.11.2018 14:56:05 | -3,600 | eb481a6e4659a0ba072d63287228206e87e2a75a | Version bump 0.13.18 | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.17\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.18\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n<forum>https://www.kodinerds.net/index.php/Thread/55612-PreRelease-Plugin-Netflix-Inputstream/</forum>\n<source>https://github.com/asciidisco/plugin.video.netflix</source>\n<news>\n+v0.13.18 (2018-11-17)\n+- Write correct codec into VP9 MPEG DAS profiles\n+\nv0.13.17 (2018-11-16)\n- Add VP9 profiles to avoid PRK exception while downloading manifest\n- Android ESN generation enhanced\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Version bump 0.13.18 |
106,018 | 19.11.2018 00:03:35 | -3,600 | d9d1467ce78a6045bfb8ca3ee6b69ebe2e8e7234 | Fix failsave response if image is missing | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/Library.py",
"new_path": "resources/lib/Library.py",
"diff": "@@ -851,4 +851,4 @@ class Library(object):\nfile = os.path.join(self.imagecache_path, imgfile)\nif xbmcvfs.exists(file):\nreturn file\n- return self.nx_common.default_fanart\n+ return \"\"\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix failsave response if image is missing |
105,992 | 19.11.2018 22:56:15 | -3,600 | 289d5228c1fef7fbf66c3c4b5f73d91b24e06d71 | Set HDCP to 1.0 if stream's HDCP value is any | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSL.py",
"new_path": "resources/lib/MSL.py",
"diff": "@@ -375,7 +375,7 @@ class MSL(object):\nhdcp_versions = '0.0'\nfor hdcp in downloadable['hdcpVersions']:\nif hdcp != 'none':\n- hdcp_versions = hdcp\n+ hdcp_versions = hdcp if hdcp != 'any' else '1.0'\nrep = ET.SubElement(\nparent=video_adaption_set,\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Set HDCP to 1.0 if stream's HDCP value is any |
105,992 | 20.11.2018 13:24:58 | -3,600 | 1ff6579b9338829e06f1ac7f5be24e929ba49191 | VP9 optional if HEVC profiles are selected | [
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -359,3 +359,7 @@ msgstr \"\"\nmsgctxt \"#30085\"\nmsgid \"Enable DolbyVision profiles\"\nmsgstr \"\"\n+\n+msgctxt \"#30086\"\n+msgid \"Enable VP9 profiles\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/KodiHelper.py",
"new_path": "resources/lib/KodiHelper.py",
"diff": "@@ -919,6 +919,7 @@ class KodiHelper(object):\nmsl_manifest_url += '&hevc=' + self.nx_common.get_setting('enable_hevc_profiles')\nmsl_manifest_url += '&hdr=' + self.nx_common.get_setting('enable_hdr_profiles')\nmsl_manifest_url += '&dolbyvision=' + self.nx_common.get_setting('enable_dolbyvision_profiles')\n+ msl_manifest_url += '&vp9=' + self.nx_common.get_setting('enable_vp9_profiles')\nplay_item = xbmcgui.ListItem(path=msl_manifest_url)\nplay_item.setContentLookup(False)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSL.py",
"new_path": "resources/lib/MSL.py",
"diff": "@@ -65,7 +65,7 @@ class MSL(object):\nself.crypto.fromDict(None)\nself.__perform_key_handshake()\n- def load_manifest(self, viewable_id, dolby, hevc, hdr, dolbyvision):\n+ def load_manifest(self, viewable_id, dolby, hevc, hdr, dolbyvision, vp9):\n\"\"\"\nLoads the manifets for the given viewable_id and\nreturns a mpd-XML-Manifest\n@@ -83,8 +83,6 @@ class MSL(object):\n'playready-h264mpl30-dash',\n'playready-h264mpl31-dash',\n'playready-h264mpl40-dash',\n- 'vp9-profile0-L30-dash-cenc',\n- 'vp9-profile0-L31-dash-cenc',\n# Audio\n'heaac-2-dash',\n@@ -124,7 +122,7 @@ class MSL(object):\n# add hevc profiles if setting is set\nif hevc is True:\n- hevc = 'hevc-main-'\n+ main = 'hevc-main-'\nmain10 = 'hevc-main10-'\nprk = 'dash-cenc-prk'\ncenc = 'dash-cenc'\n@@ -132,12 +130,12 @@ class MSL(object):\nmanifest_request_data['profiles'].append(main10 + 'L41-' + cenc)\nmanifest_request_data['profiles'].append(main10 + 'L50-' + cenc)\nmanifest_request_data['profiles'].append(main10 + 'L51-' + cenc)\n- manifest_request_data['profiles'].append(hevc + 'L30-' + cenc)\n- manifest_request_data['profiles'].append(hevc + 'L31-' + cenc)\n- manifest_request_data['profiles'].append(hevc + 'L40-' + cenc)\n- manifest_request_data['profiles'].append(hevc + 'L41-' + cenc)\n- manifest_request_data['profiles'].append(hevc + 'L50-' + cenc)\n- manifest_request_data['profiles'].append(hevc + 'L51-' + cenc)\n+ manifest_request_data['profiles'].append(main + 'L30-' + cenc)\n+ manifest_request_data['profiles'].append(main + 'L31-' + cenc)\n+ manifest_request_data['profiles'].append(main + 'L40-' + cenc)\n+ manifest_request_data['profiles'].append(main + 'L41-' + cenc)\n+ manifest_request_data['profiles'].append(main + 'L50-' + cenc)\n+ manifest_request_data['profiles'].append(main + 'L51-' + cenc)\nmanifest_request_data['profiles'].append(main10 + 'L30-' + cenc)\nmanifest_request_data['profiles'].append(main10 + 'L31-' + cenc)\nmanifest_request_data['profiles'].append(main10 + 'L40-' + cenc)\n@@ -148,10 +146,10 @@ class MSL(object):\nmanifest_request_data['profiles'].append(main10 + 'L31-' + prk)\nmanifest_request_data['profiles'].append(main10 + 'L40-' + prk)\nmanifest_request_data['profiles'].append(main10 + 'L41-' + prk)\n- manifest_request_data['profiles'].append(hevc + 'L30-L31-' + ctl)\n- manifest_request_data['profiles'].append(hevc + 'L31-L40-' + ctl)\n- manifest_request_data['profiles'].append(hevc + 'L40-L41-' + ctl)\n- manifest_request_data['profiles'].append(hevc + 'L50-L51-' + ctl)\n+ manifest_request_data['profiles'].append(main + 'L30-L31-' + ctl)\n+ manifest_request_data['profiles'].append(main + 'L31-L40-' + ctl)\n+ manifest_request_data['profiles'].append(main + 'L40-L41-' + ctl)\n+ manifest_request_data['profiles'].append(main + 'L50-L51-' + ctl)\nmanifest_request_data['profiles'].append(main10 + 'L30-L31-' + ctl)\nmanifest_request_data['profiles'].append(main10 + 'L31-L40-' + ctl)\nmanifest_request_data['profiles'].append(main10 + 'L40-L41-' + ctl)\n@@ -189,6 +187,10 @@ class MSL(object):\nmanifest_request_data['profiles'].append(dv5 + 'L50-' + prk)\nmanifest_request_data['profiles'].append(dv5 + 'L51-' + prk)\n+ if hevc is False or vp9 is True:\n+ manifest_request_data['profiles'].append('vp9-profile0-L30-dash-cenc')\n+ manifest_request_data['profiles'].append('vp9-profile0-L31-dash-cenc')\n+\n# Check if dolby sound is enabled and add to profles\nif dolby:\nmanifest_request_data['profiles'].append('ddplus-2.0-dash')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSLHttpRequestHandler.py",
"new_path": "resources/lib/MSLHttpRequestHandler.py",
"diff": "@@ -61,10 +61,12 @@ class MSLHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\nparams['hdr'][0].lower() == 'true' else 'false')\ndolbyvision = (True if 'dolbyvision' in params and\nparams['dolbyvision'][0].lower() == 'true' else 'false')\n+ vp9 = (True if 'vp9' in params and\n+ params['vp9'][0].lower() == 'true' else 'false')\ndata = self.server.msl_handler.load_manifest(\nint(params['id'][0]),\n- dolby, hevc, hdr, dolbyvision)\n+ dolby, hevc, hdr, dolbyvision, vp9)\nself.send_response(200)\nself.send_header('Content-type', 'application/xml')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/settings.xml",
"new_path": "resources/settings.xml",
"diff": "<setting id=\"enable_hevc_profiles\" type=\"bool\" label=\"30060\" default=\"false\"/>\n<setting id=\"enable_hdr_profiles\" type=\"bool\" label=\"30084\" default=\"false\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n<setting id=\"enable_dolbyvision_profiles\" type=\"bool\" label=\"30085\" default=\"false\" visible=\"eq(-2,true)\" subsetting=\"true\"/>\n+ <setting id=\"enable_vp9_profiles\" type=\"bool\" label=\"30086\" default=\"false\" visible=\"eq(-3,true)\" subsetting=\"true\"/>\n<setting id=\"ssl_verification\" type=\"bool\" label=\"30024\" default=\"true\"/>\n<setting id=\"enable_tracking\" type=\"bool\" label=\"30032\" default=\"true\"/>\n<setting id=\"esn\" type=\"text\" label=\"30034\" value=\"\" default=\"\"/>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | VP9 optional if HEVC profiles are selected |
105,992 | 22.11.2018 14:43:19 | -3,600 | 86894ce4bb7c0013d4824f61e4e451300bfb9c04 | Implement version_compare for VTT subs | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSL.py",
"new_path": "resources/lib/MSL.py",
"diff": "@@ -115,7 +115,7 @@ class MSL(object):\n# subtitles\naddon = xbmcaddon.Addon('inputstream.adaptive')\n- if addon and addon.getAddonInfo('version') >= '2.3.8':\n+ if addon and self.nx_common.compare_versions(map(int, addon.getAddonInfo('version').split('.')), [2, 3, 8]):\nmanifest_request_data['profiles'].append('webvtt-lssdh-ios8')\nelse:\nmanifest_request_data['profiles'].append('simplesdh')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/NetflixCommon.py",
"new_path": "resources/lib/NetflixCommon.py",
"diff": "@@ -157,3 +157,14 @@ class NetflixCommon(object):\n@staticmethod\ndef list_dir(data_path):\nreturn xbmcvfs.listdir(data_path)\n+\n+ @staticmethod\n+ def compare_versions(v1, v2):\n+ if len(v1) != len(v2):\n+ return len(v1) - len(v2)\n+ for i in range(0, len(v1)):\n+ if v1[i] > v2[1]:\n+ return 1\n+ elif v1[i] < v2[1]:\n+ return -1\n+ return 0\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Implement version_compare for VTT subs |
105,992 | 24.11.2018 11:12:23 | -3,600 | 80b9445560c165cfabb0826cccd9e16c42196a89 | Version bump 0.13.19 | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.18\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.19\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Version bump 0.13.19 |
105,992 | 26.11.2018 13:38:42 | -3,600 | 5d363569b025247f5005a2266e69efddb1476cc7 | Fix parameter values for stream play | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSLHttpRequestHandler.py",
"new_path": "resources/lib/MSLHttpRequestHandler.py",
"diff": "@@ -54,15 +54,15 @@ class MSLHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\nelse:\n# Get the manifest with the given id\ndolby = (True if 'dolby' in params and\n- params['dolby'][0].lower() == 'true' else 'false')\n+ params['dolby'][0].lower() == 'true' else False)\nhevc = (True if 'hevc' in params and\n- params['hevc'][0].lower() == 'true' else 'false')\n+ params['hevc'][0].lower() == 'true' else False)\nhdr = (True if 'hdr' in params and\n- params['hdr'][0].lower() == 'true' else 'false')\n+ params['hdr'][0].lower() == 'true' else False)\ndolbyvision = (True if 'dolbyvision' in params and\n- params['dolbyvision'][0].lower() == 'true' else 'false')\n+ params['dolbyvision'][0].lower() == 'true' else False)\nvp9 = (True if 'vp9' in params and\n- params['vp9'][0].lower() == 'true' else 'false')\n+ params['vp9'][0].lower() == 'true' else False)\ndata = self.server.msl_handler.load_manifest(\nint(params['id'][0]),\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix parameter values for stream play |
105,992 | 29.11.2018 13:11:04 | -3,600 | c2307770dadc99da6f463d08b2e5bcfa6d162eff | MSLv2 implementation | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSLHttpRequestHandler.py",
"new_path": "resources/lib/MSLHttpRequestHandler.py",
"diff": "@@ -11,7 +11,7 @@ import BaseHTTPServer\nfrom urlparse import urlparse, parse_qs\nfrom SocketServer import TCPServer\n-from resources.lib.MSL import MSL\n+from resources.lib.MSLv2 import MSL\nclass MSLHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/MSLv2.py",
"diff": "+# pylint: skip-file\n+# -*- coding: utf-8 -*-\n+# Author: trummerjo\n+# Module: MSLHttpRequestHandler\n+# Created on: 26.01.2017\n+# License: MIT https://goo.gl/5bMj3H\n+\n+import re\n+import sys\n+import zlib\n+import gzip\n+import json\n+import time\n+import base64\n+import random\n+import uuid\n+from StringIO import StringIO\n+from datetime import datetime\n+import requests\n+import xml.etree.ElementTree as ET\n+\n+import xbmcaddon\n+\n+#check if we are on Android\n+import subprocess\n+try:\n+ sdkversion = int(subprocess.check_output(\n+ ['/system/bin/getprop', 'ro.build.version.sdk']))\n+except:\n+ sdkversion = 0\n+\n+if sdkversion >= 18:\n+ from MSLMediaDrm import MSLMediaDrmCrypto as MSLHandler\n+else:\n+ from MSLCrypto import MSLCrypto as MSLHandler\n+\n+class MSL(object):\n+ # Is a handshake already performed and the keys loaded\n+ handshake_performed = False\n+ last_license_url = ''\n+ last_drm_context = ''\n+ last_playback_context = ''\n+\n+ current_message_id = 0\n+ session = requests.session()\n+ rndm = random.SystemRandom()\n+ tokens = []\n+ base_url = 'https://www.netflix.com/nq/msl_v1/cadmium/'\n+ endpoints = {\n+ 'manifest': base_url + 'pbo_manifests/%5E1.0.0/router',\n+ #'license': base_url + 'pbo_licenses/%5E1.0.0/router'\n+ 'license': 'http://www.netflix.com/api/msl/NFCDCH-LX/cadmium/license'\n+ }\n+\n+ def __init__(self, nx_common):\n+\n+ \"\"\"\n+ The Constructor checks for already existing crypto Keys.\n+ If they exist it will load the existing keys\n+ \"\"\"\n+ self.nx_common = nx_common\n+\n+ self.crypto = MSLHandler(nx_common)\n+\n+ if self.nx_common.file_exists(self.nx_common.data_path, 'msl_data.json'):\n+ self.init_msl_data()\n+ else:\n+ self.crypto.fromDict(None)\n+ self.__perform_key_handshake()\n+\n+ def load_manifest(self, viewable_id, dolby, hevc, hdr, dolbyvision, vp9):\n+ \"\"\"\n+ Loads the manifets for the given viewable_id and\n+ returns a mpd-XML-Manifest\n+\n+ :param viewable_id: The id of of the viewable\n+ :return: MPD XML Manifest or False if no success\n+ \"\"\"\n+ esn = self.nx_common.get_esn()\n+ manifest_request_data = {\n+ 'version': 2,\n+ 'url': '/manifest',\n+ 'id': 15423166626396,\n+ 'esn': esn,\n+ 'languages': ['de-US'],\n+ 'uiVersion': 'shakti-vb45817f4',\n+ 'clientVersion': '6.0011.474.011',\n+ 'params': {\n+ 'type': 'standard',\n+ 'viewableId': [viewable_id],\n+ 'flavor': 'PRE_FETCH',\n+ 'drmType': 'widevine',\n+ 'drmVersion': 25,\n+ 'usePsshBox': True,\n+ 'isBranching': False,\n+ 'useHttpsStreams': True,\n+ 'imageSubtitleHeight': 1080,\n+ 'uiVersion': 'shakti-vb45817f4',\n+ 'clientVersion': '6.0011.474.011',\n+ 'supportsPreReleasePin': True,\n+ 'supportsWatermark': True,\n+ 'showAllSubDubTracks': False,\n+ 'titleSpecificData': {},\n+ 'videoOutputInfo': [{\n+ 'type': 'DigitalVideoOutputDescriptor',\n+ 'outputType': 'unknown',\n+ 'supportedHdcpVersions': [],\n+ 'isHdcpEngaged': False\n+ }],\n+ 'preferAssistiveAudio': False,\n+ 'isNonMember': False\n+ }\n+ }\n+ manifest_request_data['params']['titleSpecificData'][viewable_id] = { 'unletterboxed': False }\n+\n+ profiles = ['playready-h264mpl30-dash', 'playready-h264mpl31-dash', 'playready-h264hpl30-dash', 'playready-h264hpl31-dash', 'heaac-2-dash', 'BIF240', 'BIF320']\n+\n+ # subtitles\n+ addon = xbmcaddon.Addon('inputstream.adaptive')\n+ if addon and self.nx_common.compare_versions(map(int, addon.getAddonInfo('version').split('.')), [2, 3, 8]):\n+ profiles.append('webvtt-lssdh-ios8')\n+ else:\n+ profiles.append('simplesdh')\n+\n+ # add hevc profiles if setting is set\n+ if hevc is True:\n+ main = 'hevc-main-'\n+ main10 = 'hevc-main10-'\n+ prk = 'dash-cenc-prk'\n+ cenc = 'dash-cenc'\n+ ctl = 'dash-cenc-tl'\n+ profiles.append(main10 + 'L41-' + cenc)\n+ profiles.append(main10 + 'L50-' + cenc)\n+ profiles.append(main10 + 'L51-' + cenc)\n+ profiles.append(main + 'L30-' + cenc)\n+ profiles.append(main + 'L31-' + cenc)\n+ profiles.append(main + 'L40-' + cenc)\n+ profiles.append(main + 'L41-' + cenc)\n+ profiles.append(main + 'L50-' + cenc)\n+ profiles.append(main + 'L51-' + cenc)\n+ profiles.append(main10 + 'L30-' + cenc)\n+ profiles.append(main10 + 'L31-' + cenc)\n+ profiles.append(main10 + 'L40-' + cenc)\n+ profiles.append(main10 + 'L41-' + cenc)\n+ profiles.append(main10 + 'L50-' + cenc)\n+ profiles.append(main10 + 'L51-' + cenc)\n+ profiles.append(main10 + 'L30-' + prk)\n+ profiles.append(main10 + 'L31-' + prk)\n+ profiles.append(main10 + 'L40-' + prk)\n+ profiles.append(main10 + 'L41-' + prk)\n+ profiles.append(main + 'L30-L31-' + ctl)\n+ profiles.append(main + 'L31-L40-' + ctl)\n+ profiles.append(main + 'L40-L41-' + ctl)\n+ profiles.append(main + 'L50-L51-' + ctl)\n+ profiles.append(main10 + 'L30-L31-' + ctl)\n+ profiles.append(main10 + 'L31-L40-' + ctl)\n+ profiles.append(main10 + 'L40-L41-' + ctl)\n+ profiles.append(main10 + 'L50-L51-' + ctl)\n+\n+ if hdr is True:\n+ hdr = 'hevc-hdr-main10-'\n+ profiles.append(hdr + 'L30-' + cenc)\n+ profiles.append(hdr + 'L31-' + cenc)\n+ profiles.append(hdr + 'L40-' + cenc)\n+ profiles.append(hdr + 'L41-' + cenc)\n+ profiles.append(hdr + 'L50-' + cenc)\n+ profiles.append(hdr + 'L51-' + cenc)\n+ profiles.append(hdr + 'L30-' + prk)\n+ profiles.append(hdr + 'L31-' + prk)\n+ profiles.append(hdr + 'L40-' + prk)\n+ profiles.append(hdr + 'L41-' + prk)\n+ profiles.append(hdr + 'L50-' + prk)\n+ profiles.append(hdr + 'L51-' + prk)\n+\n+\n+ if dolbyvision is True:\n+ dv = 'hevc-dv-main10-'\n+ dv5 = 'hevc-dv5-main10-'\n+ profiles.append(dv + 'L30-' + cenc)\n+ profiles.append(dv + 'L31-' + cenc)\n+ profiles.append(dv + 'L40-' + cenc)\n+ profiles.append(dv + 'L41-' + cenc)\n+ profiles.append(dv + 'L50-' + cenc)\n+ profiles.append(dv + 'L51-' + cenc)\n+ profiles.append(dv5 + 'L30-' + prk)\n+ profiles.append(dv5 + 'L31-' + prk)\n+ profiles.append(dv5 + 'L40-' + prk)\n+ profiles.append(dv5 + 'L41-' + prk)\n+ profiles.append(dv5 + 'L50-' + prk)\n+ profiles.append(dv5 + 'L51-' + prk)\n+\n+ if hevc is False or vp9 is True:\n+ profiles.append('vp9-profile0-L30-dash-cenc')\n+ profiles.append('vp9-profile0-L31-dash-cenc')\n+\n+ # Check if dolby sound is enabled and add to profles\n+ if dolby:\n+ profiles.append('ddplus-2.0-dash')\n+ profiles.append('ddplus-5.1-dash')\n+\n+ manifest_request_data[\"params\"][\"profiles\"] = profiles\n+ print manifest_request_data\n+\n+ request_data = self.__generate_msl_request_data(manifest_request_data)\n+\n+ try:\n+ resp = self.session.post(self.endpoints['manifest'], request_data)\n+ except:\n+ resp = None\n+ exc = sys.exc_info()\n+ msg = '[MSL][POST] Error {} {}'\n+ self.nx_common.log(msg=msg.format(exc[0], exc[1]))\n+\n+ if resp:\n+ try:\n+ # if the json() does not fail we have an error because\n+ # the manifest response is a chuncked json response\n+ resp.json()\n+ self.nx_common.log(\n+ msg='Error getting Manifest: ' + resp.text)\n+ return False\n+ except ValueError:\n+ # json() failed so parse the chunked response\n+ #self.nx_common.log(\n+ # msg='Got chunked Manifest Response: ' + resp.text)\n+ resp = self.__parse_chunked_msl_response(resp.text)\n+ #self.nx_common.log(\n+ # msg='Parsed chunked Response: ' + json.dumps(resp))\n+ data = self.__decrypt_payload_chunks(resp['payloads'])\n+ return self.__tranform_to_dash(data)\n+ return False\n+\n+ def get_license(self, challenge, sid):\n+ \"\"\"\n+ Requests and returns a license for the given challenge and sid\n+ :param challenge: The base64 encoded challenge\n+ :param sid: The sid paired to the challengew\n+ :return: Base64 representation of the licensekey or False unsuccessfull\n+ \"\"\"\n+ esn = self.nx_common.get_esn()\n+ id = int(time.time() * 10000)\n+ '''license_request_data = {\n+ 'version': 2,\n+ 'url': self.last_license_url,\n+ 'id': id,\n+ 'esn': esn,\n+ 'languages': ['de-US'],\n+ 'uiVersion': 'shakti-v25d2fa21',\n+ 'clientVersion': '6.0011.511.011',\n+ 'params': [{\n+ 'sessionId': sid,\n+ 'clientTime': int(id / 10000),\n+ 'challengeBase64': challenge,\n+ 'xid': str(id + 1610)\n+ }],\n+ 'echo': 'sessionId'\n+ }'''\n+\n+ license_request_data = {\n+ 'method': 'license',\n+ 'licenseType': 'STANDARD',\n+ 'clientVersion': '4.0004.899.011',\n+ 'uiVersion': 'akira',\n+ 'languages': ['de-DE'],\n+ 'playbackContextId': self.last_playback_context,\n+ 'drmContextIds': [self.last_drm_context],\n+ 'challenges': [{\n+ 'dataBase64': challenge,\n+ 'sessionId': sid\n+ }],\n+ 'clientTime': int(id / 10000),\n+ 'xid': id + 1610\n+ }\n+\n+ #print license_request_data\n+\n+ request_data = self.__generate_msl_request_data(license_request_data)\n+\n+ try:\n+ resp = self.session.post(self.endpoints['license'], request_data)\n+ except:\n+ resp = None\n+ exc = sys.exc_info()\n+ self.nx_common.log(\n+ msg='[MSL][POST] Error {} {}'.format(exc[0], exc[1]))\n+\n+ print resp\n+\n+ if resp:\n+ try:\n+ # If is valid json the request for the licnese failed\n+ resp.json()\n+ self.nx_common.log(msg='Error getting license: '+resp.text)\n+ return False\n+ except ValueError:\n+ # json() failed so we have a chunked json response\n+ resp = self.__parse_chunked_msl_response(resp.text)\n+ data = self.__decrypt_payload_chunks(resp['payloads'])\n+ if data['success'] is True:\n+ return data['result']['licenses'][0]['data']\n+ else:\n+ self.nx_common.log(\n+ msg='Error getting license: ' + json.dumps(data))\n+ return False\n+ return False\n+\n+ def __decrypt_payload_chunks(self, payloadchunks):\n+ decrypted_payload = ''\n+ for chunk in payloadchunks:\n+ payloadchunk = json.JSONDecoder().decode(chunk)\n+ payload = payloadchunk.get('payload')\n+ decoded_payload = base64.standard_b64decode(payload)\n+ encryption_envelope = json.JSONDecoder().decode(decoded_payload)\n+ # Decrypt the text\n+ plaintext = self.crypto.decrypt(base64.standard_b64decode(encryption_envelope['iv']),\n+ base64.standard_b64decode(encryption_envelope.get('ciphertext')))\n+ # unpad the plaintext\n+ plaintext = json.JSONDecoder().decode(plaintext)\n+ data = plaintext.get('data')\n+\n+ # uncompress data if compressed\n+ if plaintext.get('compressionalgo') == 'GZIP':\n+ decoded_data = base64.standard_b64decode(data)\n+ data = zlib.decompress(decoded_data, 16 + zlib.MAX_WBITS)\n+ else:\n+ data = base64.standard_b64decode(data)\n+ decrypted_payload += data\n+\n+ decrypted_payload = json.JSONDecoder().decode(decrypted_payload)[1]['payload']\n+ if 'json' in decrypted_payload:\n+ return decrypted_payload['json']['result']\n+ else:\n+ decrypted_payload = base64.standard_b64decode(decrypted_payload['data'])\n+ return json.JSONDecoder().decode(decrypted_payload)\n+\n+\n+ def __tranform_to_dash(self, manifest):\n+\n+ self.nx_common.save_file(\n+ data_path=self.nx_common.data_path,\n+ filename='manifest.json',\n+ content=json.dumps(manifest))\n+\n+ self.last_license_url = manifest['links']['ldl']['href']\n+ self.last_playback_context = manifest['playbackContextId']\n+ self.last_drm_context = manifest['drmContextId']\n+\n+ seconds = manifest['duration'] / 1000\n+ init_length = seconds / 2 * 12 + 20 * 1000\n+ duration = \"PT\" + str(seconds) + \".00S\"\n+\n+ root = ET.Element('MPD')\n+ root.attrib['xmlns'] = 'urn:mpeg:dash:schema:mpd:2011'\n+ root.attrib['xmlns:cenc'] = 'urn:mpeg:cenc:2013'\n+ root.attrib['mediaPresentationDuration'] = duration\n+\n+ period = ET.SubElement(root, 'Period', start='PT0S', duration=duration)\n+\n+ # One Adaption Set for Video\n+ for video_track in manifest['video_tracks']:\n+ video_adaption_set = ET.SubElement(\n+ parent=period,\n+ tag='AdaptationSet',\n+ mimeType='video/mp4',\n+ contentType=\"video\")\n+\n+ # Content Protection\n+ keyid = None\n+ pssh = None\n+ if 'drmHeader' in video_track:\n+ keyid = video_track['drmHeader']['keyId']\n+ pssh = video_track['drmHeader']['bytes']\n+\n+ if keyid:\n+ protection = ET.SubElement(\n+ parent=video_adaption_set,\n+ tag='ContentProtection',\n+ value='cenc',\n+ schemeIdUri='urn:mpeg:dash:mp4protection:2011')\n+ protection.set('cenc:default_KID', str(uuid.UUID(bytes=base64.standard_b64decode(keyid))))\n+\n+ protection = ET.SubElement(\n+ parent=video_adaption_set,\n+ tag='ContentProtection',\n+ schemeIdUri='urn:uuid:EDEF8BA9-79D6-4ACE-A3C8-27DCD51D21ED')\n+\n+ ET.SubElement(\n+ parent=protection,\n+ tag='widevine:license',\n+ robustness_level='HW_SECURE_CODECS_REQUIRED')\n+\n+ if pssh:\n+ ET.SubElement(protection, 'cenc:pssh').text = pssh\n+\n+ for stream in video_track['streams']:\n+\n+ codec = 'h264'\n+ if 'hevc' in stream['content_profile']:\n+ codec = 'hevc'\n+ elif stream['content_profile'] == 'vp9-profile0-L30-dash-cenc':\n+ codec = 'vp9.0.30'\n+ elif stream['content_profile'] == 'vp9-profile0-L31-dash-cenc':\n+ codec = 'vp9.0.31'\n+\n+ hdcp_versions = '0.0'\n+ #for hdcp in stream['hdcpVersions']:\n+ # if hdcp != 'none':\n+ # hdcp_versions = hdcp if hdcp != 'any' else '1.0'\n+\n+ rep = ET.SubElement(\n+ parent=video_adaption_set,\n+ tag='Representation',\n+ width=str(stream['res_w']),\n+ height=str(stream['res_h']),\n+ bandwidth=str(stream['bitrate']*1024),\n+ frameRate='%d/%d' % (stream['framerate_value'], stream['framerate_scale']),\n+ hdcp=hdcp_versions,\n+ nflxContentProfile=str(stream['content_profile']),\n+ codecs=codec,\n+ mimeType='video/mp4')\n+\n+ # BaseURL\n+ base_url = self.__get_base_url(stream['urls'])\n+ ET.SubElement(rep, 'BaseURL').text = base_url\n+ # Init an Segment block\n+ if 'startByteOffset' in stream:\n+ initSize = stream['startByteOffset']\n+ else:\n+ sidx = stream['sidx']\n+ initSize = sidx['offset'] + sidx['size']\n+\n+ segment_base = ET.SubElement(\n+ parent=rep,\n+ tag='SegmentBase',\n+ indexRange='0-' + str(initSize),\n+ indexRangeExact='true')\n+\n+ # Multiple Adaption Set for audio\n+ languageMap = {}\n+ channelCount = {'1.0':'1', '2.0':'2', '5.1':'6', '7.1':'8'}\n+\n+ for audio_track in manifest['audio_tracks']:\n+ impaired = 'true' if audio_track['trackType'] == 'ASSISTIVE' else 'false'\n+ original = 'true' if audio_track['isNative'] else 'false'\n+ default = 'false' if audio_track['language'] in languageMap else 'true'\n+ languageMap[audio_track['language']] = True\n+\n+ audio_adaption_set = ET.SubElement(\n+ parent=period,\n+ tag='AdaptationSet',\n+ lang=audio_track['language'],\n+ contentType='audio',\n+ mimeType='audio/mp4',\n+ impaired=impaired,\n+ original=original,\n+ default=default)\n+ for stream in audio_track['streams']:\n+ codec = 'aac'\n+ #self.nx_common.log(msg=stream)\n+ is_dplus2 = stream['content_profile'] == 'ddplus-2.0-dash'\n+ is_dplus5 = stream['content_profile'] == 'ddplus-5.1-dash'\n+ if is_dplus2 or is_dplus5:\n+ codec = 'ec-3'\n+ #self.nx_common.log(msg='codec is: ' + codec)\n+ rep = ET.SubElement(\n+ parent=audio_adaption_set,\n+ tag='Representation',\n+ codecs=codec,\n+ bandwidth=str(stream['bitrate']*1024),\n+ mimeType='audio/mp4')\n+\n+ # AudioChannel Config\n+ ET.SubElement(\n+ parent=rep,\n+ tag='AudioChannelConfiguration',\n+ schemeIdUri='urn:mpeg:dash:23003:3:audio_channel_configuration:2011',\n+ value=channelCount[stream['channels']])\n+\n+ # BaseURL\n+ base_url = self.__get_base_url(stream['urls'])\n+ ET.SubElement(rep, 'BaseURL').text = base_url\n+ # Index range\n+ segment_base = ET.SubElement(\n+ parent=rep,\n+ tag='SegmentBase',\n+ indexRange='0-' + str(init_length),\n+ indexRangeExact='true')\n+\n+\n+ # Multiple Adaption Sets for subtiles\n+ for text_track in manifest.get('timedtexttracks'):\n+ if text_track['isNoneTrack']:\n+ continue\n+ # Only one subtitle representation per adaptationset\n+ downloadable = text_track['ttDownloadables']\n+ content_profile = downloadable.keys()[0]\n+\n+ subtiles_adaption_set = ET.SubElement(\n+ parent=period,\n+ tag='AdaptationSet',\n+ lang=text_track.get('language'),\n+ codecs='wvtt' if content_profile == 'webvtt-lssdh-ios8' else 'stpp',\n+ contentType='text',\n+ mimeType='text/vtt' if content_profile == 'webvtt-lssdh-ios8' else 'application/ttml+xml')\n+ role = ET.SubElement(\n+ parent=subtiles_adaption_set,\n+ tag = 'Role',\n+ schemeIdUri = 'urn:mpeg:dash:role:2011',\n+ value = 'forced' if text_track.get('isForcedNarrative') else 'main')\n+ rep = ET.SubElement(\n+ parent=subtiles_adaption_set,\n+ tag='Representation',\n+ nflxProfile=content_profile)\n+\n+ base_url = downloadable[content_profile]['downloadUrls'].values()[0]\n+ ET.SubElement(rep, 'BaseURL').text = base_url\n+\n+ xml = ET.tostring(root, encoding='utf-8', method='xml')\n+ xml = xml.replace('\\n', '').replace('\\r', '')\n+\n+ self.nx_common.save_file(\n+ data_path=self.nx_common.data_path,\n+ filename='manifest.mpd',\n+ content=xml)\n+\n+ return xml\n+\n+ def __get_base_url(self, urls):\n+ for url in urls:\n+ return url['url']\n+\n+ def __parse_chunked_msl_response(self, message):\n+ header = message.split('}}')[0] + '}}'\n+ payloads = re.split(',\\\"signature\\\":\\\"[0-9A-Za-z=/+]+\\\"}', message.split('}}')[1])\n+ payloads = [x + '}' for x in payloads][:-1]\n+\n+ return {\n+ 'header': header,\n+ 'payloads': payloads\n+ }\n+\n+ def __generate_msl_request_data(self, data):\n+ #self.__load_msl_data()\n+ header_encryption_envelope = self.__encrypt(\n+ plaintext=self.__generate_msl_header())\n+ headerdata = base64.standard_b64encode(header_encryption_envelope)\n+ header = {\n+ 'headerdata': headerdata,\n+ 'signature': self.__sign(header_encryption_envelope),\n+ 'mastertoken': self.mastertoken,\n+ }\n+\n+ # Serialize the given Data\n+ raw_marshalled_data = json.dumps(data)\n+ marshalled_data = raw_marshalled_data.replace('\"', '\\\\\"')\n+ serialized_data = '[{},{\"headers\":{},\"path\":\"/cbp/cadmium-13\"'\n+ serialized_data += ',\"payload\":{\"data\":\"'\n+ serialized_data += marshalled_data\n+ serialized_data += '\"},\"query\":\"\"}]\\n'\n+\n+ compressed_data = self.__compress_data(serialized_data)\n+\n+ # Create FIRST Payload Chunks\n+ first_payload = {\n+ 'messageid': self.current_message_id,\n+ 'data': compressed_data,\n+ 'compressionalgo': 'GZIP',\n+ 'sequencenumber': 1,\n+ 'endofmsg': True\n+ }\n+ first_payload_encryption_envelope = self.__encrypt(\n+ plaintext=json.dumps(first_payload))\n+ payload = base64.standard_b64encode(first_payload_encryption_envelope)\n+ first_payload_chunk = {\n+ 'payload': payload,\n+ 'signature': self.__sign(first_payload_encryption_envelope),\n+ }\n+ request_data = json.dumps(header) + json.dumps(first_payload_chunk)\n+ return request_data\n+\n+ def __compress_data(self, data):\n+ # GZIP THE DATA\n+ out = StringIO()\n+ with gzip.GzipFile(fileobj=out, mode=\"w\") as f:\n+ f.write(data)\n+ return base64.standard_b64encode(out.getvalue())\n+\n+ def __generate_msl_header(\n+ self,\n+ is_handshake=False,\n+ is_key_request=False,\n+ compressionalgo='GZIP',\n+ encrypt=True):\n+ \"\"\"\n+ Function that generates a MSL header dict\n+ :return: The base64 encoded JSON String of the header\n+ \"\"\"\n+ self.current_message_id = self.rndm.randint(0, pow(2, 52))\n+ esn = self.nx_common.get_esn()\n+\n+ # Add compression algo if not empty\n+ compression_algos = [compressionalgo] if compressionalgo != '' else []\n+\n+ header_data = {\n+ 'sender': esn,\n+ 'handshake': is_handshake,\n+ 'nonreplayable': False,\n+ 'capabilities': {\n+ 'languages': ['en-US'],\n+ 'compressionalgos': compression_algos\n+ },\n+ 'recipient': 'Netflix',\n+ 'renewable': True,\n+ 'messageid': self.current_message_id,\n+ 'timestamp': 1467733923\n+ }\n+\n+ # If this is a keyrequest act diffrent then other requests\n+ if is_key_request:\n+ header_data['keyrequestdata'] = self.crypto.get_key_request()\n+ else:\n+ if 'usertoken' in self.tokens:\n+ pass\n+ else:\n+ account = self.nx_common.get_credentials()\n+ # Auth via email and password\n+ header_data['userauthdata'] = {\n+ 'scheme': 'EMAIL_PASSWORD',\n+ 'authdata': {\n+ 'email': account['email'],\n+ 'password': account['password']\n+ }\n+ }\n+\n+ return json.dumps(header_data)\n+\n+ def __encrypt(self, plaintext):\n+ return json.dumps(self.crypto.encrypt(plaintext, self.nx_common.get_esn(), self.sequence_number))\n+\n+ def __sign(self, text):\n+ \"\"\"\n+ Calculates the HMAC signature for the given\n+ text with the current sign key and SHA256\n+\n+ :param text:\n+ :return: Base64 encoded signature\n+ \"\"\"\n+ return base64.standard_b64encode(self.crypto.sign(text))\n+\n+ def perform_key_handshake(self):\n+ self.__perform_key_handshake()\n+\n+ def __perform_key_handshake(self):\n+ esn = self.nx_common.get_esn()\n+ self.nx_common.log(msg='perform_key_handshake: esn:' + esn)\n+\n+ if not esn:\n+ return False\n+\n+ header = self.__generate_msl_header(\n+ is_key_request=True,\n+ is_handshake=True,\n+ compressionalgo='',\n+ encrypt=False)\n+\n+ request = {\n+ 'entityauthdata': {\n+ 'scheme': 'NONE',\n+ 'authdata': {\n+ 'identity': esn\n+ }\n+ },\n+ 'headerdata': base64.standard_b64encode(header),\n+ 'signature': '',\n+ }\n+ #self.nx_common.log(msg='Key Handshake Request:')\n+ #self.nx_common.log(msg=json.dumps(request))\n+\n+ try:\n+ resp = self.session.post(\n+ url=self.endpoints['manifest'],\n+ data=json.dumps(request, sort_keys=True))\n+ except:\n+ resp = None\n+ exc = sys.exc_info()\n+ self.nx_common.log(\n+ msg='[MSL][POST] Error {} {}'.format(exc[0], exc[1]))\n+\n+ if resp and resp.status_code == 200:\n+ resp = resp.json()\n+ if 'errordata' in resp:\n+ self.nx_common.log(msg='Key Exchange failed')\n+ self.nx_common.log(\n+ msg=base64.standard_b64decode(resp['errordata']))\n+ return False\n+ base_head = base64.standard_b64decode(resp['headerdata'])\n+\n+ headerdata=json.JSONDecoder().decode(base_head)\n+ self.__set_master_token(headerdata['keyresponsedata']['mastertoken'])\n+ self.crypto.parse_key_response(headerdata)\n+ self.__save_msl_data()\n+ else:\n+ self.nx_common.log(msg='Key Exchange failed')\n+ self.nx_common.log(msg=resp.text)\n+\n+ def init_msl_data(self):\n+ self.nx_common.log(msg='MSL Data exists. Use old Tokens.')\n+ self.__load_msl_data()\n+ self.handshake_performed = True\n+\n+ def __load_msl_data(self):\n+ raw_msl_data = self.nx_common.load_file(\n+ data_path=self.nx_common.data_path,\n+ filename='msl_data.json')\n+ msl_data = json.JSONDecoder().decode(raw_msl_data)\n+ # Check expire date of the token\n+ raw_token = msl_data['tokens']['mastertoken']['tokendata']\n+ base_token = base64.standard_b64decode(raw_token)\n+ master_token = json.JSONDecoder().decode(base_token)\n+ exp = int(master_token['expiration'])\n+ valid_until = datetime.utcfromtimestamp(exp)\n+ present = datetime.now()\n+ difference = valid_until - present\n+ # If token expires in less then 10 hours or is expires renew it\n+ self.nx_common.log(msg='Expiration time: Key:' + str(valid_until) + ', Now:' + str(present) + ', Diff:' + str(difference.total_seconds()))\n+ difference = difference.total_seconds() / 60 / 60\n+ if self.crypto.fromDict(msl_data) or difference < 10:\n+ self.__perform_key_handshake()\n+ return\n+\n+ self.__set_master_token(msl_data['tokens']['mastertoken'])\n+\n+ def save_msl_data(self):\n+ self.__save_msl_data()\n+\n+ def __save_msl_data(self):\n+ \"\"\"\n+ Saves the keys and tokens in json file\n+ :return:\n+ \"\"\"\n+ data = {\n+ 'tokens': {\n+ 'mastertoken': self.mastertoken\n+ }\n+ }\n+ data.update(self.crypto.toDict())\n+\n+ serialized_data = json.JSONEncoder().encode(data)\n+ self.nx_common.save_file(\n+ data_path=self.nx_common.data_path,\n+ filename='msl_data.json',\n+ content=serialized_data)\n+\n+ def __set_master_token(self, master_token):\n+ self.mastertoken = master_token\n+ raw_token = master_token['tokendata']\n+ base_token = base64.standard_b64decode(raw_token)\n+ decoded_token = json.JSONDecoder().decode(base_token)\n+ self.sequence_number = decoded_token.get('sequencenumber')\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | MSLv2 implementation |
105,992 | 29.11.2018 13:16:13 | -3,600 | 7c433e55e796fdace07132cf1334749021920215 | Version bump 0.13.20 | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.19\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.20\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n<forum>https://www.kodinerds.net/index.php/Thread/55612-PreRelease-Plugin-Netflix-Inputstream/</forum>\n<source>https://github.com/asciidisco/plugin.video.netflix</source>\n<news>\n+v0.13.20 (2018-11-29)\n+- MSLv2 for manifest retrieval\n+\n+v0.13.19 (2018-11-24)\n+- Fix VTT / VP9 issues\n+\nv0.13.18 (2018-11-17)\n- Write correct codec into VP9 MPEG DAS profiles\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Version bump 0.13.20 |
105,992 | 29.11.2018 23:10:33 | -3,600 | 53422841020e3a697b6a4ab083aa36d85b76e47b | Add more vp9 profiles | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSLv2.py",
"new_path": "resources/lib/MSLv2.py",
"diff": "@@ -192,6 +192,15 @@ class MSL(object):\nif hevc is False or vp9 is True:\nprofiles.append('vp9-profile0-L30-dash-cenc')\nprofiles.append('vp9-profile0-L31-dash-cenc')\n+ profiles.append('vp9-profile0-L32-dash-cenc')\n+ profiles.append('vp9-profile0-L40-dash-cenc')\n+ profiles.append('vp9-profile0-L41-dash-cenc')\n+ profiles.append('vp9-profile0-L50-dash-cenc')\n+ profiles.append('vp9-profile0-L51-dash-cenc')\n+ profiles.append('vp9-profile0-L52-dash-cenc')\n+ profiles.append('vp9-profile0-L60-dash-cenc')\n+ profiles.append('vp9-profile0-L61-dash-cenc')\n+ profiles.append('vp9-profile0-L62-dash-cenc')\n# Check if dolby sound is enabled and add to profles\nif dolby:\n@@ -397,10 +406,9 @@ class MSL(object):\ncodec = 'h264'\nif 'hevc' in stream['content_profile']:\ncodec = 'hevc'\n- elif stream['content_profile'] == 'vp9-profile0-L30-dash-cenc':\n- codec = 'vp9.0.30'\n- elif stream['content_profile'] == 'vp9-profile0-L31-dash-cenc':\n- codec = 'vp9.0.31'\n+ elif 'vp9' in stream['content_profile']:\n+ lp = re.search('vp9-profile(.+?)-L(.+?)-dash', stream['content_profile'])\n+ codec = 'vp9.' + lp.group(1) + '.' + lp.group(2)\nhdcp_versions = '0.0'\n#for hdcp in stream['hdcpVersions']:\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add more vp9 profiles |
105,992 | 30.11.2018 13:00:16 | -3,600 | fe53bce6063252b021c0716ff635b0d1153c6781 | VP9 optional / fix subs for ipsa < 2.3.8 / language identifier | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSLv2.py",
"new_path": "resources/lib/MSLv2.py",
"diff": "@@ -60,6 +60,10 @@ class MSL(object):\n\"\"\"\nself.nx_common = nx_common\n+ self.locale_id = []\n+ locale_id = nx_common.get_setting('locale_id')\n+ self.locale_id.append(locale_id if locale_id else 'en-US')\n+\nself.crypto = MSLHandler(nx_common)\nif self.nx_common.file_exists(self.nx_common.data_path, 'msl_data.json'):\n@@ -82,7 +86,7 @@ class MSL(object):\n'url': '/manifest',\n'id': 15423166626396,\n'esn': esn,\n- 'languages': ['de-US'],\n+ 'languages': self.locale_id,\n'uiVersion': 'shakti-vb45817f4',\n'clientVersion': '6.0011.474.011',\n'params': {\n@@ -117,7 +121,7 @@ class MSL(object):\n# subtitles\naddon = xbmcaddon.Addon('inputstream.adaptive')\n- if addon and self.nx_common.compare_versions(map(int, addon.getAddonInfo('version').split('.')), [2, 3, 8]):\n+ if addon and self.nx_common.compare_versions(map(int, addon.getAddonInfo('version').split('.')), [2, 3, 8]) >= 0:\nprofiles.append('webvtt-lssdh-ios8')\nelse:\nprofiles.append('simplesdh')\n@@ -189,7 +193,7 @@ class MSL(object):\nprofiles.append(dv5 + 'L50-' + prk)\nprofiles.append(dv5 + 'L51-' + prk)\n- if hevc is False or vp9 is True:\n+ if vp9 is True:\nprofiles.append('vp9-profile0-L30-dash-cenc')\nprofiles.append('vp9-profile0-L31-dash-cenc')\nprofiles.append('vp9-profile0-L32-dash-cenc')\n@@ -253,7 +257,7 @@ class MSL(object):\n'url': self.last_license_url,\n'id': id,\n'esn': esn,\n- 'languages': ['de-US'],\n+ 'languages': self.locale_id,\n'uiVersion': 'shakti-v25d2fa21',\n'clientVersion': '6.0011.511.011',\n'params': [{\n@@ -270,7 +274,7 @@ class MSL(object):\n'licenseType': 'STANDARD',\n'clientVersion': '4.0004.899.011',\n'uiVersion': 'akira',\n- 'languages': ['de-DE'],\n+ 'languages': self.locale_id,\n'playbackContextId': self.last_playback_context,\n'drmContextIds': [self.last_drm_context],\n'challenges': [{\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/NetflixCommon.py",
"new_path": "resources/lib/NetflixCommon.py",
"diff": "@@ -163,8 +163,8 @@ class NetflixCommon(object):\nif len(v1) != len(v2):\nreturn len(v1) - len(v2)\nfor i in range(0, len(v1)):\n- if v1[i] > v2[1]:\n+ if v1[i] > v2[i]:\nreturn 1\n- elif v1[i] < v2[1]:\n+ elif v1[i] < v2[i]:\nreturn -1\nreturn 0\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/NetflixSession.py",
"new_path": "resources/lib/NetflixSession.py",
"diff": "@@ -112,7 +112,8 @@ class NetflixSession(object):\n'models/esnGeneratorModel/data/esn',\n'gpsModel',\n'models/userInfo/data/countryOfSignup',\n- 'models/userInfo/data/membershipStatus'\n+ 'models/userInfo/data/membershipStatus',\n+ 'models/memberContext/data/geo/preferredLocale'\n]\ndef __init__(self, cookie_path, data_path, verify_ssl, nx_common):\n@@ -2130,6 +2131,9 @@ class NetflixSession(object):\nreturn None\nself.user_data = user_data\nself.esn = self._parse_esn_data(user_data)\n+ if 'preferredLocale' in user_data:\n+ self.nx_common.set_setting('locale_id', user_data['preferredLocale']['id'])\n+\nself.api_data = {\n'API_BASE_URL': user_data.get('API_BASE_URL'),\n'API_ROOT': user_data.get('API_ROOT'),\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/settings.xml",
"new_path": "resources/settings.xml",
"diff": "<setting id=\"enable_hevc_profiles\" type=\"bool\" label=\"30060\" default=\"false\"/>\n<setting id=\"enable_hdr_profiles\" type=\"bool\" label=\"30084\" default=\"false\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n<setting id=\"enable_dolbyvision_profiles\" type=\"bool\" label=\"30085\" default=\"false\" visible=\"eq(-2,true)\" subsetting=\"true\"/>\n- <setting id=\"enable_vp9_profiles\" type=\"bool\" label=\"30086\" default=\"false\" visible=\"eq(-3,true)\" subsetting=\"true\"/>\n+ <setting id=\"enable_vp9_profiles\" type=\"bool\" label=\"30086\" default=\"false\"/>\n<setting id=\"ssl_verification\" type=\"bool\" label=\"30024\" default=\"true\"/>\n<setting id=\"enable_tracking\" type=\"bool\" label=\"30032\" default=\"true\"/>\n<setting id=\"esn\" type=\"text\" label=\"30034\" value=\"\" default=\"\"/>\n<setting id=\"hidden_esn\" visible=\"false\" value=\"\" />\n<setting id=\"tracking_id\" value=\"\" visible=\"false\"/>\n+ <setting id=\"locale_id\" visible=\"false\" value=\"en-US\" />\n<setting id=\"msl_service_port\" value=\"8000\" visible=\"false\"/>\n<setting id=\"netflix_service_port\" value=\"8001\" visible=\"false\"/>\n<setting id=\"show_update_db\" type=\"bool\" default=\"false\" visible=\"false\"/>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | VP9 optional / fix subs for ipsa < 2.3.8 / language identifier |
105,992 | 02.12.2018 20:36:15 | -3,600 | c2d113597bfee4ca1a4c4e4ec4cfca3ed158ad5d | v2 license request / Add h264 profileLevel40 streams | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/MSLv2.py",
"new_path": "resources/lib/MSLv2.py",
"diff": "import re\nimport sys\nimport zlib\n-import gzip\nimport json\nimport time\nimport base64\n@@ -48,8 +47,7 @@ class MSL(object):\nbase_url = 'https://www.netflix.com/nq/msl_v1/cadmium/'\nendpoints = {\n'manifest': base_url + 'pbo_manifests/%5E1.0.0/router',\n- #'license': base_url + 'pbo_licenses/%5E1.0.0/router'\n- 'license': 'http://www.netflix.com/api/msl/NFCDCH-LX/cadmium/license'\n+ 'license': base_url + 'pbo_licenses/%5E1.0.0/router'\n}\ndef __init__(self, nx_common):\n@@ -80,14 +78,19 @@ class MSL(object):\n:param viewable_id: The id of of the viewable\n:return: MPD XML Manifest or False if no success\n\"\"\"\n+\n+ ia_addon = xbmcaddon.Addon('inputstream.adaptive')\n+ hdcp = ia_addon is not None and ia_addon.getSetting('HDCPOVERRIDE') == 'true'\n+\nesn = self.nx_common.get_esn()\n+ id = int(time.time() * 10000)\nmanifest_request_data = {\n'version': 2,\n'url': '/manifest',\n- 'id': 15423166626396,\n+ 'id': id,\n'esn': esn,\n'languages': self.locale_id,\n- 'uiVersion': 'shakti-vb45817f4',\n+ 'uiVersion': 'shakti-v25d2fa21',\n'clientVersion': '6.0011.474.011',\n'params': {\n'type': 'standard',\n@@ -97,10 +100,10 @@ class MSL(object):\n'drmVersion': 25,\n'usePsshBox': True,\n'isBranching': False,\n- 'useHttpsStreams': True,\n+ 'useHttpsStreams': False,\n'imageSubtitleHeight': 1080,\n'uiVersion': 'shakti-vb45817f4',\n- 'clientVersion': '6.0011.474.011',\n+ 'clientVersion': '6.0011.511.011',\n'supportsPreReleasePin': True,\n'supportsWatermark': True,\n'showAllSubDubTracks': False,\n@@ -109,7 +112,7 @@ class MSL(object):\n'type': 'DigitalVideoOutputDescriptor',\n'outputType': 'unknown',\n'supportedHdcpVersions': [],\n- 'isHdcpEngaged': False\n+ 'isHdcpEngaged': hdcp\n}],\n'preferAssistiveAudio': False,\n'isNonMember': False\n@@ -117,11 +120,10 @@ class MSL(object):\n}\nmanifest_request_data['params']['titleSpecificData'][viewable_id] = { 'unletterboxed': False }\n- profiles = ['playready-h264mpl30-dash', 'playready-h264mpl31-dash', 'playready-h264hpl30-dash', 'playready-h264hpl31-dash', 'heaac-2-dash', 'BIF240', 'BIF320']\n+ profiles = ['playready-h264mpl30-dash', 'playready-h264mpl31-dash', 'playready-h264mpl40-dash', 'playready-h264hpl30-dash', 'playready-h264hpl31-dash', 'playready-h264hpl40-dash', 'heaac-2-dash', 'BIF240', 'BIF320']\n# subtitles\n- addon = xbmcaddon.Addon('inputstream.adaptive')\n- if addon and self.nx_common.compare_versions(map(int, addon.getAddonInfo('version').split('.')), [2, 3, 8]) >= 0:\n+ if ia_addon and self.nx_common.compare_versions(map(int, ia_addon.getAddonInfo('version').split('.')), [2, 3, 8]) >= 0:\nprofiles.append('webvtt-lssdh-ios8')\nelse:\nprofiles.append('simplesdh')\n@@ -212,7 +214,7 @@ class MSL(object):\nprofiles.append('ddplus-5.1-dash')\nmanifest_request_data[\"params\"][\"profiles\"] = profiles\n- print manifest_request_data\n+ #print manifest_request_data\nrequest_data = self.__generate_msl_request_data(manifest_request_data)\n@@ -252,7 +254,7 @@ class MSL(object):\n\"\"\"\nesn = self.nx_common.get_esn()\nid = int(time.time() * 10000)\n- '''license_request_data = {\n+ license_request_data = {\n'version': 2,\n'url': self.last_license_url,\n'id': id,\n@@ -267,24 +269,7 @@ class MSL(object):\n'xid': str(id + 1610)\n}],\n'echo': 'sessionId'\n- }'''\n-\n- license_request_data = {\n- 'method': 'license',\n- 'licenseType': 'STANDARD',\n- 'clientVersion': '4.0004.899.011',\n- 'uiVersion': 'akira',\n- 'languages': self.locale_id,\n- 'playbackContextId': self.last_playback_context,\n- 'drmContextIds': [self.last_drm_context],\n- 'challenges': [{\n- 'dataBase64': challenge,\n- 'sessionId': sid\n- }],\n- 'clientTime': int(id / 10000),\n- 'xid': id + 1610\n}\n-\n#print license_request_data\nrequest_data = self.__generate_msl_request_data(license_request_data)\n@@ -309,8 +294,8 @@ class MSL(object):\n# json() failed so we have a chunked json response\nresp = self.__parse_chunked_msl_response(resp.text)\ndata = self.__decrypt_payload_chunks(resp['payloads'])\n- if data['success'] is True:\n- return data['result']['licenses'][0]['data']\n+ if 'licenseResponseBase64' in data[0]:\n+ return data[0]['licenseResponseBase64']\nelse:\nself.nx_common.log(\nmsg='Error getting license: ' + json.dumps(data))\n@@ -339,7 +324,12 @@ class MSL(object):\ndata = base64.standard_b64decode(data)\ndecrypted_payload += data\n- decrypted_payload = json.JSONDecoder().decode(decrypted_payload)[1]['payload']\n+ decrypted_payload = json.JSONDecoder().decode(decrypted_payload)\n+\n+ if 'result' in decrypted_payload:\n+ return decrypted_payload['result']\n+\n+ decrypted_payload = decrypted_payload[1]['payload']\nif 'json' in decrypted_payload:\nreturn decrypted_payload['json']['result']\nelse:\n@@ -354,7 +344,7 @@ class MSL(object):\nfilename='manifest.json',\ncontent=json.dumps(manifest))\n- self.last_license_url = manifest['links']['ldl']['href']\n+ self.last_license_url = manifest['links']['license']['href']\nself.last_playback_context = manifest['playbackContextId']\nself.last_drm_context = manifest['drmContextId']\n@@ -562,21 +552,10 @@ class MSL(object):\n'mastertoken': self.mastertoken,\n}\n- # Serialize the given Data\n- raw_marshalled_data = json.dumps(data)\n- marshalled_data = raw_marshalled_data.replace('\"', '\\\\\"')\n- serialized_data = '[{},{\"headers\":{},\"path\":\"/cbp/cadmium-13\"'\n- serialized_data += ',\"payload\":{\"data\":\"'\n- serialized_data += marshalled_data\n- serialized_data += '\"},\"query\":\"\"}]\\n'\n-\n- compressed_data = self.__compress_data(serialized_data)\n-\n# Create FIRST Payload Chunks\nfirst_payload = {\n'messageid': self.current_message_id,\n- 'data': compressed_data,\n- 'compressionalgo': 'GZIP',\n+ 'data': base64.standard_b64encode(json.dumps(data)),\n'sequencenumber': 1,\n'endofmsg': True\n}\n@@ -590,13 +569,6 @@ class MSL(object):\nrequest_data = json.dumps(header) + json.dumps(first_payload_chunk)\nreturn request_data\n- def __compress_data(self, data):\n- # GZIP THE DATA\n- out = StringIO()\n- with gzip.GzipFile(fileobj=out, mode=\"w\") as f:\n- f.write(data)\n- return base64.standard_b64encode(out.getvalue())\n-\ndef __generate_msl_header(\nself,\nis_handshake=False,\n@@ -618,13 +590,13 @@ class MSL(object):\n'handshake': is_handshake,\n'nonreplayable': False,\n'capabilities': {\n- 'languages': ['en-US'],\n+ 'languages': self.locale_id,\n'compressionalgos': compression_algos\n},\n'recipient': 'Netflix',\n'renewable': True,\n'messageid': self.current_message_id,\n- 'timestamp': 1467733923\n+ 'timestamp': time.time()\n}\n# If this is a keyrequest act diffrent then other requests\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | v2 license request / Add h264 profileLevel40 streams |
105,992 | 03.12.2018 01:27:30 | -3,600 | 277499edb62447bc9ed4319d8478556937ecea40 | Version bump 0.13.21 | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.20\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.13.21\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Version bump 0.13.21 |
105,989 | 11.10.2018 14:46:11 | -7,200 | 49260f09be95883267a37ca2272cdfe830946681 | Introduce safe secret generation for password storage | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -122,40 +122,16 @@ def __crypt_key():\n__CRYPT_KEY__ = __uniq_id()\nreturn __CRYPT_KEY__\n-def __uniq_id(delay=1):\n+def __uniq_id():\n\"\"\"\nReturns a unique id based on the devices MAC address\n-\n- :param delay: Retry delay in sec\n- :type delay: int\n- :returns: string -- Unique secret\n- \"\"\"\n- import hashlib\n- mac_addr = __get_mac_address(delay=delay)\n- # Disable for now because Kodi can't reliably return the Mac address\n- # Somehow the return value seems to change over time...\n- # if ':' in mac_addr:\n- # log('Using safe crypt key based on unique ID')\n- # return hashlib.sha256(str(mac_addr).encode()).digest()\n- log('Using unsafe static secret to store credentials', LOGWARNING)\n- return hashlib.sha256('UnsafeStaticSecret'.encode()).digest()\n-\n-def __get_mac_address(delay=2):\n- \"\"\"\n- Returns the users mac address\n-\n- :param delay: retry delay in sec\n- :type delay: int\n- :returns: string -- Devices MAC address\n\"\"\"\n- mac_addr = xbmc.getInfoLabel('Network.MacAddress').decode('utf-8')\n- # hack response busy\n- i = 0\n- while ':' not in mac_addr and i < 3:\n- mac_addr = xbmc.getInfoLabel('Network.MacAddress').decode('utf-8')\n- xbmc.sleep(delay)\n- i += 1\n- return mac_addr\n+ import uuid\n+ mac = uuid.getnode()\n+ if (mac >> 40) % 2:\n+ from platform import node\n+ mac = node()\n+ return uuid.uuid5(uuid.NAMESPACE_DNS, str(mac)).bytes\ndef encrypt_credential(raw):\n\"\"\"\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Introduce safe secret generation for password storage |
105,989 | 16.10.2018 11:46:34 | -7,200 | 2bf7994280f7f1ebca261d66dafb297761d1172f | Add MSL reset on ESN change. Small improvements. | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -6,6 +6,7 @@ from __future__ import unicode_literals\nimport sys\nimport os\nimport json\n+import traceback\nfrom functools import wraps\nfrom datetime import datetime, timedelta\n@@ -45,6 +46,7 @@ class Signals(object):\n\"\"\"Signal names for use with AddonSignals\"\"\"\n# pylint: disable=too-few-public-methods\nPLAYBACK_INITIATED = 'playback_initiated'\n+ ESN_CHANGED = 'esn_changed'\nclass PersistentStorage(object):\n\"\"\"\n@@ -523,32 +525,44 @@ def get_path(search, search_space):\nreturn current_value\nreturn get_path(search[1:], current_value)\n-def register_slot(callback):\n+def register_slot(callback, signal=None):\n\"\"\"Register a callback with AddonSignals for return calls\"\"\"\n- name = _signal_name(callback)\n+ name = signal if signal else _signal_name(callback)\nAddonSignals.registerSlot(\nsignaler_id=ADDON_ID,\nsignal=name,\ncallback=callback)\ndebug('Registered AddonSignals slot {} to {}'.format(name, callback))\n-def unregister_slot(callback):\n+def unregister_slot(callback, signal=None):\n\"\"\"Remove a registered callback from AddonSignals\"\"\"\n+ name = signal if signal else _signal_name(callback)\nAddonSignals.unRegisterSlot(\nsignaler_id=ADDON_ID,\n- signal=_signal_name(callback))\n+ signal=name)\n+ debug('Unregistered AddonSignals slot {}'.format(name))\n+\n+def send_signal(signal, data=None):\n+ \"\"\"Send a signal via AddonSignals\"\"\"\n+ AddonSignals.sendSignal(\n+ source_id=ADDON_ID,\n+ signal=signal,\n+ data=data)\ndef make_call(func, data=None):\n\"\"\"Make a call via AddonSignals and wait for it to return\"\"\"\n- debug('Making AddonSignals call: {func}({data})'.format(func=_signal_name(func), data=data))\n+ callname = _signal_name(func)\n+ debug('Making AddonSignals call {}'.format(callname))\nresult = AddonSignals.makeCall(\nsource_id=ADDON_ID,\n- signal=_signal_name(func),\n+ signal=callname,\ndata=data,\ntimeout_ms=10000)\n- debug('Received return value via AddonSignals: {}'.format(result))\nif isinstance(result, dict) and 'error' in result:\n- raise Exception('{error}: {message}'.format(**result))\n+ msg = ('AddonSignals call {callname} returned {error}: {message}'\n+ .format(callname, **result))\n+ error(msg)\n+ raise Exception(msg)\nreturn result\ndef addonsignals_return_call(func):\n@@ -568,14 +582,25 @@ def addonsignals_return_call(func):\nelse:\nresult = func(instance)\nexcept Exception as exc:\n+ error('AddonSignals callback raised exception: {exc}', exc)\n+ error(''.join(traceback.format_stack(sys.exc_info()[2])))\nresult = {\n'error': exc.__class__.__name__,\n'message': exc.__unicode__()\n}\n- # Return anything but None or AddonSignals will keep waiting till timeout\n- AddonSignals.returnCall(signal=_signal_name(func),\n- source_id=ADDON_ID, data=result if result is not None else False)\n+ # Do not return None or AddonSignals will keep waiting till timeout\n+ if result is None:\n+ result = False\n+ AddonSignals.returnCall(\n+ signal=_signal_name(func), source_id=ADDON_ID, data=result)\nreturn make_return_call\ndef _signal_name(func):\nreturn func.__name__\n+\n+def reraise(exc, msg, new_exception_cls, stacktrace):\n+ \"\"\"Log an error message with original stacktrace and return\n+ as new exception type to be reraised\"\"\"\n+ error('{msg}: {exc}'.format(msg=msg, exc=exc))\n+ error(''.join(traceback.format_stack(stacktrace)))\n+ return new_exception_cls(exc)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/MSL.py",
"new_path": "resources/lib/services/msl/MSL.py",
"diff": "@@ -64,6 +64,10 @@ class MSL(object):\nself.crypto.fromDict(None)\nself.__perform_key_handshake()\n+ common.register_slot(\n+ signal=common.Signals.ESN_CHANGED,\n+ callback=self.perform_key_handshake)\n+\ndef load_manifest(self, viewable_id, dolby, hevc, hdr, dolbyvision, vp9):\n\"\"\"\nLoads the manifets for the given viewable_id and\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "\"\"\"Stateful Netflix session management\"\"\"\nfrom __future__ import unicode_literals\n+import sys\nfrom time import time\nfrom base64 import urlsafe_b64encode\nfrom functools import wraps\nimport json\nimport requests\n-import AddonSignals\n-\nimport resources.lib.common as common\nimport resources.lib.api.website as website\nimport resources.lib.services.cookies as cookies\n@@ -26,7 +25,7 @@ URLS = {\n'metadata': {'endpoint': '/metadata', 'is_api_call': True},\n'set_video_rating': {'endpoint': '/setVideoRating', 'is_api_call': True},\n'update_my_list': {'endpoint': '/playlistop', 'is_api_call': True},\n- # Don't know what these could be used for...\n+ # Don't know what these could be used for. Keeping for reference\n# 'browse': {'endpoint': '/browse', 'is_api_call': False},\n# 'video_list_ids': {'endpoint': '/preflight', 'is_api_call': True},\n# 'kids': {'endpoint': '/Kids', 'is_api_call': False}\n@@ -34,11 +33,12 @@ URLS = {\n\"\"\"List of all static endpoints for HTML/JSON POST/GET requests\"\"\"\ndef needs_login(func):\n- \"\"\"Ensure that a valid login is present when executing the method\"\"\"\n+ \"\"\"\n+ Decorator to ensure that a valid login is present when calling a method\n+ \"\"\"\n+ # pylint: disable=protected-access, missing-docstring\n@wraps(func)\ndef ensure_login(*args, **kwargs):\n- \"\"\"Wrapper function to ensure that a valid login is present\"\"\"\n- # pylint: disable=protected-access\nsession = args[0]\nif not session._is_logged_in():\nsession._login()\n@@ -71,6 +71,7 @@ class NetflixSession(object):\nself._prefetch_login()\ndef __del__(self):\n+ \"\"\"Unregister AddonSignals slots\"\"\"\nfor slot in self.slots:\ncommon.unregister_slot(slot)\n@@ -92,11 +93,11 @@ class NetflixSession(object):\n@property\ndef auth_url(self):\n- \"\"\"Valid authURL or None if it isn't known\"\"\"\n+ \"\"\"Valid authURL. Raises InvalidAuthURLError if it isn't known.\"\"\"\ntry:\nreturn self.session_data['user_data']['authURL']\n- except KeyError:\n- raise website.InvalidAuthURLError()\n+ except (AttributeError, KeyError) as exc:\n+ raise website.InvalidAuthURLError(exc)\ndef _register_slots(self):\nself.slots = [\n@@ -127,15 +128,13 @@ class NetflixSession(object):\ndef _prefetch_login(self):\n\"\"\"Check if we have stored credentials.\n- If so, do the login before the user requests it\n- \"\"\"\n+ If so, do the login before the user requests it\"\"\"\ntry:\ncommon.get_credentials()\nif not self._is_logged_in():\nself._login()\n- common.info('Login prefetch successful')\nexcept common.MissingCredentialsError:\n- common.debug(\n+ common.info(\n'Skipping login prefetch. No stored credentials are available')\ndef _is_logged_in(self):\n@@ -154,6 +153,7 @@ class NetflixSession(object):\n# If we can get session data, cookies are still valid\nself.session_data = website.extract_session_data(\nself._get('profiles').content)\n+ self._update_esn()\nexcept Exception:\ncommon.info('Stored cookies are expired')\nreturn False\n@@ -171,16 +171,25 @@ class NetflixSession(object):\ncommon.debug('Extracting session data...')\nsession_data = website.extract_session_data(login_response.content)\nexcept Exception as exc:\n- common.error('Login failed: {exc}', exc)\n- raise LoginFailedError(exc)\n+ raise common.reraise(\n+ exc, 'Login failed', LoginFailedError, sys.exc_info()[2])\ncommon.info('Login successful')\nself.session_data = session_data\ncookies.save(self.account_hash, self.session.cookies)\n+ self._update_esn()\n+\n+ def _update_esn(self):\n+ \"\"\"Return True if the esn has changed on Session initialization\"\"\"\n+ if common.set_esn(self.session_data['esn']):\n+ common.send_signal(\n+ signal=common.Signals.ESN_CHANGED,\n+ data=self.session_data['esn'])\[email protected]_return_call\ndef logout(self):\n\"\"\"Logout of the current account and reset the session\"\"\"\n+ common.debug('Logging out of current account')\nself._get('logout')\ncookies.delete(self.account_hash)\nself._init_session()\n@@ -191,8 +200,8 @@ class NetflixSession(object):\n\"\"\"Retrieve a list of all profiles in the user's account\"\"\"\ntry:\nreturn self.session_data['profiles']\n- except (AttributeError, KeyError):\n- raise website.InvalidProfilesError()\n+ except (AttributeError, KeyError) as exc:\n+ raise website.InvalidProfilesError(exc)\[email protected]_return_call\n@needs_login\n@@ -257,26 +266,24 @@ class NetflixSession(object):\n**kwargs)\ndef _request(self, method, component, **kwargs):\n- common.debug('Constructing URL for component {}'.format(component))\nurl = (_api_url(component, self.session_data['api_data'])\nif kwargs.get('req_type') == 'api'\nelse _document_url(component))\n- common.debug('Executing {verb} request to {url}'.format(verb='GET' if method == self.session.get else 'POST', url=url))\n- try:\n+ common.debug(\n+ 'Executing {verb} request to {url}'.format(\n+ verb='GET' if method == self.session.get else 'POST', url=url))\nresponse = method(\nurl=url,\nverify=self.verify_ssl,\nheaders=kwargs.get('headers'),\nparams=kwargs.get('params'),\ndata=kwargs.get('data'))\n- except:\n- common.error('REQUEST FAILED')\n- common.debug('Request executed with reponse {}'.format(response.status_code))\n+ common.debug(\n+ 'Request returned statuscode {}'.format(response.status_code))\nresponse.raise_for_status()\nreturn response\ndef _login_payload(credentials, auth_url):\n- common.debug('Constructing login payload')\nreturn {\n'userLoginId': credentials['email'],\n'email': credentials['email'],\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add MSL reset on ESN change. Small improvements. |
105,989 | 18.10.2018 00:38:10 | -7,200 | df1c3e540ccf54f28f1b6505f014c2a7a9b03023 | Start rewriting navigation. | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "from __future__ import unicode_literals\nimport sys\n+\nimport resources.lib.common as common\n-from resources.lib.Navigation import Navigation\n+import resources.lib.navigation.directory as directory\n+import resources.lib.navigation.hub as hub\n+import resources.lib.api.shakti as api\n-# We use string slicing to trim the leading ? from the plugin call paramstring\n-REQUEST_PARAMS = sys.argv[2][1:]\n+def open_settings(addon_id):\n+ \"\"\"Open settings page of another addon\"\"\"\n+ from xbmcaddon import Addon\n+ Addon(addon_id).openSettings()\nif __name__ == '__main__':\n- # Call the router function and pass the plugin call parameters to it.\n+ common.init_globals(sys.argv)\ncommon.info('Started (Version {})'.format(common.VERSION))\n- Navigation().router(paramstring=REQUEST_PARAMS)\n+ common.info('URL is {}'.format(common.URL))\n+ # Path starts with / so we need to omit empty string at index 0\n+ PATH_ITEMS = common.PATH.split('/')\n+\n+ # route to the appropriate navigation module based on first path item\n+ if not common.PATH or PATH_ITEMS[0] == common.MODE_DIRECTORY:\n+ directory.build(PATH_ITEMS[1:], common.REQUEST_PARAMS)\n+ elif PATH_ITEMS[0] == common.MODE_HUB:\n+ hub.browse(PATH_ITEMS[1:], common.REQUEST_PARAMS)\n+ elif PATH_ITEMS[0] == 'logout':\n+ api.logout()\n+ elif PATH_ITEMS[0] == 'opensettings':\n+ try:\n+ open_settings(PATH_ITEMS[1])\n+ except IndexError:\n+ common.error('Cannot open settings. Missing target addon id.')\n+ else:\n+ common.error('Invalid path: {}'.format(common.PATH))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -35,6 +35,13 @@ def root_lists():\n]\n]))\n+def video_list_id_for_type(video_list_type):\n+ video_lists = root_lists()\n+ for video_list_id in video_lists['user']:\n+ if video_lists['user'][video_list_id]['name'] == video_list_type:\n+ return str(video_lists['user'][video_list_id]['id'])\n+ return {}\n+\ndef video_list(video_list_id):\n\"\"\"Retrieve a single video list\"\"\"\npass\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -9,6 +9,8 @@ import json\nimport traceback\nfrom functools import wraps\nfrom datetime import datetime, timedelta\n+from urlparse import urlparse, parse_qs\n+from urllib import urlencode\ntry:\nimport cPickle as pickle\n@@ -22,22 +24,62 @@ import AddonSignals\nimport resources.lib.kodi.ui.newdialogs as dialogs\n+# Global vars are initialized in init_globals\n+# Commonly used addon attributes from Kodi\n+ADDON = None\n+ADDON_ID = None\n+PLUGIN = None\n+VERSION = None\n+DEFAULT_FANART = None\n+DATA_PATH = None\n+COOKIE_PATH = None\n+\n+# Information about the current plugin instance\n+URL = None\n+PLUGIN_HANDLE = None\n+BASE_URL = None\n+PATH = None\n+PARAM_STRING = None\n+REQUEST_PARAMS = None\n+\n+MODE_DIRECTORY = 'directory'\n+MODE_HUB = 'hub'\n+MODE_ACTION = 'action'\n+\n+def init_globals(argv):\n+ \"\"\"Initialized globally used module variables.\n+ Needs to be called at start of each plugin instance!\n+ This is an ugly hack because Kodi doesn't execute statements defined on module\n+ level if reusing a language invoker.\"\"\"\n+ # pylint: disable=global-statement\n+ global ADDON, ADDON_ID, PLUGIN, VERSION, DEFAULT_FANART, DATA_PATH, COOKIE_PATH\nADDON = xbmcaddon.Addon()\n+ ADDON_ID = ADDON.getAddonInfo('id')\nPLUGIN = ADDON.getAddonInfo('name')\nVERSION = ADDON.getAddonInfo('version')\n-ADDON_ID = ADDON.getAddonInfo('id')\nDEFAULT_FANART = ADDON.getAddonInfo('fanart')\nDATA_PATH = xbmc.translatePath(ADDON.getAddonInfo('profile'))\nCOOKIE_PATH = DATA_PATH + 'COOKIE'\n-BASE_URL = sys.argv[0]\n+\n+ global URL, PLUGIN_HANDLE, BASE_URL, PATH, PARAM_STRING, REQUEST_PARAMS\n+ URL = urlparse(argv[0])\ntry:\n- PLUGIN_HANDLE = int(sys.argv[1])\n+ PLUGIN_HANDLE = int(argv[1])\nexcept IndexError:\n- PLUGIN_HANDLE = None\n+ PLUGIN_HANDLE = 0\n+ BASE_URL = '{scheme}://{netloc}'.format(scheme=URL[0], netloc=URL[1])\n+ PATH = URL[2][1:]\n+ try:\n+ PARAM_STRING = argv[2][1:]\n+ except IndexError:\n+ PARAM_STRING = ''\n+ REQUEST_PARAMS = parse_qs(PARAM_STRING)\nif not xbmcvfs.exists(DATA_PATH):\nxbmcvfs.mkdir(DATA_PATH)\n+init_globals(sys.argv)\n+\nclass MissingCredentialsError(Exception):\n\"\"\"There are no stored credentials to load\"\"\"\npass\n@@ -240,11 +282,11 @@ def flush_settings():\nglobal ADDON\nADDON = xbmcaddon.Addon()\n-def select_port(server):\n+def select_port():\n\"\"\"Select a port for a server and store it in the settings\"\"\"\nport = select_unused_port()\n- ADDON.setSetting('{}_service_port'.format(server), str(port))\n- log('[{}] Picked Port: {}'.format(server.upper(), port))\n+ ADDON.setSetting('msl_service_port', str(port))\n+ log('[MSL] Picked Port: {}'.format(port))\nreturn port\ndef log(msg, level=xbmc.LOGDEBUG):\n@@ -604,3 +646,15 @@ def reraise(exc, msg, new_exception_cls, stacktrace):\nerror('{msg}: {exc}'.format(msg=msg, exc=exc))\nerror(''.join(traceback.format_stack(stacktrace)))\nreturn new_exception_cls(exc)\n+\n+def build_directory_url(pathitems, params=None):\n+ \"\"\"Build a plugin URL for directory mode\"\"\"\n+ return build_url(pathitems, params, MODE_DIRECTORY)\n+\n+def build_url(pathitems, params=None, mode=MODE_DIRECTORY):\n+ \"\"\"Build a plugin URL from pathitems and query parameters\"\"\"\n+ pathitems.insert(0, mode)\n+ return '{netloc}/{path}{qs}'.format(\n+ netloc=BASE_URL,\n+ path='/'.join(pathitems),\n+ qs='?' + urlencode(params if params else ''))\n"
},
{
"change_type": "ADD",
"old_path": "resources/lib/navigation/__init__.py",
"new_path": "resources/lib/navigation/__init__.py",
"diff": ""
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/navigation/directory.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Navigation for classic plugin directory listing mode\"\"\"\n+from __future__ import unicode_literals\n+\n+import resources.lib.common as common\n+import resources.lib.api.shakti as api\n+\n+from resources.lib.kodi.KodiHelper import KodiHelper\n+from resources.lib.library.Library import Library\n+\n+BASE_PATH_ITEM = 'directory'\n+VIDEO_LIST_TYPES = ['queue', 'topTen', 'netflixOriginals', 'continueWatching',\n+ 'trendingNow', 'newRelease', 'popularTitles']\n+\n+def build(pathitems, params):\n+ \"\"\"Build a directory listing for the given path\"\"\"\n+ try:\n+ builder = DirectoryBuilder(params).__getattribute__(\n+ pathitems[0] if pathitems else 'root')\n+ except (IndexError, AttributeError):\n+ common.error('Invalid directory path: {}'.format('/'.join(pathitems)))\n+ return\n+\n+ if len(pathitems) > 1:\n+ builder((pathitems[1:]))\n+ else:\n+ builder()\n+\n+class DirectoryBuilder(object):\n+ \"\"\"Builds directory listings\"\"\"\n+ # pylint: disable=no-self-use\n+ def __init__(self, params):\n+ self.library = Library()\n+ self.kodi_helper = KodiHelper(library=self.library)\n+ self.library.kodi_helper = self.kodi_helper\n+\n+ profile_id = params.get('profile_id')\n+ if profile_id:\n+ api.activate_profile(profile_id)\n+\n+ def root(self):\n+ autologin = common.ADDON.getSettingBool('autologin_enable')\n+ profile_id = common.ADDON.getSetting('autologin_id')\n+ if autologin and profile_id:\n+ api.activate_profile(profile_id)\n+ self.home()\n+ else:\n+ self.profiles()\n+\n+ def profiles(self):\n+ self.kodi_helper.build_profiles_listing(api.profiles())\n+\n+ def home(self):\n+ user_list_order = [\n+ 'queue', 'continueWatching', 'topTen',\n+ 'netflixOriginals', 'trendingNow',\n+ 'newRelease', 'popularTitles']\n+ # define where to route the user\n+ actions = {\n+ 'recommendations': 'user-items',\n+ 'genres': 'user-items',\n+ 'search': 'user-items',\n+ 'exported': 'user-items',\n+ 'default': 'video_list'\n+ }\n+ self.kodi_helper.build_main_menu_listing(\n+ video_list_ids=api.root_lists(),\n+ user_list_order=user_list_order,\n+ actions=actions,\n+ build_url=common.build_url)\n+\n+ def video_list(self, pathitems):\n+ if pathitems[0] in VIDEO_LIST_TYPES:\n+ video_list_id = api.video_list_id_for_type(pathitems[0])\n+ else:\n+ video_list_id = pathitems[0]\n+\n+ self.kodi_helper.build_video_listing(\n+ video_list=api.video_list(video_list_id))\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/navigation/hub.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Navigation for hub mode - needs skin support!\"\"\"\n+from __future__ import unicode_literals\n+\n+import resources.lib.common as common\n+\n+BASE_PATH_ITEM = 'hub'\n+\n+def browse(pathitems, params):\n+ \"\"\"Browse a hub page for the given path\"\"\"\n+ pass\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/__init__.py",
"new_path": "resources/lib/services/__init__.py",
"diff": "from __future__ import unicode_literals\nfrom .msl.MSLHttpRequestHandler import MSLTCPServer\n-from .session.NetflixHttpRequestHandler import NetflixTCPServer\nfrom .library_updater import LibraryUpdateService\nfrom .playback.controller import PlaybackController\n"
},
{
"change_type": "MODIFY",
"old_path": "service.py",
"new_path": "service.py",
"diff": "\"\"\"Kodi plugin for Netflix (https://netflix.com)\"\"\"\nfrom __future__ import unicode_literals\n+import sys\nimport threading\nimport xbmc\n@@ -15,68 +16,61 @@ import resources.lib.common as common\nimport resources.lib.services as services\nfrom resources.lib.services.nfsession import NetflixSession\n-SERVERS = {\n- 'msl': services.MSLTCPServer,\n- #'ns': services.NetflixTCPServer\n-}\n-\nclass NetflixService(object):\n\"\"\"\nNetflix addon service\n\"\"\"\ndef __init__(self):\n- self.servers = {}\n+ services.MSLTCPServer.allow_reuse_address = True\n+ self.msl_server = services.MSLTCPServer(\n+ ('127.0.0.1', common.select_port()))\n+ self.msl_thread = threading.Thread(\n+ target=self.msl_server.serve_forever)\nself.session = None\n- for name, server_class in SERVERS.items():\n- server_class.allow_reuse_address = True\n- instance = server_class(('127.0.0.1', common.select_port(name)))\n- thread = threading.Thread(target=instance.serve_forever)\n- self.servers[name] = {'instance': instance, 'thread': thread}\n+ self.controller = None\n+ self.library_updater = None\n- def start_servers(self):\n+ def start_services(self):\n\"\"\"\nStart the background services\n\"\"\"\nself.session = NetflixSession()\n- for name, components in self.servers.items():\n- components['instance'].server_activate()\n- components['instance'].timeout = 1\n- components['thread'].start()\n- common.info('[{}] Thread started'.format(name))\n+ self.msl_server.server_activate()\n+ self.msl_server.timeout = 1\n+ self.msl_thread.start()\n+ common.info('[MSL] Thread started')\n+ self.controller = services.PlaybackController()\n+ self.library_updater = services.LibraryUpdateService()\ndef shutdown(self):\n\"\"\"\nStop the background services\n\"\"\"\ndel self.session\n- for name, components in self.servers:\n- components['instance'].server_close()\n- components['instance'].shutdown()\n- components['thread'].join()\n- del self.servers['name']\n- common.info('Stopped {} Service'.format(name.upper()))\n+ self.msl_server.server_close()\n+ self.msl_server.shutdown()\n+ self.msl_server = None\n+ self.msl_thread.join()\n+ self.msl_thread = None\n+ common.info('Stopped MSL Service')\ndef run(self):\n\"\"\"\nMain loop. Runs until xbmc.Monitor requests abort\n\"\"\"\n- self.start_servers()\n- controller = services.PlaybackController()\n- library_updater = services.LibraryUpdateService()\n+ self.start_services()\nplayer = xbmc.Player()\n- while not controller.abortRequested():\n+ while not self.controller.abortRequested():\n# pylint: disable=broad-except\ntry:\n- # if self.servers['ns']['instance'].esn_changed():\n- # self.servers['msl']['instance'].reset_msl_data()\nif player.isPlayingVideo():\n- controller.on_playback_tick()\n- library_updater.on_tick()\n+ self.controller.on_playback_tick()\n+ self.library_updater.on_tick()\nexcept Exception as exc:\n- common.log(exc)\n+ common.error(exc)\n- if controller.waitForAbort(1):\n+ if self.controller.waitForAbort(1):\nbreak\nself.shutdown()\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Start rewriting navigation. |
105,989 | 18.10.2018 01:01:48 | -7,200 | f8e05e3a37092490d3f670781eda6ce66111e9cd | Improve recognition of timeouts when invoking background services | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -605,6 +605,8 @@ def make_call(func, data=None):\n.format(callname, **result))\nerror(msg)\nraise Exception(msg)\n+ elif result is None:\n+ raise Exception('AddonSignals call timed out')\nreturn result\ndef addonsignals_return_call(func):\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Improve recognition of timeouts when invoking background services |
105,989 | 18.10.2018 01:02:11 | -7,200 | 722e78895ea0ee2a966b7925a126b8ec79b5929b | Make current functionality fully unicode compatible | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/KodiHelper.py",
"new_path": "resources/lib/kodi/KodiHelper.py",
"diff": "@@ -228,8 +228,9 @@ class KodiHelper(object):\n# build menu items for every profile\nfor _, profile in profiles.items():\n# load & encode profile data\n- enc_profile_name = profile.get('profileName', '').encode('utf-8')\n- unescaped_profile_name = html_parser.unescape(enc_profile_name)\n+ profile_name = profile.get('profileName', '')\n+ unescaped_profile_name = html_parser.unescape(profile_name)\n+ enc_profile_name = profile_name.encode('utf-8')\nprofile_guid = profile.get('guid')\n# build urls\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Make current functionality fully unicode compatible |
105,989 | 18.10.2018 18:10:59 | -7,200 | a998263b6bc96b7d212d0b829f3fa698e4da1170 | (possibly broken) Add caching to API operations. Start refactoring Kodi helper. | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "# Module: default\n# Created on: 13.01.2017\n# License: MIT https://goo.gl/5bMj3H\n+# pylint: disable=broad-except\n\"\"\"Kodi plugin for Netflix (https://netflix.com)\"\"\"\nfrom __future__ import unicode_literals\nimport sys\n+import xbmcplugin\n+\nimport resources.lib.common as common\n+from resources.lib.navigation import InvalidPathError\nimport resources.lib.navigation.directory as directory\nimport resources.lib.navigation.hub as hub\nimport resources.lib.api.shakti as api\n+import resources.lib.api.cache as cache\ndef open_settings(addon_id):\n\"\"\"Open settings page of another addon\"\"\"\nfrom xbmcaddon import Addon\nAddon(addon_id).openSettings()\n+def route(pathitems):\n+ \"\"\"Route to the appropriate handler\"\"\"\n+ if not common.PATH or pathitems[0] == common.MODE_DIRECTORY:\n+ directory.build(pathitems[1:], common.REQUEST_PARAMS)\n+ elif pathitems[0] == common.MODE_HUB:\n+ hub.browse(pathitems[1:], common.REQUEST_PARAMS)\n+ elif pathitems[0] == 'logout':\n+ api.logout()\n+ elif pathitems[0] == 'opensettings':\n+ try:\n+ open_settings(pathitems[1])\n+ except IndexError:\n+ raise InvalidPathError('Missing target addon id.')\n+ else:\n+ raise InvalidPathError('No root handler for path {}'\n+ .format('/'.join(pathitems)))\n+\nif __name__ == '__main__':\n+ # Initialize variables in common module scope\n+ # (necessary when reusing language invoker)\ncommon.init_globals(sys.argv)\ncommon.info('Started (Version {})'.format(common.VERSION))\ncommon.info('URL is {}'.format(common.URL))\n- # Path starts with / so we need to omit empty string at index 0\n- PATH_ITEMS = common.PATH.split('/')\n-\n- # route to the appropriate navigation module based on first path item\n- if not common.PATH or PATH_ITEMS[0] == common.MODE_DIRECTORY:\n- directory.build(PATH_ITEMS[1:], common.REQUEST_PARAMS)\n- elif PATH_ITEMS[0] == common.MODE_HUB:\n- hub.browse(PATH_ITEMS[1:], common.REQUEST_PARAMS)\n- elif PATH_ITEMS[0] == 'logout':\n- api.logout()\n- elif PATH_ITEMS[0] == 'opensettings':\n+\ntry:\n- open_settings(PATH_ITEMS[1])\n- except IndexError:\n- common.error('Cannot open settings. Missing target addon id.')\n- else:\n- common.error('Invalid path: {}'.format(common.PATH))\n+ route(common.PATH.split('/'))\n+ except Exception as exc:\n+ common.error(exc)\n+ xbmcplugin.endOfDirectory(handle=common.PLUGIN_HANDLE, succeeded=False)\n+\n+ cache.commit()\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/api/cache.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Caching for API calls\"\"\"\n+from __future__ import unicode_literals\n+\n+from time import time\n+from collections import OrderedDict\n+from functools import wraps\n+try:\n+ import cPickle as pickle\n+except ImportError:\n+ import pickle\n+\n+import xbmcgui\n+\n+import resources.lib.common as common\n+\n+WND = xbmcgui.Window(10000)\n+\n+COMMON = 'common'\n+VIDEO_LIST = 'video_list'\n+SEASONS = 'seasons'\n+EPISODES = 'episodes'\n+METADATA = 'metadata'\n+\n+BUCKET_NAMES = [COMMON, VIDEO_LIST, SEASONS, EPISODES, METADATA]\n+BUCKETS = {}\n+\n+class CacheMiss(Exception):\n+ \"\"\"Requested item is not in the cache\"\"\"\n+ pass\n+\n+class UnknownCacheBucketError(Exception):\n+ \"\"\"The requested cahce bucket does ot exist\"\"\"\n+ pass\n+\n+def cache_output(bucket, identifying_param_index=0,\n+ identifying_param_name=None,\n+ fixed_identifier=None):\n+ \"\"\"Cache the output of a function\"\"\"\n+ # pylint: disable=missing-docstring\n+ def caching_decorator(func):\n+ @wraps\n+ def wrapper(*args, **kwargs):\n+ if fixed_identifier:\n+ identifier = fixed_identifier\n+ else:\n+ try:\n+ # prefer keyword over positional arguments\n+ identifier = kwargs.get(\n+ identifying_param_name, args[identifying_param_index])\n+ except IndexError:\n+ common.error(\n+ 'Invalid cache configuration.'\n+ 'Cannot determine identifier from params')\n+ try:\n+ return get(bucket, identifier)\n+ except CacheMiss:\n+ output = func(*args, **kwargs)\n+ add(bucket, identifier, output)\n+ return wrapper\n+ return caching_decorator\n+\n+def get_bucket(key):\n+ \"\"\"Get a cache bucket.\n+ Load it lazily from window property if it's not yet in memory\"\"\"\n+ if key not in BUCKET_NAMES:\n+ raise UnknownCacheBucketError()\n+\n+ if key not in BUCKETS:\n+ BUCKETS[key] = _load_bucket(key)\n+ return BUCKETS[key]\n+\n+def invalidate():\n+ \"\"\"Clear all cache buckets\"\"\"\n+ # pylint: disable=global-statement\n+ global BUCKETS\n+ for bucket in BUCKETS:\n+ _clear_bucket(bucket)\n+ BUCKETS = {}\n+\n+def invalidate_entry(bucket, identifier):\n+ \"\"\"Remove an item from a bucket\"\"\"\n+ del get_bucket(bucket)[identifier]\n+\n+def commit():\n+ \"\"\"Persist cache contents in window properties\"\"\"\n+ for bucket, contents in BUCKETS.iteritems():\n+ _persist_bucket(bucket, contents)\n+\n+def get(bucket, identifier):\n+ \"\"\"Retrieve an item from a cache bucket\"\"\"\n+ try:\n+ cache_entry = get_bucket(bucket)[identifier]\n+ except KeyError:\n+ common.debug('Cache miss on {} in bucket {}'\n+ .format(identifier, bucket))\n+ raise CacheMiss()\n+\n+ if cache_entry['eol'] >= int(time()):\n+ common.debug('Cache entry {} in {} has expired'\n+ .format(identifier, bucket))\n+ raise CacheMiss()\n+\n+ return cache_entry['content']\n+\n+def add(bucket, identifier, content):\n+ \"\"\"Add an item to a cache bucket\"\"\"\n+ eol = int(time() + 600)\n+ get_bucket(bucket).update(\n+ {identifier: {'eol': eol, 'content': content}})\n+\n+def _window_property(bucket):\n+ return 'nfmemcache_{}'.format(bucket)\n+\n+def _load_bucket(bucket):\n+ # pylint: disable=broad-except\n+ try:\n+ return pickle.loads(WND.getProperty(_window_property(bucket)))\n+ except Exception as exc:\n+ common.debug('Failed to load cache bucket: {exc}', exc)\n+ return OrderedDict()\n+\n+def _persist_bucket(bucket, contents):\n+ # pylint: disable=broad-except\n+ try:\n+ WND.setProperty(_window_property(bucket), pickle.dumps(contents))\n+ except Exception as exc:\n+ common.error('Failed to persist cache bucket: {exc}', exc)\n+\n+def _clear_bucket(bucket):\n+ WND.clearProperty(_window_property(bucket))\n+ del BUCKETS[bucket]\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/api/data_types.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Convenience representations of datatypes returned by the API\"\"\"\n+from __future__ import unicode_literals\n+\n+class LoLoMo(object):\n+ \"\"\"List of list of movies (lolomo)\"\"\"\n+ # pylint: disable=invalid-name\n+ def __init__(self, path_response):\n+ self.data = path_response['value']\n+ del self.data['null']\n+\n+ @property\n+ def id(self):\n+ \"\"\"ID of this LoLoMo\"\"\"\n+ return self.data['lolomo'][1]\n+\n+ @property\n+ def lists(self):\n+ \"\"\"Video lists referenced by this LoLoMo\"\"\"\n+ return [video_list\n+ for video_list in self.data['lists'].itervalues()]\n+\n+ def lists_by_context(self, context):\n+ \"\"\"Return a list of all video lists with the given context.\n+ Will match any video lists with type contained in context\n+ if context is a list.\"\"\"\n+ if isinstance(context, list):\n+ lists = [video_list\n+ for video_list in self.lists\n+ if video_list['context'] in context]\n+ else:\n+ lists = [video_list\n+ for video_list in self.lists\n+ if video_list['context'] == context]\n+ return lists\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -4,14 +4,21 @@ from __future__ import unicode_literals\nimport resources.lib.common as common\nfrom resources.lib.services.nfsession import NetflixSession\n+from .data_types import LoLoMo\n+import cache\nVIDEO_LIST_KEYS = ['user', 'genres', 'recommendations']\n\"\"\":obj:`list` of :obj:`str`\nDivide the users video lists into\n3 different categories (for easier digestion)\"\"\"\n+class InvalidVideoListTypeError(Exception):\n+ \"\"\"No video list of a given was available\"\"\"\n+ pass\n+\ndef activate_profile(profile_id):\n\"\"\"Activate the profile with the given ID\"\"\"\n+ cache.invalidate()\ncommon.make_call(NetflixSession.activate_profile, profile_id)\ndef logout():\n@@ -22,10 +29,10 @@ def profiles():\n\"\"\"Retrieve the list of available user profiles\"\"\"\nreturn common.make_call(NetflixSession.list_profiles)\[email protected]_output(cache.COMMON, fixed_identifier='root_lists')\ndef root_lists():\n\"\"\"Retrieve initial video lists to display on homepage\"\"\"\n- return parse_video_list_ids(\n- common.make_call(\n+ return LoLoMo(common.make_call(\nNetflixSession.path_request,\n[\n[\n@@ -35,12 +42,21 @@ def root_lists():\n]\n]))\[email protected]_output(cache.COMMON, 0, 'video_list_type')\ndef video_list_id_for_type(video_list_type):\n- video_lists = root_lists()\n- for video_list_id in video_lists['user']:\n- if video_lists['user'][video_list_id]['name'] == video_list_type:\n- return str(video_lists['user'][video_list_id]['id'])\n- return {}\n+ \"\"\"Return the dynamic video list ID for a video list of known type\"\"\"\n+ # pylint: disable=len-as-condition\n+ lists_of_type = root_lists().lists_by_context(video_list_type)\n+ if len(lists_of_type > 1):\n+ common.warn(\n+ 'Found more than one video list of type {}.'\n+ 'Returning ID for the first one found.'\n+ .format(video_list_type))\n+ try:\n+ return lists_of_type[0]['id']\n+ except IndexError:\n+ raise InvalidVideoListTypeError(\n+ 'No lists of type {} available.'.format(video_list_type))\ndef video_list(video_list_id):\n\"\"\"Retrieve a single video list\"\"\"\n@@ -50,7 +66,7 @@ def seasons(tvshow_id):\n\"\"\"Retrieve seasons of a TV show\"\"\"\npass\n-def episodes(season_id):\n+def episodes(tvshowid, season_id):\n\"\"\"Retrieve episodes of a season\"\"\"\npass\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/website.py",
"new_path": "resources/lib/api/website.py",
"diff": "@@ -64,7 +64,7 @@ def extract_profiles(content):\ntry:\nfalkor_cache = extract_json(content, 'falcorCache')\n- for guid, profile in falkor_cache.get('profiles', {}).items():\n+ for guid, profile in falkor_cache.get('profiles', {}).iteritems():\ncommon.debug('Parsing profile {}'.format(guid))\n_profile = profile['summary']['value']\n_profile['avatar'] = _get_avatar(falkor_cache, profile)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -45,6 +45,10 @@ REQUEST_PARAMS = None\nMODE_DIRECTORY = 'directory'\nMODE_HUB = 'hub'\nMODE_ACTION = 'action'\n+MODE_PLAY = 'play'\n+\n+KNOWN_LIST_TYPES = ['queue', 'topTen', 'netflixOriginals', 'continueWatching',\n+ 'trendingNow', 'newRelease', 'popularTitles']\ndef init_globals(argv):\n\"\"\"Initialized globally used module variables.\n@@ -423,7 +427,9 @@ def get_class_methods(class_item=None):\n\"\"\"\nfrom types import FunctionType\n_type = FunctionType\n- return [x for x, y in class_item.__dict__.items() if isinstance(y, _type)]\n+ return [x\n+ for x, y in class_item.__dict__.iteritems()\n+ if isinstance(y, _type)]\ndef get_user_agent():\n\"\"\"\n@@ -653,10 +659,14 @@ def build_directory_url(pathitems, params=None):\n\"\"\"Build a plugin URL for directory mode\"\"\"\nreturn build_url(pathitems, params, MODE_DIRECTORY)\n+def build_play_url(pathitems, params=None):\n+ \"\"\"Build a plugin URL for directory mode\"\"\"\n+ return build_url(pathitems, params, MODE_PLAY)\n+\ndef build_url(pathitems, params=None, mode=MODE_DIRECTORY):\n\"\"\"Build a plugin URL from pathitems and query parameters\"\"\"\npathitems.insert(0, mode)\nreturn '{netloc}/{path}{qs}'.format(\nnetloc=BASE_URL,\npath='/'.join(pathitems),\n- qs='?' + urlencode(params if params else ''))\n+ qs=('?' + urlencode(params)) if params else '')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/KodiHelper.py",
"new_path": "resources/lib/kodi/KodiHelper.py",
"diff": "@@ -46,6 +46,39 @@ CONTENT_SHOW = 'tvshows'\nCONTENT_SEASON = 'seasons'\nCONTENT_EPISODE = 'episodes'\n+def create_list_item(label, icon=None, fanart=None):\n+ \"\"\"Create a rudimentary list item with icon and fanart\"\"\"\n+ list_item = xbmcgui.ListItem(label=label,\n+ iconImage=icon or common.DEFAULT_FANART)\n+ list_item.setProperty('fanart_image', fanart or common.DEFAULT_FANART)\n+ return list_item\n+\n+def finalize_directory(items, sort_methods=None, content_type=CONTENT_FOLDER,\n+ refresh=False):\n+ \"\"\"Finalize a directory listing.\n+ Add items, set available sort methods and content type\"\"\"\n+ for item in items:\n+ xbmcplugin.addDirectoryItem(\n+ handle=common.PLUGIN_HANDLE,\n+ listitem=item[0],\n+ url=item[1],\n+ isFolder=item[2])\n+\n+ for sort_method in (sort_methods\n+ if sort_methods\n+ else [xbmcplugin.SORT_METHOD_UNSORTED]):\n+ xbmcplugin.addSortMethod(\n+ handle=common.PLUGIN_HANDLE,\n+ sortMethod=sort_method)\n+\n+ xbmcplugin.setContent(\n+ handle=common.PLUGIN_HANDLE,\n+ content=content_type)\n+\n+ xbmcplugin.endOfDirectory(\n+ handle=common.PLUGIN_HANDLE,\n+ updateListing=refresh)\n+\ndef custom_viewmode(viewtype):\n\"\"\"Decorator that sets a custom viewmode if currently in\na listing of the plugin\"\"\"\n@@ -223,83 +256,79 @@ class KodiHelper(object):\n:type build_url: fn\n:returns: bool -- List could be build\n\"\"\"\n- # init html parser for entity decoding\n+ directory_items = []\nhtml_parser = HTMLParser()\n- # build menu items for every profile\n- for _, profile in profiles.items():\n- # load & encode profile data\n+ for profile_guid, profile in profiles.iteritems():\nprofile_name = profile.get('profileName', '')\nunescaped_profile_name = html_parser.unescape(profile_name)\nenc_profile_name = profile_name.encode('utf-8')\n- profile_guid = profile.get('guid')\n-\n- # build urls\n- url = common.build_directory_url(['home'], {'profile_id': profile_guid})\n+ list_item = create_list_item(\n+ label=unescaped_profile_name, icon=profile.get('avatar'))\nautologin_url = common.build_url(\npathitems=['save_autologin', profile_guid],\nparams={'autologin_user': enc_profile_name},\nmode='action')\n-\n- # add list item\n- list_item = xbmcgui.ListItem(\n- label=unescaped_profile_name,\n- iconImage=profile.get('avatar'))\n- list_item.setProperty(\n- key='fanart_image',\n- value=common.DEFAULT_FANART)\n- # add context menu options\n- auto_login = (\n- self.get_local_string(30053),\n- 'RunPlugin(' + autologin_url + ')')\n- list_item.addContextMenuItems(items=[auto_login])\n-\n- # add directory & sorting options\n- xbmcplugin.addDirectoryItem(\n- handle=common.PLUGIN_HANDLE,\n- url=url,\n- listitem=list_item,\n- isFolder=True)\n- xbmcplugin.addSortMethod(\n- handle=common.PLUGIN_HANDLE,\n- sortMethod=xbmcplugin.SORT_METHOD_LABEL)\n-\n- xbmcplugin.setContent(\n- handle=common.PLUGIN_HANDLE,\n- content=CONTENT_FOLDER)\n-\n- return xbmcplugin.endOfDirectory(handle=common.PLUGIN_HANDLE)\n+ list_item.addContextMenuItems(\n+ items=[(self.get_local_string(30053),\n+ 'RunPlugin({})'.format(autologin_url))])\n+ directory_items.append(\n+ (list_item,\n+ common.build_directory_url(\n+ ['home'], {'profile_id': profile_guid}),\n+ True))\n+\n+ finalize_directory(\n+ items=directory_items,\n+ sort_methods=[xbmcplugin.SORT_METHOD_LABEL])\n@custom_viewmode(VIEW_FOLDER)\n- def build_main_menu_listing(self, video_list_ids, user_list_order, actions,\n- build_url):\n+ def build_main_menu_listing(self, lolomo):\n\"\"\"\nBuilds the video lists (my list, continue watching, etc.) Kodi screen\n-\n- Parameters\n- ----------\n- video_list_ids : :obj:`dict` of :obj:`str`\n- List of video lists\n-\n- user_list_order : :obj:`list` of :obj:`str`\n- Ordered user lists\n- to determine what should be displayed in the main menue\n-\n- actions : :obj:`dict` of :obj:`str`\n- Dictionary of actions to build subsequent routes\n-\n- build_url : :obj:`fn`\n- Function to build the subsequent routes\n-\n- Returns\n- -------\n- bool\n- List could be build\n\"\"\"\n+ directory_items = []\n+ for user_list in lolomo.lists_by_context(common.KNOWN_LIST_TYPES):\n+ list_item = create_list_item(user_list['displayName'])\n+ directory_items.append(\n+ (list_item,\n+ common.build_url(['video_list', user_list['context']]),\n+ True))\n+\n+ # Add search\n+ directory_items.append(\n+ (create_list_item(self.get_local_string(30011)),\n+ common.build_url(['search']),\n+ True))\n+\n+ # Add exported\n+ directory_items.append(\n+ (create_list_item(self.get_local_string(30048)),\n+ common.build_directory_url(['exported']),\n+ True))\n+\n+ finalize_directory(\n+ items=directory_items,\n+ sort_methods=[xbmcplugin.SORT_METHOD_UNSORTED],\n+ content_type=CONTENT_FOLDER)\n+\n+ def build_main_menu_listing_old(self, video_lists):\n+ user_list_order = [\n+ 'queue', 'continueWatching', 'topTen',\n+ 'netflixOriginals', 'trendingNow',\n+ 'newRelease', 'popularTitles']\n+ # define where to route the user\n+ actions = {\n+ 'recommendations': 'user-items',\n+ 'genres': 'user-items',\n+ 'search': 'user-items',\n+ 'exported': 'user-items',\n+ 'default': 'video_list'\n+ }\npreselect_items = []\nfor category in user_list_order:\n- for video_list_id in video_list_ids['user']:\n- if video_list_ids['user'][video_list_id]['name'] == category:\n- label = video_list_ids['user'][video_list_id]['displayName']\n+ for video_list_id in video_lists['user']:\n+ if video_lists['user'][video_list_id]['name'] == category:\n+ label = video_lists['user'][video_list_id]['displayName']\nif category == 'netflixOriginals':\nlabel = label.capitalize()\nli = xbmcgui.ListItem(label=label, iconImage=common.DEFAULT_FANART)\n@@ -324,7 +353,7 @@ class KodiHelper(object):\n}\nfor type in i18n_ids.keys():\n# determine if the lists have contents\n- if len(video_list_ids[type]) > 0:\n+ if len(video_lists[type]) > 0:\n# determine action route\naction = actions['default']\nif type in actions.keys():\n@@ -430,7 +459,7 @@ class KodiHelper(object):\nList could be build\n\"\"\"\nlist_items = []\n- for video_id, video in video_list.items():\n+ for video_id, video in video_list.iteritems():\nli = xbmcgui.ListItem(\nlabel=video['title'],\niconImage=common.DEFAULT_FANART)\n@@ -738,7 +767,7 @@ class KodiHelper(object):\nreturn True\n@custom_viewmode(VIEW_SEASON)\n- def build_season_listing(self, seasons_sorted, build_url):\n+ def build_season_listing(self, tvshowid, seasons):\n\"\"\"Builds the season list screen for a show\nParameters\n@@ -754,7 +783,7 @@ class KodiHelper(object):\nbool\nList could be build\n\"\"\"\n- for season in seasons_sorted:\n+ for season in seasons:\nli = xbmcgui.ListItem(label=season['text'])\n# add some art to the item\nli.setArt(self._generate_art_info(entry=season))\n@@ -764,11 +793,14 @@ class KodiHelper(object):\nli=li,\nbase_info={'mediatype': 'season'})\nself._generate_context_menu_items(entry=season, li=li)\n- params = {'action': 'episode_list', 'season_id': season['id']}\nif 'tvshowtitle' in infos:\ntitle = infos.get('tvshowtitle', '').encode('utf-8')\n- params['tvshowtitle'] = base64.urlsafe_b64encode(title)\n- url = build_url(params)\n+ params = {'tvshowtitle': base64.urlsafe_b64encode(title)}\n+ else:\n+ params = None\n+ url = common.build_directory_url(\n+ pathitems=['show', tvshowid, 'seasons', season['id']],\n+ params=params)\nxbmcplugin.addDirectoryItem(\nhandle=common.PLUGIN_HANDLE,\nurl=url,\n@@ -797,7 +829,7 @@ class KodiHelper(object):\nreturn True\n@custom_viewmode(VIEW_EPISODE)\n- def build_episode_listing(self, episodes_sorted, build_url):\n+ def build_episode_listing(self, tvshowid, seasonid, episodes):\n\"\"\"Builds the episode list screen for a season of a show\nParameters\n@@ -813,7 +845,7 @@ class KodiHelper(object):\nbool\nList could be build\n\"\"\"\n- for episode in episodes_sorted:\n+ for episode in episodes:\nli = xbmcgui.ListItem(label=episode['title'])\n# add some art to the item\nli.setArt(self._generate_art_info(entry=episode))\n@@ -825,9 +857,10 @@ class KodiHelper(object):\nself._generate_context_menu_items(entry=episode, li=li)\nmaturity = episode.get('maturity', {}).get('maturityLevel', 999)\nneeds_pin = (True, False)[int(maturity) >= 100]\n- url = build_url({\n- 'action': 'play_video',\n- 'video_id': episode['id'],\n+ url = common.build_play_url(\n+ pathitems=['show', tvshowid, 'seasons', seasonid, 'episodes',\n+ episode['id']],\n+ params={\n'start_offset': episode['bookmark'],\n'infoLabels': infos,\n'pin': needs_pin})\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/__init__.py",
"new_path": "resources/lib/navigation/__init__.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Navigation handling\"\"\"\n+from __future__ import unicode_literals\n+\n+class InvalidPathError(Exception):\n+ \"\"\"The requested path is invalid and could not be routed\"\"\"\n+ pass\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/directory.py",
"new_path": "resources/lib/navigation/directory.py",
"diff": "@@ -4,22 +4,20 @@ from __future__ import unicode_literals\nimport resources.lib.common as common\nimport resources.lib.api.shakti as api\n+from resources.lib.navigation import InvalidPathError\nfrom resources.lib.kodi.KodiHelper import KodiHelper\nfrom resources.lib.library.Library import Library\nBASE_PATH_ITEM = 'directory'\n-VIDEO_LIST_TYPES = ['queue', 'topTen', 'netflixOriginals', 'continueWatching',\n- 'trendingNow', 'newRelease', 'popularTitles']\ndef build(pathitems, params):\n\"\"\"Build a directory listing for the given path\"\"\"\ntry:\nbuilder = DirectoryBuilder(params).__getattribute__(\npathitems[0] if pathitems else 'root')\n- except (IndexError, AttributeError):\n- common.error('Invalid directory path: {}'.format('/'.join(pathitems)))\n- return\n+ except AttributeError:\n+ raise InvalidPathError('Cannot route {}'.format('/'.join(pathitems)))\nif len(pathitems) > 1:\nbuilder((pathitems[1:]))\n@@ -51,29 +49,31 @@ class DirectoryBuilder(object):\nself.kodi_helper.build_profiles_listing(api.profiles())\ndef home(self):\n- user_list_order = [\n- 'queue', 'continueWatching', 'topTen',\n- 'netflixOriginals', 'trendingNow',\n- 'newRelease', 'popularTitles']\n- # define where to route the user\n- actions = {\n- 'recommendations': 'user-items',\n- 'genres': 'user-items',\n- 'search': 'user-items',\n- 'exported': 'user-items',\n- 'default': 'video_list'\n- }\nself.kodi_helper.build_main_menu_listing(\n- video_list_ids=api.root_lists(),\n- user_list_order=user_list_order,\n- actions=actions,\n- build_url=common.build_url)\n+ lolomo=api.root_lists())\ndef video_list(self, pathitems):\n- if pathitems[0] in VIDEO_LIST_TYPES:\n+ # Use predefined names instead of dynamic IDs for common video lists\n+ if pathitems[0] in common.KNOWN_LIST_TYPES:\nvideo_list_id = api.video_list_id_for_type(pathitems[0])\nelse:\nvideo_list_id = pathitems[0]\nself.kodi_helper.build_video_listing(\nvideo_list=api.video_list(video_list_id))\n+\n+ def show(self, pathitems):\n+ tvshowid = pathitems[0]\n+ if len(pathitems > 2):\n+ self.season(tvshowid, pathitems[2:])\n+ else:\n+ self.kodi_helper.build_season_listing(\n+ tvshowid=tvshowid,\n+ seasons=api.seasons(tvshowid))\n+\n+ def season(self, tvshowid, pathitems):\n+ seasonid = pathitems[0]\n+ self.kodi_helper.build_episode_listing(\n+ tvshowid=tvshowid,\n+ seasonid=seasonid,\n+ episodes=api.episodes(tvshowid, seasonid))\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | (possibly broken) Add caching to API operations. Start refactoring Kodi helper. |
105,989 | 20.10.2018 03:28:38 | -7,200 | 9424d87dce8c3676751f9a97d66a6475c8ed9100 | Get complete infolabels | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/data_types.py",
"new_path": "resources/lib/api/data_types.py",
"diff": "@@ -5,9 +5,7 @@ from __future__ import unicode_literals\nfrom collections import OrderedDict\n-import resources.lib.common as common\n-\n-from .paths import ART_PARTIAL_PATHS\n+from .paths import resolve_refs\nclass LoLoMo(object):\n\"\"\"List of list of movies (lolomo)\"\"\"\n@@ -16,8 +14,7 @@ class LoLoMo(object):\nself.data = path_response\nself.id = self.data['lolomo'][1]\nself.lists = OrderedDict(\n- _sort_and_resolve_refs(self.data['lolomos'][self.id],\n- self.data))\n+ resolve_refs(self.data['lolomos'][self.id], self.data))\ndef lists_by_context(self, context):\n\"\"\"Return a generator expression that iterates over all video\n@@ -41,8 +38,7 @@ class VideoList(object):\nself.data = path_response\nself.id = self.data['lists'].keys()[0]\nself.videos = OrderedDict(\n- _sort_and_resolve_refs(self.data['lists'][self.id],\n- self.data))\n+ resolve_refs(self.data['lists'][self.id], self.data))\nclass SeasonList(object):\n\"\"\"A video list\"\"\"\n@@ -51,8 +47,9 @@ class SeasonList(object):\nself.data = path_response\nself.tvshowid = tvshowid\nself.seasons = OrderedDict(\n- _sort_and_resolve_refs(\n- self.data['videos'][self.tvshowid]['seasonList'], self.data))\n+ resolve_refs(\n+ self.data['videos'][self.tvshowid]['seasonList'],\n+ self.data))\nself.tvshow = self.data['videos'][self.tvshowid]\nclass EpisodeList(object):\n@@ -63,49 +60,7 @@ class EpisodeList(object):\nself.tvshowid = tvshowid\nself.seasonid = seasonid\nself.episodes = OrderedDict(\n- _sort_and_resolve_refs(\n- self.data['seasons'][self.seasonid]['episodes'], self.data))\n+ resolve_refs(\n+ self.data['seasons'][self.seasonid]['episodes'],\n+ self.data))\nself.tvshowart = None\n-\n-class InvalidReferenceError(Exception):\n- \"\"\"The provided reference cannot be dealt with as it is in an\n- unexpected format\"\"\"\n- pass\n-\n-def _sort_and_resolve_refs(references, targets):\n- \"\"\"Return a generator expression that returns the objects in targets\n- by resolving the references in sorted order\"\"\"\n- return (common.get_path(ref, targets, include_key=True)\n- for index, ref in _iterate_to_sentinel(references))\n-\n-def _iterate_to_sentinel(source):\n- \"\"\"Generator expression that iterates over a dictionary of\n- index=>reference pairs in sorted order until it reaches the sentinel\n- reference and stops iteration.\n- Items with a key that do not represent an integer are ignored.\"\"\"\n- for index, ref in sorted({int(k): v\n- for k, v in source.iteritems()\n- if common.is_numeric(k)}.iteritems()):\n- path = _reference_path(ref)\n- if _is_sentinel(path):\n- break\n- else:\n- yield (index, path)\n-\n-def _reference_path(ref):\n- \"\"\"Return the actual reference path (a list of path items to follow)\n- for a reference item.\n- The Netflix API sometimes adds another dict layer with a single key\n- 'reference' which we need to extract from.\"\"\"\n- if isinstance(ref, list):\n- return ref\n- elif isinstance(ref, dict) and 'reference' in ref:\n- return ref['reference']\n- else:\n- raise InvalidReferenceError(\n- 'Unexpected reference format encountered: {}'.format(ref))\n-\n-def _is_sentinel(ref):\n- \"\"\"Check if a reference item is of type sentinel and thus signals\n- the end of the list\"\"\"\n- return isinstance(ref, dict) and ref.get('$type') == 'sentinel'\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/paths.py",
"new_path": "resources/lib/api/paths.py",
"diff": "\"\"\"Path info to query the Shakti pathEvaluator\"\"\"\nfrom __future__ import unicode_literals\n+import resources.lib.common as common\n+\nART_SIZE_POSTER = '_342x684'\nART_SIZE_FHD = '_1920x1080'\nART_SIZE_SD = '_665x375'\n@@ -20,18 +22,87 @@ VIDEO_LIST_PARTIAL_PATHS = [\n'releaseYear', 'userRating', 'numSeasonsLabel', 'bookmarkPosition',\n'watched', 'delivery']],\n[['genres', 'tags', 'creators', 'directors', 'cast'],\n- {'from': 0, 'to': 10}, ['id', 'name']],\n- [['genres', 'tags', 'creators', 'directors', 'cast'], 'summary']\n+ {'from': 0, 'to': 10}, ['id', 'name']]\n] + ART_PARTIAL_PATHS\nSEASONS_PARTIAL_PATHS = [\n['seasonList', {'from': 0, 'to': 40}, 'summary'],\n+ ['title']\n] + ART_PARTIAL_PATHS\nEPISODES_PARTIAL_PATHS = [\n[['summary', 'synopsis', 'title', 'runtime', 'releaseYear', 'queue',\n- 'info', 'maturity', 'userRating', 'bookmarkPosition', 'creditOffset',\n+ 'info', 'maturity', 'userRating', 'bookmarkPosition', 'creditsOffset',\n'watched', 'delivery']],\n- ['genres', {'from': 0, 'to': 1}, ['id', 'name']],\n- ['genres', 'summary']\n+ [['genres', 'tags', 'creators', 'directors', 'cast'],\n+ {'from': 0, 'to': 10}, ['id', 'name']]\n] + ART_PARTIAL_PATHS\n+\n+INFO_MAPPINGS = {\n+ 'title': 'title',\n+ 'year': 'releaseYear',\n+ 'plot': 'synopsis',\n+ 'season': ['summary', 'season'],\n+ 'episode': ['summary', 'episode'],\n+ 'rating': ['userRating', 'matchScore'],\n+ 'userrating': ['userRating', 'userRating'],\n+ 'mpaa': ['maturity', 'rating', 'value'],\n+ 'duration': 'runtime',\n+ 'bookmark': 'bookmarkPosition',\n+ 'playcount': 'watched'\n+}\n+\n+INFO_TRANSFORMATIONS = {\n+ 'rating': lambda r: r / 10,\n+ 'playcount': lambda w: int(w)\n+}\n+\n+REFERENCE_MAPPINGS = {\n+ 'cast': 'cast',\n+ 'director': 'directors',\n+ 'writer': 'creators',\n+ 'genre': 'genres'\n+}\n+\n+class InvalidReferenceError(Exception):\n+ \"\"\"The provided reference cannot be dealt with as it is in an\n+ unexpected format\"\"\"\n+ pass\n+\n+def resolve_refs(references, targets):\n+ \"\"\"Return a generator expression that returns the objects in targets\n+ by resolving the references in sorted order\"\"\"\n+ return (common.get_path(ref, targets, include_key=True)\n+ for index, ref in iterate_to_sentinel(references))\n+\n+def iterate_to_sentinel(source):\n+ \"\"\"Generator expression that iterates over a dictionary of\n+ index=>reference pairs in sorted order until it reaches the sentinel\n+ reference and stops iteration.\n+ Items with a key that do not represent an integer are ignored.\"\"\"\n+ for index, ref in sorted({int(k): v\n+ for k, v in source.iteritems()\n+ if common.is_numeric(k)}.iteritems()):\n+ path = reference_path(ref)\n+ if is_sentinel(path):\n+ break\n+ else:\n+ yield (index, path)\n+\n+def reference_path(ref):\n+ \"\"\"Return the actual reference path (a list of path items to follow)\n+ for a reference item.\n+ The Netflix API sometimes adds another dict layer with a single key\n+ 'reference' which we need to extract from.\"\"\"\n+ if isinstance(ref, list):\n+ return ref\n+ elif isinstance(ref, dict) and 'reference' in ref:\n+ return ref['reference']\n+ else:\n+ raise InvalidReferenceError(\n+ 'Unexpected reference format encountered: {}'.format(ref))\n+\n+def is_sentinel(ref):\n+ \"\"\"Check if a reference item is of type sentinel and thus signals\n+ the end of the list\"\"\"\n+ return isinstance(ref, dict) and ref.get('$type') == 'sentinel'\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -86,7 +86,8 @@ def episodes(tvshow_id, season_id):\nbuild_paths(['seasons', season_id, 'episodes', {'from': 0, 'to': 40}],\nEPISODES_PARTIAL_PATHS) +\nbuild_paths(['videos', tvshow_id],\n- ART_PARTIAL_PATHS)))\n+ ART_PARTIAL_PATHS +\n+ [['title']])))\ndef browse_genre(genre_id):\n\"\"\"Retrieve video lists for a genre\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -166,7 +166,7 @@ def build_video_listing(video_list):\ndirectory_items = []\nfor video_id, video in video_list.videos.iteritems():\nlist_item = create_list_item(video['title'])\n- # add_infolabels(list_item, video)\n+ add_info(list_item, video, video_list.data)\nadd_art(list_item, video)\nneeds_pin = int(video.get('maturity', {})\n.get('level', 1001)) >= 1000\n@@ -203,7 +203,7 @@ def build_season_listing(tvshowid, season_list):\ndirectory_items = []\nfor season_id, season in season_list.seasons.iteritems():\nlist_item = create_list_item(season['summary']['name'])\n- # add_infolabels(list_item, video)\n+ add_info(list_item, season, season_list.data, tvshowid)\nadd_art(list_item, season_list.tvshow)\ndirectory_items.append(\n(common.build_directory_url(\n@@ -227,7 +227,7 @@ def build_episode_listing(tvshowid, seasonid, episode_list):\ndirectory_items = []\nfor episode_id, episode in episode_list.episodes.iteritems():\nlist_item = create_list_item(episode['title'])\n- # add_infolabels(list_item, video)\n+ add_info(list_item, episode, episode_list.data, tvshowid)\nadd_art(list_item, episode)\ndirectory_items.append(\n(common.build_url(\n@@ -245,6 +245,73 @@ def build_episode_listing(tvshowid, seasonid, episode_list):\nxbmcplugin.SORT_METHOD_LASTPLAYED],\ncontent_type=CONTENT_EPISODE)\n+def add_info(list_item, item, raw_data, tvshowid=None):\n+ \"\"\"Add infolabels to the list_item\"\"\"\n+ # Only season items don't have a type in their summary\n+ mediatype = item['summary'].get('type', 'season')\n+ if mediatype == 'show':\n+ # Type from Netflix doesn't match Kodi's expectations\n+ mediatype = 'tvshow'\n+ infos = {\n+ 'mediatype': mediatype,\n+ }\n+\n+ if mediatype == 'tvshow':\n+ infos['tvshowtitle'] = item['title']\n+ elif tvshowid and mediatype in ['season', 'episode']:\n+ infos['tvshowtitle'] = raw_data['videos'][tvshowid]['title']\n+\n+ for target, source in paths.INFO_MAPPINGS.iteritems():\n+ value = (common.get_path_safe(source, item)\n+ if isinstance(source, list)\n+ else item.get(source))\n+ if isinstance(value, dict):\n+ common.debug('Got a sentinel for {}: {}'.format(target, value))\n+ value = None\n+ if value is None:\n+ common.debug('Cannot get {} from {}'.format(target, source))\n+ continue\n+ if target in paths.INFO_TRANSFORMATIONS:\n+ value = paths.INFO_TRANSFORMATIONS[target](value)\n+ infos[target] = value\n+\n+ for target, source in paths.REFERENCE_MAPPINGS.iteritems():\n+ infos[target] = [\n+ person['name']\n+ for _, person\n+ in paths.resolve_refs(item.get(source, {}), raw_data)]\n+\n+ infos['tag'] = [tagdef['name']\n+ for tagdef\n+ in item.get('tags', {}).itervalues()\n+ if isinstance(tagdef.get('name', {}), unicode)]\n+\n+ # TODO: Cache infolabels (to mem or possibly disk)\n+ list_item.setInfo('video', infos)\n+ if infos['mediatype'] in ['episode', 'movie']:\n+ list_item.setProperty('IsPlayable', 'true')\n+ for stream_type, quality_infos in get_quality_infos(item).iteritems():\n+ list_item.addStreamInfo(stream_type, quality_infos)\n+ return infos\n+\n+def get_quality_infos(item):\n+ \"\"\"Return audio and video quality infolabels\"\"\"\n+ quality_infos = {}\n+ delivery = item.get('delivery')\n+ if delivery:\n+ if delivery.get('hasHD'):\n+ quality_infos['video'] = {'width': '1920', 'height': '1080'}\n+ elif delivery.get('hasUltraHD'):\n+ quality_infos['video'] = {'width': '3840', 'height': '2160'}\n+ else:\n+ quality_infos['video'] = {'width': '960', 'height': '540'}\n+ # quality_infos = {'width': '1280', 'height': '720'}\n+ if delivery.get('has51Audio'):\n+ quality_infos['audio'] = {'codec': 'eac3', 'channels': 6}\n+ else:\n+ quality_infos['audio'] = {'codec': 'eac3', 'channels': 2}\n+ return quality_infos\n+\ndef add_art(list_item, item):\n\"\"\"Add art infolabels to list_item\"\"\"\nboxarts = common.get_multiple_paths(\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Get complete infolabels |
105,989 | 22.10.2018 10:10:22 | -7,200 | d52b4ec7bbace59d093cbb348513e7d9e604e0ec | Fix playback | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -106,7 +106,7 @@ def metadata(video_id):\n'component': 'metadata',\n'req_type': 'api',\n'params': {'movieid': video_id}\n- })\n+ })['video']\ndef build_paths(base_path, partial_paths):\n\"\"\"Build a list of full paths by concatenating each partial path\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/player.py",
"new_path": "resources/lib/navigation/player.py",
"diff": "@@ -42,7 +42,7 @@ def play_item(pathitems, params):\nif pathitems[0] == 'show' and len(pathitems) == 6:\nplay_episode(tvshowid=pathitems[1],\nseasonid=pathitems[3],\n- episodeid=pathitems[4])\n+ episodeid=pathitems[5])\nelif pathitems[0] == 'movie' and len(pathitems) == 2:\nplay_movie(movieid=pathitems[1])\nelse:\n@@ -50,6 +50,7 @@ def play_item(pathitems, params):\ndef play_episode(tvshowid, seasonid, episodeid):\n\"\"\"Play an episode\"\"\"\n+ common.info('Playing episode {}'.format(episodeid))\nmetadata = api.metadata(tvshowid)\nepisode_metadata = common.find_episode(episodeid, metadata['seasons'])\nsignal_data = ({'tvshow_video_id': tvshowid})\n@@ -63,6 +64,8 @@ def play_video(video_id, metadata, signal_data=None):\n\"\"\"Generically play a video\"\"\"\nsignal_data = signal_data or {}\nsignal_data['timeline_markers'] = get_timeline_markers(metadata)\n+ common.debug('Got timeline markers: {}'\n+ .format(signal_data['timeline_markers']))\nlist_item = get_inputstream_listitem(video_id)\n# infolabels.add_info(list_item)\n# infolabels.add_art(list_item)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -153,7 +153,7 @@ class NetflixSession(object):\ntry:\n# If we can get session data, cookies are still valid\nself.session_data = website.extract_session_data(\n- self._get('profiles').content)\n+ self._get('profiles'))\nself._update_esn()\nexcept Exception:\ncommon.info('Stored cookies are expired')\n@@ -165,12 +165,12 @@ class NetflixSession(object):\ntry:\ncommon.debug('Extracting authURL...')\nauth_url = website.extract_userdata(\n- self._get('profiles').content)['authURL']\n+ self._get('profiles'))['authURL']\ncommon.debug('Logging in...')\nlogin_response = self._post(\n'login', _login_payload(self.credentials, auth_url))\ncommon.debug('Extracting session data...')\n- session_data = website.extract_session_data(login_response.content)\n+ session_data = website.extract_session_data(login_response)\nexcept Exception as exc:\nraise common.reraise(\nexc, 'Login failed', LoginFailedError, sys.exc_info()[2])\n@@ -238,7 +238,7 @@ class NetflixSession(object):\nreq_type='api',\nparams=params,\nheaders=headers,\n- data=data).json()['value']\n+ data=data)['value']\[email protected]_return_call\n@needs_login\n@@ -267,7 +267,7 @@ class NetflixSession(object):\ndef _request(self, method, component, **kwargs):\nurl = (_api_url(component, self.session_data['api_data'])\n- if kwargs.get('req_type') == 'api'\n+ if URLS[component]['is_api_call']\nelse _document_url(component))\ncommon.debug(\n'Executing {verb} request to {url}'.format(\n@@ -281,7 +281,9 @@ class NetflixSession(object):\ncommon.debug(\n'Request returned statuscode {}'.format(response.status_code))\nresponse.raise_for_status()\n- return response\n+ return (response.json()\n+ if URLS[component]['is_api_call']\n+ else response.content)\ndef _login_payload(credentials, auth_url):\nreturn {\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix playback |
105,989 | 22.10.2018 12:12:00 | -7,200 | ce69dec28d7cf735cf875c1bfd4ac47a89ae6884 | Add proper handling of infolabels and art upon playback | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "@@ -36,7 +36,7 @@ def route(pathitems):\nelif root_handler == nav.MODE_HUB:\nhub.browse(*pass_on_params)\nelif root_handler == nav.MODE_PLAY:\n- player.play_item(*pass_on_params)\n+ player.play(*pass_on_params)\nelif root_handler == 'logout':\napi.logout()\nelif root_handler == 'opensettings':\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -5,10 +5,8 @@ from __future__ import unicode_literals\nimport json\nimport resources.lib.common as common\n+import resources.lib.cache as cache\nfrom resources.lib.services.nfsession import NetflixSession\n-from resources.lib.cache import (cache_output, invalidate_cache, CACHE_COMMON,\n- CACHE_VIDEO_LIST, CACHE_SEASONS,\n- CACHE_EPISODES, CACHE_METADATA)\nfrom .data_types import LoLoMo, VideoList, SeasonList, EpisodeList\nfrom .paths import (VIDEO_LIST_PARTIAL_PATHS, SEASONS_PARTIAL_PATHS,\n@@ -20,19 +18,19 @@ class InvalidVideoListTypeError(Exception):\ndef activate_profile(profile_id):\n\"\"\"Activate the profile with the given ID\"\"\"\n- invalidate_cache()\n+ cache.invalidate_cache()\ncommon.make_call(NetflixSession.activate_profile, profile_id)\ndef logout():\n\"\"\"Logout of the current account\"\"\"\n- invalidate_cache()\n+ cache.invalidate_cache()\ncommon.make_call(NetflixSession.logout)\ndef profiles():\n\"\"\"Retrieve the list of available user profiles\"\"\"\nreturn common.make_call(NetflixSession.list_profiles)\n-@cache_output(CACHE_COMMON, fixed_identifier='root_lists')\[email protected]_output(cache.CACHE_COMMON, fixed_identifier='root_lists')\ndef root_lists():\n\"\"\"Retrieve initial video lists to display on homepage\"\"\"\ncommon.debug('Requesting root lists from API')\n@@ -42,7 +40,7 @@ def root_lists():\n{'from': 0, 'to': 40},\n['displayName', 'context', 'id', 'index', 'length']]]))\n-@cache_output(CACHE_COMMON, 0, 'list_type')\[email protected]_output(cache.CACHE_COMMON, 0, 'list_type')\ndef list_id_for_type(list_type):\n\"\"\"Return the dynamic video list ID for a video list of known type\"\"\"\ntry:\n@@ -54,7 +52,7 @@ def list_id_for_type(list_type):\n'Resolved list ID for {} to {}'.format(list_type, list_id))\nreturn list_id\n-@cache_output(CACHE_VIDEO_LIST, 0, 'list_id')\[email protected]_output(cache.CACHE_VIDEO_LIST, 0, 'list_id')\ndef video_list(list_id):\n\"\"\"Retrieve a single video list\"\"\"\ncommon.debug('Requesting video list {}'.format(list_id))\n@@ -63,7 +61,7 @@ def video_list(list_id):\nbuild_paths(['lists', [list_id], {'from': 0, 'to': 40}, 'reference'],\nVIDEO_LIST_PARTIAL_PATHS)))\n-@cache_output(CACHE_SEASONS, 0, 'tvshow_id')\[email protected]_output(cache.CACHE_SEASONS, 0, 'tvshow_id')\ndef seasons(tvshow_id):\n\"\"\"Retrieve seasons of a TV show\"\"\"\ncommon.debug('Requesting season list for show {}'.format(tvshow_id))\n@@ -74,7 +72,7 @@ def seasons(tvshow_id):\nbuild_paths(['videos', tvshow_id],\nSEASONS_PARTIAL_PATHS)))\n-@cache_output(CACHE_EPISODES, 1, 'season_id')\[email protected]_output(cache.CACHE_EPISODES, 1, 'season_id')\ndef episodes(tvshow_id, season_id):\n\"\"\"Retrieve episodes of a season\"\"\"\ncommon.debug('Requesting episode list for show {}, season {}'\n@@ -91,12 +89,35 @@ def episodes(tvshow_id, season_id):\nART_PARTIAL_PATHS +\n[['title']])))\[email protected]_output(cache.CACHE_EPISODES, 1, 'episode_id')\n+def episode(tvshow_id, episode_id):\n+ \"\"\"Retrieve info for a single episode\"\"\"\n+ common.debug('Requesting single episode info for {}'\n+ .format(episode_id))\n+ return common.make_call(\n+ NetflixSession.path_request,\n+ build_paths(['videos', episode_id],\n+ EPISODES_PARTIAL_PATHS) +\n+ build_paths(['videos', tvshow_id],\n+ ART_PARTIAL_PATHS +\n+ [['title']]))\n+\[email protected]_output(cache.CACHE_EPISODES, 0, 'movie_id')\n+def movie(movie_id):\n+ \"\"\"Retrieve info for a single movie\"\"\"\n+ common.debug('Requesting movie info for {}'\n+ .format(movie_id))\n+ return common.make_call(\n+ NetflixSession.path_request,\n+ build_paths(['videos', movie_id],\n+ EPISODES_PARTIAL_PATHS))\n+\ndef browse_genre(genre_id):\n\"\"\"Retrieve video lists for a genre\"\"\"\npass\n-@cache_output(CACHE_METADATA, 0, 'video_id', ttl=common.CACHE_METADATA_TTL,\n- to_disk=True)\[email protected]_output(cache.CACHE_METADATA, 0, 'video_id',\n+ ttl=common.CACHE_METADATA_TTL, to_disk=True)\ndef metadata(video_id):\n\"\"\"Retrieve additional metadata for a video\"\"\"\ncommon.debug('Requesting metdata for {}'.format(video_id))\n@@ -108,6 +129,19 @@ def metadata(video_id):\n'params': {'movieid': video_id}\n})['video']\n+def episode_metadata(tvshowid, seasonid, episodeid):\n+ \"\"\"Retrieve metadata for a single episode\"\"\"\n+ try:\n+ return common.find_episode(episodeid, metadata(tvshowid)['seasons'])\n+ except KeyError:\n+ # Episode metadata may not exist if its a new episode and cached data\n+ # is outdated. In this case, invalidate the cache entry and try again\n+ # safely (if it doesn't exist this time, there is no metadata for the\n+ # episode, so we assign an empty dict).\n+ cache.invalidate_entry(cache.CACHE_METADATA, tvshowid)\n+ return (metadata(tvshowid).get('seasons', {}).get(seasonid, {})\n+ .get('episodes', {}).get(episodeid, {}))\n+\ndef build_paths(base_path, partial_paths):\n\"\"\"Build a list of full paths by concatenating each partial path\nwith the base path\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -407,14 +407,14 @@ def find_episode(episode_id, seasons):\n\"\"\"\nGet metadata for a specific episode from within a nested\nmetadata dict.\n- :return: Episode metadata or an empty dict if the episode could not\n- be found.\n+ :return: Episode metadata. Raises KeyError if metadata for episode_id\n+ does not exist.\n\"\"\"\nfor season in seasons:\nfor episode in season['episodes']:\nif str(episode['id']) == episode_id:\nreturn episode\n- return {}\n+ raise KeyError('Metadata for episode {} does not exist'.format(episode_id))\ndef update_library_item_details(dbtype, dbid, details):\n\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -124,4 +124,4 @@ def add_art(list_item, item, item_id):\ncache.add(cache.CACHE_ARTINFO, item_id, art,\nttl=common.CACHE_METADATA_TTL, to_disk=True)\nlist_item.setArt(art)\n- return list_item\n+ return art\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/player.py",
"new_path": "resources/lib/navigation/player.py",
"diff": "@@ -7,7 +7,6 @@ import xbmcgui\nimport inputstreamhelper\nimport resources.lib.common as common\n-import resources.lib.cache as cache\nimport resources.lib.api.shakti as api\nimport resources.lib.kodi.infolabels as infolabels\nfrom resources.lib.services.playback import get_timeline_markers\n@@ -37,8 +36,8 @@ class InputstreamError(Exception):\n\"\"\"There was an error with setting up inputstream.adaptive\"\"\"\npass\n-def play_item(pathitems, params):\n- \"\"\"Play an item as specified by the path\"\"\"\n+def play(pathitems, params):\n+ \"\"\"Play an episode or movie as specified by the path\"\"\"\nif pathitems[0] == 'show' and len(pathitems) == 6:\nplay_episode(tvshowid=pathitems[1],\nseasonid=pathitems[3],\n@@ -51,24 +50,22 @@ def play_item(pathitems, params):\ndef play_episode(tvshowid, seasonid, episodeid):\n\"\"\"Play an episode\"\"\"\ncommon.info('Playing episode {}'.format(episodeid))\n- metadata = api.metadata(tvshowid)\n- episode_metadata = common.find_episode(episodeid, metadata['seasons'])\n- signal_data = ({'tvshow_video_id': tvshowid})\n- play_video(episodeid, episode_metadata, signal_data)\n+ play_video(episodeid, api.episode_metadata(tvshowid, seasonid, episodeid),\n+ tvshowid=tvshowid, signal_data={'tvshow_video_id': tvshowid})\ndef play_movie(movieid):\n\"\"\"Play a movie\"\"\"\n+ common.info('Playing movie {}'.format(movieid))\nplay_video(movieid, api.metadata(movieid))\n-def play_video(video_id, metadata, signal_data=None):\n+def play_video(videoid, metadata, tvshowid=None, signal_data=None):\n\"\"\"Generically play a video\"\"\"\n+ list_item = get_inputstream_listitem(videoid)\n+ infos, art = add_infolabels_and_art(list_item, videoid, tvshowid)\nsignal_data = signal_data or {}\n+ signal_data['infos'] = infos\n+ signal_data['art'] = art\nsignal_data['timeline_markers'] = get_timeline_markers(metadata)\n- common.debug('Got timeline markers: {}'\n- .format(signal_data['timeline_markers']))\n- list_item = get_inputstream_listitem(video_id)\n- # infolabels.add_info(list_item)\n- # infolabels.add_art(list_item)\ncommon.send_signal(common.Signals.PLAYBACK_INITIATED, signal_data)\nxbmcplugin.setResolvedUrl(\nhandle=common.PLUGIN_HANDLE,\n@@ -114,3 +111,23 @@ def get_inputstream_listitem(video_id):\nkey='inputstreamaddon',\nvalue=is_helper.inputstream_addon)\nreturn list_item\n+\n+def add_infolabels_and_art(list_item, videoid, tvshowid):\n+ \"\"\"Retrieve infolabels and art info and add them to the list_item\"\"\"\n+ try:\n+ infos = infolabels.add_info(list_item, None, None, None)\n+ art = infolabels.add_art(list_item, None, None)\n+ common.debug('Got infolabels and art from cache')\n+ except TypeError:\n+ common.info('Infolabels or art were not in cache, retrieving from API')\n+ api_data = (api.movie(videoid)\n+ if tvshowid is None\n+ else api.episode(tvshowid, videoid))\n+ infos = infolabels.add_info(list_item,\n+ item=api_data['videos'][videoid],\n+ item_id=videoid,\n+ raw_data=api_data,\n+ tvshowid=tvshowid)\n+ art = infolabels.add_art(list_item, item=api_data['videos'][videoid],\n+ item_id=videoid)\n+ return infos, art\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/playback/markers.py",
"new_path": "resources/lib/services/playback/markers.py",
"diff": "@@ -32,6 +32,9 @@ def get_offset_markers(metadata):\ndef get_section_markers(metadata):\n\"\"\"Extract section start and end markers from metadata if they exist\"\"\"\n+ if not metadata.get('creditMarkers'):\n+ return {}\n+\nreturn {\nsection: {\n'start': int(metadata['creditMarkers'][section]['start'] /\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add proper handling of infolabels and art upon playback |
105,989 | 22.10.2018 14:05:54 | -7,200 | f2ae9faafef93f4a6f511f97e81391fbaebf65ce | Replace pickle with json | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "@@ -36,7 +36,7 @@ def route(pathitems):\nelif root_handler == nav.MODE_HUB:\nhub.browse(*pass_on_params)\nelif root_handler == nav.MODE_PLAY:\n- player.play(*pass_on_params)\n+ player.play(pathitems[1:])\nelif root_handler == 'logout':\napi.logout()\nelif root_handler == 'opensettings':\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -6,10 +6,7 @@ import os\nfrom time import time\nfrom collections import OrderedDict\nfrom functools import wraps\n-try:\n- import cPickle as pickle\n-except ImportError:\n- import pickle\n+import json\nimport xbmcgui\n@@ -80,40 +77,40 @@ def cache_output(bucket, identifying_param_index=0,\nreturn wrapper\nreturn caching_decorator\n-def inject_from_cache(bucket, injection_param,\n- identifying_param_index=0,\n- identifying_param_name=None,\n- fixed_identifier=None,\n- to_disk=False):\n- \"\"\"Decorator that injects a cached value as parameter if available.\n- The decorated function must return a value to be added to the cache.\"\"\"\n- # pylint: disable=missing-docstring\n- def injecting_cache_decorator(func):\n- @wraps(func)\n- def wrapper(*args, **kwargs):\n- if fixed_identifier:\n- # Use the identifier that's statically defined in the applied\n- # decorator isntead of one of the parameters' value\n- identifier = fixed_identifier\n- else:\n- try:\n- # prefer keyword over positional arguments\n- identifier = kwargs.get(\n- identifying_param_name, args[identifying_param_index])\n- except IndexError:\n- common.error(\n- 'Invalid cache configuration.'\n- 'Cannot determine identifier from params')\n- try:\n- value_to_inject = get(bucket, identifier)\n- except CacheMiss:\n- value_to_inject = None\n- kwargs[injection_param] = value_to_inject\n- output = func(*args, **kwargs)\n- add(bucket, identifier, output, ttl=ttl, to_disk=to_disk)\n- return output\n- return wrapper\n- return injecting_cache_decorator\n+# def inject_from_cache(bucket, injection_param,\n+# identifying_param_index=0,\n+# identifying_param_name=None,\n+# fixed_identifier=None,\n+# to_disk=False):\n+# \"\"\"Decorator that injects a cached value as parameter if available.\n+# The decorated function must return a value to be added to the cache.\"\"\"\n+# # pylint: disable=missing-docstring\n+# def injecting_cache_decorator(func):\n+# @wraps(func)\n+# def wrapper(*args, **kwargs):\n+# if fixed_identifier:\n+# # Use the identifier that's statically defined in the applied\n+# # decorator isntead of one of the parameters' value\n+# identifier = fixed_identifier\n+# else:\n+# try:\n+# # prefer keyword over positional arguments\n+# identifier = kwargs.get(\n+# identifying_param_name, args[identifying_param_index])\n+# except IndexError:\n+# common.error(\n+# 'Invalid cache configuration.'\n+# 'Cannot determine identifier from params')\n+# try:\n+# value_to_inject = get(bucket, identifier)\n+# except CacheMiss:\n+# value_to_inject = None\n+# kwargs[injection_param] = value_to_inject\n+# output = func(*args, **kwargs)\n+# add(bucket, identifier, output, ttl=ttl, to_disk=to_disk)\n+# return output\n+# return wrapper\n+# return injecting_cache_decorator\ndef get_bucket(key):\n\"\"\"Get a cache bucket.\n@@ -165,7 +162,7 @@ def get_from_disk(bucket, identifier):\n.format(cache_filename))\ntry:\nwith open(cache_filename, 'rb') as cache_file:\n- cache_entry = pickle.load(cache_file)\n+ cache_entry = json.load(cache_file)\nexcept Exception as exc:\ncommon.debug('Could not load from disk: {}'.format(exc))\nraise CacheMiss()\n@@ -187,7 +184,7 @@ def add_to_disk(bucket, identifier, cache_entry):\ncache_filename = _cache_filename(bucket, identifier)\ntry:\nwith open(cache_filename, 'wb') as cache_file:\n- pickle.dump(cache_entry, cache_file)\n+ json.dump(cache_entry, cache_file)\nexcept Exception as exc:\ncommon.error('Failed to write cache entry to {}: {}'\n.format(cache_filename, exc))\n@@ -213,16 +210,16 @@ def _window_property(bucket):\ndef _load_bucket(bucket):\n# pylint: disable=broad-except\ntry:\n- return pickle.loads(WND.getProperty(_window_property(bucket)))\n+ return json.loads(WND.getProperty(_window_property(bucket)))\nexcept Exception:\ncommon.debug('Failed to load cache bucket {}. Returning empty bucket.'\n.format(bucket))\n- return OrderedDict()\n+ return {}\ndef _persist_bucket(bucket, contents):\n# pylint: disable=broad-except\ntry:\n- WND.setProperty(_window_property(bucket), pickle.dumps(contents))\n+ WND.setProperty(_window_property(bucket), json.dumps(contents))\nexcept Exception as exc:\ncommon.error('Failed to persist cache bucket: {exc}', exc)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -12,14 +12,8 @@ from datetime import datetime, timedelta\nfrom urlparse import urlparse, parse_qsl\nfrom urllib import urlencode\n-try:\n- import cPickle as pickle\n-except ImportError:\n- import pickle\n-\nimport xbmc\nimport xbmcaddon\n-import xbmcvfs\nimport AddonSignals\nimport resources.lib.kodi.ui.newdialogs as dialogs\n@@ -87,8 +81,10 @@ def init_globals(argv):\nPARAM_STRING = ''\nREQUEST_PARAMS = dict(parse_qsl(PARAM_STRING))\n- if not xbmcvfs.exists(DATA_PATH):\n- xbmcvfs.mkdir(DATA_PATH)\n+ try:\n+ os.path.mkdirs(DATA_PATH)\n+ except OSError:\n+ pass\ninit_globals(sys.argv)\n@@ -149,9 +145,8 @@ class PersistentStorage(object):\n\"\"\"\nWrite current contents to disk\n\"\"\"\n- file_handle = xbmcvfs.File(self.backing_file, 'wb')\n- pickle.dump(self._contents, file_handle)\n- file_handle.close()\n+ with open(self.backing_file, 'w+') as file_handle:\n+ json.dump(self._contents, file_handle)\nlog('Committed changes to backing file')\ndef clear(self):\n@@ -163,14 +158,13 @@ class PersistentStorage(object):\ndef _load_from_disk(self):\nlog('Trying to load contents from disk')\n- if xbmcvfs.exists(self.backing_file):\n- file_handle = xbmcvfs.File(self.backing_file, 'rb')\n- self._contents = pickle.loads(file_handle.read())\n+ try:\n+ with open(self.backing_file, 'r') as file_handle:\n+ self._contents = json.loads(file_handle.read())\n+ except IOError:\n+ log('Backing file does not exist or is not accessible')\nself._dirty = False\n- file_handle.close()\nlog('Loaded contents from backing file: {}'.format(self._contents))\n- else:\n- log('Backing file does not exist')\n__BLOCK_SIZE__ = 32\n__CRYPT_KEY__ = None\n@@ -369,35 +363,32 @@ def file_exists(filename, data_path=DATA_PATH):\n:param filename: The filename\n:return: True if so\n\"\"\"\n- return xbmcvfs.exists(path=data_path + filename)\n+ return os.path.exists(data_path + filename)\n-def save_file(filename, content, data_path=DATA_PATH):\n+def save_file(filename, content, data_path=DATA_PATH, mode='w+'):\n\"\"\"\nSaves the given content under given filename\n:param filename: The filename\n:param content: The content of the file\n\"\"\"\n- file_handle = xbmcvfs.File(filepath=data_path + filename, mode='w')\n+ with open(data_path + filename, mode) as file_handle:\nfile_handle.write(content.encode('utf-8'))\n- file_handle.close()\n-def load_file(filename, data_path=DATA_PATH):\n+def load_file(filename, data_path=DATA_PATH, mode='r'):\n\"\"\"\nLoads the content of a given filename\n:param filename: The file to load\n:return: The content of the file\n\"\"\"\n- file_handle = xbmcvfs.File(filepath=data_path + filename)\n- file_content = file_handle.read()\n- file_handle.close()\n- return file_content\n+ with open(data_path + filename, mode) as file_handle:\n+ return file_handle.read()\ndef list_dir(data_path=DATA_PATH):\n\"\"\"\nList the contents of a folder\n:return: The contents of the folder\n\"\"\"\n- return xbmcvfs.listdir(data_path)\n+ return os.listdir(data_path)\ndef noop(**kwargs):\n\"\"\"Takes everything, does nothing, classic no operation function\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "# -*- coding: utf-8 -*-\n-\"\"\"Helper functions to build plugin listings for Kodi\"\"\"\n+\"\"\"Helper functions for setting infolabels of list items\"\"\"\nfrom __future__ import unicode_literals\nimport resources.lib.common as common\nimport resources.lib.cache as cache\nimport resources.lib.api.paths as paths\n+from resources.lib.kodi.library import ItemNotFound\n+\ndef add_info(list_item, item, item_id, raw_data, tvshowid=None):\n\"\"\"Add infolabels to the list_item. The passed in list_item is modified\nin place and the infolabels are returned.\"\"\"\n@@ -15,6 +17,38 @@ def add_info(list_item, item, item_id, raw_data, tvshowid=None):\ninfos = cache_entry['infos']\nquality_infos = cache_entry['quality_infos']\nexcept cache.CacheMiss:\n+ infos, quality_infos = parse_info(item, raw_data, tvshowid)\n+ cache.add(cache.CACHE_INFOLABELS,\n+ item_id,\n+ {'infos': infos, 'quality_infos': quality_infos},\n+ ttl=common.CACHE_METADATA_TTL, to_disk=True)\n+ list_item.setInfo('video', infos)\n+ if infos['mediatype'] in ['episode', 'movie']:\n+ list_item.setProperty('IsPlayable', 'true')\n+ for stream_type, quality_infos in quality_infos.iteritems():\n+ list_item.addStreamInfo(stream_type, quality_infos)\n+ return infos\n+\n+def add_art(list_item, item, item_id):\n+ \"\"\"Add art infolabels to list_item\"\"\"\n+ try:\n+ art = cache.get(cache.CACHE_ARTINFO, item_id)\n+ except cache.CacheMiss:\n+ art = parse_art(item)\n+ cache.add(cache.CACHE_ARTINFO, item_id, art,\n+ ttl=common.CACHE_METADATA_TTL, to_disk=True)\n+ list_item.setArt(art)\n+ return art\n+\n+def add_info_for_playback(list_item, videoid, tvshowid):\n+ \"\"\"Retrieve infolabels and art info and add them to the list_item\"\"\"\n+ try:\n+ return add_info_from_library(list_item, videoid, tvshowid)\n+ except ItemNotFound:\n+ return add_info_from_netflix(list_item, videoid, tvshowid)\n+\n+def parse_info(item, raw_data, tvshowid):\n+ \"\"\"Parse info from a path request response into Kodi infolabels\"\"\"\n# Only season items don't have a type in their summary, thus, if\n# there's no type, it's a season\nmediatype = item['summary'].get('type', 'season')\n@@ -55,18 +89,7 @@ def add_info(list_item, item, item_id, raw_data, tvshowid=None):\nfor tagdef\nin item.get('tags', {}).itervalues()\nif isinstance(tagdef.get('name', {}), unicode)]\n-\n- cache.add(cache.CACHE_INFOLABELS,\n- item_id,\n- {'infos': infos, 'quality_infos': quality_infos},\n- ttl=common.CACHE_METADATA_TTL, to_disk=True)\n-\n- list_item.setInfo('video', infos)\n- if infos['mediatype'] in ['episode', 'movie']:\n- list_item.setProperty('IsPlayable', 'true')\n- for stream_type, quality_infos in quality_infos.iteritems():\n- list_item.addStreamInfo(stream_type, quality_infos)\n- return infos\n+ return infos, quality_infos\ndef get_quality_infos(item):\n\"\"\"Return audio and video quality infolabels\"\"\"\n@@ -86,11 +109,8 @@ def get_quality_infos(item):\nquality_infos['audio'] = {'channels': 2}\nreturn quality_infos\n-def add_art(list_item, item, item_id):\n- \"\"\"Add art infolabels to list_item\"\"\"\n- try:\n- art = cache.get(cache.CACHE_ARTINFO, item_id)\n- except cache.CacheMiss:\n+def parse_art(item):\n+ \"\"\"Parse art info from a path request response to Kodi art infolabels\"\"\"\nboxarts = common.get_multiple_paths(\npaths.ART_PARTIAL_PATHS[0] + ['url'], item)\nboxart_large = boxarts[paths.ART_SIZE_FHD]\n@@ -121,7 +141,29 @@ def add_art(list_item, item, item_id):\nart['landscape'] = interesting_moment\nif fanart:\nart['fanart'] = fanart\n- cache.add(cache.CACHE_ARTINFO, item_id, art,\n- ttl=common.CACHE_METADATA_TTL, to_disk=True)\n- list_item.setArt(art)\nreturn art\n+\n+def add_info_from_netflix(list_item, videoid, tvshowid):\n+ \"\"\"Apply infolabels with info from Netflix API\"\"\"\n+ try:\n+ infos = add_info(list_item, None, None, None)\n+ art = add_art(list_item, None, None)\n+ common.debug('Got infolabels and art from cache')\n+ except TypeError:\n+ common.info('Infolabels or art were not in cache, retrieving from API')\n+ import resources.lib.api.shakti as api\n+ api_data = (api.movie(videoid)\n+ if tvshowid is None\n+ else api.episode(tvshowid, videoid))\n+ infos = add_info(list_item,\n+ item=api_data['videos'][videoid],\n+ item_id=videoid,\n+ raw_data=api_data,\n+ tvshowid=tvshowid)\n+ art = add_art(list_item, item=api_data['videos'][videoid],\n+ item_id=videoid)\n+ return infos, art\n+\n+def add_info_from_library(list_item, videoid, tvshowid):\n+ \"\"\"Apply infolabels with info from Kodi library\"\"\"\n+ pass\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/directory.py",
"new_path": "resources/lib/navigation/directory.py",
"diff": "@@ -35,6 +35,7 @@ class DirectoryBuilder(object):\napi.activate_profile(profile_id)\ndef root(self):\n+ \"\"\"Show profiles or home listing is autologin es enabled\"\"\"\nautologin = common.ADDON.getSettingBool('autologin_enable')\nprofile_id = common.ADDON.getSetting('autologin_id')\nif autologin and profile_id:\n@@ -46,15 +47,18 @@ class DirectoryBuilder(object):\nself.profiles()\ndef profiles(self):\n+ \"\"\"Show profiles listing\"\"\"\ncommon.debug('Showing profiles listing')\nlistings.build_profiles_listing(api.profiles())\ndef home(self):\n+ \"\"\"Show home listing\"\"\"\ncommon.debug('Showing root video lists')\nlistings.build_main_menu_listing(\nlolomo=api.root_lists())\ndef video_list(self, pathitems):\n+ \"\"\"Show a video list\"\"\"\n# Use predefined names instead of dynamic IDs for common video lists\nif pathitems[0] in common.KNOWN_LIST_TYPES:\nlist_id = api.list_id_for_type(pathitems[0])\n@@ -65,6 +69,7 @@ class DirectoryBuilder(object):\nvideo_list=api.video_list(list_id))\ndef show(self, pathitems):\n+ \"\"\"Show seasons of a tvshow\"\"\"\ntvshowid = pathitems[0]\nif len(pathitems) > 2:\nself.season(tvshowid, pathitems[2:])\n@@ -74,6 +79,7 @@ class DirectoryBuilder(object):\nseason_list=api.seasons(tvshowid))\ndef season(self, tvshowid, pathitems):\n+ \"\"\"Show episodes of a season\"\"\"\nseasonid = pathitems[0]\nlistings.build_episode_listing(\ntvshowid=tvshowid,\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/player.py",
"new_path": "resources/lib/navigation/player.py",
"diff": "@@ -36,7 +36,7 @@ class InputstreamError(Exception):\n\"\"\"There was an error with setting up inputstream.adaptive\"\"\"\npass\n-def play(pathitems, params):\n+def play(pathitems):\n\"\"\"Play an episode or movie as specified by the path\"\"\"\nif pathitems[0] == 'show' and len(pathitems) == 6:\nplay_episode(tvshowid=pathitems[1],\n@@ -61,7 +61,7 @@ def play_movie(movieid):\ndef play_video(videoid, metadata, tvshowid=None, signal_data=None):\n\"\"\"Generically play a video\"\"\"\nlist_item = get_inputstream_listitem(videoid)\n- infos, art = add_infolabels_and_art(list_item, videoid, tvshowid)\n+ infos, art = infolabels.add_info_for_playback(list_item, videoid, tvshowid)\nsignal_data = signal_data or {}\nsignal_data['infos'] = infos\nsignal_data['art'] = art\n@@ -111,23 +111,3 @@ def get_inputstream_listitem(video_id):\nkey='inputstreamaddon',\nvalue=is_helper.inputstream_addon)\nreturn list_item\n-\n-def add_infolabels_and_art(list_item, videoid, tvshowid):\n- \"\"\"Retrieve infolabels and art info and add them to the list_item\"\"\"\n- try:\n- infos = infolabels.add_info(list_item, None, None, None)\n- art = infolabels.add_art(list_item, None, None)\n- common.debug('Got infolabels and art from cache')\n- except TypeError:\n- common.info('Infolabels or art were not in cache, retrieving from API')\n- api_data = (api.movie(videoid)\n- if tvshowid is None\n- else api.episode(tvshowid, videoid))\n- infos = infolabels.add_info(list_item,\n- item=api_data['videos'][videoid],\n- item_id=videoid,\n- raw_data=api_data,\n- tvshowid=tvshowid)\n- art = infolabels.add_art(list_item, item=api_data['videos'][videoid],\n- item_id=videoid)\n- return infos, art\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Replace pickle with json |
105,989 | 22.10.2018 17:48:56 | -7,200 | 3b775762f59e99eac94fd25142adcdd4e5878937 | Get infolabels from kodi library if video was exported | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "# -*- coding: utf-8 -*-\n-\"\"\"Caching for API calls\"\"\"\n+\"\"\"General caching facilities. Caches are segmented into buckets.\n+Within each bucket, identifiers for cache entries must be unique.\"\"\"\nfrom __future__ import unicode_literals\nimport os\nfrom time import time\n-from collections import OrderedDict\nfrom functools import wraps\nimport json\n@@ -157,11 +157,11 @@ def get(bucket, identifier):\ndef get_from_disk(bucket, identifier):\n\"\"\"Load a cache entry from disk and add it to the in memory bucket\"\"\"\n- cache_filename = _cache_filename(bucket, identifier)\n+ cache_filename = _entry_filename(bucket, identifier)\ncommon.debug('Retrieving cache entry from disk at {}'\n.format(cache_filename))\ntry:\n- with open(cache_filename, 'rb') as cache_file:\n+ with open(cache_filename, 'r') as cache_file:\ncache_entry = json.load(cache_file)\nexcept Exception as exc:\ncommon.debug('Could not load from disk: {}'.format(exc))\n@@ -181,9 +181,9 @@ def add(bucket, identifier, content, ttl=None, to_disk=False):\ndef add_to_disk(bucket, identifier, cache_entry):\n\"\"\"Write a cache entry to disk\"\"\"\n# pylint: disable=broad-except\n- cache_filename = _cache_filename(bucket, identifier)\n+ cache_filename = _entry_filename(bucket, identifier)\ntry:\n- with open(cache_filename, 'wb') as cache_file:\n+ with open(cache_filename, 'w') as cache_file:\njson.dump(cache_entry, cache_file)\nexcept Exception as exc:\ncommon.error('Failed to write cache entry to {}: {}'\n@@ -198,9 +198,10 @@ def verify_ttl(bucket, identifier, cache_entry):\n_purge_entry(bucket, identifier)\nraise CacheMiss()\n-def _cache_filename(bucket, identifier):\n+def _entry_filename(bucket, identifier):\nreturn os.path.join(\ncommon.DATA_PATH,\n+ 'cache',\nbucket,\n'{filename}.cache'.format(filename=identifier))\n@@ -212,7 +213,7 @@ def _load_bucket(bucket):\ntry:\nreturn json.loads(WND.getProperty(_window_property(bucket)))\nexcept Exception:\n- common.debug('Failed to load cache bucket {}. Returning empty bucket.'\n+ common.debug('No instance of {} found. Creating new instance...'\n.format(bucket))\nreturn {}\n@@ -221,7 +222,8 @@ def _persist_bucket(bucket, contents):\ntry:\nWND.setProperty(_window_property(bucket), json.dumps(contents))\nexcept Exception as exc:\n- common.error('Failed to persist cache bucket: {exc}', exc)\n+ common.error('Failed to persist {} to window properties: {}'\n+ .format(bucket, exc))\ndef _clear_bucket(bucket):\nWND.clearProperty(_window_property(bucket))\n@@ -230,6 +232,6 @@ def _purge_entry(bucket, identifier):\n# Remove from in-memory cache\ndel get_bucket(bucket)[identifier]\n# Remove from disk cache if it exists\n- cache_filename = _cache_filename(bucket, identifier)\n+ cache_filename = _entry_filename(bucket, identifier)\nif os.path.exists(cache_filename):\nos.remove(cache_filename)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -113,14 +113,18 @@ class PersistentStorage(object):\nself.backing_file = os.path.join(DATA_PATH, self.storage_id + '.ndb')\nself._contents = {}\nself._dirty = True\n- log('Instantiated {}'.format(self.storage_id))\n+ debug('Instantiated {}'.format(self.storage_id))\n+\n+ def __del__(self):\n+ debug('Destroying storage instance {}'.format(self.storage_id))\n+ self.commit()\ndef __getitem__(self, key):\n- log('Getting {}'.format(key))\n+ debug('Getting {}'.format(key))\nreturn self.contents[key]\ndef __setitem__(self, key, value):\n- log('Setting {} to {}'.format(key, value))\n+ debug('Setting {} to {}'.format(key, value))\nself._contents[key] = value\nself.commit()\nself._dirty = True\n@@ -145,9 +149,9 @@ class PersistentStorage(object):\n\"\"\"\nWrite current contents to disk\n\"\"\"\n- with open(self.backing_file, 'w+') as file_handle:\n+ with open(self.backing_file, 'w') as file_handle:\njson.dump(self._contents, file_handle)\n- log('Committed changes to backing file')\n+ debug('Committed changes to backing file')\ndef clear(self):\n\"\"\"\n@@ -157,14 +161,14 @@ class PersistentStorage(object):\nself.commit()\ndef _load_from_disk(self):\n- log('Trying to load contents from disk')\n+ debug('Trying to load contents from disk')\ntry:\nwith open(self.backing_file, 'r') as file_handle:\n- self._contents = json.loads(file_handle.read())\n+ self._contents = json.load(file_handle)\nexcept IOError:\n- log('Backing file does not exist or is not accessible')\n+ error('Backing file does not exist or is not accessible')\nself._dirty = False\n- log('Loaded contents from backing file: {}'.format(self._contents))\n+ debug('Loaded contents from backing file: {}'.format(self._contents))\n__BLOCK_SIZE__ = 32\n__CRYPT_KEY__ = None\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -5,8 +5,7 @@ from __future__ import unicode_literals\nimport resources.lib.common as common\nimport resources.lib.cache as cache\nimport resources.lib.api.paths as paths\n-\n-from resources.lib.kodi.library import ItemNotFound\n+import resources.lib.kodi.library as library\ndef add_info(list_item, item, item_id, raw_data, tvshowid=None):\n\"\"\"Add infolabels to the list_item. The passed in list_item is modified\n@@ -40,12 +39,12 @@ def add_art(list_item, item, item_id):\nlist_item.setArt(art)\nreturn art\n-def add_info_for_playback(list_item, videoid, tvshowid):\n+def add_info_for_playback(list_item, videoid):\n\"\"\"Retrieve infolabels and art info and add them to the list_item\"\"\"\ntry:\n- return add_info_from_library(list_item, videoid, tvshowid)\n- except ItemNotFound:\n- return add_info_from_netflix(list_item, videoid, tvshowid)\n+ return add_info_from_library(list_item, videoid)\n+ except library.ItemNotFound:\n+ return add_info_from_netflix(list_item, videoid)\ndef parse_info(item, raw_data, tvshowid):\n\"\"\"Parse info from a path request response into Kodi infolabels\"\"\"\n@@ -143,7 +142,7 @@ def parse_art(item):\nart['fanart'] = fanart\nreturn art\n-def add_info_from_netflix(list_item, videoid, tvshowid):\n+def add_info_from_netflix(list_item, videoid):\n\"\"\"Apply infolabels with info from Netflix API\"\"\"\ntry:\ninfos = add_info(list_item, None, None, None)\n@@ -152,6 +151,11 @@ def add_info_from_netflix(list_item, videoid, tvshowid):\nexcept TypeError:\ncommon.info('Infolabels or art were not in cache, retrieving from API')\nimport resources.lib.api.shakti as api\n+ if isinstance(videoid, tuple):\n+ tvshowid = videoid[0]\n+ videoid = videoid[2]\n+ else:\n+ tvshowid = None\napi_data = (api.movie(videoid)\nif tvshowid is None\nelse api.episode(tvshowid, videoid))\n@@ -164,6 +168,16 @@ def add_info_from_netflix(list_item, videoid, tvshowid):\nitem_id=videoid)\nreturn infos, art\n-def add_info_from_library(list_item, videoid, tvshowid):\n+def add_info_from_library(list_item, videoid):\n\"\"\"Apply infolabels with info from Kodi library\"\"\"\n- pass\n+ details = library.find_item(videoid, include_props=True)\n+ art = details.pop('art', {})\n+ infos = {\n+ 'DBID': details.pop('id'),\n+ 'mediatype': details['type'],\n+ 'DBTYPE': details.pop('type')\n+ }\n+ infos.update(details)\n+ list_item.setInfo(infos)\n+ list_item.setArt(art)\n+ return infos, art\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/kodi/library.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Kodi library integration\"\"\"\n+from __future__ import unicode_literals\n+\n+import resources.lib.common as common\n+\n+FILE_PROPS = [\n+ 'title', 'genre', 'year', 'rating', 'duration', 'playcount', 'director',\n+ 'tagline', 'plot', 'plotoutline', 'originaltitle', 'writer', 'studio',\n+ 'mpaa', 'cast', 'country', 'runtime', 'set', 'showlink', 'season',\n+ 'episode', 'showtitle', 'file', 'resume', 'tvshowid', 'setid', 'tag',\n+ 'art', 'uniqueid']\n+\n+__LIBRARY__ = None\n+\n+class ItemNotFound(Exception):\n+ \"\"\"The requested item could not be found in the Kodi library\"\"\"\n+ pass\n+\n+def _library():\n+ # pylint: disable=global-statement\n+ global __LIBRARY__\n+ if not __LIBRARY__:\n+ __LIBRARY__ = common.PersistentStorage('library')\n+ return __LIBRARY__\n+\n+def find_item(videoid, include_props=False):\n+ \"\"\"Find an item in the Kodi library by its Netflix videoid and return\n+ Kodi DBID and mediatype\"\"\"\n+ try:\n+ filepath = (_library()[videoid[0]][videoid[1]][videoid[2]]['file']\n+ if isinstance(videoid, tuple)\n+ else _library()[videoid])\n+ params = {'file': filepath, 'media': 'video'}\n+ if include_props:\n+ params['properties'] = FILE_PROPS\n+ return common.json_rpc('Files.GetFileDetails', params)['filedetails']\n+ except:\n+ raise ItemNotFound(\n+ 'The video with id {} is not present in the Kodi library'\n+ .format(videoid))\n+\n+def is_in_library(videoid):\n+ \"\"\"Return True if the video is in the local Kodi library, else False\"\"\"\n+ try:\n+ find_item(videoid)\n+ except ItemNotFound:\n+ return False\n+ return True\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/player.py",
"new_path": "resources/lib/navigation/player.py",
"diff": "@@ -49,19 +49,22 @@ def play(pathitems):\ndef play_episode(tvshowid, seasonid, episodeid):\n\"\"\"Play an episode\"\"\"\n- common.info('Playing episode {}'.format(episodeid))\n- play_video(episodeid, api.episode_metadata(tvshowid, seasonid, episodeid),\n- tvshowid=tvshowid, signal_data={'tvshow_video_id': tvshowid})\n+ videoid = (tvshowid, seasonid, episodeid)\n+ common.info('Playing episode {}'.format(videoid))\n+ play_video(videoid, api.episode_metadata(*videoid),\n+ signal_data={'tvshow_video_id': tvshowid})\ndef play_movie(movieid):\n\"\"\"Play a movie\"\"\"\ncommon.info('Playing movie {}'.format(movieid))\nplay_video(movieid, api.metadata(movieid))\n-def play_video(videoid, metadata, tvshowid=None, signal_data=None):\n+def play_video(videoid, metadata, signal_data=None):\n\"\"\"Generically play a video\"\"\"\n- list_item = get_inputstream_listitem(videoid)\n- infos, art = infolabels.add_info_for_playback(list_item, videoid, tvshowid)\n+ list_item = get_inputstream_listitem(videoid[0]\n+ if isinstance(videoid, tuple)\n+ else videoid)\n+ infos, art = infolabels.add_info_for_playback(list_item, videoid)\nsignal_data = signal_data or {}\nsignal_data['infos'] = infos\nsignal_data['art'] = art\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Get infolabels from kodi library if video was exported |
105,989 | 23.10.2018 01:33:44 | -7,200 | f452c30dbd9b3f90181418cbdaa7afff8823a64d | Add rate on Netflix, my list operations, proper cache invalidation. Prepare library export. Improve infolabels | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "@@ -14,17 +14,13 @@ import xbmcplugin\nimport resources.lib.cache as cache\nimport resources.lib.common as common\n-import resources.lib.api.shakti as api\nimport resources.lib.kodi.ui as ui\n+import resources.lib.kodi.library as library\nimport resources.lib.navigation as nav\nimport resources.lib.navigation.directory as directory\nimport resources.lib.navigation.hub as hub\nimport resources.lib.navigation.player as player\n-\n-def open_settings(addon_id):\n- \"\"\"Open settings page of another addon\"\"\"\n- from xbmcaddon import Addon\n- Addon(addon_id).openSettings()\n+import resources.lib.navigation.actions as actions\ndef route(pathitems):\n\"\"\"Route to the appropriate handler\"\"\"\n@@ -37,13 +33,10 @@ def route(pathitems):\nhub.browse(*pass_on_params)\nelif root_handler == nav.MODE_PLAY:\nplayer.play(pathitems[1:])\n- elif root_handler == 'logout':\n- api.logout()\n- elif root_handler == 'opensettings':\n- try:\n- open_settings(pathitems[1])\n- except IndexError:\n- raise nav.InvalidPathError('Missing target addon id.')\n+ elif root_handler == nav.MODE_ACTION:\n+ actions.execute(*pass_on_params)\n+ elif root_handler == nav.MODE_LIBRARY:\n+ library.execute(*pass_on_params)\nelse:\nraise nav.InvalidPathError(\n'No root handler for path {}'.format('/'.join(pathitems)))\n@@ -64,3 +57,4 @@ if __name__ == '__main__':\nxbmcplugin.endOfDirectory(handle=common.PLUGIN_HANDLE, succeeded=False)\ncache.commit()\n+ library.save_library()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -353,13 +353,13 @@ msgid \"Save bookmarks for library items / mark as watched\"\nmsgstr \"\"\nmsgctxt \"#30084\"\n-msgid \"Advanced\"\n+msgid \"Cache item time-to-live (minutes)\"\nmsgstr \"\"\nmsgctxt \"#30085\"\n-msgid \"Cache item time-to-live (seconds)\"\n+msgid \"Cache item time-to-live for metadata (minutes)\"\nmsgstr \"\"\nmsgctxt \"#30086\"\n-msgid \"Cache item time-to-live for metadata (seconds)\"\n+msgid \"Invalidate entire cache on modification of My List\"\nmsgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -26,6 +26,11 @@ def logout():\ncache.invalidate_cache()\ncommon.make_call(NetflixSession.logout)\n+def login():\n+ \"\"\"Perform a login\"\"\"\n+ cache.invalidate_cache()\n+ common.make_call(NetflixSession.login)\n+\ndef profiles():\n\"\"\"Retrieve the list of available user profiles\"\"\"\nreturn common.make_call(NetflixSession.list_profiles)\n@@ -112,6 +117,51 @@ def movie(movie_id):\nbuild_paths(['videos', movie_id],\nEPISODES_PARTIAL_PATHS))\n+def rate(video_id, rating):\n+ \"\"\"Rate a video on Netflix\"\"\"\n+ common.debug('Rating {} as {}'.format(video_id, rating))\n+ # In opposition to Kodi, Netflix uses a rating from 0 to in 0.5 steps\n+ rating = min(10, max(0, rating)) / 2\n+ common.make_call(\n+ NetflixSession.post,\n+ {'component': 'set_video_rating',\n+ 'headers': {\n+ 'Content-Type': 'application/json',\n+ 'Accept': 'application/json, text/javascript, */*'},\n+ 'params': {\n+ 'titleid': video_id,\n+ 'rating': rating}})\n+\n+def add_to_list(video_id):\n+ \"\"\"Add a video to my list\"\"\"\n+ common.debug('Adding {} to my list'.format(video_id))\n+ _update_my_list(video_id, 'add')\n+\n+def remove_from_list(video_id):\n+ \"\"\"Remove a video from my list\"\"\"\n+ common.debug('Removing {} from my list'.format(video_id))\n+ _update_my_list(video_id, 'remove')\n+\n+def _update_my_list(video_id, operation):\n+ \"\"\"Call API to update my list with either add or remove action\"\"\"\n+ common.make_call(\n+ NetflixSession.post,\n+ {'component': 'update_my_list',\n+ 'headers': {\n+ 'Content-Type': 'application/json',\n+ 'Accept': 'application/json, text/javascript, */*'},\n+ 'data': {\n+ 'operation': operation,\n+ 'videoId': int(video_id)}})\n+ if common.ADDON.getSettingBool('invalidate_cache_on_mylist_modify'):\n+ cache.invalidate_cache()\n+ else:\n+ cache.invalidate_last_location()\n+ cache.invalidate_entry(cache.CACHE_VIDEO_LIST,\n+ list_id_for_type('queue'))\n+ cache.invalidate_entry(cache.CACHE_COMMON, 'queue')\n+ cache.invalidate_entry(cache.CACHE_COMMON, 'root_lists')\n+\ndef browse_genre(genre_id):\n\"\"\"Retrieve video lists for a genre\"\"\"\npass\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -6,7 +6,10 @@ from __future__ import unicode_literals\nimport os\nfrom time import time\nfrom functools import wraps\n-import json\n+try:\n+ import cPickle as pickle\n+except ImportError:\n+ import pickle\nimport xbmcgui\n@@ -21,16 +24,23 @@ CACHE_EPISODES = 'cache_episodes'\nCACHE_METADATA = 'cache_metadata'\nCACHE_INFOLABELS = 'cache_infolabels'\nCACHE_ARTINFO = 'cache_artinfo'\n+CACHE_LIBRARY = 'library'\nBUCKET_NAMES = [CACHE_COMMON, CACHE_VIDEO_LIST, CACHE_SEASONS,\nCACHE_EPISODES, CACHE_METADATA, CACHE_INFOLABELS,\n- CACHE_ARTINFO]\n+ CACHE_ARTINFO, CACHE_LIBRARY]\nBUCKETS = {}\n+TTL_INFINITE = 60*60*24*365*100\n+\ndef _init_disk_cache():\nfor bucket in BUCKET_NAMES:\n+ if bucket == CACHE_LIBRARY:\n+ # Library gets special location in DATA_PATH root because we\n+ # dont want users accidentally deleting it.\n+ continue\ntry:\n- os.mkdir(os.path.join(common.DATA_PATH, bucket))\n+ os.makedirs(os.path.join(common.DATA_PATH, 'cache', bucket))\nexcept OSError:\npass\n@@ -133,8 +143,36 @@ def invalidate_cache():\ndef invalidate_entry(bucket, identifier):\n\"\"\"Remove an item from a bucket\"\"\"\n+ try:\n_purge_entry(bucket, identifier)\ncommon.debug('Invalidated {} in {}'.format(identifier, bucket))\n+ except KeyError:\n+ common.debug('Nothing to invalidate, {} was not in {}'\n+ .format(identifier, bucket))\n+\n+def invalidate_last_location():\n+ import resources.lib.api.shakti as api\n+ try:\n+ last_path = common.get_last_location()[1].split('/')\n+ common.debug('Invalidating cache for last location {}'\n+ .format(last_path))\n+ if last_path[1] == 'video_list':\n+ if last_path[2] in common.KNOWN_LIST_TYPES:\n+ video_list_id = api.list_id_for_type(last_path[2])\n+ invalidate_entry(CACHE_VIDEO_LIST,\n+ video_list_id)\n+ invalidate_entry(CACHE_COMMON, last_path[2])\n+ else:\n+ invalidate_entry(CACHE_VIDEO_LIST, last_path[2])\n+ elif last_path[1] == 'show':\n+ if len(last_path) > 4:\n+ invalidate_entry(CACHE_EPISODES, last_path[4])\n+ else:\n+ invalidate_entry(CACHE_SEASONS, last_path[2])\n+ except IndexError as exc:\n+ common.error(\n+ 'Failed to invalidate cache entry for last location: {}'\n+ .format(exc))\ndef commit():\n\"\"\"Persist cache contents in window properties\"\"\"\n@@ -162,7 +200,7 @@ def get_from_disk(bucket, identifier):\n.format(cache_filename))\ntry:\nwith open(cache_filename, 'r') as cache_file:\n- cache_entry = json.load(cache_file)\n+ cache_entry = pickle.load(cache_file)\nexcept Exception as exc:\ncommon.debug('Could not load from disk: {}'.format(exc))\nraise CacheMiss()\n@@ -184,7 +222,7 @@ def add_to_disk(bucket, identifier, cache_entry):\ncache_filename = _entry_filename(bucket, identifier)\ntry:\nwith open(cache_filename, 'w') as cache_file:\n- json.dump(cache_entry, cache_file)\n+ pickle.dump(cache_entry, cache_file)\nexcept Exception as exc:\ncommon.error('Failed to write cache entry to {}: {}'\n.format(cache_filename, exc))\n@@ -199,11 +237,14 @@ def verify_ttl(bucket, identifier, cache_entry):\nraise CacheMiss()\ndef _entry_filename(bucket, identifier):\n- return os.path.join(\n- common.DATA_PATH,\n- 'cache',\n- bucket,\n- '{filename}.cache'.format(filename=identifier))\n+ if bucket == CACHE_LIBRARY:\n+ # We want a special handling for the library database, so users\n+ # dont accidentally delete it when deleting the cache\n+ file_loc = ['library.ndb']\n+ else:\n+ file_loc = [\n+ 'cache', bucket, '{filename}.cache'.format(filename=identifier)]\n+ return os.path.join(common.DATA_PATH, *file_loc)\ndef _window_property(bucket):\nreturn 'nfmemcache_{}'.format(bucket)\n@@ -211,7 +252,7 @@ def _window_property(bucket):\ndef _load_bucket(bucket):\n# pylint: disable=broad-except\ntry:\n- return json.loads(WND.getProperty(_window_property(bucket)))\n+ return pickle.loads(WND.getProperty(_window_property(bucket)))\nexcept Exception:\ncommon.debug('No instance of {} found. Creating new instance...'\n.format(bucket))\n@@ -220,7 +261,7 @@ def _load_bucket(bucket):\ndef _persist_bucket(bucket, contents):\n# pylint: disable=broad-except\ntry:\n- WND.setProperty(_window_property(bucket), json.dumps(contents))\n+ WND.setProperty(_window_property(bucket), pickle.dumps(contents))\nexcept Exception as exc:\ncommon.error('Failed to persist {} to window properties: {}'\n.format(bucket, exc))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -14,6 +14,7 @@ from urllib import urlencode\nimport xbmc\nimport xbmcaddon\n+import xbmcgui\nimport AddonSignals\nimport resources.lib.kodi.ui.newdialogs as dialogs\n@@ -82,7 +83,7 @@ def init_globals(argv):\nREQUEST_PARAMS = dict(parse_qsl(PARAM_STRING))\ntry:\n- os.path.mkdirs(DATA_PATH)\n+ os.mkdir(DATA_PATH)\nexcept OSError:\npass\n@@ -120,11 +121,9 @@ class PersistentStorage(object):\nself.commit()\ndef __getitem__(self, key):\n- debug('Getting {}'.format(key))\nreturn self.contents[key]\ndef __setitem__(self, key, value):\n- debug('Setting {} to {}'.format(key, value))\nself._contents[key] = value\nself.commit()\nself._dirty = True\n@@ -572,6 +571,8 @@ def select_unused_port():\ndef get_path(path, search_space, include_key=False):\n\"\"\"Retrieve a value from a nested dict by following the path.\nThrows KeyError if any key along the path does not exist\"\"\"\n+ if not isinstance(path, (tuple, list)):\n+ path = [path]\ncurrent_value = search_space[path[0]]\nif len(path) == 1:\nreturn (path[0], current_value) if include_key else current_value\n@@ -652,7 +653,6 @@ def make_call(func, data=None):\ndef addonsignals_return_call(func):\n\"\"\"Makes func return callable through AddonSignals and\nhandles catching, conversion and forwarding of exceptions\"\"\"\n- func.addonsignals_return_call = True\n@wraps(func)\ndef make_return_call(instance, data):\n\"\"\"Makes func return callable through AddonSignals and\n@@ -671,7 +671,7 @@ def addonsignals_return_call(func):\nresult = func(instance)\nexcept Exception as exc:\nerror('AddonSignals callback raised exception: {exc}', exc)\n- error(''.join(traceback.format_stack(sys.exc_info()[2])))\n+ error(traceback.format_exc())\nresult = {\n'error': exc.__class__.__name__,\n'message': exc.__unicode__()\n@@ -690,7 +690,7 @@ def reraise(exc, msg, new_exception_cls, stacktrace):\n\"\"\"Log an error message with original stacktrace and return\nas new exception type to be reraised\"\"\"\nerror('{msg}: {exc}'.format(msg=msg, exc=exc))\n- error(''.join(traceback.format_stack(stacktrace)))\n+ error(traceback.format_exc())\nreturn new_exception_cls(exc)\ndef build_directory_url(pathitems, params=None):\n@@ -703,6 +703,25 @@ def build_play_url(pathitems, params=None):\nimport resources.lib.navigation as nav\nreturn build_url(pathitems, params, nav.MODE_PLAY)\n+def build_action_url(pathitems, params=None):\n+ \"\"\"Build a plugin URL for directory mode\"\"\"\n+ import resources.lib.navigation as nav\n+ return build_url(pathitems, params, nav.MODE_ACTION)\n+\n+def build_library_url(action, videoid, mediatype):\n+ \"\"\"Build a plugin URL for library mode and a library action\"\"\"\n+ library_mode = 'library'\n+ if mediatype == 'show':\n+ return build_url([action, 'show', videoid], mode=library_mode)\n+ elif mediatype == 'season':\n+ return build_url([action, 'show', videoid[0], 'seasons', videoid[1]],\n+ mode=library_mode)\n+ elif mediatype == 'episode':\n+ return build_url([action, 'show', videoid[0], 'seasons', videoid[1],\n+ 'episodes', videoid[2]],\n+ mode=library_mode)\n+ return build_url([action, 'movie', videoid], mode=library_mode)\n+\ndef build_url(pathitems, params=None, mode=None):\n\"\"\"Build a plugin URL from pathitems and query parameters\"\"\"\nif mode:\n@@ -724,3 +743,20 @@ def get_local_string(string_id):\n\"\"\"Retrieve a localized string by its id\"\"\"\nsrc = xbmc if string_id < 30000 else ADDON\nreturn src.getLocalizedString(string_id)\n+\n+def remember_last_location():\n+ \"\"\"Write the last path and params to a window property for it\n+ to be accessible to the next call\"\"\"\n+ last_location = build_url(PATH.split('/'), params=REQUEST_PARAMS)\n+ xbmcgui.Window(10000).setProperty('nf_last_location', last_location)\n+ debug('Saved last location as {}'.format(last_location))\n+\n+def get_last_location():\n+ \"\"\"Retrievethe components (base_url, path, query_params) for the last\n+ location\"\"\"\n+ last_url = xbmcgui.Window(10000).getProperty('nf_last_location')\n+ parsed_url = urlparse(last_url)\n+ return ('{scheme}://{netloc}'.format(scheme=parsed_url[0],\n+ netloc=parsed_url[1]),\n+ parsed_url[2][1:], # Path\n+ dict(parse_qsl(parsed_url[4][1:]))) # Querystring\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -96,16 +96,24 @@ def get_quality_infos(item):\ndelivery = item.get('delivery')\nif delivery:\nif delivery.get('hasHD'):\n- quality_infos['video'] = {'width': '1920', 'height': '1080'}\n+ quality_infos['video'] = {'codec': 'h264', 'width': '1920',\n+ 'height': '1080'}\nelif delivery.get('hasUltraHD'):\n- quality_infos['video'] = {'width': '3840', 'height': '2160'}\n+ quality_infos['video'] = {'codec': 'h265', 'width': '3840',\n+ 'height': '2160'}\nelse:\n- quality_infos['video'] = {'width': '960', 'height': '540'}\n+ quality_infos['video'] = {'codec': 'h264', 'width': '960',\n+ 'height': '540'}\n# quality_infos = {'width': '1280', 'height': '720'}\nif delivery.get('has51Audio'):\nquality_infos['audio'] = {'channels': 6}\nelse:\nquality_infos['audio'] = {'channels': 2}\n+\n+ quality_infos['audio']['codec'] = (\n+ 'eac3'\n+ if common.ADDON.getSettingBool('enable_dolby_sound')\n+ else 'aac')\nreturn quality_infos\ndef parse_art(item):\n@@ -170,7 +178,7 @@ def add_info_from_netflix(list_item, videoid):\ndef add_info_from_library(list_item, videoid):\n\"\"\"Apply infolabels with info from Kodi library\"\"\"\n- details = library.find_item(videoid, include_props=True)\n+ details = library.get_item(videoid, include_props=True)\nart = details.pop('art', {})\ninfos = {\n'DBID': details.pop('id'),\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "from __future__ import unicode_literals\nimport resources.lib.common as common\n+import resources.lib.cache as cache\n+from resources.lib.navigation import InvalidPathError\nFILE_PROPS = [\n'title', 'genre', 'year', 'rating', 'duration', 'playcount', 'director',\n@@ -21,16 +23,22 @@ def _library():\n# pylint: disable=global-statement\nglobal __LIBRARY__\nif not __LIBRARY__:\n- __LIBRARY__ = common.PersistentStorage('library')\n+ try:\n+ __LIBRARY__ = cache.get(cache.CACHE_LIBRARY, 'library')\n+ except cache.CacheMiss:\n+ __LIBRARY__ = {}\nreturn __LIBRARY__\n-def find_item(videoid, include_props=False):\n+def save_library():\n+ \"\"\"Save the library to disk via cache\"\"\"\n+ cache.add(cache.CACHE_LIBRARY, 'library', __LIBRARY__,\n+ ttl=cache.TTL_INFINITE, to_disk=True)\n+\n+def get_item(videoid, include_props=False):\n\"\"\"Find an item in the Kodi library by its Netflix videoid and return\nKodi DBID and mediatype\"\"\"\ntry:\n- filepath = (_library()[videoid[0]][videoid[1]][videoid[2]]['file']\n- if isinstance(videoid, tuple)\n- else _library()[videoid])\n+ filepath = common.get_path(videoid, _library())['file']\nparams = {'file': filepath, 'media': 'video'}\nif include_props:\nparams['properties'] = FILE_PROPS\n@@ -42,8 +50,40 @@ def find_item(videoid, include_props=False):\ndef is_in_library(videoid):\n\"\"\"Return True if the video is in the local Kodi library, else False\"\"\"\n+ return common.get_path_safe(videoid, _library()) is not None\n+\n+def execute(pathitems, params):\n+ \"\"\"Execute an action as specified by the path\"\"\"\ntry:\n- find_item(videoid)\n- except ItemNotFound:\n- return False\n- return True\n+ executor = ActionExecutor(params).__getattribute__(pathitems[0])\n+ except (AttributeError, IndexError):\n+ raise InvalidPathError('Unknown action {}'.format('/'.join(pathitems)))\n+\n+ common.debug('Invoking action executor {}'.format(executor.__name__))\n+\n+ if len(pathitems) > 1:\n+ executor((pathitems[1:]))\n+ else:\n+ executor()\n+\n+class ActionExecutor(object):\n+ \"\"\"Executes actions\"\"\"\n+ # pylint: disable=no-self-use\n+ def __init__(self, params):\n+ common.debug('Initializing action executor: {}'.format(params))\n+ self.params = params\n+\n+ def export(self, pathitems):\n+ \"\"\"Export an item to the Kodi library\"\"\"\n+ # TODO: Implement library export\n+ pass\n+\n+ def remove(self, pathitems):\n+ \"\"\"Remove an item from the Kodi library\"\"\"\n+ # TODO: Implement library removal\n+ pass\n+\n+ def update(self, pathitems):\n+ \"\"\"Update an item in the Kodi library\"\"\"\n+ # TODO: Implement library updates\n+ pass\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -9,6 +9,7 @@ import xbmcgui\nimport xbmcplugin\nimport resources.lib.common as common\n+import resources.lib.kodi.library as library\nfrom .infolabels import add_info, add_art\n@@ -28,6 +29,35 @@ CONTENT_SHOW = 'tvshows'\nCONTENT_SEASON = 'seasons'\nCONTENT_EPISODE = 'episodes'\n+RUN_PLUGIN = 'XBMC.RunPlugin({})'\n+\n+CONTEXT_MENU_ACTIONS = {\n+ 'export': {\n+ 'label': common.get_local_string(30018),\n+ 'url': (lambda videoid, mediatype:\n+ common.build_library_url('export', videoid, mediatype))},\n+ 'remove': {\n+ 'label': common.get_local_string(30030),\n+ 'url': (lambda videoid, mediatype:\n+ common.build_library_url('remove', videoid, mediatype))},\n+ 'update': {\n+ 'label': common.get_local_string(30030),\n+ 'url': (lambda videoid, mediatype:\n+ common.build_library_url('update', videoid, mediatype))},\n+ 'rate': {\n+ 'label': common.get_local_string(30019),\n+ 'url': (lambda videoid:\n+ common.build_action_url(['rate', videoid]))},\n+ 'add_to_list': {\n+ 'label': common.get_local_string(30021),\n+ 'url': (lambda videoid:\n+ common.build_action_url(['my_list', 'add', videoid]))},\n+ 'remove_from_list': {\n+ 'label': common.get_local_string(30020),\n+ 'url': (lambda videoid:\n+ common.build_action_url(['my_list', 'remove', videoid]))},\n+}\n+\ndef create_list_item(label, icon=None, fanart=None):\n\"\"\"Create a rudimentary list item with icon and fanart\"\"\"\nlist_item = xbmcgui.ListItem(label=label,\n@@ -64,6 +94,7 @@ def custom_viewmode(viewtype):\ndef decorate_viewmode(func):\n@wraps(func)\ndef set_custom_viewmode(*args, **kwargs):\n+ # pylint: disable=no-member\nviewtype_override = func(*args, **kwargs)\nview = (viewtype_override\nif viewtype_override in VIEWTYPES\n@@ -103,10 +134,9 @@ def build_profiles_listing(profiles):\nenc_profile_name = profile_name.encode('utf-8')\nlist_item = create_list_item(\nlabel=unescaped_profile_name, icon=profile.get('avatar'))\n- autologin_url = common.build_url(\n+ autologin_url = common.build_action_url(\npathitems=['save_autologin', profile_guid],\n- params={'autologin_user': enc_profile_name},\n- mode='action')\n+ params={'autologin_user': enc_profile_name})\nlist_item.addContextMenuItems(\nitems=[(common.get_local_string(30053),\n'RunPlugin({})'.format(autologin_url))])\n@@ -173,13 +203,16 @@ def build_video_listing(video_list):\n.get('level', 1001)) >= 1000\nis_movie = video['summary']['type'] == 'movie'\nif is_movie:\n- url = common.build_url(\n- pathitems=['play', video_id],\n+ url = common.build_play_url(\n+ pathitems=['movie', video_id],\nparams={'pin': needs_pin})\nelse:\nurl = common.build_directory_url(\npathitems=['show', video_id],\nparams={'pin': needs_pin})\n+ list_item.addContextMenuItems(\n+ _generate_context_menu_items(video_id, video['summary']['type'],\n+ video))\ndirectory_items.append(\n(url,\nlist_item,\n@@ -206,6 +239,8 @@ def build_season_listing(tvshowid, season_list):\nlist_item = create_list_item(season['summary']['name'])\nadd_info(list_item, season, season_id, season_list.data, tvshowid)\nadd_art(list_item, season_list.tvshow, tvshowid)\n+ list_item.addContextMenuItems(\n+ _generate_context_menu_items(season_id, 'season', season))\ndirectory_items.append(\n(common.build_directory_url(\npathitems=['show', tvshowid, 'seasons', season_id]),\n@@ -230,6 +265,8 @@ def build_episode_listing(tvshowid, seasonid, episode_list):\nlist_item = create_list_item(episode['title'])\nadd_info(list_item, episode, episode_id, episode_list.data, tvshowid)\nadd_art(list_item, episode, episode_id)\n+ list_item.addContextMenuItems(\n+ _generate_context_menu_items(episode_id, 'episode', episode))\ndirectory_items.append(\n(common.build_url(\npathitems=['play', 'show', tvshowid, 'seasons', seasonid,\n@@ -245,3 +282,38 @@ def build_episode_listing(tvshowid, seasonid, episode_list):\nxbmcplugin.SORT_METHOD_GENRE,\nxbmcplugin.SORT_METHOD_LASTPLAYED],\ncontent_type=CONTENT_EPISODE)\n+\n+def _generate_context_menu_items(video_id, mediatype, item):\n+ items = []\n+ if library.is_in_library(video_id):\n+ items.append(\n+ (CONTEXT_MENU_ACTIONS['remove']['label'],\n+ RUN_PLUGIN.format(\n+ CONTEXT_MENU_ACTIONS['remove']['url'](video_id, mediatype))))\n+ if mediatype in ['show', 'season']:\n+ items.append(\n+ (CONTEXT_MENU_ACTIONS['update']['label'],\n+ RUN_PLUGIN.format(\n+ CONTEXT_MENU_ACTIONS['update']['url'](video_id,\n+ mediatype))))\n+ else:\n+ items.append(\n+ (CONTEXT_MENU_ACTIONS['export']['label'],\n+ RUN_PLUGIN.format(\n+ CONTEXT_MENU_ACTIONS['export']['url'](video_id, mediatype))))\n+\n+ if mediatype != 'season':\n+ items.append(\n+ (CONTEXT_MENU_ACTIONS['rate']['label'],\n+ RUN_PLUGIN.format(\n+ CONTEXT_MENU_ACTIONS['rate']['url'](video_id))))\n+\n+ if mediatype in ['movie', 'show']:\n+ list_action = ('remove_from_list'\n+ if item['queue']['inQueue']\n+ else 'add_to_list')\n+ items.append(\n+ (CONTEXT_MENU_ACTIONS[list_action]['label'],\n+ RUN_PLUGIN.format(\n+ CONTEXT_MENU_ACTIONS[list_action]['url'](video_id))))\n+ return items\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/__init__.py",
"new_path": "resources/lib/navigation/__init__.py",
"diff": "@@ -6,6 +6,7 @@ MODE_DIRECTORY = 'directory'\nMODE_HUB = 'hub'\nMODE_ACTION = 'action'\nMODE_PLAY = 'play'\n+MODE_LIBRARY = 'library'\nclass InvalidPathError(Exception):\n\"\"\"The requested path is invalid and could not be routed\"\"\"\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/navigation/actions.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Navigation handler for actions\"\"\"\n+from __future__ import unicode_literals\n+\n+import xbmc\n+from xbmcaddon import Addon\n+\n+import resources.lib.common as common\n+import resources.lib.cache as cache\n+import resources.lib.api.shakti as api\n+from resources.lib.navigation import InvalidPathError\n+\n+def execute(pathitems, params):\n+ \"\"\"Execute an action as specified by the path\"\"\"\n+ try:\n+ executor = ActionExecutor(params).__getattribute__(pathitems[0])\n+ except (AttributeError, IndexError):\n+ raise InvalidPathError('Unknown action {}'.format('/'.join(pathitems)))\n+\n+ common.debug('Invoking action executor {}'.format(executor.__name__))\n+\n+ if len(pathitems) > 1:\n+ executor((pathitems[1:]))\n+ else:\n+ executor()\n+\n+class ActionExecutor(object):\n+ \"\"\"Executes actions\"\"\"\n+ # pylint: disable=no-self-use\n+ def __init__(self, params):\n+ common.debug('Initializing action executor: {}'.format(params))\n+ self.params = params\n+\n+ def logout(self):\n+ \"\"\"Perform account logout\"\"\"\n+ api.logout()\n+\n+ def opensettings(self, pathitems):\n+ \"\"\"Open settings of another addon\"\"\"\n+ try:\n+ Addon(pathitems[1]).openSettings()\n+ except IndexError:\n+ raise InvalidPathError('Missing target addon id')\n+\n+ def save_autologin(self, pathitems):\n+ \"\"\"Save autologin data\"\"\"\n+ try:\n+ common.ADDON.setSetting('autologin_user',\n+ self.params['autologin_user'])\n+ common.ADDON.setSetting('autologin_id', pathitems[0])\n+ common.ADDON.setSetting('autologin_enable', 'true')\n+ except (KeyError, IndexError):\n+ common.error('Cannot save autologin - invalid params')\n+ cache.invalidate_cache()\n+ xbmc.executebuiltin('Container.Refresh')\n+\n+ def switch_account(self):\n+ \"\"\"Logo out of the curent account and login into another one\"\"\"\n+ api.logout()\n+ api.login()\n+\n+ def toggle_adult_pin(self):\n+ \"\"\"Toggle adult PIN verification\"\"\"\n+ # pylint: disable=no-member\n+ common.ADDON.setSettingBool(\n+ not common.ADDON.getSettingBool('adultpin_enable'))\n+\n+ def rate(self, pathitems):\n+ \"\"\"Rate an item on Netflix. Ask for a rating if there is none supplied\n+ in the path.\"\"\"\n+ if len(pathitems) < 2:\n+ rating = ui.ask_for_rating()\n+ else:\n+ rating = pathitems[1]\n+ api.rate(pathitems[0], rating)\n+\n+ def my_list(self, pathitems):\n+ \"\"\"Add or remove an item from my list\"\"\"\n+ if len(pathitems) < 2:\n+ raise InvalidPathError('Missing video id')\n+\n+ if pathitems[0] == 'add':\n+ api.add_to_list(pathitems[1])\n+ elif pathitems[0] == 'remove':\n+ api.remove_from_list(pathitems[1])\n+ else:\n+ raise InvalidPathError('Unknown my-list action: {}'\n+ .format(pathitems[0]))\n+ xbmc.executebuiltin('Container.Refresh')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/directory.py",
"new_path": "resources/lib/navigation/directory.py",
"diff": "@@ -7,8 +7,6 @@ import resources.lib.api.shakti as api\nimport resources.lib.kodi.listings as listings\nfrom resources.lib.navigation import InvalidPathError\n-BASE_PATH_ITEM = 'directory'\n-\ndef build(pathitems, params):\n\"\"\"Build a directory listing for the given path\"\"\"\ntry:\n@@ -24,11 +22,16 @@ def build(pathitems, params):\nelse:\nbuilder()\n+ # Remember last location to be able to invalidate it in cache on\n+ # certain actions\n+ common.remember_last_location()\n+\nclass DirectoryBuilder(object):\n\"\"\"Builds directory listings\"\"\"\n# pylint: disable=no-self-use\ndef __init__(self, params):\ncommon.debug('Initializing directory builder: {}'.format(params))\n+ self.params = params\nprofile_id = params.get('profile_id')\nif profile_id:\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/hub.py",
"new_path": "resources/lib/navigation/hub.py",
"diff": "@@ -4,8 +4,6 @@ from __future__ import unicode_literals\nimport resources.lib.common as common\n-BASE_PATH_ITEM = 'hub'\n-\ndef browse(pathitems, params):\n\"\"\"Browse a hub page for the given path\"\"\"\npass\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/player.py",
"new_path": "resources/lib/navigation/player.py",
"diff": "@@ -51,7 +51,7 @@ def play_episode(tvshowid, seasonid, episodeid):\n\"\"\"Play an episode\"\"\"\nvideoid = (tvshowid, seasonid, episodeid)\ncommon.info('Playing episode {}'.format(videoid))\n- play_video(videoid, api.episode_metadata(*videoid),\n+ play_video(episodeid, api.episode_metadata(*videoid),\nsignal_data={'tvshow_video_id': tvshowid})\ndef play_movie(movieid):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -102,6 +102,7 @@ class NetflixSession(object):\ndef _register_slots(self):\nself.slots = [\n+ self.login,\nself.logout,\nself.list_profiles,\nself.activate_profile,\n@@ -160,6 +161,18 @@ class NetflixSession(object):\nreturn False\nreturn True\n+ def _update_esn(self):\n+ \"\"\"Return True if the esn has changed on Session initialization\"\"\"\n+ if common.set_esn(self.session_data['esn']):\n+ common.send_signal(\n+ signal=common.Signals.ESN_CHANGED,\n+ data=self.session_data['esn'])\n+\n+ @common.addonsignals_return_call\n+ def login(self):\n+ \"\"\"AddonSignals interface for login function\"\"\"\n+ self._login()\n+\ndef _login(self):\n\"\"\"Perform account login\"\"\"\ntry:\n@@ -168,7 +181,7 @@ class NetflixSession(object):\nself._get('profiles'))['authURL']\ncommon.debug('Logging in...')\nlogin_response = self._post(\n- 'login', _login_payload(self.credentials, auth_url))\n+ 'login', data=_login_payload(self.credentials, auth_url))\ncommon.debug('Extracting session data...')\nsession_data = website.extract_session_data(login_response)\nexcept Exception as exc:\n@@ -181,13 +194,6 @@ class NetflixSession(object):\ncookies.save(self.account_hash, self.session.cookies)\nself._update_esn()\n- def _update_esn(self):\n- \"\"\"Return True if the esn has changed on Session initialization\"\"\"\n- if common.set_esn(self.session_data['esn']):\n- common.send_signal(\n- signal=common.Signals.ESN_CHANGED,\n- data=self.session_data['esn'])\n-\[email protected]_return_call\ndef logout(self):\n\"\"\"Logout of the current account and reset the session\"\"\"\n@@ -248,9 +254,11 @@ class NetflixSession(object):\[email protected]_return_call\n@needs_login\n- def post(self, component, data, **kwargs):\n+ def post(self, component, **kwargs):\n\"\"\"Execute a POST request to the designated component's URL.\"\"\"\n- return self._post(component, data, **kwargs)\n+ result = self._post(component, **kwargs)\n+ common.debug(result)\n+ return result\ndef _get(self, component, **kwargs):\nreturn self._request(\n@@ -258,11 +266,10 @@ class NetflixSession(object):\ncomponent=component,\n**kwargs)\n- def _post(self, component, data, **kwargs):\n+ def _post(self, component, **kwargs):\nreturn self._request(\nmethod=self.session.post,\ncomponent=component,\n- data=data,\n**kwargs)\ndef _request(self, method, component, **kwargs):\n@@ -272,12 +279,18 @@ class NetflixSession(object):\ncommon.debug(\n'Executing {verb} request to {url}'.format(\nverb='GET' if method == self.session.get else 'POST', url=url))\n+\n+ data = kwargs.get('data', {})\n+ if component in ['set_video_rating', 'update_my_list']:\n+ data['authURL'] = self.auth_url\n+ data = json.dumps(data)\n+\nresponse = method(\nurl=url,\nverify=self.verify_ssl,\nheaders=kwargs.get('headers'),\nparams=kwargs.get('params'),\n- data=kwargs.get('data'))\n+ data=data)\ncommon.debug(\n'Request returned statuscode {}'.format(response.status_code))\nresponse.raise_for_status()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/settings.xml",
"new_path": "resources/settings.xml",
"diff": "<category label=\"30014\">\n<setting id=\"email\" type=\"text\" visible=\"false\" default=\"\"/>\n<setting id=\"password\" type=\"text\" visible=\"false\" default=\"\"/>\n- <setting id=\"switch_account\" type=\"action\" label=\"30059c\" action=\"RunPlugin(plugin://plugin.video.netflix/?action=switch_account)\" option=\"close\"/>\n- <setting id=\"logout\" type=\"action\" label=\"30017\" action=\"RunPlugin(plugin://plugin.video.netflix/?action=logout)\" option=\"close\"/>\n- <setting id=\"adultpin_enable\" type=\"action\" label=\"30062\" default=\"False\" action=\"RunPlugin(plugin://plugin.video.netflix/?action=toggle_adult_pin)\"/>\n+ <setting id=\"switch_account\" type=\"action\" label=\"30059c\" action=\"RunPlugin(plugin://plugin.video.netflix/action/switch_account)\" option=\"close\"/>\n+ <setting id=\"logout\" type=\"action\" label=\"30017\" action=\"RunPlugin(plugin://plugin.video.netflix/action/logout)\" option=\"close\"/>\n+ <setting id=\"adultpin_enable\" type=\"action\" label=\"30062\" default=\"False\" action=\"RunPlugin(plugin://plugin.video.netflix/action/toggle_adult_pin)\"/>\n<setting type=\"sep\"/>\n- <setting id=\"is_settings\" type=\"action\" label=\"30035\" action=\"RunPlugin(plugin://plugin.video.netflix/?mode=openSettings&url=is)\" enable=\"System.HasAddon(inputstream.adaptive)\" option=\"close\"/>\n+ <setting id=\"is_settings\" type=\"action\" label=\"30035\" action=\"RunPlugin(plugin://plugin.video.netflix/action/opensettings/inputstream.adaptive)\" enable=\"System.HasAddon(inputstream.adaptive)\" option=\"close\"/>\n</category>\n<category label=\"30025\">\n<setting id=\"enablelibraryfolder\" type=\"bool\" label=\"30026\" default=\"false\"/>\n<setting id=\"ssl_verification\" type=\"bool\" label=\"30024\" default=\"true\"/>\n<setting id=\"enable_tracking\" type=\"bool\" label=\"30032\" default=\"true\"/>\n<setting id=\"esn\" type=\"text\" label=\"30034\" value=\"\" default=\"\"/>\n+ <setting id=\"cache_ttl\" type=\"slider\" option=\"int\" range=\"0,10,525600\" label=\"30084\" default=\"10\"/>\n+ <setting id=\"cache_metadata_ttl\" type=\"slider\" option=\"int\" range=\"0,60,525600\" label=\"30085\" default=\"43200\"/>\n+ <setting id=\"invalidate_cache_on_mylist_modify\" type=\"bool\" label=\"30086\" default=\"false\"/>\n<setting id=\"hidden_esn\" visible=\"false\" value=\"\" />\n<setting id=\"tracking_id\" value=\"\" visible=\"false\"/>\n<setting id=\"locale_id\" visible=\"false\" value=\"en-US\" />\n<setting id=\"autologin_id\" type=\"text\" label=\"30056\" default=\"\" enable=\"false\" visible=\"eq(-2,true)\" subsetting=\"true\"/>\n<setting id=\"info\" type=\"text\" label=\"30057\" default=\"\" enable=\"false\" visible=\"eq(-3,true)\"/>\n</category>\n- <category label=\"30053\">\n- <setting id=\"cache_ttl\" type=\"slider\" option=\"int\" range=\"0,10,525600\" label=\"30085\" default=\"10\"/>\n- <setting id=\"cache_metadata_ttl\" type=\"slider\" option=\"int\" range=\"0,60,525600\" label=\"30086\" default=\"43200\"/>\n- </category>\n</settings>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add rate on Netflix, my list operations, proper cache invalidation. Prepare library export. Improve infolabels |
105,989 | 24.10.2018 23:57:46 | -7,200 | 9c4c5711c35487248eee83032569168a5e75afc6 | Refactor UI dialogs | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -17,8 +17,6 @@ import xbmcaddon\nimport xbmcgui\nimport AddonSignals\n-import resources.lib.kodi.ui.newdialogs as dialogs\n-\n# Global vars are initialized in init_globals\n# Commonly used addon attributes from Kodi\nADDON = None\n@@ -427,19 +425,6 @@ def set_credentials(email, password):\nADDON.setSetting('email', encrypt_credential(email))\nADDON.setSetting('password', encrypt_credential(password))\n-def ask_credentials():\n- \"\"\"\n- Show some dialogs and ask the user for account credentials\n- \"\"\"\n- email = dialogs.show_email_dialog()\n- password = dialogs.show_password_dialog()\n- verify_credentials(email, password)\n- set_credentials(email, password)\n- return {\n- 'email': email,\n- 'password': password\n- }\n-\ndef verify_credentials(email, password):\n\"\"\"Verify credentials for plausibility\"\"\"\nif not email or not password:\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -162,6 +162,24 @@ def build_main_menu_listing(lolomo):\nsort_methods=[xbmcplugin.SORT_METHOD_UNSORTED],\ncontent_type=CONTENT_FOLDER)\n+def build_lolomo_listing(lolomo, contexts=None):\n+ \"\"\"Build a listing of vieo lists (LoLoMo). Only show those\n+ lists with a context specified context if contexts is set.\"\"\"\n+ directory_items = []\n+ lists = (lolomo.lists_by_context(contexts)\n+ if contexts\n+ else lolomo.lists.iteritem())\n+ for video_list_id, video_list in lists:\n+ directory_items.append(\n+ (common.build_url(\n+ ['video_list', video_list_id], mode=nav.MODE_DIRECTORY),\n+ create_list_item(video_list['displayName']),\n+ True))\n+ finalize_directory(\n+ items=directory_items,\n+ sort_methods=[xbmcplugin.SORT_METHOD_UNSORTED],\n+ content_type=CONTENT_FOLDER)\n+\n@custom_viewmode(VIEW_SHOW)\ndef build_video_listing(video_list):\n\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/ui/Dialogs.py",
"new_path": "resources/lib/kodi/ui/Dialogs.py",
"diff": "# -*- coding: utf-8 -*-\n-# Author: asciidisco\n-# Module: Dialogs\n-# Created on: 16.10.2017\n-# License: MIT https://goo.gl/5bMj3H\n-\n-\"\"\"Kodi UI Dialogs\"\"\"\n+\"\"\"Various simple dialogs\"\"\"\n+# pylint: disable=wildcard-import\nfrom __future__ import unicode_literals\n+import xbmc\nimport xbmcgui\n+import resources.lib.common as common\n-class Dialogs(object):\n- \"\"\"Kodi UI Dialogs\"\"\"\n-\n- def __init__(self, get_local_string, custom_export_name, notify_time=5000):\n- \"\"\"\n- Sets the i18n string loader function and exprt name properties\n-\n- :param original_title: Original title of the show\n- :type original_title: str\n- \"\"\"\n- self.notify_time = notify_time\n- self.get_local_string = get_local_string\n- self.custom_export_name = custom_export_name\n-\n- def show_rating_dialog(self):\n- \"\"\"\n- Asks the user for a movie rating\n-\n- :returns: int - Movie rating between 0 & 10\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- heading = self.get_local_string(string_id=30019)\n- heading += ' '\n- heading += self.get_local_string(string_id=30022)\n- return dlg.numeric(heading=heading, type=0)\n-\n- def show_adult_pin_dialog(self):\n- \"\"\"\n- Asks the user for the adult pin\n+def show_notification(msg, title='Netflix'):\n+ \"\"\"Show a notification\"\"\"\n+ xbmc.executebuiltin('Notification({}, {}, 3000, {})'\n+ .format(title, msg, common.ICON)\n+ .encode('utf-8'))\n- :returns: int - 4 digit adult pin needed for adult movies\n+def ask_credentials():\n\"\"\"\n- dlg = xbmcgui.Dialog()\n- dialog = dlg.input(\n- heading=self.get_local_string(string_id=30002),\n- type=xbmcgui.INPUT_NUMERIC)\n- return dialog\n-\n- def show_search_term_dialog(self):\n- \"\"\"\n- Asks the user for a term to query the netflix search for\n-\n- :returns: str - Term to search for\n+ Show some dialogs and ask the user for account credentials\n\"\"\"\n- dlg = xbmcgui.Dialog()\n- term = dlg.input(\n- heading=self.get_local_string(string_id=30003),\n- type=xbmcgui.INPUT_ALPHANUM)\n- if not term:\n- term = None\n- return term\n-\n- def show_add_library_title_dialog(self, original_title):\n- \"\"\"\n- Asks the user for an alternative title for the show/movie that\n- gets exported to the local library\n-\n- :param original_title: Original title of the show\n- :type original_title: str\n-\n- :returns: str - Title to persist\n- \"\"\"\n- if self.custom_export_name == 'true':\n+ email = xbmcgui.Dialog().input(\n+ heading=common.get_local_string(30005),\n+ type=xbmcgui.INPUT_ALPHANUM) or None\n+ password = xbmcgui.Dialog().input(\n+ heading=common.get_local_string(30004),\n+ type=xbmcgui.INPUT_ALPHANUM,\n+ option=xbmcgui.ALPHANUM_HIDE_INPUT) or None\n+ common.verify_credentials(email, password)\n+ common.set_credentials(email, password)\n+ return {\n+ 'email': email,\n+ 'password': password\n+ }\n+\n+def ask_for_rating():\n+ \"\"\"Ask the user for a rating\"\"\"\n+ heading = '{} {}'.format(common.get_local_string(30019),\n+ common.get_local_string(30022))\n+ try:\n+ return int(xbmcgui.Dialog().numeric(heading=heading, type=0,\n+ defaultt=''))\n+ except ValueError:\n+ return None\n+\n+def ask_for_pin():\n+ \"\"\"Ask the user for the adult pin\"\"\"\n+ try:\n+ return int(xbmcgui.Dialog()\n+ .numeric(heading=common.get_local_string(30002),\n+ type=0,\n+ defaultt=''))\n+ except ValueError:\n+ return None\n+\n+def ask_for_search_term():\n+ \"\"\"Ask the user for a search term\"\"\"\n+ return xbmcgui.Dialog().input(\n+ heading=common.get_local_string(30003),\n+ type=xbmcgui.INPUT_ALPHANUM) or None\n+\n+def ask_for_custom_title(original_title):\n+ \"\"\"Ask the user for a custom title (for library export)\"\"\"\n+ if common.ADDON.getSettingBool('customexportname'):\nreturn original_title\n- dlg = xbmcgui.Dialog()\n- custom_title = dlg.input(\n- heading=self.get_local_string(string_id=30031),\n- defaultt=original_title,\n+ return xbmcgui.Dialog().input(\n+ heading=common.get_local_string(30031),\ntype=xbmcgui.INPUT_ALPHANUM) or original_title\n- return original_title or custom_title\n-\n- def show_password_dialog(self):\n- \"\"\"\n- Asks the user for its Netflix password\n-\n- :returns: str - Netflix password\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- dialog = dlg.input(\n- heading=self.get_local_string(string_id=30004),\n- type=xbmcgui.INPUT_ALPHANUM,\n- option=xbmcgui.ALPHANUM_HIDE_INPUT)\n- return dialog\n-\n- def show_email_dialog(self):\n- \"\"\"\n- Asks the user for its Netflix account email\n-\n- :returns: str - Netflix account email\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- dialog = dlg.input(\n- heading=self.get_local_string(string_id=30005),\n- type=xbmcgui.INPUT_ALPHANUM)\n- return dialog\n-\n- def show_login_failed_notify(self):\n- \"\"\"\n- Shows notification that the login failed\n-\n- :returns: bool - Dialog shown\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- dialog = dlg.notification(\n- heading=self.get_local_string(string_id=30008),\n- message=self.get_local_string(string_id=30009),\n- icon=xbmcgui.NOTIFICATION_ERROR,\n- time=self.notify_time)\n- return dialog\n-\n- def show_request_error_notify(self):\n- \"\"\"\n- Shows notification that a request error occured\n- :returns: bool - Dialog shown\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- dialog = dlg.notification(\n- heading=self.get_local_string(string_id=30051),\n- message=self.get_local_string(string_id=30052),\n- icon=xbmcgui.NOTIFICATION_ERROR,\n- time=self.notify_time)\n- return dialog\n-\n- def show_invalid_pin_notify(self):\n- \"\"\"\n- Shows notification that a wrong adult pin was given\n-\n- :returns: bool - Dialog shown\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- dialog = dlg.notification(\n- heading=self.get_local_string(string_id=30006),\n- message=self.get_local_string(string_id=30007),\n- icon=xbmcgui.NOTIFICATION_ERROR,\n- time=self.notify_time)\n- return dialog\n-\n- def show_no_search_results_notify(self):\n- \"\"\"\n- Shows notification that no search results could be found\n-\n- :return: bool - Dialog shown\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- dialog = dlg.notification(\n- heading=self.get_local_string(string_id=30011),\n- message=self.get_local_string(string_id=30013),\n- icon=xbmcgui.NOTIFICATION_INFO,\n- time=self.notify_time)\n- return dialog\n-\n- def show_no_seasons_notify(self):\n- \"\"\"\n- Shows notification that no seasons be found\n-\n- :returns: bool - Dialog shown\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- dialog = dlg.notification(\n- heading=self.get_local_string(string_id=30010),\n- message=self.get_local_string(string_id=30012),\n- icon=xbmcgui.NOTIFICATION_INFO,\n- time=self.notify_time)\n- return dialog\n-\n- def show_db_updated_notify(self):\n- \"\"\"\n- Shows notification that local db was updated\n-\n- :returns: bool - Dialog shown\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- dialog = dlg.notification(\n- heading=self.get_local_string(string_id=15101),\n- message=self.get_local_string(string_id=30050),\n- icon=xbmcgui.NOTIFICATION_INFO,\n- time=self.notify_time)\n- return dialog\n-\n- def show_no_metadata_notify(self):\n- \"\"\"\n- Shows notification that no metadata is available\n-\n- :returns: bool - Dialog shown\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- dialog = dlg.notification(\n- heading=self.get_local_string(string_id=14116),\n- message=self.get_local_string(string_id=195),\n- icon=xbmcgui.NOTIFICATION_INFO,\n- time=self.notify_time)\n- return dialog\n-\n- def show_episodes_added_notify(self, showtitle, episodes, icon):\n- \"\"\"\n- Shows notification that new episodes were added to the library\n-\n- :returns: bool - Dialog shown\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- dialog = dlg.notification(\n- heading=showtitle,\n- message='{} {}'.format(episodes,\n- self.get_local_string(string_id=30063)),\n- icon=icon,\n- time=self.notify_time)\n- return dialog\n-\n- def show_autologin_enabled_notify(self):\n- \"\"\"\n- Shows notification that auto login is enabled\n-\n- :returns: bool - Dialog shown\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- dialog = dlg.notification(\n- heading=self.get_local_string(string_id=14116),\n- message=self.get_local_string(string_id=30058),\n- icon=xbmcgui.NOTIFICATION_INFO,\n- time=self.notify_time)\n- return dialog\n-\n- def show_finally_remove_modal(self, title, year='0000'):\n- \"\"\"\n- Ask if user wants to remove the item from the local library\n-\n- :param title: Title of the show\n- :type title: str\n- :param year: Year of the show\n- :type year: str\n-\n- :returns: bool - Answer yes/no\n- \"\"\"\n- dlg = xbmcgui.Dialog()\n- if year == '0000':\n- dialog = dlg.yesno(\n- heading=self.get_local_string(string_id=30047),\n- line1=title)\n- return dialog\n- dialog = dlg.yesno(\n- heading=self.get_local_string(string_id=30047),\n- line1=title + ' (' + str(year) + ')')\n- return dialog\n+def ask_for_removal_confirmation(title, year=None):\n+ \"\"\"Ask the user to finally remove title from the Kodi library\"\"\"\n+ return xbmcgui.Dialog().yesno(\n+ heading=common.get_local_string(30047),\n+ line1=title + (' ({})'.format(year) if year else ''))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/ui/__init__.py",
"new_path": "resources/lib/kodi/ui/__init__.py",
"diff": "# pylint: disable=wildcard-import\nfrom __future__ import unicode_literals\n-import xbmc\n-\n+from .dialogs import *\nfrom .xmldialogs import *\n-\n-CMD_AUTOCLOSE_DIALOG = 'AlarmClock(closedialog,Dialog.Close(all,true),' \\\n- '{:02d}:{:02d},silent)'\n-\n-def show_notification(msg, title='Netflix'):\n- \"\"\"Show a notification\"\"\"\n- import resources.lib.common as common\n- xbmc.executebuiltin('Notification({}, {}, 3000, {})'\n- .format(title, msg, common.ICON)\n- .encode('utf-8'))\n-\n-def show_modal_dialog(dlg_class, xml, path, **kwargs):\n- \"\"\"\n- Show a modal Dialog in the UI.\n- Pass kwargs minutes and/or seconds tohave the dialog automatically\n- close after the specified time.\n- \"\"\"\n- dlg = dlg_class(xml, path, 'default', '1080i', **kwargs)\n- minutes = kwargs.get('minutes', 0)\n- seconds = kwargs.get('seconds', 0)\n- if minutes > 0 or seconds > 0:\n- xbmc.executebuiltin(CMD_AUTOCLOSE_DIALOG.format(minutes, seconds))\n- dlg.doModal()\n"
},
{
"change_type": "DELETE",
"old_path": "resources/lib/kodi/ui/newdialogs.py",
"new_path": null,
"diff": "-# -*- coding: utf-8 -*-\n-# pylint: disable=unused-import\n-\"\"\"Simple and statically defined dialogs\"\"\"\n-from __future__ import unicode_literals\n-\n-import xbmcgui\n-\n-def show_password_dialog():\n- \"\"\"\n- Asks the user for its Netflix password\n-\n- :returns: str - Netflix password\n- \"\"\"\n- from resources.lib.common import ADDON\n- return xbmcgui.Dialog().input(\n- heading=ADDON.getLocalizedString(30004),\n- type=xbmcgui.INPUT_ALPHANUM,\n- option=xbmcgui.ALPHANUM_HIDE_INPUT)\n-\n-def show_email_dialog():\n- \"\"\"\n- Asks the user for its Netflix account email\n-\n- :returns: str - Netflix account email\n- \"\"\"\n- from resources.lib.common import ADDON\n- return xbmcgui.Dialog().input(\n- heading=ADDON.getLocalizedString(30005),\n- type=xbmcgui.INPUT_ALPHANUM)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/ui/xmldialogs.py",
"new_path": "resources/lib/kodi/ui/xmldialogs.py",
"diff": "@@ -5,11 +5,27 @@ from __future__ import unicode_literals\nfrom platform import machine\n+import xbmc\nimport xbmcgui\nACTION_PLAYER_STOP = 13\nOS_MACHINE = machine()\n+CMD_AUTOCLOSE_DIALOG = 'AlarmClock(closedialog,Dialog.Close(all,true),' \\\n+ '{:02d}:{:02d},silent)'\n+\n+def show_modal_dialog(dlg_class, xml, path, **kwargs):\n+ \"\"\"\n+ Show a modal Dialog in the UI.\n+ Pass kwargs minutes and/or seconds tohave the dialog automatically\n+ close after the specified time.\n+ \"\"\"\n+ dlg = dlg_class(xml, path, 'default', '1080i', **kwargs)\n+ minutes = kwargs.get('minutes', 0)\n+ seconds = kwargs.get('seconds', 0)\n+ if minutes > 0 or seconds > 0:\n+ xbmc.executebuiltin(CMD_AUTOCLOSE_DIALOG.format(minutes, seconds))\n+ dlg.doModal()\nclass Skip(xbmcgui.WindowXMLDialog):\n\"\"\"\n@@ -29,12 +45,9 @@ class Skip(xbmcgui.WindowXMLDialog):\ndef onClick(self, controlID):\nif controlID == 6012:\n- import xbmc\nxbmc.Player().seekTime(self.skip_to)\nself.close()\n-\n-\nclass SaveStreamSettings(xbmcgui.WindowXMLDialog):\n\"\"\"\nDialog for skipping video parts (intro, recap, ...)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/actions.py",
"new_path": "resources/lib/navigation/actions.py",
"diff": "@@ -8,6 +8,7 @@ from xbmcaddon import Addon\nimport resources.lib.common as common\nimport resources.lib.cache as cache\nimport resources.lib.api.shakti as api\n+import resources.lib.kodi.ui as ui\nfrom resources.lib.navigation import InvalidPathError\ndef execute(pathitems, params):\n@@ -70,6 +71,7 @@ class ActionExecutor(object):\n\"\"\"Rate an item on Netflix. Ask for a rating if there is none supplied\nin the path.\"\"\"\nrating = self.params.get('rating') or ui.ask_for_rating()\n+ if rating is not None:\napi.rate(videoid, rating)\[email protected]_video_id(path_offset=1, inject_remaining_pathitems=True)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "\"\"\"Stateful Netflix session management\"\"\"\nfrom __future__ import unicode_literals\n-import sys\nfrom time import time\nfrom base64 import urlsafe_b64encode\nfrom functools import wraps\n@@ -85,7 +84,7 @@ class NetflixSession(object):\ntry:\nreturn common.get_credentials()\nexcept common.MissingCredentialsError:\n- return common.ask_credentials()\n+ return ui.ask_credentials()\n@property\ndef account_hash(self):\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Refactor UI dialogs |
105,989 | 24.10.2018 23:58:07 | -7,200 | 0f4d47385fa983e263d6ea1627306634cf64c15f | Add browsing of genres and recommendations from main menu | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/directory.py",
"new_path": "resources/lib/navigation/directory.py",
"diff": "@@ -16,12 +16,7 @@ def build(pathitems, params):\nraise InvalidPathError('Cannot route {}'.format('/'.join(pathitems)))\ncommon.debug('Invoking directory handler {}'.format(builder.__name__))\n-\n- if len(pathitems) > 1:\nbuilder(pathitems=pathitems)\n- else:\n- builder()\n-\n# Remember last location to be able to invalidate it in cache on\n# certain actions\ncommon.remember_last_location()\n@@ -37,8 +32,9 @@ class DirectoryBuilder(object):\nif profile_id:\napi.activate_profile(profile_id)\n- def root(self):\n+ def root(self, pathitems=None):\n\"\"\"Show profiles or home listing is autologin es enabled\"\"\"\n+ # pylint: disable=unused-argument\nautologin = common.ADDON.getSettingBool('autologin_enable')\nprofile_id = common.ADDON.getSetting('autologin_id')\nif autologin and profile_id:\n@@ -49,13 +45,15 @@ class DirectoryBuilder(object):\nelse:\nself.profiles()\n- def profiles(self):\n+ def profiles(self, pathitems=None):\n\"\"\"Show profiles listing\"\"\"\n+ # pylint: disable=unused-argument\ncommon.debug('Showing profiles listing')\nlistings.build_profiles_listing(api.profiles())\n- def home(self):\n+ def home(self, pathitems=None):\n\"\"\"Show home listing\"\"\"\n+ # pylint: disable=unused-argument\ncommon.debug('Showing root video lists')\nlistings.build_main_menu_listing(api.root_lists())\n@@ -80,3 +78,21 @@ class DirectoryBuilder(object):\ndef season(self, videoid):\n\"\"\"Show episodes of a season\"\"\"\nlistings.build_episode_listing(videoid, api.episodes(videoid))\n+\n+ def genres(self, pathitems):\n+ \"\"\"Show video lists for a genre\"\"\"\n+ if len(pathitems) == 1:\n+ lolomo = api.root_lists()\n+ contexts = common.MISC_CONTEXTS['genres']['contexts']\n+ else:\n+ # TODO: Implement fetching of genre lolomos\n+ lolomo = None\n+ contexts = None\n+ listings.build_lolomo_listing(lolomo, contexts)\n+\n+ def recommendations(self, pathitems=None):\n+ \"\"\"Show video lists for a genre\"\"\"\n+ # pylint: disable=unused-argument\n+ listings.build_lolomo_listing(\n+ api.root_lists(),\n+ common.MISC_CONTEXTS['recommendations']['contexts'])\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add browsing of genres and recommendations from main menu |
105,989 | 25.10.2018 00:21:09 | -7,200 | 1cb8ad717fbb5adcf4f5e0247a1017960cb2a10e | Prepare recursive browsing of genres like on Netflix Website | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -41,7 +41,7 @@ def root_lists():\nNetflixSession.path_request,\n[['lolomo',\n{'from': 0, 'to': 40},\n- ['displayName', 'context', 'id', 'index', 'length']]]))\n+ ['displayName', 'context', 'id', 'index', 'length', 'genreId']]]))\[email protected]_output(cache.CACHE_COMMON, identifying_param_index=0,\nidentifying_param_name='list_type')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -170,9 +170,13 @@ def build_lolomo_listing(lolomo, contexts=None):\nif contexts\nelse lolomo.lists.iteritem())\nfor video_list_id, video_list in lists:\n+ params = ({'genreId': video_list['genreId']}\n+ if video_list.get('genreId')\n+ else None)\ndirectory_items.append(\n(common.build_url(\n- ['video_list', video_list_id], mode=nav.MODE_DIRECTORY),\n+ ['video_list', video_list_id], mode=nav.MODE_DIRECTORY,\n+ params=params),\ncreate_list_item(video_list['displayName']),\nTrue))\nfinalize_directory(\n@@ -181,7 +185,7 @@ def build_lolomo_listing(lolomo, contexts=None):\ncontent_type=CONTENT_FOLDER)\n@custom_viewmode(VIEW_SHOW)\n-def build_video_listing(video_list):\n+def build_video_listing(video_list, genre_id=None):\n\"\"\"\nBuild a video listing\n\"\"\"\n@@ -208,6 +212,12 @@ def build_video_listing(video_list):\nlist_item,\nnot is_movie))\nonly_movies = only_movies and is_movie\n+ if genre_id:\n+ directory_items.append(\n+ (common.build_url(pathitems=['genres', genre_id],\n+ mode=nav.MODE_DIRECTORY),\n+ create_list_item('Browse more...'),\n+ True))\nfinalize_directory(\nitems=directory_items,\nsort_methods=[xbmcplugin.SORT_METHOD_UNSORTED,\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/directory.py",
"new_path": "resources/lib/navigation/directory.py",
"diff": "@@ -5,6 +5,7 @@ from __future__ import unicode_literals\nimport resources.lib.common as common\nimport resources.lib.api.shakti as api\nimport resources.lib.kodi.listings as listings\n+import resources.lib.kodi.ui as ui\nfrom resources.lib.navigation import InvalidPathError\ndef build(pathitems, params):\n@@ -65,7 +66,8 @@ class DirectoryBuilder(object):\nelse:\nlist_id = pathitems[1]\n- listings.build_video_listing(api.video_list(list_id))\n+ listings.build_video_listing(api.video_list(list_id),\n+ self.params.get('genreId'))\[email protected]_video_id(path_offset=0)\ndef show(self, videoid):\n@@ -86,8 +88,9 @@ class DirectoryBuilder(object):\ncontexts = common.MISC_CONTEXTS['genres']['contexts']\nelse:\n# TODO: Implement fetching of genre lolomos\n- lolomo = None\n- contexts = None\n+ ui.show_notification('Browsing genre {}'.format(pathitems[1]))\n+ lolomo = api.root_lists()\n+ contexts = common.MISC_CONTEXTS['genres']['contexts']\nlistings.build_lolomo_listing(lolomo, contexts)\ndef recommendations(self, pathitems=None):\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Prepare recursive browsing of genres like on Netflix Website |
105,989 | 25.10.2018 17:20:57 | -7,200 | 11c85c132d3b771fe78803c10744553c897924e7 | Make parsing of path references more robust. Several optimizations. Make artwork (of first contained video) and short selection of contained titles available for VideoList | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/data_types.py",
"new_path": "resources/lib/api/data_types.py",
"diff": "@@ -10,35 +10,53 @@ from .paths import resolve_refs\nclass LoLoMo(object):\n\"\"\"List of list of movies (lolomo)\"\"\"\n# pylint: disable=invalid-name\n- def __init__(self, path_response):\n+ def __init__(self, path_response, lolomoid=None):\nself.data = path_response\n- self.id = self.data['lolomo'][1]\n+ self.id = (lolomoid\n+ if lolomoid\n+ else next(self.data['lolomos'].iterkeys()))\nself.lists = OrderedDict(\n- resolve_refs(self.data['lolomos'][self.id], self.data))\n+ (key, VideoList(self.data, key))\n+ for key, _\n+ in resolve_refs(self.data['lolomos'][self.id], self.data))\n+\n+ def __getitem__(self, key):\n+ return self.data['lolomos'][self.id][key]\n+\n+ def get(self, key, default=None):\n+ \"\"\"Pass call on to the backing dict of this LoLoMo.\"\"\"\n+ return self.data['lolomos'][self.id].get(key, default)\ndef lists_by_context(self, context):\n\"\"\"Return a generator expression that iterates over all video\nlists with the given context.\nWill match any video lists with type contained in context\nif context is a list.\"\"\"\n- if isinstance(context, list):\n- lists = ((list_id, video_list)\n- for list_id, video_list in self.lists.iteritems()\n- if video_list['context'] in context)\n- else:\n- lists = ((list_id, video_list)\n+ match_context = ((lambda context, contexts: context in contexts)\n+ if isinstance(context, list)\n+ else (lambda context, target: context == target))\n+ return ((list_id, VideoList(self.data, list_id))\nfor list_id, video_list in self.lists.iteritems()\n- if video_list['context'] == context)\n- return lists\n+ if match_context(video_list['context'], context))\nclass VideoList(object):\n\"\"\"A video list\"\"\"\n# pylint: disable=invalid-name\n- def __init__(self, path_response):\n+ def __init__(self, path_response, list_id=None):\nself.data = path_response\n- self.id = self.data['lists'].keys()[0]\n+ self.id = list_id if list_id else next(self.data['lists'].iterkeys())\nself.videos = OrderedDict(\nresolve_refs(self.data['lists'][self.id], self.data))\n+ self.artitem = next(self.videos.itervalues())\n+ self.contained_titles = [video['title']\n+ for video in self.videos.itervalues()]\n+\n+ def __getitem__(self, key):\n+ return self.data['lists'][self.id][key]\n+\n+ def get(self, key, default=None):\n+ \"\"\"Pass call on to the backing dict of this VideoList.\"\"\"\n+ return self.data['lists'][self.id].get(key, default)\nclass SeasonList(object):\n\"\"\"A list of seasons. Includes tvshow art.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/paths.py",
"new_path": "resources/lib/api/paths.py",
"diff": "@@ -73,18 +73,19 @@ def resolve_refs(references, targets):\n\"\"\"Return a generator expression that returns the objects in targets\nby resolving the references in sorted order\"\"\"\nreturn (common.get_path(ref, targets, include_key=True)\n- for index, ref in iterate_to_sentinel(references))\n+ for index, ref in iterate_references(references))\n-def iterate_to_sentinel(source):\n+def iterate_references(source):\n\"\"\"Generator expression that iterates over a dictionary of\n- index=>reference pairs in sorted order until it reaches the sentinel\n- reference and stops iteration.\n+ index=>reference pairs (sorted in ascending order by indices) until it\n+ reaches the first empty reference, which signals the end of the reference\n+ list.\nItems with a key that do not represent an integer are ignored.\"\"\"\nfor index, ref in sorted({int(k): v\nfor k, v in source.iteritems()\nif common.is_numeric(k)}.iteritems()):\npath = reference_path(ref)\n- if is_sentinel(path):\n+ if path is None:\nbreak\nelse:\nyield (index, path)\n@@ -92,17 +93,75 @@ def iterate_to_sentinel(source):\ndef reference_path(ref):\n\"\"\"Return the actual reference path (a list of path items to follow)\nfor a reference item.\n- The Netflix API sometimes adds another dict layer with a single key\n- 'reference' which we need to extract from.\"\"\"\n+\n+ The Netflix API returns references in several different formats.\n+ In both cases, we want to get at the innermost list, which describes\n+ the path to follow when resolving the reference:\n+ - List-based references:\n+ [\n+ \"lists\",\n+ \"09a4eb6f-8f6b-45fe-a65b-c64c4fcdc6b8_60070239X20XX1539870260807\"\n+ ]\n+ - Dict-based references which have a type and a value:\n+ {\n+ \"$type\": \"ref\",\n+ \"value\": [\n+ \"videos\",\n+ \"80018294\"\n+ ]\n+ }\n+\n+ Empty references indicate the end of a list of references if there\n+ are fewer entries available than were requested. They are always a dict,\n+ regardless of valid references in the list being list-based or dict-based.\n+ They don't have a value attribute and are either of type sentinel or atom:\n+ { \"$type\": \"sentinel\" }\n+ or\n+ { \"$type\": \"atom\" }\n+\n+ In some cases, references are requested via the 'reference' attribute of\n+ a Netlix list type like so:\n+ [\"genres\", \"83\", \"rw\", \"shortform\",\n+ { \"from\": 0, \"to\": 50 },\n+ { \"from\": 0, \"to\": 7 },\n+ \"reference\",\n+ \"ACTUAL ATTRIBUTE OF REFERENCED ITEM\"]\n+ In this case, the reference we want to get the value of is nested into an\n+ additional 'reference' attribute like so:\n+ - list-based nested reference:\n+ {\n+ \"reference\": [ <== additional nesting\n+ \"videos\",\n+ \"80178971\"\n+ ]\n+ }\n+ - dict-based nested reference:\n+ {\n+ \"reference\": { <== additional nesting\n+ \"$type\": \"ref\",\n+ \"value\": [\n+ \"videos\",\n+ \"80018294\"\n+ ]\n+ }\n+ }\n+ To get to the value, we simply remove the additional layer of nesting by\n+ doing ref = ref['reference'] and continue with analyzing ref.\n+ \"\"\"\n+ if isinstance(ref, dict) and 'reference' in ref:\n+ # Nested reference, remove nesting to get to real reference\n+ ref = ref['reference']\nif isinstance(ref, list):\n+ # List-based reference (never empty, so return right away)\nreturn ref\n- elif isinstance(ref, dict) and 'reference' in ref:\n- return ref['reference']\n- else:\n+ if isinstance(ref, dict):\n+ # Dict-based reference\n+ reftype = ref.get('$type')\n+ if reftype in ['sentinel', 'atom']:\n+ # Empty reference\n+ return None\n+ elif reftype == 'ref':\n+ # Valid reference with value\n+ return ref['value']\nraise InvalidReferenceError(\n'Unexpected reference format encountered: {}'.format(ref))\n-\n-def is_sentinel(ref):\n- \"\"\"Check if a reference item is of type sentinel and thus signals\n- the end of the list\"\"\"\n- return isinstance(ref, dict) and ref.get('$type') == 'sentinel'\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -4,7 +4,6 @@ from __future__ import unicode_literals\nimport resources.lib.common as common\nimport resources.lib.cache as cache\n-from resources.lib.services.nfsession import NetflixSession\nfrom .data_types import LoLoMo, VideoList, SeasonList, EpisodeList\nfrom .paths import (VIDEO_LIST_PARTIAL_PATHS, SEASONS_PARTIAL_PATHS,\n@@ -17,31 +16,34 @@ class InvalidVideoListTypeError(Exception):\ndef activate_profile(profile_id):\n\"\"\"Activate the profile with the given ID\"\"\"\ncache.invalidate_cache()\n- common.make_call(NetflixSession.activate_profile, profile_id)\n+ common.make_call('activate_profile', profile_id)\ndef logout():\n\"\"\"Logout of the current account\"\"\"\ncache.invalidate_cache()\n- common.make_call(NetflixSession.logout)\n+ common.make_call('logout')\ndef login():\n\"\"\"Perform a login\"\"\"\ncache.invalidate_cache()\n- common.make_call(NetflixSession.login)\n+ common.make_call('login')\ndef profiles():\n\"\"\"Retrieve the list of available user profiles\"\"\"\n- return common.make_call(NetflixSession.list_profiles)\n+ return common.make_call('list_profiles')\[email protected]_output(cache.CACHE_COMMON, fixed_identifier='root_lists')\ndef root_lists():\n\"\"\"Retrieve initial video lists to display on homepage\"\"\"\ncommon.debug('Requesting root lists from API')\nreturn LoLoMo(common.make_call(\n- NetflixSession.path_request,\n+ 'path_request',\n[['lolomo',\n{'from': 0, 'to': 40},\n- ['displayName', 'context', 'id', 'index', 'length', 'genreId']]]))\n+ ['displayName', 'context', 'id', 'index', 'length', 'genreId']]] +\n+ build_paths(['lolomo', {'from': 0, 'to': 40},\n+ {'from': 0, 'to': 1}, 'reference'],\n+ [['title']] + ART_PARTIAL_PATHS)))\[email protected]_output(cache.CACHE_COMMON, identifying_param_index=0,\nidentifying_param_name='list_type')\n@@ -62,7 +64,7 @@ def video_list(list_id):\n\"\"\"Retrieve a single video list\"\"\"\ncommon.debug('Requesting video list {}'.format(list_id))\nreturn VideoList(common.make_call(\n- NetflixSession.path_request,\n+ 'path_request',\nbuild_paths(['lists', [list_id], {'from': 0, 'to': 40}, 'reference'],\nVIDEO_LIST_PARTIAL_PATHS)))\n@@ -76,7 +78,7 @@ def seasons(videoid):\nreturn SeasonList(\nvideoid,\ncommon.make_call(\n- NetflixSession.path_request,\n+ 'path_request',\nbuild_paths(['videos', videoid.tvshowid],\nSEASONS_PARTIAL_PATHS)))\n@@ -90,7 +92,7 @@ def episodes(videoid):\nreturn EpisodeList(\nvideoid,\ncommon.make_call(\n- NetflixSession.path_request,\n+ 'path_request',\nbuild_paths(['seasons', videoid.seasonid, 'episodes',\n{'from': 0, 'to': 40}],\nEPISODES_PARTIAL_PATHS) +\n@@ -109,7 +111,7 @@ def single_info(videoid):\nif videoid.mediatype == common.VideoId.EPISODE:\npaths.extend(build_paths(['videos', videoid.tvshowid],\nART_PARTIAL_PATHS + [['title']]))\n- return common.make_call(NetflixSession.path_request, paths)\n+ return common.make_call('path_request', paths)\ndef rate(videoid, rating):\n\"\"\"Rate a video on Netflix\"\"\"\n@@ -117,7 +119,7 @@ def rate(videoid, rating):\n# In opposition to Kodi, Netflix uses a rating from 0 to in 0.5 steps\nrating = min(10, max(0, rating)) / 2\ncommon.make_call(\n- NetflixSession.post,\n+ 'post',\n{'component': 'set_video_rating',\n'headers': {\n'Content-Type': 'application/json',\n@@ -139,7 +141,7 @@ def remove_from_list(videoid):\ndef _update_my_list(video_id, operation):\n\"\"\"Call API to update my list with either add or remove action\"\"\"\ncommon.make_call(\n- NetflixSession.post,\n+ 'post',\n{'component': 'update_my_list',\n'headers': {\n'Content-Type': 'application/json',\n@@ -183,7 +185,7 @@ def _metadata(video_id):\nto a show by Netflix.\"\"\"\ncommon.debug('Requesting metdata for {}'.format(video_id))\nreturn common.make_call(\n- NetflixSession.get,\n+ 'get',\n{\n'component': 'metadata',\n'req_type': 'api',\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -793,11 +793,10 @@ def send_signal(signal, data=None):\nsignal=signal,\ndata=data)\n-def make_call(func, data=None):\n+def make_call(callname, data=None):\n\"\"\"Make a call via AddonSignals and wait for it to return.\nThe contents of data will be expanded to kwargs and passed into the target\nfunction.\"\"\"\n- callname = _signal_name(func)\nresult = AddonSignals.makeCall(\nsource_id=ADDON_ID,\nsignal=callname,\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Make parsing of path references more robust. Several optimizations. Make artwork (of first contained video) and short selection of contained titles available for VideoList |
105,989 | 25.10.2018 17:45:23 | -7,200 | 06536aa7558f5de8d1edd334a13e45fa20fde179 | Add displaying artwork and a selection of contained titles for video lists | [
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -363,3 +363,7 @@ msgstr \"\"\nmsgctxt \"#30086\"\nmsgid \"Invalidate entire cache on modification of My List\"\nmsgstr \"\"\n+\n+msgctxt \"#30087\"\n+msgid \" and more...\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/data_types.py",
"new_path": "resources/lib/api/data_types.py",
"diff": "@@ -5,6 +5,8 @@ from __future__ import unicode_literals\nfrom collections import OrderedDict\n+import resources.lib.common as common\n+\nfrom .paths import resolve_refs\nclass LoLoMo(object):\n@@ -44,19 +46,22 @@ class VideoList(object):\n# pylint: disable=invalid-name\ndef __init__(self, path_response, list_id=None):\nself.data = path_response\n- self.id = list_id if list_id else next(self.data['lists'].iterkeys())\n+ self.id = common.VideoId(\n+ videoid=(list_id\n+ if list_id\n+ else next(self.data['lists'].iterkeys())))\nself.videos = OrderedDict(\n- resolve_refs(self.data['lists'][self.id], self.data))\n+ resolve_refs(self.data['lists'][self.id.value], self.data))\nself.artitem = next(self.videos.itervalues())\nself.contained_titles = [video['title']\nfor video in self.videos.itervalues()]\ndef __getitem__(self, key):\n- return self.data['lists'][self.id][key]\n+ return self.data['lists'][self.id.value][key]\ndef get(self, key, default=None):\n\"\"\"Pass call on to the backing dict of this VideoList.\"\"\"\n- return self.data['lists'][self.id].get(key, default)\n+ return self.data['lists'][self.id.value].get(key, default)\nclass SeasonList(object):\n\"\"\"A list of seasons. Includes tvshow art.\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -39,10 +39,10 @@ def root_lists():\nreturn LoLoMo(common.make_call(\n'path_request',\n[['lolomo',\n- {'from': 0, 'to': 40},\n+ {'from': 0, 'to': 35},\n['displayName', 'context', 'id', 'index', 'length', 'genreId']]] +\n- build_paths(['lolomo', {'from': 0, 'to': 40},\n- {'from': 0, 'to': 1}, 'reference'],\n+ build_paths(['lolomo', {'from': 0, 'to': 35},\n+ {'from': 0, 'to': 3}, 'reference'],\n[['title']] + ART_PARTIAL_PATHS)))\[email protected]_output(cache.CACHE_COMMON, identifying_param_index=0,\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -48,8 +48,15 @@ def add_info_for_playback(videoid, list_item):\ndef parse_info(videoid, item, raw_data):\n\"\"\"Parse info from a path request response into Kodi infolabels\"\"\"\n- # Only season items don't have a type in their summary, thus, if\n- # there's no type, it's a season\n+ if (videoid.mediatype == common.VideoId.UNSPECIFIED and\n+ hasattr(item, 'contained_titles')):\n+ # Special handling for VideoLists\n+ return {\n+ 'mediatype': 'video',\n+ 'plot': (', '.join(item.contained_titles) +\n+ common.get_local_string(30087))\n+ }, {}\n+\nmediatype = videoid.mediatype\nif mediatype == common.VideoId.SHOW:\n# Type from Netflix doesn't match Kodi's expectations\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -133,10 +133,13 @@ def build_main_menu_listing(lolomo):\n\"\"\"\ndirectory_items = []\nfor _, user_list in lolomo.lists_by_context(common.KNOWN_LIST_TYPES):\n+ list_item = create_list_item(user_list['displayName'])\n+ add_info(user_list.id, list_item, user_list, user_list.data)\n+ add_art(user_list.id, list_item, user_list.artitem)\ndirectory_items.append(\n(common.build_url(\n['video_list', user_list['context']], mode=nav.MODE_DIRECTORY),\n- create_list_item(user_list['displayName']),\n+ list_item,\nTrue))\nfor context_type, data in common.MISC_CONTEXTS.iteritems():\n@@ -173,11 +176,14 @@ def build_lolomo_listing(lolomo, contexts=None):\nparams = ({'genreId': video_list['genreId']}\nif video_list.get('genreId')\nelse None)\n+ list_item = create_list_item(video_list['displayName'])\n+ add_info(video_list.id, list_item, video_list, video_list.data)\n+ add_art(video_list.id, list_item, video_list.artitem)\ndirectory_items.append(\n(common.build_url(\n['video_list', video_list_id], mode=nav.MODE_DIRECTORY,\nparams=params),\n- create_list_item(video_list['displayName']),\n+ list_item,\nTrue))\nfinalize_directory(\nitems=directory_items,\n@@ -216,7 +222,12 @@ def build_video_listing(video_list, genre_id=None):\ndirectory_items.append(\n(common.build_url(pathitems=['genres', genre_id],\nmode=nav.MODE_DIRECTORY),\n- create_list_item('Browse more...'),\n+ create_list_item('Browse related content...'),\n+ True))\n+ directory_items.append(\n+ (common.build_url(pathitems=['genres', genre_id, 'subgenres'],\n+ mode=nav.MODE_DIRECTORY),\n+ create_list_item('Browse subgenres...'),\nTrue))\nfinalize_directory(\nitems=directory_items,\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add displaying artwork and a selection of contained titles for video lists |
105,989 | 26.10.2018 14:58:11 | -7,200 | b7ed8600ad6833dee8140ba17474572d959437f6 | Add recursive browsing of genres and video lists (browse related video lists when viewing a video list) | [
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -365,5 +365,45 @@ msgid \"Invalidate entire cache on modification of My List\"\nmsgstr \"\"\nmsgctxt \"#30087\"\n-msgid \" and more...\"\n+msgid \"Contains {} and more...\"\n+msgstr \"\"\n+\n+msgctxt \"#30088\"\n+msgid \"Browse related content\"\n+msgstr \"\"\n+\n+msgctxt \"#30089\"\n+msgid \"Browse subgenres\"\n+msgstr \"\"\n+\n+msgctxt \"#30090\"\n+msgid \"Browse through related video lists and discover more content.\"\n+msgstr \"\"\n+\n+msgctxt \"#30091\"\n+msgid \"Browse and manage contents that were exported to the Kodi library.\"\n+msgstr \"\"\n+\n+msgctxt \"#30092\"\n+msgid \"Search for content and easily find what you want to watch.\"\n+msgstr \"\"\n+\n+msgctxt \"#30093\"\n+msgid \"Browse content by genre and easily discover related content.\"\n+msgstr \"\"\n+\n+msgctxt \"#30094\"\n+msgid \"Browse recommendations and pick up on something new you might like.\"\n+msgstr \"\"\n+\n+msgctxt \"#30095\"\n+msgid \"All TV Shows\"\n+msgstr \"\"\n+\n+msgctxt \"#30096\"\n+msgid \"All Movies\"\n+msgstr \"\"\n+\n+msgctxt \"#30097\"\n+msgid \"Main Menu\"\nmsgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/data_types.py",
"new_path": "resources/lib/api/data_types.py",
"diff": "@@ -61,26 +61,29 @@ class VideoList(object):\ndef get(self, key, default=None):\n\"\"\"Pass call on to the backing dict of this VideoList.\"\"\"\n- return self.data['lists'][self.id.value].get(key, default)\n+ return _check_sentinel(self.data['lists'][self.id.value]\n+ .get(key, default))\nclass SeasonList(object):\n\"\"\"A list of seasons. Includes tvshow art.\"\"\"\ndef __init__(self, videoid, path_response):\nself.data = path_response\nself.videoid = videoid\n- self.seasons = OrderedDict(\n- resolve_refs(\n- self.data['videos'][self.videoid.tvshowid]['seasonList'],\n- self.data))\nself.tvshow = self.data['videos'][self.videoid.tvshowid]\n+ self.seasons = OrderedDict(\n+ resolve_refs(self.tvshow['seasonList'], self.data))\nclass EpisodeList(object):\n\"\"\"A list of episodes. Includes tvshow art.\"\"\"\ndef __init__(self, videoid, path_response):\nself.data = path_response\nself.videoid = videoid\n- self.episodes = OrderedDict(\n- resolve_refs(\n- self.data['seasons'][self.videoid.seasonid]['episodes'],\n- self.data))\nself.tvshow = self.data['videos'][self.videoid.tvshowid]\n+ self.season = self.data['seasons'][self.videoid.seasonid]\n+ self.episodes = OrderedDict(\n+ resolve_refs(self.season['episodes'], self.data))\n+\n+def _check_sentinel(value):\n+ return (None\n+ if isinstance(value, dict) and value.get('$type') == 'sentinel'\n+ else value)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/paths.py",
"new_path": "resources/lib/api/paths.py",
"diff": "@@ -25,6 +25,13 @@ VIDEO_LIST_PARTIAL_PATHS = [\n{'from': 0, 'to': 10}, ['id', 'name']]\n] + ART_PARTIAL_PATHS\n+GENRE_PARTIAL_PATHS = [\n+ [[\"id\", \"requestId\", \"summary\", \"name\"]],\n+ [{\"from\": 0, \"to\": 50},\n+ [\"context\", \"displayName\", \"genreId\", \"id\", \"isTallRow\", \"length\",\n+ \"requestId\", \"type\", \"videoId\"]]\n+]\n+\nSEASONS_PARTIAL_PATHS = [\n['seasonList', {'from': 0, 'to': 40}, 'summary'],\n['title']\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -7,7 +7,8 @@ import resources.lib.cache as cache\nfrom .data_types import LoLoMo, VideoList, SeasonList, EpisodeList\nfrom .paths import (VIDEO_LIST_PARTIAL_PATHS, SEASONS_PARTIAL_PATHS,\n- EPISODES_PARTIAL_PATHS, ART_PARTIAL_PATHS)\n+ EPISODES_PARTIAL_PATHS, ART_PARTIAL_PATHS,\n+ GENRE_PARTIAL_PATHS)\nclass InvalidVideoListTypeError(Exception):\n\"\"\"No video list of a given was available\"\"\"\n@@ -41,6 +42,7 @@ def root_lists():\n[['lolomo',\n{'from': 0, 'to': 35},\n['displayName', 'context', 'id', 'index', 'length', 'genreId']]] +\n+ # Titles and art of first 4 videos in each video list\nbuild_paths(['lolomo', {'from': 0, 'to': 35},\n{'from': 0, 'to': 3}, 'reference'],\n[['title']] + ART_PARTIAL_PATHS)))\n@@ -65,9 +67,27 @@ def video_list(list_id):\ncommon.debug('Requesting video list {}'.format(list_id))\nreturn VideoList(common.make_call(\n'path_request',\n+ [['lists', [list_id], 'displayName']] +\nbuild_paths(['lists', [list_id], {'from': 0, 'to': 40}, 'reference'],\nVIDEO_LIST_PARTIAL_PATHS)))\[email protected]_output(cache.CACHE_GENRES, identifying_param_index=0,\n+ identifying_param_name='genre_id')\n+def genre(genre_id):\n+ \"\"\"Retrieve LoLoMos for the given genre\"\"\"\n+ common.debug('Requesting LoLoMos for genre {}'.format(genre_id))\n+ return LoLoMo(common.make_call(\n+ 'path_request',\n+ build_paths(['genres', genre_id, 'rw'], GENRE_PARTIAL_PATHS) +\n+ # Titles and art of standard lists' items\n+ build_paths(['genres', genre_id, 'rw',\n+ {\"from\": 0, \"to\": 50},\n+ {\"from\": 0, \"to\": 3}, \"reference\"],\n+ [['title']] + ART_PARTIAL_PATHS) +\n+ # IDs and names of subgenres\n+ [['genres', genre_id, 'subgenres', {'from': 0, 'to': 30},\n+ ['id', 'name']]]))\n+\[email protected]_output(cache.CACHE_COMMON)\ndef seasons(videoid):\n\"\"\"Retrieve seasons of a TV show\"\"\"\n@@ -93,6 +113,7 @@ def episodes(videoid):\nvideoid,\ncommon.make_call(\n'path_request',\n+ [['seasons', videoid.seasonid, 'summary']] +\nbuild_paths(['seasons', videoid.seasonid, 'episodes',\n{'from': 0, 'to': 40}],\nEPISODES_PARTIAL_PATHS) +\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -18,13 +18,14 @@ import resources.lib.common as common\nWND = xbmcgui.Window(10000)\nCACHE_COMMON = 'cache_common'\n+CACHE_GENRES = 'cache_genres'\nCACHE_METADATA = 'cache_metadata'\nCACHE_INFOLABELS = 'cache_infolabels'\nCACHE_ARTINFO = 'cache_artinfo'\nCACHE_LIBRARY = 'library'\n-BUCKET_NAMES = [CACHE_COMMON, CACHE_METADATA, CACHE_INFOLABELS,\n- CACHE_ARTINFO, CACHE_LIBRARY]\n+BUCKET_NAMES = [CACHE_COMMON, CACHE_GENRES, CACHE_METADATA,\n+ CACHE_INFOLABELS, CACHE_ARTINFO, CACHE_LIBRARY]\nBUCKETS = {}\nTTL_INFINITE = 60*60*24*365*100\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -42,8 +42,12 @@ KNOWN_LIST_TYPES = ['queue', 'topTen', 'netflixOriginals', 'continueWatching',\n'trendingNow', 'newRelease', 'popularTitles']\nMISC_CONTEXTS = {\n'genres': {'label_id': 30010,\n+ 'description_id': 30093,\n+ 'icon': 'DefaultGenre.png',\n'contexts': 'genre'},\n'recommendations': {'label_id': 30001,\n+ 'description_id': 30094,\n+ 'icon': 'DefaultUser.png',\n'contexts': ['similars', 'becauseYouAdded']}\n}\n@@ -123,6 +127,7 @@ class VideoId(object):\ntvshowid=None, videoid=None):\nif videoid:\nself.videoid = videoid\n+ self.id_values = (None, None, None, None)\nelse:\nself.videoid = None\nself.id_values = (movieid, episodeid, seasonid, tvshowid)\n@@ -252,11 +257,7 @@ class VideoId(object):\nreturn '{}_{}'.format(self.mediatype, self.value)\ndef __hash__(self):\n- try:\n- return int(self.value)\n- except ValueError:\n- error('Cannot hash {}'.format(self))\n- return 0\n+ return hash(str(self))\ndef __eq__(self, other):\nreturn (self.videoid == other.videoid and\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -53,8 +53,8 @@ def parse_info(videoid, item, raw_data):\n# Special handling for VideoLists\nreturn {\n'mediatype': 'video',\n- 'plot': (', '.join(item.contained_titles) +\n- common.get_local_string(30087))\n+ 'plot': common.get_local_string(30087).format(\n+ ', '.join(item.contained_titles))\n}, {}\nmediatype = videoid.mediatype\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -126,6 +126,25 @@ def build_profiles_listing(profiles):\nitems=directory_items,\nsort_methods=[xbmcplugin.SORT_METHOD_LABEL])\n+ADDITIONAL_MAIN_MENU_ITEMS = [\n+ {'path': ['genres', '83'],\n+ 'label': common.get_local_string(30095),\n+ 'icon': 'DefaultTVShows.png',\n+ 'description': None},\n+ {'path': ['genres', '34399'],\n+ 'label': common.get_local_string(30096),\n+ 'icon': 'DefaultMovies.png',\n+ 'description': None},\n+ {'path': ['search'],\n+ 'label': common.get_local_string(30011),\n+ 'icon': None,\n+ 'description': common.get_local_string(30092)},\n+ {'path': ['exported'],\n+ 'label': common.get_local_string(30048),\n+ 'icon': 'DefaultHardDisk.png',\n+ 'description': common.get_local_string(30091)},\n+]\n+\n@custom_viewmode(VIEW_FOLDER)\ndef build_main_menu_listing(lolomo):\n\"\"\"\n@@ -145,23 +164,23 @@ def build_main_menu_listing(lolomo):\nfor context_type, data in common.MISC_CONTEXTS.iteritems():\ndirectory_items.append(\n(common.build_url([context_type], mode=nav.MODE_DIRECTORY),\n- create_list_item(common.get_local_string(data['label_id'])),\n+ create_list_item(common.get_local_string(data['label_id']),\n+ icon=data['icon'],\n+ description=common.get_local_string(\n+ data['description_id'])),\nTrue))\n- # Add search\n+ for menu_item in ADDITIONAL_MAIN_MENU_ITEMS:\ndirectory_items.append(\n- (common.build_url(['search'], mode=nav.MODE_DIRECTORY),\n- create_list_item(common.get_local_string(30011)),\n- True))\n-\n- # Add exported\n- directory_items.append(\n- (common.build_url(['exported'], mode=nav.MODE_DIRECTORY),\n- create_list_item(common.get_local_string(30048)),\n+ (common.build_url(menu_item['path'], mode=nav.MODE_DIRECTORY),\n+ create_list_item(menu_item['label'],\n+ icon=menu_item['icon'],\n+ description=menu_item['description']),\nTrue))\nfinalize_directory(\nitems=directory_items,\n+ title=common.get_local_string(30097),\nsort_methods=[xbmcplugin.SORT_METHOD_UNSORTED],\ncontent_type=CONTENT_FOLDER)\n@@ -171,8 +190,11 @@ def build_lolomo_listing(lolomo, contexts=None):\ndirectory_items = []\nlists = (lolomo.lists_by_context(contexts)\nif contexts\n- else lolomo.lists.iteritem())\n+ else lolomo.lists.iteritems())\nfor video_list_id, video_list in lists:\n+ if video_list['context'] == 'billboard':\n+ # Skip billboard (only contains one video)\n+ continue\nparams = ({'genreId': video_list['genreId']}\nif video_list.get('genreId')\nelse None)\n@@ -187,6 +209,7 @@ def build_lolomo_listing(lolomo, contexts=None):\nTrue))\nfinalize_directory(\nitems=directory_items,\n+ title=lolomo.get('name'),\nsort_methods=[xbmcplugin.SORT_METHOD_UNSORTED],\ncontent_type=CONTENT_FOLDER)\n@@ -222,15 +245,19 @@ def build_video_listing(video_list, genre_id=None):\ndirectory_items.append(\n(common.build_url(pathitems=['genres', genre_id],\nmode=nav.MODE_DIRECTORY),\n- create_list_item('Browse related content...'),\n- True))\n- directory_items.append(\n- (common.build_url(pathitems=['genres', genre_id, 'subgenres'],\n- mode=nav.MODE_DIRECTORY),\n- create_list_item('Browse subgenres...'),\n+ create_list_item(common.get_local_string(30088),\n+ icon='DefaultAddSource.png',\n+ description=common.get_local_string(30090)),\nTrue))\n+ # TODO: Implement browsing of subgenres\n+ # directory_items.append(\n+ # (common.build_url(pathitems=['genres', genre_id, 'subgenres'],\n+ # mode=nav.MODE_DIRECTORY),\n+ # create_list_item('Browse subgenres...'),\n+ # True))\nfinalize_directory(\nitems=directory_items,\n+ title=video_list['displayName'],\nsort_methods=[xbmcplugin.SORT_METHOD_UNSORTED,\nxbmcplugin.SORT_METHOD_LABEL,\nxbmcplugin.SORT_METHOD_TITLE,\n@@ -259,6 +286,8 @@ def build_season_listing(tvshowid, season_list):\nTrue))\nfinalize_directory(\nitems=directory_items,\n+ title=' - '.join((season_list.tvshow['title'],\n+ common.get_local_string(20366)[2:])),\nsort_methods=[xbmcplugin.SORT_METHOD_NONE,\nxbmcplugin.SORT_METHOD_VIDEO_YEAR,\nxbmcplugin.SORT_METHOD_LABEL,\n@@ -285,6 +314,8 @@ def build_episode_listing(seasonid, episode_list):\nFalse))\nfinalize_directory(\nitems=directory_items,\n+ title=' - '.join((episode_list.tvshow['title'],\n+ episode_list.season['summary']['name'])),\nsort_methods=[xbmcplugin.SORT_METHOD_UNSORTED,\nxbmcplugin.SORT_METHOD_LABEL,\nxbmcplugin.SORT_METHOD_TITLE,\n@@ -294,17 +325,20 @@ def build_episode_listing(seasonid, episode_list):\ncontent_type=CONTENT_EPISODE)\n-def create_list_item(label, icon=None, fanart=None):\n+def create_list_item(label, icon=None, fanart=None, description=None):\n\"\"\"Create a rudimentary list item with icon and fanart\"\"\"\n# pylint: disable=unexpected-keyword-arg\nlist_item = xbmcgui.ListItem(label=label,\niconImage=icon or common.DEFAULT_FANART,\noffscreen=True)\nlist_item.setProperty('fanart_image', fanart or common.DEFAULT_FANART)\n+ list_item.setContentLookup(False)\n+ if description:\n+ list_item.setInfo('video', {'plot': description})\nreturn list_item\ndef finalize_directory(items, sort_methods=None, content_type=CONTENT_FOLDER,\n- refresh=False):\n+ refresh=False, title=None):\n\"\"\"Finalize a directory listing.\nAdd items, set available sort methods and content type\"\"\"\nxbmcplugin.addDirectoryItems(\n@@ -317,6 +351,11 @@ def finalize_directory(items, sort_methods=None, content_type=CONTENT_FOLDER,\nhandle=common.PLUGIN_HANDLE,\nsortMethod=sort_method)\n+ if title:\n+ xbmcplugin.setPluginCategory(\n+ handle=common.PLUGIN_HANDLE,\n+ category=title)\n+\nxbmcplugin.setContent(\nhandle=common.PLUGIN_HANDLE,\ncontent=content_type)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/directory.py",
"new_path": "resources/lib/navigation/directory.py",
"diff": "@@ -83,14 +83,12 @@ class DirectoryBuilder(object):\ndef genres(self, pathitems):\n\"\"\"Show video lists for a genre\"\"\"\n- if len(pathitems) == 1:\n+ if len(pathitems) < 2:\nlolomo = api.root_lists()\ncontexts = common.MISC_CONTEXTS['genres']['contexts']\nelse:\n- # TODO: Implement fetching of genre lolomos\n- ui.show_notification('Browsing genre {}'.format(pathitems[1]))\n- lolomo = api.root_lists()\n- contexts = common.MISC_CONTEXTS['genres']['contexts']\n+ lolomo = api.genre(pathitems[1])\n+ contexts = None\nlistings.build_lolomo_listing(lolomo, contexts)\ndef recommendations(self, pathitems=None):\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add recursive browsing of genres and video lists (browse related video lists when viewing a video list) |
105,989 | 26.10.2018 16:13:42 | -7,200 | 572eb63c6ae20805dd385fd5a4a9d8e63232d6c9 | Request new credentials if stored ones cannot be decrypted | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -412,10 +412,14 @@ def get_credentials():\nemail = ADDON.getSetting('email')\npassword = ADDON.getSetting('password')\nverify_credentials(email, password)\n+ try:\nreturn {\n'email': decrypt_credential(email),\n'password': decrypt_credential(password)\n}\n+ except ValueError:\n+ raise MissingCredentialsError(\n+ 'Existing credentials could not be decrypted')\ndef set_credentials(email, password):\n\"\"\"\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Request new credentials if stored ones cannot be decrypted |
105,989 | 28.10.2018 13:50:54 | -3,600 | 92d1de41942ebf1eefacd7b549664b6b7e6e7dc8 | Disable clearlogo for videolists (can't see title in some skins). Ensure paths always end in / | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -860,7 +860,7 @@ def build_url(pathitems=None, videoid=None, params=None, mode=None):\npathitems.insert(0, mode)\nreturn '{netloc}/{path}{qs}'.format(\nnetloc=BASE_URL,\n- path='/'.join(pathitems),\n+ path='/'.join(pathitems) + '/',\nqs=('?' + urlencode(params)) if params else '')\ndef is_numeric(string):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -144,7 +144,7 @@ def parse_art(videoid, item, raw_data):\nart = {}\nif poster:\nart['poster'] = poster\n- if clearlogo:\n+ if clearlogo and videoid.mediatype != common.VideoId.UNSPECIFIED:\nart['clearlogo'] = clearlogo\nif interesting_moment:\nart['fanart'] = interesting_moment\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -328,13 +328,14 @@ def build_episode_listing(seasonid, episode_list):\ndef create_list_item(label, icon=None, fanart=None, description=None):\n\"\"\"Create a rudimentary list item with icon and fanart\"\"\"\n# pylint: disable=unexpected-keyword-arg\n- list_item = xbmcgui.ListItem(label=label,\n- iconImage=icon or common.DEFAULT_FANART,\n- offscreen=True)\n- list_item.setProperty('fanart_image', fanart or common.DEFAULT_FANART)\n+ list_item = xbmcgui.ListItem(label=label, iconImage=icon, offscreen=True)\nlist_item.setContentLookup(False)\n+ if fanart:\n+ list_item.setProperty('fanart_image', fanart)\n+ info = {'title': label}\nif description:\n- list_item.setInfo('video', {'plot': description})\n+ info['plot'] = description\n+ list_item.setInfo('video', info)\nreturn list_item\ndef finalize_directory(items, sort_methods=None, content_type=CONTENT_FOLDER,\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Disable clearlogo for videolists (can't see title in some skins). Ensure paths always end in / |
105,989 | 28.10.2018 13:52:10 | -3,600 | 85329673d3a154070cdff0c93569ee8ff56cfe85 | Add cache locking to prevent race conditions (work with empty and volatile cache if a lock can't be acquired in a short time). Add simpler mechanism to check if an item is in my list and correct cache invalidtion | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -134,6 +134,14 @@ def single_info(videoid):\nART_PARTIAL_PATHS + [['title']]))\nreturn common.make_call('path_request', paths)\[email protected]_output(cache.CACHE_COMMON, fixed_identifier='my_list_items')\n+def mylist_items():\n+ \"\"\"Return a list of all the items currently contained in my list\"\"\"\n+ return [video_id\n+ for video_id, video in video_list(\n+ list_id_for_type('queue')).videos.iteritems()\n+ if video['queue'].get('inQueue', False)]\n+\ndef rate(videoid, rating):\n\"\"\"Rate a video on Netflix\"\"\"\ncommon.debug('Rating {} as {}'.format(videoid.value, rating))\n@@ -170,13 +178,10 @@ def _update_my_list(video_id, operation):\n'data': {\n'operation': operation,\n'videoId': int(video_id)}})\n- if common.ADDON.getSettingBool('invalidate_cache_on_mylist_modify'):\n- cache.invalidate_cache()\n- else:\n- cache.invalidate_last_location()\ncache.invalidate_entry(cache.CACHE_COMMON,\nlist_id_for_type('queue'))\ncache.invalidate_entry(cache.CACHE_COMMON, 'queue')\n+ cache.invalidate_entry(cache.CACHE_COMMON, 'my_list_items')\ncache.invalidate_entry(cache.CACHE_COMMON, 'root_lists')\ndef metadata(videoid):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -28,6 +28,8 @@ BUCKET_NAMES = [CACHE_COMMON, CACHE_GENRES, CACHE_METADATA,\nCACHE_INFOLABELS, CACHE_ARTINFO, CACHE_LIBRARY]\nBUCKETS = {}\n+BUCKET_LOCKED = 'LOCKED_BY_{}'\n+\nTTL_INFINITE = 60*60*24*365*100\ndef _init_disk_cache():\n@@ -78,6 +80,7 @@ def cache_output(bucket, identifying_param_index=0,\ntry:\nreturn get(bucket, identifier)\nexcept CacheMiss:\n+ common.debug('Cache miss on {}'.format(identifying_param_name))\noutput = func(*args, **kwargs)\nadd(bucket, identifier, output, ttl=ttl, to_disk=to_disk)\nreturn output\n@@ -147,29 +150,6 @@ def invalidate_entry(bucket, identifier):\ncommon.debug('Nothing to invalidate, {} was not in {}'\n.format(identifier, bucket))\n-def invalidate_last_location():\n- import resources.lib.api.shakti as api\n- try:\n- last_path = common.get_last_location()[1].split('/')\n- common.debug('Invalidating cache for last location {}'\n- .format(last_path))\n- if last_path[1] == 'video_list':\n- if last_path[2] in common.KNOWN_LIST_TYPES:\n- video_list_id = api.list_id_for_type(last_path[2])\n- invalidate_entry(CACHE_COMMON, video_list_id)\n- invalidate_entry(CACHE_COMMON, last_path[2])\n- else:\n- invalidate_entry(CACHE_COMMON, last_path[2])\n- elif last_path[1] == 'show':\n- if len(last_path) > 4:\n- invalidate_entry(CACHE_COMMON, last_path[4])\n- else:\n- invalidate_entry(CACHE_COMMON, last_path[2])\n- except IndexError as exc:\n- common.error(\n- 'Failed to invalidate cache entry for last location: {}'\n- .format(exc))\n-\ndef commit():\n\"\"\"Persist cache contents in window properties\"\"\"\nfor bucket, contents in BUCKETS.iteritems():\n@@ -246,20 +226,35 @@ def _window_property(bucket):\ndef _load_bucket(bucket):\n# pylint: disable=broad-except\n+ wnd_property = ''\n+ for _ in range(1,10):\n+ wnd_property = WND.getProperty(_window_property(bucket))\n+ if wnd_property.startswith(BUCKET_LOCKED[:-2]):\n+ common.debug('Waiting for release of {}'.format(bucket))\n+ xbmc.sleep(50)\n+ else:\ntry:\n- return pickle.loads(WND.getProperty(_window_property(bucket)))\n+ return pickle.loads(wnd_property)\nexcept Exception:\n- common.debug('No instance of {} found. Creating new instance...'\n+ common.debug('No instance of {} found. Creating new instance.'\n.format(bucket))\nreturn {}\n+ common.warn('Bucket {} is {}. Working with an empty instance...'\n+ .format(bucket, wnd_property))\n+ return {}\n+\ndef _persist_bucket(bucket, contents):\n# pylint: disable=broad-except\n+ lock = WND.getProperty(_window_property(bucket))\n+ if lock == BUCKET_LOCKED.format(common.PLUGIN_HANDLE):\ntry:\nWND.setProperty(_window_property(bucket), pickle.dumps(contents))\nexcept Exception as exc:\ncommon.error('Failed to persist {} to window properties: {}'\n.format(bucket, exc))\n+ else:\n+ common.warn('Bucket {} is {}. Discarding changes...'.format(bucket, lock))\ndef _clear_bucket(bucket):\nWND.clearProperty(_window_property(bucket))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -876,23 +876,6 @@ def get_local_string(string_id):\nsrc = xbmc if string_id < 30000 else ADDON\nreturn src.getLocalizedString(string_id)\n-def remember_last_location():\n- \"\"\"Write the last path and params to a window property for it\n- to be accessible to the next call\"\"\"\n- last_location = build_url(PATH.split('/'), params=REQUEST_PARAMS)\n- xbmcgui.Window(10000).setProperty('nf_last_location', last_location)\n- debug('Saved last location as {}'.format(last_location))\n-\n-def get_last_location():\n- \"\"\"Retrievethe components (base_url, path, query_params) for the last\n- location\"\"\"\n- last_url = xbmcgui.Window(10000).getProperty('nf_last_location')\n- parsed_url = urlparse(last_url)\n- return ('{scheme}://{netloc}'.format(scheme=parsed_url[0],\n- netloc=parsed_url[1]),\n- parsed_url[2][1:], # Path\n- dict(parse_qsl(parsed_url[4][1:]))) # Querystring\n-\ndef inject_video_id(path_offset, pathitems_arg='pathitems',\ninject_remaining_pathitems=False):\n\"\"\"Decorator that converts a pathitems argument into a VideoId\n@@ -916,3 +899,6 @@ def inject_video_id(path_offset, pathitems_arg='pathitems',\nreturn func(*args, **kwargs)\nreturn wrapper\nreturn injecting_decorator\n+\n+def refresh_container():\n+ xbmc.executebuiltin('Container.Refresh')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -10,6 +10,7 @@ import xbmcplugin\nimport resources.lib.common as common\nimport resources.lib.navigation as nav\n+import resources.lib.api.shakti as api\nimport resources.lib.kodi.library as library\nfrom .infolabels import add_info, add_art\n@@ -391,7 +392,7 @@ def _generate_context_menu_items(videoid, item):\nif videoid.mediatype in [common.VideoId.MOVIE, common.VideoId.SHOW]:\nlist_action = ('remove_from_list'\n- if item['queue']['inQueue']\n+ if videoid.value in api.mylist_items()\nelse 'add_to_list')\nitems.append(\n(CONTEXT_MENU_ACTIONS[list_action]['label'],\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/actions.py",
"new_path": "resources/lib/navigation/actions.py",
"diff": "@@ -53,7 +53,7 @@ class ActionExecutor(object):\nexcept (KeyError, IndexError):\ncommon.error('Cannot save autologin - invalid params')\ncache.invalidate_cache()\n- xbmc.executebuiltin('Container.Refresh')\n+ common.refresh_container()\ndef switch_account(self):\n\"\"\"Logo out of the curent account and login into another one\"\"\"\n@@ -84,4 +84,4 @@ class ActionExecutor(object):\nelse:\nraise InvalidPathError('Unknown my-list action: {}'\n.format(pathitems[0]))\n- xbmc.executebuiltin('Container.Refresh')\n+ common.refresh_container()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/directory.py",
"new_path": "resources/lib/navigation/directory.py",
"diff": "@@ -18,9 +18,6 @@ def build(pathitems, params):\ncommon.debug('Invoking directory handler {}'.format(builder.__name__))\nbuilder(pathitems=pathitems)\n- # Remember last location to be able to invalidate it in cache on\n- # certain actions\n- common.remember_last_location()\nclass DirectoryBuilder(object):\n\"\"\"Builds directory listings\"\"\"\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add cache locking to prevent race conditions (work with empty and volatile cache if a lock can't be acquired in a short time). Add simpler mechanism to check if an item is in my list and correct cache invalidtion |
105,989 | 29.10.2018 13:32:25 | -3,600 | 35792b42139d412e1f9b46d93076e8c044ba3788 | Add export (and removal) to library | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "@@ -27,16 +27,16 @@ def route(pathitems):\ncommon.debug('Routing navigation request')\nroot_handler = pathitems[0]\npass_on_params = (pathitems[1:], common.REQUEST_PARAMS)\n- if not common.PATH or root_handler == nav.MODE_DIRECTORY:\n+ if not common.PATH or root_handler == common.MODE_DIRECTORY:\ndirectory.build(*pass_on_params)\n- elif root_handler == nav.MODE_HUB:\n+ elif root_handler == common.MODE_HUB:\nhub.browse(*pass_on_params)\n- elif root_handler == nav.MODE_PLAY:\n+ elif root_handler == common.MODE_PLAY:\nplayer.play(pathitems=pathitems[1:],\nneeds_pin=common.REQUEST_PARAMS.get('pin', False))\n- elif root_handler == nav.MODE_ACTION:\n+ elif root_handler == common.MODE_ACTION:\nactions.execute(*pass_on_params)\n- elif root_handler == nav.MODE_LIBRARY:\n+ elif root_handler == common.MODE_LIBRARY:\nlibrary.execute(*pass_on_params)\nelse:\nraise nav.InvalidPathError(\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -51,6 +51,12 @@ MISC_CONTEXTS = {\n'contexts': ['similars', 'becauseYouAdded']}\n}\n+MODE_DIRECTORY = 'directory'\n+MODE_HUB = 'hub'\n+MODE_ACTION = 'action'\n+MODE_PLAY = 'play'\n+MODE_LIBRARY = 'library'\n+\ndef init_globals(argv):\n\"\"\"Initialized globally used module variables.\nNeeds to be called at start of each plugin instance!\n@@ -561,6 +567,22 @@ def noop(**kwargs):\n\"\"\"Takes everything, does nothing, classic no operation function\"\"\"\nreturn kwargs\n+def find_season(season_id, seasons, raise_exc=True):\n+ \"\"\"\n+ Get metadata for a specific season from within a nested\n+ metadata dict.\n+ :return: Season metadata. Raises KeyError if metadata for season_id\n+ does not exist.\n+ \"\"\"\n+ for season in seasons:\n+ if str(season['id']) == season_id:\n+ return season\n+ if raise_exc:\n+ raise KeyError('Metadata for season {} does not exist'\n+ .format(season_id))\n+ else:\n+ return {}\n+\ndef find_episode(episode_id, seasons, raise_exc=True):\n\"\"\"\nGet metadata for a specific episode from within a nested\n@@ -754,6 +776,19 @@ def get_path_safe(path, search_space, include_key=False, default=None):\nexcept KeyError:\nreturn default\n+def remove_path(path, search_space, remove_remnants=True):\n+ \"\"\"Remove a value from a nested dict by following a path.\n+ Also removes remaining empty dicts in the hierarchy if remove_remnants\n+ is True\"\"\"\n+ if not isinstance(path, (tuple, list)):\n+ path = [path]\n+ if len(path) == 1:\n+ del search_space[path[0]]\n+ else:\n+ remove_path(path[1:], search_space[path[0]])\n+ if remove_remnants and not search_space[path[0]]:\n+ del search_space[path[0]]\n+\ndef get_multiple_paths(path, search_space, default=None):\n\"\"\"Retrieve multiple values from a nested dict by following the path.\nThe path may branch into multiple paths at any point.\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "\"\"\"Kodi library integration\"\"\"\nfrom __future__ import unicode_literals\n+import os\n+import codecs\n+\n+import xbmc\n+\nimport resources.lib.common as common\nimport resources.lib.cache as cache\n+import resources.lib.api.shakti as api\nfrom resources.lib.navigation import InvalidPathError\nFILE_PROPS = [\n@@ -13,6 +19,10 @@ FILE_PROPS = [\n'episode', 'showtitle', 'file', 'resume', 'tvshowid', 'setid', 'tag',\n'art', 'uniqueid']\n+LIBRARY_HOME = 'library'\n+FOLDER_MOVIES = 'movies'\n+FOLDER_TV = 'shows'\n+\n__LIBRARY__ = None\nclass ItemNotFound(Exception):\n@@ -29,6 +39,12 @@ def _library():\n__LIBRARY__ = {}\nreturn __LIBRARY__\n+def library_path():\n+ \"\"\"Return the full path to the library\"\"\"\n+ return (common.ADDON.getSetting('customlibraryfolder')\n+ if common.ADDON.getSettingBool('enablelibraryfolder')\n+ else common.DATA_PATH)\n+\ndef save_library():\n\"\"\"Save the library to disk via cache\"\"\"\nif __LIBRARY__ is not None:\n@@ -53,6 +69,97 @@ def is_in_library(videoid):\n\"\"\"Return True if the video is in the local Kodi library, else False\"\"\"\nreturn common.get_path_safe(videoid.to_list(), _library()) is not None\n+def _export_movie(videoid):\n+ \"\"\"Export a movie to the library\"\"\"\n+ metadata = api.metadata(videoid)\n+ name = '{title} ({year})'.format(\n+ title=metadata['video']['title'],\n+ year=2018)\n+ _export_item(videoid, library_path(), FOLDER_MOVIES, name, name)\n+\n+def _export_tv(videoid):\n+ \"\"\"Export a complete TV show to the library\"\"\"\n+ metadata = api.metadata(videoid)\n+ if videoid.mediatype == common.VideoId.SHOW:\n+ for season in metadata['video']['seasons']:\n+ _export_season(\n+ videoid.derive_season(season['id']), metadata, season)\n+ elif videoid.mediatype == common.VideoId.SEASON:\n+ _export_season(\n+ videoid, metadata, common.find_season(videoid.seasonid, metadata))\n+ else:\n+ _export_episode(\n+ videoid, metadata, common.find_season(videoid.seasonid, metadata),\n+ common.find_episode(videoid.episodeid, metadata))\n+\n+def _export_season(videoid, metadata, season):\n+ \"\"\"Export a complete season to the library\"\"\"\n+ for episode in season['episodes']:\n+ _export_episode(\n+ videoid.derive_episode(episode['id']), metadata, season, episode)\n+\n+def _export_episode(videoid, metadata, season, episode):\n+ \"\"\"Export a single episode to the library\"\"\"\n+ showname = metadata['video']['title']\n+ filename = 'S{:02d}E{:02d}'.format(season['seq'], episode['seq'])\n+ _export_item(videoid, library_path(), FOLDER_TV, showname, filename)\n+\n+def _export_item(videoid, library, section, destination, filename):\n+ \"\"\"Create strm file for an item and add it to the library\"\"\"\n+ destination_folder = os.path.join(library, section, destination)\n+ export_filename = os.path.join(destination_folder, filename + '.strm')\n+ try:\n+ os.makedirs(xbmc.translatePath(destination_folder))\n+ with codecs.open(xbmc.translatePath(export_filename),\n+ mode='w',\n+ encoding='utf-8',\n+ errors='replace') as filehandle:\n+ filehandle.write(\n+ common.build_url(videoid=videoid, mode=common.MODE_PLAY))\n+ except OSError as exc:\n+ if exc.errno == os.errno.EEXIST:\n+ common.info('{} already exists, skipping export'\n+ .format(export_filename))\n+ else:\n+ raise\n+ _add_to_library(videoid, export_filename)\n+\n+def _add_to_library(videoid, export_filename):\n+ \"\"\"Add an exported file to the library\"\"\"\n+ library_node = _library()\n+ for id_item in videoid.to_list():\n+ if id_item not in library_node:\n+ library_node[id_item] = {}\n+ library_node = library_node[id_item]\n+ library_node['file'] = export_filename\n+ save_library()\n+\n+def _remove_tv(videoid):\n+ metadata = api.metadata(videoid)\n+ if videoid.mediatype == common.VideoId.SHOW:\n+ for season in metadata['video']['seasons']:\n+ _remove_season(\n+ videoid.derive_season(season['id']), season)\n+ elif videoid.mediatype == common.VideoId.SEASON:\n+ _remove_season(\n+ videoid, common.find_season(videoid.seasonid, metadata))\n+ else:\n+ _remove_item(videoid)\n+\n+def _remove_season(videoid, season):\n+ for episode in season['episodes']:\n+ _remove_item(videoid.derive_episode(episode['id']))\n+\n+def _remove_item(videoid):\n+ exported_filename = xbmc.translatePath(\n+ common.get_path(videoid.to_list, _library())['file'])\n+ parent_folder = os.path.dirname(exported_filename)\n+ os.remove(xbmc.translatePath(exported_filename))\n+ if not os.listdir(parent_folder):\n+ os.remove(parent_folder)\n+ common.remove_path(videoid.to_list(), _library())\n+ save_library()\n+\ndef execute(pathitems, params):\n\"\"\"Execute an action as specified by the path\"\"\"\ntry:\n@@ -77,14 +184,26 @@ class ActionExecutor(object):\[email protected]_video_id(path_offset=0)\ndef export(self, videoid):\n\"\"\"Export an item to the Kodi library\"\"\"\n- # TODO: Implement library export\n- pass\n+ if videoid.mediatype == common.VideoId.MOVIE:\n+ _export_movie(videoid)\n+ elif videoid.mediatype in [common.VideoId.SHOW,\n+ common.VideoId.SEASON,\n+ common.VideoId.EPISODE]:\n+ _export_tv(videoid)\n+ else:\n+ raise ValueError('Cannot export {}'.format(videoid))\[email protected]_video_id(path_offset=0)\ndef remove(self, videoid):\n\"\"\"Remove an item from the Kodi library\"\"\"\n- # TODO: Implement library removal\n- pass\n+ if videoid.mediatype == common.VideoId.MOVIE:\n+ _remove_item(videoid)\n+ elif videoid.mediatype in [common.VideoId.SHOW,\n+ common.VideoId.SEASON,\n+ common.VideoId.EPISODE]:\n+ _remove_tv(videoid)\n+ else:\n+ raise ValueError('Cannot remove {}'.format(videoid))\[email protected]_video_id(path_offset=0)\ndef update(self, videoid):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -9,7 +9,6 @@ import xbmcgui\nimport xbmcplugin\nimport resources.lib.common as common\n-import resources.lib.navigation as nav\nimport resources.lib.api.shakti as api\nimport resources.lib.kodi.library as library\n@@ -37,29 +36,33 @@ CONTEXT_MENU_ACTIONS = {\n'export': {\n'label': common.get_local_string(30018),\n'url': (lambda videoid:\n- common.build_url(['export'], videoid, mode=nav.MODE_LIBRARY))},\n+ common.build_url(['export'], videoid,\n+ mode=common.MODE_LIBRARY))},\n'remove': {\n'label': common.get_local_string(30030),\n'url': (lambda videoid:\n- common.build_url(['remove'], videoid, mode=nav.MODE_LIBRARY))},\n+ common.build_url(['remove'], videoid,\n+ mode=common.MODE_LIBRARY))},\n'update': {\n'label': common.get_local_string(30030),\n'url': (lambda videoid:\n- common.build_url(['update'], videoid, mode=nav.MODE_LIBRARY))},\n+ common.build_url(['update'], videoid,\n+ mode=common.MODE_LIBRARY))},\n'rate': {\n'label': common.get_local_string(30019),\n'url': (lambda videoid:\n- common.build_url(['rate'], videoid, mode=nav.MODE_ACTION))},\n+ common.build_url(['rate'], videoid,\n+ mode=common.MODE_ACTION))},\n'add_to_list': {\n'label': common.get_local_string(30021),\n'url': (lambda videoid:\ncommon.build_url(['my_list', 'add'], videoid,\n- mode=nav.MODE_ACTION))},\n+ mode=common.MODE_ACTION))},\n'remove_from_list': {\n'label': common.get_local_string(30020),\n'url': (lambda videoid:\ncommon.build_url(['my_list', 'remove'], videoid,\n- mode=nav.MODE_ACTION))},\n+ mode=common.MODE_ACTION))},\n}\ndef custom_viewmode(viewtype):\n@@ -112,14 +115,14 @@ def build_profiles_listing(profiles):\nautologin_url = common.build_url(\npathitems=['save_autologin', profile_guid],\nparams={'autologin_user': enc_profile_name},\n- mode=nav.MODE_ACTION)\n+ mode=common.MODE_ACTION)\nlist_item.addContextMenuItems(\nitems=[(common.get_local_string(30053),\n'RunPlugin({})'.format(autologin_url))])\ndirectory_items.append(\n(common.build_url(pathitems=['home'],\nparams={'profile_id': profile_guid},\n- mode=nav.MODE_DIRECTORY),\n+ mode=common.MODE_DIRECTORY),\nlist_item,\nTrue))\n@@ -158,13 +161,14 @@ def build_main_menu_listing(lolomo):\nadd_art(user_list.id, list_item, user_list.artitem)\ndirectory_items.append(\n(common.build_url(\n- ['video_list', user_list['context']], mode=nav.MODE_DIRECTORY),\n+ ['video_list', user_list['context']],\n+ mode=common.MODE_DIRECTORY),\nlist_item,\nTrue))\nfor context_type, data in common.MISC_CONTEXTS.iteritems():\ndirectory_items.append(\n- (common.build_url([context_type], mode=nav.MODE_DIRECTORY),\n+ (common.build_url([context_type], mode=common.MODE_DIRECTORY),\ncreate_list_item(common.get_local_string(data['label_id']),\nicon=data['icon'],\ndescription=common.get_local_string(\n@@ -173,7 +177,7 @@ def build_main_menu_listing(lolomo):\nfor menu_item in ADDITIONAL_MAIN_MENU_ITEMS:\ndirectory_items.append(\n- (common.build_url(menu_item['path'], mode=nav.MODE_DIRECTORY),\n+ (common.build_url(menu_item['path'], mode=common.MODE_DIRECTORY),\ncreate_list_item(menu_item['label'],\nicon=menu_item['icon'],\ndescription=menu_item['description']),\n@@ -204,7 +208,7 @@ def build_lolomo_listing(lolomo, contexts=None):\nadd_art(video_list.id, list_item, video_list.artitem)\ndirectory_items.append(\n(common.build_url(\n- ['video_list', video_list_id], mode=nav.MODE_DIRECTORY,\n+ ['video_list', video_list_id], mode=common.MODE_DIRECTORY,\nparams=params),\nlist_item,\nTrue))\n@@ -232,11 +236,11 @@ def build_video_listing(video_list, genre_id=None):\n.get('level', 1001)) >= 1000\nurl = common.build_url(videoid=videoid,\nparams={'pin': needs_pin},\n- mode=(nav.MODE_PLAY\n+ mode=(common.MODE_PLAY\nif is_movie\n- else nav.MODE_DIRECTORY))\n+ else common.MODE_DIRECTORY))\nlist_item.addContextMenuItems(\n- _generate_context_menu_items(videoid, video))\n+ _generate_context_menu_items(videoid))\ndirectory_items.append(\n(url,\nlist_item,\n@@ -245,7 +249,7 @@ def build_video_listing(video_list, genre_id=None):\nif genre_id:\ndirectory_items.append(\n(common.build_url(pathitems=['genres', genre_id],\n- mode=nav.MODE_DIRECTORY),\n+ mode=common.MODE_DIRECTORY),\ncreate_list_item(common.get_local_string(30088),\nicon='DefaultAddSource.png',\ndescription=common.get_local_string(30090)),\n@@ -253,7 +257,7 @@ def build_video_listing(video_list, genre_id=None):\n# TODO: Implement browsing of subgenres\n# directory_items.append(\n# (common.build_url(pathitems=['genres', genre_id, 'subgenres'],\n- # mode=nav.MODE_DIRECTORY),\n+ # mode=common.MODE_DIRECTORY),\n# create_list_item('Browse subgenres...'),\n# True))\nfinalize_directory(\n@@ -280,9 +284,9 @@ def build_season_listing(tvshowid, season_list):\nadd_info(seasonid, list_item, season, season_list.data)\nadd_art(tvshowid, list_item, season_list.tvshow)\nlist_item.addContextMenuItems(\n- _generate_context_menu_items(seasonid, season))\n+ _generate_context_menu_items(seasonid))\ndirectory_items.append(\n- (common.build_url(videoid=seasonid, mode=nav.MODE_DIRECTORY),\n+ (common.build_url(videoid=seasonid, mode=common.MODE_DIRECTORY),\nlist_item,\nTrue))\nfinalize_directory(\n@@ -308,9 +312,9 @@ def build_episode_listing(seasonid, episode_list):\nadd_info(episodeid, list_item, episode, episode_list.data)\nadd_art(episodeid, list_item, episode)\nlist_item.addContextMenuItems(\n- _generate_context_menu_items(episodeid, episode))\n+ _generate_context_menu_items(episodeid))\ndirectory_items.append(\n- (common.build_url(videoid=episodeid, mode=nav.MODE_PLAY),\n+ (common.build_url(videoid=episodeid, mode=common.MODE_PLAY),\nlist_item,\nFalse))\nfinalize_directory(\n@@ -366,7 +370,7 @@ def finalize_directory(items, sort_methods=None, content_type=CONTENT_FOLDER,\nhandle=common.PLUGIN_HANDLE,\nupdateListing=refresh)\n-def _generate_context_menu_items(videoid, item):\n+def _generate_context_menu_items(videoid):\nitems = []\nif library.is_in_library(videoid):\nitems.append(\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/__init__.py",
"new_path": "resources/lib/navigation/__init__.py",
"diff": "\"\"\"Navigation handling\"\"\"\nfrom __future__ import unicode_literals\n-MODE_DIRECTORY = 'directory'\n-MODE_HUB = 'hub'\n-MODE_ACTION = 'action'\n-MODE_PLAY = 'play'\n-MODE_LIBRARY = 'library'\n-\nclass InvalidPathError(Exception):\n\"\"\"The requested path is invalid and could not be routed\"\"\"\npass\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add export (and removal) to library |
105,989 | 29.10.2018 18:29:35 | -3,600 | 28eac3d754919edd9f930370c7c29b60f5b3c781 | Refine library export/remove/update (add GUI feedback). Reduce complexity in several locations | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "@@ -15,12 +15,12 @@ import xbmcplugin\nimport resources.lib.cache as cache\nimport resources.lib.common as common\nimport resources.lib.kodi.ui as ui\n-import resources.lib.kodi.library as library\nimport resources.lib.navigation as nav\nimport resources.lib.navigation.directory as directory\nimport resources.lib.navigation.hub as hub\nimport resources.lib.navigation.player as player\nimport resources.lib.navigation.actions as actions\n+import resources.lib.navigation.library as library\ndef route(pathitems):\n\"\"\"Route to the appropriate handler\"\"\"\n@@ -28,16 +28,15 @@ def route(pathitems):\nroot_handler = pathitems[0]\npass_on_params = (pathitems[1:], common.REQUEST_PARAMS)\nif not common.PATH or root_handler == common.MODE_DIRECTORY:\n- directory.build(*pass_on_params)\n+ nav.execute(directory.DirectoryBuilder, *pass_on_params)\nelif root_handler == common.MODE_HUB:\nhub.browse(*pass_on_params)\nelif root_handler == common.MODE_PLAY:\n- player.play(pathitems=pathitems[1:],\n- needs_pin=common.REQUEST_PARAMS.get('pin', False))\n+ player.play(pathitems=pathitems[1:])\nelif root_handler == common.MODE_ACTION:\n- actions.execute(*pass_on_params)\n+ nav.execute(actions.AddonActionExecutor, *pass_on_params)\nelif root_handler == common.MODE_LIBRARY:\n- library.execute(*pass_on_params)\n+ nav.execute(library.LibraryActionExecutor, *pass_on_params)\nelse:\nraise nav.InvalidPathError(\n'No root handler for path {}'.format('/'.join(pathitems)))\n@@ -58,4 +57,3 @@ if __name__ == '__main__':\nxbmcplugin.endOfDirectory(handle=common.PLUGIN_HANDLE, succeeded=False)\ncache.commit()\n- library.save_library()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -11,6 +11,7 @@ try:\nexcept ImportError:\nimport pickle\n+import xbmc\nimport xbmcgui\nimport resources.lib.common as common\n@@ -64,28 +65,37 @@ def cache_output(bucket, identifying_param_index=0,\ndef caching_decorator(func):\n@wraps(func)\ndef wrapper(*args, **kwargs):\n+ identifier = _get_identifier(fixed_identifier,\n+ identifying_param_name,\n+ kwargs,\n+ identifying_param_index,\n+ args)\n+ try:\n+ return get(bucket, identifier)\n+ except CacheMiss:\n+ common.debug('Cache miss on {}'.format(identifying_param_name))\n+ output = func(*args, **kwargs)\n+ add(bucket, identifier, output, ttl=ttl, to_disk=to_disk)\n+ return output\n+ return wrapper\n+ return caching_decorator\n+\n+def _get_identifier(fixed_identifier, identifying_param_name, kwargs,\n+ identifying_param_index, args):\n+ \"\"\"Return the identifier to use with the caching_decorator\"\"\"\nif fixed_identifier:\n# Use the identifier that's statically defined in the applied\n# decorator isntead of one of the parameters' value\n- identifier = fixed_identifier\n+ return fixed_identifier\nelse:\ntry:\n# prefer keyword over positional arguments\n- identifier = kwargs.get(\n- identifying_param_name, args[identifying_param_index])\n+ return kwargs.get(identifying_param_name,\n+ args[identifying_param_index])\nexcept IndexError:\ncommon.error(\n'Invalid cache configuration.'\n'Cannot determine identifier from params')\n- try:\n- return get(bucket, identifier)\n- except CacheMiss:\n- common.debug('Cache miss on {}'.format(identifying_param_name))\n- output = func(*args, **kwargs)\n- add(bucket, identifier, output, ttl=ttl, to_disk=to_disk)\n- return output\n- return wrapper\n- return caching_decorator\n# def inject_from_cache(bucket, injection_param,\n# identifying_param_index=0,\n@@ -106,7 +116,8 @@ def cache_output(bucket, identifying_param_index=0,\n# try:\n# # prefer keyword over positional arguments\n# identifier = kwargs.get(\n-# identifying_param_name, args[identifying_param_index])\n+# identifying_param_name,\n+# args[identifying_param_index])\n# except IndexError:\n# common.error(\n# 'Invalid cache configuration.'\n@@ -175,7 +186,7 @@ def get_from_disk(bucket, identifier):\ntry:\nwith open(cache_filename, 'r') as cache_file:\ncache_entry = pickle.load(cache_file)\n- except Exception as exc:\n+ except:\nraise CacheMiss()\nadd(bucket, identifier, cache_entry['content'])\nreturn cache_entry\n@@ -243,7 +254,6 @@ def _load_bucket(bucket):\n.format(bucket, wnd_property))\nreturn {}\n-\ndef _persist_bucket(bucket, contents):\n# pylint: disable=broad-except\nlock = WND.getProperty(_window_property(bucket))\n@@ -254,7 +264,8 @@ def _persist_bucket(bucket, contents):\ncommon.error('Failed to persist {} to window properties: {}'\n.format(bucket, exc))\nelse:\n- common.warn('Bucket {} is {}. Discarding changes...'.format(bucket, lock))\n+ common.warn('Bucket {} is {}. Discarding changes...'\n+ .format(bucket, lock))\ndef _clear_bucket(bucket):\nWND.clearProperty(_window_property(bucket))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -517,16 +517,9 @@ def check_folder_path(path):\nIf not correct it (makes sure xbmcvfs.exists is working correct)\n\"\"\"\nend = ''\n- if isinstance(path, unicode):\n- check = path.encode('ascii', 'ignore')\n- if '/' in check and not str(check).endswith('/'):\n- end = u'/'\n- if '\\\\' in check and not str(check).endswith('\\\\'):\n- end = u'\\\\'\n- else:\n- if '/' in path and not str(path).endswith('/'):\n+ if '/' in path and not path.endswith('/'):\nend = '/'\n- if '\\\\' in path and not str(path).endswith('\\\\'):\n+ if '\\\\' in path and not path.endswith('\\\\'):\nend = '\\\\'\nreturn path + end\n@@ -860,12 +853,7 @@ def addonsignals_return_call(func):\nhandles catching, conversion and forwarding of exceptions\"\"\"\n# pylint: disable=broad-except\ntry:\n- if isinstance(data, dict):\n- result = func(instance, **data)\n- elif data is not None:\n- result = func(instance, data)\n- else:\n- result = func(instance)\n+ result = _call(instance, func, data)\nexcept Exception as exc:\nerror('AddonSignals callback raised exception: {exc}', exc)\nerror(traceback.format_exc())\n@@ -880,6 +868,13 @@ def addonsignals_return_call(func):\nsignal=_signal_name(func), source_id=ADDON_ID, data=result)\nreturn make_return_call\n+def _call(instance, func, data):\n+ if isinstance(data, dict):\n+ return func(instance, **data)\n+ elif data is not None:\n+ return func(instance, data)\n+ return func(instance)\n+\ndef _signal_name(func):\nreturn func.__name__\n@@ -936,4 +931,34 @@ def inject_video_id(path_offset, pathitems_arg='pathitems',\nreturn injecting_decorator\ndef refresh_container():\n+ \"\"\"Refresh the current container\"\"\"\nxbmc.executebuiltin('Container.Refresh')\n+\n+def execute_tasks(title, tasks, task_handler, notify_errors=False, **kwargs):\n+ \"\"\"Run all tasks through task_handler and display a progress\n+ dialog in the GUI. Additional kwargs will be passed into task_handler\n+ on each invocation.\n+ Returns a list of errors that occured during execution of tasks.\"\"\"\n+ errors = []\n+ progress = xbmcgui.DialogProgress()\n+ progress.create(title)\n+ for task_num, task in tasks:\n+ # pylint: disable=broad-except\n+ task_title = task.get('title', 'Unknown Task')\n+ progress.update(percent=int(task_num / len(tasks) * 100),\n+ line1=task_title)\n+ xbmc.sleep(100)\n+ if progress.iscanceled():\n+ break\n+ try:\n+ task_handler(task, **kwargs)\n+ except Exception as exc:\n+ errors.append({\n+ 'task_title': task_title,\n+ 'error': ': '.join((type(exc).__name__, exc.message))})\n+ if notify_errors and errors:\n+ xbmcgui.Dialog().ok(get_local_string(0),\n+ '\\n'.join(['{} ({})'.format(err['task_title'],\n+ err['error'])\n+ for err in errors]))\n+ return errors\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -57,19 +57,26 @@ def parse_info(videoid, item, raw_data):\n', '.join(item.contained_titles))\n}, {}\n- mediatype = videoid.mediatype\n- if mediatype == common.VideoId.SHOW:\n- # Type from Netflix doesn't match Kodi's expectations\n- mediatype = 'tvshow'\n+ infos = {'mediatype': ('tvshow'\n+ if videoid.mediatype == common.VideoId.SHOW\n+ else videoid.mediatype)}\n+ if videoid.mediatype in [common.VideoId.SHOW, common.VideoId.SEASON,\n+ common.VideoId.EPISODE]:\n+ infos['tvshowtitle'] = raw_data['videos'][videoid.tvshowid]['title']\n- infos = {'mediatype': mediatype}\n- quality_infos = get_quality_infos(item)\n+ parse_atomic_infos(item, infos)\n+ parse_referenced_infos(item, infos, raw_data)\n- if videoid.mediatype == common.VideoId.SHOW:\n- infos['tvshowtitle'] = item['title']\n- elif videoid.mediatype in [common.VideoId.SEASON, common.VideoId.EPISODE]:\n- infos['tvshowtitle'] = raw_data['videos'][videoid.tvshowid]['title']\n+ infos['tag'] = [tagdef['name']\n+ for tagdef\n+ in item.get('tags', {}).itervalues()\n+ if isinstance(tagdef.get('name', {}), unicode)]\n+ return infos, get_quality_infos(item)\n+\n+def parse_atomic_infos(item, infos):\n+ \"\"\"Parse those infos into infolabels that are directly accesible from\n+ the item dict\"\"\"\nfor target, source in paths.INFO_MAPPINGS.iteritems():\nvalue = (common.get_path_safe(source, item)\nif isinstance(source, list)\n@@ -82,18 +89,17 @@ def parse_info(videoid, item, raw_data):\nif target in paths.INFO_TRANSFORMATIONS:\nvalue = paths.INFO_TRANSFORMATIONS[target](value)\ninfos[target] = value\n+ return infos\n+def parse_referenced_infos(item, infos, raw_data):\n+ \"\"\"Parse those infos into infolabels that need their references\n+ resolved within the raw data\"\"\"\nfor target, source in paths.REFERENCE_MAPPINGS.iteritems():\ninfos[target] = [\nperson['name']\nfor _, person\nin paths.resolve_refs(item.get(source, {}), raw_data)]\n-\n- infos['tag'] = [tagdef['name']\n- for tagdef\n- in item.get('tags', {}).itervalues()\n- if isinstance(tagdef.get('name', {}), unicode)]\n- return infos, quality_infos\n+ return infos\ndef get_quality_infos(item):\n\"\"\"Return audio and video quality infolabels\"\"\"\n@@ -125,34 +131,39 @@ def parse_art(videoid, item, raw_data):\n\"\"\"Parse art info from a path request response to Kodi art infolabels\"\"\"\nboxarts = common.get_multiple_paths(\npaths.ART_PARTIAL_PATHS[0] + ['url'], item)\n- boxart_large = boxarts[paths.ART_SIZE_FHD]\n- boxart_small = boxarts[paths.ART_SIZE_SD]\n- poster = boxarts[paths.ART_SIZE_POSTER]\ninteresting_moment = common.get_multiple_paths(\npaths.ART_PARTIAL_PATHS[1] + ['url'], item)[paths.ART_SIZE_FHD]\nclearlogo = common.get_path_safe(\npaths.ART_PARTIAL_PATHS[3] + ['url'], item)\nfanart = common.get_path_safe(\npaths.ART_PARTIAL_PATHS[4] + [0, 'url'], item)\n- if boxart_large or boxart_small:\n- art = {\n- 'thumb': boxart_large or boxart_small,\n- 'landscape': boxart_large or boxart_small,\n- 'fanart': boxart_large or boxart_small,\n- }\n- else:\n+ return assign_art(videoid,\n+ boxarts[paths.ART_SIZE_FHD],\n+ boxarts[paths.ART_SIZE_SD],\n+ boxarts[paths.ART_SIZE_POSTER],\n+ interesting_moment,\n+ clearlogo,\n+ fanart)\n+\n+def assign_art(videoid, boxart_large, boxart_small, poster, interesting_moment,\n+ clearlogo, fanart):\n+ \"\"\"Assign the art available from Netflix to appropriate Kodi art\"\"\"\n+ # pylint: disable=too-many-arguments\nart = {}\n- if poster:\n- art['poster'] = poster\n- if clearlogo and videoid.mediatype != common.VideoId.UNSPECIFIED:\n- art['clearlogo'] = clearlogo\n- if interesting_moment:\n- art['fanart'] = interesting_moment\n- if item.get('summary', {}).get('type') == 'episode':\n- art['thumb'] = interesting_moment\n- art['landscape'] = interesting_moment\n- if fanart:\n- art['fanart'] = fanart\n+ art['poster'] = poster or ''\n+ art['clearlogo'] = (clearlogo\n+ if videoid.mediatype != common.VideoId.UNSPECIFIED\n+ else '') or ''\n+ art['thumb'] = ((interesting_moment\n+ if videoid.mediatype == common.VideoId.EPISODE else '') or\n+ boxart_large or\n+ boxart_small)\n+ art['landscape'] = art['thumb']\n+ art['fanart'] = (fanart or\n+ interesting_moment or\n+ boxart_large or\n+ boxart_small or\n+ '')\nreturn art\ndef add_info_from_netflix(videoid, list_item):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "@@ -10,7 +10,6 @@ import xbmc\nimport resources.lib.common as common\nimport resources.lib.cache as cache\nimport resources.lib.api.shakti as api\n-from resources.lib.navigation import InvalidPathError\nFILE_PROPS = [\n'title', 'genre', 'year', 'rating', 'duration', 'playcount', 'director',\n@@ -69,45 +68,65 @@ def is_in_library(videoid):\n\"\"\"Return True if the video is in the local Kodi library, else False\"\"\"\nreturn common.get_path_safe(videoid.to_list(), _library()) is not None\n-def _export_movie(videoid):\n- \"\"\"Export a movie to the library\"\"\"\n+def compile_tasks(videoid):\n+ \"\"\"Compile a list of tasks for items based on the videoid.\n+ If videoid represents a show or season, tasks will be generated for\n+ all contained seasons and episodes\"\"\"\nmetadata = api.metadata(videoid)\n+ if videoid.mediatype == common.VideoId.MOVIE:\nname = '{title} ({year})'.format(\ntitle=metadata['video']['title'],\n- year=2018)\n- _export_item(videoid, library_path(), FOLDER_MOVIES, name, name)\n-\n-def _export_tv(videoid):\n- \"\"\"Export a complete TV show to the library\"\"\"\n- metadata = api.metadata(videoid)\n- if videoid.mediatype == common.VideoId.SHOW:\n- for season in metadata['video']['seasons']:\n- _export_season(\n+ year=metadata['video']['year'])\n+ return [_create_item_task(name, FOLDER_MOVIES, videoid, name, name)]\n+ elif videoid.mediatype == common.VideoId.SHOW:\n+ return [\n+ task for task in (\n+ _compile_season_tasks(\nvideoid.derive_season(season['id']), metadata, season)\n+ for season in metadata['video']['seasons'])]\nelif videoid.mediatype == common.VideoId.SEASON:\n- _export_season(\n- videoid, metadata, common.find_season(videoid.seasonid, metadata))\n- else:\n- _export_episode(\n- videoid, metadata, common.find_season(videoid.seasonid, metadata),\n- common.find_episode(videoid.episodeid, metadata))\n+ return _compile_season_tasks(\n+ videoid, metadata, common.find_season(videoid.seasonid,\n+ metadata))\n+ elif videoid.mediatype == common.VideoId.EPISODE:\n+ return [_create_episode_task(videoid, metadata)]\n+\n+ raise ValueError('Cannot handle {}'.format(videoid))\n-def _export_season(videoid, metadata, season):\n- \"\"\"Export a complete season to the library\"\"\"\n- for episode in season['episodes']:\n- _export_episode(\n- videoid.derive_episode(episode['id']), metadata, season, episode)\n+def _compile_season_tasks(videoid, metadata, season):\n+ \"\"\"Compile a list of task items for all episodes in a season\"\"\"\n+ return [_create_episode_task(videoid.derive_episode(episode['id']),\n+ metadata, season, episode)\n+ for episode in season['episodes']]\n-def _export_episode(videoid, metadata, season, episode):\n+def _create_episode_task(videoid, metadata, season=None, episode=None):\n\"\"\"Export a single episode to the library\"\"\"\nshowname = metadata['video']['title']\n+ season = season or common.find_season(\n+ videoid.seasonid, metadata['video']['seasons'])\n+ episode = episode or common.find_episode(\n+ videoid.episodeid, metadata['video']['seasons'])\n+ title = episode['title']\nfilename = 'S{:02d}E{:02d}'.format(season['seq'], episode['seq'])\n- _export_item(videoid, library_path(), FOLDER_TV, showname, filename)\n-\n-def _export_item(videoid, library, section, destination, filename):\n+ title = ' - '.join((showname, filename, title))\n+ return _create_item_task(title, FOLDER_TV, videoid, showname, filename)\n+\n+def _create_item_task(title, section, videoid, destination, filename):\n+ \"\"\"Create a single task item\"\"\"\n+ return {\n+ 'title': title,\n+ 'section': section,\n+ 'videoid': videoid,\n+ 'destination': destination,\n+ 'filename': filename\n+ }\n+\n+def export_item(item_task, library_home):\n\"\"\"Create strm file for an item and add it to the library\"\"\"\n- destination_folder = os.path.join(library, section, destination)\n- export_filename = os.path.join(destination_folder, filename + '.strm')\n+ destination_folder = os.path.join(\n+ library_home, item_task['section'], item_task['destination'])\n+ export_filename = os.path.join(\n+ destination_folder, item_task['filename'] + '.strm')\ntry:\nos.makedirs(xbmc.translatePath(destination_folder))\nwith codecs.open(xbmc.translatePath(export_filename),\n@@ -115,14 +134,15 @@ def _export_item(videoid, library, section, destination, filename):\nencoding='utf-8',\nerrors='replace') as filehandle:\nfilehandle.write(\n- common.build_url(videoid=videoid, mode=common.MODE_PLAY))\n+ common.build_url(videoid=item_task['videoid'],\n+ mode=common.MODE_PLAY))\nexcept OSError as exc:\nif exc.errno == os.errno.EEXIST:\ncommon.info('{} already exists, skipping export'\n.format(export_filename))\nelse:\nraise\n- _add_to_library(videoid, export_filename)\n+ _add_to_library(item_task['videoid'], export_filename)\ndef _add_to_library(videoid, export_filename):\n\"\"\"Add an exported file to the library\"\"\"\n@@ -134,79 +154,19 @@ def _add_to_library(videoid, export_filename):\nlibrary_node['file'] = export_filename\nsave_library()\n-def _remove_tv(videoid):\n- metadata = api.metadata(videoid)\n- if videoid.mediatype == common.VideoId.SHOW:\n- for season in metadata['video']['seasons']:\n- _remove_season(\n- videoid.derive_season(season['id']), season)\n- elif videoid.mediatype == common.VideoId.SEASON:\n- _remove_season(\n- videoid, common.find_season(videoid.seasonid, metadata))\n- else:\n- _remove_item(videoid)\n-\n-def _remove_season(videoid, season):\n- for episode in season['episodes']:\n- _remove_item(videoid.derive_episode(episode['id']))\n-\n-def _remove_item(videoid):\n+def remove_item(item_task):\n+ \"\"\"Remove an item from the library and delete if from disk\"\"\"\n+ id_path = item_task['videoid'].to_list()\nexported_filename = xbmc.translatePath(\n- common.get_path(videoid.to_list, _library())['file'])\n+ common.get_path(id_path, _library())['file'])\nparent_folder = os.path.dirname(exported_filename)\nos.remove(xbmc.translatePath(exported_filename))\nif not os.listdir(parent_folder):\nos.remove(parent_folder)\n- common.remove_path(videoid.to_list(), _library())\n+ common.remove_path(id_path, _library())\nsave_library()\n-def execute(pathitems, params):\n- \"\"\"Execute an action as specified by the path\"\"\"\n- try:\n- executor = ActionExecutor(params).__getattribute__(pathitems[0])\n- except (AttributeError, IndexError):\n- raise InvalidPathError('Unknown action {}'.format('/'.join(pathitems)))\n-\n- common.debug('Invoking action executor {}'.format(executor.__name__))\n-\n- if len(pathitems) > 1:\n- executor(pathitems=pathitems[1:])\n- else:\n- executor()\n-\n-class ActionExecutor(object):\n- \"\"\"Executes actions\"\"\"\n- # pylint: disable=no-self-use\n- def __init__(self, params):\n- common.debug('Initializing action executor: {}'.format(params))\n- self.params = params\n-\n- @common.inject_video_id(path_offset=0)\n- def export(self, videoid):\n- \"\"\"Export an item to the Kodi library\"\"\"\n- if videoid.mediatype == common.VideoId.MOVIE:\n- _export_movie(videoid)\n- elif videoid.mediatype in [common.VideoId.SHOW,\n- common.VideoId.SEASON,\n- common.VideoId.EPISODE]:\n- _export_tv(videoid)\n- else:\n- raise ValueError('Cannot export {}'.format(videoid))\n-\n- @common.inject_video_id(path_offset=0)\n- def remove(self, videoid):\n- \"\"\"Remove an item from the Kodi library\"\"\"\n- if videoid.mediatype == common.VideoId.MOVIE:\n- _remove_item(videoid)\n- elif videoid.mediatype in [common.VideoId.SHOW,\n- common.VideoId.SEASON,\n- common.VideoId.EPISODE]:\n- _remove_tv(videoid)\n- else:\n- raise ValueError('Cannot remove {}'.format(videoid))\n-\n- @common.inject_video_id(path_offset=0)\n- def update(self, videoid):\n- \"\"\"Update an item in the Kodi library\"\"\"\n- # TODO: Implement library updates\n- pass\n+def update_item(item_task, library_home):\n+ \"\"\"Remove and then re-export an item to the Kodi library\"\"\"\n+ remove_item(item_task)\n+ export_item(item_task, library_home)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/__init__.py",
"new_path": "resources/lib/navigation/__init__.py",
"diff": "\"\"\"Navigation handling\"\"\"\nfrom __future__ import unicode_literals\n+import resources.lib.common as common\n+\nclass InvalidPathError(Exception):\n\"\"\"The requested path is invalid and could not be routed\"\"\"\npass\n+\n+def execute(executor_type, pathitems, params):\n+ \"\"\"Execute an action as specified by the path\"\"\"\n+ try:\n+ executor = executor_type(params).__getattribute__(\n+ pathitems[0] if pathitems else 'root')\n+ except AttributeError:\n+ raise InvalidPathError('Unknown action {}'.format('/'.join(pathitems)))\n+\n+ common.debug('Invoking action executor {}'.format(executor.__name__))\n+\n+ if len(pathitems) > 1:\n+ executor(pathitems=pathitems[1:])\n+ else:\n+ executor()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/actions.py",
"new_path": "resources/lib/navigation/actions.py",
"diff": "\"\"\"Navigation handler for actions\"\"\"\nfrom __future__ import unicode_literals\n-import xbmc\nfrom xbmcaddon import Addon\nimport resources.lib.common as common\n@@ -11,25 +10,12 @@ import resources.lib.api.shakti as api\nimport resources.lib.kodi.ui as ui\nfrom resources.lib.navigation import InvalidPathError\n-def execute(pathitems, params):\n- \"\"\"Execute an action as specified by the path\"\"\"\n- try:\n- executor = ActionExecutor(params).__getattribute__(pathitems[0])\n- except (AttributeError, IndexError):\n- raise InvalidPathError('Unknown action {}'.format('/'.join(pathitems)))\n-\n- common.debug('Invoking action executor {}'.format(executor.__name__))\n-\n- if len(pathitems) > 1:\n- executor(pathitems=pathitems[1:])\n- else:\n- executor()\n-\n-class ActionExecutor(object):\n+class AddonActionExecutor(object):\n\"\"\"Executes actions\"\"\"\n# pylint: disable=no-self-use\ndef __init__(self, params):\n- common.debug('Initializing action executor: {}'.format(params))\n+ common.debug('Initializing AddonActionExecutor: {}'\n+ .format(params))\nself.params = params\ndef logout(self):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/directory.py",
"new_path": "resources/lib/navigation/directory.py",
"diff": "@@ -5,19 +5,6 @@ from __future__ import unicode_literals\nimport resources.lib.common as common\nimport resources.lib.api.shakti as api\nimport resources.lib.kodi.listings as listings\n-import resources.lib.kodi.ui as ui\n-from resources.lib.navigation import InvalidPathError\n-\n-def build(pathitems, params):\n- \"\"\"Build a directory listing for the given path\"\"\"\n- try:\n- builder = DirectoryBuilder(params).__getattribute__(\n- pathitems[0] if pathitems else 'root')\n- except AttributeError:\n- raise InvalidPathError('Cannot route {}'.format('/'.join(pathitems)))\n-\n- common.debug('Invoking directory handler {}'.format(builder.__name__))\n- builder(pathitems=pathitems)\nclass DirectoryBuilder(object):\n\"\"\"Builds directory listings\"\"\"\n@@ -58,10 +45,10 @@ class DirectoryBuilder(object):\ndef video_list(self, pathitems):\n\"\"\"Show a video list\"\"\"\n# Use predefined names instead of dynamic IDs for common video lists\n- if pathitems[1] in common.KNOWN_LIST_TYPES:\n- list_id = api.list_id_for_type(pathitems[1])\n+ if pathitems[0] in common.KNOWN_LIST_TYPES:\n+ list_id = api.list_id_for_type(pathitems[0])\nelse:\n- list_id = pathitems[1]\n+ list_id = pathitems[0]\nlistings.build_video_listing(api.video_list(list_id),\nself.params.get('genreId'))\n@@ -78,13 +65,13 @@ class DirectoryBuilder(object):\n\"\"\"Show episodes of a season\"\"\"\nlistings.build_episode_listing(videoid, api.episodes(videoid))\n- def genres(self, pathitems):\n+ def genres(self, pathitems=None):\n\"\"\"Show video lists for a genre\"\"\"\n- if len(pathitems) < 2:\n+ if not pathitems:\nlolomo = api.root_lists()\ncontexts = common.MISC_CONTEXTS['genres']['contexts']\nelse:\n- lolomo = api.genre(pathitems[1])\n+ lolomo = api.genre(pathitems[0])\ncontexts = None\nlistings.build_lolomo_listing(lolomo, contexts)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/player.py",
"new_path": "resources/lib/navigation/player.py",
"diff": "@@ -35,7 +35,7 @@ class InputstreamError(Exception):\npass\[email protected]_video_id(path_offset=0)\n-def play(videoid, needs_pin):\n+def play(videoid):\n\"\"\"Play an episode or movie as specified by the path\"\"\"\nmetadata = api.metadata(videoid)\ntimeline_markers = get_timeline_markers(metadata)\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Refine library export/remove/update (add GUI feedback). Reduce complexity in several locations |
105,989 | 29.10.2018 18:39:13 | -3,600 | be79fc863c228084806cecf2570d35c5583edf72 | Add new file forgotten on last commit | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/navigation/library.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Navigation handler for library actions\"\"\"\n+from __future__ import unicode_literals\n+\n+import resources.lib.common as common\n+import resources.lib.kodi.library as library\n+\n+class LibraryActionExecutor(object):\n+ \"\"\"Executes actions\"\"\"\n+ # pylint: disable=no-self-use\n+ def __init__(self, params):\n+ common.debug('Initializing LibraryActionExecutor: {}'\n+ .format(params))\n+ self.params = params\n+\n+ @common.inject_video_id(path_offset=0)\n+ def export(self, videoid):\n+ \"\"\"Export an item to the Kodi library\"\"\"\n+ common.execute_tasks(title=common.get_local_string(650),\n+ tasks=library.compile_tasks(videoid),\n+ task_handler=library.export_item,\n+ notify_errors=True,\n+ library_home=library.library_path())\n+\n+ @common.inject_video_id(path_offset=0)\n+ def export_silent(self, videoid):\n+ \"\"\"Export an item to the Kodi library\"\"\"\n+ # pylint: disable=bare-except\n+ for task in library.compile_tasks(videoid):\n+ try:\n+ library.export_item(task, library.library_path())\n+ except:\n+ import traceback\n+ common.error(traceback.format_exc())\n+ common.error('Export of {} failed'.format(task['title']))\n+\n+ @common.inject_video_id(path_offset=0)\n+ def remove(self, videoid):\n+ \"\"\"Remove an item from the Kodi library\"\"\"\n+ common.execute_tasks(title=common.get_local_string(650),\n+ tasks=library.compile_tasks(videoid),\n+ task_handler=library.remove_item,\n+ notify_errors=True)\n+\n+ @common.inject_video_id(path_offset=0)\n+ def update(self, videoid):\n+ \"\"\"Update an item in the Kodi library\"\"\"\n+ common.execute_tasks(title=common.get_local_string(650),\n+ tasks=library.compile_tasks(videoid),\n+ task_handler=library.update_item,\n+ notify_errors=True,\n+ library_home=library.library_path())\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add new file forgotten on last commit |
105,989 | 29.10.2018 23:21:43 | -3,600 | b6bdef8594c08a17d67508cce944a2ec8552d7fa | Add sentinel check to getitem | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/data_types.py",
"new_path": "resources/lib/api/data_types.py",
"diff": "@@ -24,7 +24,7 @@ class LoLoMo(object):\nin resolve_refs(self.data['lolomos'][self.id], self.data))\ndef __getitem__(self, key):\n- return self.data['lolomos'][self.id][key]\n+ return _check_sentinel(self.data['lolomos'][self.id][key])\ndef get(self, key, default=None):\n\"\"\"Pass call on to the backing dict of this LoLoMo.\"\"\"\n@@ -59,7 +59,7 @@ class VideoList(object):\nfor video in self.videos.itervalues()]\ndef __getitem__(self, key):\n- return self.data['lists'][self.id.value][key]\n+ return _check_sentinel(self.data['lists'][self.id.value][key])\ndef get(self, key, default=None):\n\"\"\"Pass call on to the backing dict of this VideoList.\"\"\"\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add sentinel check to getitem |
105,989 | 29.10.2018 23:22:32 | -3,600 | fe7a3772b6ff6d7f32ed8cbcc41d00bf8660fb7a | Reduce complexity. Get context genreId directly from videolist instead of passing it as a param | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -75,7 +75,7 @@ def video_list(list_id):\ncommon.debug('Requesting video list {}'.format(list_id))\nreturn VideoList(common.make_call(\n'path_request',\n- [['lists', [list_id], 'displayName']] +\n+ [['lists', [list_id], ['displayName', 'context', 'genreId']]] +\nbuild_paths(['lists', [list_id], {'from': 0, 'to': 40}, 'reference'],\nVIDEO_LIST_PARTIAL_PATHS)))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -68,66 +68,64 @@ def parse_info(videoid, item, raw_data):\ncommon.VideoId.EPISODE]:\ninfos['tvshowtitle'] = raw_data['videos'][videoid.tvshowid]['title']\n- parse_atomic_infos(item, infos)\n- parse_referenced_infos(item, infos, raw_data)\n-\n- infos['tag'] = [tagdef['name']\n- for tagdef\n- in item.get('tags', {}).itervalues()\n- if isinstance(tagdef.get('name', {}), unicode)]\n+ infos.update(parse_atomic_infos(item))\n+ infos.update(parse_referenced_infos(item, raw_data))\n+ infos.update(parse_tags(item))\nreturn infos, get_quality_infos(item)\n-def parse_atomic_infos(item, infos):\n+def parse_atomic_infos(item):\n\"\"\"Parse those infos into infolabels that are directly accesible from\nthe item dict\"\"\"\n- for target, source in paths.INFO_MAPPINGS.iteritems():\n- value = (common.get_path_safe(source, item)\n- if isinstance(source, list)\n- else item.get(source))\n+ return {target: _get_and_transform(source, target, item)\n+ for target, source\n+ in paths.INFO_MAPPINGS.iteritems()}\n+\n+\n+def _get_and_transform(source, target, item):\n+ \"\"\"Get the value for source and transform it if neccessary\"\"\"\n+ value = common.get_path_safe(source, item)\nif isinstance(value, dict):\n- value = None\n- if value is None:\n- common.debug('Infolabel {} not available'.format(target))\n- continue\n- if target in paths.INFO_TRANSFORMATIONS:\n- value = paths.INFO_TRANSFORMATIONS[target](value)\n- infos[target] = value\n- return infos\n+ return ''\n+ return (paths.INFO_TRANSFORMATIONS[target](value)\n+ if target in paths.INFO_TRANSFORMATIONS\n+ else value)\n-def parse_referenced_infos(item, infos, raw_data):\n+def parse_referenced_infos(item, raw_data):\n\"\"\"Parse those infos into infolabels that need their references\nresolved within the raw data\"\"\"\n- for target, source in paths.REFERENCE_MAPPINGS.iteritems():\n- infos[target] = [\n- person['name']\n+ return {target: [person['name']\nfor _, person\nin paths.resolve_refs(item.get(source, {}), raw_data)]\n- return infos\n+ for target, source in paths.REFERENCE_MAPPINGS.iteritems()}\n+\n+def parse_tags(item):\n+ \"\"\"Parse the tags\"\"\"\n+ return {'tag': [tagdef['name']\n+ for tagdef\n+ in item.get('tags', {}).itervalues()\n+ if isinstance(tagdef.get('name', {}), unicode)]}\n+\n+\n+QUALITIES = [\n+ {'codec': 'h264', 'width': '960', 'height': '540'},\n+ {'codec': 'h264', 'width': '1920', 'height': '1080'},\n+ {'codec': 'h265', 'width': '3840', 'height': '2160'}\n+]\ndef get_quality_infos(item):\n\"\"\"Return audio and video quality infolabels\"\"\"\nquality_infos = {}\ndelivery = item.get('delivery')\nif delivery:\n- if delivery.get('hasHD'):\n- quality_infos['video'] = {'codec': 'h264', 'width': '1920',\n- 'height': '1080'}\n- elif delivery.get('hasUltraHD'):\n- quality_infos['video'] = {'codec': 'h265', 'width': '3840',\n- 'height': '2160'}\n- else:\n- quality_infos['video'] = {'codec': 'h264', 'width': '960',\n- 'height': '540'}\n- # quality_infos = {'width': '1280', 'height': '720'}\n- if delivery.get('has51Audio'):\n- quality_infos['audio'] = {'channels': 6}\n- else:\n- quality_infos['audio'] = {'channels': 2}\n-\n+ quality_infos['video'] = QUALITIES[\n+ min((delivery.get('hasUltraHD', False)<<1 |\n+ delivery.get('hasHD')), 2)]\n+ quality_infos['audio'] = {\n+ 'channels': 2 + 4*delivery.get('has51Audio', False)}\nquality_infos['audio']['codec'] = (\n'eac3'\nif common.ADDON.getSettingBool('enable_dolby_sound')\n@@ -158,24 +156,25 @@ def assign_art(videoid, boxart_large, boxart_small, poster, interesting_moment,\nclearlogo, fanart):\n\"\"\"Assign the art available from Netflix to appropriate Kodi art\"\"\"\n# pylint: disable=too-many-arguments\n- art = {}\n- art['poster'] = poster or ''\n- art['clearlogo'] = (clearlogo\n- if videoid.mediatype != common.VideoId.UNSPECIFIED\n- else '') or ''\n+ art = {'poster': _best_art([poster]),\n+ 'fanart': _best_art([fanart, interesting_moment, boxart_large,\n+ boxart_small])}\nart['thumb'] = ((interesting_moment\nif videoid.mediatype == common.VideoId.EPISODE else '') or\nboxart_large or\nboxart_small)\nart['landscape'] = art['thumb']\n- art['fanart'] = (fanart or\n- interesting_moment or\n- boxart_large or\n- boxart_small or\n- '')\n+ if videoid.mediatype != common.VideoId.UNSPECIFIED:\n+ art['clearlogo'] = _best_art([clearlogo])\nreturn art\n+def _best_art(arts):\n+ \"\"\"Return the best art (determined by list order of arts) or\n+ an empty string if none is available\"\"\"\n+ return next((art for art in arts if art), '')\n+\n+\ndef add_info_from_netflix(videoid, list_item):\n\"\"\"Apply infolabels with info from Netflix API\"\"\"\ntry:\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -51,37 +51,33 @@ ADDITIONAL_MAIN_MENU_ITEMS = [\n'description': common.get_local_string(30091)},\n]\n+def ctx_item_url(paths, mode=common.MODE_ACTION):\n+ \"\"\"Return a function that builds an URL from a videoid\n+ for the predefined path\"\"\"\n+ def url_builder(videoid):\n+ \"\"\"Build defined URL from videoid\"\"\"\n+ return common.build_url(paths, videoid, mode)\n+ return url_builder\n+\nCONTEXT_MENU_ACTIONS = {\n'export': {\n'label': common.get_local_string(30018),\n- 'url': (lambda videoid:\n- common.build_url(['export'], videoid,\n- mode=common.MODE_LIBRARY))},\n+ 'url': ctx_item_url(['export'], common.MODE_LIBRARY)},\n'remove': {\n'label': common.get_local_string(30030),\n- 'url': (lambda videoid:\n- common.build_url(['remove'], videoid,\n- mode=common.MODE_LIBRARY))},\n+ 'url': ctx_item_url(['remove'], common.MODE_LIBRARY)},\n'update': {\n'label': common.get_local_string(30030),\n- 'url': (lambda videoid:\n- common.build_url(['update'], videoid,\n- mode=common.MODE_LIBRARY))},\n+ 'url': ctx_item_url(['update'], common.MODE_LIBRARY)},\n'rate': {\n'label': common.get_local_string(30019),\n- 'url': (lambda videoid:\n- common.build_url(['rate'], videoid,\n- mode=common.MODE_ACTION))},\n+ 'url': ctx_item_url(['rate'])},\n'add_to_list': {\n'label': common.get_local_string(30021),\n- 'url': (lambda videoid:\n- common.build_url(['my_list', 'add'], videoid,\n- mode=common.MODE_ACTION))},\n+ 'url': ctx_item_url(['my_list', 'add'])},\n'remove_from_list': {\n'label': common.get_local_string(30020),\n- 'url': (lambda videoid:\n- common.build_url(['my_list', 'remove'], videoid,\n- mode=common.MODE_ACTION))},\n+ 'url': ctx_item_url(['my_list', 'remove'])},\n}\n@@ -97,6 +93,14 @@ def custom_viewmode(viewtype):\nview = (viewtype_override\nif viewtype_override in VIEWTYPES\nelse viewtype)\n+ _activate_view(view)\n+ return set_custom_viewmode\n+ return decorate_viewmode\n+\n+\n+def _activate_view(view):\n+ \"\"\"Activate the given view if the plugin is run in the foreground\n+ and custom views are enabled\"\"\"\nif (('plugin://{}'.format(common.ADDON_ID) in\nxbmc.getInfoLabel('Container.FolderPath')) and\ncommon.ADDON.getSettingBool('customview')):\n@@ -104,52 +108,40 @@ def custom_viewmode(viewtype):\nif view_id != -1:\nxbmc.executebuiltin(\n'Container.SetViewMode({})'.format(view_id))\n- return set_custom_viewmode\n- return decorate_viewmode\n@custom_viewmode(VIEW_FOLDER)\ndef build_profiles_listing(profiles):\n- \"\"\"\n- Builds the profiles list Kodi screen\n-\n- :param profiles: list of user profiles\n- :type profiles: list\n- :param action: action paramter to build the subsequent routes\n- :type action: str\n- :param build_url: function to build the subsequent routes\n- :type build_url: fn\n- :returns: bool -- List could be build\n- \"\"\"\n- directory_items = []\n+ \"\"\"Builds the profiles list Kodi screen\"\"\"\ntry:\nfrom HTMLParser import HTMLParser\nexcept ImportError:\nfrom html.parser import HTMLParser\nhtml_parser = HTMLParser()\n- for profile_guid, profile in profiles.iteritems():\n+ finalize_directory([_create_profile_item(guid, profile, html_parser)\n+ for guid, profile\n+ in profiles.iteritems()])\n+\n+\n+def _create_profile_item(profile_guid, profile, html_parser):\n+ \"\"\"Create a tuple that can be added to a Kodi directory that represents\n+ a profile as listed in the profiles listing\"\"\"\nprofile_name = profile.get('profileName', '')\nunescaped_profile_name = html_parser.unescape(profile_name)\nenc_profile_name = profile_name.encode('utf-8')\n- list_item = create_list_item(\n+ list_item = list_item_skeleton(\nlabel=unescaped_profile_name, icon=profile.get('avatar'))\nautologin_url = common.build_url(\npathitems=['save_autologin', profile_guid],\nparams={'autologin_user': enc_profile_name},\nmode=common.MODE_ACTION)\nlist_item.addContextMenuItems(\n- items=[(common.get_local_string(30053),\n+ [(common.get_local_string(30053),\n'RunPlugin({})'.format(autologin_url))])\n- directory_items.append(\n- (common.build_url(pathitems=['home'],\n+ url = common.build_url(pathitems=['home'],\nparams={'profile_id': profile_guid},\n- mode=common.MODE_DIRECTORY),\n- list_item,\n- True))\n-\n- finalize_directory(\n- items=directory_items,\n- sort_methods=[xbmcplugin.SORT_METHOD_LABEL])\n+ mode=common.MODE_DIRECTORY)\n+ return (url, list_item, True)\n@custom_viewmode(VIEW_FOLDER)\n@@ -157,188 +149,151 @@ def build_main_menu_listing(lolomo):\n\"\"\"\nBuilds the video lists (my list, continue watching, etc.) Kodi screen\n\"\"\"\n- directory_items = []\n- for _, user_list in lolomo.lists_by_context(common.KNOWN_LIST_TYPES):\n- list_item = create_list_item(user_list['displayName'])\n- add_info(user_list.id, list_item, user_list, user_list.data)\n- add_art(user_list.id, list_item, user_list.artitem)\n- directory_items.append(\n- (common.build_url(\n- ['video_list', user_list['context']],\n- mode=common.MODE_DIRECTORY),\n- list_item,\n- True))\n-\n+ directory_items = [_create_videolist_item(list_id, user_list)\n+ for list_id, user_list\n+ in lolomo.lists_by_context(common.KNOWN_LIST_TYPES)]\nfor context_type, data in common.MISC_CONTEXTS.iteritems():\ndirectory_items.append(\n(common.build_url([context_type], mode=common.MODE_DIRECTORY),\n- create_list_item(common.get_local_string(data['label_id']),\n+ list_item_skeleton(common.get_local_string(data['label_id']),\nicon=data['icon'],\ndescription=common.get_local_string(\ndata['description_id'])),\nTrue))\n-\nfor menu_item in ADDITIONAL_MAIN_MENU_ITEMS:\ndirectory_items.append(\n(common.build_url(menu_item['path'], mode=common.MODE_DIRECTORY),\n- create_list_item(menu_item['label'],\n+ list_item_skeleton(menu_item['label'],\nicon=menu_item['icon'],\ndescription=menu_item['description']),\nTrue))\n+ finalize_directory(directory_items, CONTENT_FOLDER,\n+ title=common.get_local_string(30097))\n- finalize_directory(\n- items=directory_items,\n- title=common.get_local_string(30097),\n- sort_methods=[xbmcplugin.SORT_METHOD_UNSORTED],\n- content_type=CONTENT_FOLDER)\n@custom_viewmode(VIEW_FOLDER)\ndef build_lolomo_listing(lolomo, contexts=None):\n\"\"\"Build a listing of vieo lists (LoLoMo). Only show those\nlists with a context specified context if contexts is set.\"\"\"\n- directory_items = []\nlists = (lolomo.lists_by_context(contexts)\nif contexts\nelse lolomo.lists.iteritems())\n- for video_list_id, video_list in lists:\n- if video_list['context'] == 'billboard':\n- # Skip billboard (only contains one video)\n- continue\n- params = ({'genreId': video_list['genreId']}\n- if video_list.get('genreId')\n- else None)\n- list_item = create_list_item(video_list['displayName'])\n+ directory_items = [_create_videolist_item(video_list_id, video_list)\n+ for video_list_id, video_list\n+ in lists\n+ if video_list['context'] != 'billboard']\n+ finalize_directory(directory_items, CONTENT_FOLDER,\n+ title=lolomo.get('name'))\n+\n+\n+def _create_videolist_item(video_list_id, video_list):\n+ \"\"\"Create a tuple that can be added to a Kodi directory that represents\n+ a videolist as listed in a LoLoMo\"\"\"\n+ if video_list['context'] in common.KNOWN_LIST_TYPES:\n+ video_list_id = video_list['context']\n+ list_item = list_item_skeleton(video_list['displayName'])\nadd_info(video_list.id, list_item, video_list, video_list.data)\nadd_art(video_list.id, list_item, video_list.artitem)\n+ url = common.build_url(['video_list', video_list_id],\n+ mode=common.MODE_DIRECTORY)\n+ return (url, list_item, True)\n+\n+\n+@custom_viewmode(VIEW_SHOW)\n+def build_video_listing(video_list):\n+ \"\"\"Build a video listing\"\"\"\n+ directory_items = [_create_video_item(videoid_value, video, video_list)\n+ for videoid_value, video\n+ in video_list.videos.iteritems()]\n+ if video_list['genre_id']:\ndirectory_items.append(\n- (common.build_url(\n- ['video_list', video_list_id], mode=common.MODE_DIRECTORY,\n- params=params),\n- list_item,\n+ (common.build_url(pathitems=['genres', video_list['genre_id']],\n+ mode=common.MODE_DIRECTORY),\n+ list_item_skeleton(common.get_local_string(30088),\n+ icon='DefaultAddSource.png',\n+ description=common.get_local_string(30090)),\nTrue))\n- finalize_directory(\n- items=directory_items,\n- title=lolomo.get('name'),\n- sort_methods=[xbmcplugin.SORT_METHOD_UNSORTED],\n- content_type=CONTENT_FOLDER)\n+ # TODO: Implement browsing of subgenres\n+ # directory_items.append(\n+ # (common.build_url(pathitems=['genres', genre_id, 'subgenres'],\n+ # mode=common.MODE_DIRECTORY),\n+ # list_item_skeleton('Browse subgenres...'),\n+ # True))\n+ finalize_directory(directory_items, CONTENT_SHOW,\n+ title=video_list['displayName'])\n-@custom_viewmode(VIEW_SHOW)\n-def build_video_listing(video_list, genre_id=None):\n- \"\"\"\n- Build a video listing\n- \"\"\"\n- only_movies = True\n- directory_items = []\n- for videoid_value, video in video_list.videos.iteritems():\n+def _create_video_item(videoid_value, video, video_list):\n+ \"\"\"Create a tuple that can be added to a Kodi directory that represents\n+ a video as listed in a videolist\"\"\"\nis_movie = video['summary']['type'] == 'movie'\nvideoid = common.VideoId(\n**{('movieid' if is_movie else 'tvshowid'): videoid_value})\n- list_item = create_list_item(video['title'])\n+ list_item = list_item_skeleton(video['title'])\nadd_info(videoid, list_item, video, video_list.data)\nadd_art(videoid, list_item, video)\n- needs_pin = int(video.get('maturity', {})\n- .get('level', 1001)) >= 1000\nurl = common.build_url(videoid=videoid,\n- params={'pin': needs_pin},\nmode=(common.MODE_PLAY\nif is_movie\nelse common.MODE_DIRECTORY))\nlist_item.addContextMenuItems(\n_generate_context_menu_items(videoid))\n- directory_items.append(\n- (url,\n- list_item,\n- not is_movie))\n- only_movies = only_movies and is_movie\n- if genre_id:\n- directory_items.append(\n- (common.build_url(pathitems=['genres', genre_id],\n- mode=common.MODE_DIRECTORY),\n- create_list_item(common.get_local_string(30088),\n- icon='DefaultAddSource.png',\n- description=common.get_local_string(30090)),\n- True))\n- # TODO: Implement browsing of subgenres\n- # directory_items.append(\n- # (common.build_url(pathitems=['genres', genre_id, 'subgenres'],\n- # mode=common.MODE_DIRECTORY),\n- # create_list_item('Browse subgenres...'),\n- # True))\n- finalize_directory(\n- items=directory_items,\n- title=video_list['displayName'],\n- sort_methods=[xbmcplugin.SORT_METHOD_UNSORTED,\n- xbmcplugin.SORT_METHOD_LABEL,\n- xbmcplugin.SORT_METHOD_TITLE,\n- xbmcplugin.SORT_METHOD_VIDEO_YEAR,\n- xbmcplugin.SORT_METHOD_GENRE,\n- xbmcplugin.SORT_METHOD_LASTPLAYED],\n- content_type=CONTENT_MOVIE if only_movies else CONTENT_SHOW)\n- return VIEW_MOVIE if only_movies else VIEW_SHOW\n+ return (url, list_item, not is_movie)\n@custom_viewmode(VIEW_SEASON)\ndef build_season_listing(tvshowid, season_list):\n- \"\"\"\n- Build a season listing\n- \"\"\"\n- directory_items = []\n- for seasonid_value, season in season_list.seasons.iteritems():\n+ \"\"\"Build a season listing\"\"\"\n+ directory_items = [_create_season_item(tvshowid, seasonid_value, season,\n+ season_list)\n+ for seasonid_value, season\n+ in season_list.seasons.iteritems()]\n+ finalize_directory(directory_items, CONTENT_SEASON,\n+ title=' - '.join((season_list.tvshow['title'],\n+ common.get_local_string(20366)[2:])))\n+\n+\n+def _create_season_item(tvshowid, seasonid_value, season, season_list):\n+ \"\"\"Create a tuple that can be added to a Kodi directory that represents\n+ a season as listed in a season listing\"\"\"\nseasonid = tvshowid.derive_season(seasonid_value)\n- list_item = create_list_item(season['summary']['name'])\n+ list_item = list_item_skeleton(season['summary']['name'])\nadd_info(seasonid, list_item, season, season_list.data)\nadd_art(tvshowid, list_item, season_list.tvshow)\nlist_item.addContextMenuItems(\n_generate_context_menu_items(seasonid))\n- directory_items.append(\n- (common.build_url(videoid=seasonid, mode=common.MODE_DIRECTORY),\n- list_item,\n- True))\n- finalize_directory(\n- items=directory_items,\n- title=' - '.join((season_list.tvshow['title'],\n- common.get_local_string(20366)[2:])),\n- sort_methods=[xbmcplugin.SORT_METHOD_NONE,\n- xbmcplugin.SORT_METHOD_VIDEO_YEAR,\n- xbmcplugin.SORT_METHOD_LABEL,\n- xbmcplugin.SORT_METHOD_LASTPLAYED,\n- xbmcplugin.SORT_METHOD_TITLE],\n- content_type=CONTENT_SEASON)\n+ url = common.build_url(videoid=seasonid, mode=common.MODE_DIRECTORY)\n+ return (url, list_item, True)\n@custom_viewmode(VIEW_EPISODE)\ndef build_episode_listing(seasonid, episode_list):\n- \"\"\"\n- Build a season listing\n- \"\"\"\n- directory_items = []\n- for episodeid_value, episode in episode_list.episodes.iteritems():\n+ \"\"\"Build a season listing\"\"\"\n+ directory_items = [_create_episode_item(seasonid, episodeid_value, episode,\n+ episode_list)\n+ for episodeid_value, episode\n+ in episode_list.episodes.iteritems()]\n+ finalize_directory(directory_items, CONTENT_EPISODE,\n+ title=' - '.join(\n+ (episode_list.tvshow['title'],\n+ episode_list.season['summary']['name'])))\n+\n+\n+def _create_episode_item(seasonid, episodeid_value, episode, episode_list):\n+ \"\"\"Create a tuple that can be added to a Kodi directory that represents\n+ an episode as listed in an episode listing\"\"\"\nepisodeid = seasonid.derive_episode(episodeid_value)\n- list_item = create_list_item(episode['title'])\n+ list_item = list_item_skeleton(episode['title'])\nadd_info(episodeid, list_item, episode, episode_list.data)\nadd_art(episodeid, list_item, episode)\nlist_item.addContextMenuItems(\n_generate_context_menu_items(episodeid))\n- directory_items.append(\n- (common.build_url(videoid=episodeid, mode=common.MODE_PLAY),\n- list_item,\n- False))\n- finalize_directory(\n- items=directory_items,\n- title=' - '.join((episode_list.tvshow['title'],\n- episode_list.season['summary']['name'])),\n- sort_methods=[xbmcplugin.SORT_METHOD_UNSORTED,\n- xbmcplugin.SORT_METHOD_LABEL,\n- xbmcplugin.SORT_METHOD_TITLE,\n- xbmcplugin.SORT_METHOD_VIDEO_YEAR,\n- xbmcplugin.SORT_METHOD_GENRE,\n- xbmcplugin.SORT_METHOD_LASTPLAYED],\n- content_type=CONTENT_EPISODE)\n-\n-\n-def create_list_item(label, icon=None, fanart=None, description=None):\n- \"\"\"Create a rudimentary list item with icon and fanart\"\"\"\n+ url = common.build_url(videoid=episodeid, mode=common.MODE_PLAY)\n+ return (url, list_item, False)\n+\n+\n+def list_item_skeleton(label, icon=None, fanart=None, description=None):\n+ \"\"\"Create a rudimentary list item skeleton with icon and fanart\"\"\"\n# pylint: disable=unexpected-keyword-arg\nlist_item = xbmcgui.ListItem(label=label, iconImage=icon, offscreen=True)\nlist_item.setContentLookup(False)\n@@ -351,64 +306,37 @@ def create_list_item(label, icon=None, fanart=None, description=None):\nreturn list_item\n-def finalize_directory(items, sort_methods=None, content_type=CONTENT_FOLDER,\n- refresh=False, title=None):\n+def finalize_directory(items, content_type=CONTENT_FOLDER, refresh=False,\n+ title=None):\n\"\"\"Finalize a directory listing.\nAdd items, set available sort methods and content type\"\"\"\n- xbmcplugin.addDirectoryItems(\n- common.PLUGIN_HANDLE, items, len(items))\n-\n- for sort_method in (sort_methods\n- if sort_methods\n- else [xbmcplugin.SORT_METHOD_UNSORTED]):\n- xbmcplugin.addSortMethod(\n- handle=common.PLUGIN_HANDLE,\n- sortMethod=sort_method)\n-\nif title:\n- xbmcplugin.setPluginCategory(\n- handle=common.PLUGIN_HANDLE,\n- category=title)\n-\n- xbmcplugin.setContent(\n- handle=common.PLUGIN_HANDLE,\n- content=content_type)\n-\n- xbmcplugin.endOfDirectory(\n- handle=common.PLUGIN_HANDLE,\n- updateListing=refresh)\n+ xbmcplugin.setPluginCategory(common.PLUGIN_HANDLE, title)\n+ xbmcplugin.addDirectoryItems(common.PLUGIN_HANDLE, items)\n+ xbmcplugin.setContent(common.PLUGIN_HANDLE, content_type)\n+ xbmcplugin.endOfDirectory(common.PLUGIN_HANDLE, updateListing=refresh)\ndef _generate_context_menu_items(videoid):\n- items = []\n- if library.is_in_library(videoid):\n- items.append(\n- (CONTEXT_MENU_ACTIONS['remove']['label'],\n- RUN_PLUGIN.format(\n- CONTEXT_MENU_ACTIONS['remove']['url'](videoid))))\n- if videoid.mediatype in [common.VideoId.SHOW, common.VideoId.SEASON]:\n- items.append(\n- (CONTEXT_MENU_ACTIONS['update']['label'],\n- RUN_PLUGIN.format(\n- CONTEXT_MENU_ACTIONS['update']['url'](videoid))))\n- else:\n- items.append(\n- (CONTEXT_MENU_ACTIONS['export']['label'],\n- RUN_PLUGIN.format(\n- CONTEXT_MENU_ACTIONS['export']['url'](videoid))))\n+ library_actions = (['remove', 'update']\n+ if library.is_in_library(videoid)\n+ else ['export'])\n+ items = [_ctx_item(action, videoid) for action in library_actions]\nif videoid.mediatype != common.VideoId.SEASON:\n- items.append(\n- (CONTEXT_MENU_ACTIONS['rate']['label'],\n- RUN_PLUGIN.format(\n- CONTEXT_MENU_ACTIONS['rate']['url'](videoid))))\n+ items.append(_ctx_item('rate', videoid))\nif videoid.mediatype in [common.VideoId.MOVIE, common.VideoId.SHOW]:\nlist_action = ('remove_from_list'\nif videoid.value in api.mylist_items()\nelse 'add_to_list')\n- items.append(\n- (CONTEXT_MENU_ACTIONS[list_action]['label'],\n- RUN_PLUGIN.format(\n- CONTEXT_MENU_ACTIONS[list_action]['url'](videoid))))\n+ items.append(_ctx_item(list_action, videoid))\n+\nreturn items\n+\n+\n+def _ctx_item(template, videoid):\n+ \"\"\"Create a context menu item based on the given template and videoid\"\"\"\n+ return (CONTEXT_MENU_ACTIONS[template]['label'],\n+ RUN_PLUGIN.format(\n+ CONTEXT_MENU_ACTIONS[template]['url'](videoid)))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/directory.py",
"new_path": "resources/lib/navigation/directory.py",
"diff": "@@ -50,8 +50,7 @@ class DirectoryBuilder(object):\nelse:\nlist_id = pathitems[0]\n- listings.build_video_listing(api.video_list(list_id),\n- self.params.get('genreId'))\n+ listings.build_video_listing(api.video_list(list_id))\[email protected]_video_id(path_offset=0)\ndef show(self, videoid):\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Reduce complexity. Get context genreId directly from videolist instead of passing it as a param |
105,989 | 29.10.2018 23:41:35 | -3,600 | 44f70e5588e7e0a55aa822dd32aff78b8cf343ee | Fix URL building for context menu items. Fix passing of related genreId | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -56,7 +56,7 @@ def ctx_item_url(paths, mode=common.MODE_ACTION):\nfor the predefined path\"\"\"\ndef url_builder(videoid):\n\"\"\"Build defined URL from videoid\"\"\"\n- return common.build_url(paths, videoid, mode)\n+ return common.build_url(paths, videoid, mode=mode)\nreturn url_builder\nCONTEXT_MENU_ACTIONS = {\n@@ -205,9 +205,9 @@ def build_video_listing(video_list):\ndirectory_items = [_create_video_item(videoid_value, video, video_list)\nfor videoid_value, video\nin video_list.videos.iteritems()]\n- if video_list['genre_id']:\n+ if video_list.get('genreId'):\ndirectory_items.append(\n- (common.build_url(pathitems=['genres', video_list['genre_id']],\n+ (common.build_url(pathitems=['genres', video_list['genreId']],\nmode=common.MODE_DIRECTORY),\nlist_item_skeleton(common.get_local_string(30088),\nicon='DefaultAddSource.png',\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix URL building for context menu items. Fix passing of related genreId |
105,989 | 29.10.2018 23:41:52 | -3,600 | a7319bcd2b3a15b9df90123193a8cb1f722ca663 | Fix regression of videoid injection | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/__init__.py",
"new_path": "resources/lib/navigation/__init__.py",
"diff": "@@ -20,6 +20,6 @@ def execute(executor_type, pathitems, params):\ncommon.debug('Invoking action executor {}'.format(executor.__name__))\nif len(pathitems) > 1:\n- executor(pathitems=pathitems[1:])\n+ executor(pathitems=pathitems)\nelse:\nexecutor()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/actions.py",
"new_path": "resources/lib/navigation/actions.py",
"diff": "@@ -18,7 +18,7 @@ class AddonActionExecutor(object):\n.format(params))\nself.params = params\n- def logout(self):\n+ def logout(self, pathitems=None):\n\"\"\"Perform account logout\"\"\"\napi.logout()\n@@ -34,19 +34,19 @@ class AddonActionExecutor(object):\ntry:\ncommon.ADDON.setSetting('autologin_user',\nself.params['autologin_user'])\n- common.ADDON.setSetting('autologin_id', pathitems[0])\n+ common.ADDON.setSetting('autologin_id', pathitems[1])\ncommon.ADDON.setSetting('autologin_enable', 'true')\nexcept (KeyError, IndexError):\ncommon.error('Cannot save autologin - invalid params')\ncache.invalidate_cache()\ncommon.refresh_container()\n- def switch_account(self):\n+ def switch_account(self, pathitems=None):\n\"\"\"Logo out of the curent account and login into another one\"\"\"\napi.logout()\napi.login()\n- def toggle_adult_pin(self):\n+ def toggle_adult_pin(self, pathitems=None):\n\"\"\"Toggle adult PIN verification\"\"\"\n# pylint: disable=no-member\ncommon.ADDON.setSettingBool(\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/directory.py",
"new_path": "resources/lib/navigation/directory.py",
"diff": "@@ -45,10 +45,10 @@ class DirectoryBuilder(object):\ndef video_list(self, pathitems):\n\"\"\"Show a video list\"\"\"\n# Use predefined names instead of dynamic IDs for common video lists\n- if pathitems[0] in common.KNOWN_LIST_TYPES:\n- list_id = api.list_id_for_type(pathitems[0])\n+ if pathitems[1] in common.KNOWN_LIST_TYPES:\n+ list_id = api.list_id_for_type(pathitems[1])\nelse:\n- list_id = pathitems[0]\n+ list_id = pathitems[1]\nlistings.build_video_listing(api.video_list(list_id))\n@@ -70,7 +70,7 @@ class DirectoryBuilder(object):\nlolomo = api.root_lists()\ncontexts = common.MISC_CONTEXTS['genres']['contexts']\nelse:\n- lolomo = api.genre(pathitems[0])\n+ lolomo = api.genre(pathitems[1])\ncontexts = None\nlistings.build_lolomo_listing(lolomo, contexts)\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix regression of videoid injection |
105,989 | 30.10.2018 00:33:44 | -3,600 | ff705b90eef8010616c1f20310cb5124c70f5c6e | Fix cache locking. Fix conversion errors on missing infolabels | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -173,9 +173,15 @@ def invalidate_entry(bucket, identifier):\ndef commit():\n\"\"\"Persist cache contents in window properties\"\"\"\n- for bucket, contents in BUCKETS.iteritems():\n+ # pylint: disable=global-statement\n+ global BUCKETS\n+ for bucket, contents in BUCKETS.items():\n_persist_bucket(bucket, contents)\n- common.debug('Successfully persisted cache to window properties')\n+ # The BUCKETS dict survives across addon invocations if the same\n+ # languageInvoker thread is being used so we MUST clear its contents\n+ # to allow cache consistency between instances\n+ del BUCKETS[bucket]\n+ common.debug('Cache committ successful')\ndef get(bucket, identifier):\n@@ -258,33 +264,42 @@ def _load_bucket(bucket):\nwnd_property = ''\nfor _ in range(1, 10):\nwnd_property = WND.getProperty(_window_property(bucket))\n- if wnd_property.startswith(BUCKET_LOCKED[:-2]):\n+ # pickle stored byte data, so we must compare against a str\n+ if wnd_property.startswith(str('LOCKED')):\ncommon.debug('Waiting for release of {}'.format(bucket))\nxbmc.sleep(50)\nelse:\ntry:\n- return pickle.loads(wnd_property)\n+ bucket_instance = pickle.loads(wnd_property)\nexcept Exception:\ncommon.debug('No instance of {} found. Creating new instance.'\n.format(bucket))\n- return {}\n- common.warn('Bucket {} is {}. Working with an empty instance...'\n- .format(bucket, wnd_property))\n+ bucket_instance = {}\n+ WND.setProperty(_window_property(bucket),\n+ str(BUCKET_LOCKED.format(common.PLUGIN_HANDLE)))\n+ common.debug('Acquired lock on {}'.format(bucket))\n+ return bucket_instance\n+ common.warn('{} is locked. Working with an empty instance...'\n+ .format(bucket))\nreturn {}\ndef _persist_bucket(bucket, contents):\n# pylint: disable=broad-except\nlock = WND.getProperty(_window_property(bucket))\n- if lock == BUCKET_LOCKED.format(common.PLUGIN_HANDLE):\n+ # pickle stored byte data, so we must compare against a str\n+ if lock == str(BUCKET_LOCKED.format(common.PLUGIN_HANDLE)):\ntry:\nWND.setProperty(_window_property(bucket), pickle.dumps(contents))\nexcept Exception as exc:\ncommon.error('Failed to persist {} to window properties: {}'\n.format(bucket, exc))\n+ WND.clearProperty(_window_property(bucket))\n+ finally:\n+ common.debug('Released lock on {}'.format(bucket))\nelse:\n- common.warn('Bucket {} is {}. Discarding changes...'\n- .format(bucket, lock))\n+ common.warn('{} is locked by another instance. Discarding changes...'\n+ .format(bucket))\ndef _clear_bucket(bucket):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -86,7 +86,7 @@ def parse_atomic_infos(item):\ndef _get_and_transform(source, target, item):\n\"\"\"Get the value for source and transform it if neccessary\"\"\"\nvalue = common.get_path_safe(source, item)\n- if isinstance(value, dict):\n+ if isinstance(value, dict) or value is None:\nreturn ''\nreturn (paths.INFO_TRANSFORMATIONS[target](value)\nif target in paths.INFO_TRANSFORMATIONS\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix cache locking. Fix conversion errors on missing infolabels |
105,989 | 30.10.2018 02:47:57 | -3,600 | c392c7c4e9238e75b1bf01bf214f32295b929a90 | Fix library export. Other fixes | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/common.py",
"new_path": "resources/lib/common.py",
"diff": "@@ -201,13 +201,13 @@ class VideoId(object):\nif self.videoid:\nreturn [self.videoid]\nif self.movieid:\n- return [self.MOVIE, self.movieid]\n+ return [self.MOVIE, unicode(self.movieid)]\n- pathitems = [self.SHOW, self.tvshowid]\n+ pathitems = [self.SHOW, unicode(self.tvshowid)]\nif self.seasonid:\n- pathitems.extend([self.SEASON, self.seasonid])\n+ pathitems.extend([self.SEASON, unicode(self.seasonid)])\nif self.episodeid:\n- pathitems.extend([self.EPISODE, self.episodeid])\n+ pathitems.extend([self.EPISODE, unicode(self.episodeid)])\nreturn pathitems\ndef to_list(self):\n@@ -886,7 +886,7 @@ def make_call(callname, data=None):\ntimeout_ms=10000)\nif isinstance(result, dict) and 'error' in result:\nmsg = ('AddonSignals call {callname} returned {error}: {message}'\n- .format(callname, **result))\n+ .format(callname=callname, **result))\nerror(msg)\nraise Exception(msg)\nelif result is None:\n@@ -934,16 +934,13 @@ def _signal_name(func):\ndef build_url(pathitems=None, videoid=None, params=None, mode=None):\n\"\"\"Build a plugin URL from pathitems and query parameters.\nAdd videoid to the path if it's present.\"\"\"\n- pathitems = pathitems or []\n- if videoid:\n- pathitems.extend(videoid.to_path())\n- elif not pathitems:\n+ if not pathitems and not videoid:\nraise ValueError('Either pathitems or videoid must be set.')\n- if mode:\n- pathitems.insert(0, mode)\nreturn '{netloc}/{path}{qs}'.format(\nnetloc=BASE_URL,\n- path='/'.join(pathitems) + '/',\n+ path='/'.join(([mode] if mode else []) +\n+ (pathitems or []) +\n+ (videoid.to_path() if videoid else [])) + '/',\nqs=('?' + urlencode(params)) if params else '')\n@@ -1000,20 +997,21 @@ def execute_tasks(title, tasks, task_handler, notify_errors=False, **kwargs):\nerrors = []\nprogress = xbmcgui.DialogProgress()\nprogress.create(title)\n- for task_num, task in tasks:\n+ for task_num, task in enumerate(tasks):\n# pylint: disable=broad-except\ntask_title = task.get('title', 'Unknown Task')\nprogress.update(percent=int(task_num / len(tasks) * 100),\nline1=task_title)\n- xbmc.sleep(100)\n+ xbmc.sleep(25)\nif progress.iscanceled():\nbreak\ntry:\ntask_handler(task, **kwargs)\nexcept Exception as exc:\n+ error(traceback.format_exc())\nerrors.append({\n'task_title': task_title,\n- 'error': ': '.join((type(exc).__name__, exc.message))})\n+ 'error': ': '.join((type(exc).__name__, unicode(exc)))})\nif notify_errors and errors:\nxbmcgui.Dialog().ok(get_local_string(0),\n'\\n'.join(['{} ({})'.format(err['task_title'],\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "@@ -82,15 +82,14 @@ def compile_tasks(videoid):\nmetadata = api.metadata(videoid)\nif videoid.mediatype == common.VideoId.MOVIE:\nname = '{title} ({year})'.format(\n- title=metadata['video']['title'],\n- year=metadata['video']['year'])\n+ title=metadata['title'],\n+ year=metadata['year'])\nreturn [_create_item_task(name, FOLDER_MOVIES, videoid, name, name)]\nelif videoid.mediatype == common.VideoId.SHOW:\nreturn [\n- task for task in (\n- _compile_season_tasks(\n- videoid.derive_season(season['id']), metadata, season)\n- for season in metadata['video']['seasons'])]\n+ task for season in metadata['seasons']\n+ for task in _compile_season_tasks(\n+ videoid.derive_season(season['id']), metadata, season)]\nelif videoid.mediatype == common.VideoId.SEASON:\nreturn _compile_season_tasks(\nvideoid, metadata, common.find_season(videoid.seasonid,\n@@ -110,11 +109,11 @@ def _compile_season_tasks(videoid, metadata, season):\ndef _create_episode_task(videoid, metadata, season=None, episode=None):\n\"\"\"Export a single episode to the library\"\"\"\n- showname = metadata['video']['title']\n+ showname = metadata['title']\nseason = season or common.find_season(\n- videoid.seasonid, metadata['video']['seasons'])\n+ videoid.seasonid, metadata['seasons'])\nepisode = episode or common.find_episode(\n- videoid.episodeid, metadata['video']['seasons'])\n+ videoid.episodeid, metadata['seasons'])\ntitle = episode['title']\nfilename = 'S{:02d}E{:02d}'.format(season['seq'], episode['seq'])\ntitle = ' - '.join((showname, filename, title))\n@@ -140,6 +139,11 @@ def export_item(item_task, library_home):\ndestination_folder, item_task['filename'] + '.strm')\ntry:\nos.makedirs(xbmc.translatePath(destination_folder))\n+ except OSError as exc:\n+ if exc.errno != os.errno.EEXIST:\n+ raise\n+\n+ try:\nwith codecs.open(xbmc.translatePath(export_filename),\nmode='w',\nencoding='utf-8',\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -54,10 +54,10 @@ ADDITIONAL_MAIN_MENU_ITEMS = [\ndef ctx_item_url(paths, mode=common.MODE_ACTION):\n\"\"\"Return a function that builds an URL from a videoid\nfor the predefined path\"\"\"\n- def url_builder(videoid):\n- \"\"\"Build defined URL from videoid\"\"\"\n+ def ctx_url_builder(videoid):\n+ \"\"\"Build a context menu item URL\"\"\"\nreturn common.build_url(paths, videoid, mode=mode)\n- return url_builder\n+ return ctx_url_builder\nCONTEXT_MENU_ACTIONS = {\n'export': {\n@@ -67,7 +67,7 @@ CONTEXT_MENU_ACTIONS = {\n'label': common.get_local_string(30030),\n'url': ctx_item_url(['remove'], common.MODE_LIBRARY)},\n'update': {\n- 'label': common.get_local_string(30030),\n+ 'label': common.get_local_string(30061),\n'url': ctx_item_url(['update'], common.MODE_LIBRARY)},\n'rate': {\n'label': common.get_local_string(30019),\n@@ -339,5 +339,4 @@ def _generate_context_menu_items(videoid):\ndef _ctx_item(template, videoid):\n\"\"\"Create a context menu item based on the given template and videoid\"\"\"\nreturn (CONTEXT_MENU_ACTIONS[template]['label'],\n- RUN_PLUGIN.format(\n- CONTEXT_MENU_ACTIONS[template]['url'](videoid)))\n+ RUN_PLUGIN.format(CONTEXT_MENU_ACTIONS[template]['url'](videoid)))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/actions.py",
"new_path": "resources/lib/navigation/actions.py",
"diff": "@@ -52,7 +52,7 @@ class AddonActionExecutor(object):\ncommon.ADDON.setSettingBool(\nnot common.ADDON.getSettingBool('adultpin_enable'))\n- @common.inject_video_id(path_offset=0)\n+ @common.inject_video_id(path_offset=1)\ndef rate(self, videoid):\n\"\"\"Rate an item on Netflix. Ask for a rating if there is none supplied\nin the path.\"\"\"\n@@ -60,14 +60,14 @@ class AddonActionExecutor(object):\nif rating is not None:\napi.rate(videoid, rating)\n- @common.inject_video_id(path_offset=1, inject_remaining_pathitems=True)\n+ @common.inject_video_id(path_offset=2, inject_remaining_pathitems=True)\ndef my_list(self, videoid, pathitems):\n\"\"\"Add or remove an item from my list\"\"\"\n- if pathitems[0] == 'add':\n+ if pathitems[1] == 'add':\napi.add_to_list(videoid)\n- elif pathitems[0] == 'remove':\n+ elif pathitems[1] == 'remove':\napi.remove_from_list(videoid)\nelse:\nraise InvalidPathError('Unknown my-list action: {}'\n- .format(pathitems[0]))\n+ .format(pathitems[1]))\ncommon.refresh_container()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/library.py",
"new_path": "resources/lib/navigation/library.py",
"diff": "@@ -13,7 +13,7 @@ class LibraryActionExecutor(object):\n.format(params))\nself.params = params\n- @common.inject_video_id(path_offset=0)\n+ @common.inject_video_id(path_offset=1)\ndef export(self, videoid):\n\"\"\"Export an item to the Kodi library\"\"\"\ncommon.execute_tasks(title=common.get_local_string(650),\n@@ -22,7 +22,7 @@ class LibraryActionExecutor(object):\nnotify_errors=True,\nlibrary_home=library.library_path())\n- @common.inject_video_id(path_offset=0)\n+ @common.inject_video_id(path_offset=1)\ndef export_silent(self, videoid):\n\"\"\"Export an item to the Kodi library\"\"\"\n# pylint: disable=bare-except\n@@ -34,7 +34,7 @@ class LibraryActionExecutor(object):\ncommon.error(traceback.format_exc())\ncommon.error('Export of {} failed'.format(task['title']))\n- @common.inject_video_id(path_offset=0)\n+ @common.inject_video_id(path_offset=1)\ndef remove(self, videoid):\n\"\"\"Remove an item from the Kodi library\"\"\"\ncommon.execute_tasks(title=common.get_local_string(650),\n@@ -42,7 +42,7 @@ class LibraryActionExecutor(object):\ntask_handler=library.remove_item,\nnotify_errors=True)\n- @common.inject_video_id(path_offset=0)\n+ @common.inject_video_id(path_offset=1)\ndef update(self, videoid):\n\"\"\"Update an item in the Kodi library\"\"\"\ncommon.execute_tasks(title=common.get_local_string(650),\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix library export. Other fixes |
105,989 | 31.10.2018 11:09:18 | -3,600 | 163445a1e3e8b2b7eb717b17a3cf43fea8c93cd0 | Fix issues with identifying items in Kodi library. | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/kodiops.py",
"new_path": "resources/lib/common/kodiops.py",
"diff": "@@ -7,16 +7,7 @@ import json\nimport xbmc\nfrom resources.lib.globals import g\n-\n-\n-def update_library_item_details(dbtype, dbid, details):\n- \"\"\"\n- Update properties of an item in the Kodi library\n- \"\"\"\n- method = 'VideoLibrary.Set{}Details'.format(dbtype.capitalize())\n- params = {'{}id'.format(dbtype): dbid}\n- params.update(details)\n- return json_rpc(method, params)\n+from .logging import debug\ndef json_rpc(method, params=None):\n@@ -32,8 +23,10 @@ def json_rpc(method, params=None):\nrequest_data = {'jsonrpc': '2.0', 'method': method, 'id': 1,\n'params': params or {}}\nrequest = json.dumps(request_data)\n- response = json.loads(unicode(xbmc.executeJSONRPC(request), 'utf-8',\n- errors='ignore'))\n+ debug('Executing JSON-RPC: {}'.format(request))\n+ raw_response = unicode(xbmc.executeJSONRPC(request), 'utf-8')\n+ debug('JSON-RPC response: {}'.format(raw_response))\n+ response = json.loads(raw_response)\nif 'error' in response:\nraise IOError('JSONRPC-Error {}: {}'\n.format(response['error']['code'],\n@@ -41,6 +34,24 @@ def json_rpc(method, params=None):\nreturn response['result']\n+def update_library_item_details(dbtype, dbid, details):\n+ \"\"\"\n+ Update properties of an item in the Kodi library\n+ \"\"\"\n+ method = 'VideoLibrary.Set{}Details'.format(dbtype.capitalize())\n+ params = {'{}id'.format(dbtype): dbid}\n+ params.update(details)\n+ return json_rpc(method, params)\n+\n+\n+def get_library_items(dbtype):\n+ \"\"\"Return a list of all items in the Kodi library that are of type\n+ dbtype (either movie or episode)\"\"\"\n+ method = 'VideoLibrary.Get{}s'.format(dbtype.capitalize())\n+ params = {'properties': ['title', 'file', 'resume']}\n+ return json_rpc(method, params)[dbtype + 's']\n+\n+\ndef refresh_container():\n\"\"\"Refresh the current container\"\"\"\nxbmc.executebuiltin('Container.Refresh')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -47,7 +47,8 @@ def add_info_for_playback(videoid, list_item):\n\"\"\"Retrieve infolabels and art info and add them to the list_item\"\"\"\ntry:\nreturn add_info_from_library(videoid, list_item)\n- except library.ItemNotFound:\n+ except library.ItemNotFound as exc:\n+ common.debug(exc)\nreturn add_info_from_netflix(videoid, list_item)\n@@ -185,23 +186,28 @@ def add_info_from_netflix(videoid, list_item):\ncommon.info('Infolabels or art were not in cache, retrieving from API')\nimport resources.lib.api.shakti as api\napi_data = api.single_info(videoid)\n- infos = add_info(videoid, list_item, api_data['videos'][videoid],\n+ infos = add_info(videoid, list_item, api_data['videos'][videoid.value],\napi_data)\n- art = add_art(videoid, list_item, api_data['videos'][videoid])\n+ art = add_art(videoid, list_item, api_data['videos'][videoid.value])\nreturn infos, art\ndef add_info_from_library(videoid, list_item):\n\"\"\"Apply infolabels with info from Kodi library\"\"\"\n- details = library.get_item(videoid, include_props=True)\n+ details = library.get_item(videoid)\ncommon.debug('Got fileinfo from library: {}'.format(details))\nart = details.pop('art', {})\n+ # Resuming for strm files in library is currently broken in Leia Beta\n+ # keeping this for reference / in hopes this will get fixed\n+ resume = details.pop('resume', {})\n+ # if resume:\n+ # start_percent = resume['position'] / resume['total'] * 100.0\n+ # list_item.setProperty('startPercent', str(start_percent))\ninfos = {\n- 'DBID': details.pop('id'),\n- 'mediatype': details['type'],\n- 'DBTYPE': details.pop('type')\n+ 'DBID': details.pop('{}id'.format(videoid.mediatype)),\n+ 'mediatype': videoid.mediatype,\n+ 'title': details['title']\n}\n- infos.update(details)\n- list_item.setInfo(infos)\n+ list_item.setInfo('video', infos)\nlist_item.setArt(art)\nreturn infos, art\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "@@ -12,13 +12,6 @@ from resources.lib.globals import g\nimport resources.lib.common as common\nimport resources.lib.api.shakti as api\n-FILE_PROPS = [\n- 'title', 'genre', 'year', 'rating', 'duration', 'playcount', 'director',\n- 'tagline', 'plot', 'plotoutline', 'originaltitle', 'writer', 'studio',\n- 'mpaa', 'cast', 'country', 'runtime', 'set', 'showlink', 'season',\n- 'episode', 'showtitle', 'file', 'resume', 'tvshowid', 'setid', 'tag',\n- 'art', 'uniqueid']\n-\nLIBRARY_HOME = 'library'\nFOLDER_MOVIES = 'movies'\nFOLDER_TV = 'shows'\n@@ -36,18 +29,21 @@ def library_path():\nelse g.DATA_PATH)\n-def get_item(videoid, include_props=False):\n+def get_item(videoid):\n\"\"\"Find an item in the Kodi library by its Netflix videoid and return\nKodi DBID and mediatype\"\"\"\n+ # pylint: disable=broad-except\ntry:\n- filepath = xbmc.translatePath(common.get_path(videoid.to_list(), g.library())['file'])\n- params = {'file': filepath, 'media': 'video'}\n- if include_props:\n- params['properties'] = FILE_PROPS\n- return common.json_rpc('Files.GetFileDetails', params)['filedetails']\n+ exported_filepath = os.path.normcase(\n+ xbmc.translatePath(\n+ common.get_path(videoid.to_list(), g.library())['file']))\n+ for library_item in common.get_library_items(videoid.mediatype):\n+ if os.path.normcase(library_item['file']) == exported_filepath:\n+ return library_item\nexcept Exception:\nimport traceback\n- common.debug(traceback.format_exc())\n+ common.error(traceback.format_exc())\n+ # This is intentionally not raised in the except block!\nraise ItemNotFound(\n'The video with id {} is not present in the Kodi library'\n.format(videoid))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -142,6 +142,7 @@ class NetflixSession(object):\n_update_esn(self.session_data['esn'])\nreturn True\nreturn False\n+ return True\ndef _refresh_session_data(self):\n\"\"\"Refresh session_data from the Netflix website\"\"\"\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix issues with identifying items in Kodi library. |
105,989 | 01.11.2018 16:40:58 | -3,600 | 6c1ff3e3cce9a0c70c75b9d2dd1ae2e54fa20e41 | Add debug output to MSL | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/MSL.py",
"new_path": "resources/lib/services/msl/MSL.py",
"diff": "@@ -59,9 +59,11 @@ class MSL(object):\n\"\"\"\nself.crypto = MSLHandler()\n- if common.file_exists(g.DATA_PATH, 'msl_data.json'):\n+ if common.file_exists('msl_data.json'):\n+ common.error('MSL data exists')\nself.init_msl_data()\nelse:\n+ common.error('MSL data does not exist')\nself.crypto.fromDict(None)\nself.__perform_key_handshake()\n@@ -201,7 +203,7 @@ class MSL(object):\nmanifest_request_data['profiles'].append('ddplus-5.1-dash')\nrequest_data = self.__generate_msl_request_data(manifest_request_data)\n-\n+ common.debug(request_data)\ntry:\nresp = self.session.post(self.endpoints['manifest'], request_data)\nexcept:\n@@ -507,8 +509,10 @@ class MSL(object):\ndef __generate_msl_request_data(self, data):\n#self.__load_msl_data()\n+ mslheader = self.__generate_msl_header()\n+ common.debug('Plaintext headerdata: {}'.format(mslheader))\nheader_encryption_envelope = self.__encrypt(\n- plaintext=self.__generate_msl_header())\n+ plaintext=mslheader)\nheaderdata = base64.standard_b64encode(header_encryption_envelope)\nheader = {\n'headerdata': headerdata,\n@@ -523,7 +527,7 @@ class MSL(object):\nserialized_data += ',\"payload\":{\"data\":\"'\nserialized_data += marshalled_data\nserialized_data += '\"},\"query\":\"\"}]\\n'\n-\n+ common.debug('Serialized data: {}'.format(serialized_data))\ncompressed_data = self.__compress_data(serialized_data)\n# Create FIRST Payload Chunks\n@@ -534,6 +538,7 @@ class MSL(object):\n'sequencenumber': 1,\n'endofmsg': True\n}\n+ common.debug('Plaintext Payload: {}'.format(first_payload))\nfirst_payload_encryption_envelope = self.__encrypt(\nplaintext=json.dumps(first_payload))\npayload = base64.standard_b64encode(first_payload_encryption_envelope)\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add debug output to MSL |
105,989 | 01.11.2018 20:20:33 | -3,600 | 6e0e4caf31e49de69dd73bb0c462c2bb391e8291 | Start of MSL rewrite. Introduce separate module for profiles | [
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -407,3 +407,15 @@ msgstr \"\"\nmsgctxt \"#30097\"\nmsgid \"Main Menu\"\nmsgstr \"\"\n+\n+msgctxt \"#30098\"\n+msgid \"Enable HDR profiles\"\n+msgstr \"\"\n+\n+msgctxt \"#30099\"\n+msgid \"Enable DolbyVision profiles\"\n+msgstr \"\"\n+\n+msgctxt \"#30136\"\n+msgid \"Enable VP9 profiles\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/__init__.py",
"new_path": "resources/lib/services/__init__.py",
"diff": "\"\"\"Background services for the plugin\"\"\"\nfrom __future__ import unicode_literals\n-from .msl.MSLHttpRequestHandler import MSLTCPServer\n+from .msl.http_server import MSLTCPServer\nfrom .library_updater import LibraryUpdateService\nfrom .playback.controller import PlaybackController\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/MSL.py",
"new_path": "resources/lib/services/msl/MSL.py",
"diff": "@@ -23,6 +23,8 @@ import xml.etree.ElementTree as ET\nfrom resources.lib.globals import g\nimport resources.lib.common as common\n+from .profiles import enabled_profiles\n+\n#check if we are on Android\nimport subprocess\ntry:\n@@ -32,11 +34,11 @@ except:\nsdkversion = 0\nif sdkversion >= 18:\n- from MSLMediaDrm import MSLMediaDrmCrypto as MSLHandler\n+ from MSLMediaDrm import MSLMediaDrmCrypto as MSLCrypto\nelse:\n- from MSLCrypto import MSLCrypto as MSLHandler\n+ from MSLCrypto import MSLCrypto as MSLCrypto\n-class MSL(object):\n+class MSLHandler(object):\n# Is a handshake already performed and the keys loaded\nhandshake_performed = False\nlast_drm_context = ''\n@@ -57,7 +59,7 @@ class MSL(object):\nThe Constructor checks for already existing crypto Keys.\nIf they exist it will load the existing keys\n\"\"\"\n- self.crypto = MSLHandler()\n+ self.crypto = MSLCrypto()\nif common.file_exists('msl_data.json'):\ncommon.error('MSL data exists')\n@@ -71,7 +73,7 @@ class MSL(object):\nsignal=common.Signals.ESN_CHANGED,\ncallback=self.perform_key_handshake)\n- def load_manifest(self, viewable_id, dolby, hevc, hdr, dolbyvision, vp9):\n+ def load_manifest(self, viewable_id):\n\"\"\"\nLoads the manifets for the given viewable_id and\nreturns a mpd-XML-Manifest\n@@ -83,25 +85,7 @@ class MSL(object):\n'method': 'manifest',\n'lookupType': 'PREPARE',\n'viewableIds': [viewable_id],\n- 'profiles': [\n- # Video\n- 'playready-h264bpl30-dash',\n- 'playready-h264mpl30-dash',\n- 'playready-h264mpl31-dash',\n- 'playready-h264mpl40-dash',\n-\n- # Audio\n- 'heaac-2-dash',\n-\n- # Subtiltes (handled separately)\n- # 'dfxp-ls-sdh',\n- # 'simplesdh',\n- # 'nflx-cmisc',\n-\n- # Unkown\n- 'BIF240',\n- 'BIF320'\n- ],\n+ 'profiles': enabled_profiles(),\n'drmSystem': 'widevine',\n'appId': '14673889385265',\n'sessionParams': {\n@@ -118,90 +102,6 @@ class MSL(object):\n'clientVersion': '4.0004.899.011',\n'uiVersion': 'akira'\n}\n-\n- # subtitles\n- addon = xbmcaddon.Addon('inputstream.adaptive')\n- if addon and self.nx_common.compare_versions(map(int, addon.getAddonInfo('version').split('.')), [2, 3, 8]):\n- manifest_request_data['profiles'].append('webvtt-lssdh-ios8')\n- else:\n- manifest_request_data['profiles'].append('simplesdh')\n-\n- # add hevc profiles if setting is set\n- if hevc is True:\n- main = 'hevc-main-'\n- main10 = 'hevc-main10-'\n- prk = 'dash-cenc-prk'\n- cenc = 'dash-cenc'\n- ctl = 'dash-cenc-ctl'\n- manifest_request_data['profiles'].append(main10 + 'L41-' + cenc)\n- manifest_request_data['profiles'].append(main10 + 'L50-' + cenc)\n- manifest_request_data['profiles'].append(main10 + 'L51-' + cenc)\n- manifest_request_data['profiles'].append(main + 'L30-' + cenc)\n- manifest_request_data['profiles'].append(main + 'L31-' + cenc)\n- manifest_request_data['profiles'].append(main + 'L40-' + cenc)\n- manifest_request_data['profiles'].append(main + 'L41-' + cenc)\n- manifest_request_data['profiles'].append(main + 'L50-' + cenc)\n- manifest_request_data['profiles'].append(main + 'L51-' + cenc)\n- manifest_request_data['profiles'].append(main10 + 'L30-' + cenc)\n- manifest_request_data['profiles'].append(main10 + 'L31-' + cenc)\n- manifest_request_data['profiles'].append(main10 + 'L40-' + cenc)\n- manifest_request_data['profiles'].append(main10 + 'L41-' + cenc)\n- manifest_request_data['profiles'].append(main10 + 'L50-' + cenc)\n- manifest_request_data['profiles'].append(main10 + 'L51-' + cenc)\n- manifest_request_data['profiles'].append(main10 + 'L30-' + prk)\n- manifest_request_data['profiles'].append(main10 + 'L31-' + prk)\n- manifest_request_data['profiles'].append(main10 + 'L40-' + prk)\n- manifest_request_data['profiles'].append(main10 + 'L41-' + prk)\n- manifest_request_data['profiles'].append(main + 'L30-L31-' + ctl)\n- manifest_request_data['profiles'].append(main + 'L31-L40-' + ctl)\n- manifest_request_data['profiles'].append(main + 'L40-L41-' + ctl)\n- manifest_request_data['profiles'].append(main + 'L50-L51-' + ctl)\n- manifest_request_data['profiles'].append(main10 + 'L30-L31-' + ctl)\n- manifest_request_data['profiles'].append(main10 + 'L31-L40-' + ctl)\n- manifest_request_data['profiles'].append(main10 + 'L40-L41-' + ctl)\n- manifest_request_data['profiles'].append(main10 + 'L50-L51-' + ctl)\n-\n- if hdr is True:\n- hdr = 'hevc-hdr-main10-'\n- manifest_request_data['profiles'].append(hdr + 'L30-' + cenc)\n- manifest_request_data['profiles'].append(hdr + 'L31-' + cenc)\n- manifest_request_data['profiles'].append(hdr + 'L40-' + cenc)\n- manifest_request_data['profiles'].append(hdr + 'L41-' + cenc)\n- manifest_request_data['profiles'].append(hdr + 'L50-' + cenc)\n- manifest_request_data['profiles'].append(hdr + 'L51-' + cenc)\n- manifest_request_data['profiles'].append(hdr + 'L30-' + prk)\n- manifest_request_data['profiles'].append(hdr + 'L31-' + prk)\n- manifest_request_data['profiles'].append(hdr + 'L40-' + prk)\n- manifest_request_data['profiles'].append(hdr + 'L41-' + prk)\n- manifest_request_data['profiles'].append(hdr + 'L50-' + prk)\n- manifest_request_data['profiles'].append(hdr + 'L51-' + prk)\n-\n-\n- if dolbyvision is True:\n- dv = 'hevc-dv-main10-'\n- dv5 = 'hevc-dv5-main10-'\n- manifest_request_data['profiles'].append(dv + 'L30-' + cenc)\n- manifest_request_data['profiles'].append(dv + 'L31-' + cenc)\n- manifest_request_data['profiles'].append(dv + 'L40-' + cenc)\n- manifest_request_data['profiles'].append(dv + 'L41-' + cenc)\n- manifest_request_data['profiles'].append(dv + 'L50-' + cenc)\n- manifest_request_data['profiles'].append(dv + 'L51-' + cenc)\n- manifest_request_data['profiles'].append(dv5 + 'L30-' + prk)\n- manifest_request_data['profiles'].append(dv5 + 'L31-' + prk)\n- manifest_request_data['profiles'].append(dv5 + 'L40-' + prk)\n- manifest_request_data['profiles'].append(dv5 + 'L41-' + prk)\n- manifest_request_data['profiles'].append(dv5 + 'L50-' + prk)\n- manifest_request_data['profiles'].append(dv5 + 'L51-' + prk)\n-\n- if hevc is False or vp9 is True:\n- manifest_request_data['profiles'].append('vp9-profile0-L30-dash-cenc')\n- manifest_request_data['profiles'].append('vp9-profile0-L31-dash-cenc')\n-\n- # Check if dolby sound is enabled and add to profles\n- if dolby:\n- manifest_request_data['profiles'].append('ddplus-2.0-dash')\n- manifest_request_data['profiles'].append('ddplus-5.1-dash')\n-\nrequest_data = self.__generate_msl_request_data(manifest_request_data)\ncommon.debug(request_data)\ntry:\n"
},
{
"change_type": "DELETE",
"old_path": "resources/lib/services/msl/MSLHttpRequestHandler.py",
"new_path": null,
"diff": "-# -*- coding: utf-8 -*-\n-# Author: trummerjo\n-# Module: MSLHttpRequestHandler\n-# Created on: 26.01.2017\n-# License: MIT https://goo.gl/5bMj3H\n-\n-\"\"\"Handles & translates requests from Inputstream to Netflix\"\"\"\n-from __future__ import unicode_literals\n-\n-import base64\n-import BaseHTTPServer\n-from urlparse import urlparse, parse_qs\n-\n-from SocketServer import TCPServer\n-from resources.lib.services.msl.MSL import MSL\n-import resources.lib.common as common\n-\n-\n-class MSLHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n- \"\"\"Handles & translates requests from Inputstream to Netflix\"\"\"\n-\n- # pylint: disable=invalid-name\n- def do_HEAD(self):\n- \"\"\"Answers head requests with a success code\"\"\"\n- self.send_response(200)\n-\n- # pylint: disable=invalid-name\n- def do_POST(self):\n- \"\"\"Loads the licence for the requested resource\"\"\"\n- length = int(self.headers.get('content-length'))\n- post = self.rfile.read(length)\n- data = post.split('!')\n- if len(data) is 2:\n- challenge = data[0]\n- sid = base64.standard_b64decode(data[1])\n- b64license = self.server.msl_handler.get_license(challenge, sid)\n- if b64license is not '':\n- self.send_response(200)\n- self.end_headers()\n- self.wfile.write(base64.standard_b64decode(b64license))\n- self.finish()\n- else:\n- self.server.nx_common.log(msg='Error getting License')\n- self.send_response(400)\n- else:\n- self.server.nx_common.log(msg='Error in License Request')\n- self.send_response(400)\n-\n- # pylint: disable=invalid-name\n- def do_GET(self):\n- \"\"\"Loads the XML manifest for the requested resource\"\"\"\n- url = urlparse(self.path)\n- params = parse_qs(url.query)\n- if 'id' not in params:\n- self.send_response(400, 'No id')\n- else:\n- # Get the manifest with the given id\n- dolby = (True if 'dolby' in params and\n- params['dolby'][0].lower() == 'true' else 'false')\n- hevc = (True if 'hevc' in params and\n- params['hevc'][0].lower() == 'true' else 'false')\n- hdr = (True if 'hdr' in params and\n- params['hdr'][0].lower() == 'true' else 'false')\n- dolbyvision = (True if 'dolbyvision' in params and\n- params['dolbyvision'][0].lower() == 'true' else 'false')\n- vp9 = (True if 'vp9' in params and\n- params['vp9'][0].lower() == 'true' else 'false')\n-\n- data = self.server.msl_handler.load_manifest(\n- int(params['id'][0]),\n- dolby, hevc, hdr, dolbyvision, vp9)\n-\n- self.send_response(200)\n- self.send_header('Content-type', 'application/xml')\n- self.end_headers()\n- self.wfile.write(data)\n-\n- def log_message(self, *args):\n- \"\"\"Disable the BaseHTTPServer Log\"\"\"\n- pass\n-\n-\n-##################################\n-\n-\n-class MSLTCPServer(TCPServer):\n- \"\"\"Override TCPServer to allow usage of shared members\"\"\"\n-\n- def __init__(self, server_address):\n- \"\"\"Initialization of MSLTCPServer\"\"\"\n- common.log('Constructing MSLTCPServer')\n- self.msl_handler = MSL()\n- TCPServer.__init__(self, server_address, MSLHttpRequestHandler)\n-\n- def reset_msl_data(self):\n- \"\"\"Initialization of MSLTCPServerResets MSL data (perform handshake)\"\"\"\n- self.msl_handler.perform_key_handshake()\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/services/msl/exceptions.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Common MSL exceptions\"\"\"\n+from __future__ import unicode_literals\n+\n+\n+class MSLError(Exception):\n+ pass\n+\n+\n+class LicenseError(MSLError):\n+ pass\n+\n+\n+class ManifestError(MSLError):\n+ pass\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/services/msl/http_server.py",
"diff": "+# -*- coding: utf-8 -*-\n+# Author: trummerjo\n+# Module: MSLHttpRequestHandler\n+# Created on: 26.01.2017\n+# License: MIT https://goo.gl/5bMj3H\n+\"\"\"Handles & translates requests from Inputstream to Netflix\"\"\"\n+from __future__ import unicode_literals\n+\n+import base64\n+import BaseHTTPServer\n+from urlparse import urlparse, parse_qs\n+\n+from SocketServer import TCPServer\n+import resources.lib.common as common\n+\n+from .MSL import MSLHandler\n+from .exceptions import MSLError\n+\n+\n+class MSLHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n+ \"\"\"Handles & translates requests from Inputstream to Netflix\"\"\"\n+ # pylint: disable=invalid-name, broad-except\n+ def do_HEAD(self):\n+ \"\"\"Answers head requests with a success code\"\"\"\n+ self.send_response(200)\n+\n+ def do_POST(self):\n+ \"\"\"Loads the licence for the requested resource\"\"\"\n+ try:\n+ length = int(self.headers.get('content-length', 0))\n+ data = self.rfile.read(length).split('!')\n+ b64license = self.server.msl_handler.get_license(\n+ challenge=data[0], sid=base64.standard_b64decode(data[1]))\n+ self.send_response(200)\n+ self.end_headers()\n+ self.wfile.write(base64.standard_b64decode(b64license))\n+ self.finish()\n+ except MSLError as exc:\n+ self.send_error(500, exc.message)\n+ except Exception:\n+ self.send_error(400, 'Invalid license request')\n+\n+ def do_GET(self):\n+ \"\"\"Loads the XML manifest for the requested resource\"\"\"\n+ try:\n+ params = parse_qs(urlparse(self.path).query)\n+ data = self.server.msl_handler.load_manifest(int(params['id'][0]))\n+ self.send_response(200)\n+ self.send_header('Content-type', 'application/xml')\n+ self.end_headers()\n+ self.wfile.write(data)\n+ except MSLError as exc:\n+ self.send_error(500, exc.message)\n+ except Exception:\n+ self.send_error(400, 'Invalid manifest request')\n+\n+ def log_message(self, *args):\n+ # pylint: disable=arguments-differ\n+ \"\"\"Disable the BaseHTTPServer Log\"\"\"\n+ pass\n+\n+\n+class MSLTCPServer(TCPServer):\n+ \"\"\"Override TCPServer to allow usage of shared members\"\"\"\n+ def __init__(self, server_address):\n+ \"\"\"Initialization of MSLTCPServer\"\"\"\n+ common.log('Constructing MSLTCPServer')\n+ self.msl_handler = MSLHandler()\n+ TCPServer.__init__(self, server_address, MSLHttpRequestHandler)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/services/msl/profiles.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"MSL video profiles\"\"\"\n+from __future__ import unicode_literals\n+\n+import xbmcaddon\n+\n+from resources.lib.globals import g\n+\n+HEVC = 'hevc-main-'\n+HEVC_M10 = 'hevc-main10-'\n+CENC_PRK = 'dash-cenc-prk'\n+CENC = 'dash-cenc'\n+CENC_TL = 'dash-cenc-tl'\n+HDR = 'hevc-hdr-main10-'\n+DV = 'hevc-dv-main10-'\n+DV5 = 'hevc-dv5-main10-'\n+\n+BASE_LEVELS = ['L30-', 'L31-', 'L40-', 'L41-', 'L50-', 'L51-']\n+CENC_TL_LEVELS = ['L30-L31-', 'L31-L40-', 'L40-L41-', 'L50-L51-']\n+\n+\n+def _profile_strings(base, tails):\n+ \"\"\"Creates a list of profile strings by concatenating base with all\n+ permutations of tails\"\"\"\n+ return [base + level + tail[1] for tail in tails for level in tail[0]]\n+\n+\n+PROFILES = {\n+ 'base': [\n+ # Video\n+ 'playready-h264bpl30-dash', 'playready-h264mpl30-dash',\n+ 'playready-h264mpl31-dash', 'playready-h264mpl40-dash',\n+ # Audio\n+ 'heaac-2-dash',\n+ # Subtiltes\n+ # 'dfxp-ls-sdh',\n+ # 'simplesdh',\n+ # 'nflx-cmisc',\n+ # Unkown\n+ 'BIF240', 'BIF320'],\n+ 'dolbysound': ['ddplus-2.0-dash', 'ddplus-5.1-dash'],\n+ 'hevc':\n+ _profile_strings(base=HEVC,\n+ tails=[(BASE_LEVELS, CENC),\n+ (CENC_TL_LEVELS, CENC_TL)]) +\n+ _profile_strings(base=HEVC_M10,\n+ tails=[(BASE_LEVELS, CENC),\n+ (BASE_LEVELS[:4], CENC_PRK),\n+ (CENC_TL_LEVELS, CENC_TL)]),\n+ 'hdr':\n+ _profile_strings(base=HDR,\n+ tails=[(BASE_LEVELS, CENC),\n+ (BASE_LEVELS, CENC_PRK)]),\n+ 'dolbyvision':\n+ _profile_strings(base=DV,\n+ tails=[(BASE_LEVELS, CENC)]) +\n+ _profile_strings(base=DV5,\n+ tails=[(BASE_LEVELS, CENC_PRK)]),\n+ 'vp9': ['vp9-profile0-L30-dash-cenc', 'vp9-profile0-L31-dash-cenc']\n+}\n+\n+\n+def enabled_profiles():\n+ \"\"\"Return a list of all base and enabled additional profiles\"\"\"\n+ return (PROFILES['base'] +\n+ _subtitle_profiles() +\n+ _additional_profiles('dolbysound', 'enable_dolby_sound') +\n+ _additional_profiles('hevc', 'enable_hevc_profiles') +\n+ _additional_profiles('hdr',\n+ ['enable_hevc_profiles',\n+ 'enable_hdr_profiles']) +\n+ _additional_profiles('dolbyvision',\n+ ['enable_hevc_profiles',\n+ 'enable_dolbyvision_profiles']) +\n+ _vp9_profiles())\n+\n+\n+def _subtitle_profiles():\n+ inputstream_addon = xbmcaddon.Addon('inputstream.adaptive')\n+ return ['webvtt-lssdh-ios8'\n+ if inputstream_addon.getAddonInfo('version') >= '2.3.8'\n+ else 'simplesdh']\n+\n+\n+def _additional_profiles(profiles, settings):\n+ settings = settings if isinstance(settings, list) else [settings]\n+ return (PROFILES[profiles]\n+ if all(g.ADDON.getSettingBool(setting) for setting in settings)\n+ else [])\n+\n+\n+def _vp9_profiles():\n+ return (PROFILES['vp9']\n+ if (not g.ADDON.getSettingBool('enable_hevc_profiles') or\n+ g.ADDON.getSettingBool('enable_vp9_profiles'))\n+ else [])\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/settings.xml",
"new_path": "resources/settings.xml",
"diff": "<category label=\"30023\">\n<setting id=\"enable_dolby_sound\" type=\"bool\" label=\"30033\" default=\"true\"/>\n<setting id=\"enable_hevc_profiles\" type=\"bool\" label=\"30060\" default=\"false\"/>\n- <setting id=\"enable_hdr_profiles\" type=\"bool\" label=\"30084\" default=\"false\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n- <setting id=\"enable_dolbyvision_profiles\" type=\"bool\" label=\"30085\" default=\"false\" visible=\"eq(-2,true)\" subsetting=\"true\"/>\n- <setting id=\"enable_vp9_profiles\" type=\"bool\" label=\"30086\" default=\"false\"/>\n+ <setting id=\"enable_hdr_profiles\" type=\"bool\" label=\"30098\" default=\"false\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n+ <setting id=\"enable_dolbyvision_profiles\" type=\"bool\" label=\"30099\" default=\"false\" visible=\"eq(-2,true)\" subsetting=\"true\"/>\n+ <setting id=\"enable_vp9_profiles\" type=\"bool\" label=\"30136\" default=\"false\" visible=\"eq(-3,true)\" subsetting=\"true\"/>\n<setting id=\"ssl_verification\" type=\"bool\" label=\"30024\" default=\"true\"/>\n<setting id=\"enable_tracking\" type=\"bool\" label=\"30032\" default=\"true\"/>\n<setting id=\"esn\" type=\"text\" label=\"30034\" value=\"\" default=\"\"/>\n<setting id=\"invalidate_cache_on_mylist_modify\" type=\"bool\" label=\"30086\" default=\"false\"/>\n<setting id=\"hidden_esn\" visible=\"false\" value=\"\" />\n<setting id=\"tracking_id\" value=\"\" visible=\"false\"/>\n- <setting id=\"locale_id\" visible=\"false\" value=\"en-US\" />\n<setting id=\"msl_service_port\" value=\"8000\" visible=\"false\"/>\n<setting id=\"show_update_db\" type=\"bool\" default=\"false\" visible=\"false\"/>\n</category>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Start of MSL rewrite. Introduce separate module for profiles |
105,989 | 01.11.2018 21:58:05 | -3,600 | f1a6fbd650649369449d4780e98a9f10a9f2f1ce | Refactor MPD conversion | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/MSL.py",
"new_path": "resources/lib/services/msl/MSL.py",
"diff": "@@ -24,6 +24,7 @@ from resources.lib.globals import g\nimport resources.lib.common as common\nfrom .profiles import enabled_profiles\n+from .converter import convert_to_dash\n#check if we are on Android\nimport subprocess\n@@ -209,189 +210,11 @@ class MSLHandler(object):\nreturn json.JSONDecoder().decode(decrypted_payload)\ndef __tranform_to_dash(self, manifest):\n- common.save_file(filename='manifest.json', content=json.dumps(manifest))\n+ common.save_file('manifest.json', json.dumps(manifest))\nmanifest = manifest['result']['viewables'][0]\n-\nself.last_playback_context = manifest['playbackContextId']\nself.last_drm_context = manifest['drmContextId']\n-\n- # Check for pssh\n- pssh = ''\n- keyid = None\n- if 'psshb64' in manifest:\n- if len(manifest['psshb64']) >= 1:\n- pssh = manifest['psshb64'][0]\n- psshbytes = base64.standard_b64decode(pssh)\n- if len(psshbytes) == 52:\n- keyid = psshbytes[36:]\n-\n- seconds = manifest['runtime']/1000\n- init_length = seconds / 2 * 12 + 20*1000\n- duration = \"PT\"+str(seconds)+\".00S\"\n-\n- root = ET.Element('MPD')\n- root.attrib['xmlns'] = 'urn:mpeg:dash:schema:mpd:2011'\n- root.attrib['xmlns:cenc'] = 'urn:mpeg:cenc:2013'\n- root.attrib['mediaPresentationDuration'] = duration\n-\n- period = ET.SubElement(root, 'Period', start='PT0S', duration=duration)\n-\n- # One Adaption Set for Video\n- for video_track in manifest['videoTracks']:\n- video_adaption_set = ET.SubElement(\n- parent=period,\n- tag='AdaptationSet',\n- mimeType='video/mp4',\n- contentType=\"video\")\n-\n- # Content Protection\n- if keyid:\n- protection = ET.SubElement(\n- parent=video_adaption_set,\n- tag='ContentProtection',\n- value='cenc',\n- schemeIdUri='urn:mpeg:dash:mp4protection:2011')\n- protection.set('cenc:default_KID', str(uuid.UUID(bytes=keyid)))\n-\n- protection = ET.SubElement(\n- parent=video_adaption_set,\n- tag='ContentProtection',\n- schemeIdUri='urn:uuid:EDEF8BA9-79D6-4ACE-A3C8-27DCD51D21ED')\n-\n- ET.SubElement(\n- parent=protection,\n- tag='widevine:license',\n- robustness_level='HW_SECURE_CODECS_REQUIRED')\n-\n- if pssh is not '':\n- ET.SubElement(protection, 'cenc:pssh').text = pssh\n-\n- for downloadable in video_track['downloadables']:\n-\n- codec = 'h264'\n- if 'hevc' in downloadable['contentProfile']:\n- codec = 'hevc'\n- elif downloadable['contentProfile'] == 'vp9-profile0-L30-dash-cenc':\n- codec = 'vp9.0.30'\n- elif downloadable['contentProfile'] == 'vp9-profile0-L31-dash-cenc':\n- codec = 'vp9.0.31'\n-\n- hdcp_versions = '0.0'\n- for hdcp in downloadable['hdcpVersions']:\n- if hdcp != 'none':\n- hdcp_versions = hdcp if hdcp != 'any' else '1.0'\n-\n- rep = ET.SubElement(\n- parent=video_adaption_set,\n- tag='Representation',\n- width=str(downloadable['width']),\n- height=str(downloadable['height']),\n- bandwidth=str(downloadable['bitrate']*1024),\n- hdcp=hdcp_versions,\n- nflxContentProfile=str(downloadable['contentProfile']),\n- codecs=codec,\n- mimeType='video/mp4')\n-\n- # BaseURL\n- base_url = self.__get_base_url(downloadable['urls'])\n- ET.SubElement(rep, 'BaseURL').text = base_url\n- # Init an Segment block\n- segment_base = ET.SubElement(\n- parent=rep,\n- tag='SegmentBase',\n- indexRange='0-' + str(init_length),\n- indexRangeExact='true')\n-\n- # Multiple Adaption Set for audio\n- language = None\n- for audio_track in manifest['audioTracks']:\n- impaired = 'false'\n- original = 'false'\n- default = 'false'\n-\n- if audio_track.get('trackType') == 'ASSISTIVE':\n- impaired = 'true'\n- elif not language or language == audio_track.get('language'):\n- language = audio_track.get('language')\n- default = 'true'\n- if audio_track.get('language').find('[') > 0:\n- original = 'true'\n-\n- audio_adaption_set = ET.SubElement(\n- parent=period,\n- tag='AdaptationSet',\n- lang=audio_track['bcp47'],\n- contentType='audio',\n- mimeType='audio/mp4',\n- impaired=impaired,\n- original=original,\n- default=default)\n- for downloadable in audio_track['downloadables']:\n- codec = 'aac'\n- #common.log(downloadable)\n- is_dplus2 = downloadable['contentProfile'] == 'ddplus-2.0-dash'\n- is_dplus5 = downloadable['contentProfile'] == 'ddplus-5.1-dash'\n- if is_dplus2 or is_dplus5:\n- codec = 'ec-3'\n- #common.log('codec is: ' + codec)\n- rep = ET.SubElement(\n- parent=audio_adaption_set,\n- tag='Representation',\n- codecs=codec,\n- bandwidth=str(downloadable['bitrate']*1024),\n- mimeType='audio/mp4')\n-\n- # AudioChannel Config\n- uri = 'urn:mpeg:dash:23003:3:audio_channel_configuration:2011'\n- ET.SubElement(\n- parent=rep,\n- tag='AudioChannelConfiguration',\n- schemeIdUri=uri,\n- value=str(audio_track.get('channelsCount')))\n-\n- # BaseURL\n- base_url = self.__get_base_url(downloadable['urls'])\n- ET.SubElement(rep, 'BaseURL').text = base_url\n- # Index range\n- segment_base = ET.SubElement(\n- parent=rep,\n- tag='SegmentBase',\n- indexRange='0-' + str(init_length),\n- indexRangeExact='true')\n-\n- # Multiple Adaption Sets for subtiles\n- for text_track in manifest.get('textTracks'):\n- is_downloadables = 'downloadables' not in text_track\n- if is_downloadables or text_track.get('downloadables') is None:\n- continue\n- # Only one subtitle representation per adaptationset\n- downloadable = text_track['downloadables'][0]\n-\n- subtiles_adaption_set = ET.SubElement(\n- parent=period,\n- tag='AdaptationSet',\n- lang=text_track.get('bcp47'),\n- codecs='wvtt' if downloadable.get('contentProfile') == 'webvtt-lssdh-ios8' else 'stpp',\n- contentType='text',\n- mimeType='text/vtt' if downloadable.get('contentProfile') == 'webvtt-lssdh-ios8' else 'application/ttml+xml')\n- role = ET.SubElement(\n- parent=subtiles_adaption_set,\n- tag = 'Role',\n- schemeIdUri = 'urn:mpeg:dash:role:2011',\n- value = 'forced' if text_track.get('isForced') == True else 'main')\n- rep = ET.SubElement(\n- parent=subtiles_adaption_set,\n- tag='Representation',\n- nflxProfile=downloadable.get('contentProfile'))\n- base_url = self.__get_base_url(downloadable['urls'])\n- ET.SubElement(rep, 'BaseURL').text = base_url\n-\n- xml = ET.tostring(root, encoding='utf-8', method='xml')\n- xml = xml.replace('\\n', '').replace('\\r', '')\n-\n- common.save_file(filename='manifest.mpd', content=xml)\n-\n- return xml\n+ return convert_to_dash(manifest)\ndef __get_base_url(self, urls):\nfor key in urls:\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/services/msl/converter.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Manifest format conversion\"\"\"\n+from __future__ import unicode_literals\n+\n+import base64\n+import uuid\n+import xml.etree.ElementTree as ET\n+\n+import resources.lib.common as common\n+\n+\n+def convert_to_dash(manifest):\n+ \"\"\"Convert a Netflix style manifest to MPEGDASH manifest\"\"\"\n+ seconds = manifest['runtime']/1000\n+ init_length = seconds / 2 * 12 + 20*1000\n+ duration = \"PT\"+str(seconds)+\".00S\"\n+\n+ root = _mpd_manifest_root(duration)\n+ period = ET.SubElement(root, 'Period', start='PT0S', duration=duration)\n+ protection = _protection_info(manifest)\n+\n+ for video_track in manifest['videoTracks']:\n+ _convert_video_track(\n+ video_track, period, init_length, protection)\n+\n+ for index, audio_track in enumerate(manifest['audioTracks']):\n+ # Assume that first listed track is the default\n+ _convert_audio_track(audio_track, period, init_length,\n+ default=(index == 0))\n+\n+ for text_track in manifest.get('textTracks'):\n+ _convert_text_track(text_track, period)\n+\n+ xml = ET.tostring(root, encoding='utf-8', method='xml')\n+ common.save_file('manifest.mpd', xml)\n+ return xml.replace('\\n', '').replace('\\r', '')\n+\n+\n+def _mpd_manifest_root(duration):\n+ root = ET.Element('MPD')\n+ root.attrib['xmlns'] = 'urn:mpeg:dash:schema:mpd:2011'\n+ root.attrib['xmlns:cenc'] = 'urn:mpeg:cenc:2013'\n+ root.attrib['mediaPresentationDuration'] = duration\n+ return root\n+\n+\n+def _protection_info(manifest):\n+ try:\n+ pssh = manifest['psshb64'][0]\n+ psshbytes = base64.standard_b64decode(pssh)\n+ if len(psshbytes) == 52:\n+ keyid = psshbytes[36:]\n+ except (KeyError, AttributeError, IndexError):\n+ pssh = None\n+ keyid = None\n+ return {'pssh': pssh, 'keyid': keyid}\n+\n+\n+def _convert_video_track(video_track, period, init_length, protection):\n+ adaptation_set = ET.SubElement(\n+ parent=period,\n+ tag='AdaptationSet',\n+ mimeType='video/mp4',\n+ contentType='video')\n+ _add_protection_info(adaptation_set, **protection)\n+ for downloadable in video_track['downloadables']:\n+ _convert_video_downloadable(\n+ downloadable, adaptation_set, init_length)\n+\n+\n+def _add_protection_info(adaptation_set, pssh, keyid):\n+ if keyid:\n+ protection = ET.SubElement(\n+ parent=adaptation_set,\n+ tag='ContentProtection',\n+ value='cenc',\n+ schemeIdUri='urn:mpeg:dash:mp4protection:2011').set(\n+ 'cenc:default_KID', str(uuid.UUID(bytes=keyid)))\n+ protection = ET.SubElement(\n+ parent=adaptation_set,\n+ tag='ContentProtection',\n+ schemeIdUri='urn:uuid:EDEF8BA9-79D6-4ACE-A3C8-27DCD51D21ED')\n+ ET.SubElement(\n+ parent=protection,\n+ tag='widevine:license',\n+ robustness_level='HW_SECURE_CODECS_REQUIRED')\n+ if pssh:\n+ ET.SubElement(protection, 'cenc:pssh').text = pssh\n+\n+\n+def _convert_video_downloadable(downloadable, adaptation_set,\n+ init_length):\n+ codec = ('hevc'\n+ if 'hevc' in downloadable['contentProfile']\n+ else 'h264')\n+ hdcp_versions = next((hdcp\n+ for hdcp\n+ in downloadable['hdcpVersions']\n+ if hdcp != 'none'), '0.0')\n+ representation = ET.SubElement(\n+ parent=adaptation_set,\n+ tag='Representation',\n+ width=str(downloadable['width']),\n+ height=str(downloadable['height']),\n+ bandwidth=str(downloadable['bitrate']*1024),\n+ hdcp=hdcp_versions,\n+ nflxContentProfile=str(downloadable['contentProfile']),\n+ codecs=codec,\n+ mimeType='video/mp4')\n+ _add_base_url(representation, downloadable)\n+ _add_segment_base(representation, init_length)\n+\n+\n+def _convert_audio_track(audio_track, period, init_length, default):\n+ adaptation_set = ET.SubElement(\n+ parent=period,\n+ tag='AdaptationSet',\n+ lang=audio_track['bcp47'],\n+ contentType='audio',\n+ mimeType='audio/mp4',\n+ impaired=str(audio_track.get('trackType') == 'ASSISTIVE').lower(),\n+ original=str(audio_track.get('language', '').find('[') > 0).lower(),\n+ default=str(default).lower())\n+ for downloadable in audio_track['downloadables']:\n+ _convert_audio_downloadable(\n+ downloadable, adaptation_set, init_length,\n+ audio_track.get('channelsCount'))\n+\n+\n+def _convert_audio_downloadable(downloadable, adaptation_set, init_length,\n+ channels_count):\n+ is_dplus2 = downloadable['contentProfile'] == 'ddplus-2.0-dash'\n+ is_dplus5 = downloadable['contentProfile'] == 'ddplus-5.1-dash'\n+ representation = ET.SubElement(\n+ parent=adaptation_set,\n+ tag='Representation',\n+ codecs='ec-3' if is_dplus2 or is_dplus5 else 'aac',\n+ bandwidth=str(downloadable['bitrate']*1024),\n+ mimeType='audio/mp4')\n+ ET.SubElement(\n+ parent=representation,\n+ tag='AudioChannelConfiguration',\n+ schemeIdUri='urn:mpeg:dash:23003:3:audio_channel_configuration:2011',\n+ value=str(channels_count))\n+ _add_base_url(representation, downloadable)\n+ _add_segment_base(representation, init_length)\n+\n+\n+def _convert_text_track(text_track, period):\n+ if text_track.get('downloadables'):\n+ # Only one subtitle representation per adaptationset\n+ downloadable = text_track['downloadables'][0]\n+ is_ios8 = downloadable.get('contentProfile') == 'webvtt-lssdh-ios8'\n+ adaptation_set = ET.SubElement(\n+ parent=period,\n+ tag='AdaptationSet',\n+ lang=text_track.get('bcp47'),\n+ codecs=('stpp', 'wvtt')[is_ios8],\n+ contentType='text',\n+ mimeType=('application/ttml+xml', 'text/vtt')[is_ios8])\n+ ET.SubElement(\n+ parent=adaptation_set,\n+ tag='Role',\n+ schemeIdUri='urn:mpeg:dash:role:2011',\n+ value='forced' if text_track.get('isForced') else 'main')\n+ representation = ET.SubElement(\n+ parent=adaptation_set,\n+ tag='Representation',\n+ nflxProfile=downloadable.get('contentProfile'))\n+ _add_base_url(representation, downloadable)\n+\n+\n+def _add_base_url(representation, downloadable):\n+ ET.SubElement(\n+ parent=representation,\n+ tag='BaseURL').text = downloadable['urls'].values()[0]\n+\n+\n+def _add_segment_base(representation, init_length):\n+ ET.SubElement(\n+ parent=representation,\n+ tag='SegmentBase',\n+ indexRange='0-' + str(init_length),\n+ indexRangeExact='true')\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Refactor MPD conversion |
105,989 | 01.11.2018 22:39:07 | -3,600 | d5552298e5f8389b167f6beee3f6c39cc15a9ba7 | Refactor crypto operations | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/MSL.py",
"new_path": "resources/lib/services/msl/MSL.py",
"diff": "@@ -37,7 +37,7 @@ except:\nif sdkversion >= 18:\nfrom MSLMediaDrm import MSLMediaDrmCrypto as MSLCrypto\nelse:\n- from MSLCrypto import MSLCrypto as MSLCrypto\n+ from .default_crypto import MSLCrypto as MSLCrypto\nclass MSLHandler(object):\n# Is a handshake already performed and the keys loaded\n@@ -55,21 +55,13 @@ class MSLHandler(object):\n}\ndef __init__(self):\n-\n- \"\"\"\n- The Constructor checks for already existing crypto Keys.\n- If they exist it will load the existing keys\n- \"\"\"\n+ # pylint: disable=broad-except\n+ try:\n+ msl_data = json.loads(common.load_file('msl_data.json'))\n+ self.crypto = MSLCrypto(msl_data)\n+ except Exception:\nself.crypto = MSLCrypto()\n-\n- if common.file_exists('msl_data.json'):\n- common.error('MSL data exists')\n- self.init_msl_data()\n- else:\n- common.error('MSL data does not exist')\n- self.crypto.fromDict(None)\n- self.__perform_key_handshake()\n-\n+ self.perform_key_handshake()\ncommon.register_slot(\nsignal=common.Signals.ESN_CHANGED,\ncallback=self.perform_key_handshake)\n@@ -234,13 +226,12 @@ class MSLHandler(object):\n#self.__load_msl_data()\nmslheader = self.__generate_msl_header()\ncommon.debug('Plaintext headerdata: {}'.format(mslheader))\n- header_encryption_envelope = self.__encrypt(\n- plaintext=mslheader)\n+ header_encryption_envelope = self.crypto.encrypt(mslheader)\nheaderdata = base64.standard_b64encode(header_encryption_envelope)\nheader = {\n'headerdata': headerdata,\n- 'signature': self.__sign(header_encryption_envelope),\n- 'mastertoken': self.mastertoken,\n+ 'signature': self.crypto.sign(header_encryption_envelope),\n+ 'mastertoken': self.crypto.mastertoken,\n}\n# Serialize the given Data\n@@ -262,12 +253,11 @@ class MSLHandler(object):\n'endofmsg': True\n}\ncommon.debug('Plaintext Payload: {}'.format(first_payload))\n- first_payload_encryption_envelope = self.__encrypt(\n- plaintext=json.dumps(first_payload))\n+ first_payload_encryption_envelope = self.crypto.encrypt(json.dumps(first_payload))\npayload = base64.standard_b64encode(first_payload_encryption_envelope)\nfirst_payload_chunk = {\n'payload': payload,\n- 'signature': self.__sign(first_payload_encryption_envelope),\n+ 'signature': self.crypto.sign(first_payload_encryption_envelope),\n}\nrequest_data = json.dumps(header) + json.dumps(first_payload_chunk)\nreturn request_data\n@@ -328,23 +318,7 @@ class MSLHandler(object):\nreturn json.dumps(header_data)\n- def __encrypt(self, plaintext):\n- return json.dumps(self.crypto.encrypt(plaintext, g.get_esn(), self.sequence_number))\n-\n- def __sign(self, text):\n- \"\"\"\n- Calculates the HMAC signature for the given\n- text with the current sign key and SHA256\n-\n- :param text:\n- :return: Base64 encoded signature\n- \"\"\"\n- return base64.standard_b64encode(self.crypto.sign(text))\n-\ndef perform_key_handshake(self):\n- self.__perform_key_handshake()\n-\n- def __perform_key_handshake(self):\nesn = g.get_esn()\ncommon.log('perform_key_handshake: esn:' + esn)\n@@ -390,61 +364,7 @@ class MSLHandler(object):\nbase_head = base64.standard_b64decode(resp['headerdata'])\nheaderdata=json.JSONDecoder().decode(base_head)\n- self.__set_master_token(headerdata['keyresponsedata']['mastertoken'])\nself.crypto.parse_key_response(headerdata)\n- self.__save_msl_data()\nelse:\ncommon.log('Key Exchange failed')\ncommon.log(resp.text)\n-\n- def init_msl_data(self):\n- common.log('MSL Data exists. Use old Tokens.')\n- self.__load_msl_data()\n- self.handshake_performed = True\n-\n- def __load_msl_data(self):\n- raw_msl_data = common.load_file('msl_data.json')\n- msl_data = json.JSONDecoder().decode(raw_msl_data)\n- # Check expire date of the token\n- raw_token = msl_data['tokens']['mastertoken']['tokendata']\n- base_token = base64.standard_b64decode(raw_token)\n- master_token = json.JSONDecoder().decode(base_token)\n- exp = int(master_token['expiration'])\n- valid_until = datetime.utcfromtimestamp(exp)\n- present = datetime.now()\n- difference = valid_until - present\n- # If token expires in less then 10 hours or is expires renew it\n- common.log('Expiration time: Key:' + str(valid_until) + ', Now:' + str(present) + ', Diff:' + str(difference.total_seconds()))\n- difference = difference.total_seconds() / 60 / 60\n- if self.crypto.fromDict(msl_data) or difference < 10:\n- self.__perform_key_handshake()\n- return\n-\n- self.__set_master_token(msl_data['tokens']['mastertoken'])\n-\n- def save_msl_data(self):\n- self.__save_msl_data()\n-\n- def __save_msl_data(self):\n- \"\"\"\n- Saves the keys and tokens in json file\n- :return:\n- \"\"\"\n- data = {\n- 'tokens': {\n- 'mastertoken': self.mastertoken\n- }\n- }\n- data.update(self.crypto.toDict())\n-\n- serialized_data = json.JSONEncoder().encode(data)\n- common.save_file(\n- filename='msl_data.json',\n- content=serialized_data)\n-\n- def __set_master_token(self, master_token):\n- self.mastertoken = master_token\n- raw_token = master_token['tokendata']\n- base_token = base64.standard_b64decode(raw_token)\n- decoded_token = json.JSONDecoder().decode(base_token)\n- self.sequence_number = decoded_token.get('sequencenumber')\n"
},
{
"change_type": "DELETE",
"old_path": "resources/lib/services/msl/MSLCrypto.py",
"new_path": null,
"diff": "-# -*- coding: utf-8 -*-\n-# Author: trummerjo\n-# Module: MSLHttpRequestHandler\n-# Created on: 26.01.2017\n-# License: MIT https://goo.gl/5bMj3H\n-from __future__ import unicode_literals\n-\n-import json\n-import base64\n-from Cryptodome.Random import get_random_bytes\n-from Cryptodome.Hash import HMAC, SHA256\n-from Cryptodome.Cipher import PKCS1_OAEP\n-from Cryptodome.PublicKey import RSA\n-from Cryptodome.Util import Padding\n-from Cryptodome.Cipher import AES\n-\n-import resources.lib.common as common\n-\n-\n-class MSLCrypto():\n-\n- def __init__(self):\n- self.encryption_key = None\n- self.sign_key = None\n-\n- def __init_generate_rsa_keys(self):\n- common.log('Create new RSA Keys')\n- # Create new Key Pair and save\n- self.rsa_key = RSA.generate(2048)\n-\n- @staticmethod\n- def __base64key_decode(payload):\n- l = len(payload) % 4\n- if l == 2:\n- payload += '=='\n- elif l == 3:\n- payload += '='\n- elif l != 0:\n- raise ValueError('Invalid base64 string')\n- return base64.urlsafe_b64decode(payload.encode('utf-8'))\n-\n- def toDict(self):\n- common.log('Provide RSA Keys to dict')\n- # Get the DER Base64 of the keys\n- encrypted_key = self.rsa_key.exportKey()\n-\n- data = {\n- \"encryption_key\": base64.standard_b64encode(self.encryption_key),\n- 'sign_key': base64.standard_b64encode(self.sign_key),\n- 'rsa_key': base64.standard_b64encode(encrypted_key)\n- }\n- return data\n-\n- def fromDict(self, msl_data):\n- need_handshake = False\n- rsa_key = None\n-\n- try:\n- common.log('Parsing RSA Keys from Dict')\n- self.encryption_key = base64.standard_b64decode(msl_data['encryption_key'])\n- self.sign_key = base64.standard_b64decode(msl_data['sign_key'])\n- rsa_key = base64.standard_b64decode(msl_data['rsa_key'])\n- self.rsa_key = RSA.importKey(rsa_key)\n- except:\n- need_handshake = True\n-\n- if not rsa_key:\n- need_handshake = True\n- self.__init_generate_rsa_keys()\n-\n- if not (self.encryption_key and self.sign_key):\n- need_handshake = True\n-\n- return need_handshake\n-\n- def get_key_request(self):\n- raw_key = self.rsa_key.publickey().exportKey(format='DER')\n- public_key = base64.standard_b64encode(raw_key)\n-\n- key_request = [{\n- 'scheme': 'ASYMMETRIC_WRAPPED',\n- 'keydata': {\n- 'publickey': public_key,\n- 'mechanism': 'JWK_RSA',\n- 'keypairid': 'superKeyPair'\n- }\n- }]\n- return key_request\n-\n- def parse_key_response(self, headerdata):\n- # Init Decryption\n- enc_key = headerdata['keyresponsedata']['keydata']['encryptionkey']\n- hmac_key = headerdata['keyresponsedata']['keydata']['hmackey']\n- encrypted_encryption_key = base64.standard_b64decode(enc_key)\n- encrypted_sign_key = base64.standard_b64decode(hmac_key)\n- cipher_rsa = PKCS1_OAEP.new(self.rsa_key)\n-\n- # Decrypt encryption key\n- cipher_raw = cipher_rsa.decrypt(encrypted_encryption_key)\n- encryption_key_data = json.JSONDecoder().decode(cipher_raw)\n- self.encryption_key = self.__base64key_decode(encryption_key_data['k'])\n-\n- # Decrypt sign key\n- sign_key_raw = cipher_rsa.decrypt(encrypted_sign_key)\n- sign_key_data = json.JSONDecoder().decode(sign_key_raw)\n- self.sign_key = self.__base64key_decode(sign_key_data['k'])\n-\n- def decrypt(self, iv, data):\n- cipher = AES.new(self.encryption_key, AES.MODE_CBC, iv)\n- return Padding.unpad(cipher.decrypt(data), 16)\n-\n- def encrypt(self, data, esn, sequence_number):\n- \"\"\"\n- Encrypt the given Plaintext with the encryption key\n- :param plaintext:\n- :return: Serialized JSON String of the encryption Envelope\n- \"\"\"\n- iv = get_random_bytes(16)\n- encryption_envelope = {\n- 'ciphertext': '',\n- 'keyid': esn + '_' + str(sequence_number),\n- 'sha256': 'AA==',\n- 'iv': base64.standard_b64encode(iv)\n- }\n- # Padd the plaintext\n- plaintext = Padding.pad(data, 16)\n- # Encrypt the text\n- cipher = AES.new(self.encryption_key, AES.MODE_CBC, iv)\n- citext = cipher.encrypt(plaintext)\n- encryption_envelope['ciphertext'] = base64.standard_b64encode(citext)\n-\n- return encryption_envelope;\n-\n- def sign(self, message):\n- return HMAC.new(self.sign_key, message, SHA256).digest()\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/services/msl/default_crypto.py",
"diff": "+# -*- coding: utf-8 -*-\n+# Author: trummerjo\n+# Module: MSLHttpRequestHandler\n+# Created on: 26.01.2017\n+# License: MIT https://goo.gl/5bMj3H\n+\"\"\"Crypto handler for non-Android platforms\"\"\"\n+from __future__ import unicode_literals\n+\n+import time\n+import json\n+import base64\n+from Cryptodome.Random import get_random_bytes\n+from Cryptodome.Hash import HMAC, SHA256\n+from Cryptodome.Cipher import PKCS1_OAEP\n+from Cryptodome.PublicKey import RSA\n+from Cryptodome.Util import Padding\n+from Cryptodome.Cipher import AES\n+\n+from resources.lib.globals import g\n+import resources.lib.common as common\n+\n+from .exceptions import MastertokenExpired\n+\n+\n+class MSLCrypto(object):\n+ \"\"\"Crypto Handler for non-Android platforms\"\"\"\n+ def __init__(self, msl_data=None):\n+ # pylint: disable=broad-except\n+ try:\n+ self.encryption_key = base64.standard_b64decode(\n+ msl_data['encryption_key'])\n+ self.sign_key = base64.standard_b64decode(\n+ msl_data['sign_key'])\n+ if not self.encryption_key or not self.sign_key:\n+ raise ValueError('Missing encryption_key or sign_key')\n+ self.rsa_key = RSA.importKey(\n+ base64.standard_b64decode(msl_data['rsa_key']))\n+ self._set_mastertoken(msl_data['tokens']['mastertoken'])\n+ common.debug('Loaded crypto keys')\n+ except Exception:\n+ common.debug('Generating new RSA keys')\n+ self.rsa_key = RSA.generate(2048)\n+ self.encryption_key = None\n+ self.sign_key = None\n+\n+ def key_request_data(self):\n+ \"\"\"Return a key request dict\"\"\"\n+ public_key = base64.standard_b64encode(\n+ self.rsa_key.publickey().exportKey(format='DER'))\n+ return [{'scheme': 'ASYMMETRIC_WRAPPED',\n+ 'keydata': {\n+ 'publickey': public_key,\n+ 'mechanism': 'JWK_RSA',\n+ 'keypairid': 'superKeyPair'\n+ }}]\n+\n+ def parse_key_response(self, headerdata):\n+ \"\"\"Parse a key response and assign contained encryption_key and\n+ sign_key\"\"\"\n+ self._set_mastertoken(headerdata['keyresponsedata']['mastertoken'])\n+ cipher = PKCS1_OAEP.new(self.rsa_key)\n+ encrypted_encryption_key = base64.standard_b64decode(\n+ headerdata['keyresponsedata']['keydata']['encryptionkey'])\n+ encrypted_sign_key = base64.standard_b64decode(\n+ headerdata['keyresponsedata']['keydata']['hmackey'])\n+ self.encryption_key = _decrypt_key(encrypted_encryption_key, cipher)\n+ self.sign_key = _decrypt_key(encrypted_sign_key, cipher)\n+ self._save_msl_data()\n+\n+ def encrypt(self, plaintext):\n+ \"\"\"\n+ Encrypt the given Plaintext with the encryption key\n+ :param plaintext:\n+ :return: Serialized JSON String of the encryption Envelope\n+ \"\"\"\n+ init_vector = get_random_bytes(16)\n+ cipher = AES.new(self.encryption_key, AES.MODE_CBC, init_vector)\n+ encryption_envelope = {\n+ 'ciphertext': '',\n+ 'keyid': '_'.join((g.get_esn(), str(self.sequence_number))),\n+ 'sha256': 'AA==',\n+ 'iv': base64.standard_b64encode(init_vector)\n+ }\n+ encryption_envelope['ciphertext'] = base64.standard_b64encode(\n+ cipher.encrypt(Padding.pad(plaintext, 16)))\n+\n+ return json.dumps(encryption_envelope)\n+\n+ def decrypt(self, init_vector, data):\n+ \"\"\"Decrypt a ciphertext\"\"\"\n+ cipher = AES.new(self.encryption_key, AES.MODE_CBC, init_vector)\n+ return Padding.unpad(cipher.decrypt(data), 16)\n+\n+ def sign(self, message):\n+ \"\"\"Sign a message\"\"\"\n+ return base64.standard_b64encode(\n+ HMAC.new(self.sign_key, message, SHA256).digest())\n+\n+ def _save_msl_data(self):\n+ \"\"\"Save encryption keys and mastertoken to disk\"\"\"\n+ msl_data = {\n+ 'tokens': {'mastertoken': self.mastertoken},\n+ 'encryption_key': base64.standard_b64encode(self.encryption_key),\n+ 'sign_key': base64.standard_b64encode(self.sign_key),\n+ 'rsa_key': base64.standard_b64encode(self.rsa_key.exportKey())\n+ }\n+ common.save_file('msl_data.json', json.dumps(msl_data))\n+ common.debug('Successfully saved MSL data to disk')\n+\n+ def _set_mastertoken(self, mastertoken):\n+ tokendata = json.loads(\n+ base64.standard_b64decode(mastertoken['tokendata']))\n+ remaining_ttl = (int(tokendata['expiration']) - time.time())\n+ if remaining_ttl / 60 / 60 >= 10:\n+ self.mastertoken = mastertoken\n+ self.sequence_number = tokendata.get('sequencenumber', 0)\n+ else:\n+ raise MastertokenExpired\n+\n+\n+def _decrypt_key(encrypted_key, cipher):\n+ return _base64key_decode(json.loads(cipher.decrypt(encrypted_key))['k'])\n+\n+\n+def _base64key_decode(payload):\n+ length = len(payload) % 4\n+ if length == 2:\n+ payload += '=='\n+ elif length == 3:\n+ payload += '='\n+ elif length != 0:\n+ raise ValueError('Invalid base64 string')\n+ return base64.urlsafe_b64decode(payload.encode('utf-8'))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/exceptions.py",
"new_path": "resources/lib/services/msl/exceptions.py",
"diff": "@@ -13,3 +13,7 @@ class LicenseError(MSLError):\nclass ManifestError(MSLError):\npass\n+\n+\n+class MastertokenExpired(MSLError):\n+ pass\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Refactor crypto operations |
105,989 | 01.11.2018 23:08:46 | -3,600 | 5e52b3b146dc1d07c626329b47603ba4274c9dec | Refactor handling of MSL responses | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/MSL.py",
"new_path": "resources/lib/services/msl/MSL.py",
"diff": "@@ -25,6 +25,7 @@ import resources.lib.common as common\nfrom .profiles import enabled_profiles\nfrom .converter import convert_to_dash\n+from .exceptions import MSLError, LicenseError\n#check if we are on Android\nimport subprocess\n@@ -39,27 +40,36 @@ if sdkversion >= 18:\nelse:\nfrom .default_crypto import MSLCrypto as MSLCrypto\n+CHROME_BASE_URL = 'http://www.netflix.com/api/msl/NFCDCH-LX/cadmium/'\n+ENDPOINTS = {\n+ 'chrome': {\n+ 'manifest': CHROME_BASE_URL + 'manifest',\n+ 'license': CHROME_BASE_URL + 'license'},\n+ 'edge': {\n+ 'manifest': None,\n+ 'license': None}\n+}\n+\n+\nclass MSLHandler(object):\n# Is a handshake already performed and the keys loaded\n- handshake_performed = False\nlast_drm_context = ''\nlast_playback_context = ''\ncurrent_message_id = 0\nsession = requests.session()\nrndm = random.SystemRandom()\ntokens = []\n- base_url = 'http://www.netflix.com/api/msl/NFCDCH-LX/cadmium/'\n- endpoints = {\n- 'manifest': base_url + 'manifest',\n- 'license': base_url + 'license'\n- }\ndef __init__(self):\n# pylint: disable=broad-except\ntry:\nmsl_data = json.loads(common.load_file('msl_data.json'))\nself.crypto = MSLCrypto(msl_data)\n+ common.debug('Loaded MSL data from disk')\nexcept Exception:\n+ import traceback\n+ common.debug(traceback.format_exc())\n+ common.debug('Stored MSL data expired or not available')\nself.crypto = MSLCrypto()\nself.perform_key_handshake()\ncommon.register_slot(\n@@ -97,32 +107,9 @@ class MSLHandler(object):\n}\nrequest_data = self.__generate_msl_request_data(manifest_request_data)\ncommon.debug(request_data)\n- try:\n- resp = self.session.post(self.endpoints['manifest'], request_data)\n- except:\n- resp = None\n- exc = sys.exc_info()\n- msg = '[MSL][POST] Error {} {}'\n- common.log(msg.format(exc[0], exc[1]))\n-\n- if resp:\n- try:\n- # if the json() does not fail we have an error because\n- # the manifest response is a chuncked json response\n- resp.json()\n- common.log(\n- msg='Error getting Manifest: ' + resp.text)\n- return False\n- except ValueError:\n- # json() failed so parse the chunked response\n- #common.log(\n- # msg='Got chunked Manifest Response: ' + resp.text)\n- resp = self.__parse_chunked_msl_response(resp.text)\n- #common.log(\n- # msg='Parsed chunked Response: ' + json.dumps(resp))\n- data = self.__decrypt_payload_chunks(resp['payloads'])\n+ data = self._process_chunked_response(\n+ self._post(ENDPOINTS['chrome']['manifest'], request_data))\nreturn self.__tranform_to_dash(data)\n- return False\ndef get_license(self, challenge, sid):\n\"\"\"\n@@ -148,58 +135,12 @@ class MSLHandler(object):\n}\nrequest_data = self.__generate_msl_request_data(license_request_data)\n-\n- try:\n- resp = self.session.post(self.endpoints['license'], request_data)\n- except:\n- resp = None\n- exc = sys.exc_info()\n- common.log(\n- msg='[MSL][POST] Error {} {}'.format(exc[0], exc[1]))\n-\n- if resp:\n- try:\n- # If is valid json the request for the licnese failed\n- resp.json()\n- common.log('Error getting license: '+resp.text)\n- return False\n- except ValueError:\n- # json() failed so we have a chunked json response\n- resp = self.__parse_chunked_msl_response(resp.text)\n- data = self.__decrypt_payload_chunks(resp['payloads'])\n- if data['success'] is True:\n+ data = self._process_chunked_response(\n+ self._post(ENDPOINTS['chrome']['license'], request_data))\n+ if not data['success']:\n+ common.error('Error getting license: {}'.format(json.dumps(data)))\n+ raise LicenseError\nreturn data['result']['licenses'][0]['data']\n- else:\n- common.log(\n- msg='Error getting license: ' + json.dumps(data))\n- return False\n- return False\n-\n- def __decrypt_payload_chunks(self, payloadchunks):\n- decrypted_payload = ''\n- for chunk in payloadchunks:\n- payloadchunk = json.JSONDecoder().decode(chunk)\n- payload = payloadchunk.get('payload')\n- decoded_payload = base64.standard_b64decode(payload)\n- encryption_envelope = json.JSONDecoder().decode(decoded_payload)\n- # Decrypt the text\n- plaintext = self.crypto.decrypt(base64.standard_b64decode(encryption_envelope['iv']),\n- base64.standard_b64decode(encryption_envelope.get('ciphertext')))\n- # unpad the plaintext\n- plaintext = json.JSONDecoder().decode(plaintext)\n- data = plaintext.get('data')\n-\n- # uncompress data if compressed\n- if plaintext.get('compressionalgo') == 'GZIP':\n- decoded_data = base64.standard_b64decode(data)\n- data = zlib.decompress(decoded_data, 16 + zlib.MAX_WBITS)\n- else:\n- data = base64.standard_b64decode(data)\n- decrypted_payload += data\n-\n- decrypted_payload = json.JSONDecoder().decode(decrypted_payload)[1]['payload']['data']\n- decrypted_payload = base64.standard_b64decode(decrypted_payload)\n- return json.JSONDecoder().decode(decrypted_payload)\ndef __tranform_to_dash(self, manifest):\ncommon.save_file('manifest.json', json.dumps(manifest))\n@@ -208,20 +149,6 @@ class MSLHandler(object):\nself.last_drm_context = manifest['drmContextId']\nreturn convert_to_dash(manifest)\n- def __get_base_url(self, urls):\n- for key in urls:\n- return urls[key]\n-\n- def __parse_chunked_msl_response(self, message):\n- header = message.split('}}')[0] + '}}'\n- payloads = re.split(',\\\"signature\\\":\\\"[0-9A-Za-z=/+]+\\\"}', message.split('}}')[1])\n- payloads = [x + '}' for x in payloads][:-1]\n-\n- return {\n- 'header': header,\n- 'payloads': payloads\n- }\n-\ndef __generate_msl_request_data(self, data):\n#self.__load_msl_data()\nmslheader = self.__generate_msl_header()\n@@ -319,11 +246,11 @@ class MSLHandler(object):\nreturn json.dumps(header_data)\ndef perform_key_handshake(self):\n- esn = g.get_esn()\n- common.log('perform_key_handshake: esn:' + esn)\n+ if not g.get_esn():\n+ common.error('Cannot perform key handshake, missing ESN')\n+ return\n- if not esn:\n- return False\n+ common.debug('Performing key handshake. ESN: {}'.format(g.get_esn()))\nheader = self.__generate_msl_header(\nis_key_request=True,\n@@ -335,36 +262,87 @@ class MSLHandler(object):\n'entityauthdata': {\n'scheme': 'NONE',\n'authdata': {\n- 'identity': esn\n+ 'identity': g.get_esn()\n}\n},\n'headerdata': base64.standard_b64encode(header),\n'signature': '',\n}\n- #common.log('Key Handshake Request:')\n- #common.log(json.dumps(request))\n- try:\n- resp = self.session.post(\n- url=self.endpoints['manifest'],\n- data=json.dumps(request, sort_keys=True))\n- except:\n- resp = None\n- exc = sys.exc_info()\n- common.log(\n- msg='[MSL][POST] Error {} {}'.format(exc[0], exc[1]))\n-\n- if resp and resp.status_code == 200:\n- resp = resp.json()\n- if 'errordata' in resp:\n- common.log('Key Exchange failed')\n- common.log(\n- msg=base64.standard_b64decode(resp['errordata']))\n- return False\n- base_head = base64.standard_b64decode(resp['headerdata'])\n-\n- headerdata=json.JSONDecoder().decode(base_head)\n+ response = _process_json_response(\n+ self._post(ENDPOINTS['chrome']['manifest'],\n+ json.dumps(request, sort_keys=True)))\n+ headerdata = json.loads(\n+ base64.standard_b64decode(response['headerdata']))\nself.crypto.parse_key_response(headerdata)\n+ common.debug('Key handshake successful')\n+\n+ def _post(self, endpoint, request_data):\n+ \"\"\"Execute a post request\"\"\"\n+ response = self.session.post(endpoint, request_data)\n+ response.raise_for_status()\n+ return response\n+\n+ def _process_chunked_response(self, response):\n+ \"\"\"Parse and decrypt an encrypted chunked response. Raise an error\n+ if the response is plaintext json\"\"\"\n+ try:\n+ # if the json() does not fail we have an error because\n+ # the expected response is a chunked json response\n+ return _raise_if_error(response.json())\n+ except ValueError:\n+ # json() failed so parse and decrypt the chunked response\n+ response = _parse_chunks(response.text)\n+ return _decrypt_chunks(response['payloads'],\n+ self.crypto)\n+\n+\n+def _process_json_response(response):\n+ \"\"\"Execute a post request and expect a JSON response\"\"\"\n+ try:\n+ return _raise_if_error(response.json())\n+ except ValueError:\n+ raise MSLError('Expected JSON response')\n+\n+\n+def _raise_if_error(decoded_response):\n+ if 'errordata' in decoded_response:\n+ raise MSLError(\n+ base64.standard_b64decode(decoded_response['errordata']))\n+ return decoded_response\n+\n+\n+def _parse_chunks(message):\n+ header = message.split('}}')[0] + '}}'\n+ payloads = re.split(',\\\"signature\\\":\\\"[0-9A-Za-z=/+]+\\\"}',\n+ message.split('}}')[1])\n+ payloads = [x + '}' for x in payloads][:-1]\n+ return {'header': header, 'payloads': payloads}\n+\n+\n+def _decrypt_chunks(chunks, crypto):\n+ decrypted_payload = ''\n+ for chunk in chunks:\n+ payloadchunk = json.JSONDecoder().decode(chunk)\n+ payload = payloadchunk.get('payload')\n+ decoded_payload = base64.standard_b64decode(payload)\n+ encryption_envelope = json.JSONDecoder().decode(decoded_payload)\n+ # Decrypt the text\n+ plaintext = crypto.decrypt(\n+ base64.standard_b64decode(encryption_envelope['iv']),\n+ base64.standard_b64decode(encryption_envelope.get('ciphertext')))\n+ # unpad the plaintext\n+ plaintext = json.JSONDecoder().decode(plaintext)\n+ data = plaintext.get('data')\n+\n+ # uncompress data if compressed\n+ if plaintext.get('compressionalgo') == 'GZIP':\n+ decoded_data = base64.standard_b64decode(data)\n+ data = zlib.decompress(decoded_data, 16 + zlib.MAX_WBITS)\nelse:\n- common.log('Key Exchange failed')\n- common.log(resp.text)\n+ data = base64.standard_b64decode(data)\n+ decrypted_payload += data\n+\n+ decrypted_payload = json.loads(decrypted_payload)[1]['payload']['data']\n+ decrypted_payload = base64.standard_b64decode(decrypted_payload)\n+ return json.JSONDecoder().decode(decrypted_payload)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/default_crypto.py",
"new_path": "resources/lib/services/msl/default_crypto.py",
"diff": "# -*- coding: utf-8 -*-\n-# Author: trummerjo\n-# Module: MSLHttpRequestHandler\n-# Created on: 26.01.2017\n-# License: MIT https://goo.gl/5bMj3H\n\"\"\"Crypto handler for non-Android platforms\"\"\"\nfrom __future__ import unicode_literals\n@@ -36,7 +32,6 @@ class MSLCrypto(object):\nself.rsa_key = RSA.importKey(\nbase64.standard_b64decode(msl_data['rsa_key']))\nself._set_mastertoken(msl_data['tokens']['mastertoken'])\n- common.debug('Loaded crypto keys')\nexcept Exception:\ncommon.debug('Generating new RSA keys')\nself.rsa_key = RSA.generate(2048)\n@@ -115,6 +110,7 @@ class MSLCrypto(object):\nself.mastertoken = mastertoken\nself.sequence_number = tokendata.get('sequencenumber', 0)\nelse:\n+ common.error('Mastertoken has expired')\nraise MastertokenExpired\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/http_server.py",
"new_path": "resources/lib/services/msl/http_server.py",
"diff": "\"\"\"Handles & translates requests from Inputstream to Netflix\"\"\"\nfrom __future__ import unicode_literals\n+import traceback\nimport base64\nimport BaseHTTPServer\nfrom urlparse import urlparse, parse_qs\n@@ -35,10 +36,9 @@ class MSLHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\nself.end_headers()\nself.wfile.write(base64.standard_b64decode(b64license))\nself.finish()\n- except MSLError as exc:\n- self.send_error(500, exc.message)\n- except Exception:\n- self.send_error(400, 'Invalid license request')\n+ except Exception as exc:\n+ common.error(traceback.format_exc())\n+ self.send_response(500 if isinstance(exc, MSLError) else 400)\ndef do_GET(self):\n\"\"\"Loads the XML manifest for the requested resource\"\"\"\n@@ -49,10 +49,9 @@ class MSLHttpRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\nself.send_header('Content-type', 'application/xml')\nself.end_headers()\nself.wfile.write(data)\n- except MSLError as exc:\n- self.send_error(500, exc.message)\n- except Exception:\n- self.send_error(400, 'Invalid manifest request')\n+ except Exception as exc:\n+ common.error(traceback.format_exc())\n+ self.send_response(500 if isinstance(exc, MSLError) else 400)\ndef log_message(self, *args):\n# pylint: disable=arguments-differ\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Refactor handling of MSL responses |
105,989 | 01.11.2018 23:38:48 | -3,600 | be72c5b094ed71277cb05bb6926f4f95e2c5546e | Refactor MSL request building | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/misc_utils.py",
"new_path": "resources/lib/common/misc_utils.py",
"diff": "@@ -6,6 +6,9 @@ from __future__ import unicode_literals\nimport traceback\nfrom datetime import datetime\nfrom urllib import urlencode\n+import gzip\n+import base64\n+from StringIO import StringIO\nimport xbmc\nimport xbmcgui\n@@ -181,3 +184,10 @@ def _show_errors(notify_errors, errors):\n'\\n'.join(['{} ({})'.format(err['task_title'],\nerr['error'])\nfor err in errors]))\n+\n+def compress_data(data):\n+ \"\"\"GZIP and b64 encode data\"\"\"\n+ out = StringIO()\n+ with gzip.GzipFile(fileobj=out, mode='w') as outh:\n+ outh.write(data)\n+ return base64.standard_b64encode(out.getvalue())\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/http_server.py",
"new_path": "resources/lib/services/msl/http_server.py",
"diff": "@@ -14,7 +14,7 @@ from urlparse import urlparse, parse_qs\nfrom SocketServer import TCPServer\nimport resources.lib.common as common\n-from .MSL import MSLHandler\n+from .msl_handler import MSLHandler\nfrom .exceptions import MSLError\n"
},
{
"change_type": "RENAME",
"old_path": "resources/lib/services/msl/MSL.py",
"new_path": "resources/lib/services/msl/msl_handler.py",
"diff": "from __future__ import unicode_literals\nimport re\n-import sys\nimport zlib\n-import gzip\nimport json\nimport time\nimport base64\n-import random\n-import uuid\n-from StringIO import StringIO\n-from datetime import datetime\nimport requests\n-import xml.etree.ElementTree as ET\nfrom resources.lib.globals import g\nimport resources.lib.common as common\n+from .request_builder import MSLRequestBuilder\nfrom .profiles import enabled_profiles\nfrom .converter import convert_to_dash\nfrom .exceptions import MSLError, LicenseError\n-#check if we are on Android\n-import subprocess\n-try:\n- sdkversion = int(subprocess.check_output(\n- ['/system/bin/getprop', 'ro.build.version.sdk']))\n-except:\n- sdkversion = 0\n-\n-if sdkversion >= 18:\n- from MSLMediaDrm import MSLMediaDrmCrypto as MSLCrypto\n-else:\n- from .default_crypto import MSLCrypto as MSLCrypto\n-\nCHROME_BASE_URL = 'http://www.netflix.com/api/msl/NFCDCH-LX/cadmium/'\nENDPOINTS = {\n'chrome': {\n@@ -52,30 +33,44 @@ ENDPOINTS = {\nclass MSLHandler(object):\n- # Is a handshake already performed and the keys loaded\n+ \"\"\"Handles session management and crypto for license and manifest\n+ requests\"\"\"\nlast_drm_context = ''\nlast_playback_context = ''\n- current_message_id = 0\nsession = requests.session()\n- rndm = random.SystemRandom()\n- tokens = []\ndef __init__(self):\n# pylint: disable=broad-except\ntry:\nmsl_data = json.loads(common.load_file('msl_data.json'))\n- self.crypto = MSLCrypto(msl_data)\n+ self.request_builder = MSLRequestBuilder(msl_data)\ncommon.debug('Loaded MSL data from disk')\nexcept Exception:\nimport traceback\ncommon.debug(traceback.format_exc())\ncommon.debug('Stored MSL data expired or not available')\n- self.crypto = MSLCrypto()\n+ self.request_builder = MSLRequestBuilder()\nself.perform_key_handshake()\ncommon.register_slot(\nsignal=common.Signals.ESN_CHANGED,\ncallback=self.perform_key_handshake)\n+ def perform_key_handshake(self):\n+ \"\"\"Perform a key handshake and initialize crypto keys\"\"\"\n+ if not g.get_esn():\n+ common.error('Cannot perform key handshake, missing ESN')\n+ return\n+\n+ common.debug('Performing key handshake. ESN: {}'.format(g.get_esn()))\n+\n+ response = _process_json_response(\n+ self._post(ENDPOINTS['chrome']['manifest'],\n+ self.request_builder.handshake_request()))\n+ headerdata = json.loads(\n+ base64.standard_b64decode(response['headerdata']))\n+ self.request_builder.crypto.parse_key_response(headerdata)\n+ common.debug('Key handshake successful')\n+\ndef load_manifest(self, viewable_id):\n\"\"\"\nLoads the manifets for the given viewable_id and\n@@ -105,11 +100,11 @@ class MSLHandler(object):\n'clientVersion': '4.0004.899.011',\n'uiVersion': 'akira'\n}\n- request_data = self.__generate_msl_request_data(manifest_request_data)\n- common.debug(request_data)\n- data = self._process_chunked_response(\n- self._post(ENDPOINTS['chrome']['manifest'], request_data))\n- return self.__tranform_to_dash(data)\n+ manifest = self._process_chunked_response(\n+ self._post(\n+ ENDPOINTS['chrome']['manifest'],\n+ self.request_builder.msl_request(manifest_request_data)))\n+ return self.__tranform_to_dash(manifest)\ndef get_license(self, challenge, sid):\n\"\"\"\n@@ -134,13 +129,15 @@ class MSLHandler(object):\n'xid': int((int(time.time()) + 0.1612) * 1000)\n}\n- request_data = self.__generate_msl_request_data(license_request_data)\n- data = self._process_chunked_response(\n- self._post(ENDPOINTS['chrome']['license'], request_data))\n- if not data['success']:\n- common.error('Error getting license: {}'.format(json.dumps(data)))\n+ response = self._process_chunked_response(\n+ self._post(\n+ ENDPOINTS['chrome']['license'],\n+ self.request_builder.msl_request(license_request_data)))\n+ if not response['success']:\n+ common.error('Error getting license: {}'\n+ .format(json.dumps(response)))\nraise LicenseError\n- return data['result']['licenses'][0]['data']\n+ return response['result']['licenses'][0]['data']\ndef __tranform_to_dash(self, manifest):\ncommon.save_file('manifest.json', json.dumps(manifest))\n@@ -149,134 +146,6 @@ class MSLHandler(object):\nself.last_drm_context = manifest['drmContextId']\nreturn convert_to_dash(manifest)\n- def __generate_msl_request_data(self, data):\n- #self.__load_msl_data()\n- mslheader = self.__generate_msl_header()\n- common.debug('Plaintext headerdata: {}'.format(mslheader))\n- header_encryption_envelope = self.crypto.encrypt(mslheader)\n- headerdata = base64.standard_b64encode(header_encryption_envelope)\n- header = {\n- 'headerdata': headerdata,\n- 'signature': self.crypto.sign(header_encryption_envelope),\n- 'mastertoken': self.crypto.mastertoken,\n- }\n-\n- # Serialize the given Data\n- raw_marshalled_data = json.dumps(data)\n- marshalled_data = raw_marshalled_data.replace('\"', '\\\\\"')\n- serialized_data = '[{},{\"headers\":{},\"path\":\"/cbp/cadmium-13\"'\n- serialized_data += ',\"payload\":{\"data\":\"'\n- serialized_data += marshalled_data\n- serialized_data += '\"},\"query\":\"\"}]\\n'\n- common.debug('Serialized data: {}'.format(serialized_data))\n- compressed_data = self.__compress_data(serialized_data)\n-\n- # Create FIRST Payload Chunks\n- first_payload = {\n- 'messageid': self.current_message_id,\n- 'data': compressed_data,\n- 'compressionalgo': 'GZIP',\n- 'sequencenumber': 1,\n- 'endofmsg': True\n- }\n- common.debug('Plaintext Payload: {}'.format(first_payload))\n- first_payload_encryption_envelope = self.crypto.encrypt(json.dumps(first_payload))\n- payload = base64.standard_b64encode(first_payload_encryption_envelope)\n- first_payload_chunk = {\n- 'payload': payload,\n- 'signature': self.crypto.sign(first_payload_encryption_envelope),\n- }\n- request_data = json.dumps(header) + json.dumps(first_payload_chunk)\n- return request_data\n-\n- def __compress_data(self, data):\n- # GZIP THE DATA\n- out = StringIO()\n- with gzip.GzipFile(fileobj=out, mode=\"w\") as f:\n- f.write(data)\n- return base64.standard_b64encode(out.getvalue())\n-\n- def __generate_msl_header(\n- self,\n- is_handshake=False,\n- is_key_request=False,\n- compressionalgo='GZIP',\n- encrypt=True):\n- \"\"\"\n- Function that generates a MSL header dict\n- :return: The base64 encoded JSON String of the header\n- \"\"\"\n- self.current_message_id = self.rndm.randint(0, pow(2, 52))\n- esn = g.get_esn()\n-\n- # Add compression algo if not empty\n- compression_algos = [compressionalgo] if compressionalgo != '' else []\n-\n- header_data = {\n- 'sender': esn,\n- 'handshake': is_handshake,\n- 'nonreplayable': False,\n- 'capabilities': {\n- 'languages': ['en-US'],\n- 'compressionalgos': compression_algos\n- },\n- 'recipient': 'Netflix',\n- 'renewable': True,\n- 'messageid': self.current_message_id,\n- 'timestamp': 1467733923\n- }\n-\n- # If this is a keyrequest act diffrent then other requests\n- if is_key_request:\n- header_data['keyrequestdata'] = self.crypto.get_key_request()\n- else:\n- if 'usertoken' in self.tokens:\n- pass\n- else:\n- account = common.get_credentials()\n- # Auth via email and password\n- header_data['userauthdata'] = {\n- 'scheme': 'EMAIL_PASSWORD',\n- 'authdata': {\n- 'email': account['email'],\n- 'password': account['password']\n- }\n- }\n-\n- return json.dumps(header_data)\n-\n- def perform_key_handshake(self):\n- if not g.get_esn():\n- common.error('Cannot perform key handshake, missing ESN')\n- return\n-\n- common.debug('Performing key handshake. ESN: {}'.format(g.get_esn()))\n-\n- header = self.__generate_msl_header(\n- is_key_request=True,\n- is_handshake=True,\n- compressionalgo='',\n- encrypt=False)\n-\n- request = {\n- 'entityauthdata': {\n- 'scheme': 'NONE',\n- 'authdata': {\n- 'identity': g.get_esn()\n- }\n- },\n- 'headerdata': base64.standard_b64encode(header),\n- 'signature': '',\n- }\n-\n- response = _process_json_response(\n- self._post(ENDPOINTS['chrome']['manifest'],\n- json.dumps(request, sort_keys=True)))\n- headerdata = json.loads(\n- base64.standard_b64decode(response['headerdata']))\n- self.crypto.parse_key_response(headerdata)\n- common.debug('Key handshake successful')\n-\ndef _post(self, endpoint, request_data):\n\"\"\"Execute a post request\"\"\"\nresponse = self.session.post(endpoint, request_data)\n@@ -294,7 +163,7 @@ class MSLHandler(object):\n# json() failed so parse and decrypt the chunked response\nresponse = _parse_chunks(response.text)\nreturn _decrypt_chunks(response['payloads'],\n- self.crypto)\n+ self.request_builder.crypto)\ndef _process_json_response(response):\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/services/msl/request_builder.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"MSL request building\"\"\"\n+from __future__ import unicode_literals\n+\n+import json\n+import base64\n+import subprocess\n+import random\n+\n+from resources.lib.globals import g\n+import resources.lib.common as common\n+\n+# check if we are on Android\n+try:\n+ SDKVERSION = int(subprocess.check_output(\n+ ['/system/bin/getprop', 'ro.build.version.sdk']))\n+except (OSError, subprocess.CalledProcessError):\n+ SDKVERSION = 0\n+\n+if SDKVERSION >= 18:\n+ from .android_crypto import MSLMediaDrmCrypto as MSLCrypto\n+else:\n+ from .default_crypto import MSLCrypto as MSLCrypto\n+\n+\n+class MSLRequestBuilder(object):\n+ \"\"\"Provides mechanisms to create MSL requests\"\"\"\n+ def __init__(self, msl_data=None):\n+ self.current_message_id = None\n+ self.tokens = []\n+ self.rndm = random.SystemRandom()\n+ self.crypto = MSLCrypto(msl_data)\n+\n+ def msl_request(self, data):\n+ \"\"\"Create an encrypted MSL request\"\"\"\n+ return (json.dumps(self._signed_header()) +\n+ json.dumps(self._encrypted_chunk(data)))\n+\n+ def handshake_request(self):\n+ \"\"\"Create a key handshake request\"\"\"\n+ return json.dumps({\n+ 'entityauthdata': {\n+ 'scheme': 'NONE',\n+ 'authdata': {'identity': g.get_esn()}},\n+ 'headerdata':\n+ base64.standard_b64encode(\n+ self._headerdata(is_key_request=True, is_handshake=True,\n+ compression=None)),\n+ 'signature': ''\n+ }, sort_keys=True)\n+\n+ def _signed_header(self):\n+ encryption_envelope = self.crypto.encrypt(self._headerdata())\n+ return {\n+ 'headerdata': base64.standard_b64encode(encryption_envelope),\n+ 'signature': self.crypto.sign(encryption_envelope),\n+ 'mastertoken': self.crypto.mastertoken,\n+ }\n+\n+ def _headerdata(self, is_handshake=False, is_key_request=False,\n+ compression='GZIP'):\n+ \"\"\"\n+ Function that generates a MSL header dict\n+ :return: The base64 encoded JSON String of the header\n+ \"\"\"\n+ self.current_message_id = self.rndm.randint(0, pow(2, 52))\n+ header_data = {\n+ 'sender': g.get_esn(),\n+ 'handshake': is_handshake,\n+ 'nonreplayable': False,\n+ 'capabilities': {\n+ 'languages': ['en-US'],\n+ 'compressionalgos': [compression] if compression else []\n+ },\n+ 'recipient': 'Netflix',\n+ 'renewable': True,\n+ 'messageid': self.current_message_id,\n+ 'timestamp': 1467733923\n+ }\n+\n+ # If this is a keyrequest act diffrent then other requests\n+ if is_key_request:\n+ header_data['keyrequestdata'] = self.crypto.key_request_data()\n+ else:\n+ _add_auth_info(header_data, self.tokens)\n+\n+ return json.dumps(header_data)\n+\n+ def _encrypted_chunk(self, data):\n+ # Serialize the given Data\n+ serialized_data = ''.join((\n+ '[{},{\"headers\":{},\"path\":\"/cbp/cadmium-13\",\"payload\":{\"data\":\"',\n+ json.dumps(data).replace('\"', '\\\\\"'),\n+ '\"},\"query\":\"\"}]\\n'))\n+ payload = {\n+ 'messageid': self.current_message_id,\n+ 'data': common.compress_data(serialized_data),\n+ 'compressionalgo': 'GZIP',\n+ 'sequencenumber': 1,\n+ 'endofmsg': True\n+ }\n+ encryption_envelope = self.crypto.encrypt(json.dumps(payload))\n+ return {\n+ 'payload': base64.standard_b64encode(encryption_envelope),\n+ 'signature': self.crypto.sign(encryption_envelope),\n+ }\n+\n+\n+def _add_auth_info(header_data, tokens):\n+ if 'usertoken' not in tokens:\n+ credentials = common.get_credentials()\n+ # Auth via email and password\n+ header_data['userauthdata'] = {\n+ 'scheme': 'EMAIL_PASSWORD',\n+ 'authdata': {\n+ 'email': credentials['email'],\n+ 'password': credentials['password']\n+ }\n+ }\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Refactor MSL request building |
105,989 | 02.11.2018 00:39:06 | -3,600 | 32fb8fb79fa69395872f3be49c6da532b31c6c27 | Extract common base class for crypto handlers and refactor MSLMediaDrm into android_crypto | [
{
"change_type": "DELETE",
"old_path": "resources/lib/services/msl/MSLMediaDrm.py",
"new_path": null,
"diff": "-from __future__ import unicode_literals\n-\n-from os import urandom\n-import json\n-import base64\n-import xbmcdrm\n-import pprint\n-\n-import resources.lib.common as common\n-\n-class MSLMediaDrmCrypto:\n-\n- def __init__(self, kodi_helper):\n- self.kodi_helper = kodi_helper\n-\n- self.keySetId = None\n- self.keyId = None\n- self.hmacKeyId = None\n-\n- try:\n- self.cryptoSession = xbmcdrm.CryptoSession('edef8ba9-79d6-4ace-a3c8-27dcd51d21ed',\n- 'AES/CBC/NoPadding', 'HmacSHA256')\n- common.log('Widevine CryptoSession successful constructed')\n- except:\n- self.cryptoSession = None\n- return\n-\n- self.systemId = self.cryptoSession.GetPropertyString('systemId')\n- common.log('Widevine CryptoSession systemId: {}'.format(self.systemId))\n-\n- algorithms = self.cryptoSession.GetPropertyString('algorithms')\n- common.log('Widevine CryptoSession algorithms: {}'.format(algorithms))\n-\n- def __del__(self):\n- self.cryptoSession = None\n-\n- def __getKeyRequest(self, data):\n- #No key update supported -> remove existing keys\n- self.cryptoSession.RemoveKeys()\n- keyRequest = self.cryptoSession.GetKeyRequest(data, 'application/xml', True, dict())\n- if keyRequest:\n- common.log('Widevine CryptoSession getKeyRequest successful with size: {}'.format(len(keyRequest)))\n- return keyRequest\n- else:\n- common.log('Widevine CryptoSession getKeyRequest failed!')\n-\n- def __provideKeyResponse(self, data):\n- if len(data) == 0:\n- return False\n-\n- self.keySetId = self.cryptoSession.ProvideKeyResponse(data)\n-\n- if self.keySetId:\n- common.log('Widevine CryptoSession provideKeyResponse successful, keySetId: {}'.format(self.keySetId))\n- else:\n- common.log('Widevine CryptoSession provideKeyResponse failed!')\n-\n- return self.keySetId != None\n-\n- def toDict(self):\n- common.log('Provide Widevine keys to dict')\n- data = {\n- \"key_set_id\": base64.standard_b64encode(self.keySetId),\n- 'key_id': base64.standard_b64encode(self.keyId),\n- 'hmac_key_id': base64.standard_b64encode(self.hmacKeyId)\n- }\n- return data\n-\n- def fromDict(self, msl_data):\n- need_handshake = False\n-\n- if not self.cryptoSession:\n- return False\n-\n- try:\n- common.log('Parsing Widevine keys from Dict')\n- self.keySetId = base64.standard_b64decode(msl_data['key_set_id'])\n- self.keyId = base64.standard_b64decode(msl_data['key_id'])\n- self.hmacKeyId = base64.standard_b64decode(msl_data['hmac_key_id'])\n-\n- self.cryptoSession.RestoreKeys(self.keySetId)\n-\n- except:\n- need_handshake = True\n-\n- return need_handshake\n-\n- def get_key_request(self):\n- drmKeyRequest = self.__getKeyRequest(bytes([10, 122, 0, 108, 56, 43]))\n-\n- key_request = [{\n- 'scheme': 'WIDEVINE',\n- 'keydata': {\n- 'keyrequest': base64.standard_b64encode(drmKeyRequest)\n- }\n- }]\n-\n- return key_request\n-\n- def parse_key_response(self, headerdata):\n- # Init Decryption\n- key_resonse = base64.standard_b64decode(headerdata['keyresponsedata']['keydata']['cdmkeyresponse'])\n-\n- if not self.__provideKeyResponse(key_resonse):\n- return\n-\n- self.keyId = base64.standard_b64decode(headerdata['keyresponsedata']['keydata']['encryptionkeyid'])\n- self.hmacKeyId = base64.standard_b64decode(headerdata['keyresponsedata']['keydata']['hmackeyid'])\n-\n- def decrypt(self, iv, data):\n- decrypted = self.cryptoSession.Decrypt(self.keyId, data, iv)\n-\n- if decrypted:\n- common.log('Widevine CryptoSession decrypt successful: {} bytes returned'.format(len(decrypted)))\n-\n- # remove PKCS5Padding\n- pad = decrypted[len(decrypted) - 1]\n-\n- return decrypted[:-pad].decode('utf-8')\n- else:\n- common.log('Widevine CryptoSession decrypt failed!')\n-\n- def encrypt(self, data, esn, sequence_number):\n-\n- iv = urandom(16)\n-\n- # Add PKCS5Padding\n- pad = 16 - len(data) % 16\n- newData = data + ''.join([chr(pad)] * pad)\n-\n- encrypted = self.cryptoSession.Encrypt(self.keyId, newData, iv)\n-\n- if encrypted:\n- common.log('Widevine CryptoSession encrypt successful: {} bytes returned'.format(len(encrypted)))\n-\n- encryption_envelope = {\n- 'version' : 1,\n- 'ciphertext': base64.standard_b64encode(encrypted),\n- 'sha256': 'AA==',\n- 'keyid': base64.standard_b64encode(self.keyId),\n- #'cipherspec' : 'AES/CBC/PKCS5Padding',\n- 'iv': base64.standard_b64encode(iv)\n- }\n- return encryption_envelope\n- else:\n- common.log('Widevine CryptoSession encrypt failed!')\n-\n- def sign(self, message):\n- signature = self.cryptoSession.Sign(self.hmacKeyId, message)\n- if signature:\n- common.log('Widevine CryptoSession sign success: length: {}'.format(len(signature)))\n- return signature\n- else:\n- common.log('Widevine CryptoSession sign failed!')\n-\n- def verify(self, message, signature):\n- return self.cryptoSession.Verify(self.hmacKeyId, message, signature)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/services/msl/android_crypto.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Crypto handler for Android platforms\"\"\"\n+from __future__ import unicode_literals\n+\n+from os import urandom\n+import base64\n+import xbmcdrm\n+\n+import resources.lib.common as common\n+\n+from .base_crypto import MSLBaseCrypto\n+from .exceptions import MSLError\n+\n+\n+class AndroidMSLCrypto(MSLBaseCrypto):\n+ \"\"\"Crypto handler for Android platforms\"\"\"\n+ def __init__(self, msl_data=None):\n+ # pylint: disable=broad-except\n+ try:\n+ self.crypto_session = xbmcdrm.CryptoSession(\n+ 'edef8ba9-79d6-4ace-a3c8-27dcd51d21ed', 'AES/CBC/NoPadding',\n+ 'HmacSHA256')\n+ common.debug('Widevine CryptoSession successful constructed')\n+ except Exception:\n+ import traceback\n+ common.error(traceback.format_exc())\n+ raise MSLError('Failed to construct Widevine CryptoSession')\n+\n+ try:\n+ super(AndroidMSLCrypto, self).__init__(msl_data)\n+ self.keyset_id = base64.standard_b64decode(msl_data['key_set_id'])\n+ self.key_id = base64.standard_b64decode(msl_data['key_id'])\n+ self.hmac_key_id = base64.standard_b64decode(\n+ msl_data['hmac_key_id'])\n+ self.crypto_session.RestoreKeys(self.keyset_id)\n+ except Exception:\n+ self.keyset_id = None\n+ self.key_id = None\n+ self.hmac_key_id = None\n+\n+ common.debug('Widevine CryptoSession systemId: {}'\n+ .format(\n+ self.crypto_session.GetPropertyString('systemId')))\n+ common.debug('Widevine CryptoSession algorithms: {}'\n+ .format(\n+ self.crypto_session.GetPropertyString('algorithms')))\n+\n+ def __del__(self):\n+ self.crypto_session = None\n+\n+ def key_request_data(self):\n+ \"\"\"Return a key request dict\"\"\"\n+ #No key update supported -> remove existing keys\n+ self.crypto_session.RemoveKeys()\n+ key_request = self.crypto_session.GetKeyRequest(\n+ bytes([10, 122, 0, 108, 56, 43]), 'application/xml', True, dict())\n+\n+ if not key_request:\n+ raise MSLError('Widevine CryptoSession getKeyRequest failed!')\n+\n+ common.log('Widevine CryptoSession getKeyRequest successful. Size: {}'\n+ .format(len(key_request)))\n+ return [{\n+ 'scheme': 'WIDEVINE',\n+ 'keydata': {\n+ 'keyrequest': base64.standard_b64encode(key_request)\n+ }\n+ }]\n+\n+ def _provide_key_response(self, data):\n+ if not data:\n+ raise MSLError('Missing key response data')\n+ self.keyset_id = self.crypto_session.ProvideKeyResponse(data)\n+ if not self.keyset_id:\n+ raise MSLError('Widevine CryptoSession provideKeyResponse failed')\n+ common.debug('Widevine CryptoSession provideKeyResponse successful')\n+ common.debug('keySetId: {}'.format(self.keyset_id))\n+\n+ def encrypt(self, plaintext):\n+ \"\"\"\n+ Encrypt the given Plaintext with the encryption key\n+ :param plaintext:\n+ :return: Serialized JSON String of the encryption Envelope\n+ \"\"\"\n+ init_vector = urandom(16)\n+ # Add PKCS5Padding\n+ pad = 16 - len(plaintext) % 16\n+ padded_data = plaintext + ''.join([chr(pad)] * pad)\n+ encrypted_data = self.crypto_session.Encrypt(self.key_id, padded_data,\n+ init_vector)\n+\n+ if not encrypted_data:\n+ raise MSLError('Widevine CryptoSession encrypt failed!')\n+\n+ return {\n+ 'version' : 1,\n+ 'ciphertext': base64.standard_b64encode(encrypted_data),\n+ 'sha256': 'AA==',\n+ 'keyid': base64.standard_b64encode(self.key_id),\n+ #'cipherspec' : 'AES/CBC/PKCS5Padding',\n+ 'iv': base64.standard_b64encode(init_vector)\n+ }\n+\n+ def decrypt(self, init_vector, ciphertext):\n+ \"\"\"Decrypt a ciphertext\"\"\"\n+ decrypted_data = self.crypto_session.Decrypt(self.key_id, ciphertext,\n+ init_vector)\n+ if not decrypted_data:\n+ raise MSLError('Widevine CryptoSession decrypt failed!')\n+\n+ # remove PKCS5Padding\n+ pad = decrypted_data[len(decrypted_data) - 1]\n+ return decrypted_data[:-pad].decode('utf-8')\n+\n+ def sign(self, message):\n+ \"\"\"Sign a message\"\"\"\n+ signature = self.crypto_session.Sign(self.hmac_key_id, message)\n+ if not signature:\n+ raise MSLError('Widevine CryptoSession sign failed!')\n+ return signature\n+\n+ def verify(self, message, signature):\n+ \"\"\"Verify a message's signature\"\"\"\n+ return self.crypto_session.Verify(self.hmac_key_id, message, signature)\n+\n+ def _init_keys(self, key_response_data):\n+ key_response = base64.standard_b64decode(\n+ key_response_data['keydata']['cdmkeyresponse'])\n+ self._provide_key_response(key_response)\n+ self.key_id = base64.standard_b64decode(\n+ key_response_data['keydata']['encryptionkeyid'])\n+ self.hmac_key_id = base64.standard_b64decode(\n+ key_response_data['keydata']['hmackeyid'])\n+\n+ def _export_keys(self):\n+ return {\n+ 'key_set_id': base64.standard_b64encode(self.keyset_id),\n+ 'key_id': base64.standard_b64encode(self.key_id),\n+ 'hmac_key_id': base64.standard_b64encode(self.hmac_key_id)\n+ }\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/services/msl/base_crypto.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Common base for crypto handlers\"\"\"\n+from __future__ import unicode_literals\n+\n+import time\n+import json\n+import base64\n+\n+import resources.lib.common as common\n+\n+from .exceptions import MastertokenExpired\n+\n+\n+class MSLBaseCrypto(object):\n+ \"\"\"Common base class for MSL crypto operations.\n+ Handles mastertoken and sequence number\"\"\"\n+ # pylint: disable=too-few-public-methods\n+ def __init__(self, msl_data=None):\n+ if msl_data:\n+ self._set_mastertoken(msl_data['tokens']['mastertoken'])\n+\n+ def parse_key_response(self, headerdata):\n+ \"\"\"Parse a key response and update crypto keys\"\"\"\n+ self._set_mastertoken(headerdata['keyresponsedata']['mastertoken'])\n+ self._init_keys(headerdata['keyresponsedata'])\n+ self._save_msl_data()\n+\n+ def _set_mastertoken(self, mastertoken):\n+ \"\"\"Set the mastertoken and check it for validity\"\"\"\n+ tokendata = json.loads(\n+ base64.standard_b64decode(mastertoken['tokendata']))\n+ remaining_ttl = (int(tokendata['expiration']) - time.time())\n+ if remaining_ttl / 60 / 60 >= 10:\n+ self.mastertoken = mastertoken\n+ self.sequence_number = tokendata.get('sequencenumber', 0)\n+ else:\n+ common.error('Mastertoken has expired')\n+ raise MastertokenExpired\n+\n+ def _save_msl_data(self):\n+ \"\"\"Save crypto keys and mastertoken to disk\"\"\"\n+ msl_data = {'tokens': {'mastertoken': self.mastertoken}}\n+ msl_data.update(self._export_keys())\n+ common.save_file('msl_data.json', json.dumps(msl_data))\n+ common.debug('Successfully saved MSL data to disk')\n+\n+ def _init_keys(self, key_response_data):\n+ \"\"\"Initialize crypto keys from key_response_data\"\"\"\n+ raise NotImplementedError\n+\n+ def _export_keys(self):\n+ \"\"\"Export crypto keys to a dict\"\"\"\n+ raise NotImplementedError\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/default_crypto.py",
"new_path": "resources/lib/services/msl/default_crypto.py",
"diff": "\"\"\"Crypto handler for non-Android platforms\"\"\"\nfrom __future__ import unicode_literals\n-import time\nimport json\nimport base64\nfrom Cryptodome.Random import get_random_bytes\n@@ -15,14 +14,15 @@ from Cryptodome.Cipher import AES\nfrom resources.lib.globals import g\nimport resources.lib.common as common\n-from .exceptions import MastertokenExpired\n+from .base_crypto import MSLBaseCrypto\n-class MSLCrypto(object):\n+class DefaultMSLCrypto(MSLBaseCrypto):\n\"\"\"Crypto Handler for non-Android platforms\"\"\"\ndef __init__(self, msl_data=None):\n# pylint: disable=broad-except\ntry:\n+ super(DefaultMSLCrypto, self).__init__(msl_data)\nself.encryption_key = base64.standard_b64decode(\nmsl_data['encryption_key'])\nself.sign_key = base64.standard_b64decode(\n@@ -31,7 +31,6 @@ class MSLCrypto(object):\nraise ValueError('Missing encryption_key or sign_key')\nself.rsa_key = RSA.importKey(\nbase64.standard_b64decode(msl_data['rsa_key']))\n- self._set_mastertoken(msl_data['tokens']['mastertoken'])\nexcept Exception:\ncommon.debug('Generating new RSA keys')\nself.rsa_key = RSA.generate(2048)\n@@ -49,19 +48,6 @@ class MSLCrypto(object):\n'keypairid': 'superKeyPair'\n}}]\n- def parse_key_response(self, headerdata):\n- \"\"\"Parse a key response and assign contained encryption_key and\n- sign_key\"\"\"\n- self._set_mastertoken(headerdata['keyresponsedata']['mastertoken'])\n- cipher = PKCS1_OAEP.new(self.rsa_key)\n- encrypted_encryption_key = base64.standard_b64decode(\n- headerdata['keyresponsedata']['keydata']['encryptionkey'])\n- encrypted_sign_key = base64.standard_b64decode(\n- headerdata['keyresponsedata']['keydata']['hmackey'])\n- self.encryption_key = _decrypt_key(encrypted_encryption_key, cipher)\n- self.sign_key = _decrypt_key(encrypted_sign_key, cipher)\n- self._save_msl_data()\n-\ndef encrypt(self, plaintext):\n\"\"\"\nEncrypt the given Plaintext with the encryption key\n@@ -81,37 +67,31 @@ class MSLCrypto(object):\nreturn json.dumps(encryption_envelope)\n- def decrypt(self, init_vector, data):\n+ def decrypt(self, init_vector, ciphertext):\n\"\"\"Decrypt a ciphertext\"\"\"\ncipher = AES.new(self.encryption_key, AES.MODE_CBC, init_vector)\n- return Padding.unpad(cipher.decrypt(data), 16)\n+ return Padding.unpad(cipher.decrypt(ciphertext), 16)\ndef sign(self, message):\n\"\"\"Sign a message\"\"\"\nreturn base64.standard_b64encode(\nHMAC.new(self.sign_key, message, SHA256).digest())\n- def _save_msl_data(self):\n- \"\"\"Save encryption keys and mastertoken to disk\"\"\"\n- msl_data = {\n- 'tokens': {'mastertoken': self.mastertoken},\n+ def _init_keys(self, key_response_data):\n+ cipher = PKCS1_OAEP.new(self.rsa_key)\n+ encrypted_encryption_key = base64.standard_b64decode(\n+ key_response_data['keydata']['encryptionkey'])\n+ encrypted_sign_key = base64.standard_b64decode(\n+ key_response_data['keydata']['hmackey'])\n+ self.encryption_key = _decrypt_key(encrypted_encryption_key, cipher)\n+ self.sign_key = _decrypt_key(encrypted_sign_key, cipher)\n+\n+ def _export_keys(self):\n+ return {\n'encryption_key': base64.standard_b64encode(self.encryption_key),\n'sign_key': base64.standard_b64encode(self.sign_key),\n'rsa_key': base64.standard_b64encode(self.rsa_key.exportKey())\n}\n- common.save_file('msl_data.json', json.dumps(msl_data))\n- common.debug('Successfully saved MSL data to disk')\n-\n- def _set_mastertoken(self, mastertoken):\n- tokendata = json.loads(\n- base64.standard_b64decode(mastertoken['tokendata']))\n- remaining_ttl = (int(tokendata['expiration']) - time.time())\n- if remaining_ttl / 60 / 60 >= 10:\n- self.mastertoken = mastertoken\n- self.sequence_number = tokendata.get('sequencenumber', 0)\n- else:\n- common.error('Mastertoken has expired')\n- raise MastertokenExpired\ndef _decrypt_key(encrypted_key, cipher):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/request_builder.py",
"new_path": "resources/lib/services/msl/request_builder.py",
"diff": "@@ -18,9 +18,9 @@ except (OSError, subprocess.CalledProcessError):\nSDKVERSION = 0\nif SDKVERSION >= 18:\n- from .android_crypto import MSLMediaDrmCrypto as MSLCrypto\n+ from .android_crypto import AndroidMSLCrypto as MSLCrypto\nelse:\n- from .default_crypto import MSLCrypto as MSLCrypto\n+ from .default_crypto import DefaultMSLCrypto as MSLCrypto\nclass MSLRequestBuilder(object):\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Extract common base class for crypto handlers and refactor MSLMediaDrm into android_crypto |
105,989 | 02.11.2018 01:16:20 | -3,600 | 62467d1974e11706176750900f5f10c9e15dfb4d | Reduce log spam. Fix bookmarks manager | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/paths.py",
"new_path": "resources/lib/api/paths.py",
"diff": "@@ -55,7 +55,7 @@ INFO_MAPPINGS = {\n'userrating': ['userRating', 'userRating'],\n'mpaa': ['maturity', 'rating', 'value'],\n'duration': 'runtime',\n- 'bookmark': 'bookmarkPosition',\n+ # 'bookmark': 'bookmarkPosition',\n'playcount': 'watched'\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -190,12 +190,12 @@ def get(bucket, identifier):\ntry:\ncache_entry = get_bucket(bucket)[identifier]\nexcept KeyError:\n+ common.debug('In-memory cache miss on {} in {}'\n+ .format(identifier, bucket))\ncache_entry = get_from_disk(bucket, identifier)\nverify_ttl(bucket, identifier, cache_entry)\n- common.debug('Cache hit on {} in {}. Entry valid until {}'\n- .format(identifier, bucket, cache_entry['eol']))\nreturn cache_entry['content']\n@@ -206,6 +206,8 @@ def get_from_disk(bucket, identifier):\nwith open(cache_filename, 'r') as cache_file:\ncache_entry = pickle.load(cache_file)\nexcept Exception:\n+ common.debug('On-disk cache miss on {} in {}'\n+ .format(identifier, bucket))\nraise CacheMiss()\nadd(bucket, identifier, cache_entry['content'])\nreturn cache_entry\n@@ -214,8 +216,8 @@ def get_from_disk(bucket, identifier):\ndef add(bucket, identifier, content, ttl=None, to_disk=False):\n\"\"\"Add an item to a cache bucket\"\"\"\neol = int(time() + (ttl if ttl else g.CACHE_TTL))\n- common.debug('Adding {} to {} (valid until {})'\n- .format(identifier, bucket, eol))\n+ # common.debug('Adding {} to {} (valid until {})'\n+ # .format(identifier, bucket, eol))\ncache_entry = {'eol': eol, 'content': content}\nget_bucket(bucket).update(\n{identifier: cache_entry})\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/kodiops.py",
"new_path": "resources/lib/common/kodiops.py",
"diff": "@@ -23,9 +23,9 @@ def json_rpc(method, params=None):\nrequest_data = {'jsonrpc': '2.0', 'method': method, 'id': 1,\n'params': params or {}}\nrequest = json.dumps(request_data)\n- debug('Executing JSON-RPC: {}'.format(request))\n+ # debug('Executing JSON-RPC: {}'.format(request))\nraw_response = unicode(xbmc.executeJSONRPC(request), 'utf-8')\n- debug('JSON-RPC response: {}'.format(raw_response))\n+ # debug('JSON-RPC response: {}'.format(raw_response))\nresponse = json.loads(raw_response)\nif 'error' in response:\nraise IOError('JSONRPC-Error {}: {}'\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -277,7 +277,6 @@ def finalize_directory(items, content_type=CONTENT_FOLDER, refresh=False,\ntitle=None):\n\"\"\"Finalize a directory listing.\nAdd items, set available sort methods and content type\"\"\"\n- common.debug('Finalizing directory: {}'.format(items))\nif title:\nxbmcplugin.setPluginCategory(g.PLUGIN_HANDLE, title)\nxbmcplugin.addDirectoryItems(g.PLUGIN_HANDLE, items)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/playback/bookmarks.py",
"new_path": "resources/lib/services/playback/bookmarks.py",
"diff": "@@ -26,7 +26,7 @@ class BookmarkManager(PlaybackActionManager):\n.format(self.enabled, self.infos, self.markers))\ndef _initialize(self, data):\n- if 'DBID' in data:\n+ if 'DBID' in data['infos']:\nself.infos = data['infos']\nself.markers = data.get('timeline_markers', {})\nself.progress = 0\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Reduce log spam. Fix bookmarks manager |
105,989 | 02.11.2018 12:38:26 | -3,600 | 749d88cecc6722905e286f3a7f6929e931bc7238 | Add view for browsing exported items | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/data_types.py",
"new_path": "resources/lib/api/data_types.py",
"diff": "@@ -90,6 +90,25 @@ class SearchVideoList(object):\nreturn _check_sentinel(self.data['search'].get(key, default))\n+class CustomVideoList(object):\n+ \"\"\"A video list\"\"\"\n+ # pylint: disable=invalid-name\n+ def __init__(self, path_response):\n+ self.data = path_response\n+ self.title = common.get_local_string(30048)\n+ self.videos = self.data['videos']\n+ self.artitem = next(self.videos.itervalues())\n+ self.contained_titles = [video['title']\n+ for video in self.videos.itervalues()]\n+\n+ def __getitem__(self, key):\n+ return _check_sentinel(self.data[key])\n+\n+ def get(self, key, default=None):\n+ \"\"\"Pass call on to the backing dict of this VideoList.\"\"\"\n+ return _check_sentinel(self.data.get(key, default))\n+\n+\nclass SeasonList(object):\n\"\"\"A list of seasons. Includes tvshow art.\"\"\"\ndef __init__(self, videoid, path_response):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -7,7 +7,7 @@ import resources.lib.common as common\nimport resources.lib.cache as cache\nfrom .data_types import (LoLoMo, VideoList, SeasonList, EpisodeList,\n- SearchVideoList)\n+ SearchVideoList, CustomVideoList)\nfrom .paths import (VIDEO_LIST_PARTIAL_PATHS, SEASONS_PARTIAL_PATHS,\nEPISODES_PARTIAL_PATHS, ART_PARTIAL_PATHS,\nGENRE_PARTIAL_PATHS)\n@@ -82,6 +82,16 @@ def video_list(list_id):\nVIDEO_LIST_PARTIAL_PATHS)))\n+def custom_video_list(video_ids):\n+ \"\"\"Retrieve a video list which contains the videos specified by\n+ video_ids\"\"\"\n+ common.debug('Requesting custom video list with {} videos'\n+ .format(len(video_ids)))\n+ return CustomVideoList(common.make_call(\n+ 'path_request',\n+ build_paths(['videos', video_ids], VIDEO_LIST_PARTIAL_PATHS)))\n+\n+\[email protected]_output(cache.CACHE_GENRES, identifying_param_index=0,\nidentifying_param_name='genre_id')\ndef genre(genre_id):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "@@ -49,6 +49,12 @@ def get_item(videoid):\n.format(videoid))\n+def list_contents():\n+ \"\"\"Return a list of all top-level video IDs (movies, shows)\n+ contained in the library\"\"\"\n+ return g.library().keys()\n+\n+\ndef is_in_library(videoid):\n\"\"\"Return True if the video is in the local Kodi library, else False\"\"\"\nreturn common.get_path_safe(videoid.to_list(), g.library()) is not None\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/directory.py",
"new_path": "resources/lib/navigation/directory.py",
"diff": "@@ -9,6 +9,7 @@ import resources.lib.common as common\nimport resources.lib.api.shakti as api\nimport resources.lib.kodi.listings as listings\nimport resources.lib.kodi.ui as ui\n+import resources.lib.kodi.library as library\nclass DirectoryBuilder(object):\n@@ -100,3 +101,14 @@ class DirectoryBuilder(object):\nelse:\nui.show_notification(common.get_local_string(30013))\nxbmcplugin.endOfDirectory(g.PLUGIN_HANDLE, succeeded=False)\n+\n+ def exported(self, pathitems=None):\n+ \"\"\"List all items that are exported to the Kodi library\"\"\"\n+ # pylint: disable=unused-argument\n+ library_contents = library.list_contents()\n+ if library_contents:\n+ listings.build_video_listing(\n+ api.custom_video_list(library_contents))\n+ else:\n+ ui.show_notification(common.get_local_string(30013))\n+ xbmcplugin.endOfDirectory(g.PLUGIN_HANDLE, succeeded=False)\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add view for browsing exported items |
105,989 | 02.11.2018 14:55:21 | -3,600 | 39133aae08a8845fb69d219c899f171ad5db1a4d | Add more informative error display | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "@@ -61,7 +61,10 @@ if __name__ == '__main__':\nexcept Exception as exc:\nimport traceback\ncommon.error(traceback.format_exc())\n- ui.show_notification(msg='Error: {}'.format(exc))\n+ ui.show_error_info(title=common.get_local_string(30105),\n+ message=': '.join((exc.__class__.__name__,\n+ exc.message)),\n+ netflix_error=False)\nxbmcplugin.endOfDirectory(handle=g.PLUGIN_HANDLE, succeeded=False)\ncache.commit()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -435,3 +435,11 @@ msgstr \"\"\nmsgctxt \"#30103\"\nmsgid \"Error details have been written to the Kodi logfile. If the error message does not provide guidance on how to resolve the issue or you continue to receive this error, please report it via GitHub. Please provide a full debug log with your error report (enable \\\"Debug Logging\\\" in Kodi settings).\"\nmsgstr \"\"\n+\n+msgctxt \"#30104\"\n+msgid \"The addon encountered to following error:\"\n+msgstr \"\"\n+\n+msgctxt \"#30105\"\n+msgid \"Netflix Addon Error\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/ui/dialogs.py",
"new_path": "resources/lib/kodi/ui/dialogs.py",
"diff": "@@ -80,10 +80,11 @@ def ask_for_removal_confirmation(title, year=None):\nheading=common.get_local_string(30047),\nline1=title + (' ({})'.format(year) if year else ''))\n-def show_error_info(title, error_message, unknown_error=False):\n+\n+def show_error_info(title, message, unknown_error=False, netflix_error=False):\n\"\"\"Show a dialog that displays the error message\"\"\"\n- prefix = 30101 if unknown_error else 30102\n+ prefix = (30104, 30101, 30102)[unknown_error + netflix_error]\nreturn xbmcgui.Dialog().ok(title,\nline1=common.get_local_string(prefix),\n- line2=error_message,\n+ line2=message,\nline3=common.get_local_string(30103))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/msl_handler.py",
"new_path": "resources/lib/services/msl/msl_handler.py",
"diff": "@@ -226,16 +226,16 @@ def _parse_chunks(message):\ndef _decrypt_chunks(chunks, crypto):\ndecrypted_payload = ''\nfor chunk in chunks:\n- payloadchunk = json.JSONDecoder().decode(chunk)\n+ payloadchunk = json.loads(chunk)\npayload = payloadchunk.get('payload')\ndecoded_payload = base64.standard_b64decode(payload)\n- encryption_envelope = json.JSONDecoder().decode(decoded_payload)\n+ encryption_envelope = json.loads(decoded_payload)\n# Decrypt the text\nplaintext = crypto.decrypt(\nbase64.standard_b64decode(encryption_envelope['iv']),\nbase64.standard_b64decode(encryption_envelope.get('ciphertext')))\n# unpad the plaintext\n- plaintext = json.JSONDecoder().decode(plaintext)\n+ plaintext = json.loads(plaintext)\ndata = plaintext.get('data')\n# uncompress data if compressed\n@@ -248,4 +248,4 @@ def _decrypt_chunks(chunks, crypto):\ndecrypted_payload = json.loads(decrypted_payload)[1]['payload']['data']\ndecrypted_payload = base64.standard_b64decode(decrypted_payload)\n- return json.JSONDecoder().decode(decrypted_payload)\n+ return json.loads(decrypted_payload)\n"
},
{
"change_type": "MODIFY",
"old_path": "service.py",
"new_path": "service.py",
"diff": "@@ -65,10 +65,17 @@ class NetflixService(object):\ncommon.info('Stopped MSL Service')\ndef run(self):\n- \"\"\"\n- Main loop. Runs until xbmc.Monitor requests abort\n- \"\"\"\n+ \"\"\"Main loop. Runs until xbmc.Monitor requests abort\"\"\"\n+ # pylint: disable=broad-except\n+ try:\nself.start_services()\n+ except Exception as exc:\n+ ui.show_error_info(\n+ title=common.get_local_string(30105),\n+ message=': '.join((exc.__class__.__name__, exc.message)),\n+ netflix_error=False)\n+ return\n+\nplayer = xbmc.Player()\nwhile not self.controller.abortRequested():\nif self._tick_and_wait_for_abort(player.isPlayingVideo()):\n@@ -81,8 +88,9 @@ class NetflixService(object):\nif is_playing_video:\nself.controller.on_playback_tick()\nself.library_updater.on_tick()\n- except Exception:\n+ except Exception as exc:\ncommon.error(traceback.format_exc())\n+ ui.show_notification(exc.message)\nreturn self.controller.waitForAbort(1)\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add more informative error display |
105,989 | 02.11.2018 15:19:32 | -3,600 | 962f83eb8cc453e58739a1b8e91c9de2ef979632 | Improve error handling. Fix small issues in playback services | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/msl_handler.py",
"new_path": "resources/lib/services/msl/msl_handler.py",
"diff": "@@ -178,10 +178,8 @@ class MSLHandler(object):\ntry:\n# if the json() does not fail we have an error because\n# the expected response is a chunked json response\n- return _raise_if_error(json.loads(response))\n+ return _raise_if_error(response.json())\nexcept ValueError:\n- import traceback\n- common.debug(traceback.format_exc())\n# json() failed so parse and decrypt the chunked response\nresponse = _parse_chunks(response.text)\nreturn _decrypt_chunks(response['payloads'],\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/playback/action_manager.py",
"new_path": "resources/lib/services/playback/action_manager.py",
"diff": "@@ -40,13 +40,7 @@ class PlaybackActionManager(object):\n\"\"\"\nInitialize the manager with data when the addon initiates a playback.\n\"\"\"\n- # pylint: disable=broad-except\n- try:\nself._call_if_enabled(self._initialize, data=data)\n- except Exception as exc:\n- self.enabled = False\n- common.error('{} disabled due to exception while initializing: {}'\n- .format(self.name, exc))\ncommon.debug('Initialiized {}: {}'.format(self.name, self))\ndef on_playback_started(self, player_state):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/playback/bookmarks.py",
"new_path": "resources/lib/services/playback/bookmarks.py",
"diff": "@@ -28,7 +28,7 @@ class BookmarkManager(PlaybackActionManager):\ndef _initialize(self, data):\nif 'DBID' in data['infos']:\nself.infos = data['infos']\n- self.markers = data.get('timeline_markers', {})\n+ self.markers = data['timeline_markers']\nself.progress = 0\nself.elapsed = 0\nelse:\n@@ -37,6 +37,9 @@ class BookmarkManager(PlaybackActionManager):\ndef _on_playback_stopped(self):\nif self._watched_to_end():\nself._mark_as_watched()\n+ else:\n+ common.debug('Progress insufficient, not marking {} as watched.'\n+ .format(self.infos))\nself.infos = None\nself.markers = None\n@@ -50,7 +53,7 @@ class BookmarkManager(PlaybackActionManager):\ncommon.debug('Saving bookmark for {} at {}s'.format(self.infos,\nself.elapsed))\ncommon.update_library_item_details(\n- self.infos['DBTYPE'], self.infos['DBID'],\n+ self.infos['mediatype'], self.infos['DBID'],\n{'resume': {'position': self.elapsed}})\ndef _watched_to_end(self):\n@@ -61,6 +64,6 @@ class BookmarkManager(PlaybackActionManager):\ndef _mark_as_watched(self):\ncommon.info('Marking {} as watched'.format(self.infos))\ncommon.update_library_item_details(\n- self.infos['DBTYPE'], self.infos['DBID'],\n+ self.infos['mediatype'], self.infos['DBID'],\n{'playcount': self.infos.get('playcount', 0) + 1,\n'resume': {'position': 0}})\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/playback/controller.py",
"new_path": "resources/lib/services/playback/controller.py",
"diff": "@@ -60,7 +60,7 @@ class PlaybackController(xbmc.Monitor):\njson.loads(unicode(data, 'utf-8', errors='ignore')))\nelif method == 'Player.OnStop':\nself._on_playback_stopped()\n- except Exception as exc:\n+ except Exception:\nimport traceback\ncommon.error(traceback.format_exc())\n@@ -86,14 +86,21 @@ class PlaybackController(xbmc.Monitor):\nself.action_managers = None\ndef _notify_all(self, notification, data=None):\n+ # pylint: disable=broad-except\ncommon.debug('Notifying all managers of {} (data={})'\n.format(notification.__name__, data))\nfor manager in self.action_managers:\nnotify_method = getattr(manager, notification.__name__)\n+ try:\nif data is not None:\nnotify_method(data)\nelse:\nnotify_method()\n+ except Exception as exc:\n+ common.error('{} disabled due to exception: {}'\n+ .format(manager.name, exc))\n+ manager.enabled = False\n+ raise\ndef _get_player_state(self):\ntry:\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/playback/stream_continuity.py",
"new_path": "resources/lib/services/playback/stream_continuity.py",
"diff": "@@ -49,8 +49,11 @@ class StreamContinuityManager(PlaybackActionManager):\nreturn self.storage.get(self.current_show, {})\ndef _initialize(self, data):\n+ if 'tvshowid' in data['videoid']:\nself.did_restore = False\nself.current_show = data['videoid']['tvshowid']\n+ else:\n+ self.enabled = False\ndef _on_playback_started(self, player_state):\nxbmc.sleep(1000)\n"
},
{
"change_type": "MODIFY",
"old_path": "service.py",
"new_path": "service.py",
"diff": "@@ -90,7 +90,8 @@ class NetflixService(object):\nself.library_updater.on_tick()\nexcept Exception as exc:\ncommon.error(traceback.format_exc())\n- ui.show_notification(exc.message)\n+ ui.show_notification(': '.join((exc.__class__.__name__,\n+ exc.message)))\nreturn self.controller.waitForAbort(1)\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Improve error handling. Fix small issues in playback services |
105,989 | 02.11.2018 16:41:15 | -3,600 | ad6442d34ca1339b66527979ab592a95e07002e2 | Add adult PIN verification | [
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -443,3 +443,15 @@ msgstr \"\"\nmsgctxt \"#30105\"\nmsgid \"Netflix Addon Error\"\nmsgstr \"\"\n+\n+msgctxt \"#30106\"\n+msgid \"Invalid PIN\"\n+msgstr \"\"\n+\n+msgctxt \"#30107\"\n+msgid \"Disabled PIN verfication\"\n+msgstr \"\"\n+\n+msgctxt \"#30108\"\n+msgid \"Enabled PIN verfication\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -176,9 +176,6 @@ def rate(videoid, rating):\ncommon.make_call(\n'post',\n{'component': 'set_video_rating',\n- 'headers': {\n- 'Content-Type': 'application/json',\n- 'Accept': 'application/json, text/javascript, */*'},\n'params': {\n'titleid': videoid.value,\n'rating': rating}})\n@@ -190,9 +187,6 @@ def update_my_list(videoid, operation):\ncommon.make_call(\n'post',\n{'component': 'update_my_list',\n- 'headers': {\n- 'Content-Type': 'application/json',\n- 'Accept': 'application/json, text/javascript, */*'},\n'data': {\n'operation': operation,\n'videoId': int(videoid.value)}})\n@@ -240,6 +234,7 @@ def _metadata(video_id):\n'params': {'movieid': video_id}\n})['video']\n+\ndef search(search_term):\n\"\"\"Retrieve a video list of search results\"\"\"\ncommon.debug('Searching for {}'.format(search_term))\n@@ -252,6 +247,19 @@ def search(search_term):\nVIDEO_LIST_PARTIAL_PATHS)))\n+def verify_pin(pin):\n+ \"\"\"Send adult PIN to Netflix and verify it.\"\"\"\n+ # pylint: disable=broad-except\n+ try:\n+ return common.make_call(\n+ 'post',\n+ {'component': 'adult_pin',\n+ 'data': {\n+ 'pin': pin}}).get('success', False)\n+ except Exception:\n+ return False\n+\n+\ndef build_paths(base_path, partial_paths):\n\"\"\"Build a list of full paths by concatenating each partial path\nwith the base path\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "@@ -41,8 +41,9 @@ def get_item(videoid):\nif os.path.normcase(library_item['file']) == exported_filepath:\nreturn library_item\nexcept Exception:\n- import traceback\n- common.error(traceback.format_exc())\n+ # import traceback\n+ # common.error(traceback.format_exc())\n+ pass\n# This is intentionally not raised in the except block!\nraise ItemNotFound(\n'The video with id {} is not present in the Kodi library'\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/ui/dialogs.py",
"new_path": "resources/lib/kodi/ui/dialogs.py",
"diff": "@@ -49,13 +49,10 @@ def ask_for_rating():\ndef ask_for_pin():\n\"\"\"Ask the user for the adult pin\"\"\"\n- try:\n- return int(xbmcgui.Dialog()\n- .numeric(heading=common.get_local_string(30002),\n+ return xbmcgui.Dialog().numeric(\n+ heading=common.get_local_string(30002),\ntype=0,\n- defaultt=''))\n- except ValueError:\n- return None\n+ defaultt='') or None\ndef ask_for_search_term():\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/actions.py",
"new_path": "resources/lib/navigation/actions.py",
"diff": "@@ -38,6 +38,7 @@ class AddonActionExecutor(object):\nself.params['autologin_user'])\ng.ADDON.setSetting('autologin_id', pathitems[1])\ng.ADDON.setSetting('autologin_enable', 'true')\n+ g.flush_settings()\nexcept (KeyError, IndexError):\ncommon.error('Cannot save autologin - invalid params')\ncache.invalidate_cache()\n@@ -51,8 +52,18 @@ class AddonActionExecutor(object):\ndef toggle_adult_pin(self, pathitems=None):\n\"\"\"Toggle adult PIN verification\"\"\"\n# pylint: disable=no-member\n- g.ADDON.setSettingBool(\n- not g.ADDON.getSettingBool('adultpin_enable'))\n+ pin = ui.ask_for_pin()\n+ if pin is None:\n+ return\n+ if api.verify_pin(pin):\n+ current_setting = {'true': True, 'false': False}.get(\n+ g.ADDON.getSetting('adultpin_enable').lower())\n+ g.ADDON.setSetting('adultpin_enable', str(not current_setting))\n+ g.flush_settings()\n+ ui.show_notification(\n+ common.get_local_string(30107 if current_setting else 30108))\n+ else:\n+ ui.show_notification(common.get_local_string(30106))\[email protected]_video_id(path_offset=1)\ndef rate(self, videoid):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/player.py",
"new_path": "resources/lib/navigation/player.py",
"diff": "@@ -10,6 +10,7 @@ from resources.lib.globals import g\nimport resources.lib.common as common\nimport resources.lib.api.shakti as api\nimport resources.lib.kodi.infolabels as infolabels\n+import resources.lib.kodi.ui as ui\nfrom resources.lib.services.playback import get_timeline_markers\nSERVICE_URL_FORMAT = 'http://localhost:{port}'\n@@ -42,6 +43,12 @@ def play(videoid):\n\"\"\"Play an episode or movie as specified by the path\"\"\"\ncommon.debug('Playing {}'.format(videoid))\nmetadata = api.metadata(videoid)\n+\n+ if not _verify_pin(metadata['requiresPin']):\n+ ui.show_notification(common.get_local_string(30106))\n+ xbmcplugin.endOfDirectory(g.PLUGIN_HANDLE, succeeded=False)\n+ return\n+\ntimeline_markers = get_timeline_markers(metadata)\nlist_item = get_inputstream_listitem(videoid)\ninfos, art = infolabels.add_info_for_playback(videoid, list_item)\n@@ -103,6 +110,14 @@ def get_inputstream_listitem(videoid):\nreturn list_item\n+def _verify_pin(pin_required):\n+ if (not pin_required or\n+ g.ADDON.getSetting('adultpin_enable').lower() == 'false'):\n+ return True\n+ pin = ui.ask_for_pin()\n+ return pin is not None and api.verify_pin(pin)\n+\n+\ndef integrate_upnext(videoid, current, timeline_markers, metadata):\n\"\"\"Determine next episode and send an AddonSignal to UpNext addon\"\"\"\npass\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -152,6 +152,8 @@ class NetflixSession(object):\nself.session_data = website.extract_session_data(\nself._get('profiles'))\nexcept Exception:\n+ import traceback\n+ common.debug(traceback.format_exc())\ncommon.info('Failed to refresh session data, login expired')\nreturn False\nreturn True\n@@ -222,6 +224,8 @@ class NetflixSession(object):\n'switchProfileGuid': guid,\n'_': int(time()),\n'authURL': self.auth_url})\n+ self.session.headers.update(\n+ {'x-netflix.request.client.user.guid': guid})\nself.session_data['user_data']['guid'] = guid\ncommon.debug('Successfully activated profile {}'.format(guid))\n@@ -281,14 +285,18 @@ class NetflixSession(object):\nstart = time()\ndata = kwargs.get('data', {})\n- if component in ['set_video_rating', 'update_my_list']:\n+ headers = kwargs.get('headers', {})\n+ if component in ['set_video_rating', 'update_my_list', 'adult_pin']:\n+ headers.update({\n+ 'Content-Type': 'application/json',\n+ 'Accept': 'application/json, text/javascript, */*'})\ndata['authURL'] = self.auth_url\ndata = json.dumps(data)\nresponse = method(\nurl=url,\nverify=self.verify_ssl,\n- headers=kwargs.get('headers'),\n+ headers=headers,\nparams=kwargs.get('params'),\ndata=data)\ncommon.debug('Request took {}s'.format(time() - start))\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add adult PIN verification |
105,989 | 03.11.2018 00:12:17 | -3,600 | 2a6b1beb63e9d8940bff9426b906907139d38101 | Fix caching when reusing Kodi language invokers | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "@@ -17,7 +17,6 @@ from resources.lib.globals import g\ng.init_globals(sys.argv)\nimport resources.lib.common as common\n-import resources.lib.cache as cache\nimport resources.lib.kodi.ui as ui\nimport resources.lib.navigation as nav\nimport resources.lib.navigation.directory as directory\n@@ -67,4 +66,4 @@ if __name__ == '__main__':\nnetflix_error=False)\nxbmcplugin.endOfDirectory(handle=g.PLUGIN_HANDLE, succeeded=False)\n- cache.commit()\n+ g.CACHE.commit()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -20,19 +20,19 @@ class InvalidVideoListTypeError(Exception):\ndef activate_profile(profile_id):\n\"\"\"Activate the profile with the given ID\"\"\"\n- cache.invalidate_cache()\n+ g.CACHE.invalidate()\ncommon.make_call('activate_profile', profile_id)\ndef logout():\n\"\"\"Logout of the current account\"\"\"\n- cache.invalidate_cache()\n+ g.CACHE.invalidate()\ncommon.make_call('logout')\ndef login():\n\"\"\"Perform a login\"\"\"\n- cache.invalidate_cache()\n+ g.CACHE.invalidate()\ncommon.make_call('login')\n@@ -41,7 +41,7 @@ def profiles():\nreturn common.make_call('list_profiles')\[email protected]_output(cache.CACHE_COMMON, fixed_identifier='root_lists')\[email protected]_output(g, cache.CACHE_COMMON, fixed_identifier='root_lists')\ndef root_lists():\n\"\"\"Retrieve initial video lists to display on homepage\"\"\"\ncommon.debug('Requesting root lists from API')\n@@ -56,7 +56,7 @@ def root_lists():\n[['title']] + ART_PARTIAL_PATHS)))\[email protected]_output(cache.CACHE_COMMON, identifying_param_index=0,\[email protected]_output(g, cache.CACHE_COMMON, identifying_param_index=0,\nidentifying_param_name='list_type')\ndef list_id_for_type(list_type):\n\"\"\"Return the dynamic video list ID for a video list of known type\"\"\"\n@@ -70,7 +70,7 @@ def list_id_for_type(list_type):\nreturn list_id\[email protected]_output(cache.CACHE_COMMON, identifying_param_index=0,\[email protected]_output(g, cache.CACHE_COMMON, identifying_param_index=0,\nidentifying_param_name='list_id')\ndef video_list(list_id):\n\"\"\"Retrieve a single video list\"\"\"\n@@ -92,7 +92,7 @@ def custom_video_list(video_ids):\nbuild_paths(['videos', video_ids], VIDEO_LIST_PARTIAL_PATHS)))\[email protected]_output(cache.CACHE_GENRES, identifying_param_index=0,\[email protected]_output(g, cache.CACHE_GENRES, identifying_param_index=0,\nidentifying_param_name='genre_id')\ndef genre(genre_id):\n\"\"\"Retrieve LoLoMos for the given genre\"\"\"\n@@ -110,7 +110,7 @@ def genre(genre_id):\n['id', 'name']]]))\[email protected]_output(cache.CACHE_COMMON)\[email protected]_output(g, cache.CACHE_COMMON)\ndef seasons(videoid):\n\"\"\"Retrieve seasons of a TV show\"\"\"\nif videoid.mediatype != common.VideoId.SHOW:\n@@ -125,7 +125,7 @@ def seasons(videoid):\nSEASONS_PARTIAL_PATHS)))\[email protected]_output(cache.CACHE_COMMON)\[email protected]_output(g, cache.CACHE_COMMON)\ndef episodes(videoid):\n\"\"\"Retrieve episodes of a season\"\"\"\nif videoid.mediatype != common.VideoId.SEASON:\n@@ -145,7 +145,7 @@ def episodes(videoid):\n[['title']])))\[email protected]_output(cache.CACHE_COMMON)\[email protected]_output(g, cache.CACHE_COMMON)\ndef single_info(videoid):\n\"\"\"Retrieve info for a single episode\"\"\"\nif videoid.mediatype not in [common.VideoId.EPISODE, common.VideoId.MOVIE]:\n@@ -159,13 +159,17 @@ def single_info(videoid):\nreturn common.make_call('path_request', paths)\[email protected]_output(cache.CACHE_COMMON, fixed_identifier='my_list_items')\[email protected]_output(g, cache.CACHE_COMMON,\n+ fixed_identifier='my_list_items')\ndef mylist_items():\n\"\"\"Return a list of all the items currently contained in my list\"\"\"\n+ try:\nreturn [video_id\nfor video_id, video in video_list(\nlist_id_for_type('queue')).videos.iteritems()\nif video['queue'].get('inQueue', False)]\n+ except InvalidVideoListTypeError:\n+ return []\ndef rate(videoid, rating):\n@@ -190,11 +194,10 @@ def update_my_list(videoid, operation):\n'data': {\n'operation': operation,\n'videoId': int(videoid.value)}})\n- cache.invalidate_entry(cache.CACHE_COMMON,\n- list_id_for_type('queue'))\n- cache.invalidate_entry(cache.CACHE_COMMON, 'queue')\n- cache.invalidate_entry(cache.CACHE_COMMON, 'my_list_items')\n- cache.invalidate_entry(cache.CACHE_COMMON, 'root_lists')\n+ g.CACHE.invalidate_entry(cache.CACHE_COMMON, list_id_for_type('queue'))\n+ g.CACHE.invalidate_entry(cache.CACHE_COMMON, 'queue')\n+ g.CACHE.invalidate_entry(cache.CACHE_COMMON, 'my_list_items')\n+ g.CACHE.invalidate_entry(cache.CACHE_COMMON, 'root_lists')\ndef metadata(videoid):\n@@ -211,7 +214,7 @@ def metadata(videoid):\n# data is outdated. In this case, invalidate the cache entry and\n# try again safely (if it doesn't exist this time, there is no\n# metadata for the episode, so we assign an empty dict).\n- cache.invalidate_entry(cache.CACHE_METADATA, videoid.tvshowid)\n+ g.CACHE.invalidate_entry(cache.CACHE_METADATA, videoid.tvshowid)\nseason = common.find(videoid.seasonid,\n_metadata(videoid.tvshowid)['seasons'],\nraise_exc=False)\n@@ -219,7 +222,7 @@ def metadata(videoid):\nraise_exc=False)\[email protected]_output(cache.CACHE_METADATA, 0, 'video_id',\[email protected]_output(g, cache.CACHE_METADATA, 0, 'video_id',\nttl=g.CACHE_METADATA_TTL, to_disk=True)\ndef _metadata(video_id):\n\"\"\"Retrieve additional metadata for a video.This is a separate method from\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/website.py",
"new_path": "resources/lib/api/website.py",
"diff": "@@ -54,7 +54,7 @@ def extract_session_data(content):\nfor item in PAGE_ITEMS\nif 'serverDefs' in item)}\nif user_data.get('membershipStatus') != 'CURRENT_MEMBER':\n- raise InvalidMembershipStatusError()\n+ raise InvalidMembershipStatusError(user_data.get('membershipStatus'))\nreturn {\n'profiles': profiles,\n'user_data': user_data,\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "# -*- coding: utf-8 -*-\n\"\"\"General caching facilities. Caches are segmented into buckets.\n-Within each bucket, identifiers for cache entries must be unique.\"\"\"\n+Within each bucket, identifiers for cache entries must be unique.\n+\n+Must not be used within these modules, because stale values may\n+be used and cause inconsistencies:\n+resources.lib.self.common\n+resources.lib.services\n+resources.lib.kodi.ui\n+resources.lib.services.nfsession\n+\"\"\"\nfrom __future__ import unicode_literals\nimport os\n@@ -14,11 +22,6 @@ except ImportError:\nimport xbmc\nimport xbmcgui\n-from resources.lib.globals import g\n-import resources.lib.common as common\n-\n-WND = xbmcgui.Window(10000)\n-\nCACHE_COMMON = 'cache_common'\nCACHE_GENRES = 'cache_genres'\nCACHE_METADATA = 'cache_metadata'\n@@ -28,28 +31,12 @@ CACHE_LIBRARY = 'library'\nBUCKET_NAMES = [CACHE_COMMON, CACHE_GENRES, CACHE_METADATA,\nCACHE_INFOLABELS, CACHE_ARTINFO, CACHE_LIBRARY]\n-BUCKETS = {}\nBUCKET_LOCKED = 'LOCKED_BY_{}'\nTTL_INFINITE = 60*60*24*365*100\n-def _init_disk_cache():\n- for bucket in BUCKET_NAMES:\n- if bucket == CACHE_LIBRARY:\n- # Library gets special location in DATA_PATH root because we\n- # dont want users accidentally deleting it.\n- continue\n- try:\n- os.makedirs(os.path.join(g.DATA_PATH, 'cache', bucket))\n- except OSError:\n- pass\n-\n-\n-_init_disk_cache()\n-\n-\nclass CacheMiss(Exception):\n\"\"\"Requested item is not in the cache\"\"\"\npass\n@@ -60,29 +47,32 @@ class UnknownCacheBucketError(Exception):\npass\n-# pylint: disable=too-many-arguments\n-def cache_output(bucket, identifying_param_index=0,\n+def cache_output(g, bucket, identifying_param_index=0,\nidentifying_param_name='videoid',\nfixed_identifier=None,\nttl=None,\nto_disk=False):\n\"\"\"Decorator that ensures caching the output of a function\"\"\"\n- # pylint: disable=missing-docstring\n+ # pylint: disable=missing-docstring, invalid-name, too-many-arguments\ndef caching_decorator(func):\n@wraps(func)\ndef wrapper(*args, **kwargs):\n+ try:\nidentifier = _get_identifier(fixed_identifier,\nidentifying_param_name,\nkwargs,\nidentifying_param_index,\nargs)\n- try:\n- return get(bucket, identifier)\n+ cached_result = g.CACHE.get(bucket, identifier)\n+ return cached_result\nexcept CacheMiss:\n- common.debug('Cache miss on {}'.format(identifying_param_name))\noutput = func(*args, **kwargs)\n- add(bucket, identifier, output, ttl=ttl, to_disk=to_disk)\n+ g.CACHE.add(bucket, identifier, output, ttl=ttl,\n+ to_disk=to_disk)\nreturn output\n+ except IndexError:\n+ # Do not cache if identifier couldn't be determined\n+ return func(*args, **kwargs)\nreturn wrapper\nreturn caching_decorator\n@@ -90,21 +80,13 @@ def cache_output(bucket, identifying_param_index=0,\ndef _get_identifier(fixed_identifier, identifying_param_name, kwargs,\nidentifying_param_index, args):\n\"\"\"Return the identifier to use with the caching_decorator\"\"\"\n- if fixed_identifier:\n- # Use the identifier that's statically defined in the applied\n- # decorator isntead of one of the parameters' value\n- return fixed_identifier\n- else:\n- try:\n- # prefer keyword over positional arguments\n- return kwargs.get(identifying_param_name,\n- args[identifying_param_index])\n- except IndexError:\n- common.error(\n- 'Invalid cache configuration.'\n- 'Cannot determine identifier from params')\n+ return (fixed_identifier\n+ if fixed_identifier\n+ else kwargs.get(identifying_param_name,\n+ args[identifying_param_index]))\n-# def inject_from_cache(bucket, injection_param,\n+\n+# def inject_from_cache(cache, bucket, injection_param,\n# identifying_param_index=0,\n# identifying_param_name=None,\n# fixed_identifier=None,\n@@ -115,208 +97,191 @@ def _get_identifier(fixed_identifier, identifying_param_name, kwargs,\n# def injecting_cache_decorator(func):\n# @wraps(func)\n# def wrapper(*args, **kwargs):\n-# if fixed_identifier:\n-# # Use the identifier that's statically defined in the applied\n-# # decorator isntead of one of the parameters' value\n-# identifier = fixed_identifier\n-# else:\n-# try:\n-# # prefer keyword over positional arguments\n-# identifier = kwargs.get(\n+# identifier = _get_identifier(fixed_identifier,\n# identifying_param_name,\n-# args[identifying_param_index])\n-# except IndexError:\n-# common.error(\n-# 'Invalid cache configuration.'\n-# 'Cannot determine identifier from params')\n+# kwargs,\n+# identifying_param_index,\n+# args)\n# try:\n-# value_to_inject = get(bucket, identifier)\n+# value_to_inject = cache.get(bucket, identifier)\n# except CacheMiss:\n# value_to_inject = None\n# kwargs[injection_param] = value_to_inject\n# output = func(*args, **kwargs)\n-# add(bucket, identifier, output, ttl=ttl, to_disk=to_disk)\n+# cache.add(bucket, identifier, output, ttl=ttl, to_disk=to_disk)\n# return output\n# return wrapper\n# return injecting_cache_decorator\n-def get_bucket(key):\n- \"\"\"Get a cache bucket.\n- Load it lazily from window property if it's not yet in memory\"\"\"\n- if key not in BUCKET_NAMES:\n- raise UnknownCacheBucketError()\n-\n- if key not in BUCKETS:\n- BUCKETS[key] = _load_bucket(key)\n- return BUCKETS[key]\n-\n-\n-def invalidate_cache():\n- \"\"\"Clear all cache buckets\"\"\"\n- # pylint: disable=global-statement\n- global BUCKETS\n- for bucket in BUCKETS:\n- _clear_bucket(bucket)\n- BUCKETS = {}\n- common.info('Cache invalidated')\n-\n-\n-def invalidate_entry(bucket, identifier):\n- \"\"\"Remove an item from a bucket\"\"\"\n+class Cache(object):\n+ def __init__(self, common, data_path, ttl, metadata_ttl, plugin_handle):\n+ # pylint: disable=too-many-arguments\n+ # We have the self.common module injected as a dependency to work\n+ # around circular dependencies with gloabl variable initialization\n+ self.common = common\n+ self.data_path = data_path\n+ self.ttl = ttl\n+ self.metadata_ttl = metadata_ttl\n+ self.buckets = {}\n+ self.lock_marker = str(BUCKET_LOCKED.format(plugin_handle))\n+ self.window = xbmcgui.Window(10000)\n+ self.common.debug('Cache instantiated')\n+\n+ def get(self, bucket, identifier):\n+ \"\"\"Retrieve an item from a cache bucket\"\"\"\ntry:\n- _purge_entry(bucket, identifier)\n- common.debug('Invalidated {} in {}'.format(identifier, bucket))\n+ cache_entry = self._get_bucket(bucket)[identifier]\nexcept KeyError:\n- common.debug('Nothing to invalidate, {} was not in {}'\n- .format(identifier, bucket))\n+ cache_entry = self._get_from_disk(bucket, identifier)\n+ self.add(bucket, identifier, cache_entry['content'])\n+ self.verify_ttl(bucket, identifier, cache_entry)\n+ return cache_entry['content']\n+ def add(self, bucket, identifier, content, ttl=None, to_disk=False):\n+ \"\"\"Add an item to a cache bucket\"\"\"\n+ # pylint: disable=too-many-arguments\n+ eol = int(time() + (ttl if ttl else self.ttl))\n+ # self.common.debug('Adding {} to {} (valid until {})'\n+ # .format(identifier, bucket, eol))\n+ cache_entry = {'eol': eol, 'content': content}\n+ self._get_bucket(bucket).update(\n+ {identifier: cache_entry})\n+ if to_disk:\n+ self._add_to_disk(bucket, identifier, cache_entry)\n-def commit():\n+ def commit(self):\n\"\"\"Persist cache contents in window properties\"\"\"\n# pylint: disable=global-statement\n- global BUCKETS\n- for bucket, contents in BUCKETS.items():\n- _persist_bucket(bucket, contents)\n- # The BUCKETS dict survives across addon invocations if the same\n- # languageInvoker thread is being used so we MUST clear its contents\n- # to allow cache consistency between instances\n- del BUCKETS[bucket]\n- common.debug('Cache committ successful')\n-\n+ for bucket, contents in self.buckets.items():\n+ self._persist_bucket(bucket, contents)\n+ # The self.buckets dict survives across addon invocations if the\n+ # same languageInvoker thread is being used so we MUST clear its\n+ # contents to allow cache consistency between instances\n+ # del self.buckets[bucket]\n+ self.common.debug('Cache committ successful')\n+\n+ def invalidate(self):\n+ \"\"\"Clear all cache buckets\"\"\"\n+ # pylint: disable=global-statement\n+ for bucket in BUCKET_NAMES:\n+ self.window.clearProperty(_window_property(bucket))\n+ self.buckets = {}\n+ self.common.info('Cache invalidated')\n-def get(bucket, identifier):\n- \"\"\"Retrieve an item from a cache bucket\"\"\"\n+ def invalidate_entry(self, bucket, identifier):\n+ \"\"\"Remove an item from a bucket\"\"\"\ntry:\n- cache_entry = get_bucket(bucket)[identifier]\n+ self._purge_entry(bucket, identifier)\n+ self.common.debug('Invalidated {} in {}'\n+ .format(identifier, bucket))\nexcept KeyError:\n- common.debug('In-memory cache miss on {} in {}'\n+ self.common.debug('Nothing to invalidate, {} was not in {}'\n.format(identifier, bucket))\n- cache_entry = get_from_disk(bucket, identifier)\n- verify_ttl(bucket, identifier, cache_entry)\n+ def _get_bucket(self, key):\n+ \"\"\"Get a cache bucket.\n+ Load it lazily from window property if it's not yet in memory\"\"\"\n+ if key not in BUCKET_NAMES:\n+ raise UnknownCacheBucketError()\n+ if key not in self.buckets:\n+ self.buckets[key] = self._load_bucket(key)\n+ return self.buckets[key]\n- return cache_entry['content']\n+ def _load_bucket(self, bucket):\n+ wnd_property = ''\n+ # Try 10 times to acquire a lock\n+ for _ in range(1, 10):\n+ wnd_property = self.window.getProperty(_window_property(bucket))\n+ # pickle stores byte data, so we must compare against a str\n+ if wnd_property.startswith(str('LOCKED')):\n+ self.common.debug('Waiting for release of {}'.format(bucket))\n+ xbmc.sleep(50)\n+ else:\n+ return self._load_bucket_from_wndprop(bucket, wnd_property)\n+ self.common.warn('{} is locked. Working with an empty instance...'\n+ .format(bucket))\n+ return {}\n+ def _load_bucket_from_wndprop(self, bucket, wnd_property):\n+ # pylint: disable=broad-except\n+ try:\n+ bucket_instance = pickle.loads(wnd_property)\n+ except Exception:\n+ self.common.debug('No instance of {} found. Creating new instance.'\n+ .format(bucket))\n+ bucket_instance = {}\n+ self.window.setProperty(_window_property(bucket), self.lock_marker)\n+ self.common.debug('Acquired lock on {}'.format(bucket))\n+ return bucket_instance\n-def get_from_disk(bucket, identifier):\n+ def _get_from_disk(self, bucket, identifier):\n\"\"\"Load a cache entry from disk and add it to the in memory bucket\"\"\"\n- cache_filename = _entry_filename(bucket, identifier)\n+ cache_filename = self._entry_filename(bucket, identifier)\ntry:\nwith open(cache_filename, 'r') as cache_file:\ncache_entry = pickle.load(cache_file)\nexcept Exception:\n- common.debug('On-disk cache miss on {} in {}'\n- .format(identifier, bucket))\nraise CacheMiss()\n- add(bucket, identifier, cache_entry['content'])\nreturn cache_entry\n-\n-def add(bucket, identifier, content, ttl=None, to_disk=False):\n- \"\"\"Add an item to a cache bucket\"\"\"\n- eol = int(time() + (ttl if ttl else g.CACHE_TTL))\n- # common.debug('Adding {} to {} (valid until {})'\n- # .format(identifier, bucket, eol))\n- cache_entry = {'eol': eol, 'content': content}\n- get_bucket(bucket).update(\n- {identifier: cache_entry})\n- if to_disk:\n- add_to_disk(bucket, identifier, cache_entry)\n-\n-\n-def add_to_disk(bucket, identifier, cache_entry):\n+ def _add_to_disk(self, bucket, identifier, cache_entry):\n\"\"\"Write a cache entry to disk\"\"\"\n# pylint: disable=broad-except\n- cache_filename = _entry_filename(bucket, identifier)\n+ cache_filename = self._entry_filename(bucket, identifier)\ntry:\nwith open(cache_filename, 'w') as cache_file:\npickle.dump(cache_entry, cache_file)\nexcept Exception as exc:\n- common.error('Failed to write cache entry to {}: {}'\n+ self.common.error('Failed to write cache entry to {}: {}'\n.format(cache_filename, exc))\n-\n-def verify_ttl(bucket, identifier, cache_entry):\n- \"\"\"Verify if cache_entry has reached its EOL.\n- Remove from in-memory and disk cache if so and raise CacheMiss\"\"\"\n- if cache_entry['eol'] < int(time()):\n- common.debug('Cache entry {} in {} has expired => cache miss'\n- .format(identifier, bucket))\n- _purge_entry(bucket, identifier)\n- raise CacheMiss()\n-\n-\n-def _entry_filename(bucket, identifier):\n+ def _entry_filename(self, bucket, identifier):\nif bucket == CACHE_LIBRARY:\n# We want a special handling for the library database, so users\n# dont accidentally delete it when deleting the cache\n- file_loc = ['library.ndb']\n+ file_loc = ['library.ndb2']\nelse:\nfile_loc = [\n- 'cache', bucket, '{filename}.cache'.format(filename=identifier)]\n- return os.path.join(g.DATA_PATH, *file_loc)\n-\n-\n-def _window_property(bucket):\n- return 'nfmemcache_{}'.format(bucket)\n-\n+ 'cache', bucket, '{}.cache'.format(identifier)]\n+ return os.path.join(self.data_path, *file_loc)\n-def _load_bucket(bucket):\n- wnd_property = ''\n- for _ in range(1, 10):\n- wnd_property = WND.getProperty(_window_property(bucket))\n- # pickle stores byte data, so we must compare against a str\n- if wnd_property.startswith(str('LOCKED')):\n- common.debug('Waiting for release of {}'.format(bucket))\n- xbmc.sleep(50)\n- else:\n- return _load_bucket_from_wndprop(bucket, wnd_property)\n- common.warn('{} is locked. Working with an empty instance...'\n- .format(bucket))\n- return {}\n-\n-\n-def _load_bucket_from_wndprop(bucket, wnd_property):\n- # pylint: disable=broad-except\n- try:\n- bucket_instance = pickle.loads(wnd_property)\n- except Exception:\n- common.debug('No instance of {} found. Creating new instance.'\n- .format(bucket))\n- bucket_instance = {}\n- WND.setProperty(_window_property(bucket),\n- str(BUCKET_LOCKED.format(g.PLUGIN_HANDLE)))\n- common.debug('Acquired lock on {}'.format(bucket))\n- return bucket_instance\n-\n-\n-def _persist_bucket(bucket, contents):\n+ def _persist_bucket(self, bucket, contents):\n# pylint: disable=broad-except\n- lock = WND.getProperty(_window_property(bucket))\n+ lock = self.window.getProperty(_window_property(bucket))\n# pickle stored byte data, so we must compare against a str\n- if lock == str(BUCKET_LOCKED.format(g.PLUGIN_HANDLE)):\n+ if lock == self.lock_marker:\ntry:\n- WND.setProperty(_window_property(bucket), pickle.dumps(contents))\n+ self.window.setProperty(_window_property(bucket),\n+ pickle.dumps(contents))\nexcept Exception as exc:\n- common.error('Failed to persist {} to window properties: {}'\n+ self.common.error('Failed to persist {} to wnd properties: {}'\n.format(bucket, exc))\n- WND.clearProperty(_window_property(bucket))\n+ self.window.clearProperty(_window_property(bucket))\nfinally:\n- common.debug('Released lock on {}'.format(bucket))\n+ self.common.debug('Released lock on {}'.format(bucket))\nelse:\n- common.warn('{} is locked by another instance. Discarding changes...'\n+ self.common.warn(\n+ '{} is locked by another instance. Discarding changes'\n.format(bucket))\n+ def verify_ttl(self, bucket, identifier, cache_entry):\n+ \"\"\"Verify if cache_entry has reached its EOL.\n+ Remove from in-memory and disk cache if so and raise CacheMiss\"\"\"\n+ if cache_entry['eol'] < int(time()):\n+ self.common.debug('Cache entry {} in {} has expired => cache miss'\n+ .format(identifier, bucket))\n+ self._purge_entry(bucket, identifier)\n+ raise CacheMiss()\n-def _clear_bucket(bucket):\n- WND.clearProperty(_window_property(bucket))\n-\n-\n-def _purge_entry(bucket, identifier):\n+ def _purge_entry(self, bucket, identifier):\n# Remove from in-memory cache\n- del get_bucket(bucket)[identifier]\n+ del self._get_bucket(bucket)[identifier]\n# Remove from disk cache if it exists\n- cache_filename = _entry_filename(bucket, identifier)\n+ cache_filename = self._entry_filename(bucket, identifier)\nif os.path.exists(cache_filename):\nos.remove(cache_filename)\n+\n+\n+def _window_property(bucket):\n+ return 'nfmemcache_{}'.format(bucket)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/logging.py",
"new_path": "resources/lib/common/logging.py",
"diff": "@@ -14,8 +14,9 @@ def log(msg, exc=None, level=xbmc.LOGDEBUG):\nIf msg contains a format placeholder for exc and exc is not none,\nexc will be formatted into the message.\"\"\"\nmsg = msg.format(exc=exc) if exc is not None and '{exc}' in msg else msg\n- xbmc.log(\n- '[{identifier}] {msg}'.format(identifier=g.ADDON_ID, msg=msg), level)\n+ xbmc.log('[{identifier} ({handle})] {msg}'\n+ .format(identifier=g.ADDON_ID, handle=g.PLUGIN_HANDLE, msg=msg),\n+ level)\ndef debug(msg='{exc}', exc=None):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/globals.py",
"new_path": "resources/lib/globals.py",
"diff": "# -*- coding: utf-8 -*-\n-\"\"\"Global addon constants\"\"\"\n+\"\"\"Global addon constants.\n+Everything that is to be globally accessible must be defined in this module\n+and initialized in GlobalVariables.init_globals.\n+When reusing Kodi languageInvokers, only the code in the main module\n+(addon.py or service.py) will be run every time the addon is called.\n+All other code executed on module level will only be executed once, when\n+the module is first imported on the first addon invocation.\"\"\"\nfrom __future__ import unicode_literals\n-import sys\nimport os\nfrom urlparse import urlparse, parse_qsl\nimport xbmc\nimport xbmcaddon\n+import resources.lib.cache as cache\n+\nclass GlobalVariables(object):\n\"\"\"Encapsulation for global variables to work around quirks with\nKodi's reuseLanguageInvoker behavior\"\"\"\n+ # pylint: disable=attribute-defined-outside-init\n# pylint: disable=invalid-name, too-many-instance-attributes\nKNOWN_LIST_TYPES = ['queue', 'topTen', 'netflixOriginals',\n'continueWatching', 'trendingNow', 'newRelease',\n@@ -34,15 +42,15 @@ class GlobalVariables(object):\nMODE_PLAY = 'play'\nMODE_LIBRARY = 'library'\n- def __init__(self, argv):\n- self.init_globals(argv)\n+ def __init__(self):\n+ \"\"\"Do nothing on constructing the object\"\"\"\n+ pass\ndef init_globals(self, argv):\n\"\"\"Initialized globally used module variables.\nNeeds to be called at start of each plugin instance!\nThis is an ugly hack because Kodi doesn't execute statements defined on\nmodule level if reusing a language invoker.\"\"\"\n- # pylint: disable=global-statement\nself._library = None\nself.ADDON = xbmcaddon.Addon()\nself.ADDON_ID = self.ADDON.getAddonInfo('id')\n@@ -75,22 +83,39 @@ class GlobalVariables(object):\nexcept OSError:\npass\n+ self._init_cache()\n+\n+ def _init_cache(self):\n+ if not os.path.exists(os.path.join(self.DATA_PATH, 'cache')):\n+ for bucket in cache.BUCKET_NAMES:\n+ if bucket == cache.CACHE_LIBRARY:\n+ # Library gets special location in DATA_PATH root because\n+ # we don't want users accidentally deleting it.\n+ continue\n+ try:\n+ os.makedirs(os.path.join(g.DATA_PATH, 'cache', bucket))\n+ except OSError:\n+ pass\n+ # This is ugly: Pass the common module into Cache.__init__ to work\n+ # around circular import dependencies.\n+ import resources.lib.common as common\n+ self.CACHE = cache.Cache(common, self.DATA_PATH, self.CACHE_TTL,\n+ self.CACHE_METADATA_TTL, self.PLUGIN_HANDLE)\n+\ndef library(self):\n\"\"\"Get the current library instance\"\"\"\n# pylint: disable=global-statement, attribute-defined-outside-init\n- import resources.lib.cache as cache\nif not self._library:\ntry:\n- self._library = cache.get(cache.CACHE_LIBRARY, 'library')\n+ self._library = self.CACHE.get(cache.CACHE_LIBRARY, 'library')\nexcept cache.CacheMiss:\nself._library = {}\nreturn self._library\ndef save_library(self):\n\"\"\"Save the library to disk via cache\"\"\"\n- import resources.lib.cache as cache\nif self._library is not None:\n- cache.add(cache.CACHE_LIBRARY, 'library', self._library,\n+ self.CACHE.add(cache.CACHE_LIBRARY, 'library', self._library,\nttl=cache.TTL_INFINITE, to_disk=True)\ndef get_esn(self):\n@@ -116,7 +141,7 @@ class GlobalVariables(object):\n# pylint: disable=invalid-name\n# This will have no effect most of the time, as it doesn't seem to be executed\n# on subsequent addon invocations when reuseLanguageInvoker is being used.\n-# We initialize this once so the instance is importable from addon.py and\n-# service.py, where g.init_globals(sys.argv) MUST be called before doing\n+# We initialize an empty instance so the instance is importable from addon.py\n+# and service.py, where g.init_globals(sys.argv) MUST be called before doing\n# anything else (even BEFORE OTHER IMPORTS from this addon)\n-g = GlobalVariables(sys.argv)\n+g = GlobalVariables()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -20,13 +20,12 @@ def add_info(videoid, list_item, item, raw_data):\nin place and the infolabels are returned.\"\"\"\n# pylint: disable=too-many-locals\ntry:\n- cache_entry = cache.get(cache.CACHE_INFOLABELS, videoid)\n+ cache_entry = g.CACHE.get(cache.CACHE_INFOLABELS, videoid)\ninfos = cache_entry['infos']\nquality_infos = cache_entry['quality_infos']\nexcept cache.CacheMiss:\ninfos, quality_infos = parse_info(videoid, item, raw_data)\n- cache.add(cache.CACHE_INFOLABELS,\n- videoid,\n+ g.CACHE.add(cache.CACHE_INFOLABELS, videoid,\n{'infos': infos, 'quality_infos': quality_infos},\nttl=g.CACHE_METADATA_TTL, to_disk=True)\nlist_item.setInfo('video', infos)\n@@ -40,10 +39,10 @@ def add_info(videoid, list_item, item, raw_data):\ndef add_art(videoid, list_item, item, raw_data=None):\n\"\"\"Add art infolabels to list_item\"\"\"\ntry:\n- art = cache.get(cache.CACHE_ARTINFO, videoid)\n+ art = g.CACHE.get(cache.CACHE_ARTINFO, videoid)\nexcept cache.CacheMiss:\nart = parse_art(videoid, item, raw_data)\n- cache.add(cache.CACHE_ARTINFO, videoid, art,\n+ g.CACHE.add(cache.CACHE_ARTINFO, videoid, art,\nttl=g.CACHE_METADATA_TTL, to_disk=True)\nlist_item.setArt(art)\nreturn art\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/msl_handler.py",
"new_path": "resources/lib/services/msl/msl_handler.py",
"diff": "@@ -75,8 +75,9 @@ class MSLHandler(object):\ncallback=self.perform_key_handshake)\n@display_error_info\n- def perform_key_handshake(self):\n+ def perform_key_handshake(self, data=None):\n\"\"\"Perform a key handshake and initialize crypto keys\"\"\"\n+ # pylint: disable=unused-argument\nif not g.get_esn():\ncommon.error('Cannot perform key handshake, missing ESN')\nreturn\n@@ -195,7 +196,8 @@ def _process_json_response(response):\ndef _raise_if_error(decoded_response):\n- if 'errordata' in decoded_response or not decoded_response['success']:\n+ if ('errordata' in decoded_response or\n+ not decoded_response.get('success', True)):\nraise MSLError(_get_error_details(decoded_response))\nreturn decoded_response\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -224,8 +224,6 @@ class NetflixSession(object):\n'switchProfileGuid': guid,\n'_': int(time()),\n'authURL': self.auth_url})\n- self.session.headers.update(\n- {'x-netflix.request.client.user.guid': guid})\nself.session_data['user_data']['guid'] = guid\ncommon.debug('Successfully activated profile {}'.format(guid))\n"
},
{
"change_type": "MODIFY",
"old_path": "service.py",
"new_path": "service.py",
"diff": "@@ -14,11 +14,13 @@ import traceback\nimport xbmc\n# Import and intiliaze globals right away to avoid stale values from the last\n-# addon invocation. Otherwise Kodi's reuseLanguageInvoker will caus some\n-# really quirky behavior!\n+# addon invocation. Otherwise Kodi's reuseLanguageInvoker option will cause\n+# some really quirky behavior!\nfrom resources.lib.globals import g\ng.init_globals(sys.argv)\n+# Global cache must not be used within these modules, because stale values may\n+# be used and cause inconsistencies!\nimport resources.lib.common as common\nimport resources.lib.services as services\nimport resources.lib.kodi.ui as ui\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix caching when reusing Kodi language invokers |
105,989 | 03.11.2018 00:54:59 | -3,600 | 023ec3383ca92668d953458116678909366db871 | Fix profile switching | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -194,7 +194,10 @@ def update_my_list(videoid, operation):\n'data': {\n'operation': operation,\n'videoId': int(videoid.value)}})\n+ try:\ng.CACHE.invalidate_entry(cache.CACHE_COMMON, list_id_for_type('queue'))\n+ except InvalidVideoListTypeError:\n+ pass\ng.CACHE.invalidate_entry(cache.CACHE_COMMON, 'queue')\ng.CACHE.invalidate_entry(cache.CACHE_COMMON, 'my_list_items')\ng.CACHE.invalidate_entry(cache.CACHE_COMMON, 'root_lists')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -224,7 +224,7 @@ class NetflixSession(object):\n'switchProfileGuid': guid,\n'_': int(time()),\n'authURL': self.auth_url})\n- self.session_data['user_data']['guid'] = guid\n+ self._refresh_session_data()\ncommon.debug('Successfully activated profile {}'.format(guid))\[email protected]_return_call\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix profile switching |
105,989 | 03.11.2018 13:32:18 | -3,600 | 37a9984de027820a5257350f9de43a0f38bb968f | Improve profile switching and session setup | [
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.de_de/strings.po",
"new_path": "resources/language/resource.language.de_de/strings.po",
"diff": "@@ -447,3 +447,11 @@ msgstr \"PIN-Abfrage deaktiviert\"\nmsgctxt \"#30108\"\nmsgid \"Enabled PIN verfication\"\nmsgstr \"PIN-Abfrage aktiviert\"\n+\n+msgctxt \"#30109\"\n+msgid \"Login successful\"\n+msgstr \"Login erfolgreich\"\n+\n+msgctxt \"#30110\"\n+msgid \"Background services started\"\n+msgstr \"Hintergrunddienste gestartet\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -455,3 +455,11 @@ msgstr \"\"\nmsgctxt \"#30108\"\nmsgid \"Enabled PIN verfication\"\nmsgstr \"\"\n+\n+msgctxt \"#30109\"\n+msgid \"Login successful\"\n+msgstr \"\"\n+\n+msgctxt \"#30110\"\n+msgid \"Background services started\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -20,8 +20,8 @@ class InvalidVideoListTypeError(Exception):\ndef activate_profile(profile_id):\n\"\"\"Activate the profile with the given ID\"\"\"\n+ if common.make_call('activate_profile', profile_id):\ng.CACHE.invalidate()\n- common.make_call('activate_profile', profile_id)\ndef logout():\n@@ -47,6 +47,10 @@ def root_lists():\ncommon.debug('Requesting root lists from API')\nreturn LoLoMo(common.make_call(\n'path_request',\n+ # TODO: Make sure that mylist is always retrieved\n+ [['lolomo',\n+ ['queue'],\n+ ['displayName', 'context', 'id', 'index', 'length', 'genreId']]] +\n[['lolomo',\n{'from': 0, 'to': 35},\n['displayName', 'context', 'id', 'index', 'length', 'genreId']]] +\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/website.py",
"new_path": "resources/lib/api/website.py",
"diff": "from __future__ import unicode_literals\nimport json\n+import traceback\nfrom re import compile as recompile, DOTALL\nimport resources.lib.common as common\n@@ -24,17 +25,22 @@ JSON_REGEX = r'netflix\\.%s\\s*=\\s*(.*?);\\s*</script>'\nAVATAR_SUBPATH = ['images', 'byWidth', '320', 'value']\n-class InvalidAuthURLError(Exception):\n+class WebsiteParsingError(Exception):\n+ \"\"\"Parsing info from the Netflix Website failed\"\"\"\n+ pass\n+\n+\n+class InvalidAuthURLError(WebsiteParsingError):\n\"\"\"The authURL is invalid\"\"\"\npass\n-class InvalidProfilesError(Exception):\n+class InvalidProfilesError(WebsiteParsingError):\n\"\"\"Cannot extract profiles from Netflix webpage\"\"\"\npass\n-class InvalidMembershipStatusError(Exception):\n+class InvalidMembershipStatusError(WebsiteParsingError):\n\"\"\"The user logging in does not have a valid subscription\"\"\"\npass\n@@ -44,41 +50,44 @@ def extract_session_data(content):\nCall all the parsers we need to extract all\nthe session relevant data from the HTML page\n\"\"\"\n- profiles = extract_profiles(content)\n+ common.debug('Extracting session data...')\n+ falkor_cache = extract_json(content, 'falcorCache')\n+ profiles, active_profile = extract_profiles(falkor_cache)\nuser_data = extract_userdata(content)\n- esn = generate_esn(user_data)\n- api_data = {\n- api_item: user_data[api_item]\n- for api_item in (\n- item.split('/')[-1]\n- for item in PAGE_ITEMS\n- if 'serverDefs' in item)}\nif user_data.get('membershipStatus') != 'CURRENT_MEMBER':\n+ common.error(user_data)\nraise InvalidMembershipStatusError(user_data.get('membershipStatus'))\nreturn {\n'profiles': profiles,\n+ 'active_profile': active_profile,\n+ 'root_lolomo': next(falkor_cache.get('lolomos', {}).iterkeys(), None),\n'user_data': user_data,\n- 'esn': esn,\n- 'api_data': api_data\n+ 'esn': generate_esn(user_data),\n+ 'api_data': _parse_api_data(user_data)\n}\n-def extract_profiles(content):\n+def extract_profiles(falkor_cache):\n\"\"\"Extract profile information from Netflix website\"\"\"\nprofiles = {}\n-\n+ active_profile = None\ntry:\n- falkor_cache = extract_json(content, 'falcorCache')\n- for guid, profile in falkor_cache.get('profiles', {}).iteritems():\n- common.debug('Parsing profile {}'.format(guid))\n+ for guid, profile in falkor_cache.get('profiles', {}).items():\n+ profiles[guid], is_active = _parse_profile(profile, falkor_cache)\n+ if is_active:\n+ active_profile = guid\n+ except Exception:\n+ common.error(traceback.format_exc())\n+ raise InvalidProfilesError\n+\n+ return profiles, active_profile\n+\n+\n+def _parse_profile(profile, falkor_cache):\n_profile = profile['summary']['value']\n+ common.debug('Parsing profile {}'.format(_profile['guid']))\n_profile['avatar'] = _get_avatar(falkor_cache, profile)\n- profiles.update({guid: _profile})\n- except Exception as exc:\n- common.error('Cannot parse profiles from webpage: {exc}', exc)\n- raise InvalidProfilesError()\n-\n- return profiles\n+ return _profile, _profile['isActive']\ndef _get_avatar(falkor_cache, profile):\n@@ -107,6 +116,14 @@ def extract_userdata(content):\nreturn assert_valid_auth_url(user_data)\n+def _parse_api_data(user_data):\n+ return {api_item: user_data[api_item]\n+ for api_item in (\n+ item.split('/')[-1]\n+ for item in PAGE_ITEMS\n+ if 'serverDefs' in item)}\n+\n+\ndef assert_valid_auth_url(user_data):\n\"\"\"Raise an exception if user_data does not contain a valid authURL\"\"\"\nif len(user_data.get('authURL', '')) != 42:\n@@ -145,11 +162,13 @@ def generate_esn(user_data):\ndef extract_json(content, name):\n\"\"\"Extract json from netflix content page\"\"\"\ncommon.debug('Extracting {} JSON'.format(name))\n+ try:\njson_array = recompile(JSON_REGEX % name, DOTALL).findall(content)\n- if not json_array:\n- return {} # Return an empty dict if json not found !\njson_str = json_array[0]\njson_str = json_str.replace('\\\"', '\\\\\"') # Escape double-quotes\njson_str = json_str.replace('\\\\s', '\\\\\\\\s') # Escape \\s\njson_str = json_str.decode('unicode_escape') # finally decoding...\nreturn json.loads(json_str)\n+ except Exception:\n+ common.error(traceback.format_exc())\n+ raise WebsiteParsingError('Unable to extract {}'.format(name))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -126,7 +126,6 @@ class Cache(object):\nself.buckets = {}\nself.lock_marker = str(BUCKET_LOCKED.format(plugin_handle))\nself.window = xbmcgui.Window(10000)\n- self.common.debug('Cache instantiated')\ndef get(self, bucket, identifier):\n\"\"\"Retrieve an item from a cache bucket\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/logging.py",
"new_path": "resources/lib/common/logging.py",
"diff": "@@ -15,7 +15,8 @@ def log(msg, exc=None, level=xbmc.LOGDEBUG):\nexc will be formatted into the message.\"\"\"\nmsg = msg.format(exc=exc) if exc is not None and '{exc}' in msg else msg\nxbmc.log('[{identifier} ({handle})] {msg}'\n- .format(identifier=g.ADDON_ID, handle=g.PLUGIN_HANDLE, msg=msg),\n+ .format(identifier=g.ADDON_ID, handle=g.PLUGIN_HANDLE, msg=msg)\n+ .encode('utf-8'),\nlevel)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "\"\"\"Stateful Netflix session management\"\"\"\nfrom __future__ import unicode_literals\n+import traceback\nfrom time import time\nfrom base64 import urlsafe_b64encode\nfrom functools import wraps\n@@ -20,6 +21,7 @@ BASE_URL = 'https://www.netflix.com'\nURLS = {\n'login': {'endpoint': '/login', 'is_api_call': False},\n'shakti': {'endpoint': '/pathEvaluator', 'is_api_call': True},\n+ 'browse': {'endpoint': '/browse', 'is_api_call': False},\n'profiles': {'endpoint': '/profiles/manage', 'is_api_call': False},\n'activate_profile': {'endpoint': '/profiles/switch', 'is_api_call': True},\n'adult_pin': {'endpoint': '/pin/service', 'is_api_call': True},\n@@ -27,7 +29,6 @@ URLS = {\n'set_video_rating': {'endpoint': '/setVideoRating', 'is_api_call': True},\n'update_my_list': {'endpoint': '/playlistop', 'is_api_call': True},\n# Don't know what these could be used for. Keeping for reference\n- # 'browse': {'endpoint': '/browse', 'is_api_call': False},\n# 'video_list_ids': {'endpoint': '/preflight', 'is_api_call': True},\n# 'kids': {'endpoint': '/Kids', 'is_api_call': False}\n}\n@@ -62,14 +63,11 @@ class NetflixSession(object):\nsession = None\n\"\"\"The requests.session object to handle communication to Netflix\"\"\"\n- session_data = None\n- \"\"\"The session data extracted from the Netflix webpage.\n- Contains profiles, user_data, esn and api_data\"\"\"\n-\nverify_ssl = bool(g.ADDON.getSettingBool('ssl_verification'))\n\"\"\"Use SSL verification when performing requests\"\"\"\ndef __init__(self):\n+ self._session_data = None\nself.slots = [\nself.login,\nself.logout,\n@@ -100,6 +98,23 @@ class NetflixSession(object):\n\"\"\"The unique hash of the current account\"\"\"\nreturn urlsafe_b64encode(self.credentials.get('email', 'NoMail'))\n+ @property\n+ def session_data(self):\n+ \"\"\"The session data extracted from the Netflix webpage.\n+ Contains profiles, active_profile, root_lolomo, user_data, esn\n+ and api_data\"\"\"\n+ return self._session_data\n+\n+ @session_data.setter\n+ def session_data(self, new_session_data):\n+ self._session_data = new_session_data\n+ self.session.headers.update(\n+ {'x-netflix.request.client.user.guid':\n+ new_session_data['active_profile']})\n+ cookies.save(self.account_hash, self.session.cookies)\n+ _update_esn(self.session_data['esn'])\n+ common.debug('Set session data: {}'.format(self._session_data))\n+\n@property\ndef auth_url(self):\n\"\"\"Valid authURL. Raises InvalidAuthURLError if it isn't known.\"\"\"\n@@ -115,7 +130,9 @@ class NetflixSession(object):\ncommon.info('Session closed')\nexcept AttributeError:\npass\n- self.session_data = {}\n+ # Do not use property setter for session_data because self.session may\n+ # be None at this point\n+ self._session_data = {}\nself.session = requests.session()\nself.session.headers.update({\n'User-Agent': common.get_user_agent(),\n@@ -137,11 +154,7 @@ class NetflixSession(object):\n\"\"\"Check if the user is logged in\"\"\"\nif not self.session.cookies:\ncommon.debug('Active session has no cookies, trying to restore...')\n- self._load_cookies()\n- if self._refresh_session_data():\n- _update_esn(self.session_data['esn'])\n- return True\n- return False\n+ return self._load_cookies() and self._refresh_session_data()\nreturn True\ndef _refresh_session_data(self):\n@@ -150,12 +163,12 @@ class NetflixSession(object):\ntry:\n# If we can get session data, cookies are still valid\nself.session_data = website.extract_session_data(\n- self._get('profiles'))\n+ self._get('browse'))\nexcept Exception:\n- import traceback\ncommon.debug(traceback.format_exc())\ncommon.info('Failed to refresh session data, login expired')\nreturn False\n+ common.debug('Successfully refreshed session data')\nreturn True\ndef _load_cookies(self):\n@@ -164,9 +177,11 @@ class NetflixSession(object):\nself.session.cookies = cookies.load(self.account_hash)\nexcept cookies.MissingCookiesError:\ncommon.info('No stored cookies available')\n+ return False\nexcept cookies.CookiesExpiredError:\n# Ignore this for now, because login is sometimes valid anyway\npass\n+ return True\[email protected]_return_call\ndef login(self):\n@@ -176,24 +191,19 @@ class NetflixSession(object):\ndef _login(self):\n\"\"\"Perform account login\"\"\"\ntry:\n- common.debug('Extracting authURL...')\nauth_url = website.extract_userdata(\n- self._get('profiles'))['authURL']\n+ self._get('browse'))['authURL']\ncommon.debug('Logging in...')\nlogin_response = self._post(\n'login', data=_login_payload(self.credentials, auth_url))\n- common.debug('Extracting session data...')\nsession_data = website.extract_session_data(login_response)\nexcept Exception:\n- import traceback\ncommon.error(traceback.format_exc())\nraise LoginFailedError\ncommon.info('Login successful')\n- ui.show_notification('Netflix', 'Login successful')\n+ ui.show_notification(common.get_local_string(30109))\nself.session_data = session_data\n- cookies.save(self.account_hash, self.session.cookies)\n- _update_esn(self.session_data['esn'])\[email protected]_return_call\ndef logout(self):\n@@ -217,6 +227,9 @@ class NetflixSession(object):\ndef activate_profile(self, guid):\n\"\"\"Set the profile identified by guid as active\"\"\"\ncommon.debug('Activating profile {}'.format(guid))\n+ if guid == self.session_data['active_profile']:\n+ common.debug('Profile {} is already active'.format(guid))\n+ return False\nself._get(\ncomponent='activate_profile',\nreq_type='api',\n@@ -226,6 +239,7 @@ class NetflixSession(object):\n'authURL': self.auth_url})\nself._refresh_session_data()\ncommon.debug('Successfully activated profile {}'.format(guid))\n+ return True\[email protected]_return_call\n@needs_login\n"
},
{
"change_type": "MODIFY",
"old_path": "service.py",
"new_path": "service.py",
"diff": "@@ -52,7 +52,7 @@ class NetflixService(object):\ncommon.info('[MSL] Thread started')\nself.controller = services.PlaybackController()\nself.library_updater = services.LibraryUpdateService()\n- ui.show_notification('Background services started')\n+ ui.show_notification(common.get_local_string(30110))\ndef shutdown(self):\n\"\"\"\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Improve profile switching and session setup |
105,989 | 03.11.2018 14:10:46 | -3,600 | 84408dac28a83867bde2ed31ab8b3514deb9fb64 | Improve fetching of root video lists. My List, continue watching and netflix originals are now always included. | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -47,17 +47,24 @@ def root_lists():\ncommon.debug('Requesting root lists from API')\nreturn LoLoMo(common.make_call(\n'path_request',\n- # TODO: Make sure that mylist is always retrieved\n- [['lolomo',\n- ['queue'],\n+ # By prepending this as first pathitem, we will trigger special\n+ # handling in nfsession, which will inject the ID of the root LoLoMo\n+ # extracted from falkorCache\n+ ['root_lolomo'] +\n+ # Make sure these 3 are always retrieved (even is not in top40 lists)\n+ [[['mylist', 'continueWatching', 'netflixOriginals'],\n['displayName', 'context', 'id', 'index', 'length', 'genreId']]] +\n- [['lolomo',\n- {'from': 0, 'to': 35},\n+ # Retrieve additional lists on start page\n+ [[{'from': 0, 'to': 40},\n['displayName', 'context', 'id', 'index', 'length', 'genreId']]] +\n- # Titles and art of first 4 videos in each video list\n- build_paths(['lolomo', {'from': 0, 'to': 35},\n- {'from': 0, 'to': 3}, 'reference'],\n- [['title']] + ART_PARTIAL_PATHS)))\n+ # Titles of first 4 videos in each video list\n+ [[{'from': 0, 'to': 40},\n+ {'from': 0, 'to': 3}, 'reference', 'title']] +\n+ # Art for first video in each video list\n+ # (will be displayed as video list art)\n+ build_paths([{'from': 0, 'to': 40},\n+ {'from': 0, 'to': 0}, 'reference'],\n+ ART_PARTIAL_PATHS)))\[email protected]_output(g, cache.CACHE_COMMON, identifying_param_index=0,\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -245,6 +245,7 @@ class NetflixSession(object):\n@needs_login\ndef path_request(self, paths):\n\"\"\"Perform a path request against the Shakti API\"\"\"\n+ paths = _inject_root_lolomo(paths, self.session_data['root_lolomo'])\ncommon.debug('Executing path request: {}'.format(json.dumps(paths)))\nheaders = {\n'Content-Type': 'application/json',\n@@ -320,6 +321,20 @@ class NetflixSession(object):\nelse response.content)\n+def _inject_root_lolomo(paths, root_lolomo):\n+ \"\"\"Apply special handling for path requests that query the root lists\n+ (displayed on homepage): If first pathitem == 'root_lolomo' (will be\n+ supplied by shakti api client), we prepend ['lolomos', root_lolomo] to\n+ all paths, where root_lolomo is the ID of the root LoLoMo as extracted\n+ from falkorCache.\n+ If the first pathitem is not the 'root_lolomo' indicator, we just return\n+ the untouched paths\"\"\"\n+ if paths[0] != 'root_lolomo':\n+ return paths\n+ return [['lolomos', root_lolomo] + path\n+ for path in paths[1:]]\n+\n+\ndef _login_payload(credentials, auth_url):\nreturn {\n'userLoginId': credentials['email'],\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Improve fetching of root video lists. My List, continue watching and netflix originals are now always included. |
105,989 | 03.11.2018 15:18:51 | -3,600 | 25cc155f05495cef5af51a700b12a962c90902de | Add fetching of lists with more than 40 items by fetching them in parts and merging the responses | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -87,9 +87,11 @@ def video_list(list_id):\n\"\"\"Retrieve a single video list\"\"\"\ncommon.debug('Requesting video list {}'.format(list_id))\nreturn VideoList(common.make_call(\n- 'path_request',\n- [['lists', [list_id], ['displayName', 'context', 'genreId']]] +\n- build_paths(['lists', [list_id], {'from': 0, 'to': 40}, 'reference'],\n+ 'perpetual_path_request',\n+ # The length attribute MUST be present with perpetual_path_request!\n+ [['lists', [list_id],\n+ ['displayName', 'context', 'genreId', 'length']]] +\n+ build_paths(['lists', [list_id], 'RANGE_SELECTOR', 'reference'],\nVIDEO_LIST_PARTIAL_PATHS)))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/misc_utils.py",
"new_path": "resources/lib/common/misc_utils.py",
"diff": "@@ -192,3 +192,16 @@ def compress_data(data):\nwith gzip.GzipFile(fileobj=out, mode='w') as outh:\nouth.write(data)\nreturn base64.standard_b64encode(out.getvalue())\n+\n+\n+def merge_dicts(dict_to_merge, merged_dict):\n+ \"\"\"Recursively merge the contents of dict_to_merge into merged_dict.\n+ Values that are already present in merged_dict will not be overwritten\n+ if they are also present in dict_to_merge\"\"\"\n+ for key, value in dict_to_merge.iteritems():\n+ if key in merged_dict:\n+ if isinstance(merged_dict[key], dict):\n+ merge_dicts(value, merged_dict[key])\n+ else:\n+ merged_dict[key] = value\n+ return merged_dict\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -34,6 +34,9 @@ URLS = {\n}\n\"\"\"List of all static endpoints for HTML/JSON POST/GET requests\"\"\"\n+MAX_PATH_REQUEST_SIZE = 40\n+\"\"\"How many entries of a list will be fetched with one path request\"\"\"\n+\ndef needs_login(func):\n\"\"\"\n@@ -74,6 +77,7 @@ class NetflixSession(object):\nself.list_profiles,\nself.activate_profile,\nself.path_request,\n+ self.perpetual_path_request,\nself.get,\nself.post\n]\n@@ -245,7 +249,31 @@ class NetflixSession(object):\n@needs_login\ndef path_request(self, paths):\n\"\"\"Perform a path request against the Shakti API\"\"\"\n- paths = _inject_root_lolomo(paths, self.session_data['root_lolomo'])\n+ return self._path_request(\n+ _inject_root_lolomo(paths, self.session_data['root_lolomo']))\n+\n+ @common.addonsignals_return_call\n+ @needs_login\n+ def perpetual_path_request(self, paths):\n+ \"\"\"Perform a perpetual path request against the Shakti API to retrieve\n+ a possibly large video list. If the requested video list's size is\n+ larger than MAX_PATH_REQUEST_SIZE, multiple path requests will be\n+ executed with forward shifting range selectors and the results will\n+ be combined into one path response.\"\"\"\n+ range_start = 0\n+ range_end = MAX_PATH_REQUEST_SIZE\n+ merged_response = {}\n+ while range_start < range_end:\n+ path_response = self._path_request(\n+ _set_range_selector(paths, range_start, range_end))\n+ common.merge_dicts(path_response, merged_response)\n+ range_start = range_end + 1\n+ if path_response['lists'].values()[0]['length'] > range_end:\n+ range_end += MAX_PATH_REQUEST_SIZE\n+ return merged_response\n+\n+ def _path_request(self, paths):\n+ \"\"\"Execute a path request with static paths\"\"\"\ncommon.debug('Executing path request: {}'.format(json.dumps(paths)))\nheaders = {\n'Content-Type': 'application/json',\n@@ -335,6 +363,16 @@ def _inject_root_lolomo(paths, root_lolomo):\nfor path in paths[1:]]\n+def _set_range_selector(paths, range_start, range_end):\n+ import copy\n+ ranged_paths = copy.deepcopy(paths)\n+ for path in ranged_paths:\n+ for i in range(0, len(path) - 1):\n+ if path[i] == 'RANGE_SELECTOR':\n+ path[i] = {'from': range_start, 'to': range_end}\n+ return ranged_paths\n+\n+\ndef _login_payload(credentials, auth_url):\nreturn {\n'userLoginId': credentials['email'],\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add fetching of lists with more than 40 items by fetching them in parts and merging the responses |
105,989 | 03.11.2018 18:22:00 | -3,600 | 98b8897db8911d465c7d0fa175bb2462bb9fbed0 | Expand fetching of lists with more than 40 entries to seasons and episodes | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/paths.py",
"new_path": "resources/lib/api/paths.py",
"diff": "@@ -4,10 +4,22 @@ from __future__ import unicode_literals\nimport resources.lib.common as common\n+RANGE_SELECTOR = 'RANGE_SELECTOR'\n+\nART_SIZE_POSTER = '_342x684'\nART_SIZE_FHD = '_1920x1080'\nART_SIZE_SD = '_665x375'\n+LENGTH_ATTRIBUTES = {\n+ 'videolist': lambda r: r['lists'].values()[0]['length'],\n+ 'seasonlist': (lambda r, tvshowid:\n+ r['videos'][tvshowid]['seasonList']\n+ ['summary']['length']),\n+ 'episodelist': (lambda r, seasonid:\n+ r['seasons'][seasonid]['summary']['length'])}\n+\"\"\"Predefined lambda expressions that return the value of the length\n+attribute from within a path response dict\"\"\"\n+\nART_PARTIAL_PATHS = [\n['boxarts', [ART_SIZE_SD, ART_SIZE_FHD, ART_SIZE_POSTER], 'jpg'],\n['interestingMoment', [ART_SIZE_SD, ART_SIZE_FHD], 'jpg'],\n@@ -33,7 +45,8 @@ GENRE_PARTIAL_PATHS = [\n]\nSEASONS_PARTIAL_PATHS = [\n- ['seasonList', {'from': 0, 'to': 40}, 'summary'],\n+ ['seasonList', 'summary'],\n+ ['seasonList', RANGE_SELECTOR, 'summary'],\n['title']\n] + ART_PARTIAL_PATHS\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -10,7 +10,7 @@ from .data_types import (LoLoMo, VideoList, SeasonList, EpisodeList,\nSearchVideoList, CustomVideoList)\nfrom .paths import (VIDEO_LIST_PARTIAL_PATHS, SEASONS_PARTIAL_PATHS,\nEPISODES_PARTIAL_PATHS, ART_PARTIAL_PATHS,\n- GENRE_PARTIAL_PATHS)\n+ GENRE_PARTIAL_PATHS, RANGE_SELECTOR)\nclass InvalidVideoListTypeError(Exception):\n@@ -88,11 +88,15 @@ def video_list(list_id):\ncommon.debug('Requesting video list {}'.format(list_id))\nreturn VideoList(common.make_call(\n'perpetual_path_request',\n- # The length attribute MUST be present with perpetual_path_request!\n+ {\n+ 'path_type': 'videolist',\n+ 'paths':\n[['lists', [list_id],\n+ # The length attribute MUST be present!\n['displayName', 'context', 'genreId', 'length']]] +\n- build_paths(['lists', [list_id], 'RANGE_SELECTOR', 'reference'],\n- VIDEO_LIST_PARTIAL_PATHS)))\n+ build_paths(['lists', [list_id], RANGE_SELECTOR, 'reference'],\n+ VIDEO_LIST_PARTIAL_PATHS)\n+ }))\ndef custom_video_list(video_ids):\n@@ -133,9 +137,13 @@ def seasons(videoid):\nreturn SeasonList(\nvideoid,\ncommon.make_call(\n- 'path_request',\n- build_paths(['videos', videoid.tvshowid],\n- SEASONS_PARTIAL_PATHS)))\n+ 'perpetual_path_request',\n+ {\n+ 'path_type': 'seasonlist',\n+ 'length_params': [videoid.tvshowid],\n+ 'paths': build_paths(['videos', videoid.tvshowid],\n+ SEASONS_PARTIAL_PATHS)\n+ }))\[email protected]_output(g, cache.CACHE_COMMON)\n@@ -148,14 +156,18 @@ def episodes(videoid):\nreturn EpisodeList(\nvideoid,\ncommon.make_call(\n- 'path_request',\n- [['seasons', videoid.seasonid, 'summary']] +\n+ 'perpetual_path_request',\n+ {\n+ 'path_type': 'episodelist',\n+ 'length_params': [videoid.seasonid],\n+ 'paths': [['seasons', videoid.seasonid, 'summary']] +\nbuild_paths(['seasons', videoid.seasonid, 'episodes',\n- {'from': 0, 'to': 40}],\n+ RANGE_SELECTOR],\nEPISODES_PARTIAL_PATHS) +\nbuild_paths(['videos', videoid.tvshowid],\nART_PARTIAL_PATHS +\n- [['title']])))\n+ [['title']])\n+ }))\[email protected]_output(g, cache.CACHE_COMMON)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -12,6 +12,7 @@ import requests\nfrom resources.lib.globals import g\nimport resources.lib.common as common\nimport resources.lib.api.website as website\n+import resources.lib.api.paths as apipaths\nimport resources.lib.services.cookies as cookies\nimport resources.lib.kodi.ui as ui\n@@ -254,12 +255,14 @@ class NetflixSession(object):\[email protected]_return_call\n@needs_login\n- def perpetual_path_request(self, paths):\n+ def perpetual_path_request(self, paths, path_type, length_params=None):\n\"\"\"Perform a perpetual path request against the Shakti API to retrieve\na possibly large video list. If the requested video list's size is\nlarger than MAX_PATH_REQUEST_SIZE, multiple path requests will be\nexecuted with forward shifting range selectors and the results will\nbe combined into one path response.\"\"\"\n+ length_params = length_params or []\n+ length = apipaths.LENGTH_ATTRIBUTES[path_type]\nrange_start = 0\nrange_end = MAX_PATH_REQUEST_SIZE\nmerged_response = {}\n@@ -268,7 +271,9 @@ class NetflixSession(object):\n_set_range_selector(paths, range_start, range_end))\ncommon.merge_dicts(path_response, merged_response)\nrange_start = range_end + 1\n- if path_response['lists'].values()[0]['length'] > range_end:\n+ if length(path_response, *length_params) > range_end:\n+ common.debug('{} has more items, doing another path request'\n+ .format(path_type))\nrange_end += MAX_PATH_REQUEST_SIZE\nreturn merged_response\n@@ -364,11 +369,15 @@ def _inject_root_lolomo(paths, root_lolomo):\ndef _set_range_selector(paths, range_start, range_end):\n+ \"\"\"Replace the RANGE_SELECTOR placeholder with an actual dict:\n+ {'from': range_start, 'to': range_end}\"\"\"\nimport copy\n+ # Make a deepcopy because we don't want to lose the original paths\n+ # with the placeholder\nranged_paths = copy.deepcopy(paths)\nfor path in ranged_paths:\nfor i in range(0, len(path) - 1):\n- if path[i] == 'RANGE_SELECTOR':\n+ if path[i] == apipaths.RANGE_SELECTOR:\npath[i] = {'from': range_start, 'to': range_end}\nreturn ranged_paths\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Expand fetching of lists with more than 40 entries to seasons and episodes |
105,989 | 03.11.2018 18:30:34 | -3,600 | a949e25eba962693c9d2a091a29b46c9b783fa1d | Add dolby atmos support | [
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.de_de/strings.po",
"new_path": "resources/language/resource.language.de_de/strings.po",
"diff": "@@ -455,3 +455,7 @@ msgstr \"Login erfolgreich\"\nmsgctxt \"#30110\"\nmsgid \"Background services started\"\nmsgstr \"Hintergrunddienste gestartet\"\n+\n+msgctxt \"#30111\"\n+msgid \"Enable Dolby Atmos\"\n+msgstr \"Aktiviere Dolby Atmos\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -463,3 +463,7 @@ msgstr \"\"\nmsgctxt \"#30110\"\nmsgid \"Background services started\"\nmsgstr \"\"\n+\n+msgctxt \"#30111\"\n+msgid \"Enable Dolby Atmos\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/profiles.py",
"new_path": "resources/lib/services/msl/profiles.py",
"diff": "@@ -39,6 +39,7 @@ PROFILES = {\n# Unkown\n'BIF240', 'BIF320'],\n'dolbysound': ['ddplus-2.0-dash', 'ddplus-5.1-dash'],\n+ 'atmos': ['ddplus-atmos-dash'],\n'hevc':\n_profile_strings(base=HEVC,\ntails=[(BASE_LEVELS, CENC),\n@@ -65,6 +66,7 @@ def enabled_profiles():\nreturn (PROFILES['base'] +\n_subtitle_profiles() +\n_additional_profiles('dolbysound', 'enable_dolby_sound') +\n+ _additional_profiles('atmos', 'enable_atmos_sound') +\n_additional_profiles('hevc', 'enable_hevc_profiles') +\n_additional_profiles('hdr',\n['enable_hevc_profiles',\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/settings.xml",
"new_path": "resources/settings.xml",
"diff": "</category>\n<category label=\"30023\">\n<setting id=\"enable_dolby_sound\" type=\"bool\" label=\"30033\" default=\"true\"/>\n+ <setting id=\"enable_atmos_sound\" type=\"bool\" label=\"30111\" default=\"true\"/>\n<setting id=\"enable_hevc_profiles\" type=\"bool\" label=\"30060\" default=\"false\"/>\n<setting id=\"enable_hdr_profiles\" type=\"bool\" label=\"30098\" default=\"false\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n<setting id=\"enable_dolbyvision_profiles\" type=\"bool\" label=\"30099\" default=\"false\" visible=\"eq(-2,true)\" subsetting=\"true\"/>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add dolby atmos support |
105,989 | 03.11.2018 22:50:54 | -3,600 | 637ed8b62fcf4a047e9860c497b388d309915691 | Refactor & cleanup code | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "@@ -60,10 +60,7 @@ if __name__ == '__main__':\nexcept Exception as exc:\nimport traceback\ncommon.error(traceback.format_exc())\n- ui.show_error_info(title=common.get_local_string(30105),\n- message=': '.join((exc.__class__.__name__,\n- exc.message)),\n- netflix_error=False)\n+ ui.show_addon_error_info(exc)\nxbmcplugin.endOfDirectory(handle=g.PLUGIN_HANDLE, succeeded=False)\ng.CACHE.commit()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -160,13 +160,15 @@ def episodes(videoid):\n{\n'path_type': 'episodelist',\n'length_params': [videoid.seasonid],\n- 'paths': [['seasons', videoid.seasonid, 'summary']] +\n- build_paths(['seasons', videoid.seasonid, 'episodes',\n+ 'paths':\n+ [['seasons', videoid.seasonid, 'summary']] +\n+ build_paths(\n+ ['seasons', videoid.seasonid, 'episodes',\nRANGE_SELECTOR],\nEPISODES_PARTIAL_PATHS) +\n- build_paths(['videos', videoid.tvshowid],\n- ART_PARTIAL_PATHS +\n- [['title']])\n+ build_paths(\n+ ['videos', videoid.tvshowid],\n+ ART_PARTIAL_PATHS + [['title']])\n}))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -63,16 +63,15 @@ def cache_output(g, bucket, identifying_param_index=0,\nkwargs,\nidentifying_param_index,\nargs)\n- cached_result = g.CACHE.get(bucket, identifier)\n- return cached_result\n+ return g.CACHE.get(bucket, identifier)\n+ except IndexError:\n+ # Do not cache if identifier couldn't be determined\n+ return func(*args, **kwargs)\nexcept CacheMiss:\noutput = func(*args, **kwargs)\ng.CACHE.add(bucket, identifier, output, ttl=ttl,\nto_disk=to_disk)\nreturn output\n- except IndexError:\n- # Do not cache if identifier couldn't be determined\n- return func(*args, **kwargs)\nreturn wrapper\nreturn caching_decorator\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/misc_utils.py",
"new_path": "resources/lib/common/misc_utils.py",
"diff": "@@ -199,8 +199,7 @@ def merge_dicts(dict_to_merge, merged_dict):\nValues that are already present in merged_dict will not be overwritten\nif they are also present in dict_to_merge\"\"\"\nfor key, value in dict_to_merge.iteritems():\n- if key in merged_dict:\n- if isinstance(merged_dict[key], dict):\n+ if isinstance(merged_dict.get(key), dict):\nmerge_dicts(value, merged_dict[key])\nelse:\nmerged_dict[key] = value\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/globals.py",
"new_path": "resources/lib/globals.py",
"diff": "@@ -87,20 +87,23 @@ class GlobalVariables(object):\ndef _init_cache(self):\nif not os.path.exists(os.path.join(self.DATA_PATH, 'cache')):\n+ self._init_filesystem_cache()\n+ # This is ugly: Pass the common module into Cache.__init__ to work\n+ # around circular import dependencies.\n+ import resources.lib.common as common\n+ self.CACHE = cache.Cache(common, self.DATA_PATH, self.CACHE_TTL,\n+ self.CACHE_METADATA_TTL, self.PLUGIN_HANDLE)\n+\n+ def _init_filesystem_cache(self):\nfor bucket in cache.BUCKET_NAMES:\nif bucket == cache.CACHE_LIBRARY:\n# Library gets special location in DATA_PATH root because\n# we don't want users accidentally deleting it.\ncontinue\ntry:\n- os.makedirs(os.path.join(g.DATA_PATH, 'cache', bucket))\n+ os.makedirs(os.path.join(self.DATA_PATH, 'cache', bucket))\nexcept OSError:\npass\n- # This is ugly: Pass the common module into Cache.__init__ to work\n- # around circular import dependencies.\n- import resources.lib.common as common\n- self.CACHE = cache.Cache(common, self.DATA_PATH, self.CACHE_TTL,\n- self.CACHE_METADATA_TTL, self.PLUGIN_HANDLE)\ndef library(self):\n\"\"\"Get the current library instance\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/ui/dialogs.py",
"new_path": "resources/lib/kodi/ui/dialogs.py",
"diff": "@@ -85,3 +85,10 @@ def show_error_info(title, message, unknown_error=False, netflix_error=False):\nline1=common.get_local_string(prefix),\nline2=message,\nline3=common.get_local_string(30103))\n+\n+def show_addon_error_info(exc):\n+ \"\"\"Show a dialog to notify of an addon internal error\"\"\"\n+ show_error_info(title=common.get_local_string(30105),\n+ message=': '.join((exc.__class__.__name__,\n+ exc.message)),\n+ netflix_error=False)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -376,9 +376,11 @@ def _set_range_selector(paths, range_start, range_end):\n# with the placeholder\nranged_paths = copy.deepcopy(paths)\nfor path in ranged_paths:\n- for i in range(0, len(path) - 1):\n- if path[i] == apipaths.RANGE_SELECTOR:\n- path[i] = {'from': range_start, 'to': range_end}\n+ try:\n+ path[path.index(apipaths.RANGE_SELECTOR)] = (\n+ {'from': range_start, 'to': range_end})\n+ except ValueError:\n+ pass\nreturn ranged_paths\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/playback/controller.py",
"new_path": "resources/lib/services/playback/controller.py",
"diff": "@@ -90,17 +90,7 @@ class PlaybackController(xbmc.Monitor):\ncommon.debug('Notifying all managers of {} (data={})'\n.format(notification.__name__, data))\nfor manager in self.action_managers:\n- notify_method = getattr(manager, notification.__name__)\n- try:\n- if data is not None:\n- notify_method(data)\n- else:\n- notify_method()\n- except Exception as exc:\n- common.error('{} disabled due to exception: {}'\n- .format(manager.name, exc))\n- manager.enabled = False\n- raise\n+ _notify_managers(manager, notification, data)\ndef _get_player_state(self):\ntry:\n@@ -125,3 +115,17 @@ class PlaybackController(xbmc.Monitor):\nplayer_state['time']['seconds'])\nreturn player_state\n+\n+\n+def _notify_managers(manager, notification, data):\n+ notify_method = getattr(manager, notification.__name__)\n+ try:\n+ if data is not None:\n+ notify_method(data)\n+ else:\n+ notify_method()\n+ except Exception as exc:\n+ common.error('{} disabled due to exception: {}'\n+ .format(manager.name, exc))\n+ manager.enabled = False\n+ raise\n"
},
{
"change_type": "MODIFY",
"old_path": "service.py",
"new_path": "service.py",
"diff": "@@ -72,10 +72,7 @@ class NetflixService(object):\ntry:\nself.start_services()\nexcept Exception as exc:\n- ui.show_error_info(\n- title=common.get_local_string(30105),\n- message=': '.join((exc.__class__.__name__, exc.message)),\n- netflix_error=False)\n+ ui.show_addon_error_info(exc)\nreturn\nplayer = xbmc.Player()\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Refactor & cleanup code |
105,989 | 03.11.2018 23:54:34 | -3,600 | ea4b027723c18799ae76357c7846d3f7846ee996 | Pull checking for login into client/frontend processes. Fix edge cases for login failures | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "from __future__ import unicode_literals\nimport sys\n+from functools import wraps\n+\nimport xbmcplugin\n# Import and intiliaze globals right away to avoid stale values from the last\n@@ -17,6 +19,7 @@ from resources.lib.globals import g\ng.init_globals(sys.argv)\nimport resources.lib.common as common\n+import resources.lib.api.shakti as api\nimport resources.lib.kodi.ui as ui\nimport resources.lib.navigation as nav\nimport resources.lib.navigation.directory as directory\n@@ -25,6 +28,8 @@ import resources.lib.navigation.player as player\nimport resources.lib.navigation.actions as actions\nimport resources.lib.navigation.library as library\n+from resources.lib.api.exceptions import NotLoggedInError\n+\nNAV_HANDLERS = {\ng.MODE_DIRECTORY: directory.DirectoryBuilder,\ng.MODE_ACTION: actions.AddonActionExecutor,\n@@ -33,6 +38,28 @@ NAV_HANDLERS = {\n}\n+def lazy_login(func):\n+ \"\"\"\n+ Decorator to ensure that a valid login is present when calling a method\n+ \"\"\"\n+ # pylint: disable=protected-access, missing-docstring\n+ @wraps(func)\n+ def lazy_login_wrapper(*args, **kwargs):\n+ try:\n+ return func(*args, **kwargs)\n+ except NotLoggedInError:\n+ common.debug('Tried to perform an action without being logged in')\n+ if api.login():\n+ common.debug('Now that we\\'re logged in, let\\'s try again')\n+ return func(*args, **kwargs)\n+ else:\n+ common.debug('Login failed or canceled, abort initial action')\n+ xbmcplugin.endOfDirectory(handle=g.PLUGIN_HANDLE,\n+ succeeded=False)\n+ return lazy_login_wrapper\n+\n+\n+@lazy_login\ndef route(pathitems):\n\"\"\"Route to the appropriate handler\"\"\"\ncommon.debug('Routing navigation request')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.de_de/strings.po",
"new_path": "resources/language/resource.language.de_de/strings.po",
"diff": "@@ -459,3 +459,11 @@ msgstr \"Hintergrunddienste gestartet\"\nmsgctxt \"#30111\"\nmsgid \"Enable Dolby Atmos\"\nmsgstr \"Aktiviere Dolby Atmos\"\n+\n+msgctxt \"#30112\"\n+msgid \"You need to be logged in to use this function\"\n+msgstr \"Du musst eingeloggt sein um diese Funktion zu benutzen\"\n+\n+msgctxt \"#30113\"\n+msgid \"Logout successful\"\n+msgstr \"Logout erfolgreich\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -467,3 +467,11 @@ msgstr \"\"\nmsgctxt \"#30111\"\nmsgid \"Enable Dolby Atmos\"\nmsgstr \"\"\n+\n+msgctxt \"#30112\"\n+msgid \"You need to be logged in to use this function\"\n+msgstr \"\"\n+\n+msgctxt \"#30113\"\n+msgid \"Logout successful\"\n+msgstr \"\"\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "resources/lib/api/exceptions.py",
"diff": "+# -*- coding: utf-8 -*-\n+\"\"\"Common exception types for API operations\"\"\"\n+from __future__ import unicode_literals\n+\n+\n+class InvalidReferenceError(Exception):\n+ \"\"\"The provided reference cannot be dealt with as it is in an\n+ unexpected format\"\"\"\n+ pass\n+\n+\n+class InvalidVideoListTypeError(Exception):\n+ \"\"\"No video list of a given was available\"\"\"\n+ pass\n+\n+\n+class WebsiteParsingError(Exception):\n+ \"\"\"Parsing info from the Netflix Website failed\"\"\"\n+ pass\n+\n+\n+class InvalidAuthURLError(WebsiteParsingError):\n+ \"\"\"The authURL is invalid\"\"\"\n+ pass\n+\n+\n+class InvalidProfilesError(WebsiteParsingError):\n+ \"\"\"Cannot extract profiles from Netflix webpage\"\"\"\n+ pass\n+\n+\n+class InvalidMembershipStatusError(WebsiteParsingError):\n+ \"\"\"The user logging in does not have a valid subscription\"\"\"\n+ pass\n+\n+\n+class LoginFailedError(Exception):\n+ \"\"\"The login attempt has failed\"\"\"\n+ pass\n+\n+\n+class NotLoggedInError(Exception):\n+ \"\"\"The requested operation requires a valid and active login, which\n+ is not present\"\"\"\n+ pass\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/paths.py",
"new_path": "resources/lib/api/paths.py",
"diff": "@@ -4,6 +4,8 @@ from __future__ import unicode_literals\nimport resources.lib.common as common\n+from .exceptions import InvalidReferenceError\n+\nRANGE_SELECTOR = 'RANGE_SELECTOR'\nART_SIZE_POSTER = '_342x684'\n@@ -85,12 +87,6 @@ REFERENCE_MAPPINGS = {\n}\n-class InvalidReferenceError(Exception):\n- \"\"\"The provided reference cannot be dealt with as it is in an\n- unexpected format\"\"\"\n- pass\n-\n-\ndef resolve_refs(references, targets):\n\"\"\"Return a generator expression that returns the objects in targets\nby resolving the references in sorted order\"\"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "\"\"\"Access to Netflix's Shakti API\"\"\"\nfrom __future__ import unicode_literals\n+from functools import wraps\n+\nfrom resources.lib.globals import g\nimport resources.lib.common as common\nimport resources.lib.cache as cache\n+import resources.lib.kodi.ui as ui\nfrom .data_types import (LoLoMo, VideoList, SeasonList, EpisodeList,\nSearchVideoList, CustomVideoList)\nfrom .paths import (VIDEO_LIST_PARTIAL_PATHS, SEASONS_PARTIAL_PATHS,\nEPISODES_PARTIAL_PATHS, ART_PARTIAL_PATHS,\nGENRE_PARTIAL_PATHS, RANGE_SELECTOR)\n-\n-\n-class InvalidVideoListTypeError(Exception):\n- \"\"\"No video list of a given was available\"\"\"\n- pass\n+from .exceptions import InvalidVideoListTypeError, LoginFailedError\ndef activate_profile(profile_id):\n@@ -28,12 +27,24 @@ def logout():\n\"\"\"Logout of the current account\"\"\"\ng.CACHE.invalidate()\ncommon.make_call('logout')\n+ common.purge_credentials()\ndef login():\n\"\"\"Perform a login\"\"\"\ng.CACHE.invalidate()\n+ try:\n+ ui.ask_credentials()\n+ except common.MissingCredentialsError:\n+ ui.show_notification(common.get_local_string(30112))\n+ return False\n+ try:\ncommon.make_call('login')\n+ except LoginFailedError:\n+ ui.show_notification(common.get_local_string(30009))\n+ common.purge_credentials()\n+ return False\n+ return True\ndef profiles():\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/website.py",
"new_path": "resources/lib/api/website.py",
"diff": "@@ -8,6 +8,9 @@ from re import compile as recompile, DOTALL\nimport resources.lib.common as common\n+from .exceptions import (InvalidProfilesError, InvalidAuthURLError,\n+ InvalidMembershipStatusError, WebsiteParsingError)\n+\nPAGE_ITEMS = [\n'gpsModel',\n'models/userInfo/data/authURL',\n@@ -25,26 +28,6 @@ JSON_REGEX = r'netflix\\.%s\\s*=\\s*(.*?);\\s*</script>'\nAVATAR_SUBPATH = ['images', 'byWidth', '320', 'value']\n-class WebsiteParsingError(Exception):\n- \"\"\"Parsing info from the Netflix Website failed\"\"\"\n- pass\n-\n-\n-class InvalidAuthURLError(WebsiteParsingError):\n- \"\"\"The authURL is invalid\"\"\"\n- pass\n-\n-\n-class InvalidProfilesError(WebsiteParsingError):\n- \"\"\"Cannot extract profiles from Netflix webpage\"\"\"\n- pass\n-\n-\n-class InvalidMembershipStatusError(WebsiteParsingError):\n- \"\"\"The user logging in does not have a valid subscription\"\"\"\n- pass\n-\n-\ndef extract_session_data(content):\n\"\"\"\nCall all the parsers we need to extract all\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/credentials.py",
"new_path": "resources/lib/common/credentials.py",
"diff": "@@ -83,7 +83,7 @@ def get_credentials():\n\"\"\"\nemail = g.ADDON.getSetting('email')\npassword = g.ADDON.getSetting('password')\n- verify_credentials(email, password)\n+ verify_credentials(email and password)\ntry:\nreturn {\n'email': decrypt_credential(email),\n@@ -104,7 +104,13 @@ def set_credentials(email, password):\ng.ADDON.setSetting('password', encrypt_credential(password))\n-def verify_credentials(email, password):\n+def purge_credentials():\n+ \"\"\"Delete the stored credentials\"\"\"\n+ g.ADDON.setSetting('email', '')\n+ g.ADDON.setSetting('password', '')\n+\n+\n+def verify_credentials(credential):\n\"\"\"Verify credentials for plausibility\"\"\"\n- if not email or not password:\n+ if not credential:\nraise MissingCredentialsError()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/ipc.py",
"new_path": "resources/lib/common/ipc.py",
"diff": "@@ -9,6 +9,8 @@ from time import time\nimport AddonSignals\nfrom resources.lib.globals import g\n+import resources.lib.api.exceptions as apierrors\n+\nfrom .logging import debug, error\n@@ -61,7 +63,10 @@ def make_call(callname, data=None):\nmsg = ('AddonSignals call {callname} returned {error}: {message}'\n.format(callname=callname, **result))\nerror(msg)\n- raise Exception(msg)\n+ try:\n+ raise apierrors.__dict__[result['error']]\n+ except KeyError:\n+ raise Exception(result['error'])\nelif result is None:\nraise Exception('AddonSignals call timed out')\nreturn result\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/ui/dialogs.py",
"new_path": "resources/lib/kodi/ui/dialogs.py",
"diff": "@@ -24,11 +24,12 @@ def ask_credentials():\nemail = xbmcgui.Dialog().input(\nheading=common.get_local_string(30005),\ntype=xbmcgui.INPUT_ALPHANUM) or None\n+ common.verify_credentials(email)\npassword = xbmcgui.Dialog().input(\nheading=common.get_local_string(30004),\ntype=xbmcgui.INPUT_ALPHANUM,\noption=xbmcgui.ALPHANUM_HIDE_INPUT) or None\n- common.verify_credentials(email, password)\n+ common.verify_credentials(password)\ncommon.set_credentials(email, password)\nreturn {\n'email': email,\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -16,6 +16,8 @@ import resources.lib.api.paths as apipaths\nimport resources.lib.services.cookies as cookies\nimport resources.lib.kodi.ui as ui\n+from resources.lib.api.exceptions import NotLoggedInError, LoginFailedError\n+\nBASE_URL = 'https://www.netflix.com'\n\"\"\"str: Secure Netflix url\"\"\"\n@@ -48,16 +50,11 @@ def needs_login(func):\ndef ensure_login(*args, **kwargs):\nsession = args[0]\nif not session._is_logged_in():\n- session._login()\n+ raise NotLoggedInError\nreturn func(*args, **kwargs)\nreturn ensure_login\n-class LoginFailedError(Exception):\n- \"\"\"The login attempt has failed\"\"\"\n- pass\n-\n-\nclass NetflixSession(object):\n\"\"\"Stateful netflix session management\"\"\"\n@@ -87,21 +84,11 @@ class NetflixSession(object):\nself._init_session()\nself._prefetch_login()\n- @property\n- def credentials(self):\n- \"\"\"\n- The stored credentials.\n- Will ask for credentials if there are none in store\n- \"\"\"\n- try:\n- return common.get_credentials()\n- except common.MissingCredentialsError:\n- return ui.ask_credentials()\n-\n@property\ndef account_hash(self):\n\"\"\"The unique hash of the current account\"\"\"\n- return urlsafe_b64encode(self.credentials.get('email', 'NoMail'))\n+ return urlsafe_b64encode(\n+ common.get_credentials().get('email', 'NoMail'))\n@property\ndef session_data(self):\n@@ -154,6 +141,8 @@ class NetflixSession(object):\nself._login()\nexcept common.MissingCredentialsError:\ncommon.info('Login prefetch: No stored credentials are available')\n+ except LoginFailedError:\n+ ui.show_notification(common.get_local_string(30009))\ndef _is_logged_in(self):\n\"\"\"Check if the user is logged in\"\"\"\n@@ -172,6 +161,7 @@ class NetflixSession(object):\nexcept Exception:\ncommon.debug(traceback.format_exc())\ncommon.info('Failed to refresh session data, login expired')\n+ self.session.cookies.clear()\nreturn False\ncommon.debug('Successfully refreshed session data')\nreturn True\n@@ -180,6 +170,10 @@ class NetflixSession(object):\n\"\"\"Load stored cookies from disk\"\"\"\ntry:\nself.session.cookies = cookies.load(self.account_hash)\n+ except common.MissingCredentialsError:\n+ common.debug(\n+ 'No stored credentials available, cannot identify account')\n+ return False\nexcept cookies.MissingCookiesError:\ncommon.info('No stored cookies available')\nreturn False\n@@ -200,10 +194,12 @@ class NetflixSession(object):\nself._get('browse'))['authURL']\ncommon.debug('Logging in...')\nlogin_response = self._post(\n- 'login', data=_login_payload(self.credentials, auth_url))\n+ 'login',\n+ data=_login_payload(common.get_credentials(), auth_url))\nsession_data = website.extract_session_data(login_response)\nexcept Exception:\ncommon.error(traceback.format_exc())\n+ self.session.cookies.clear()\nraise LoginFailedError\ncommon.info('Login successful')\n@@ -216,6 +212,8 @@ class NetflixSession(object):\ncommon.debug('Logging out of current account')\nself._get('logout')\ncookies.delete(self.account_hash)\n+ common.info('Logout successful')\n+ ui.show_notification(common.get_local_string(30109))\nself._init_session()\[email protected]_return_call\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Pull checking for login into client/frontend processes. Fix edge cases for login failures |
105,989 | 04.11.2018 00:04:28 | -3,600 | 23cf3cd2ca3c44bb875f3a34d8f7f63ac0e15b88 | Move in-memory cookie storage to GlobalVariables. Add handler for unexpected cookie loading errors (e.g. old storage format) | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/globals.py",
"new_path": "resources/lib/globals.py",
"diff": "@@ -52,6 +52,7 @@ class GlobalVariables(object):\nThis is an ugly hack because Kodi doesn't execute statements defined on\nmodule level if reusing a language invoker.\"\"\"\nself._library = None\n+ self.COOKIES = {}\nself.ADDON = xbmcaddon.Addon()\nself.ADDON_ID = self.ADDON.getAddonInfo('id')\nself.PLUGIN = self.ADDON.getAddonInfo('name')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/cookies.py",
"new_path": "resources/lib/services/cookies.py",
"diff": "@@ -12,9 +12,6 @@ except ImportError:\nfrom resources.lib.globals import g\nimport resources.lib.common as common\n-COOKIES = {}\n-\"\"\"In-memory storage for account cookies\"\"\"\n-\nclass MissingCookiesError(Exception):\n\"\"\"No session cookies have been stored\"\"\"\n@@ -29,7 +26,7 @@ class CookiesExpiredError(Exception):\ndef save(account_hash, cookie_jar):\n\"\"\"Save a cookie jar to file and in-memory storage\"\"\"\n# pylint: disable=broad-except\n- COOKIES[account_hash] = cookie_jar\n+ g.COOKIES[account_hash] = cookie_jar\ntry:\nwith open(cookie_filename(account_hash), 'wb') as cookie_file:\ncommon.debug('Saving cookies to file')\n@@ -41,7 +38,7 @@ def save(account_hash, cookie_jar):\ndef delete(account_hash):\n\"\"\"Delete cookies for an account from in-memory storage and the disk\"\"\"\n# pylint: disable=broad-except\n- del COOKIES[account_hash]\n+ del g.COOKIES[account_hash]\ntry:\nos.remove(cookie_filename(account_hash))\nexcept Exception as exc:\n@@ -50,13 +47,13 @@ def delete(account_hash):\ndef load(account_hash):\n\"\"\"Load cookies for a given account and check them for validity\"\"\"\n- cookie_jar = (COOKIES.get(account_hash) or\n+ cookie_jar = (g.COOKIES.get(account_hash) or\nload_from_file(account_hash))\nif expired(cookie_jar):\nraise CookiesExpiredError()\n- COOKIES[account_hash] = cookie_jar\n+ g.COOKIES[account_hash] = cookie_jar\nreturn cookie_jar\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -168,6 +168,7 @@ class NetflixSession(object):\ndef _load_cookies(self):\n\"\"\"Load stored cookies from disk\"\"\"\n+ # pylint: disable=broad-except\ntry:\nself.session.cookies = cookies.load(self.account_hash)\nexcept common.MissingCredentialsError:\n@@ -180,6 +181,11 @@ class NetflixSession(object):\nexcept cookies.CookiesExpiredError:\n# Ignore this for now, because login is sometimes valid anyway\npass\n+ except Exception:\n+ common.error('Unexpected error while trying to load cookies. '\n+ 'Maybe using old storage format?')\n+ common.debug(traceback.format_exc())\n+ return False\nreturn True\[email protected]_return_call\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Move in-memory cookie storage to GlobalVariables. Add handler for unexpected cookie loading errors (e.g. old storage format) |
105,989 | 04.11.2018 02:33:59 | -3,600 | 0d8ca9aae93ea614ee58b41c347615d06416ffb4 | Several small fixes: filesystem path safety, identification of items in Kodi library, search behavior and many more | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -27,7 +27,6 @@ def logout():\n\"\"\"Logout of the current account\"\"\"\ng.CACHE.invalidate()\ncommon.make_call('logout')\n- common.purge_credentials()\ndef login():\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -114,12 +114,12 @@ def _get_identifier(fixed_identifier, identifying_param_name, kwargs,\nclass Cache(object):\n- def __init__(self, common, data_path, ttl, metadata_ttl, plugin_handle):\n+ def __init__(self, common, cache_path, ttl, metadata_ttl, plugin_handle):\n# pylint: disable=too-many-arguments\n# We have the self.common module injected as a dependency to work\n# around circular dependencies with gloabl variable initialization\nself.common = common\n- self.data_path = data_path\n+ self.cache_path = cache_path\nself.ttl = ttl\nself.metadata_ttl = metadata_ttl\nself.buckets = {}\n@@ -238,11 +238,11 @@ class Cache(object):\nif bucket == CACHE_LIBRARY:\n# We want a special handling for the library database, so users\n# dont accidentally delete it when deleting the cache\n- file_loc = ['library.ndb2']\n+ file_loc = [os.path.dirname(self.cache_path), 'library.ndb2']\nelse:\n- file_loc = [\n- 'cache', bucket, '{}.cache'.format(identifier)]\n- return os.path.join(self.data_path, *file_loc)\n+ file_loc = [self.cache_path, bucket, '{}.cache'.format(identifier)]\n+ return self.common.translate_path(\n+ os.path.join(*file_loc))\ndef _persist_bucket(self, bucket, contents):\n# pylint: disable=broad-except\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/fileops.py",
"new_path": "resources/lib/common/fileops.py",
"diff": "@@ -4,8 +4,12 @@ from __future__ import unicode_literals\nimport os\n+import xbmc\n+\nfrom resources.lib.globals import g\n+from .logging import debug\n+\ndef check_folder_path(path):\n\"\"\"\n@@ -29,24 +33,26 @@ def file_exists(filename, data_path=g.DATA_PATH):\nreturn os.path.exists(data_path + filename)\n-def save_file(filename, content, data_path=g.DATA_PATH, mode='w'):\n+def save_file(filename, content, mode='w'):\n\"\"\"\nSaves the given content under given filename\n:param filename: The filename\n:param content: The content of the file\n\"\"\"\n- with open(data_path + filename, mode) as file_handle:\n+ with open(translate_path(os.path.join(g.DATA_PATH, filename)),\n+ mode) as file_handle:\nfile_handle.write(content.encode('utf-8'))\n-def load_file(filename, data_path=g.DATA_PATH, mode='r'):\n+def load_file(filename, mode='r'):\n\"\"\"\nLoads the content of a given filename\n:param filename: The file to load\n:return: The content of the file\n\"\"\"\n- with open(data_path + filename, mode) as file_handle:\n- return file_handle.read()\n+ with open(translate_path(os.path.join(g.DATA_PATH, filename)),\n+ mode) as file_handle:\n+ return file_handle.read().decode('utf-8')\ndef list_dir(data_path=g.DATA_PATH):\n@@ -55,3 +61,8 @@ def list_dir(data_path=g.DATA_PATH):\n:return: The contents of the folder\n\"\"\"\nreturn os.listdir(data_path)\n+\n+\n+def translate_path(path):\n+ \"\"\"Translate path if it contains special:// and decode it to unicode\"\"\"\n+ return xbmc.translatePath(path).decode('utf-8')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/kodiops.py",
"new_path": "resources/lib/common/kodiops.py",
"diff": "@@ -7,7 +7,21 @@ import json\nimport xbmc\nfrom resources.lib.globals import g\n-from .logging import debug\n+\n+LIBRARY_PROPS = {\n+ 'episode': ['title', 'plot', 'writer', 'firstaired', 'playcount',\n+ 'runtime', 'director', 'productioncode', 'season',\n+ 'episode', 'originaltitle', 'showtitle', 'lastplayed',\n+ 'fanart', 'thumbnail', 'file', 'resume', 'tvshowid',\n+ 'dateadded', 'art', 'specialsortseason',\n+ 'specialsortepisode', 'userrating', 'seasonid'],\n+ 'movie': ['title', 'genre', 'year', 'director', 'trailer',\n+ 'tagline', 'plot', 'plotoutline', 'originaltitle', 'lastplayed',\n+ 'playcount', 'writer', 'studio', 'mpaa', 'country',\n+ 'imdbnumber', 'runtime', 'set', 'showlink', 'premiered',\n+ 'top250', 'fanart', 'thumbnail', 'file', 'sorttitle',\n+ 'resume', 'setid', 'dateadded', 'tag', 'art', 'userrating']\n+}\ndef json_rpc(method, params=None):\n@@ -48,10 +62,19 @@ def get_library_items(dbtype):\n\"\"\"Return a list of all items in the Kodi library that are of type\ndbtype (either movie or episode)\"\"\"\nmethod = 'VideoLibrary.Get{}s'.format(dbtype.capitalize())\n- params = {'properties': ['title', 'file', 'resume']}\n+ params = {'properties': ['file']}\nreturn json_rpc(method, params)[dbtype + 's']\n+def get_library_item_details(dbtype, itemid):\n+ \"\"\"Return details for an item from the Kodi library\"\"\"\n+ method = 'VideoLibrary.Get{}Details'.format(dbtype.capitalize())\n+ params = {\n+ dbtype + 'id': itemid,\n+ 'properties': LIBRARY_PROPS[dbtype]}\n+ return json_rpc(method, params)[dbtype + 'details']\n+\n+\ndef refresh_container():\n\"\"\"Refresh the current container\"\"\"\nxbmc.executebuiltin('Container.Refresh')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/storage.py",
"new_path": "resources/lib/common/storage.py",
"diff": "@@ -7,6 +7,7 @@ import json\nfrom resources.lib.globals import g\nfrom .logging import debug, error\n+from .fileops import translate_path\nclass PersistentStorage(object):\n@@ -21,7 +22,8 @@ class PersistentStorage(object):\n\"\"\"\ndef __init__(self, storage_id):\nself.storage_id = storage_id\n- self.backing_file = os.path.join(g.DATA_PATH, self.storage_id + '.ndb')\n+ self.backing_file = translate_path(\n+ os.path.join(g.DATA_PATH, self.storage_id + '.ndb'))\nself._contents = {}\nself._dirty = True\ndebug('Instantiated {}'.format(self.storage_id))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/globals.py",
"new_path": "resources/lib/globals.py",
"diff": "@@ -59,8 +59,9 @@ class GlobalVariables(object):\nself.VERSION = self.ADDON.getAddonInfo('version')\nself.DEFAULT_FANART = self.ADDON.getAddonInfo('fanart')\nself.ICON = self.ADDON.getAddonInfo('icon')\n- self.DATA_PATH = xbmc.translatePath(self.ADDON.getAddonInfo('profile'))\n- self.COOKIE_PATH = self.DATA_PATH + 'COOKIE'\n+ self.DATA_PATH = self.ADDON.getAddonInfo('profile')\n+ self.CACHE_PATH = os.path.join(self.DATA_PATH, 'cache')\n+ self.COOKIE_PATH = os.path.join(self.DATA_PATH, 'COOKIE')\nself.CACHE_TTL = self.ADDON.getSettingInt('cache_ttl') * 60\nself.CACHE_METADATA_TTL = (\nself.ADDON.getSettingInt('cache_metadata_ttl') * 60)\n@@ -87,12 +88,13 @@ class GlobalVariables(object):\nself._init_cache()\ndef _init_cache(self):\n- if not os.path.exists(os.path.join(self.DATA_PATH, 'cache')):\n+ if not os.path.exists(\n+ xbmc.translatePath(self.CACHE_PATH).decode('utf-8')):\nself._init_filesystem_cache()\n# This is ugly: Pass the common module into Cache.__init__ to work\n# around circular import dependencies.\nimport resources.lib.common as common\n- self.CACHE = cache.Cache(common, self.DATA_PATH, self.CACHE_TTL,\n+ self.CACHE = cache.Cache(common, self.CACHE_PATH, self.CACHE_TTL,\nself.CACHE_METADATA_TTL, self.PLUGIN_HANDLE)\ndef _init_filesystem_cache(self):\n@@ -102,7 +104,9 @@ class GlobalVariables(object):\n# we don't want users accidentally deleting it.\ncontinue\ntry:\n- os.makedirs(os.path.join(self.DATA_PATH, 'cache', bucket))\n+ os.makedirs(\n+ xbmc.translatePath(\n+ os.path.join(self.CACHE_PATH, bucket)).decode('utf-8'))\nexcept OSError:\npass\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -204,9 +204,9 @@ def add_info_from_library(videoid, list_item):\n# list_item.setProperty('startPercent', str(start_percent))\ninfos = {\n'DBID': details.pop('{}id'.format(videoid.mediatype)),\n- 'mediatype': videoid.mediatype,\n- 'title': details['title']\n+ 'mediatype': videoid.mediatype\n}\n+ infos.update(details)\nlist_item.setInfo('video', infos)\nlist_item.setArt(art)\nreturn infos, art\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "@@ -35,11 +35,12 @@ def get_item(videoid):\n# pylint: disable=broad-except\ntry:\nexported_filepath = os.path.normcase(\n- xbmc.translatePath(\n+ common.translate_path(\ncommon.get_path(videoid.to_list(), g.library())['file']))\nfor library_item in common.get_library_items(videoid.mediatype):\nif os.path.normcase(library_item['file']) == exported_filepath:\n- return library_item\n+ return common.get_library_item_details(\n+ videoid.mediatype, library_item[videoid.mediatype + 'id'])\nexcept Exception:\n# import traceback\n# common.error(traceback.format_exc())\n@@ -141,12 +142,13 @@ def export_item(item_task, library_home):\n_create_destination_folder(destination_folder)\n_write_strm_file(item_task, export_filename)\n_add_to_library(item_task['videoid'], export_filename)\n+ common.debug('Exported {}'.format(item_task['title']))\ndef _create_destination_folder(destination_folder):\n\"\"\"Create destination folder, ignore error if it already exists\"\"\"\ntry:\n- os.makedirs(xbmc.translatePath(destination_folder))\n+ os.makedirs(common.translate_path(destination_folder))\nexcept OSError as exc:\nif exc.errno != os.errno.EEXIST:\nraise\n@@ -155,7 +157,7 @@ def _create_destination_folder(destination_folder):\ndef _write_strm_file(item_task, export_filename):\n\"\"\"Write the playable URL to a strm file\"\"\"\ntry:\n- with codecs.open(xbmc.translatePath(export_filename),\n+ with codecs.open(common.translate_path(export_filename),\nmode='w',\nencoding='utf-8',\nerrors='replace') as filehandle:\n@@ -184,10 +186,10 @@ def _add_to_library(videoid, export_filename):\ndef remove_item(item_task):\n\"\"\"Remove an item from the library and delete if from disk\"\"\"\nid_path = item_task['videoid'].to_list()\n- exported_filename = xbmc.translatePath(\n+ exported_filename = common.translate_path(\ncommon.get_path(id_path, g.library())['file'])\nparent_folder = os.path.dirname(exported_filename)\n- os.remove(xbmc.translatePath(exported_filename))\n+ os.remove(common.translate_path(exported_filename))\nif not os.listdir(parent_folder):\nos.remove(parent_folder)\ncommon.remove_path(id_path, g.library())\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/listings.py",
"new_path": "resources/lib/kodi/listings.py",
"diff": "@@ -100,6 +100,7 @@ def _create_profile_item(profile_guid, profile, html_parser):\nenc_profile_name = profile_name.encode('utf-8')\nlist_item = list_item_skeleton(\nlabel=unescaped_profile_name, icon=profile.get('avatar'))\n+ list_item.select(profile.get('isActive', False))\nautologin_url = common.build_url(\npathitems=['save_autologin', profile_guid],\nparams={'autologin_user': enc_profile_name},\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/ui/dialogs.py",
"new_path": "resources/lib/kodi/ui/dialogs.py",
"diff": "@@ -87,6 +87,7 @@ def show_error_info(title, message, unknown_error=False, netflix_error=False):\nline2=message,\nline3=common.get_local_string(30103))\n+\ndef show_addon_error_info(exc):\n\"\"\"Show a dialog to notify of an addon internal error\"\"\"\nshow_error_info(title=common.get_local_string(30105),\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/directory.py",
"new_path": "resources/lib/navigation/directory.py",
"diff": "\"\"\"Navigation for classic plugin directory listing mode\"\"\"\nfrom __future__ import unicode_literals\n+import xbmc\nimport xbmcplugin\nfrom resources.lib.globals import g\n@@ -90,11 +91,10 @@ class DirectoryBuilder(object):\ndef search(self, pathitems):\n\"\"\"Ask for a search term if none is given via path, query API\nand display search results\"\"\"\n- search_term = (pathitems[1]\n- if len(pathitems) > 1\n- else ui.ask_for_search_term())\n- if search_term:\n- search_results = api.search(search_term)\n+ if len(pathitems) == 1:\n+ _ask_search_term_and_redirect()\n+ else:\n+ search_results = api.search(pathitems[1])\nif search_results.videos:\nlistings.build_video_listing(search_results)\nreturn\n@@ -112,3 +112,13 @@ class DirectoryBuilder(object):\nelse:\nui.show_notification(common.get_local_string(30013))\nxbmcplugin.endOfDirectory(g.PLUGIN_HANDLE, succeeded=False)\n+\n+\n+def _ask_search_term_and_redirect():\n+ search_term = ui.ask_for_search_term()\n+ if search_term:\n+ url = common.build_url(['search', search_term], mode=g.MODE_DIRECTORY)\n+ xbmcplugin.endOfDirectory(g.PLUGIN_HANDLE, succeeded=True)\n+ xbmc.executebuiltin('Container.Update({},replace)'.format(url))\n+ else:\n+ xbmcplugin.endOfDirectory(g.PLUGIN_HANDLE, succeeded=False)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/library.py",
"new_path": "resources/lib/navigation/library.py",
"diff": "\"\"\"Navigation handler for library actions\"\"\"\nfrom __future__ import unicode_literals\n+import os\n+\n+import xbmc\n+\nimport resources.lib.common as common\nimport resources.lib.kodi.library as library\n@@ -52,3 +56,9 @@ def _execute_library_tasks(videoid, task_handler, title):\ntask_handler=task_handler,\nnotify_errors=True,\nlibrary_home=library.library_path())\n+ path_to_scan = common.translate_path(\n+ os.path.join(library.library_path(),\n+ 'movies'\n+ if videoid.mediatype == common.VideoId.MOVIE\n+ else 'shows'))\n+ xbmc.executebuiltin('UpdateLibrary(video)')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/cookies.py",
"new_path": "resources/lib/services/cookies.py",
"diff": "@@ -81,4 +81,4 @@ def expired(cookie_jar):\ndef cookie_filename(account_hash):\n\"\"\"Return a filename to store cookies for a given account\"\"\"\n- return '{}_{}'.format(g.COOKIE_PATH, account_hash)\n+ return common.translate_path('{}_{}'.format(g.COOKIE_PATH, account_hash))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -218,6 +218,7 @@ class NetflixSession(object):\ncommon.debug('Logging out of current account')\nself._get('logout')\ncookies.delete(self.account_hash)\n+ common.purge_credentials()\ncommon.info('Logout successful')\nui.show_notification(common.get_local_string(30109))\nself._init_session()\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Several small fixes: filesystem path safety, identification of items in Kodi library, search behavior and many more |
105,989 | 04.11.2018 10:54:22 | -3,600 | 967681e72375e24d2c897af71bcaba904c23b904 | Add migrating from old credential encryption with unsafe secret. Ensure plaintext is byte string for AES encryption. | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/credentials.py",
"new_path": "resources/lib/common/credentials.py",
"diff": "@@ -4,6 +4,8 @@ from __future__ import unicode_literals\nfrom resources.lib.globals import g\n+from .logging import debug\n+\n__BLOCK_SIZE__ = 32\n__CRYPT_KEY__ = None\n@@ -55,7 +57,7 @@ def encrypt_credential(raw):\nreturn base64.b64encode(iv + cipher.encrypt(raw))\n-def decrypt_credential(enc):\n+def decrypt_credential(enc, secret=None):\n\"\"\"\nDecodes data\n@@ -69,7 +71,7 @@ def decrypt_credential(enc):\nfrom Cryptodome.Util import Padding\nenc = base64.b64decode(enc)\niv = enc[:AES.block_size]\n- cipher = AES.new(__uniq_id(), AES.MODE_CBC, iv)\n+ cipher = AES.new(secret or __uniq_id(), AES.MODE_CBC, iv)\ndecoded = Padding.unpad(\npadded_data=cipher.decrypt(enc[AES.block_size:]),\nblock_size=__BLOCK_SIZE__).decode('utf-8')\n@@ -89,9 +91,23 @@ def get_credentials():\n'email': decrypt_credential(email),\n'password': decrypt_credential(password)\n}\n+ except ValueError:\n+ return migrate_credentials(email, password)\n+\n+\n+def migrate_credentials(encrypted_email, encrypted_password):\n+ \"\"\"Try to decrypt stored credentials with the old unsafe secret and update\n+ them to new safe format\"\"\"\n+ unsafe_secret = 'UnsafeStaticSecret'.encode()\n+ try:\n+ email = decrypt_credential(encrypted_email, secret=unsafe_secret)\n+ password = decrypt_credential(encrypted_password, secret=unsafe_secret)\nexcept ValueError:\nraise MissingCredentialsError(\n'Existing credentials could not be decrypted')\n+ set_credentials(email, password)\n+ debug('Migrated old unsafely stored credentials to new safe format')\n+ return {'email': email, 'password': password}\ndef set_credentials(email, password):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/default_crypto.py",
"new_path": "resources/lib/services/msl/default_crypto.py",
"diff": "@@ -63,7 +63,7 @@ class DefaultMSLCrypto(MSLBaseCrypto):\n'iv': base64.standard_b64encode(init_vector)\n}\nencryption_envelope['ciphertext'] = base64.standard_b64encode(\n- cipher.encrypt(Padding.pad(plaintext, 16)))\n+ cipher.encrypt(Padding.pad(plaintext.encode('utf-8'), 16)))\nreturn json.dumps(encryption_envelope)\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add migrating from old credential encryption with unsafe secret. Ensure plaintext is byte string for AES encryption. |
105,989 | 04.11.2018 12:02:27 | -3,600 | 9c8c0e99c96ae61965987a457b27d3dbb20c7cb4 | Add mylist and library auto-sync | [
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.de_de/strings.po",
"new_path": "resources/language/resource.language.de_de/strings.po",
"diff": "@@ -467,3 +467,19 @@ msgstr \"Du musst eingeloggt sein um diese Funktion zu benutzen\"\nmsgctxt \"#30113\"\nmsgid \"Logout successful\"\nmsgstr \"Logout erfolgreich\"\n+\n+msgctxt \"#30114\"\n+msgid \"Keep My List and Kodi Library in sync\"\n+msgstr \"Meine Liste und Kodi Library synchronisieren\"\n+\n+msgctxt \"#30115\"\n+msgid \"Content Profiles\"\n+msgstr \"Inhaltsprofile\"\n+\n+msgctxt \"#30116\"\n+msgid \"Advanced Addon Configuration\"\n+msgstr \"Erweiterte Addon-Konfiguration\"\n+\n+msgctxt \"#30117\"\n+msgid \"Cache\"\n+msgstr \"Cache\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -475,3 +475,19 @@ msgstr \"\"\nmsgctxt \"#30113\"\nmsgid \"Logout successful\"\nmsgstr \"\"\n+\n+msgctxt \"#30114\"\n+msgid \"Keep My List and Kodi Library in sync\"\n+msgstr \"\"\n+\n+msgctxt \"#30115\"\n+msgid \"Content Profiles\"\n+msgstr \"\"\n+\n+msgctxt \"#30116\"\n+msgid \"Advanced Addon Configuration\"\n+msgstr \"\"\n+\n+msgctxt \"#30117\"\n+msgid \"Cache\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "@@ -225,12 +225,17 @@ def rate(videoid, rating):\ndef update_my_list(videoid, operation):\n\"\"\"Call API to update my list with either add or remove action\"\"\"\ncommon.debug('My List: {} {}'.format(operation, videoid))\n+ # We want the tvshowid for seasons and episodes (such videoids may be\n+ # passed by the mylist/library auto-sync feature)\n+ videoid_value = (videoid.movieid\n+ if videoid.mediatype == common.VideoId.MOVIE\n+ else videoid.tvshowid)\ncommon.make_call(\n'post',\n{'component': 'update_my_list',\n'data': {\n'operation': operation,\n- 'videoId': int(videoid.value)}})\n+ 'videoId': int(videoid_value)}})\ntry:\ng.CACHE.invalidate_entry(cache.CACHE_COMMON, list_id_for_type('queue'))\nexcept InvalidVideoListTypeError:\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/kodiops.py",
"new_path": "resources/lib/common/kodiops.py",
"diff": "@@ -99,3 +99,9 @@ def run_plugin(path, block=False):\nthe execution of code will block until the called plugin has finished\nrunning.\"\"\"\nxbmc.executebuiltin(run_plugin_action(path, block))\n+\n+\n+def schedule_builtin(time, command, name='NetflixTask'):\n+ \"\"\"Set an alarm to run builtin command after time has passed\"\"\"\n+ xbmc.executebuiltin('AlarmClock({},{},{},True])'\n+ .format(name, command, time))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "@@ -183,15 +183,16 @@ def _add_to_library(videoid, export_filename):\ng.save_library()\n-def remove_item(item_task):\n+def remove_item(item_task, library_home=None):\n\"\"\"Remove an item from the library and delete if from disk\"\"\"\n+ # pylint: disable=unused-argument\nid_path = item_task['videoid'].to_list()\nexported_filename = common.translate_path(\ncommon.get_path(id_path, g.library())['file'])\nparent_folder = os.path.dirname(exported_filename)\nos.remove(common.translate_path(exported_filename))\nif not os.listdir(parent_folder):\n- os.remove(parent_folder)\n+ os.rmdir(parent_folder)\ncommon.remove_path(id_path, g.library())\ng.save_library()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/actions.py",
"new_path": "resources/lib/navigation/actions.py",
"diff": "\"\"\"Navigation handler for actions\"\"\"\nfrom __future__ import unicode_literals\n+import xbmc\nfrom xbmcaddon import Addon\nfrom resources.lib.globals import g\nimport resources.lib.common as common\n-import resources.lib.cache as cache\nimport resources.lib.api.shakti as api\nimport resources.lib.kodi.ui as ui\nfrom resources.lib.navigation import InvalidPathError\n@@ -38,10 +38,9 @@ class AddonActionExecutor(object):\nself.params['autologin_user'])\ng.ADDON.setSetting('autologin_id', pathitems[1])\ng.ADDON.setSetting('autologin_enable', 'true')\n- g.flush_settings()\nexcept (KeyError, IndexError):\ncommon.error('Cannot save autologin - invalid params')\n- cache.invalidate_cache()\n+ g.CACHE.invalidate()\ncommon.refresh_container()\ndef switch_account(self, pathitems=None):\n@@ -76,5 +75,22 @@ class AddonActionExecutor(object):\[email protected]_video_id(path_offset=2, inject_remaining_pathitems=True)\ndef my_list(self, videoid, pathitems):\n\"\"\"Add or remove an item from my list\"\"\"\n- api.update_my_list(videoid, pathitems[1])\n+ operation = pathitems[1]\n+ api.update_my_list(videoid, operation)\n+ _sync_library(videoid, operation)\ncommon.refresh_container()\n+\n+\n+def _sync_library(videoid, operation):\n+ operation = {\n+ 'add': 'export_silent',\n+ 'remove': 'remove_silent'}.get(operation)\n+ if operation and g.ADDON.getSettingBool('mylist_library_sync'):\n+ common.debug('Syncing library due to change of my list')\n+ # We need to wait a little before syncing the library to prevent race\n+ # conditions with the Container refresh\n+ common.schedule_builtin(\n+ '00:03',\n+ common.run_plugin_action(\n+ common.build_url([operation], videoid, mode=g.MODE_LIBRARY)),\n+ name='NetflixLibrarySync')\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/library.py",
"new_path": "resources/lib/navigation/library.py",
"diff": "\"\"\"Navigation handler for library actions\"\"\"\nfrom __future__ import unicode_literals\n-import os\n-\nimport xbmc\n+from resources.lib. globals import g\nimport resources.lib.common as common\n+import resources.lib.api.shakti as api\nimport resources.lib.kodi.library as library\n@@ -18,18 +18,6 @@ class LibraryActionExecutor(object):\n.format(params))\nself.params = params\n- @common.inject_video_id(path_offset=1)\n- def export_silent(self, videoid):\n- \"\"\"Export an item to the Kodi library\"\"\"\n- # pylint: disable=broad-except\n- for task in library.compile_tasks(videoid):\n- try:\n- library.export_item(task, library.library_path())\n- except Exception:\n- import traceback\n- common.error(traceback.format_exc())\n- common.error('Export of {} failed'.format(task['title']))\n-\[email protected]_video_id(path_offset=1)\ndef export(self, videoid):\n\"\"\"Export an item to the Kodi library\"\"\"\n@@ -48,6 +36,34 @@ class LibraryActionExecutor(object):\n_execute_library_tasks(videoid, library.update_item,\ncommon.get_local_string(30061))\n+ @common.inject_video_id(path_offset=1)\n+ def export_silent(self, videoid):\n+ \"\"\"Silently export an item to the Kodi library\n+ (without GUI feedback). This will ignore the setting for syncing my\n+ list and Kodi library and do no sync, if not explicitly asked to.\"\"\"\n+ # pylint: disable=broad-except\n+ _execute_library_tasks_silently(\n+ videoid, library.export_item,\n+ self.params.get('sync_mylist', False))\n+\n+ @common.inject_video_id(path_offset=1)\n+ def remove_silent(self, videoid):\n+ \"\"\"Silently remove an item from the Kodi library\n+ (without GUI feedback). This will ignore the setting for syncing my\n+ list and Kodi library and do no sync, if not explicitly asked to.\"\"\"\n+ _execute_library_tasks_silently(\n+ videoid, library.remove_item,\n+ self.params.get('sync_mylist', False))\n+\n+ @common.inject_video_id(path_offset=1)\n+ def update_silent(self, videoid):\n+ \"\"\"Silently update an item in the Kodi library\n+ (without GUI feedback). This will ignore the setting for syncing my\n+ list and Kodi library and do no sync, if not explicitly asked to.\"\"\"\n+ _execute_library_tasks_silently(\n+ videoid, library.update_item,\n+ self.params.get('sync_mylist', False))\n+\ndef _execute_library_tasks(videoid, task_handler, title):\n\"\"\"Execute library tasks for videoid and show errors in foreground\"\"\"\n@@ -56,9 +72,31 @@ def _execute_library_tasks(videoid, task_handler, title):\ntask_handler=task_handler,\nnotify_errors=True,\nlibrary_home=library.library_path())\n- path_to_scan = common.translate_path(\n- os.path.join(library.library_path(),\n- 'movies'\n- if videoid.mediatype == common.VideoId.MOVIE\n- else 'shows'))\n+ _sync_mylist(videoid, task_handler)\nxbmc.executebuiltin('UpdateLibrary(video)')\n+\n+\n+def _execute_library_tasks_silently(videoid, task_handler, sync_mylist):\n+ \"\"\"Execute library tasks for videoid and don't show any GUI feedback\"\"\"\n+ # pylint: disable=broad-except\n+ for task in library.compile_tasks(videoid):\n+ try:\n+ task_handler(task, library.library_path())\n+ except Exception:\n+ import traceback\n+ common.error(traceback.format_exc())\n+ common.error('{} of {} failed'\n+ .format(task_handler.__name__, task['title']))\n+ xbmc.executebuiltin('UpdateLibrary(video)')\n+ if sync_mylist:\n+ _sync_mylist(videoid, task_handler)\n+\n+\n+def _sync_mylist(videoid, task_handler):\n+ \"\"\"Add or remove exported items to My List, if enabled in settings\"\"\"\n+ operation = {\n+ 'export_item': 'add',\n+ 'remove_item': 'remove'}.get(task_handler.__name__)\n+ if operation and g.ADDON.getSettingBool('mylist_library_sync'):\n+ common.debug('Syncing my list due to change of Kodi library')\n+ api.update_my_list(videoid, operation)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/settings.xml",
"new_path": "resources/settings.xml",
"diff": "<setting id=\"switch_account\" type=\"action\" label=\"30059c\" action=\"RunPlugin(plugin://plugin.video.netflix/action/switch_account)\" option=\"close\"/>\n<setting id=\"logout\" type=\"action\" label=\"30017\" action=\"RunPlugin(plugin://plugin.video.netflix/action/logout)\" option=\"close\"/>\n<setting id=\"adultpin_enable\" type=\"action\" label=\"30062\" default=\"False\" action=\"RunPlugin(plugin://plugin.video.netflix/action/toggle_adult_pin)\"/>\n+ <setting label=\"30053\" type=\"lsep\"/>\n+ <setting id=\"autologin_enable\" type=\"bool\" label=\"30054\" default=\"false\"/>\n+ <setting id=\"autologin_user\" type=\"text\" label=\"30055\" default=\"\" enable=\"false\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n+ <setting id=\"autologin_id\" type=\"text\" label=\"30056\" default=\"\" enable=\"false\" visible=\"eq(-2,true)\" subsetting=\"true\"/>\n+ <setting id=\"info\" type=\"text\" label=\"30057\" default=\"\" enable=\"false\" visible=\"eq(-3,true)\"/>\n<setting type=\"sep\"/>\n<setting id=\"is_settings\" type=\"action\" label=\"30035\" action=\"RunPlugin(plugin://plugin.video.netflix/action/opensettings/inputstream.adaptive)\" enable=\"System.HasAddon(inputstream.adaptive)\" option=\"close\"/>\n</category>\n<category label=\"30025\">\n<setting id=\"enablelibraryfolder\" type=\"bool\" label=\"30026\" default=\"false\"/>\n<setting id=\"customlibraryfolder\" type=\"folder\" label=\"30027\" enable=\"eq(-1,true)\" default=\"special://profile/addon_data/plugin.video.netflix\" source=\"auto\" option=\"writeable\" subsetting=\"true\"/>\n- <setting id=\"customexportname\" type=\"bool\" label=\"30036\" default=\"false\"/>\n+ <setting id=\"mylist_library_sync\" type=\"bool\" label=\"30114\" default=\"false\"/>\n<setting label=\"30065\" type=\"lsep\"/>\n<setting id=\"auto_update\" type=\"enum\" label=\"30064\" lvalues=\"30066|30067|30068|30069|30070\" default=\"0\"/>\n<setting id=\"update_time\" type=\"time\" label=\"30071\" visible=\"gt(-1,0)\" default=\"00:00\" subsetting=\"true\"/>\n<setting id=\"pause_on_skip\" type=\"bool\" label=\"30080\" default=\"false\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n</category>\n<category label=\"30023\">\n+ <setting label=\"30115\" type=\"lsep\"/>\n<setting id=\"enable_dolby_sound\" type=\"bool\" label=\"30033\" default=\"true\"/>\n<setting id=\"enable_atmos_sound\" type=\"bool\" label=\"30111\" default=\"true\"/>\n<setting id=\"enable_hevc_profiles\" type=\"bool\" label=\"30060\" default=\"false\"/>\n<setting id=\"enable_hdr_profiles\" type=\"bool\" label=\"30098\" default=\"false\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n<setting id=\"enable_dolbyvision_profiles\" type=\"bool\" label=\"30099\" default=\"false\" visible=\"eq(-2,true)\" subsetting=\"true\"/>\n<setting id=\"enable_vp9_profiles\" type=\"bool\" label=\"30136\" default=\"false\" visible=\"eq(-3,true)\" subsetting=\"true\"/>\n+ <setting label=\"30116\" type=\"lsep\"/>\n<setting id=\"ssl_verification\" type=\"bool\" label=\"30024\" default=\"true\"/>\n<setting id=\"enable_tracking\" type=\"bool\" label=\"30032\" default=\"true\"/>\n<setting id=\"esn\" type=\"text\" label=\"30034\" value=\"\" default=\"\"/>\n- <setting id=\"cache_ttl\" type=\"slider\" option=\"int\" range=\"0,10,525600\" label=\"30084\" default=\"10\"/>\n- <setting id=\"cache_metadata_ttl\" type=\"slider\" option=\"int\" range=\"0,60,525600\" label=\"30085\" default=\"43200\"/>\n- <setting id=\"invalidate_cache_on_mylist_modify\" type=\"bool\" label=\"30086\" default=\"false\"/>\n<setting id=\"hidden_esn\" visible=\"false\" value=\"\" />\n<setting id=\"tracking_id\" value=\"\" visible=\"false\"/>\n<setting id=\"msl_service_port\" value=\"8000\" visible=\"false\"/>\n<setting id=\"show_update_db\" type=\"bool\" default=\"false\" visible=\"false\"/>\n- </category>\n- <category label=\"30053\">\n- <setting id=\"autologin_enable\" type=\"bool\" label=\"30054\" default=\"false\"/>\n- <setting id=\"autologin_user\" type=\"text\" label=\"30055\" default=\"\" enable=\"false\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n- <setting id=\"autologin_id\" type=\"text\" label=\"30056\" default=\"\" enable=\"false\" visible=\"eq(-2,true)\" subsetting=\"true\"/>\n- <setting id=\"info\" type=\"text\" label=\"30057\" default=\"\" enable=\"false\" visible=\"eq(-3,true)\"/>\n+ <setting label=\"30117\" type=\"lsep\"/>\n+ <setting id=\"cache_ttl\" type=\"slider\" option=\"int\" range=\"0,10,525600\" label=\"30084\" default=\"10\"/>\n+ <setting id=\"cache_metadata_ttl\" type=\"slider\" option=\"int\" range=\"0,1,365\" label=\"30085\" default=\"30\"/>\n</category>\n</settings>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add mylist and library auto-sync |
105,989 | 04.11.2018 14:35:52 | -3,600 | 0631684a69c287291efe85d5bc97f1d54b9738fd | Massively improve Kodi library integration. Add better error handling and user feedback. Several small bugfixes | [
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -357,7 +357,7 @@ msgid \"Cache item time-to-live (minutes)\"\nmsgstr \"\"\nmsgctxt \"#30085\"\n-msgid \"Cache item time-to-live for metadata (minutes)\"\n+msgid \"Cache item time-to-live for metadata (days)\"\nmsgstr \"\"\nmsgctxt \"#30086\"\n@@ -491,3 +491,15 @@ msgstr \"\"\nmsgctxt \"#30117\"\nmsgid \"Cache\"\nmsgstr \"\"\n+\n+msgctxt \"#30118\"\n+msgid \"My List operation failed: {}\"\n+msgstr \"\"\n+\n+msgctxt \"#30119\"\n+msgid \"My List operation successful\"\n+msgstr \"\"\n+\n+msgctxt \"#30120\"\n+msgid \"Cannot automatically remove a season from Kodi library, please do it manually\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/exceptions.py",
"new_path": "resources/lib/api/exceptions.py",
"diff": "@@ -43,3 +43,8 @@ class NotLoggedInError(Exception):\n\"\"\"The requested operation requires a valid and active login, which\nis not present\"\"\"\npass\n+\n+\n+class APIError(Exception):\n+ \"\"\"The requested API operation has resulted in an error\"\"\"\n+ pass\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "\"\"\"Access to Netflix's Shakti API\"\"\"\nfrom __future__ import unicode_literals\n-from functools import wraps\n-\nfrom resources.lib.globals import g\nimport resources.lib.common as common\nimport resources.lib.cache as cache\n@@ -14,7 +12,7 @@ from .data_types import (LoLoMo, VideoList, SeasonList, EpisodeList,\nfrom .paths import (VIDEO_LIST_PARTIAL_PATHS, SEASONS_PARTIAL_PATHS,\nEPISODES_PARTIAL_PATHS, ART_PARTIAL_PATHS,\nGENRE_PARTIAL_PATHS, RANGE_SELECTOR)\n-from .exceptions import InvalidVideoListTypeError, LoginFailedError\n+from .exceptions import InvalidVideoListTypeError, LoginFailedError, APIError\ndef activate_profile(profile_id):\n@@ -230,12 +228,16 @@ def update_my_list(videoid, operation):\nvideoid_value = (videoid.movieid\nif videoid.mediatype == common.VideoId.MOVIE\nelse videoid.tvshowid)\n+ try:\ncommon.make_call(\n'post',\n{'component': 'update_my_list',\n'data': {\n'operation': operation,\n'videoId': int(videoid_value)}})\n+ ui.show_notification(common.get_local_string(30119))\n+ except APIError as exc:\n+ ui.show_notification(common.get_local_string(30118).format(exc))\ntry:\ng.CACHE.invalidate_entry(cache.CACHE_COMMON, list_id_for_type('queue'))\nexcept InvalidVideoListTypeError:\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -34,6 +34,7 @@ BUCKET_NAMES = [CACHE_COMMON, CACHE_GENRES, CACHE_METADATA,\nBUCKET_LOCKED = 'LOCKED_BY_{}'\n+# 100 years TTL should be close enough to infinite\nTTL_INFINITE = 60*60*24*365*100\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/ipc.py",
"new_path": "resources/lib/common/ipc.py",
"diff": "@@ -64,7 +64,7 @@ def make_call(callname, data=None):\n.format(callname=callname, **result))\nerror(msg)\ntry:\n- raise apierrors.__dict__[result['error']]\n+ raise apierrors.__dict__[result['error']](result['message'])\nexcept KeyError:\nraise Exception(result['error'])\nelif result is None:\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/kodiops.py",
"new_path": "resources/lib/common/kodiops.py",
"diff": "@@ -8,6 +8,8 @@ import xbmc\nfrom resources.lib.globals import g\n+from .logging import debug\n+\nLIBRARY_PROPS = {\n'episode': ['title', 'plot', 'writer', 'firstaired', 'playcount',\n'runtime', 'director', 'productioncode', 'season',\n@@ -37,7 +39,7 @@ def json_rpc(method, params=None):\nrequest_data = {'jsonrpc': '2.0', 'method': method, 'id': 1,\n'params': params or {}}\nrequest = json.dumps(request_data)\n- # debug('Executing JSON-RPC: {}'.format(request))\n+ debug('Executing JSON-RPC: {}'.format(request))\nraw_response = unicode(xbmc.executeJSONRPC(request), 'utf-8')\n# debug('JSON-RPC response: {}'.format(raw_response))\nresponse = json.loads(raw_response)\n@@ -103,5 +105,5 @@ def run_plugin(path, block=False):\ndef schedule_builtin(time, command, name='NetflixTask'):\n\"\"\"Set an alarm to run builtin command after time has passed\"\"\"\n- xbmc.executebuiltin('AlarmClock({},{},{},True])'\n+ xbmc.executebuiltin('AlarmClock({},{},{},silent)'\n.format(name, command, time))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/logging.py",
"new_path": "resources/lib/common/logging.py",
"diff": "@@ -14,6 +14,8 @@ def log(msg, exc=None, level=xbmc.LOGDEBUG):\nIf msg contains a format placeholder for exc and exc is not none,\nexc will be formatted into the message.\"\"\"\nmsg = msg.format(exc=exc) if exc is not None and '{exc}' in msg else msg\n+ if isinstance(msg, str):\n+ msg = msg.decode('utf-8')\nxbmc.log('[{identifier} ({handle})] {msg}'\n.format(identifier=g.ADDON_ID, handle=g.PLUGIN_HANDLE, msg=msg)\n.encode('utf-8'),\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/globals.py",
"new_path": "resources/lib/globals.py",
"diff": "@@ -64,7 +64,7 @@ class GlobalVariables(object):\nself.COOKIE_PATH = os.path.join(self.DATA_PATH, 'COOKIE')\nself.CACHE_TTL = self.ADDON.getSettingInt('cache_ttl') * 60\nself.CACHE_METADATA_TTL = (\n- self.ADDON.getSettingInt('cache_metadata_ttl') * 60)\n+ self.ADDON.getSettingInt('cache_metadata_ttl') * 24 * 60 * 60)\nself.URL = urlparse(argv[0])\ntry:\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/context_menu.py",
"new_path": "resources/lib/kodi/context_menu.py",
"diff": "@@ -50,7 +50,8 @@ def generate_context_menu_items(videoid):\nlist_action = ('remove_from_list'\nif videoid.value in api.mylist_items()\nelse 'add_to_list')\n- items.append(_ctx_item(list_action, videoid))\n+ # Put this as first item\n+ items.insert(0, _ctx_item(list_action, videoid))\nreturn items\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "from __future__ import unicode_literals\nimport os\n+import re\nimport codecs\nfrom datetime import datetime, timedelta\n+from functools import wraps\nimport xbmc\nfrom resources.lib.globals import g\nimport resources.lib.common as common\nimport resources.lib.api.shakti as api\n+import resources.lib.kodi.ui as ui\nLIBRARY_HOME = 'library'\nFOLDER_MOVIES = 'movies'\nFOLDER_TV = 'shows'\n+ILLEGAL_CHARACTERS = '[<|>|\"|?|$|!|:|#|*]'\nclass ItemNotFound(Exception):\n@@ -34,23 +38,42 @@ def get_item(videoid):\nKodi DBID and mediatype\"\"\"\n# pylint: disable=broad-except\ntry:\n- exported_filepath = os.path.normcase(\n- common.translate_path(\n- common.get_path(videoid.to_list(), g.library())['file']))\n- for library_item in common.get_library_items(videoid.mediatype):\n- if os.path.normcase(library_item['file']) == exported_filepath:\n- return common.get_library_item_details(\n- videoid.mediatype, library_item[videoid.mediatype + 'id'])\n- except Exception:\n- # import traceback\n- # common.error(traceback.format_exc())\n- pass\n- # This is intentionally not raised in the except block!\n+ library_entry, entry_type = _get_library_entry(videoid)\n+ return _get_item(entry_type, library_entry['file'])\n+ except (KeyError, AttributeError, IndexError, ItemNotFound):\n+ import traceback\n+ common.error(traceback.format_exc())\nraise ItemNotFound(\n'The video with id {} is not present in the Kodi library'\n.format(videoid))\n+def _get_library_entry(videoid):\n+ \"\"\"Get the first leaf-entry for videoid from the library.\n+ For shows and seasons this will return the first contained episode\"\"\"\n+ if videoid.mediatype in [common.VideoId.MOVIE, common.VideoId.EPISODE]:\n+ return (common.get_path(videoid.to_list(), g.library()),\n+ videoid.mediatype)\n+ elif videoid.mediatype == common.VideoId.SHOW:\n+ return (g.library()[videoid.tvshowid].values()[0].values()[0],\n+ common.VideoId.EPISODE)\n+ elif videoid.mediatype == common.VideoId.SHOW:\n+ return (g.library()[videoid.tvshowid][videoid.seasonid].values()[0],\n+ common.VideoId.EPISODE)\n+ else:\n+ raise ItemNotFound('No items of type {} in library'\n+ .format(videoid.mediatype))\n+\n+\n+def _get_item(mediatype, filename):\n+ exported_filepath = os.path.normcase(common.translate_path(filename))\n+ for library_item in common.get_library_items(mediatype):\n+ if os.path.normcase(library_item['file']) == exported_filepath:\n+ return common.get_library_item_details(\n+ mediatype, library_item[mediatype + 'id'])\n+ raise ItemNotFound\n+\n+\ndef list_contents():\n\"\"\"Return a list of all top-level video IDs (movies, shows)\ncontained in the library\"\"\"\n@@ -62,6 +85,44 @@ def is_in_library(videoid):\nreturn common.get_path_safe(videoid.to_list(), g.library()) is not None\n+def update_kodi_library(library_operation):\n+ \"\"\"Decorator that ensures an update of the Kodi libarary\"\"\"\n+ @wraps(library_operation)\n+ def kodi_library_update_wrapper(videoid, task_handler, *args, **kwargs):\n+ \"\"\"Either trigger an update of the Kodi library or remove the\n+ items associated with videoid, depending on the invoked task_handler\"\"\"\n+ is_remove = task_handler == remove_item\n+ if is_remove:\n+ _remove_from_kodi_library(videoid)\n+ library_operation(videoid, task_handler, *args, **kwargs)\n+ if not is_remove:\n+ common.debug('Triggering Kodi library scan')\n+ xbmc.executebuiltin('UpdateLibrary(video)')\n+ return kodi_library_update_wrapper\n+\n+\n+def _remove_from_kodi_library(videoid):\n+ \"\"\"Remove an item from the Kodi library.\"\"\"\n+ common.debug('Removing {} videoid from Kodi library'.format(videoid))\n+ try:\n+ kodi_library_item = get_item(videoid)\n+ rpc_params = {\n+ 'movie': ['VideoLibrary.RemoveMovie', 'movieid'],\n+ 'show': ['VideoLibrary.RemoveTVShow', 'tvshowid'],\n+ 'episode': ['VideoLibrary.RemoveEpisode', 'episodeid']\n+ }[videoid.mediatype]\n+ common.json_rpc(rpc_params[0],\n+ {rpc_params[1]: kodi_library_item[rpc_params[1]]})\n+ except ItemNotFound:\n+ common.debug('Cannot remove {} from Kodi library, item not present'\n+ .format(videoid))\n+ except KeyError as exc:\n+ ui.show_notification(common.get_local_string(30120), time=7500)\n+ common.warn('Cannot remove {} from Kodi library, '\n+ 'Kodi does not support this (yet)'\n+ .format(exc))\n+\n+\ndef compile_tasks(videoid):\n\"\"\"Compile a list of tasks for items based on the videoid\"\"\"\nmetadata = api.metadata(videoid)\n@@ -128,8 +189,8 @@ def _create_item_task(title, section, videoid, destination, filename):\n'title': title,\n'section': section,\n'videoid': videoid,\n- 'destination': destination,\n- 'filename': filename\n+ 'destination': re.sub(ILLEGAL_CHARACTERS, '', destination),\n+ 'filename': re.sub(ILLEGAL_CHARACTERS, '', filename)\n}\n@@ -186,6 +247,11 @@ def _add_to_library(videoid, export_filename):\ndef remove_item(item_task, library_home=None):\n\"\"\"Remove an item from the library and delete if from disk\"\"\"\n# pylint: disable=unused-argument\n+ common.debug('Removing {} from library'.format(item_task['title']))\n+ if not is_in_library(item_task['videoid']):\n+ common.warn('cannot remove {}, item not in library'\n+ .format(item_task['title']))\n+ return\nid_path = item_task['videoid'].to_list()\nexported_filename = common.translate_path(\ncommon.get_path(id_path, g.library())['file'])\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/ui/dialogs.py",
"new_path": "resources/lib/kodi/ui/dialogs.py",
"diff": "@@ -10,10 +10,10 @@ from resources.lib.globals import g\nimport resources.lib.common as common\n-def show_notification(msg, title='Netflix'):\n+def show_notification(msg, title='Netflix', time=3000):\n\"\"\"Show a notification\"\"\"\n- xbmc.executebuiltin('Notification({}, {}, 3000, {})'\n- .format(title, msg, g.ICON)\n+ xbmc.executebuiltin('Notification({}, {}, {}, {})'\n+ .format(title, msg, time, g.ICON)\n.encode('utf-8'))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/library.py",
"new_path": "resources/lib/navigation/library.py",
"diff": "\"\"\"Navigation handler for library actions\"\"\"\nfrom __future__ import unicode_literals\n-import xbmc\nfrom resources.lib. globals import g\nimport resources.lib.common as common\n@@ -65,6 +64,7 @@ class LibraryActionExecutor(object):\nself.params.get('sync_mylist', False))\[email protected]_kodi_library\ndef _execute_library_tasks(videoid, task_handler, title):\n\"\"\"Execute library tasks for videoid and show errors in foreground\"\"\"\ncommon.execute_tasks(title=title,\n@@ -73,9 +73,9 @@ def _execute_library_tasks(videoid, task_handler, title):\nnotify_errors=True,\nlibrary_home=library.library_path())\n_sync_mylist(videoid, task_handler)\n- xbmc.executebuiltin('UpdateLibrary(video)')\[email protected]_kodi_library\ndef _execute_library_tasks_silently(videoid, task_handler, sync_mylist):\n\"\"\"Execute library tasks for videoid and don't show any GUI feedback\"\"\"\n# pylint: disable=broad-except\n@@ -87,7 +87,6 @@ def _execute_library_tasks_silently(videoid, task_handler, sync_mylist):\ncommon.error(traceback.format_exc())\ncommon.error('{} of {} failed'\n.format(task_handler.__name__, task['title']))\n- xbmc.executebuiltin('UpdateLibrary(video)')\nif sync_mylist:\n_sync_mylist(videoid, task_handler)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -16,7 +16,8 @@ import resources.lib.api.paths as apipaths\nimport resources.lib.services.cookies as cookies\nimport resources.lib.kodi.ui as ui\n-from resources.lib.api.exceptions import NotLoggedInError, LoginFailedError\n+from resources.lib.api.exceptions import (NotLoggedInError, LoginFailedError,\n+ APIError)\nBASE_URL = 'https://www.netflix.com'\n\"\"\"str: Secure Netflix url\"\"\"\n@@ -354,7 +355,7 @@ class NetflixSession(object):\ncommon.debug(\n'Request returned statuscode {}'.format(response.status_code))\nresponse.raise_for_status()\n- return (response.json()\n+ return (_raise_api_error(response.json())\nif URLS[component]['is_api_call']\nelse response.content)\n@@ -421,3 +422,9 @@ def _update_esn(esn):\n\"\"\"Return True if the esn has changed on Session initialization\"\"\"\nif g.set_esn(esn):\ncommon.send_signal(signal=common.Signals.ESN_CHANGED, data=esn)\n+\n+\n+def _raise_api_error(decoded_response):\n+ if decoded_response.get('status', 'success') == 'error':\n+ raise APIError(decoded_response.get('message'))\n+ return decoded_response\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/settings.xml",
"new_path": "resources/settings.xml",
"diff": "<setting id=\"enablelibraryfolder\" type=\"bool\" label=\"30026\" default=\"false\"/>\n<setting id=\"customlibraryfolder\" type=\"folder\" label=\"30027\" enable=\"eq(-1,true)\" default=\"special://profile/addon_data/plugin.video.netflix\" source=\"auto\" option=\"writeable\" subsetting=\"true\"/>\n<setting id=\"mylist_library_sync\" type=\"bool\" label=\"30114\" default=\"false\"/>\n+ <setting id=\"customexportname\" type=\"bool\" label=\"No longer in use\" default=\"true\" visible=\"false\"/>\n+ <setting id=\"invalidate_cache_on_mylist_modify\" type=\"bool\" label=\"No longer in use\" default=\"true\" visible=\"false\"/>\n<setting label=\"30065\" type=\"lsep\"/>\n<setting id=\"auto_update\" type=\"enum\" label=\"30064\" lvalues=\"30066|30067|30068|30069|30070\" default=\"0\"/>\n<setting id=\"update_time\" type=\"time\" label=\"30071\" visible=\"gt(-1,0)\" default=\"00:00\" subsetting=\"true\"/>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Massively improve Kodi library integration. Add better error handling and user feedback. Several small bugfixes |
105,989 | 04.11.2018 18:07:43 | -3,600 | 864feaf992ca152c80a39b66218a22672c65a63c | Add full sync of my list to Kodi library. Add library purge. Reorder context menu items. Improve GUI feedback on API actions (rate, ...). Tons of bugfixes | [
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -493,7 +493,7 @@ msgid \"Cache\"\nmsgstr \"\"\nmsgctxt \"#30118\"\n-msgid \"My List operation failed: {}\"\n+msgid \"API operation failed: {}\"\nmsgstr \"\"\nmsgctxt \"#30119\"\n@@ -503,3 +503,31 @@ msgstr \"\"\nmsgctxt \"#30120\"\nmsgid \"Cannot automatically remove a season from Kodi library, please do it manually\"\nmsgstr \"\"\n+\n+msgctxt \"#30121\"\n+msgid \"Perform full sync now\"\n+msgstr \"\"\n+\n+msgctxt \"#30122\"\n+msgid \"Sync My List to Kodi library\"\n+msgstr \"\"\n+\n+msgctxt \"#30123\"\n+msgid \"Do you really want to proceed?\\nThis will delete all previously exported items and export all items from My List for the currently active profile.\\nThis operation may take some time...\"\n+msgstr \"\"\n+\n+msgctxt \"#30124\"\n+msgid \"Do you really want to remove this item?\"\n+msgstr \"\"\n+\n+msgctxt \"#30125\"\n+msgid \"Purge library\"\n+msgstr \"\"\n+\n+msgctxt \"#30126\"\n+msgid \"Do you really want to purge your library?\\nAll exported items will be deleted.\"\n+msgstr \"\"\n+\n+msgctxt \"#30127\"\n+msgid \"Awarded rating of {}\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/data_types.py",
"new_path": "resources/lib/api/data_types.py",
"diff": "@@ -58,6 +58,11 @@ class VideoList(object):\nself.artitem = next(self.videos.itervalues())\nself.contained_titles = [video['title']\nfor video in self.videos.itervalues()]\n+ try:\n+ self.videoids = [common.VideoId.from_videolist_item(video)\n+ for video in self.videos.itervalues()]\n+ except KeyError:\n+ self.videoids = None\ndef __getitem__(self, key):\nreturn _check_sentinel(self.data['lists'][self.id.value][key])\n@@ -78,6 +83,8 @@ class SearchVideoList(object):\nself.videos = OrderedDict(\nresolve_refs(self.data['search']['byReference'].values()[0],\nself.data))\n+ self.videoids = [common.VideoId.from_videolist_item(video)\n+ for video in self.videos.itervalues()]\nself.artitem = next(self.videos.itervalues(), None)\nself.contained_titles = [video['title']\nfor video in self.videos.itervalues()]\n@@ -97,6 +104,8 @@ class CustomVideoList(object):\nself.data = path_response\nself.title = common.get_local_string(30048)\nself.videos = self.data['videos']\n+ self.videoids = [common.VideoId.from_videolist_item(video)\n+ for video in self.videos.itervalues()]\nself.artitem = next(self.videos.itervalues())\nself.contained_titles = [video['title']\nfor video in self.videos.itervalues()]\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/shakti.py",
"new_path": "resources/lib/api/shakti.py",
"diff": "\"\"\"Access to Netflix's Shakti API\"\"\"\nfrom __future__ import unicode_literals\n+from functools import wraps\n+\nfrom resources.lib.globals import g\nimport resources.lib.common as common\nimport resources.lib.cache as cache\n@@ -15,6 +17,18 @@ from .paths import (VIDEO_LIST_PARTIAL_PATHS, SEASONS_PARTIAL_PATHS,\nfrom .exceptions import InvalidVideoListTypeError, LoginFailedError, APIError\n+def catch_api_errors(func):\n+ \"\"\"Decorator that catches API errors and displays a notification\"\"\"\n+ # pylint: disable=missing-docstring\n+ @wraps(func)\n+ def api_error_wrapper(*args, **kwargs):\n+ try:\n+ return func(*args, **kwargs)\n+ except APIError as exc:\n+ ui.show_notification(common.get_local_string(30118).format(exc))\n+ return api_error_wrapper\n+\n+\ndef activate_profile(profile_id):\n\"\"\"Activate the profile with the given ID\"\"\"\nif common.make_call('activate_profile', profile_id):\n@@ -67,7 +81,7 @@ def root_lists():\n['displayName', 'context', 'id', 'index', 'length', 'genreId']]] +\n# Titles of first 4 videos in each video list\n[[{'from': 0, 'to': 40},\n- {'from': 0, 'to': 3}, 'reference', 'title']] +\n+ {'from': 0, 'to': 3}, 'reference', ['title', 'summary']]] +\n# Art for first video in each video list\n# (will be displayed as video list art)\nbuild_paths([{'from': 0, 'to': 40},\n@@ -129,7 +143,7 @@ def genre(genre_id):\nbuild_paths(['genres', genre_id, 'rw',\n{\"from\": 0, \"to\": 50},\n{\"from\": 0, \"to\": 3}, \"reference\"],\n- [['title']] + ART_PARTIAL_PATHS) +\n+ [['title', 'summary']] + ART_PARTIAL_PATHS) +\n# IDs and names of subgenres\n[['genres', genre_id, 'subgenres', {'from': 0, 'to': 30},\n['id', 'name']]]))\n@@ -207,6 +221,7 @@ def mylist_items():\nreturn []\n+@catch_api_errors\ndef rate(videoid, rating):\n\"\"\"Rate a video on Netflix\"\"\"\ncommon.debug('Rating {} as {}'.format(videoid.value, rating))\n@@ -218,8 +233,10 @@ def rate(videoid, rating):\n'params': {\n'titleid': videoid.value,\n'rating': rating}})\n+ ui.show_notification(common.get_local_string(30127).format(rating * 2))\n+@catch_api_errors\ndef update_my_list(videoid, operation):\n\"\"\"Call API to update my list with either add or remove action\"\"\"\ncommon.debug('My List: {} {}'.format(operation, videoid))\n@@ -228,7 +245,6 @@ def update_my_list(videoid, operation):\nvideoid_value = (videoid.movieid\nif videoid.mediatype == common.VideoId.MOVIE\nelse videoid.tvshowid)\n- try:\ncommon.make_call(\n'post',\n{'component': 'update_my_list',\n@@ -236,8 +252,6 @@ def update_my_list(videoid, operation):\n'operation': operation,\n'videoId': int(videoid_value)}})\nui.show_notification(common.get_local_string(30119))\n- except APIError as exc:\n- ui.show_notification(common.get_local_string(30118).format(exc))\ntry:\ng.CACHE.invalidate_entry(cache.CACHE_COMMON, list_id_for_type('queue'))\nexcept InvalidVideoListTypeError:\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/misc_utils.py",
"new_path": "resources/lib/common/misc_utils.py",
"diff": "@@ -204,3 +204,10 @@ def merge_dicts(dict_to_merge, merged_dict):\nelse:\nmerged_dict[key] = value\nreturn merged_dict\n+\n+\n+def any_value_except(mapping, excluded_key):\n+ \"\"\"Return a random value from a dict that is not associated with\n+ excluded_key. Raises StopIteration if there are no other keys than\n+ excluded_key\"\"\"\n+ return next(mapping[key] for key in mapping if key != excluded_key)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/pathops.py",
"new_path": "resources/lib/common/pathops.py",
"diff": "@@ -23,7 +23,7 @@ def get_path_safe(path, search_space, include_key=False, default=None):\nreturn default\n-def remove_path(path, search_space, remove_remnants=True):\n+def remove_path(path, search_space, is_empty, remove_remnants=True):\n\"\"\"Remove a value from a nested dict by following a path.\nAlso removes remaining empty dicts in the hierarchy if remove_remnants\nis True\"\"\"\n@@ -31,8 +31,8 @@ def remove_path(path, search_space, remove_remnants=True):\nif len(path) == 1:\ndel search_space[path[0]]\nelse:\n- remove_path(path[1:], search_space[path[0]])\n- if remove_remnants and not search_space[path[0]]:\n+ remove_path(path[1:], search_space[path[0]], is_empty)\n+ if remove_remnants and is_empty(search_space[path[0]]):\ndel search_space[path[0]]\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/videoid.py",
"new_path": "resources/lib/common/videoid.py",
"diff": "@@ -4,6 +4,8 @@ from __future__ import unicode_literals\nfrom functools import wraps\n+from .logging import debug\n+\nclass InvalidVideoId(Exception):\n\"\"\"The provided video id is not valid\"\"\"\n@@ -39,9 +41,7 @@ class VideoId(object):\n}\ndef __init__(self, **kwargs):\n- self._id_values = (kwargs.get('videoid'), kwargs.get('movieid'),\n- kwargs.get('episodeid'), kwargs.get('seasonid'),\n- kwargs.get('tvshowid'))\n+ self._id_values = _get_unicode_kwargs(kwargs)\nself._validate()\ndef _validate(self):\n@@ -56,14 +56,28 @@ class VideoId(object):\n@classmethod\ndef from_path(cls, pathitems):\n\"\"\"Create a VideoId instance from pathitems\"\"\"\n- if pathitems[0] == 'movie':\n+ if pathitems[0] == VideoId.MOVIE:\nreturn cls(movieid=pathitems[1])\n- elif pathitems[0] == 'show':\n+ elif pathitems[0] == VideoId.SHOW:\nreturn cls(tvshowid=_path_attr(pathitems, 1),\nseasonid=_path_attr(pathitems, 3),\nepisodeid=_path_attr(pathitems, 5))\nreturn cls(videoid=pathitems[0])\n+ @classmethod\n+ def from_videolist_item(cls, video):\n+ \"\"\"Create a VideoId from a video item contained in a\n+ videolist path response\"\"\"\n+ mediatype = video['summary']['type']\n+ video_id = video['summary']['id']\n+ if mediatype == VideoId.MOVIE:\n+ return cls(movieid=video_id)\n+ elif mediatype == VideoId.SHOW:\n+ return cls(tvshowid=video_id)\n+ else:\n+ raise InvalidVideoId(\n+ 'Can only construct a VideoId from a show or movie item')\n+\n@property\ndef value(self):\n\"\"\"The value of this VideoId\"\"\"\n@@ -151,6 +165,20 @@ class VideoId(object):\nreturn type(self)(tvshowid=self.tvshowid, seasonid=self.seasonid,\nepisodeid=unicode(episodeid))\n+ def derive_parent(self, depth):\n+ \"\"\"Returns a new videoid for the parent mediatype (season for episodes,\n+ show for seasons) that is at the depth's level of the mediatype\n+ hierarchy or this instance if there is no parent mediatype.\"\"\"\n+ if self.mediatype == VideoId.SEASON:\n+ return type(self)(tvshowid=self.tvshowid)\n+ if self.mediatype == VideoId.EPISODE:\n+ if depth == 0:\n+ return type(self)(tvshowid=self.tvshowid)\n+ if depth == 1:\n+ return type(self)(tvshowid=self.tvshowid,\n+ seasonid=self.seasonid)\n+ return self\n+\ndef _assigned_id_values(self):\n\"\"\"Return a list of all id_values that are not None\"\"\"\nreturn [id_value\n@@ -171,6 +199,15 @@ class VideoId(object):\nreturn not self.__eq__(other)\n+def _get_unicode_kwargs(kwargs):\n+ return tuple((unicode(kwargs[idpart])\n+ if kwargs.get(idpart)\n+ else None)\n+ for idpart\n+ in ['videoid', 'movieid', 'episodeid', 'seasonid',\n+ 'tvshowid'])\n+\n+\ndef _path_attr(pathitems, index):\nreturn pathitems[index] if len(pathitems) > index else None\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/context_menu.py",
"new_path": "resources/lib/kodi/context_menu.py",
"diff": "@@ -44,13 +44,12 @@ def generate_context_menu_items(videoid):\nitems = _generate_library_ctx_items(videoid)\nif videoid.mediatype != common.VideoId.SEASON:\n- items.append(_ctx_item('rate', videoid))\n+ items.insert(0, _ctx_item('rate', videoid))\nif videoid.mediatype in [common.VideoId.MOVIE, common.VideoId.SHOW]:\nlist_action = ('remove_from_list'\nif videoid.value in api.mylist_items()\nelse 'add_to_list')\n- # Put this as first item\nitems.insert(0, _ctx_item(list_action, videoid))\nreturn items\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "@@ -55,16 +55,25 @@ def _get_library_entry(videoid):\nreturn (common.get_path(videoid.to_list(), g.library()),\nvideoid.mediatype)\nelif videoid.mediatype == common.VideoId.SHOW:\n- return (g.library()[videoid.tvshowid].values()[0].values()[0],\n+ return (\n+ _any_child_library_entry(\n+ _any_child_library_entry(g.library()[videoid.tvshowid])),\ncommon.VideoId.EPISODE)\n- elif videoid.mediatype == common.VideoId.SHOW:\n- return (g.library()[videoid.tvshowid][videoid.seasonid].values()[0],\n+ elif videoid.mediatype == common.VideoId.SEASON:\n+ return (\n+ _any_child_library_entry(\n+ g.library()[videoid.tvshowid][videoid.seasonid]),\ncommon.VideoId.EPISODE)\nelse:\nraise ItemNotFound('No items of type {} in library'\n.format(videoid.mediatype))\n+def _any_child_library_entry(library_entry):\n+ \"\"\"Return a random library entry that is a child of library_entry\"\"\"\n+ return common.any_value_except(library_entry, 'videoid')\n+\n+\ndef _get_item(mediatype, filename):\nexported_filepath = os.path.normcase(common.translate_path(filename))\nfor library_item in common.get_library_items(mediatype):\n@@ -123,8 +132,19 @@ def _remove_from_kodi_library(videoid):\n.format(exc))\n+def purge():\n+ \"\"\"Purge all items exported to Kodi library and delete internal library\n+ database\"\"\"\n+ common.debug('Purging library: {}'.format(g.library()))\n+ for library_item in g.library().values():\n+ execute_library_tasks(library_item['videoid'], remove_item,\n+ common.get_local_string(30030),\n+ sync_mylist=False)\n+\n+\ndef compile_tasks(videoid):\n\"\"\"Compile a list of tasks for items based on the videoid\"\"\"\n+ common.debug('Compiling library tasks for {}'.format(videoid))\nmetadata = api.metadata(videoid)\nif videoid.mediatype == common.VideoId.MOVIE:\nreturn _create_movie_task(videoid, metadata)\n@@ -200,9 +220,9 @@ def export_item(item_task, library_home):\nlibrary_home, item_task['section'], item_task['destination'])\nexport_filename = os.path.join(\ndestination_folder, item_task['filename'] + '.strm')\n+ _add_to_library(item_task['videoid'], export_filename)\n_create_destination_folder(destination_folder)\n_write_strm_file(item_task, export_filename)\n- _add_to_library(item_task['videoid'], export_filename)\ncommon.debug('Exported {}'.format(item_task['title']))\n@@ -236,11 +256,15 @@ def _write_strm_file(item_task, export_filename):\ndef _add_to_library(videoid, export_filename):\n\"\"\"Add an exported file to the library\"\"\"\nlibrary_node = g.library()\n- for id_item in videoid.to_list():\n+ for depth, id_item in enumerate(videoid.to_list()):\nif id_item not in library_node:\n- library_node[id_item] = {}\n+ # No entry yet at this level, create a new one and assign\n+ # it an appropriate videoid for later reference\n+ library_node[id_item] = {\n+ 'videoid': videoid.derive_parent(depth)}\nlibrary_node = library_node[id_item]\nlibrary_node['file'] = export_filename\n+ library_node['videoid'] = videoid\ng.save_library()\n@@ -259,7 +283,7 @@ def remove_item(item_task, library_home=None):\nos.remove(common.translate_path(exported_filename))\nif not os.listdir(parent_folder):\nos.rmdir(parent_folder)\n- common.remove_path(id_path, g.library())\n+ common.remove_path(id_path, g.library(), lambda e: e.keys() == ['videoid'])\ng.save_library()\n@@ -292,3 +316,41 @@ def update_library():\n('XBMC.RunPlugin(plugin://{}/?action=export-new-episodes'\n'&inbackground=True)')\n.format(g.ADDON_ID))\n+\n+\n+\n+@update_kodi_library\n+def execute_library_tasks(videoid, task_handler, title, sync_mylist=True):\n+ \"\"\"Execute library tasks for videoid and show errors in foreground\"\"\"\n+ common.execute_tasks(title=title,\n+ tasks=compile_tasks(videoid),\n+ task_handler=task_handler,\n+ notify_errors=True,\n+ library_home=library_path())\n+ _sync_mylist(videoid, task_handler, sync_mylist)\n+\n+\n+@update_kodi_library\n+def execute_library_tasks_silently(videoid, task_handler, sync_mylist):\n+ \"\"\"Execute library tasks for videoid and don't show any GUI feedback\"\"\"\n+ # pylint: disable=broad-except\n+ for task in compile_tasks(videoid):\n+ try:\n+ task_handler(task, library_path())\n+ except Exception:\n+ import traceback\n+ common.error(traceback.format_exc())\n+ common.error('{} of {} failed'\n+ .format(task_handler.__name__, task['title']))\n+ if sync_mylist:\n+ _sync_mylist(videoid, task_handler, sync_mylist)\n+\n+\n+def _sync_mylist(videoid, task_handler, enabled):\n+ \"\"\"Add or remove exported items to My List, if enabled in settings\"\"\"\n+ operation = {\n+ 'export_item': 'add',\n+ 'remove_item': 'remove'}.get(task_handler.__name__)\n+ if enabled and operation and g.ADDON.getSettingBool('mylist_library_sync'):\n+ common.debug('Syncing my list due to change of Kodi library')\n+ api.update_my_list(videoid, operation)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/ui/dialogs.py",
"new_path": "resources/lib/kodi/ui/dialogs.py",
"diff": "@@ -72,11 +72,16 @@ def ask_for_custom_title(original_title):\ntype=xbmcgui.INPUT_ALPHANUM) or original_title\n-def ask_for_removal_confirmation(title, year=None):\n+def ask_for_removal_confirmation():\n\"\"\"Ask the user to finally remove title from the Kodi library\"\"\"\n- return xbmcgui.Dialog().yesno(\n- heading=common.get_local_string(30047),\n- line1=title + (' ({})'.format(year) if year else ''))\n+ return ask_for_confirmation(\n+ common.get_local_string(30047),\n+ common.get_local_string(30124))\n+\n+\n+def ask_for_confirmation(title, message):\n+ \"\"\"Ask the user to finally remove title from the Kodi library\"\"\"\n+ return xbmcgui.Dialog().yesno(heading=title, line1=message)\ndef show_error_info(title, message, unknown_error=False, netflix_error=False):\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/library.py",
"new_path": "resources/lib/navigation/library.py",
"diff": "@@ -6,6 +6,7 @@ from __future__ import unicode_literals\nfrom resources.lib. globals import g\nimport resources.lib.common as common\nimport resources.lib.api.shakti as api\n+import resources.lib.kodi.ui as ui\nimport resources.lib.kodi.library as library\n@@ -20,19 +21,20 @@ class LibraryActionExecutor(object):\[email protected]_video_id(path_offset=1)\ndef export(self, videoid):\n\"\"\"Export an item to the Kodi library\"\"\"\n- _execute_library_tasks(videoid, library.export_item,\n+ library.execute_library_tasks(videoid, library.export_item,\ncommon.get_local_string(30018))\[email protected]_video_id(path_offset=1)\ndef remove(self, videoid):\n\"\"\"Remove an item from the Kodi library\"\"\"\n- _execute_library_tasks(videoid, library.remove_item,\n+ if ui.ask_for_removal_confirmation():\n+ library.execute_library_tasks(videoid, library.remove_item,\ncommon.get_local_string(30030))\[email protected]_video_id(path_offset=1)\ndef update(self, videoid):\n\"\"\"Update an item in the Kodi library\"\"\"\n- _execute_library_tasks(videoid, library.update_item,\n+ library.execute_library_tasks(videoid, library.update_item,\ncommon.get_local_string(30061))\[email protected]_video_id(path_offset=1)\n@@ -41,7 +43,7 @@ class LibraryActionExecutor(object):\n(without GUI feedback). This will ignore the setting for syncing my\nlist and Kodi library and do no sync, if not explicitly asked to.\"\"\"\n# pylint: disable=broad-except\n- _execute_library_tasks_silently(\n+ library.execute_library_tasks_silently(\nvideoid, library.export_item,\nself.params.get('sync_mylist', False))\n@@ -50,7 +52,7 @@ class LibraryActionExecutor(object):\n\"\"\"Silently remove an item from the Kodi library\n(without GUI feedback). This will ignore the setting for syncing my\nlist and Kodi library and do no sync, if not explicitly asked to.\"\"\"\n- _execute_library_tasks_silently(\n+ library.execute_library_tasks_silently(\nvideoid, library.remove_item,\nself.params.get('sync_mylist', False))\n@@ -59,43 +61,29 @@ class LibraryActionExecutor(object):\n\"\"\"Silently update an item in the Kodi library\n(without GUI feedback). This will ignore the setting for syncing my\nlist and Kodi library and do no sync, if not explicitly asked to.\"\"\"\n- _execute_library_tasks_silently(\n+ library.execute_library_tasks_silently(\nvideoid, library.update_item,\nself.params.get('sync_mylist', False))\n-\[email protected]_kodi_library\n-def _execute_library_tasks(videoid, task_handler, title):\n- \"\"\"Execute library tasks for videoid and show errors in foreground\"\"\"\n- common.execute_tasks(title=title,\n- tasks=library.compile_tasks(videoid),\n- task_handler=task_handler,\n- notify_errors=True,\n- library_home=library.library_path())\n- _sync_mylist(videoid, task_handler)\n-\n-\[email protected]_kodi_library\n-def _execute_library_tasks_silently(videoid, task_handler, sync_mylist):\n- \"\"\"Execute library tasks for videoid and don't show any GUI feedback\"\"\"\n- # pylint: disable=broad-except\n- for task in library.compile_tasks(videoid):\n- try:\n- task_handler(task, library.library_path())\n- except Exception:\n- import traceback\n- common.error(traceback.format_exc())\n- common.error('{} of {} failed'\n- .format(task_handler.__name__, task['title']))\n- if sync_mylist:\n- _sync_mylist(videoid, task_handler)\n-\n-\n-def _sync_mylist(videoid, task_handler):\n- \"\"\"Add or remove exported items to My List, if enabled in settings\"\"\"\n- operation = {\n- 'export_item': 'add',\n- 'remove_item': 'remove'}.get(task_handler.__name__)\n- if operation and g.ADDON.getSettingBool('mylist_library_sync'):\n- common.debug('Syncing my list due to change of Kodi library')\n- api.update_my_list(videoid, operation)\n+ def initial_mylist_sync(self, pathitems):\n+ \"\"\"Perform an initial sync of My List and the Kodi library\"\"\"\n+ # pylint: disable=unused-argument\n+ do_it = ui.ask_for_confirmation(common.get_local_string(30122),\n+ common.get_local_string(30123))\n+ if not do_it or not g.ADDON.getSettingBool('mylist_library_sync'):\n+ return\n+\n+ common.debug('Performing full sync from My List to Kodi library')\n+ library.purge()\n+ for videoid in api.video_list(\n+ api.list_id_for_type('queue')).videoids:\n+ library.execute_library_tasks(videoid, library.export_item,\n+ common.get_local_string(30018),\n+ sync_mylist=False)\n+\n+ def purge(self, pathitems):\n+ \"\"\"Delete all previously exported items from the Kodi library\"\"\"\n+ # pylint: disable=unused-argument\n+ if ui.ask_for_confirmation(common.get_local_string(30125),\n+ common.get_local_string(30126)):\n+ library.purge()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/navigation/player.py",
"new_path": "resources/lib/navigation/player.py",
"diff": "@@ -14,8 +14,7 @@ import resources.lib.kodi.ui as ui\nfrom resources.lib.services.playback import get_timeline_markers\nSERVICE_URL_FORMAT = 'http://localhost:{port}'\n-MANIFEST_PATH_FORMAT = ('/manifest?id={videoid}'\n- '&dolby={enable_dolby}&hevc={enable_hevc}')\n+MANIFEST_PATH_FORMAT = '/manifest?id={videoid}'\nLICENSE_PATH_FORMAT = '/license?id={videoid}'\nINPUTSTREAM_SERVER_CERTIFICATE = '''Cr0CCAMSEOVEukALwQ8307Y2+LVP+0MYh/HPkwUijg\n@@ -73,11 +72,7 @@ def get_inputstream_listitem(videoid):\nfor playback of the given video_id\"\"\"\nservice_url = SERVICE_URL_FORMAT.format(\nport=g.ADDON.getSetting('msl_service_port'))\n- manifest_path = MANIFEST_PATH_FORMAT.format(\n- videoid=videoid.value,\n- enable_dolby=g.ADDON.getSetting('enable_dolby_sound'),\n- enable_hevc=g.ADDON.getSetting('enable_hevc_profiles'))\n-\n+ manifest_path = MANIFEST_PATH_FORMAT.format(videoid=videoid.value)\nlist_item = xbmcgui.ListItem(path=service_url + manifest_path,\noffscreen=True)\nlist_item.setContentLookup(False)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/settings.xml",
"new_path": "resources/settings.xml",
"diff": "<setting id=\"enablelibraryfolder\" type=\"bool\" label=\"30026\" default=\"false\"/>\n<setting id=\"customlibraryfolder\" type=\"folder\" label=\"30027\" enable=\"eq(-1,true)\" default=\"special://profile/addon_data/plugin.video.netflix\" source=\"auto\" option=\"writeable\" subsetting=\"true\"/>\n<setting id=\"mylist_library_sync\" type=\"bool\" label=\"30114\" default=\"false\"/>\n+ <setting id=\"initial_mylist_sync\" type=\"action\" label=\"30121\" action=\"RunPlugin(plugin://plugin.video.netflix/library/initial_mylist_sync)\" visible=\"eq(-1,true)\" subsetting=\"true\"/>\n+ <setting id=\"purge_library\" type=\"action\" label=\"30125\" action=\"RunPlugin(plugin://plugin.video.netflix/library/purge)\"/>\n<setting id=\"customexportname\" type=\"bool\" label=\"No longer in use\" default=\"true\" visible=\"false\"/>\n<setting id=\"invalidate_cache_on_mylist_modify\" type=\"bool\" label=\"No longer in use\" default=\"true\" visible=\"false\"/>\n<setting label=\"30065\" type=\"lsep\"/>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add full sync of my list to Kodi library. Add library purge. Reorder context menu items. Improve GUI feedback on API actions (rate, ...). Tons of bugfixes |
105,989 | 04.11.2018 18:08:43 | -3,600 | 6932ab9cde41b427f47bf0ab78220ddc4bd17c50 | Bump version. This should be ready for beta trials | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.14.0~beta1\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.14.0~beta2\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Bump version. This should be ready for beta trials |
105,989 | 05.11.2018 17:58:03 | -3,600 | 86bb743b213538410cb29b184136cdfa7150f40c | Fix wrong catching of KeyErrors | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "@@ -66,13 +66,12 @@ def route(pathitems):\nroot_handler = pathitems[0] if pathitems else g.MODE_DIRECTORY\nif root_handler == g.MODE_PLAY:\nplayer.play(pathitems=pathitems[1:])\n+ elif root_handler not in NAV_HANDLERS:\n+ raise nav.InvalidPathError(\n+ 'No root handler for path {}'.format('/'.join(pathitems)))\nelse:\n- try:\nnav.execute(NAV_HANDLERS[root_handler], pathitems[1:],\ng.REQUEST_PARAMS)\n- except KeyError:\n- raise nav.InvalidPathError(\n- 'No root handler for path {}'.format('/'.join(pathitems)))\nif __name__ == '__main__':\n"
},
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.14.0~beta2\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.14.0~beta3\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix wrong catching of KeyErrors |
105,989 | 05.11.2018 21:23:03 | -3,600 | 909e1621465a66760399f82223bde7353baaf992 | Use xbmcvfs instead of native os | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -21,6 +21,7 @@ except ImportError:\nimport xbmc\nimport xbmcgui\n+import xbmcvfs\nCACHE_COMMON = 'cache_common'\nCACHE_GENRES = 'cache_genres'\n@@ -216,24 +217,26 @@ class Cache(object):\ndef _get_from_disk(self, bucket, identifier):\n\"\"\"Load a cache entry from disk and add it to the in memory bucket\"\"\"\n- cache_filename = self._entry_filename(bucket, identifier)\n+ handle = xbmcvfs.File(self._entry_filename(bucket, identifier), 'r')\ntry:\n- with open(cache_filename, 'r') as cache_file:\n- cache_entry = pickle.load(cache_file)\n+ return pickle.load(handle)\nexcept Exception:\nraise CacheMiss()\n- return cache_entry\n+ finally:\n+ handle.close()\ndef _add_to_disk(self, bucket, identifier, cache_entry):\n\"\"\"Write a cache entry to disk\"\"\"\n# pylint: disable=broad-except\ncache_filename = self._entry_filename(bucket, identifier)\n+ handle = xbmcvfs.File(cache_filename, 'w')\ntry:\n- with open(cache_filename, 'w') as cache_file:\n- pickle.dump(cache_entry, cache_file)\n+ return pickle.dump(cache_entry, handle)\nexcept Exception as exc:\nself.common.error('Failed to write cache entry to {}: {}'\n.format(cache_filename, exc))\n+ finally:\n+ handle.close()\ndef _entry_filename(self, bucket, identifier):\nif bucket == CACHE_LIBRARY:\n@@ -242,8 +245,7 @@ class Cache(object):\nfile_loc = [os.path.dirname(self.cache_path), 'library.ndb2']\nelse:\nfile_loc = [self.cache_path, bucket, '{}.cache'.format(identifier)]\n- return self.common.translate_path(\n- os.path.join(*file_loc))\n+ return xbmc.translatePath(os.path.join(*file_loc))\ndef _persist_bucket(self, bucket, contents):\n# pylint: disable=broad-except\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/fileops.py",
"new_path": "resources/lib/common/fileops.py",
"diff": "@@ -5,6 +5,7 @@ from __future__ import unicode_literals\nimport os\nimport xbmc\n+import xbmcvfs\nfrom resources.lib.globals import g\n@@ -39,9 +40,12 @@ def save_file(filename, content, mode='w'):\n:param filename: The filename\n:param content: The content of the file\n\"\"\"\n- with open(translate_path(os.path.join(g.DATA_PATH, filename)),\n- mode) as file_handle:\n+ file_handle = xbmcvfs.File(\n+ xbmc.translatePath(os.path.join(g.DATA_PATH, filename)), mode)\n+ try:\nfile_handle.write(content.encode('utf-8'))\n+ finally:\n+ file_handle.close()\ndef load_file(filename, mode='r'):\n@@ -50,9 +54,12 @@ def load_file(filename, mode='r'):\n:param filename: The file to load\n:return: The content of the file\n\"\"\"\n- with open(translate_path(os.path.join(g.DATA_PATH, filename)),\n- mode) as file_handle:\n- return file_handle.read().decode('utf-8')\n+ file_handle = xbmcvfs.File(\n+ xbmc.translatePath(os.path.join(g.DATA_PATH, filename)), mode)\n+ try:\n+ file_handle.read().decode('utf-8')\n+ finally:\n+ file_handle.close()\ndef list_dir(data_path=g.DATA_PATH):\n@@ -60,9 +67,4 @@ def list_dir(data_path=g.DATA_PATH):\nList the contents of a folder\n:return: The contents of the folder\n\"\"\"\n- return os.listdir(data_path)\n-\n-\n-def translate_path(path):\n- \"\"\"Translate path if it contains special:// and decode it to unicode\"\"\"\n- return xbmc.translatePath(path).decode('utf-8')\n+ return xbmcvfs.listdir(xbmc.translatePath(data_path))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/storage.py",
"new_path": "resources/lib/common/storage.py",
"diff": "\"\"\"Generic persistent on disk storage\"\"\"\nfrom __future__ import unicode_literals\n-import os\nimport json\n-from resources.lib.globals import g\n-from .logging import debug, error\n-from .fileops import translate_path\n+from .logging import debug, warn\n+from .fileops import save_file, load_file\nclass PersistentStorage(object):\n@@ -22,8 +20,7 @@ class PersistentStorage(object):\n\"\"\"\ndef __init__(self, storage_id):\nself.storage_id = storage_id\n- self.backing_file = translate_path(\n- os.path.join(g.DATA_PATH, self.storage_id + '.ndb'))\n+ self.backing_file = self.storage_id + '.ndb'\nself._contents = {}\nself._dirty = True\ndebug('Instantiated {}'.format(self.storage_id))\n@@ -60,8 +57,7 @@ class PersistentStorage(object):\n\"\"\"\nWrite current contents to disk\n\"\"\"\n- with open(self.backing_file, 'w') as file_handle:\n- json.dump(self._contents, file_handle)\n+ save_file(self.backing_file, json.dumps(self._contents))\ndebug('Committed changes to backing file')\ndef clear(self):\n@@ -72,11 +68,12 @@ class PersistentStorage(object):\nself.commit()\ndef _load_from_disk(self):\n+ # pylint: disable=broad-except\ndebug('Trying to load contents from disk')\ntry:\n- with open(self.backing_file, 'r') as file_handle:\n- self._contents = json.load(file_handle)\n- except IOError:\n- error('Backing file does not exist or is not accessible')\n+ self._contents = json.loads(load_file(self.backing_file))\n+ debug('Loaded contents from backing file: {}'\n+ .format(self._contents))\n+ except Exception:\n+ warn('Backing file does not exist or is not readable')\nself._dirty = False\n- debug('Loaded contents from backing file: {}'.format(self._contents))\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "@@ -4,11 +4,11 @@ from __future__ import unicode_literals\nimport os\nimport re\n-import codecs\nfrom datetime import datetime, timedelta\nfrom functools import wraps\nimport xbmc\n+import xbmcvfs\nfrom resources.lib.globals import g\nimport resources.lib.common as common\n@@ -75,7 +75,7 @@ def _any_child_library_entry(library_entry):\ndef _get_item(mediatype, filename):\n- exported_filepath = os.path.normcase(common.translate_path(filename))\n+ exported_filepath = os.path.normcase(xbmc.translatePath(filename))\nfor library_item in common.get_library_items(mediatype):\nif os.path.normcase(library_item['file']) == exported_filepath:\nreturn common.get_library_item_details(\n@@ -228,29 +228,19 @@ def export_item(item_task, library_home):\ndef _create_destination_folder(destination_folder):\n\"\"\"Create destination folder, ignore error if it already exists\"\"\"\n- try:\n- os.makedirs(common.translate_path(destination_folder))\n- except OSError as exc:\n- if exc.errno != os.errno.EEXIST:\n- raise\n+ destination_folder = xbmc.translatePath(destination_folder)\n+ if not xbmcvfs.exists(destination_folder):\n+ xbmcvfs.mkdirs(destination_folder)\ndef _write_strm_file(item_task, export_filename):\n\"\"\"Write the playable URL to a strm file\"\"\"\n+ filehandle = xbmcvfs.File(xbmc.translatePath(export_filename), 'w')\ntry:\n- with codecs.open(common.translate_path(export_filename),\n- mode='w',\n- encoding='utf-8',\n- errors='replace') as filehandle:\n- filehandle.write(\n- common.build_url(videoid=item_task['videoid'],\n- mode=g.MODE_PLAY))\n- except OSError as exc:\n- if exc.errno == os.errno.EEXIST:\n- common.info('{} already exists, skipping export'\n- .format(export_filename))\n- else:\n- raise\n+ filehandle.write(common.build_url(videoid=item_task['videoid'],\n+ mode=g.MODE_PLAY).encode('utf-8'))\n+ finally:\n+ filehandle.close()\ndef _add_to_library(videoid, export_filename):\n@@ -277,10 +267,10 @@ def remove_item(item_task, library_home=None):\n.format(item_task['title']))\nreturn\nid_path = item_task['videoid'].to_list()\n- exported_filename = common.translate_path(\n+ exported_filename = xbmc.translatePath(\ncommon.get_path(id_path, g.library())['file'])\nparent_folder = os.path.dirname(exported_filename)\n- os.remove(common.translate_path(exported_filename))\n+ os.remove(xbmc.translatePath(exported_filename))\nif not os.listdir(parent_folder):\nos.rmdir(parent_folder)\ncommon.remove_path(id_path, g.library(), lambda e: e.keys() == ['videoid'])\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/cookies.py",
"new_path": "resources/lib/services/cookies.py",
"diff": "@@ -9,6 +9,9 @@ try:\nexcept ImportError:\nimport pickle\n+import xbmc\n+import xbmcvfs\n+\nfrom resources.lib.globals import g\nimport resources.lib.common as common\n@@ -27,12 +30,13 @@ def save(account_hash, cookie_jar):\n\"\"\"Save a cookie jar to file and in-memory storage\"\"\"\n# pylint: disable=broad-except\ng.COOKIES[account_hash] = cookie_jar\n+ cookie_file = xbmcvfs.File(cookie_filename(account_hash), 'w')\ntry:\n- with open(cookie_filename(account_hash), 'wb') as cookie_file:\n- common.debug('Saving cookies to file')\npickle.dump(cookie_jar, cookie_file)\nexcept Exception as exc:\ncommon.error('Failed to save cookies to file: {exc}', exc)\n+ finally:\n+ cookie_file.close()\ndef delete(account_hash):\n@@ -40,7 +44,7 @@ def delete(account_hash):\n# pylint: disable=broad-except\ndel g.COOKIES[account_hash]\ntry:\n- os.remove(cookie_filename(account_hash))\n+ xbmcvfs.delete(cookie_filename(account_hash))\nexcept Exception as exc:\ncommon.error('Failed to delete cookies on disk: {exc}', exc)\n@@ -60,13 +64,15 @@ def load(account_hash):\ndef load_from_file(account_hash):\n\"\"\"Load cookies for a given account from file\"\"\"\n- try:\n- with open(cookie_filename(account_hash), 'rb') as cookie_file:\ncommon.debug('Loading cookies from file')\n+ cookie_file = xbmcvfs.File(cookie_filename(account_hash), 'r')\n+ try:\nreturn pickle.load(cookie_file)\nexcept Exception as exc:\ncommon.error('Failed to load cookies from file: {exc}', exc)\nraise MissingCookiesError()\n+ finally:\n+ cookie_file.close()\ndef expired(cookie_jar):\n@@ -81,4 +87,4 @@ def expired(cookie_jar):\ndef cookie_filename(account_hash):\n\"\"\"Return a filename to store cookies for a given account\"\"\"\n- return common.translate_path('{}_{}'.format(g.COOKIE_PATH, account_hash))\n+ return xbmc.translatePath('{}_{}'.format(g.COOKIE_PATH, account_hash))\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Use xbmcvfs instead of native os |
105,989 | 05.11.2018 21:54:14 | -3,600 | 66e3cfbeae7130985972a1fc0ae94bdfbb7dbba5 | Fix logout. Make VideoList construction safe. Fix Kids profiles (no characters list for now, sorry) | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.14.0~beta3\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.14.0~beta4\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/language/resource.language.en_gb/strings.po",
"new_path": "resources/language/resource.language.en_gb/strings.po",
"diff": "@@ -531,3 +531,7 @@ msgstr \"\"\nmsgctxt \"#30127\"\nmsgid \"Awarded rating of {}\"\nmsgstr \"\"\n+\n+msgctxt \"#30128\"\n+msgid \"No contained titles yet...\"\n+msgstr \"\"\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/data_types.py",
"new_path": "resources/lib/api/data_types.py",
"diff": "@@ -56,11 +56,9 @@ class VideoList(object):\nself.videos = OrderedDict(\nresolve_refs(self.data['lists'][self.id.value], self.data))\nself.artitem = next(self.videos.itervalues())\n- self.contained_titles = [video['title']\n- for video in self.videos.itervalues()]\n+ self.contained_titles = _get_titles(self.videos)\ntry:\n- self.videoids = [common.VideoId.from_videolist_item(video)\n- for video in self.videos.itervalues()]\n+ self.videoids = _get_videoids(self.videos)\nexcept KeyError:\nself.videoids = None\n@@ -83,11 +81,9 @@ class SearchVideoList(object):\nself.videos = OrderedDict(\nresolve_refs(self.data['search']['byReference'].values()[0],\nself.data))\n- self.videoids = [common.VideoId.from_videolist_item(video)\n- for video in self.videos.itervalues()]\n+ self.videoids = _get_videoids(self.videos)\nself.artitem = next(self.videos.itervalues(), None)\n- self.contained_titles = [video['title']\n- for video in self.videos.itervalues()]\n+ self.contained_titles = _get_titles(self.videos)\ndef __getitem__(self, key):\nreturn _check_sentinel(self.data['search'][key])\n@@ -104,11 +100,9 @@ class CustomVideoList(object):\nself.data = path_response\nself.title = common.get_local_string(30048)\nself.videos = self.data['videos']\n- self.videoids = [common.VideoId.from_videolist_item(video)\n- for video in self.videos.itervalues()]\n+ self.videoids = _get_videoids(self.videos)\nself.artitem = next(self.videos.itervalues())\n- self.contained_titles = [video['title']\n- for video in self.videos.itervalues()]\n+ self.contained_titles = _get_titles(self.videos)\ndef __getitem__(self, key):\nreturn _check_sentinel(self.data[key])\n@@ -143,3 +137,22 @@ def _check_sentinel(value):\nreturn (None\nif isinstance(value, dict) and value.get('$type') == 'sentinel'\nelse value)\n+\n+\n+def _get_title(video):\n+ \"\"\"Get the title of a video (either from direct key or nested within\n+ summary)\"\"\"\n+ return video.get('title', video.get('summary', {}).get('title'))\n+\n+\n+def _get_titles(videos):\n+ \"\"\"Return a list of videos' titles\"\"\"\n+ return [_get_title(video)\n+ for video in videos.itervalues()\n+ if _get_title(video)]\n+\n+\n+def _get_videoids(videos):\n+ \"\"\"Return a list of VideoId objects for the videos\"\"\"\n+ return [common.VideoId.from_videolist_item(video)\n+ for video in videos.itervalues()]\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/api/paths.py",
"new_path": "resources/lib/api/paths.py",
"diff": "@@ -106,6 +106,9 @@ def iterate_references(source):\npath = reference_path(ref)\nif path is None:\nbreak\n+ elif path[0] == 'characters':\n+ # TODO: Implement handling of character references in Kids profiles\n+ continue\nelse:\nyield (index, path)\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -64,8 +64,11 @@ def parse_info(videoid, item, raw_data):\n# Special handling for VideoLists\nreturn {\n'mediatype': 'video',\n- 'plot': common.get_local_string(30087).format(\n+ 'plot':\n+ common.get_local_string(30087).format(\n', '.join(item.contained_titles))\n+ if item.contained_titles\n+ else common.get_local_string(30087)\n}, {}\ninfos = {'mediatype': ('tvshow'\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -24,6 +24,7 @@ BASE_URL = 'https://www.netflix.com'\nURLS = {\n'login': {'endpoint': '/login', 'is_api_call': False},\n+ 'logout': {'endpoint': '/SignOut', 'is_api_call': False},\n'shakti': {'endpoint': '/pathEvaluator', 'is_api_call': True},\n'browse': {'endpoint': '/browse', 'is_api_call': False},\n'profiles': {'endpoint': '/profiles/manage', 'is_api_call': False},\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix logout. Make VideoList construction safe. Fix Kids profiles (no characters list for now, sorry) |
105,989 | 05.11.2018 22:02:20 | -3,600 | 7cd06dbfd8654a62063dca19781388bd742f6ce3 | Fix MSL android_crypto. Add safeguard for deleting non-existent files. | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/library.py",
"new_path": "resources/lib/kodi/library.py",
"diff": "@@ -260,7 +260,7 @@ def _add_to_library(videoid, export_filename):\ndef remove_item(item_task, library_home=None):\n\"\"\"Remove an item from the library and delete if from disk\"\"\"\n- # pylint: disable=unused-argument\n+ # pylint: disable=unused-argument, broad-except\ncommon.debug('Removing {} from library'.format(item_task['title']))\nif not is_in_library(item_task['videoid']):\ncommon.warn('cannot remove {}, item not in library'\n@@ -270,9 +270,13 @@ def remove_item(item_task, library_home=None):\nexported_filename = xbmc.translatePath(\ncommon.get_path(id_path, g.library())['file'])\nparent_folder = os.path.dirname(exported_filename)\n- os.remove(xbmc.translatePath(exported_filename))\n+ try:\n+ xbmcvfs.delete(xbmc.translatePath(exported_filename))\nif not os.listdir(parent_folder):\nos.rmdir(parent_folder)\n+ except Exception:\n+ common.debug('Cannot delete {}, file does not exist'\n+ .format(exported_filename))\ncommon.remove_path(id_path, g.library(), lambda e: e.keys() == ['videoid'])\ng.save_library()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/android_crypto.py",
"new_path": "resources/lib/services/msl/android_crypto.py",
"diff": "@@ -83,9 +83,10 @@ class AndroidMSLCrypto(MSLBaseCrypto):\n:return: Serialized JSON String of the encryption Envelope\n\"\"\"\ninit_vector = urandom(16)\n+ plaintext = plaintext.encode('utf-8')\n# Add PKCS5Padding\npad = 16 - len(plaintext) % 16\n- padded_data = plaintext + ''.join([chr(pad)] * pad)\n+ padded_data = plaintext + str('').join([chr(pad)] * pad)\nencrypted_data = self.crypto_session.Encrypt(self.key_id, padded_data,\ninit_vector)\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix MSL android_crypto. Add safeguard for deleting non-existent files. |
105,989 | 05.11.2018 23:09:39 | -3,600 | 05db034624992b1a5bc8fcda6241022259325cbe | Make getting interesting moment a safe operation | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/kodi/infolabels.py",
"new_path": "resources/lib/kodi/infolabels.py",
"diff": "@@ -141,7 +141,7 @@ def parse_art(videoid, item, raw_data):\nboxarts = common.get_multiple_paths(\npaths.ART_PARTIAL_PATHS[0] + ['url'], item)\ninteresting_moment = common.get_multiple_paths(\n- paths.ART_PARTIAL_PATHS[1] + ['url'], item)[paths.ART_SIZE_FHD]\n+ paths.ART_PARTIAL_PATHS[1] + ['url'], item, {}).get(paths.ART_SIZE_FHD)\nclearlogo = common.get_path_safe(\npaths.ART_PARTIAL_PATHS[3] + ['url'], item)\nfanart = common.get_path_safe(\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Make getting interesting moment a safe operation |
105,989 | 05.11.2018 23:19:35 | -3,600 | 1be56bb57bd05eae0c46f12f8ba38318d454efc6 | Fix broken fileops, remove log spam | [
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.14.0~beta4\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.14.0~beta5\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -219,7 +219,7 @@ class Cache(object):\n\"\"\"Load a cache entry from disk and add it to the in memory bucket\"\"\"\nhandle = xbmcvfs.File(self._entry_filename(bucket, identifier), 'r')\ntry:\n- return pickle.load(handle)\n+ return pickle.loads(handle.read())\nexcept Exception:\nraise CacheMiss()\nfinally:\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/common/fileops.py",
"new_path": "resources/lib/common/fileops.py",
"diff": "@@ -57,7 +57,7 @@ def load_file(filename, mode='r'):\nfile_handle = xbmcvfs.File(\nxbmc.translatePath(os.path.join(g.DATA_PATH, filename)), mode)\ntry:\n- file_handle.read().decode('utf-8')\n+ return file_handle.read().decode('utf-8')\nfinally:\nfile_handle.close()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/cookies.py",
"new_path": "resources/lib/services/cookies.py",
"diff": "@@ -67,7 +67,7 @@ def load_from_file(account_hash):\ncommon.debug('Loading cookies from file')\ncookie_file = xbmcvfs.File(cookie_filename(account_hash), 'r')\ntry:\n- return pickle.load(cookie_file)\n+ return pickle.loads(cookie_file.read())\nexcept Exception as exc:\ncommon.error('Failed to load cookies from file: {exc}', exc)\nraise MissingCookiesError()\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/nfsession.py",
"new_path": "resources/lib/services/nfsession.py",
"diff": "@@ -107,7 +107,6 @@ class NetflixSession(object):\nnew_session_data['active_profile']})\ncookies.save(self.account_hash, self.session.cookies)\n_update_esn(self.session_data['esn'])\n- common.debug('Set session data: {}'.format(self._session_data))\n@property\ndef auth_url(self):\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix broken fileops, remove log spam |
105,989 | 06.11.2018 00:46:16 | -3,600 | 54e15a539dc8d16c1a663f0f0278bac6f6546941 | Add override for stale cache locks | [
{
"change_type": "MODIFY",
"old_path": "resources/lib/cache.py",
"new_path": "resources/lib/cache.py",
"diff": "@@ -12,6 +12,7 @@ resources.lib.services.nfsession\nfrom __future__ import unicode_literals\nimport os\n+import sys\nfrom time import time\nfrom functools import wraps\ntry:\n@@ -33,7 +34,7 @@ CACHE_LIBRARY = 'library'\nBUCKET_NAMES = [CACHE_COMMON, CACHE_GENRES, CACHE_METADATA,\nCACHE_INFOLABELS, CACHE_ARTINFO, CACHE_LIBRARY]\n-BUCKET_LOCKED = 'LOCKED_BY_{}'\n+BUCKET_LOCKED = 'LOCKED_BY_{:04d}_AT_{}'\n# 100 years TTL should be close enough to infinite\nTTL_INFINITE = 60*60*24*365*100\n@@ -121,13 +122,20 @@ class Cache(object):\n# We have the self.common module injected as a dependency to work\n# around circular dependencies with gloabl variable initialization\nself.common = common\n+ self.plugin_handle = plugin_handle\nself.cache_path = cache_path\nself.ttl = ttl\nself.metadata_ttl = metadata_ttl\nself.buckets = {}\n- self.lock_marker = str(BUCKET_LOCKED.format(plugin_handle))\nself.window = xbmcgui.Window(10000)\n+ def lock_marker(self, bucket):\n+ \"\"\"Return a lock marker for this instance and the current time\"\"\"\n+ # Return maximum timestamp for library to prevent stale lock\n+ # overrides which may lead to inconsistencies\n+ timestamp = sys.maxint if bucket == CACHE_LIBRARY else int(time())\n+ return str(BUCKET_LOCKED.format(self.plugin_handle, timestamp))\n+\ndef get(self, bucket, identifier):\n\"\"\"Retrieve an item from a cache bucket\"\"\"\ntry:\n@@ -211,10 +219,14 @@ class Cache(object):\nself.common.debug('No instance of {} found. Creating new instance.'\n.format(bucket))\nbucket_instance = {}\n- self.window.setProperty(_window_property(bucket), self.lock_marker)\n+ self._lock(bucket)\nself.common.debug('Acquired lock on {}'.format(bucket))\nreturn bucket_instance\n+ def _lock(self, bucket):\n+ self.window.setProperty(_window_property(bucket),\n+ self.lock_marker(bucket))\n+\ndef _get_from_disk(self, bucket, identifier):\n\"\"\"Load a cache entry from disk and add it to the in memory bucket\"\"\"\nhandle = xbmcvfs.File(self._entry_filename(bucket, identifier), 'r')\n@@ -250,8 +262,13 @@ class Cache(object):\ndef _persist_bucket(self, bucket, contents):\n# pylint: disable=broad-except\nlock = self.window.getProperty(_window_property(bucket))\n- # pickle stored byte data, so we must compare against a str\n- if lock == self.lock_marker:\n+ # Only persist if we acquired the original lock or if the lock is older\n+ # than 15 seconds (override stale locks)\n+ is_own_lock = lock[:14] == self.lock_marker(bucket)[:14]\n+ is_stale_lock = int(lock[18:]) <= time() - 15\n+ if is_own_lock or is_stale_lock:\n+ if is_stale_lock:\n+ self.common.info('Overriding stale cache lock {}'.format(lock))\ntry:\nself.window.setProperty(_window_property(bucket),\npickle.dumps(contents))\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Add override for stale cache locks |
105,989 | 06.11.2018 00:58:38 | -3,600 | 52b58ef1ae53b2d587c1e7c63f2ce1c75e0ae5c8 | Fix android_crypto. Ignore invocations from extrafanart | [
{
"change_type": "MODIFY",
"old_path": "addon.py",
"new_path": "addon.py",
"diff": "@@ -69,6 +69,9 @@ def route(pathitems):\nelif root_handler not in NAV_HANDLERS:\nraise nav.InvalidPathError(\n'No root handler for path {}'.format('/'.join(pathitems)))\n+ elif root_handler == 'extrafanart':\n+ common.debug('Ignoring extrafanart invocation')\n+ xbmcplugin.endOfDirectory(handle=g.PLUGIN_HANDLE, succeeded=False)\nelse:\nnav.execute(NAV_HANDLERS[root_handler], pathitems[1:],\ng.REQUEST_PARAMS)\n"
},
{
"change_type": "MODIFY",
"old_path": "addon.xml",
"new_path": "addon.xml",
"diff": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n-<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.14.0~beta5\" provider-name=\"libdev + jojo + asciidisco\">\n+<addon id=\"plugin.video.netflix\" name=\"Netflix\" version=\"0.14.0~beta6\" provider-name=\"libdev + jojo + asciidisco\">\n<requires>\n<import addon=\"xbmc.python\" version=\"2.25.0\"/>\n<import addon=\"script.module.requests\" version=\"2.12.4\"/>\n"
},
{
"change_type": "MODIFY",
"old_path": "resources/lib/services/msl/android_crypto.py",
"new_path": "resources/lib/services/msl/android_crypto.py",
"diff": "@@ -4,6 +4,8 @@ from __future__ import unicode_literals\nfrom os import urandom\nimport base64\n+import json\n+\nimport xbmcdrm\nimport resources.lib.common as common\n@@ -93,14 +95,14 @@ class AndroidMSLCrypto(MSLBaseCrypto):\nif not encrypted_data:\nraise MSLError('Widevine CryptoSession encrypt failed!')\n- return {\n+ return json.dumps({\n'version': 1,\n'ciphertext': base64.standard_b64encode(encrypted_data),\n'sha256': 'AA==',\n'keyid': base64.standard_b64encode(self.key_id),\n# 'cipherspec' : 'AES/CBC/PKCS5Padding',\n'iv': base64.standard_b64encode(init_vector)\n- }\n+ })\ndef decrypt(self, init_vector, ciphertext):\n\"\"\"Decrypt a ciphertext\"\"\"\n"
}
] | Python | MIT License | castagnait/plugin.video.netflix | Fix android_crypto. Ignore invocations from extrafanart |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.