def createSubFolders(self): progress = DialogProgress() try: progress.create(SF_SUBFOLDERS_PROGRESS_HEADER, SF_SUBFOLDERS_PROGRESS_MSG) row = "id_channel" if getSFFoldersPattern() == AddonConst.SF_XMLTV_ID_PATTERN else 'display_name' request = "SELECT %s FROM channels" % row if self.database is None or self.cursor is None: notify(SF_CHANNELS_INFOS_ERROR) progress.close() return self.cursor.execute(request) channels = self.cursor.fetchall() i = 1 for channel in channels: if not isfile(join(getSFFolder(translate=True), channel[0])): try: mkdir(join(getSFFolder(translate=True), channel[0])) except OSError: pass progress.update(int( ( i / float(len(channels)) ) * 100), "", SF_DIR_STRING + ' %i/%i' % (i, len(channels))) i += 1 except SqliteError: progress.close() if DEBUG: notify(SF_CHANNELS_INFOS_ERROR) progress.close()
def _http_download(self, url, message=None): """Makes HTTP request and displays a progress dialog on download.""" req = self._http_request(url) if req is None: return None filename = url.split('/')[-1] if not message: # display "downloading [filename]" message = localize(30015, filename=filename) # Downloading file self._download_path = os.path.join(self._temp_path(), filename) total_length = float(req.info().get('content-length')) progress_dialog = DialogProgress() progress_dialog.create(localize(30014), message) # Download in progress chunk_size = 32 * 1024 with open(self._download_path, 'wb') as image: size = 0 while True: chunk = req.read(chunk_size) if not chunk: break image.write(chunk) size += len(chunk) percent = int(size * 100 / total_length) if progress_dialog.iscanceled(): progress_dialog.close() req.close() return False progress_dialog.update(percent) progress_dialog.close() return True
def _check_for_updates(): try: # import needed classes from xbmcgui import Dialog, DialogProgress # create dialog pDialog = DialogProgress() # Addon class Addon = XBMCADDON().Addon( id=os.path.basename( cwd ) ) # give feedback pDialog.create( Addon.getAddonInfo( "Name" ), Addon.getLocalizedString( 30760 ) ) pDialog.update( 0 ) # import module import urllib2 # url to addon.xml file url = "%ssvn/addons/%s/addon.xml" % ( Addon.getSetting( "Repo" ), Addon.getAddonInfo( "Id" ), ) # get addon.xml source xml = urllib2.urlopen( url ).read() # parse version version = re.search( "<addon id=\"[^\"]+\".+?name=\"[^\"]+\".+?version=\"([^\"]+)\".+?provider-name=\"[^\"]+\".*?>", xml, re.DOTALL ).group( 1 ) # set proper message msg1 = Addon.getLocalizedString( 30700 ) % ( Addon.getAddonInfo( "Version" ), ) msg2 = [ Addon.getLocalizedString( 30701 ), Addon.getLocalizedString( 30702 ) % ( version, ) ][ version > Addon.getAddonInfo( "Version" ) ] except Exception, e: # set proper error messages msg1 = Addon.getLocalizedString( 30770 ) msg2 = str( e )
def login(plugin): method = Dialog().yesno("Login", "Select Login Method", yeslabel="Keyboard", nolabel="WEB") if method == 1: login_type = Dialog().yesno("Login", "Select Login Type", yeslabel="OTP", nolabel="Password") if login_type == 1: mobile = keyboard("Enter your Jio mobile number") error = sendOTP(mobile) if error: Script.notify("Login Error", error) return otp = keyboard("Enter OTP", hidden=True) ULogin(mobile, otp, mode="otp") elif login_type == 0: username = keyboard("Enter your Jio mobile number or email") password = keyboard("Enter your password", hidden=True) ULogin(username, password) elif method == 0: pDialog = DialogProgress() pDialog.create( 'JioTV', 'Visit [B]http://%s:48996/[/B] to login' % socket.gethostbyname(socket.gethostname())) for i in range(120): sleep(1) with PersistentDict("headers") as db: headers = db.get("headers") if headers or pDialog.iscanceled(): break pDialog.update(i) pDialog.close()
def generate_pairing_code(): monitor = Monitor() progress = DialogProgress() progress.create(get_string(32000), get_string(32001)) chromecast = YoutubeCastV1() pairing_code = chromecast.pair() i = 0 if PY3: progress.update(i, message="{} {}".format(get_string(32002), pairing_code)) else: progress.update(i, get_string(32002), pairing_code) start_time = time.time() while not monitor.abortRequested( ) and not chromecast.has_client and not progress.iscanceled() and not ( time.time() - start_time) > (60 * 1): i += 10 if i > 100: i = 0 if PY3: progress.update(i, message="{} {}".format(get_string(32002), pairing_code)) else: progress.update(i, get_string(32002), pairing_code) monitor.waitForAbort(2) progress.close()
def wait_for_metadata(info_hash): close_busy_dialog() percent = 0 timeout = get_metadata_timeout() start_time = time.time() monitor = Monitor() progress = DialogProgress() progress.create(ADDON_NAME, translate(30237)) try: while not api.torrent_status(info_hash).has_metadata: if monitor.waitForAbort(0.5): raise PlayError("Abort requested") passed_time = time.time() - start_time if 0 < timeout: if timeout < passed_time: notification(translate(30238)) raise PlayError("No metadata after timeout") percent = int(100 * passed_time / timeout) else: percent = 0 if percent == 100 else (percent + 5) progress.update(percent) if progress.iscanceled(): raise CanceledError("User canceled metadata", info_hash) finally: progress.close()
def play_Video(): progress = DialogProgress() progress.create('Loading') progress.update(10, "", 'Loading Video Info', "") img = plugin.args['img'][0] video_url = plugin.args['video'][0] plot = plugin.args['plot'][0] # print '=======================>' progress.update(30, "", 'Loading Web Files', "") # print video_url p = Get('http://www.zxzjs.com/video/' + video_url + '.html') # match = re.search(r'\"url\":\"(.*?mp4)\"',p) # match = re.search(r'cms_player\s*=\s*{"url":"(.*?)"',p) match = re.search(r'url":"(https.*?)"', p) #print match.group(1).replace('\/','/') #title = re.search(r'<h4 class=\"title\"><a href=\".*?\">(.*?)</a></h4>',p).group(1) title = "video" # li = ListItem(title + ' ' + video_url,thumbnailImage=img) # plot = '' # plotObj = re.search(r'<span class=\"left text-muted\">简介:</span><p>(.*?)</p>',p) # if plotObj: # plot = plotObj.group(1) # print '=======================>' # print plot # li.setInfo("video",{ # # 'director': jsonArr['list']['anime']['author'], # 'title': title, # # 'originaltitle': jsonArr['list']['anime']['name_jpn'], # 'plot': plot # # 'sorttitle': jsonEpisodes['title'], # # 'status': jsonArr['list']['anime']['is_ended'] # }) video_url = match.group(1).replace("\\", "") progress.update(60, "", "Analyse Video Url", "") print("0", video_url, 'http://www.zxzjs.com/video/' + plugin.args['video'][0] + '.html') p = Get(video_url, referer='http://www.zxzjs.com/video/' + plugin.args['video'][0] + '.html') video_url = re.search(r"'(.*?)',", p).group(1) progress.update(90, "", "Decode Video Url", "") print("1", video_url) # video_url = str(decode.var['decode'](video_url)).replace("'","") video_url = decode.decode(video_url) print("2", video_url) #dialog.ok(video_url,video_url) progress.update(100, "", "", "") # addDirectoryItem(plugin.handle, video_url, li) progress.close() playUrl(video_url, img, plot)
def show_progress(self, heading='', message=''): """ Show a Kodi progress dialog """ from xbmcgui import DialogProgress if not heading: heading = self._addon.getAddonInfo('name') progress = DialogProgress() progress.create(heading=heading, line1=message) return progress
def progress(heading='', message=''): """ Show a Kodi progress dialog """ from xbmcgui import DialogProgress if not heading: heading = ADDON.getAddonInfo('name') dialog_progress = DialogProgress() dialog_progress.create(heading=heading, line1=message) return dialog_progress
def login(plugin): msg = "1. Go to [B]https://tv.hotstar.com[/B]\n2. Login with your hotstar account[CR]3. Enter the 4 digit code : " pdialog = DialogProgress() pdialog.create("Login", msg + "Loading...") for code, i in api.doLogin(): if pdialog.iscanceled() or i == 100: break else: time.sleep(1) pdialog.update(i, msg + "[B][UPPERCASE]%s[/UPPERCASE][/B]" % code) pdialog.close()
def login(plugin): pdialog = DialogProgress() pdialog.create("Login", "1. Go to [B]hotstar.com/in/activate[/B]", line2="2. Login with your hotstar account[CR]3. Enter the 4 digit code", line3="Loading...") for code, i in api.doLogin(): if pdialog.iscanceled() or i == 100: break else: time.sleep(1) pdialog.update(i, line3="[B][UPPERCASE]%s[/UPPERCASE][/B]" % code) pdialog.close()
def _install_widevine_x86(self): """Install Widevine CDM on x86 based architectures.""" cdm_version = self._latest_widevine_version() cdm_os = config.WIDEVINE_OS_MAP[system_os()] cdm_arch = config.WIDEVINE_ARCH_MAP_X86[self._arch()] url = config.WIDEVINE_DOWNLOAD_URL.format(version=cdm_version, os=cdm_os, arch=cdm_arch) downloaded = self._http_download(url) if downloaded: progress_dialog = DialogProgress() progress_dialog.create( heading=localize(30043), line1=localize(30044)) # Extracting Widevine CDM progress_dialog.update( 94, line1=localize(30049)) # Installing Widevine CDM self._unzip(self._ia_cdm_path()) progress_dialog.update(97, line1=localize(30050)) # Finishing self._cleanup() if not self._widevine_eula(): return False if self._has_widevine(): if os.path.lexists(self._widevine_config_path()): os.remove(self._widevine_config_path()) os.rename( os.path.join(self._ia_cdm_path(), config.WIDEVINE_MANIFEST_FILE), self._widevine_config_path()) wv_check = self._check_widevine() if wv_check: progress_dialog.update(100, line1=localize( 30051)) # Widevine CDM successfully installed. Dialog().notification(localize(30037), localize( 30051)) # Success! Widevine successfully installed. progress_dialog.close() return wv_check progress_dialog.close() Dialog().ok(localize(30004), localize(30005)) # An error occurred return False
def play_info_hash(info_hash, timeout=30, buffer=True): start_time = time.time() monitor = Monitor() progress = DialogProgress() progress.create(ADDON_NAME, translate(30237)) try: while not api.torrent_status(info_hash).has_metadata: if monitor.waitForAbort(0.5): raise PlayError("Abort requested") passed_time = time.time() - start_time if 0 < timeout < passed_time: notification(translate(30238)) raise PlayError("No metadata after timeout") progress.update(int(100 * passed_time / timeout)) if progress.iscanceled(): raise PlayError("User canceled metadata") finally: progress.close() files = api.files(info_hash, status=False) min_candidate_size = get_min_candidate_size() * 1024 * 1024 candidate_files = [ f for f in files if is_video(f.path) and f.length >= min_candidate_size ] if not candidate_files: notification(translate(30239)) raise PlayError("No candidate files found for {}".format(info_hash)) elif len(candidate_files) == 1: chosen_file = candidate_files[0] else: sort_files(candidate_files) chosen_index = Dialog().select(translate(30240), [f.name for f in candidate_files]) if chosen_index < 0: raise PlayError("User canceled dialog select") chosen_file = candidate_files[chosen_index] if buffer: buffer_and_play(info_hash, chosen_file.id) else: play(info_hash, chosen_file.id)
def clean(self): """ Clean up any watched videos in the Kodi library, satisfying any conditions set via the addon settings. :rtype: (dict, int) :return: A single-line (localized) summary of the cleaning results to be used for a notification, plus a status. """ debug("Starting cleaning routine.") if get_value(clean_when_idle) and xbmc.Player().isPlaying(): debug("Kodi is currently playing a file. Skipping cleaning.", xbmc.LOGWARNING) return None, self.exit_status cleaning_results = [] if not get_value(clean_when_low_disk_space) or (get_value(clean_when_low_disk_space) and disk_space_low()): for video_type in KNOWN_VIDEO_TYPES: if self.exit_status != self.STATUS_ABORTED: progress = DialogProgress() if not self.silent: progress.create(f"{ADDON_NAME} - {LOCALIZED_VIDEO_TYPES[video_type].capitalize()}") progress_text = f"{translate(32618).format(type=LOCALIZED_VIDEO_TYPES[video_type])}" progress.update(0, progress_text) self.monitor.waitForAbort(2) if self.user_aborted(progress): progress.close() break else: cleaned_files, status = self.clean_category(video_type, progress) cleaning_results.extend(cleaned_files) if not self.silent: progress.close() else: debug("User aborted") break self.clean_library(cleaning_results) Log().prepend(cleaning_results) return cleaning_results, self.exit_status
def buffer_and_play(info_hash, file_id): api.download_file(info_hash, file_id, buffer=True) monitor = Monitor() progress = DialogProgress() progress.create(ADDON_NAME) try: timeout = get_buffering_timeout() start_time = time.time() last_time = 0 last_done = 0 while True: current_time = time.time() status = api.file_status(info_hash, file_id) if status.buffering_progress >= 100: break total_done = status.buffering_total * status.buffering_progress / 100 speed = float(total_done - last_done) / (current_time - last_time) last_time = current_time last_done = total_done progress.update( int(status.buffering_progress), "{} - {:.2f}%\n{} {} {} - {}/s\n\n".format( get_state_string(status.state), status.buffering_progress, sizeof_fmt(total_done), translate(30244), sizeof_fmt(status.buffering_total), sizeof_fmt(speed))) if progress.iscanceled(): raise PlayError("User canceled buffering") if 0 < timeout < current_time - start_time: notification(translate(30236)) raise PlayError("Buffering timeout reached") if monitor.waitForAbort(1): raise PlayError("Abort requested") finally: progress.close() play(info_hash, file_id)
def wait_for_buffering_completion(info_hash, file_id): close_busy_dialog() info = api.file_info(info_hash, file_id) of = translate(30244) timeout = get_buffering_timeout() last_time = last_done = 0 start_time = time.time() monitor = Monitor() progress = DialogProgress() progress.create(ADDON_NAME) try: while True: current_time = time.time() status = api.file_status(info_hash, file_id) if status.buffering_progress >= 100: break total_done = status.buffering_total * status.buffering_progress / 100 speed = float(total_done - last_done) / (current_time - last_time) last_time = current_time last_done = total_done progress.update( int(status.buffering_progress), "{} - {:.2f}%\n{} {} {} - {}/s\n{}\n".format( get_state_string(status.state), status.buffering_progress, sizeof_fmt(total_done), of, sizeof_fmt(status.buffering_total), sizeof_fmt(speed), info.name)) if progress.iscanceled(): raise CanceledError("User canceled buffering", info_hash) if 0 < timeout < current_time - start_time: notification(translate(30236)) raise PlayError("Buffering timeout reached") if monitor.waitForAbort(1): raise PlayError("Abort requested") finally: progress.close()
def login(plugin): isKeyboard = Dialog().yesno("Login", "Select Login Type", yeslabel="Keyboard", nolabel="WEB") if isKeyboard: username = keyboard("Enter your Jio mobile number or email") password = keyboard("Enter your password", hidden=True) ULogin(username, password) else: pDialog = DialogProgress() pDialog.create( 'JioTV', 'Visit [B]http://%s:48996/web/login[/B] to login' % socket.gethostbyname(socket.gethostname())) for i in range(120): sleep(1) with PersistentDict("headers") as db: headers = db.get("headers") if headers or pDialog.iscanceled(): break pDialog.update(i) pDialog.close()
class EpgXml(object): epg_db = None progress_bar = None def __init__(self, database, cursor, progress_bar=True): self.epg_db = EpgDb(database, cursor) self.progress_bar = DialogProgress( ) if progress_bar else DialogProgressBG() ''' Global entry point to get / parse and push xmltv data into db. ''' def getXMLTV(self): if self.epg_db.isDBInitOk(): if isfile(getEpgXmlFilePath()): remove(getEpgXmlFilePath()) if getXMLTVSourceType() == AddonConst.XMLTV_SOURCE_LOCAL: self.__getLocalXmltv(getXMLTVURLLocal()) elif getXMLTVSourceType() == AddonConst.XMLTV_SOURCE_URL: self.__getUrlXmltv(getXMLTVURLRemote()) else: notify(strings.XMLTV_LOAD_ERROR) return return self.__parseXMLTV() ''' Basic xml file checks ''' def __getLocalXmltv(self, local_file): if not isfile(local_file): notify(strings.XMLTV_FILE_NOT_FOUND) else: if not isXMLTVCompressed() and not local_file.endswith(".xml"): notify(strings.BAD_XMLTV_FILE_TYPE) elif not isXMLTVCompressed(): # Moving to userdata if not getXMLTVSourceType() == AddonConst.XMLTV_SOURCE_URL: copyfile(local_file, getEpgXmlFilePath()) else: # Uncompress and moving to userdata self.__uncompressAndMove(local_file) ''' Retrive an xmltv file from a given url. ''' def __getUrlXmltv(self, url_file_source): import ssl ssl._create_default_https_context = ssl._create_unverified_context dest_file = getEpgXmlFilePath() try: self.progress_bar.create(strings.SFX_EPG_UPDATE_HEADER, strings.SFX_DOWNLOADING_MSG) download = urlopen(url_file_source, timeout=30) if isfile(dest_file): remove(dest_file) tsf = open(dest_file, "w") tsf.write(download.read()) tsf.close() del tsf self.progress_bar.close() self.__getLocalXmltv(dest_file) except HTTPError as e: if e.code == 304: notify(strings.HTTP_UNCHANGED_REMOTE_FILE, e.reason) elif e.code == 301: notify(strings.HTTP_MOVED_PERMANENTLY, e.reason) elif e.code == 400: notify(strings.HTTP_BAD_REQUEST, e.reason) elif e.code in [401, 403]: notify(strings.HTTP_UNAUTHORIZED, e.reason) elif e.code == 404: notify(strings.HTTP_NOT_FOUND, e.reason) elif e.code == 500: notify(strings.HTTP_INTERNAL_SERVER_ERROR, e.reason) elif e.code == 502: notify(strings.HTTP_BAD_GATEWAY, e.reason) elif e.code == 503: notify(strings.HTTP_SERVER_OVERLOADED, e.reason) elif e.code == 504: notify(strings.HTTP_REQUEST_TIMEOUT, e.reason) else: notify(strings.HTTP_UNHANDLED_ERROR, e.reason) self.progress_bar.close() return ''' Uncompress zip, tar, ... archive and moves it into the right directory. ''' def __uncompressAndMove(self, zfile): dest = join(getAddonUserDataPath(), "epg.archive") if is_zipfile(zfile): try: with ZipFile(zfile, "r") as xmltv_zip: xmltv_zip.extractall(dest) xmltv_zip.close() except BadZipfile, LargeZipFile: if isdir(dest): rmtree(dest) notify(strings.ARCHIVE_ZIP_UNCOMPRESS_ERROR) return elif is_tarfile(zfile): try: with TarFile(zfile) as xmltv_tar: xmltv_tar.extractall(dest) xmltv_tar.close() except TarReadError: if isdir(dest): rmtree(dest) notify(strings.ARCHIVE_TAR_UNCOMPRESS_ERROR) return
class cLiveSPOpt(): def __init__(self): self.adn = Addon('plugin.video.xAmAx-Mod') def UrlADFLY(self, code): zero = '' un = '' for n, letter in enumerate(code): if n % 2 == 0: zero += code[n] else: un = code[n] + un clef = zero + un print "clef ADFLY: " + str(clef) clef = base64.b64decode(clef.encode("latin1")) return clef[2:] def ConvNom(self, Nom): NomRet = str(Nom) #.decode("latin1").encode("latin1","replace") NomRet = NomRet.replace(b64decode("SXB0djRzYXQuY29t"), "").replace( "L-FR: ", "").replace("FR: ", "").replace("FR : ", "").replace( "FR:", "").replace("FR|", "").replace("FR-", "").replace( " FR ", "").replace(" FR_", "").replace(" (FR)", "").replace( "ENF-", "").replace("FRENCH", "FRANCE").replace( "FRANCE", "FRANCE " ).replace("FRANCE ", "FRANCE ").replace( "+", " +" ).replace(" +", " +").replace( "FRANCE |", "").replace( "\R", "" ).replace( "(SERVER 1)", "" ).replace( "\xe2\x80\x99", "" ).replace( "\xc2\xa0", " " ).replace( "\xc3\xa9", "e" ).replace( "\xc3\x89", "E" ).replace( "\xc3\xa8", "e" ).replace( "\xc3\xa7", "c" ).replace( "\xc3\x94", "O" ).replace( "¯", "-" ).replace( ".", " " ).replace( "_", " " ).replace( "|", " " ).replace( "ALACART", "A LA CARTE" ).replace( "ALACARTE", "A LA CARTE" ).replace( "A-LA-CARTE", "A LA CARTE" ).replace( "&", "&" ).replace( b64decode( "W0NPTE9SIHJlZF0gTE9HQU4gVFZbL0NPTE9SXQ==" ), "") if NomRet.startswith("FR "): NomRet = NomRet[3:] while 1: if NomRet.startswith(' '): NomRet = NomRet[1:] else: break return NomRet.upper() def ConvText(self, Text): return Text.replace('\\/', '/').replace('&', '&').replace( '\xc9', 'E').replace('–', '-').replace('&', '&').replace( '’', '\'').replace('\r', '').replace('\n', '').replace( '\t', '').replace(''', "'").replace('"', '"').replace( '>', '>').replace('<', '<').replace(' ', '') def CreerBouquet(self, CheminxAmAx): Bouquet = [] print "CreerBouquet: CheminxAmAx= " + CheminxAmAx dbxAmAx = os.path.join(CheminxAmAx, "xAmAx.db") try: DBxAmAx = db(dbxAmAx) DBxAmAx.Delete("UrlBouquet") DBxAmAx.CreerTable( Table="UrlBouquet", colonnes= "`IDUrlB` INTEGER PRIMARY KEY AUTOINCREMENT,`IdBouquet` INTEGER,`IDChaine` INTEGER,`Url` TEXT,`NomAffichChaine` TEXT" ) IdUrlChaine = 0 for numTab in range(1, 5): if DBxAmAx.TableExist("List" + str(numTab)): #print "------List"+str(numTab) cBouq = DBxAmAx.Select(Table="Bouquet", Colonnes="IDBouquet, TriDesChaines", Where="", Order="Ordre ASC") for IDBouqu, TriDesChaines in cBouq: cChaine = DBxAmAx.Select( Table="ChaineBouquet", Colonnes="IDChaineB, NomChaine, PasDansChaine", Where="IDBouqChaine = " + str(IDBouqu), Order=str(TriDesChaines)) #print "-----cChaine: "+str(cChaine) for IDChaine, NomC, PasNom in cChaine: if PasNom != None and PasNom != "": ANDWHERE = "AND Nom NOT LIKE '%" + PasNom + "%' " else: ANDWHERE = "" cListCh = DBxAmAx.Select( Table="List" + str(numTab), Colonnes="*", Where="Nom LIKE '%" + str(NomC).upper() + "%' " + ANDWHERE, Order="Nom ASC") #print "-----cListCh: "+str(cListCh) for IdLP, Nom, Url, Entete in cListCh: IdUrlChaine += 1 DBxAmAx.Insert( Table="UrlBouquet", Colonnes= "IDUrlB,IdBouquet,IDChaine,Url,NomAffichChaine", Valeurs=(IdUrlChaine, IDBouqu, IDChaine, Url, Nom)) DBxAmAx.FinEnregistrement() except: print "Erreur de connection à la base xAmAx!" return "Erreur de connection à la base xAmAx!" return "OK" def RechercheChaine(self, CheminxAmAx): i = 0 j = 0 ListeEffacer = False dbxAmAx = os.path.join(CheminxAmAx, "xAmAx.db") M3uxAmAx = os.path.join(CheminxAmAx, "M3uTV.m3u") print "Ouverture de la Base de donnée xAmAx: " + dbxAmAx DBxAmAx = db(dbxAmAx) IdLP = 0 liste = [] liste.append([ 'Iptv4Sat', "https://www.iptv4sat.com/dl-iptv-french/", '"https://www.iptv4sat.com/download-attachment/([^"]+)".+?class="attachment-caption">([^<]+)<', '', 0, False ]) """liste.append( ['Iptv Gratuit', 'https://iptvgratuit.com/iptv-france/', '<h2 class="entry-title"><a href="(.+?)" rel="bookmark">(.+?)</a>', '<a class="more-link" title="(.+?)".+?href="(.+?)"', 0, False])""" NbMaj = len(liste) self.MajDiv = 100 / NbMaj self.TotMaj = 0 self.dp = DialogProgress() sleep(0.5) self.dp.create("Telechargement de la liste de chaine:") sleep(0.5) NbMajEc = 1 NbRecherche = 0 print "Liste de chaine 1 a afficher" ListeEffacer = True DivisionRech = (self.MajDiv - self.TotMaj) TxtFinal = "" for Nom, Url, Re1, Re2, NumM3u, TelLien in liste: NbRecherche += 1 if self.adn.getSetting(id="MajList" + str(NbRecherche)) == "true": log( '\t[PLUGIN] xAmAx-Mod: Recherche Liste de chaine ' + str(Nom), LOGNOTICE) #print "Recherche Liste de chaine "+str(Nom) self.dp.update(self.TotMaj, "Recherche Liste de chaine " + str(NbRecherche)) sleep(0.5) if Nom != "Iptv4Sat": Retour2, Erreur2 = self.ListTv(Url, Re1, Re2, NumM3u, TelLien, CheminxAmAx) log( '\t[PLUGIN] xAmAx-Mod: Nombre de résultat de la Liste de chaine ' + str(len(Retour2)), LOGNOTICE) #print "Nombre de résultat de la Liste de chaine "+str(len(Retour2)) if len(Retour2) > 0 and Erreur2 == "OK": try: DBxAmAx.Delete(Table="List" + str(NbRecherche)) except: pass DBxAmAx.CreerTable( Table="List" + str(NbRecherche), colonnes= "`IDLP` INTEGER PRIMARY KEY AUTOINCREMENT, `Nom` TEXT, `Url` TEXT, `Entete` TEXT" ) for NomTv, UrlTV in Retour2: IdLP += 1 DBxAmAx.Insert( Table="List" + str(NbRecherche), Colonnes="IDLP,Nom,Url", Valeurs=(IdLP, NomTv + " [COLOR gold](" + str(NbRecherche) + ")[/COLOR]", UrlTV)) #+"&name="+NomTv)) elif Erreur2 != "OK": executebuiltin( "XBMC.Notification(Mise à jour Liste TV " + str(NbRecherche) + " Impossible!!! ," + Erreur2 + ",5000,'')") else: Page = cDL().TelechargPage2(url=Url) #print Page try: part = re.compile(Re1, re.I + re.M + re.S).findall( self.ConvText(Page)) except: part = '' log('\t[PLUGIN] xAmAx-Mod: part = ' + str(part), LOGNOTICE) try: zip = 'https://www.iptv4sat.com/download-attachment/' + str( part[0][0][:-1]) #).group(1) except: zip = '' #Page = cDL().TelechargPage2(url=Url) #log('\t[PLUGIN] xAmAx-Mod: page = '+self.ConvText(Page), LOGNOTICE) try: udata = os.path.join(CheminxAmAx, "Telecharg") dest = os.path.join(udata, 'iptv4sat.zip') if not os.path.exists(udata): os.makedirs(udata) cDL().TelechargementZip(zip, dest, DPAff=False, Nom="Téléchargement Liste 1") #Page = cDL().TelechargPage2(url=Url) #log('\t[PLUGIN] xAmAx-Mod: page = '+self.ConvText(Page), LOGNOTICE) from resources.ziptools import ziptools unzipper = ziptools() unzipper.extract(dest, udata) os.remove(dest) dir = os.listdir(udata) for a in dir: if a.endswith('.m3u'): print "Ouverture de :" + os.path.join(udata, a) with open(os.path.join(udata, a), 'r') as fm3u: ListM3u = fm3u.read() Retour3 = self.TabM3u(ListM3u, True, True) os.remove(os.path.join(udata, a)) log( '\t[PLUGIN] xAmAx-Mod: Nombre de résultat de la Liste de chaine ' + str(len(Retour3)), LOGNOTICE) #print "Nombre de résultat de la Liste de chaine "+str(len(Retour3)) if len(Retour3) > 0: try: DBxAmAx.Delete(Table="List" + str(NbRecherche)) except: pass DBxAmAx.CreerTable( Table="List" + str(NbRecherche), colonnes= "`IDLP` INTEGER PRIMARY KEY AUTOINCREMENT, `Nom` TEXT, `Url` TEXT, `Entete` TEXT" ) for NomTv, UrlTV in Retour3: IdLP += 1 DBxAmAx.Insert( Table="List" + str(NbRecherche), Colonnes="IDLP,Nom,Url", Valeurs=( IdLP, NomTv + " [COLOR gold](" + str(NbRecherche) + ")[/COLOR]", UrlTV)) #+"&name="+NomTv)) else: executebuiltin( "XBMC.Notification(Mise à jour Liste TV " + str(NbRecherche) + " Impossible!!! ," + "Pas fichier dans la liste!" + ",5000,'')") else: os.remove(os.path.join(udata, a)) except: executebuiltin( "XBMC.Notification(Mise à jour Liste TV " + str(NbRecherche) + " Impossible!!! ," + "Pas fichier dans la liste!" + ", ,5000,'')") else: DBxAmAx.Delete(Table="List" + str(NbRecherche)) DBxAmAx.CreerTable( Table="List" + str(NbRecherche), colonnes= "`IDLP` INTEGER PRIMARY KEY AUTOINCREMENT, `Nom` TEXT, `Url` TEXT, `Entete` TEXT" ) DBxAmAx.FinEnregistrement() self.TotMaj = self.MajDiv * NbRecherche print "Telechargement de la liste de chaine:" + str( self.TotMaj) + "%" if NbRecherche < 4: for i in range(NbRecherche + 1, 5): DBxAmAx.Delete(Table="List" + str(i)) DBxAmAx.CreerTable( Table="List" + str(i), colonnes= "`IDLP` INTEGER PRIMARY KEY AUTOINCREMENT, `Nom` TEXT, `Url` TEXT, `Entete` TEXT" ) DBxAmAx.FinEnregistrement() self.dp.update( 100, "Nombre de résultat sur les " + str(NbRecherche) + " listes de chaines: " + str(IdLP)) sleep(1) self.dp.close() executebuiltin("XBMC.Notification(" + str(IdLP) + " Chaînes à jour,,,5000,'')") return "OK" def TabM3u(self, FichierTxt, F4m=False, cvNom=True, reComp='^#.+?:-?[0-9]*(.*?),(.*?)\n(.*?)\n', AjoutHttp="", AjoutFin=""): ret = [] TabM3u = re.compile(reComp, re.I + re.M + re.U + re.S).findall(FichierTxt) for Par, Nom, Url in TabM3u: if cvNom == True: Nom = self.ConvNom(Nom) Url = Url.split("|")[0].replace("\r", "") if F4m == True: if (not ".m3u8" in Url): Url = 'plugin://plugin.video.f4mTester/?url=%s&streamtype=TSDOWNLOADER&name=%s' % ( urlib.quote_plus(AjoutHttp + Url + AjoutFin), urlib.quote(Nom)) #&name=%s ,Nom else: Url = 'plugin://plugin.video.f4mTester/?url=%s&streamtype=HLSRETRY&name=%s' % ( urlib.quote_plus(AjoutHttp + Url + AjoutFin), urlib.quote(Nom)) #&name=%s ,Nom DicM3u = (Nom, Url) ret.append(DicM3u) return ret def LireM3u(self, CheminxAmAx, F4m=False, cvNom=True): print "Liste de chaine M3u" dialog = Dialog() fn = dialog.browse(1, 'Ouvrir le fichier M3u', 'files', '.m3u|.m3u8', False, False, 'special://home') ret = [] if fn != False and fn != "": if exists(fn): f = File(fn) M3u = f.read() f.close() if M3u != "": ret = self.TabM3u(M3u, F4m, cvNom) return ret def ListTv(self, Adress, Re1, Re2, NumM3u, TelLien, CheminxAmAx=""): Cmp = 0 ListeRet = [] try: #print Adress ret2 = cDL().TelechargPage(url=Adress) #print ret2 TabLien = re.compile(Re1, re.I + re.M + re.S).findall( self.ConvText(ret2)) print TabLien TabLien2 = [] for Url, Nom in TabLien: if (("France" in Nom)): # or ("French" in Nom)): ret2 = cDL().TelechargPage(url=Url) #print ret2 TabLien2 = re.compile(Re2, re.I + re.M + re.S).findall( self.ConvText(ret2)) break if len(TabLien2) > 0: print str(TabLien2) if TelLien: if TabLien2[0][1][-4:] == ".zip": udata = os.path.join(CheminxAmAx, "Telecharg") dest = os.path.join(udata, 'm3u.zip') if not os.path.exists(udata): os.makedirs(udata) cDL().TelechargementZip(TabLien2[0][1], dest, DPAff=False, Nom="Téléchargement Liste") from resources.ziptools import ziptools unzipper = ziptools() unzipper.extract(dest, udata) os.remove(dest) dir = os.listdir(udata) for a in dir: if a.endswith('.m3u'): print "Ouverture de :" + os.path.join(udata, a) with open(os.path.join(udata, a), 'r') as fm3u: ListM3u = fm3u.read() ListeRet = self.TabM3u(ListM3u, True, True) os.remove(os.path.join(udata, a)) else: ret2 = cDL().TelechargPage(url=TabLien2[0][NumM3u]) print ret2 ListeRet = self.TabM3u(ret2, F4m=True, cvNom=True) else: #print TabLien2[0] ret2 = TabLien2[0].replace('<br />', '') ListeRet = self.TabM3u( ret2, F4m=True, cvNom=True, reComp='EXTINF.+?:-?[0-9]*(.*?),FR(.*?)http:(.*?).ts', AjoutHttp="http:", AjoutFin=".ts") #print str(TabLien2[0][1]) except: return ListeRet, "Erreur de Recherche des chaines de la liste!" return ListeRet, "OK" def AdulteSources( self, Url='aHR0cHM6Ly93d3cubXJzZXhlLmNvbS9jYXQvNjIvc29kb21pZS8='): print "Recherche de la liste de chaine..." Page = str(cDL().TelechargPage(url=b64decode(Url))) ret = [] if not Page.startswith("Erreur"): match = re.compile('thumb-list(.*?)<ul class="right pagination">', re.DOTALL | re.IGNORECASE).findall(Page) #xbmc.log("Resulta 1 tri: "+str(match)) match1 = re.compile( r'<li class="[^"]*">\s<a class="thumbnail" href="([^"]+)">\n<script.+?([^;]+);</script>\n<figure>\n<img id=".+?" src="([^"]+)".+?/>\n<figcaption>\n<span class="video-icon"><i class="fa fa-play"></i></span>\n<span class="duration"><i class="fa fa-clock-o"></i>([^<]+)</span>\n(.+?)\n', re.DOTALL | re.IGNORECASE).findall(match[0]) for url, Timage, image, Temp, Descript in match1: ret.append( (url, "https:" + image, Timage.split("(")[1][:-1].replace( "'", "").split(","), Descript + " " + Temp)) print "Recherche OK..." try: nextp = re.compile( r'<li class="arrow"><a href="(.+?)">suivant</li>').findall( Page) ret.append(('https://www.mrsexe.com' + nextp[0], "", [], "Page Suivante...")) except: pass else: dialog = Dialog() ok = dialog.ok("Telechargement impossible...", Page) return ret
class TestVitesseDeb(): def __init__(self): #, Dialog self.dp = DialogProgress() self.dp.create("Test du débit de votre connexion:") time.sleep(1) #self.dp = Dialog def __del__(self): self.dp.close() def MajProgression(self, Pourcentage, TextMessage): print TextMessage self.dp.update(Pourcentage, TextMessage) time.sleep(1) def downloadSpeed(self, files, quiet=False): TempsDeRef = timeit.default_timer() def FichierEC(q, files): for file in files: OperationEC = DlVitesseTaille(file, TempsDeRef) OperationEC.start() q.put(OperationEC, True) if not quiet and not EvtSource.isSet(): sys.stdout.write('.') sys.stdout.flush() TempTotaleFichier = [] def AffVitesseEC(q, total_files): while len(TempTotaleFichier) < total_files: OperationEC = q.get(True) while OperationEC.isAlive(): OperationEC.join(timeout=0.1) TempTotaleFichier.append(sum(OperationEC.result)) #VitesseMbps = ((sum(TempTotaleFichier) / (timeit.default_timer() - TempsDeRef)) / 1000 / 1000) * 8 #print 'Vitesse en cour: %.02f Mbps' % VitesseMbps del OperationEC TabFifo = Queue(6) ThFichEC = threading.Thread(target=FichierEC, args=(TabFifo, files)) ThAffVitesse = threading.Thread(target=AffVitesseEC, args=(TabFifo, len(files))) TempsDeRef = timeit.default_timer() ThFichEC.start() ThAffVitesse.start() while ThFichEC.isAlive(): ThFichEC.join(timeout=0.1) while ThAffVitesse.isAlive(): ThAffVitesse.join(timeout=0.1) return (sum(TempTotaleFichier) / (timeit.default_timer() - TempsDeRef)) def uploadSpeed(self, url, sizes, quiet=False): TempsDeRef = timeit.default_timer() TempTotaleFichier = [] def FichierEC(q, sizes): for TailleEC in sizes: OperationEC = UploadVitesseTaille(url, TempsDeRef, TailleEC) OperationEC.start() q.put(OperationEC, True) if not quiet and not EvtSource.isSet(): sys.stdout.write('.') sys.stdout.flush() def AffVitesseEC(q, total_sizes): while len(TempTotaleFichier) < total_sizes: OperationEC = q.get(True) while OperationEC.isAlive(): OperationEC.join(timeout=0.1) TempTotaleFichier.append(OperationEC.result) #VitesseMbps = ((sum(TempTotaleFichier) / (timeit.default_timer() - TempsDeRef)) / 1000 / 1000) * 8 #print 'Vitesse en cour: %.02f Mbps' % VitesseMbps del OperationEC TabFifo = Queue(6) ThFichEC = threading.Thread(target=FichierEC, args=(TabFifo, sizes)) ThAffVitesse = threading.Thread(target=AffVitesseEC, args=(TabFifo, len(sizes))) TempsDeRef = timeit.default_timer() ThFichEC.start() ThAffVitesse.start() while ThFichEC.isAlive(): ThFichEC.join(timeout=0.1) while ThAffVitesse.isAlive(): ThAffVitesse.join(timeout=0.1) return (sum(TempTotaleFichier) / (timeit.default_timer() - TempsDeRef)) def Demare(self, timeout=10, units=('bit', 8)): try: global EvtSource, Source TxtFinal = "" EvtSource = threading.Event() socket.setdefaulttimeout(timeout) self.MajProgression(2, 'Recherche configuration de speedtest.net...') try: ConfigSpeedTest = DLConfigSpeedtest() except URLError: TxtFinal = 'La configuration de speedtest.net est introuvable' self.MajProgression(100, TxtFinal) return TxtFinal self.MajProgression( 10, 'Recherche liste de serveurs de speedtest.net...') ListSrvOrd = RechSrvPlusProche(ConfigSpeedTest['client']) #self.MajProgression(15,str(ConfigSpeedTest)) self.MajProgression( 20, 'Test connection depuis: %(isp)s (%(ip)s)...' % ConfigSpeedTest['client']) self.MajProgression( 25, 'Selection du meilleur server en fonction de la latence...') ServerUtiliser = RechLatencySrv(ListSrvOrd) try: TxtFinal = ( 'Heberger par %(sponsor)s (%(name)s) [%(d)0.2f km]: ' '%(latency)s ms' % ServerUtiliser).encode( 'utf-8', 'ignore') self.MajProgression(30, TxtFinal) except NameError: TxtFinal = ( 'Heberger par %(sponsor)s (%(name)s) [%(d)0.2f km]: ' '%(latency)s ms' % ServerUtiliser) self.MajProgression(30, TxtFinal) TabIndex = [ 350, 500, 750, 1000, 1500, 2000, 2500, 3000, 3500, 4000 ] TabUrlRandom = [] for Taille in TabIndex: for i in range(0, 4): TabUrlRandom.append( '%s/random%sx%s.jpg' % (os.path.dirname( ServerUtiliser['url']), Taille, Taille)) time.sleep(1) self.MajProgression(40, 'Test vitesse téléchargement...') VitesseDL = self.downloadSpeed(TabUrlRandom) VitesseDLAff = 'Vitesses téléchargement (Débit descendant): %0.2f M%s/s' % ( (VitesseDL / 1000 / 1000) * units[1], units[0]) TxtFinal += "\n" + VitesseDLAff self.MajProgression(60, VitesseDLAff) TailleUpl = [250000, 500000] TabTailleUpl = [] for TaillEc in TailleUpl: for i in range(0, 25): TabTailleUpl.append(TaillEc) self.MajProgression(80, "Test vitesse d'envoi...") VitesseUpload = self.uploadSpeed(ServerUtiliser['url'], TabTailleUpl) VitesseUpAff = "Vitesse d'envoi (Débit montant): %0.2f M%s/s" % ( (VitesseUpload / 1000 / 1000) * units[1], units[0]) TxtFinal += "\n" + VitesseUpAff self.MajProgression(100, VitesseUpAff) return TxtFinal except: return "Erreur lors de la recherche de votre débit!\nDésolé pour ce problème!"
def _install_widevine_arm(self): # pylint: disable=too-many-statements """Installs Widevine CDM on ARM-based architectures.""" root_cmds = ['mount', 'umount', 'losetup', 'modprobe'] devices = self._chromeos_config() arm_device = self._select_best_chromeos_image(devices) if arm_device is None: log('We could not find an ARM device in recovery.conf') Dialog().ok(localize(30004), localize(30005)) return '' required_diskspace = int(arm_device['filesize']) + int( arm_device['zipfilesize']) if Dialog().yesno( localize( 30001 ), # Due to distributing issues, this takes a long time localize(30006, diskspace=self._sizeof_fmt( required_diskspace))) and self._widevine_eula(): if system_os() != 'Linux': Dialog().ok(localize(30004), localize(30019, os=system_os())) return False while required_diskspace >= self._diskspace(): if Dialog().yesno(localize(30004), localize( 30055)): # Not enough space, alternative path? self._update_temp_path(Dialog().browseSingle( 3, localize(30909), 'files')) # Temporary path continue Dialog().ok( localize(30004), # Not enough free disk space localize(30018, diskspace=self._sizeof_fmt(required_diskspace))) return False if not self._cmd_exists('fdisk') and not self._cmd_exists( 'parted'): Dialog().ok( localize(30004), localize(30020, command1='fdisk', command2='parted')) # Commands are missing return False if not self._cmd_exists('mount'): Dialog().ok(localize(30004), localize( 30021, command='mount')) # Mount command is missing return False if not self._cmd_exists('losetup'): Dialog().ok(localize(30004), localize( 30021, command='losetup')) # Losetup command is missing return False if os.getuid() != 0: # ask for permissions to run cmds as root if not Dialog().yesno(localize(30001), localize(30030, cmds=', '.join(root_cmds)), yeslabel=localize(30027), nolabel=localize(30028)): return False # Clean up any remaining mounts self._unmount() url = arm_device['url'] downloaded = self._http_download( url, message=localize(30022)) # Downloading the recovery image if downloaded: progress_dialog = DialogProgress() progress_dialog.create( heading=localize(30043), line1=localize(30044)) # Extracting Widevine CDM bin_filename = url.split('/')[-1].replace('.zip', '') bin_path = os.path.join(self._temp_path(), bin_filename) progress_dialog.update( 5, line1=localize(30045), line2=localize(30046), line3=localize(30047)) # Uncompressing image success = [ self._unzip(self._temp_path(), bin_filename), self._check_loop(), self._set_loop_dev(), self._losetup(bin_path), self._mnt_loop_dev(), ] if all(success): progress_dialog.update( 91, line1=localize(30048)) # Extracting Widevine CDM self._extract_widevine_from_img() progress_dialog.update( 94, line1=localize(30049)) # Installing Widevine CDM progress_dialog.update(97, line1=localize(30050)) # Finishing self._cleanup() if self._has_widevine(): set_setting('chromeos_version', arm_device['version']) with open(self._widevine_config_path(), 'w') as config_file: config_file.write(json.dumps(devices, indent=4)) wv_check = self._check_widevine() if wv_check: progress_dialog.update(100, line1=localize( 30051)) # Widevine CDM successfully installed. Dialog().notification( localize(30037), localize(30051) ) # Success! Widevine CDM successfully installed. progress_dialog.close() return wv_check else: progress_dialog.update(100, line1=localize(30050)) # Finishing self._cleanup() progress_dialog.close() Dialog().ok(localize(30004), localize(30005)) # An error occurred return False