def language_dialog(media_key=None): """Display a list of languages and set the global language setting :param media_key: play this media file instead of changing global setting """ # Note: the list from jw.org is already sorted by ['name'] data = get_json(LANGUAGE_URL + global_lang + '/web') # Convert language data to a list of tuples with (code, name) languages = [(l.get('code'), l.get('name', '') + ' / ' + l.get('vernacular', '')) for l in data['languages']] # Get the languages matching the ones from history and put them first history = addon.getSetting(SettingID.LANG_HIST).split() languages = [l for h in history for l in languages if l[0] == h] + languages if media_key: # Lookup media, and only show available languages url = MEDIA_URL + global_lang + '/' + media_key data = get_json(url) available_langs = data['media'][0].get('availableLanguages') if available_langs: languages = [l for l in languages if l[0] in available_langs] dialog_strings = [] dialog_actions = [] for code, name in languages: dialog_strings.append(name) if media_key: request = request_to_self({ Q.MODE: M.PLAY, Q.MEDIAKEY: media_key, Q.LANGCODE: code }) dialog_actions.append('RunPlugin(' + request + ')') else: request = request_to_self({ Q.MODE: M.SET_LANG, Q.LANGNAME: name, Q.LANGCODE: code }) dialog_actions.append('RunPlugin(' + request + ')') selection = xbmcgui.Dialog().select('', dialog_strings) if selection >= 0: xbmc.executebuiltin(dialog_actions[selection])
def Dialog_Confirm_With_Timeout(self, title, message, focused, timeout): dialog = xbmcgui.Dialog() yes = getLocalizedString(30413) no = getLocalizedString(30414) if timeout > 0 and timeout < 1200: if focused: yes = getLocalizedLabel("LOCALIZE[30632];;%d" % timeout) else: no = getLocalizedLabel("LOCALIZE[30633];;%d" % timeout) return int( dialog.yesno(getLocalizedLabel(title), getLocalizedLabel(message), nolabel=no, yeslabel=yes))
def get_video_url(plugin, item_id, video_id, download_mode=False, **kwargs): if get_kodi_version() < 18: xbmcgui.Dialog().ok('Info', plugin.localize(30602)) return False is_helper = inputstreamhelper.Helper('mpd', drm='widevine') if not is_helper.check_inputstream(): return False resp = urlquick.get(URL_CLIENT_KEY_VIDEO_JS) client_key_value = 'client-key %s' % re.compile( r'prod\"\,clientKey\:\"(.*?)\"').findall(resp.text)[0] headers = {'Authorization': client_key_value} resp2 = urlquick.get(URL_STREAM_REPLAY % video_id, headers=headers, max_age=-1) json_parser = json.loads(resp2.text) if json_parser["params"] is not None: licence_key_drm = '' for licence_key_drm_datas in json_parser["params"]: if 'widevineLicenseUrl' in licence_key_drm_datas["name"]: licence_key_drm = licence_key_drm_datas["value"] token_drm = '' for token_drm_datas in json_parser["params"]: if 'widevineAuthToken' in token_drm_datas["name"]: token_drm = token_drm_datas["value"] item = Listitem() item.path = json_parser["url"].replace('filter=', 'format=mpd-time-csf,filter=') item.label = get_selected_item_label() item.art.update(get_selected_item_art()) item.info.update(get_selected_item_info()) item.property['inputstreamaddon'] = 'inputstream.adaptive' item.property['inputstream.adaptive.manifest_type'] = 'mpd' item.property[ 'inputstream.adaptive.license_type'] = 'com.widevine.alpha' item.property[ 'inputstream.adaptive.license_key'] = licence_key_drm + '|Content-Type=&User-Agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3041.0 Safari/537.36&Authorization=%s|R{SSM}|' % token_drm return item plugin.notify('ERROR', plugin.localize(30713)) return False
def disconnect_openvpn(): with storage.PersistentDict('vpn') as db: Script.log('OpenVPN: Disconnecting OpenVPN') try: db['status'] = "disconnecting" response = vpnlib.is_running(ip, port) if response[0]: vpnlib.disconnect(ip, port) if response[1] is not None: Script.notify('OpenVPN', Script.localize(30355)) db['status'] = "disconnected" Script.log('OpenVPN: Disconnect OpenVPN successful') except vpnlib.OpenVPNError as exception: xbmcgui.Dialog().ok('OpenVPN', Script.localize(30358)) Script.log('OpenVPN: OpenVPN error: ' + str(exception)) db['status'] = "failed" db.flush()
def notificationDialog(self, message, header=ADDON_NAME, sound=False, time=4000, icon=ICON): try: xbmcgui.Dialog().notification(header, message, icon, time, sound=False) except Exception as e: self.log("notificationDialog Failed! " + str(e), xbmc.LOGERROR) xbmc.executebuiltin("Notification(%s, %s, %d, %s)" % (header, message, time, icon)) return True
def play_link(link): logger.log('Playing Link: |%s|' % (link), log_utils.LOGDEBUG) if link.endswith('$$all'): hmf = resolveurl.HostedMediaFile(url=link[:-5], return_all=True) else: hmf = resolveurl.HostedMediaFile(url=link) if not hmf: logger.log('Indirect hoster_url not supported by smr: %s' % (link)) kodi.notify('Link Not Supported: %s' % (link), duration=7500) return False logger.log('Link Supported: |%s|' % (link), log_utils.LOGDEBUG) try: if link.endswith('$$all'): allfiles = hmf.resolve() names = [x.get('name') for x in allfiles] item = xbmcgui.Dialog().select('Select file to play', names, preselect=0) if item == -1: return False stream_url = allfiles[item].get('link') if resolveurl.HostedMediaFile(stream_url): stream_url = resolveurl.resolve(stream_url) else: stream_url = hmf.resolve() if not stream_url or not isinstance(stream_url, string_types): try: msg = stream_url.msg except: msg = link raise Exception(msg) except Exception as e: try: msg = str(e) except: msg = link kodi.notify('Resolve Failed: %s' % (msg), duration=7500) return False logger.log('Link Resolved: |%s|%s|' % (link, stream_url), log_utils.LOGDEBUG) listitem = xbmcgui.ListItem(path=stream_url) # listitem.setContentLookup(False) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem)
def get_live_url(plugin, item_id, video_id, item_dict, **kwargs): if cqu.get_kodi_version() < 18: xbmcgui.Dialog().ok('Info', plugin.localize(30602)) return False is_helper = inputstreamhelper.Helper('mpd', drm='widevine') if not is_helper.check_inputstream(): return False if item_id == 'questtv': resp = urlquick.get(URL_LIVE % 'quest', max_age=-1) elif item_id == 'questred': resp = urlquick.get(URL_LIVE % 'quest-red', max_age=-1) if len(re.compile(r'drmToken\"\:\"(.*?)\"').findall(resp.text)) > 0: token = re.compile(r'drmToken\"\:\"(.*?)\"').findall(resp.text)[0] if len(re.compile(r'streamUrlDash\"\:\"(.*?)\"').findall( resp.text)) > 0: live_url = re.compile(r'streamUrlDash\"\:\"(.*?)\"').findall( resp.text)[0] item = Listitem() item.path = live_url if item_dict: if 'label' in item_dict: item.label = item_dict['label'] if 'info' in item_dict: item.info.update(item_dict['info']) if 'art' in item_dict: item.art.update(item_dict['art']) else: item.label = LABELS[item_id] item.art["thumb"] = "" item.art["icon"] = "" item.art["fanart"] = "" item.info["plot"] = LABELS[item_id] item.property['inputstreamaddon'] = 'inputstream.adaptive' item.property['inputstream.adaptive.manifest_type'] = 'mpd' item.property[ 'inputstream.adaptive.license_type'] = 'com.widevine.alpha' item.property[ 'inputstream.adaptive.license_key'] = URL_LICENCE_KEY % token return item plugin.notify('ERROR', plugin.localize(30713)) return False
def hide_item(plugin, item_id, menu_id): """Callback function of 'hide item' context menu Args: plugin (codequick.script.Script) item_id (str): item_id to move menu_id (str): menu_id of the item """ if plugin.setting.get_boolean('show_hidden_items_information'): xbmcgui.Dialog().ok( plugin.localize(LABELS['Information']), plugin.localize( LABELS['To re-enable hidden items go to the plugin settings'])) plugin.setting['show_hidden_items_information'] = False set_item_visibility(item_id, menu_id, True) xbmc.executebuiltin('XBMC.Container.Refresh()')
def get_video_url(plugin, item_id, video_url, download_mode=False, **kwargs): resp = urlquick.get(video_url, max_age=-1) stream_url = re.compile(r'og\:video\" content\=\"(.*?)\"').findall( resp.text)[0] desired_quality = Script.setting.get_string('quality') all_datas_videos_quality = [] all_datas_videos_path = [] for quality in QUALITIES_STREAM: all_datas_videos_quality.append(quality) if quality == 'sd': all_datas_videos_path.append( stream_url.replace('mp4-231', 'mp4-322')) elif quality == 'md': all_datas_videos_path.append( stream_url.replace('mp4-231', 'mp4-323')) elif quality == 'hq': all_datas_videos_path.append( stream_url.replace('mp4-231', 'mp4-12')) else: all_datas_videos_path.append(stream_url) url = '' if desired_quality == "DIALOG": seleted_item = xbmcgui.Dialog().select( plugin.localize(LABELS['choose_video_quality']), all_datas_videos_quality) if seleted_item == -1: url = '' url = all_datas_videos_path[seleted_item] elif desired_quality == "BEST": url_best = '' for data_video in all_datas_videos_path: url_best = data_video url = url_best else: url = all_datas_videos_path[0] if download_mode: return download.download_video(url) return url
def get_active_dls(): PLog('get_active_dls_start:') import threading xbmc.sleep(1000) # Pause für Datei-OP durch Haupt-PRG open(DL_CHECK, 'w').close() # Lock dl_check_alive anlegen PLog("dl_check_alive_angelegt") icon = R('icon-downl.png') monitor = xbmc.Monitor() i = 0 while not monitor.abortRequested(): # Abbruch durch Kodi if os.path.exists(DL_CHECK) == False: # Abbruch durch Addon break if SETTINGS.getSetting('pref_dl_cnt') == 'false': # dopp. Sicherung break if os.path.exists(DL_CNT): with open(DL_CNT, 'r') as f: line = f.read() cnt, new_len = line.split("|") if new_len == '0' or new_len == '': new_len = u"Größe unbekannt" else: new_len = humanbytes(new_len) else: cnt = '' # PLog("%d.dlcnt: %s" % (i, cnt)) # Debug if cnt != '' and cnt != '0': msg1 = "Downloads" msg2 = "Anzahl: %s | %s" % (cnt, new_len) xbmcgui.Dialog().notification(msg1, msg2, icon, 2000) i = i + 1 xbmc.sleep(2000) PLog('get_active_dls_stop:') #-------------------------- # Abbruch durch Addon oder Kodi if os.path.exists(DL_CHECK): os.remove(DL_CHECK) # Lock dl_check_alive entfernen PLog("dl_check_alive_entfernt") if os.path.exists(DL_CNT): os.remove(DL_CNT) # Zähler dl_cnt entfernen PLog("dl_cnt_entfernt") return
def Kika_VideosBeliebt(): PLog('Kika_VideosBeliebt:') li = xbmcgui.ListItem() li = home(li, ID='Kinderprogramme') # Home-Button path = 'https://www.kika.de/videos/allevideos/allevideos-buendelgruppen100.html' page, msg = get_page(path) if page == '': msg1 = "Fehler in Kika_VideosBeliebt:" msg2 = msg xbmcgui.Dialog().ok(ADDON_NAME, msg1, msg2, '') return li PLog(len(page)) buendel = blockextract('teaser teaserIdent', page) PLog(len(buendel)) for s in buendel: # PLog(s[0:40]) # bei Bedarf href = BASE_KIKA + stringextract('href=\"', '\"', s) img = stringextract('<noscript>', '</noscript>', s).strip() # Bildinfo separieren img_alt = stringextract('alt=\"', '\"', img) img_src = stringextract('src="', '"', img) if img_src.startswith('http') == False: img_src = BASE_KIKA + img_src dachzeile = stringextract('<h4 class=\"headline\">', '</h4>', s) headline = stringextract('page=artikel\">', '</a>', dachzeile).strip() stitle = headline stitle = unescape(stitle); stitle = repl_json_chars(stitle) img_alt = unescape(img_alt); PLog('Satz:') PLog(href);PLog(stitle);PLog(img_alt);PLog(img_src) href=py2_encode(href); stitle=py2_encode(stitle); img_src=py2_encode(img_src); if 'KiKA LIVE' in stitle: # s. Main_KIKA continue else: fparams="&fparams={'path': '%s', 'title': '%s', 'thumb': '%s'}" %\ (quote(href), quote(stitle), quote(img_src)) addDir(li=li, label=stitle, action="dirList", dirID="resources.lib.childs.Kika_Videos", fanart=img_src, thumb=img_src, fparams=fparams, tagline=img_alt) xbmcplugin.endOfDirectory(HANDLE, cacheToDisc=True)
def top_level_page(): """The main menu""" if addon.getSetting(SettingID.STARTUP_MSG) == 'true': dialog = xbmcgui.Dialog() try: dialog.textviewer(S.THEO_WARN, S.DISCLAIMER) # Kodi v16 except AttributeError: dialog.ok(S.THEO_WARN, S.DISCLAIMER) addon.setSetting(SettingID.STARTUP_MSG, 'false') # Auto set language, if it has never been set and Kodi is configured for something else then English isolang = xbmc.getLanguage(xbmc.ISO_639_1) if not addon.getSetting(SettingID.LANG_HIST) and isolang != 'en': try: # Search for matching language, save setting (and update translations) language_dialog(preselect=isolang) # Reload for this instance global global_language global_language = addon.getSetting(SettingID.LANG) or 'E' except StopIteration: # No suitable language was found, just write something to history, so this check won't run again addon.setSetting(SettingID.LANG_HIST, 'E') fanart = os.path.join(addon.getAddonInfo('path'), addon.getAddonInfo('fanart')) MenuItem( url=request_to_self(M.BIBLE), title=T.BIBLE or S.BIBLE, icon=ICON_BIBLE, fanart=fanart ).add_item_in_kodi() MenuItem( url=request_to_self(M.MAGAZINES), title=T.MAGAZINES or S.MAGAZINES, icon=ICON_WATCHTOWER, fanart=fanart ).add_item_in_kodi() MenuItem( url=request_to_self(M.BOOKS), title=T.BOOKS or S.BOOKS, icon=ICON_BOOKS, fanart=fanart ).add_item_in_kodi() xbmcplugin.endOfDirectory(addon_handle)
def get_video_url(plugin, item_id, video_id, video_id_ext, download_mode=False, **kwargs): resp = urlquick.get(URL_VIDEO % (item_id, get_token(item_id), video_id)) json_parser = json.loads(resp.text) video_streams = json_parser['video']['medias'] final_video_url = '' if DESIRED_QUALITY == "DIALOG": all_datas_videos_quality = [] all_datas_videos_path = [] for datas in video_streams: all_datas_videos_quality.append("Video Height : " + str(datas['frame_height']) + " (Encoding : " + str(datas['encoding_rate']) + ")") all_datas_videos_path.append(datas['video_url']) seleted_item = xbmcgui.Dialog().select( plugin.localize(LABELS['choose_video_quality']), all_datas_videos_quality) if seleted_item > -1: final_video_url = all_datas_videos_path[seleted_item] else: return False elif DESIRED_QUALITY == 'BEST': # GET LAST NODE (VIDEO BEST QUALITY) url_best_quality = '' for datas in video_streams: url_best_quality = datas['video_url'] final_video_url = url_best_quality else: # DEFAULT VIDEO final_video_url = json_parser['video']['video_url'] if download_mode: return download.download_video(final_video_url) return final_video_url
def run(context, url, name): _dialog = xbmcgui.Dialog() context.plex_network = plex.Plex(context.settings, load=True) tree = get_xml(context, url) if tree is None: return try: name = unquote_plus(name) except: # pylint: disable=bare-except pass operations = {} plugins = tree.findall('Directory') for idx, plugin in enumerate(plugins): operations[idx] = plugin.get('title') # If we find an install option, switch to a yes/no dialog box if operations[idx].lower() == 'install': LOG.debug('Not installed. Print dialog') result = \ _dialog.yesno(i18n('Plex Online'), i18n('About to install') + ' ' + name) if result: LOG.debug('Installing....') _ = get_xml(context, url + '/install') return # Else continue to a selection dialog box result = _dialog.select(i18n('This plugin is already installed'), list(operations.values())) if result == -1: LOG.debug('No option selected, cancelling') return LOG.debug('Option %s selected. Operation is %s' % (result, operations[result])) item_url = url + '/' + operations[result].lower() _ = get_xml(context, item_url) xbmc.executebuiltin('Container.Refresh')
def downloadAPK(self, url, dest): if self.fileExists(dest): return self.installAPK(dest) start_time = time.time() dia = xbmcgui.DialogProgress() fle = dest.rsplit('/', 1)[1] dia.create(ADDON_NAME, LANGUAGE(30002) % fle) try: urllib.request.urlretrieve( url.rstrip('/'), dest, lambda nb, bs, fs: self.pbhook( nb, bs, fs, dia, start_time, fle)) except Exception as e: dia.close() xbmcgui.Dialog().notification(ADDON_NAME, LANGUAGE(30001), ICON, 4000) log("downloadAPK, Failed! (%s) %s" % (url, str(e)), xbmc.LOGERROR) return self.deleleAPK(dest) dia.close() return self.installAPK(dest)
def run(context): context.plex_network = plex.Plex(context.settings, load=True) server_uuid = get_argv()[2] metadata_id = get_argv()[3] LOG.debug('Deleting media at: %s' % metadata_id) result = xbmcgui.Dialog().yesno( i18n('Confirm file delete?'), i18n('Delete this item? This action will delete media ' 'and associated data files.')) if result: LOG.debug('Deleting....') server = context.plex_network.get_server_from_uuid(server_uuid) server.delete_metadata(metadata_id) xbmc.executebuiltin('Container.Refresh')
def playVideo(vid, live=False): if live: url = getStreamUrl(vid, live=True) else: url = getStreamUrl(vid) xbmc.log("DAILYMOTION - FinalUrl = {0}".format(url), xbmc.LOGDEBUG) if url: listitem = xbmcgui.ListItem(path=url) if '.m3u8' in url: listitem.setMimeType("application/x-mpegURL") else: listitem.setMimeType("video/mp4") listitem.setContentLookup(False) xbmcplugin.setResolvedUrl(pluginhandle, True, listitem=listitem) else: xbmcgui.Dialog().notification('Info:', translation(30022), _icon, 5000, False)
def _widevine_eula(self): """Displays the Widevine EULA and prompts user to accept it.""" if os.path.exists(os.path.join(self._ia_cdm_path(), config.WIDEVINE_LICENSE_FILE)): license_file = os.path.join(self._ia_cdm_path(), config.WIDEVINE_LICENSE_FILE) with open(license_file, 'r') as f: eula = f.read().strip().replace('\n', ' ') else: # grab the license from the x86 files log('Acquiring Widevine EULA from x86 files.') url = config.WIDEVINE_DOWNLOAD_URL.format(version=self._latest_widevine_version(eula=True), os='mac', arch='x64') downloaded = self._http_download(url, message=localize(30025)) # Acquiring EULA if not downloaded: return False with zipfile.ZipFile(self._download_path) as z: with z.open(config.WIDEVINE_LICENSE_FILE) as f: eula = f.read().decode().strip().replace('\n', ' ') return xbmcgui.Dialog().yesno(localize(30026), eula, yeslabel=localize(30027), nolabel=localize(30028)) # Widevine CDM EULA
def _custom_access_urls(self): choices = [] append_choice = choices.append append_choice(i18n('Add custom access url')) for url in self.access_urls: append_choice(url) choice = xbmcgui.Dialog().select(i18n('Custom access urls'), choices) if choice < 0: self._refresh() return if choice == 0: self._add_custom_access_url() else: self._modify_custom_access_url( choice - 1) # shift index to compensate for 'add' choice
def import_ids(self, what, filename, action): try: ok = False f = xbmcvfs.File(filename, 'r') ids = f.read().decode('utf-8').split('\n') f.close() ids = [item.split('\t')[0] for item in ids] ids = [item for item in ids if len(item) > 0] if len(ids) > 0: ok = action(ids) if ok: xbmcgui.Dialog().notification( _P(what), _S(Msg.i30429).format(n=len(ids)), xbmcgui.NOTIFICATION_INFO) except Exception as e: log.logException(e) return ok
def user_playlist_delete(playlist_id): dialog = xbmcgui.Dialog() playlist = session.get_playlist(playlist_id) ok = dialog.yesno( _T(Msg.i30235), _T(Msg.i30236).format(name=playlist.title, count=playlist.numberOfItems)) if ok: session.show_busydialog(_T(Msg.i30235), playlist.name) try: session.user.delete_playlist(playlist_id) except Exception as e: log.logException(e, txt='Couldn' 't delete playlist %s' % playlist_id) traceback.print_exc() session.hide_busydialog() xbmc.executebuiltin('Container.Refresh()')
def cleanLibrary(self, cronJob): # check if we should verify with user first unless we're on 'clean after update' if (utils.getSettingBool('user_confirm_clean') and utils.getSettingInt('clean_timer') != 0): # user can decide 'no' here and exit this runClean = xbmcgui.Dialog().yesno(utils.getString(30000), utils.getString(30052), line2=utils.getString(30053), autoclose=15000) if (not runClean): return # run the clean operation utils.log("Cleaning Database") cronJob.executeCommand() # write last run time, will trigger notifications self.writeLastRun()
def Kikaninchen_Videos(path): PLog('Kikaninchen_Videos') li = xbmcgui.ListItem() li = home(li, ID='Kinderprogramme') # Home-Button page, msg = get_page(path) if page == '': msg1 = "Fehler in Kikaninchen_Videos:" msg2 = msg xbmcgui.Dialog().ok(ADDON_NAME, msg1, msg2, '') return li videos = blockextract('class="av-playerContainer"', page) # 16 pro Seite PLog(len(videos)) mediatype='' if SETTINGS.getSetting('pref_video_direct') == 'true': # Kennz. Video für Sofortstart mediatype='video' for s in videos: # stringextract('', '', s) href = ref = stringextract('dataURL:\'', '\'}', s) # Link Videodetails (..avCustom.xml) PLog(href); # PLog(s); # Bei Bedarf img = stringextract('<noscript>', '</noscript>', s).strip() # Bildinfo separieren img_alt = stringextract('alt="', '"', img) img_alt = unescape(img_alt) img_src = stringextract('src="', '"', img) if img_src.startswith('http') == False: img_src = BASE_KIKA + img_src stitle = stringextract('title="', '"', s) stitle = unescape(stitle) duration = stringextract('icon-duration">', '</span>', s) tagline = duration + ' Minuten' stitle = repl_json_chars(stitle) img_alt = repl_json_chars(img_alt); PLog(href); PLog(stitle); PLog(img_src); PLog(img_alt) href=py2_encode(href); href=py2_encode(href); stitle=py2_encode(stitle); img_src=py2_encode(img_src); img_alt=py2_encode(img_alt); fparams="&fparams={'path': '%s', 'title': '%s', 'thumb': '%s', 'summ': '%s', 'duration': '%s'}" %\ (quote(href), quote(stitle), quote(img_src), quote(img_alt), quote(duration)) addDir(li=li, label=stitle, action="dirList", dirID="resources.lib.childs.Kika_SingleBeitrag", fanart=img_src, thumb=img_src, fparams=fparams, tagline=tagline, mediatype=mediatype) xbmcplugin.endOfDirectory(HANDLE, cacheToDisc=True)
def _http_download(self, message=None): """Makes HTTP request and displays a progress dialog on download.""" log('Request URL: {0}'.format(self._url)) filename = self._url.split('/')[-1] try: req = urlopen(self._url) log('Response code: {0}'.format(req.getcode())) if 400 <= req.getcode() < 600: raise HTTPError('HTTP %s Error for url: %s' % (req.getcode(), self._url), response=req) except HTTPError: xbmcgui.Dialog().ok( LANGUAGE(30004), LANGUAGE(30013).format(filename)) # Failed to retrieve file return False if not message: # display "downloading [filename]" message = LANGUAGE(30015).format(filename) # Downloading file self._download_path = os.path.join(self._temp_path(), filename) total_length = float(req.info().get('content-length')) progress_dialog = xbmcgui.DialogProgress() progress_dialog.create(LANGUAGE(30014), message) # Download in progress chunk_size = 32 * 1024 with open(self._download_path, 'wb') as f: dl = 0 while True: chunk = req.read(chunk_size) if not chunk: break f.write(chunk) dl += len(chunk) percent = int(dl * 100 / total_length) if progress_dialog.iscanceled(): progress_dialog.close() req.close() return False progress_dialog.update(percent) progress_dialog.close() return True
def _get_proxies(self): usehttpproxy = self._get_global_setting('network.usehttpproxy') if usehttpproxy is False: return None httpproxytype = self._get_global_setting('network.httpproxytype') socks_supported = has_socks() if httpproxytype != 0 and not socks_supported: # Only open the dialog the first time (to avoid multiple popups) if socks_supported is None: xbmcgui.Dialog().ok('', LANGUAGE(30042)) # Requires PySocks return None proxy_types = ['http', 'socks4', 'socks4a', 'socks5', 'socks5h'] if 0 <= httpproxytype <= 5: httpproxyscheme = proxy_types[httpproxytype] else: httpproxyscheme = 'http' httpproxyserver = self._get_global_setting('network.httpproxyserver') httpproxyport = self._get_global_setting('network.httpproxyport') httpproxyusername = self._get_global_setting( 'network.httpproxyusername') httpproxypassword = self._get_global_setting( 'network.httpproxypassword') if httpproxyserver and httpproxyport and httpproxyusername and httpproxypassword: proxy_address = '%s://%s:%s@%s:%s' % ( httpproxyscheme, httpproxyusername, httpproxypassword, httpproxyserver, httpproxyport) elif httpproxyserver and httpproxyport and httpproxyusername: proxy_address = '%s://%s@%s:%s' % (httpproxyscheme, httpproxyusername, httpproxyserver, httpproxyport) elif httpproxyserver and httpproxyport: proxy_address = '%s://%s:%s' % (httpproxyscheme, httpproxyserver, httpproxyport) elif httpproxyserver: proxy_address = '%s://%s' % (httpproxyscheme, httpproxyserver) else: return None return dict(http=proxy_address, https=proxy_address)
def _check_drm(self): """Main function for ensuring that specified DRM system is installed and available.""" if not self.drm or self.inputstream_addon != 'inputstream.adaptive': return True if self.drm == 'widevine': if not self._has_widevine(): dialog = xbmcgui.Dialog() if dialog.yesno(LANGUAGE(30041), LANGUAGE(30002), yeslabel=LANGUAGE(30038), nolabel=LANGUAGE(30028)): return self._install_widevine() else: return False return self._check_widevine() return True
def get_video_url(plugin, item_id, video_url, download_mode=False, **kwargs): """Get video URL and start video player""" info_video_html = urlquick.get(video_url, headers={ 'User-Agent': web_utils.get_random_ua() }, max_age=-1).text video_id = re.compile('player=7&pod=(.*?)[\"\&]').findall( info_video_html)[0] info_video_json = urlquick.get(INFO_VIDEO % video_id).text info_video_json = json.loads(info_video_json) stream_id = re.compile('images/(.*).jpg').findall( info_video_json["thumbnail_url_static"])[0].split('/')[1] desired_quality = Script.setting.get_string('quality') all_datas_videos_quality = [] all_datas_videos_path = [] for quality in QUALITIES_STREAM: all_datas_videos_quality.append(quality) all_datas_videos_path.append(INFO_STREAM % (quality, stream_id)) url = '' if desired_quality == "DIALOG": seleted_item = xbmcgui.Dialog().select( plugin.localize(LABELS['choose_video_quality']), all_datas_videos_quality) if seleted_item == -1: url = '' url = all_datas_videos_path[seleted_item] elif desired_quality == "BEST": url_best = '' for data_video in all_datas_videos_path: url_best = data_video url = url_best else: url = all_datas_videos_path[0] if download_mode: return download.download_video(url) return url
def _http_get(self): ''' Perform an HTTP GET request and return content ''' log('Request URL: {0}'.format(self._url)) try: req = urlopen(self._url) log('Response code: {0}'.format(req.getcode())) if 400 <= req.getcode() < 600: raise HTTPError('HTTP %s Error for url: %s' % (req.getcode(), self._url), response=req) except HTTPError: xbmcgui.Dialog().ok( LANGUAGE(30004), LANGUAGE(30013).format( self._url.split('/')[-1])) # Failed to retrieve file return None content = req.read() log('Response: {0}'.format(content)) return content
def select(heading=None, options=None, autoclose=None, **kwargs): heading = _make_heading(heading) options = options or [] if KODI_VERSION < 17: kwargs.pop('preselect', None) kwargs.pop('useDetails', None) if autoclose: kwargs['autoclose'] = autoclose _options = [] for option in options: if issubclass(type(option), Item): option = option.label if KODI_VERSION < 17 else option.get_li() _options.append(option) return xbmcgui.Dialog().select(heading, _options, **kwargs)
def _update_widevine(self): """Prompts user to upgrade Widevine CDM when a newer version is available.""" last_update = ADDON.getSetting('last_update') if last_update and not self._first_run(): last_update_dt = datetime.fromtimestamp( float(ADDON.getSetting('last_update'))) if last_update_dt + timedelta( days=config.WIDEVINE_UPDATE_INTERVAL_DAYS ) >= datetime.utcnow(): log('Widevine update check was made on {date}', date=last_update_dt.isoformat()) return wv_config = self._load_widevine_config() latest_version = self._latest_widevine_version() if 'x86' in self._arch(): component = 'Widevine CDM' current_version = wv_config['version'] else: component = 'Chrome OS' current_version = self._select_best_chromeos_image( wv_config)['version'] log('Latest {component} version is {version}', component=component, version=latest_version) log('Current {component} version installed is {version}', component=component, version=current_version) if LooseVersion(latest_version) > LooseVersion(current_version): log('There is an update available for {component}', component=component) if xbmcgui.Dialog().yesno(localize(30040), localize(30033), yeslabel=localize(30034), nolabel=localize(30028)): self.install_widevine() else: log('User declined to update {component}.', component=component) else: log('User is on the latest available {component} version.', component=component)