├── resources ├── __init__.py ├── lib │ ├── __init__.py │ └── constants.py ├── screenshot-01.jpg ├── screenshot-02.jpg ├── screenshot-03.jpg ├── settings.xml └── language │ └── resource.language.en_gb │ └── strings.po ├── fanart.jpg ├── icon.png ├── addon.xml ├── README.md ├── LICENSE.txt └── addon.py /resources/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /resources/lib/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /fanart.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/allejok96/plugin.video.jwb-unofficial/HEAD/fanart.jpg -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/allejok96/plugin.video.jwb-unofficial/HEAD/icon.png -------------------------------------------------------------------------------- /resources/screenshot-01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/allejok96/plugin.video.jwb-unofficial/HEAD/resources/screenshot-01.jpg -------------------------------------------------------------------------------- /resources/screenshot-02.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/allejok96/plugin.video.jwb-unofficial/HEAD/resources/screenshot-02.jpg -------------------------------------------------------------------------------- /resources/screenshot-03.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/allejok96/plugin.video.jwb-unofficial/HEAD/resources/screenshot-03.jpg -------------------------------------------------------------------------------- /resources/settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /addon.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | video 16 | 17 | 18 | 19 | Unofficial JW Broadcasting client 20 | Watch latest videos, play streaming channels and listen to audio recordings from JW Broadcasting. 21 | This is not an official plugin, please do not contact jw.org for support. 22 | all 23 | v1.15.2 (2021-05-30) 24 | - Fix always use last selected language bug 25 | 26 | 27 | icon.png 28 | fanart.jpg 29 | resources/screenshot-01.jpg 30 | resources/screenshot-02.jpg 31 | resources/screenshot-03.jpg 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /resources/language/resource.language.en_gb/strings.po: -------------------------------------------------------------------------------- 1 | # Not transifexically correct, but it works 2 | # And for some reason there must be an empty string at the start 3 | msgid "" 4 | msgstr "" 5 | 6 | msgctxt "#30000" 7 | msgid "Video Resolution" 8 | msgstr "" 9 | 10 | msgctxt "#30001" 11 | msgid "240p" 12 | msgstr "" 13 | 14 | msgctxt "#30002" 15 | msgid "360p" 16 | msgstr "" 17 | 18 | msgctxt "#30003" 19 | msgid "480p" 20 | msgstr "" 21 | 22 | msgctxt "#30004" 23 | msgid "720p" 24 | msgstr "" 25 | 26 | msgctxt "#30005" 27 | msgid "1080p" 28 | msgstr "" 29 | 30 | msgctxt "#30010" 31 | msgid "Language" 32 | msgstr "" 33 | 34 | msgctxt "#30011" 35 | msgid "Set Language ..." 36 | msgstr "" 37 | 38 | msgctxt "#30012" 39 | msgid "Display subtitles by default" 40 | msgstr "" 41 | 42 | msgctxt "#30013" 43 | msgid "-- Hidden item --" 44 | 45 | msgctxt "#30014" 46 | msgid "Have you already attended this year's convention?" 47 | msgstr "" 48 | 49 | msgctxt "#30015" 50 | msgid "Startup warning" 51 | msgstr "" 52 | 53 | msgctxt "#30016" 54 | msgid "Theocratic warning" 55 | msgstr "" 56 | 57 | msgctxt "#30020" 58 | msgid "This add-on is not supported by, or affiliated with the Watchtower society in any way.\n" 59 | "Please use the official JW Broadcasting app for your device, if available.\n" 60 | "Or consider buying a device that supports the JW Broadcasting or JW Library app.\n\n" 61 | "Since this add-on is homemade, you must choose if you are willing to trust it.\n" 62 | "- The add-on may not work as intended.\n" 63 | "- You may not get all the benefits of jw.org.\n" 64 | "- The spiritual food could in absolute worst case be tampered with.\n\n" 65 | "Please read the following Watchtower article before you make up your mind:\n" 66 | "[B]w18 April page 30[/B]\n\n" 67 | "This message will only be shown once." 68 | 69 | msgctxt "#30021" 70 | msgid "Play in another language" 71 | msgstr "" 72 | 73 | msgctxt "#30023" 74 | msgid "Shuffle this category" 75 | msgstr "" 76 | 77 | msgctxt "#30024" 78 | msgid "[audio only]" 79 | 80 | msgctxt "#30025" 81 | msgid "Connection error" 82 | msgstr "" 83 | 84 | msgctxt "#30026" 85 | msgid "Always use last selected language" 86 | msgstr "" 87 | 88 | msgctxt "#30027" 89 | msgid "Not available in selected language" 90 | msgstr "" 91 | -------------------------------------------------------------------------------- /resources/lib/constants.py: -------------------------------------------------------------------------------- 1 | """ 2 | Static variables to simplify for the IDE, and a proxy object for translation IDs 3 | """ 4 | from __future__ import absolute_import, division, unicode_literals 5 | 6 | API_BASE = 'https://data.jw-api.org/mediator/v1' 7 | TRANSLATION_URL = API_BASE + '/translations/' 8 | CATEGORY_URL = API_BASE + '/categories/' 9 | MEDIA_URL = API_BASE + '/media-items/' 10 | LANGUAGE_URL = API_BASE + '/languages/' 11 | 12 | TOKEN_URL = 'https://b.jw-cdn.org/tokens/jworg.jwt' 13 | SEARCH_URL = 'https://data.jw-api.org/search/query' 14 | 15 | 16 | class AttributeProxy(object): 17 | """A class which runs a function when accessing its attributes 18 | 19 | For example: 20 | proxy = AttributeProxy(function) 21 | proxy.some_attribute 22 | 23 | Is the same as: 24 | function(AttributeProxy.some_attribute) 25 | """ 26 | 27 | def __init__(self, function): 28 | self._func = function 29 | 30 | def __getattribute__(self, name): 31 | # Py2: getattribute is ok with unicode, as long as it's all ASCII characters 32 | custom_function = super(AttributeProxy, self).__getattribute__('_func') 33 | original_value = super(AttributeProxy, self).__getattribute__(name) 34 | return custom_function(original_value) 35 | 36 | 37 | class Query(object): 38 | """Strings for URL queries to addon itself""" 39 | MODE = 'mode' 40 | CATKEY = 'category' 41 | LANGCODE = 'language' 42 | LANGNAME = 'lname' 43 | MEDIAKEY = 'media' 44 | STREAMKEY = 'category' 45 | 46 | 47 | class Mode(object): 48 | """Modes for use with mode= query to addon itself""" 49 | LANGUAGES = 'languages' 50 | SET_LANG = 'set_language' 51 | SEARCH = 'search' 52 | HIDDEN = 'ask_hidden' 53 | PLAY = 'play' 54 | BROWSE = 'browse' 55 | STREAM = 'stream' 56 | 57 | 58 | class SettingID(object): 59 | """IDs from settins.xml""" 60 | RESOLUTION = 'video_res' 61 | SUBTITLES = 'subtitles' 62 | LANGUAGE = 'language' 63 | LANG_HIST = 'lang_history' 64 | LANG_NAME = 'lang_name' 65 | LANG_NEXT = 'lang_next' 66 | TOKEN = 'jwt_token' 67 | START_WARNING = 'startupmsg' 68 | SEARCH_TRANSL = 'search_tr' 69 | REMEMBER_LANG = 'remember_lang' 70 | 71 | 72 | class LocalizedStringID(AttributeProxy): 73 | """IDs from strings.po""" 74 | HIDDEN = 30013 75 | CONV_QUESTION = 30014 76 | START_WARN = 30015 77 | THEO_WARN = 30016 78 | DISCLAIMER = 30020 79 | PLAY_LANG = 30021 80 | SHUFFLE_CAT = 30023 81 | AUDIO_ONLY = 30024 82 | CONN_ERR = 30025 83 | NOT_AVAIL = 30027 84 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Unofficial JW Broadcasting plugin for Kodi 2 | ========================================== 3 | 4 | *This is a fork/continuation of the older "JW Broadcasting (unofficial)" add-on for Kodi. It is not officially supported by the Watchtower Society. Do not contact jw.org for support, instead please leave an issue here on GitHub if you run into any problems.* 5 | 6 | ## The best TV channel ever 7 | 8 | ![screenshot](https://raw.githubusercontent.com/allejok96/plugin.video.jwb-unofficial/master/resources/screenshot-01.jpg) 9 | 10 | Browse [JW Broadcasting](https://tv.jw.org) on your Kodi box! Watch streams, listen to sound recordings and watch the latest videos in any available language. 11 | 12 | The best way to watch it is using an officially supported device with the officially supported [JW Broadcasting App](https://www.jw.org/en/online-help/jw-broadcasting/). The Watchtower Society urges people to use their official apps, instead of third-party software like Kodi add-ons ([w18 April page 30-31](https://wol.jw.org/en/wol/d/r1/lp-e/2018364)). 13 | 14 | ## Installation 15 | 16 | There are multiple ways you can install this add-on. You could use `git clone` or Download ZIP from GitHub. 17 | 18 | But the easiest way is to install it from my repo. This way you'll receive updates automatically (if I remember to upload them): 19 | 20 | 1. Download [this ZIP](https://github.com/allejok96/repository.allejok96/raw/master/downloads/repository.allejok96.zip) 21 | 1. In Kodi: click on "Add-ons" 22 | 1. Click on the little box icon in the upper left hand corner 23 | 1. "Install from zip file" 24 | 1. Browse to the directory with the zip and select it 25 | 1. Click on "Install from repository" 26 | 1. "allejok96's Repository > Video add-ons > JWB Unofficial > Install" 27 | 28 | ## Disclaimer 29 | 30 | The benefits of this add-on are countless, but there are some risks, as the WT article above points out: 31 | 32 | * When tv.jw.org improves, this add-on may break, misbehave or lag behind. 33 | * If someone hacked my repo, they could forge the spiritual food (extremely unlikely). 34 | 35 | But since you found this page I guess you know what you're doing. 36 | 37 | #### Why not in Kodi official repository? 38 | 39 | The original author of this add-on, who wishes to stay anonymous, decided to take it down for personal reasons. Including some of the reasons mentioned above. It really got me thinking, and I decided to play it safe, even if I would continue to develop the add-on. After all, it's not just any random video site we're talking about... 40 | 41 | So my wish is that *you* take responsibility for the installations *you* make. Chances are if you found this page, you can install a zip in Kodi. Maybe your aunt can't, but then you can help her. It's better that you be there for your aunt if something happens, than me having a 1000 aunts broken Broadcasting on my conscience. 42 | 43 | You may be of a different opinion, but please respect my personal decision. And if you want to change something, it's open source, so go ahead and fork it. 44 | 45 | #### Is this legal? 46 | 47 | Yes, this is considered "proper use". The [Terms of Service](http://www.jw.org/en/terms-of-use/) allows for: 48 | 49 | > distribution of free, non-commercial applications designed to download electronic files such as EPUB, PDF, MP3, and MP4 files from public areas of jw.org. 50 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /addon.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache License, Version 2.0 2 | from __future__ import unicode_literals, division, print_function, absolute_import 3 | 4 | import sys 5 | import os.path 6 | import json 7 | import random 8 | import time 9 | import traceback 10 | 11 | from kodi_six import xbmc, xbmcaddon, xbmcgui, xbmcplugin, py2_decode, py2_encode 12 | 13 | from resources.lib.constants import Query as Q, Mode as M, SettingID, LocalizedStringID 14 | from resources.lib.constants import CATEGORY_URL, LANGUAGE_URL, MEDIA_URL, SEARCH_URL, TOKEN_URL, TRANSLATION_URL 15 | 16 | try: 17 | from urllib.error import HTTPError, URLError 18 | from urllib.request import urlopen, Request 19 | from urllib.parse import parse_qs, urlencode 20 | from time import strftime 21 | 22 | except ImportError: 23 | from urlparse import parse_qs as _parse_qs 24 | from urllib2 import urlopen, Request, HTTPError, URLError 25 | from urllib import urlencode as _urlencode 26 | from time import strftime as _strftime 27 | 28 | 29 | # Py2: urlencode only accepts byte strings 30 | def urlencode(query): 31 | # Dict[str, str] -> str 32 | return py2_decode(_urlencode({py2_encode(param): py2_encode(arg) for param, arg in query.items()})) 33 | 34 | 35 | # Py2: even if parse_qs accepts unicode, the return makes no sense 36 | def parse_qs(qs): 37 | # str -> Dict[str, List[str]] 38 | return {py2_decode(param): [py2_decode(a) for a in args] 39 | for param, args in _parse_qs(py2_encode(qs)).items()} 40 | 41 | 42 | # Py2: strftime returns byte string 43 | def strftime(format, t=None): 44 | return py2_decode(_strftime(py2_encode(format))) 45 | 46 | 47 | # Py2: When using str, we mean unicode string 48 | str = unicode 49 | 50 | 51 | def log(msg, level=xbmc.LOGDEBUG): 52 | """Write to log file""" 53 | 54 | for line in msg.splitlines(): 55 | xbmc.log(addon.getAddonInfo('id') + ': ' + line, level) 56 | 57 | 58 | class Directory(object): 59 | def __init__(self, key=None, url=None, title=None, icon=None, fanart=None, hidden=False, description=None, 60 | is_folder=True, streamable=False): 61 | """An object containing metadata for a folder""" 62 | 63 | self.key = key 64 | self.url = url 65 | self.title = title 66 | self.icon = icon 67 | self.fanart = fanart 68 | self.hidden = hidden 69 | self.description = description 70 | self.is_folder = is_folder 71 | self.streamable = streamable 72 | 73 | def parse_common(self, data): 74 | """Constructor from common metadata""" 75 | self.description = data.get('description') 76 | 77 | # Note about tags 78 | # RokuExclude, FireTVExclude, AppleTVExclude are set-top boxes like Kodi, we should use one of these 79 | # WebExclude = deprecated? may be tv.jw.org 80 | # RWSLExclude = Sign Language? 81 | # JWORGExclude vs WWWExclude, what's the difference? 82 | # Library[Tag] has something to do with the new changes to jw.org 83 | self.hidden = 'AppleTVExclude' in data.get('tags', []) 84 | 85 | # Note about image abbreviations 86 | # Last letter: s is smaller, r/h is bigger 87 | # pss/psr 3:4 88 | # sqs/sqr 1:1 89 | # cvr 1:1 90 | # rps/rph 5:4 91 | # wss/wsr 16:9 92 | # lsr/lss 2:1 93 | # pns/pnr 3:1 94 | self.icon = getitem(data, 'images', ('sqr', 'cvr'), ('lg', 'md')) 95 | # Note: don't overwrite fanart choice (in main menu) 96 | if not self.fanart: 97 | self.fanart = getitem(data, 'images', ('wsr', 'lsr', 'pnr'), ('md', 'lg')) 98 | 99 | def parse_category(self, data): 100 | """Constructor taking jw category metadata 101 | 102 | :param data: deserialized JSON data from jw.org 103 | """ 104 | self.parse_common(data) 105 | self.key = data.get('key') 106 | self.title = data.get('name') 107 | 108 | tags = data.get('tags', []) 109 | if 'StreamThisChannelEnabled' in tags or 'AllowShuffleInCategoryHeader' in tags: 110 | self.streamable = True 111 | 112 | if self.key: 113 | self.url = request_to_self({Q.MODE: M.BROWSE, Q.STREAMKEY: self.key}) 114 | 115 | def listitem(self): 116 | """Create a Kodi listitem from the metadata""" 117 | 118 | try: 119 | # offscreen is a Kodi v18 feature 120 | # We wont't be able to change the listitem after running .addDirectoryItem() 121 | # But load time for this function is cut down by 93% (!) 122 | li = xbmcgui.ListItem(self.title, offscreen=True) 123 | except TypeError: 124 | li = xbmcgui.ListItem(self.title) 125 | art_dict = {'icon': self.icon, 'poster': self.icon, 'fanart': self.fanart} 126 | # Check if there's any art, setArt can be kinda slow 127 | if any(art_dict.values()): 128 | li.setArt(art_dict) 129 | li.setInfo('video', {'plot': self.description}) 130 | 131 | if self.streamable: 132 | query = {Q.MODE: M.STREAM, Q.STREAMKEY: self.key} 133 | action = 'RunPlugin(' + request_to_self(query) + ')' 134 | li.addContextMenuItems([(S.SHUFFLE_CAT, action)]) 135 | 136 | return li 137 | 138 | def add_item_in_kodi(self): 139 | """Adds this as a directory item in Kodi""" 140 | 141 | xbmcplugin.addDirectoryItem(handle=addon_handle, url=self.url, listitem=self.listitem(), 142 | isFolder=self.is_folder) 143 | 144 | 145 | class Media(Directory): 146 | def __init__(self, duration=None, media_type='video', publish_date=None, 147 | size=None, is_folder=False, subtitles=None, **kwargs): 148 | """An object containing metadata for a video or audio recording""" 149 | 150 | super(Media, self).__init__(**kwargs) 151 | self.media_type = media_type 152 | self.size = size 153 | self.__publish_date = publish_date 154 | self.__duration = duration 155 | self.is_folder = is_folder 156 | self.subtitles = subtitles 157 | self.resolved_url = None 158 | 159 | def parse_media(self, data, censor_hidden=True): 160 | """Constructor taking jw media metadata 161 | 162 | :param data: deserialized JSON data from jw.org 163 | :param censor_hidden: if True, media marked as hidden will ask for permission before being displayed 164 | """ 165 | self.parse_common(data) 166 | self.key = data.get('languageAgnosticNaturalKey') 167 | if self.key: 168 | self.url = request_to_self({Q.MODE: M.PLAY, Q.MEDIAKEY: self.key}) 169 | 170 | if self.hidden and censor_hidden: 171 | # Reset to these values 172 | self.__init__(title=S.HIDDEN, 173 | url=request_to_self({Q.MODE: M.HIDDEN, Q.MEDIAKEY: self.key}), 174 | is_folder=True) 175 | else: 176 | self.resolved_url, self.size, self.subtitles = self.get_preferred_media_file(data.get('files', [])) 177 | self.title = data.get('title') 178 | if data.get('type') == 'audio': 179 | self.media_type = 'music' 180 | self.duration = data.get('duration') 181 | self.publish_date = data.get('firstPublished') 182 | 183 | def parse_hits(self, data): 184 | """Create an instance of Media out of search results 185 | 186 | :param data: deserialized search result JSON data from jw.org 187 | """ 188 | self.title = data.get('displayTitle') 189 | if 'type:audio' in data.get('tags', []): 190 | self.media_type = 'music' 191 | self.title += ' ' + S.AUDIO_ONLY 192 | self.key = data.get('languageAgnosticNaturalKey') 193 | self.publish_date = data.get('firstPublishedDate') 194 | if self.key: 195 | self.url = request_to_self({Q.MODE: M.PLAY, Q.MEDIAKEY: self.key}) 196 | 197 | for m in data.get('metadata', []): 198 | if m.get('key') == 'duration': 199 | self.duration = m.get('value') 200 | 201 | # TODO? We could try for pnr and cvr images too, but I'm too lazy, and no one cares about search anyway 202 | for i in data.get('images', []): 203 | if i.get('size') == 'md' and i.get('type') == 'sqr': 204 | self.icon = i.get('url') 205 | if i.get('size') == 'md' and i.get('type') == 'lsr': 206 | self.fanart = i.get('url') 207 | 208 | @property 209 | def publish_date(self): 210 | return self.__publish_date 211 | 212 | @publish_date.setter 213 | def publish_date(self, value): 214 | """Value is a string like 2017-05-18T15:41:52.197Z""" 215 | 216 | # Dates are not visible in default skin, all this does is slow down processing 217 | # try: self.__publish_date = time.strptime(value[0:19], '%Y-%m-%dT%H:%M:%S') 218 | # except (ValueError, TypeError): pass 219 | 220 | pass 221 | 222 | @property 223 | def duration(self): 224 | return self.__duration 225 | 226 | @duration.setter 227 | def duration(self, value): 228 | try: 229 | self.__duration = int(value) 230 | return 231 | except (TypeError, ValueError): 232 | pass 233 | try: 234 | t = value.split(':') 235 | if len(value) == 3: 236 | self.__duration = int(t[0]) * 60 * 60 + int(t[1]) * 60 + int(t[2]) 237 | elif len(t) == 2: 238 | self.__duration = int(t[0]) * 60 + int(t[1]) 239 | elif len(t) == 1: 240 | self.__duration = int(t[0]) 241 | except (AttributeError, ValueError, TypeError): 242 | pass 243 | 244 | @staticmethod 245 | def get_preferred_media_file(data): 246 | """Take an jw JSON array of files and metadata and return the most suitable like (url, size, subtitles)""" 247 | 248 | # Rank media files depending on how they match certain criteria 249 | # Video resolution will be converted to a rank between 2 and 10 250 | resolution_not_too_big = 200 251 | subtitles_matches_pref = 100 252 | 253 | files = [] 254 | for f in data: 255 | rank = 0 256 | try: 257 | # Grab resolution from label, eg. 360p, and remove the p 258 | res = int(f.get('label')[:-1]) 259 | except (TypeError, ValueError): 260 | try: 261 | res = int(f.get('frameHeight', 0)) 262 | except (TypeError, ValueError): 263 | res = 0 264 | rank += res // 10 265 | if 0 < res <= video_res: 266 | rank += resolution_not_too_big 267 | # 'subtitled' only applies to hardcoded video subtitles 268 | if f.get('subtitled') == subtitle_setting: 269 | rank += subtitles_matches_pref 270 | files.append((rank, f)) 271 | files.sort() 272 | 273 | if len(files) > 0: 274 | # [-1] The file with the highest rank, [1] the filename, not the rank 275 | f = files[-1][1] 276 | return f['progressiveDownloadURL'], f['filesize'], getitem(f, 'subtitles', 'url', default=None) 277 | else: 278 | return None, None, None 279 | 280 | def listitem(self): 281 | """Create a Kodi listitem from the metadata""" 282 | 283 | art_dict = { 284 | 'icon': self.icon, 285 | 'poster': self.icon, 286 | 'fanart': self.fanart 287 | } 288 | info_dict = { 289 | 'duration': self.duration, 290 | 'title': self.title, 291 | 'size': self.size 292 | } 293 | 294 | if self.media_type == 'music': 295 | info_dict['comment'] = self.description 296 | else: 297 | info_dict['plot'] = self.description 298 | 299 | if self.publish_date: 300 | info_dict['date'] = strftime('%d.%m.%Y', self.publish_date) 301 | info_dict['year'] = strftime('%Y', self.publish_date) 302 | 303 | try: 304 | # Kodi v18 305 | li = xbmcgui.ListItem(self.title, offscreen=True) 306 | except TypeError: 307 | li = xbmcgui.ListItem(self.title) 308 | 309 | li.setArt(art_dict) 310 | li.setInfo(self.media_type, info_dict) 311 | 312 | # For some reason needed for listitems that will open xbmcplugin.setResolvedUrl 313 | li.setProperty('isPlayable', 'true') 314 | 315 | if self.subtitles: 316 | li.setSubtitles([self.subtitles]) 317 | 318 | context_menu = [] 319 | 320 | # Play in other language context menu 321 | if self.key: 322 | query = {Q.MODE: M.LANGUAGES, Q.MEDIAKEY: self.key} 323 | # Note: Use RunPlugin instead of RunAddon, because an add-on assumes a folder view 324 | action = 'RunPlugin(' + request_to_self(query) + ')' 325 | context_menu.append((S.PLAY_LANG, action)) 326 | 327 | if context_menu: 328 | li.addContextMenuItems(context_menu) 329 | 330 | return li 331 | 332 | def listitem_with_resolved_url(self): 333 | """Return ListItem with path set, because apparently setPath() is slow""" 334 | 335 | li = self.listitem() 336 | li.setPath(self.resolved_url) 337 | return li 338 | 339 | 340 | def getitem(obj, *keys, **kwargs): 341 | """Recursive get function 342 | 343 | Keys are checked in order, and the first found value is returned 344 | 345 | :param obj: list, dictionary or tuple 346 | :param keys: a index or a key name or a tuple with indexes and key names 347 | :keyword default: value to return if it fails 348 | :keyword fail: used internally 349 | 350 | Example: getitem(colorlist, ('red', 'green'), 2) 351 | 352 | Would match: colorlist['red'][2] or colorlist['green'][2] 353 | """ 354 | assert keys 355 | sublevels = list(keys) 356 | toplevels = sublevels.pop(0) 357 | 358 | if type(toplevels) != tuple: 359 | toplevels = (toplevels,) 360 | 361 | for toplevel in toplevels: 362 | try: 363 | if len(sublevels) > 0: 364 | # More levels, go deeper 365 | return getitem(obj[toplevel], *sublevels, fail=True) 366 | else: 367 | # Last level, return value 368 | return obj[toplevel] 369 | except (TypeError, KeyError, IndexError): 370 | # Could not get value, try next 371 | continue 372 | 373 | # Py2: get() unicode is ok 374 | if kwargs.get('fail', False): 375 | # No keys existed for this level, return to parent 376 | raise KeyError 377 | else: 378 | # Everything failed, we return nicely 379 | return kwargs.get('default') 380 | 381 | 382 | def get_json(url, ignore_errors=False, catch_401=True): 383 | """Fetch JSON data from an URL and return it as a Python object 384 | 385 | :param url: URL to open or a Request object 386 | :param ignore_errors: IO exceptions will only be logged, don't exit 387 | :param catch_401: If False HTTP 401 will be passed on instead of caught 388 | 389 | IF an IO exception occurs a message will be displayed and the script exits. 390 | """ 391 | if isinstance(url, Request): 392 | log('opening {}'.format(url.get_full_url()), xbmc.LOGINFO) 393 | else: 394 | log('opening {}'.format(url), xbmc.LOGINFO) 395 | 396 | try: 397 | data = urlopen(url).read().decode('utf-8') # urlopen returns bytes 398 | # Catches URLError, HTTPError, SSLError ... 399 | except IOError as e: 400 | if ignore_errors: 401 | log(traceback.format_exc(), level=xbmc.LOGWARNING) 402 | return None 403 | elif not catch_401 and isinstance(e, HTTPError) and e.code == 401: 404 | raise 405 | else: 406 | log(traceback.format_exc(), level=xbmc.LOGERROR) 407 | xbmcgui.Dialog().notification( 408 | addon.getAddonInfo('name'), 409 | S.CONN_ERR, 410 | icon=xbmcgui.NOTIFICATION_ERROR) 411 | # Don't raise an error, it will just generate another cryptic notification in Kodi 412 | exit() 413 | raise # to make PyCharm happy 414 | 415 | return json.loads(data) 416 | 417 | 418 | def top_level_page(): 419 | """The main menu, media categories from tv.jw.org plus extra stuff""" 420 | 421 | default_fanart = os.path.join(addon.getAddonInfo('path'), addon.getAddonInfo('fanart')) 422 | 423 | if addon.getSetting(SettingID.START_WARNING) == 'true': 424 | dialog = xbmcgui.Dialog() 425 | try: 426 | dialog.textviewer(S.THEO_WARN, S.DISCLAIMER) # Kodi v16 427 | except AttributeError: 428 | dialog.ok(S.THEO_WARN, S.DISCLAIMER) 429 | addon.setSetting(SettingID.START_WARNING, 'false') 430 | 431 | # Auto language 432 | isolang = xbmc.getLanguage(xbmc.ISO_639_1) 433 | if not addon.getSetting(SettingID.LANG_HIST): 434 | # Write English to language history, so this code only runs once 435 | addon.setSetting(SettingID.LANG_HIST, 'E') 436 | # If Kodi is in foreign language 437 | if isolang != 'en': 438 | data = get_json(LANGUAGE_URL + 'E/web') 439 | for l in data['languages']: 440 | if l['locale'] == isolang: 441 | # Save setting, and update for this this instance 442 | set_language(l['code'], l['name'] + ' / ' + l['vernacular']) 443 | global global_lang 444 | global_lang = addon.getSetting(SettingID.LANGUAGE) or 'E' 445 | break 446 | 447 | data = get_json(CATEGORY_URL + global_lang + '?detailed=True') 448 | 449 | for c in data['categories']: 450 | d = Directory(fanart=default_fanart) 451 | d.parse_category(c) 452 | if d.url and not d.hidden: 453 | d.add_item_in_kodi() 454 | 455 | # Get "search" translation from internet - overkill but so cool 456 | # Try cache first, to speed up loading 457 | search_label = addon.getSetting(SettingID.SEARCH_TRANSL) 458 | if not search_label: 459 | data = get_json(TRANSLATION_URL + global_lang, ignore_errors=True) 460 | search_label = getitem(data, 'translations', global_lang, 'hdgSearch', default='Search') 461 | addon.setSetting(SettingID.SEARCH_TRANSL, search_label) 462 | d = Directory(url=request_to_self({Q.MODE: M.SEARCH}), title=search_label, fanart=default_fanart, 463 | icon='DefaultMusicSearch.png') 464 | d.add_item_in_kodi() 465 | 466 | xbmcplugin.endOfDirectory(addon_handle) 467 | 468 | 469 | def sub_level_page(sub_level): 470 | """A sub-level page with either folders or playable media""" 471 | 472 | # TODO: less detailed request? 473 | # For categories like VODStudio that contains subcategories with media, 474 | # all media is included in the response, which slows down the parsing a lot. 475 | # All this extra data has no function in this script. If there only was a way 476 | # to request the subcategories, but without their media... 477 | data = get_json(CATEGORY_URL + global_lang + '/' + sub_level + '?&detailed=1') 478 | data = data['category'] 479 | 480 | # Enable more viewtypes 481 | if data.get('type') == 'ondemand': 482 | xbmcplugin.setContent(addon_handle, 'videos') 483 | 484 | if 'subcategories' in data: 485 | for sc in data['subcategories']: 486 | d = Directory() 487 | d.parse_category(sc) 488 | if d.url and not d.hidden: 489 | d.add_item_in_kodi() 490 | if 'media' in data: 491 | for md in data['media']: 492 | m = Media() 493 | m.parse_media(md) 494 | if m.url: 495 | m.add_item_in_kodi() 496 | 497 | xbmcplugin.endOfDirectory(addon_handle) 498 | 499 | 500 | def shuffle_category(key): 501 | """Generate a shuffled playlist and start playing""" 502 | 503 | data = get_json(CATEGORY_URL + global_lang + '/' + key + '?&detailed=1') 504 | data = data['category'] 505 | all_media = data.get('media', []) 506 | for sc in data.get('subcategories', []): # type: dict 507 | # Don't include things like Featured, because that would become duplicate 508 | if 'AllowShuffleInCategoryHeader' in sc.get('tags', []): 509 | all_media += sc.get('media', []) 510 | 511 | # Shuffle in place, we don't want to mess with Kodi's settings 512 | random.shuffle(all_media) 513 | 514 | pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) 515 | pl.clear() 516 | 517 | for md in all_media: 518 | media = Media() 519 | media.parse_media(md, censor_hidden=False) 520 | if media.url and not media.hidden: 521 | pl.add(media.resolved_url, media.listitem()) 522 | 523 | xbmc.Player().play(pl) 524 | 525 | 526 | def language_dialog(media_key=None): 527 | """Display a list of languages and set the global language setting 528 | 529 | :param media_key: play this media file instead of changing global setting 530 | """ 531 | # Note: the list from jw.org is already sorted by ['name'] 532 | data = get_json(LANGUAGE_URL + global_lang + '/web') 533 | # Convert language data to a list of tuples with (code, name) 534 | languages = [(l.get('code'), l.get('name', '') + ' / ' + l.get('vernacular', '')) 535 | for l in data['languages']] 536 | # Get the languages matching the ones from history and put them first 537 | history = addon.getSetting(SettingID.LANG_HIST).split() 538 | languages = [l for h in history for l in languages if l[0] == h] + languages 539 | 540 | if media_key: 541 | # Lookup media, and only show available languages 542 | url = MEDIA_URL + global_lang + '/' + media_key 543 | data = get_json(url) 544 | available_langs = data['media'][0].get('availableLanguages') 545 | if available_langs: 546 | languages = [l for l in languages if l[0] in available_langs] 547 | 548 | dialog_strings = [] 549 | dialog_actions = [] 550 | for code, name in languages: 551 | dialog_strings.append(name) 552 | if media_key: 553 | request = request_to_self({ 554 | Q.MODE: M.PLAY, 555 | Q.MEDIAKEY: media_key, 556 | Q.LANGCODE: code}) 557 | dialog_actions.append('RunPlugin(' + request + ')') 558 | else: 559 | request = request_to_self({ 560 | Q.MODE: M.SET_LANG, 561 | Q.LANGNAME: name, 562 | Q.LANGCODE: code}) 563 | dialog_actions.append('RunPlugin(' + request + ')') 564 | 565 | selection = xbmcgui.Dialog().select('', dialog_strings) 566 | if selection >= 0: 567 | xbmc.executebuiltin(dialog_actions[selection]) 568 | 569 | 570 | def set_language(lang, name): 571 | """Save a language to setting and history""" 572 | 573 | addon.setSetting(SettingID.LANGUAGE, lang) 574 | addon.setSetting(SettingID.LANG_NAME, name) 575 | save_language_history(lang) 576 | # Forget about the translation of "Search" 577 | addon.setSetting(SettingID.SEARCH_TRANSL, '') 578 | 579 | 580 | def save_language_history(lang): 581 | """Save a language code first in history""" 582 | 583 | history = addon.getSetting(SettingID.LANG_HIST).split() 584 | history = [lang] + [h for h in history if h != lang] 585 | history = history[0:5] 586 | addon.setSetting(SettingID.LANG_HIST, ' '.join(history)) 587 | 588 | 589 | def search_page(): 590 | """Display a search dialog, then the results""" 591 | 592 | kb = xbmc.Keyboard() 593 | kb.doModal() 594 | if kb.isConfirmed(): 595 | # Enable more viewtypes 596 | xbmcplugin.setContent(addon_handle, 'videos') 597 | 598 | search_string = kb.getText() 599 | query = urlencode({'q': search_string, 'lang': global_lang, 'limit': 24}) 600 | 601 | try: 602 | token = addon.getSetting(SettingID.TOKEN) 603 | if not token: 604 | raise RuntimeError 605 | 606 | headers = {'Authorization': 'Bearer ' + token} 607 | data = get_json(Request(SEARCH_URL + '?' + query, headers=headers), catch_401=False) 608 | 609 | except (HTTPError, RuntimeError): 610 | # Get and save new token 611 | log('requesting new authentication token from jw.org', xbmc.LOGINFO) 612 | token = urlopen(TOKEN_URL).read().decode('utf-8') 613 | if not token: 614 | raise RuntimeError('failed to get search authentication token') 615 | 616 | addon.setSetting(SettingID.TOKEN, token) 617 | 618 | headers = {'Authorization': 'Bearer ' + token} 619 | data = get_json(Request(SEARCH_URL + '?' + query, headers=headers)) 620 | 621 | for hd in data['hits']: 622 | media = Media() 623 | media.parse_hits(hd) 624 | if media.url: 625 | media.add_item_in_kodi() 626 | 627 | xbmcplugin.endOfDirectory(addon_handle) 628 | 629 | 630 | def hidden_media_dialog(media_key): 631 | """Ask the user for permission, then create a folder with a single media entry""" 632 | 633 | dialog = xbmcgui.Dialog() 634 | if dialog.yesno(S.HIDDEN, S.CONV_QUESTION): 635 | data = get_json(MEDIA_URL + global_lang + '/' + media_key) 636 | media = Media() 637 | media.parse_media(data['media'][0], censor_hidden=False) 638 | if media.url: 639 | media.add_item_in_kodi() 640 | else: 641 | raise RuntimeError 642 | xbmcplugin.endOfDirectory(addon_handle) 643 | 644 | 645 | def resolve_media(media_key, lang=None): 646 | """Resolve to a playable URL for a media key name 647 | 648 | :param media_key: string, id of media to play 649 | :param lang: string, language code 650 | 651 | When language is specified, play video in that language, with subtitles in "global language" 652 | """ 653 | if lang: 654 | # If we were called with a language, remove it from the URI and make a new request 655 | # This will make watched status and resume position language agnostic 656 | save_language_history(lang) 657 | addon.setSetting(SettingID.LANG_NEXT, lang) 658 | xbmc.executebuiltin('PlayMedia({}, resume)'.format(request_to_self({Q.MODE: M.PLAY, Q.MEDIAKEY: media_key}))) 659 | return 660 | 661 | one_time_lang = addon.getSetting(SettingID.LANG_NEXT) 662 | 663 | data = get_json(MEDIA_URL + (one_time_lang or global_lang) + '/' + media_key) 664 | 665 | # If set to always use foreign language, it may try to play a video in a language where it doesn't exist 666 | # this does not happen when using the one-time language menu, because it looks up languages on individual videos 667 | if one_time_lang and not data.get('media', None): 668 | xbmcgui.Dialog().notification(addon.getAddonInfo('name'), S.NOT_AVAIL, icon=xbmcgui.NOTIFICATION_WARNING) 669 | data = get_json(MEDIA_URL + global_lang + '/' + media_key) 670 | one_time_lang = None 671 | 672 | media = Media() 673 | media.parse_media(data['media'][0], censor_hidden=False) 674 | 675 | if one_time_lang: 676 | if addon.getSetting(SettingID.REMEMBER_LANG) == 'false': 677 | addon.setSetting(SettingID.LANG_NEXT, None) 678 | 679 | if one_time_lang != global_lang: 680 | # Add subtitles from the global language too 681 | data = get_json(MEDIA_URL + global_lang + '/' + media_key, ignore_errors=True) 682 | global_lang_subs = getitem(data, 'media', 0, 'files', 0, 'subtitles', 'url', default=None) 683 | if global_lang_subs: 684 | media.subtitles = global_lang_subs 685 | 686 | if media.resolved_url: 687 | xbmcplugin.setResolvedUrl(addon_handle, succeeded=True, listitem=media.listitem_with_resolved_url()) 688 | # Ugly way to turn on/off subtitles (without changing the global Kodi setting), try it for 10 sec 689 | # TODO change this if made possible in the future 690 | player = xbmc.Player() 691 | for i in range(1, 10): 692 | if player.getAvailableSubtitleStreams(): 693 | # Subtitles are always on if a FOREIGN language is explicitly specified 694 | player.showSubtitles(one_time_lang and one_time_lang != global_lang or subtitle_setting) 695 | break 696 | time.sleep(1) 697 | 698 | else: 699 | raise RuntimeError 700 | 701 | 702 | def request_to_self(query): 703 | """Return a string with an URL request to the add-on itself""" 704 | 705 | # argv[0] is path to the plugin 706 | return sys.argv[0] + '?' + urlencode(query) 707 | 708 | 709 | if __name__ == '__main__': 710 | # To send stuff to the screen 711 | addon_handle = int(sys.argv[1]) 712 | # To get settings and info 713 | addon = xbmcaddon.Addon() 714 | # For logging purpose 715 | addon_id = addon.getAddonInfo('id') 716 | # To to get translated strings 717 | S = LocalizedStringID(addon.getLocalizedString) 718 | 719 | video_res = [1080, 720, 480, 360, 240][int(addon.getSetting(SettingID.RESOLUTION))] 720 | subtitle_setting = addon.getSetting(SettingID.SUBTITLES) == 'true' 721 | global_lang = addon.getSetting(SettingID.LANGUAGE) or 'E' 722 | 723 | # The awkward way Kodi passes arguments to the add-on... 724 | # argv[2] is a URL query string, probably passed by request_to_self() 725 | # example: ?mode=play&media=ThisVideo 726 | args = parse_qs(sys.argv[2][1:]) 727 | # parse_qs puts the values in a list, so we grab the first value for each key 728 | args = {k: v[0] for k, v in args.items()} 729 | 730 | # Tested in Kodi 18: This will disable all viewtypes but list and icons won't be displayed within the list 731 | xbmcplugin.setContent(addon_handle, 'files') 732 | 733 | mode = args.get(Q.MODE) 734 | 735 | if mode is None: 736 | top_level_page() 737 | elif mode == M.LANGUAGES: 738 | language_dialog(args.get(Q.MEDIAKEY)) 739 | elif mode == M.SET_LANG: 740 | set_language(args[Q.LANGCODE], args[Q.LANGNAME]) 741 | elif mode == M.HIDDEN: 742 | hidden_media_dialog(args[Q.MEDIAKEY]) 743 | elif mode == M.SEARCH: 744 | search_page() 745 | elif mode == M.PLAY: 746 | resolve_media(args[Q.MEDIAKEY], args.get(Q.LANGCODE)) 747 | elif mode == M.BROWSE: 748 | sub_level_page(args[Q.CATKEY]) 749 | elif mode == M.STREAM: 750 | shuffle_category(args[Q.STREAMKEY]) 751 | # Backwards compatibility 752 | elif mode.startswith('Streaming') and mode != 'Streaming': 753 | shuffle_category(mode) 754 | else: 755 | sub_level_page(mode) 756 | --------------------------------------------------------------------------------