def _download_img(self): imgdata = utils.fetch_url(self._imgurl, timeout=10) xbmcvfs.File(self._tmp_imgfile, 'w').write(imgdata)
def read(path, linea_inicio=0, total_lineas=None, whence=0, silent=False, vfs=True): """ Read the contents of a file and return the data @param path: file path @type path: str @param linea_inicio: first line to read from the file @type linea_inicio: positive int @param total_lineas: maximum number of lines to read. If it is None or greater than the total lines, the file will be read until the end. @type total_lineas: positive int @rtype: str @return: data contained in the file """ path = encode(path) try: if not isinstance(linea_inicio, int): try: linea_inicio = int(linea_inicio) except: logger.error('Read: Start_line ERROR: %s' % str(linea_inicio)) linea_inicio = 0 if total_lineas != None and not isinstance(total_lineas, int): try: total_lineas = int(total_lineas) except: logger.error('Read: ERROR of total_lineas: %s' % str(total_lineas)) total_lineas = None if xbmc_vfs and vfs: if not exists(path): return False f = xbmcvfs.File(path, "r") data = f.read() if total_lineas == None: total_lineas = 9999999999 if linea_inicio > 0: if not isinstance(whence, int): try: whence = int(whence) except: return False data = '\n'.join(data.split('\n')[linea_inicio:total_lineas]) return data elif path.lower().startswith("smb://"): f = samba.smb_open(path, "rb") else: f = open(path, "rb") data = [] for x, line in enumerate(f): if x < linea_inicio: continue if len(data) == total_lineas: break data.append(line) f.close() except: if not silent: logger.error("ERROR reading file: %s" % path) logger.error(traceback.format_exc()) return False else: if not PY3: return unicode("".join(data)) else: return unicode(b"".join(data))
def addSeasonToLibrary(url): if mysettings.getSetting('cust_LibTV_path') == 'true': newlibraryFolderMovies = custLibTvFolder else: newlibraryFolderMovies = libraryFolderTV movieFolderName = (''.join(c for c in unicode(gname, 'utf-8') if c not in '/\\:?"*|<>')).strip(' .') newMovieFolderName = '' finalName = '' keyb = xbmc.Keyboard(name, '[COLOR ffffd700]Enter Title[/COLOR]') keyb.doModal() if (keyb.isConfirmed()): newMovieFolderName = keyb.getText() if newMovieFolderName != '': dir = os.path.join(newlibraryFolderMovies, newMovieFolderName) finalName = newMovieFolderName else: dir = os.path.join(newlibraryFolderMovies, movieFolderName) finalName = movieFolderName keyb = xbmc.Keyboard(name, '[COLOR ffffd700]Enter Season[/COLOR]') keyb.doModal() if (keyb.isConfirmed()): seasonnum = keyb.getText() link = GetContent(url) soup = BeautifulSoup(link) server_item = soup('div', {'class': 'server_item'})[inum] span = BeautifulSoup(str(server_item))('span') if not os.path.isdir(dir): xbmcvfs.mkdir(dir) for s in span: ssoup = BeautifulSoup(str(s)) try: s['class'] sname = '1' if len(sname) == 1: epnum = '0' + sname else: epnum = etitle epname = ''.join( ["S", seasonnum, "E", epnum, ' - ', finalName]) slink = ssoup('a')[0]['href'] fh = xbmcvfs.File(os.path.join(dir, epname + ".strm"), 'w') fh.write('plugin://' + addonID + '/?mode=4&url=' + urllib.quote_plus(slink) + '&name=' + urllib.quote_plus(''.join( ["[", sname.encode('utf-8'), "] ", gname]))) fh.close() except KeyError: slink = ssoup('a')[0]['href'] sname = ssoup('a')[0].contents[0] if len(sname) == 1: epnum = '0' + sname else: epnum = sname epname = ''.join( ["S", seasonnum, "E", epnum, ' - ', finalName]) fh = xbmcvfs.File(os.path.join(dir, epname + ".strm"), 'w') fh.write('plugin://' + addonID + '/?mode=4&url=' + urllib.quote_plus(slink) + '&name=' + urllib.quote_plus(''.join( ["[", sname.encode('utf-8'), "] ", gname]))) fh.close() else: dialog = xbmcgui.Dialog() if dialog.yesno('TV Show Exists', 'Update Files?'): for s in span: ssoup = BeautifulSoup(str(s)) try: s['class'] sname = '1' if len(sname) == 1: epnum = '0' + sname else: epnum = etitle epname = ''.join( ["S", seasonnum, "E", epnum, ' - ', finalName]) slink = ssoup('a')[0]['href'] fh = xbmcvfs.File(os.path.join(dir, epname + ".strm"), 'w') fh.write('plugin://' + addonID + '/?mode=4&url=' + urllib.quote_plus(slink) + '&name=' + urllib.quote_plus(''.join( ["[", sname.encode('utf-8'), "] ", gname]))) fh.close() except KeyError: slink = ssoup('a')[0]['href'] sname = ssoup('a')[0].contents[0] if len(sname) == 1: epnum = '0' + sname else: epnum = sname epname = ''.join( ["S", seasonnum, "E", epnum, ' - ', finalName]) fh = xbmcvfs.File(os.path.join(dir, epname + ".strm"), 'w') fh.write('plugin://' + addonID + '/?mode=4&url=' + urllib.quote_plus(slink) + '&name=' + urllib.quote_plus(''.join( ["[", sname.encode('utf-8'), "] ", gname]))) fh.close()
def ResolveCaptcha(key, urlOuo): urlBase = 'https://www.google.com/recaptcha/api/fallback?k=' + key oRequestHandler = cRequestHandler(urlBase) oRequestHandler.addHeaderEntry('User-Agent', UA) oRequestHandler.addHeaderEntry( 'Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8') oRequestHandler.addHeaderEntry('Accept-Language', 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3') oRequestHandler.addHeaderEntry('Accept-Encoding', 'gzip, deflate') oRequestHandler.addHeaderEntry('Referer', urlOuo) body = oRequestHandler.request() captchaScrap = re.findall( 'value="8"><img class="fbc-imageselect-payload" src="(.+?)"', str(body)) text = re.search( '<div class="rc-imageselect.+?">.+?<strong>(.+?)</strong>', str(body)).group(1) c = re.search('method="POST"><input type="hidden" name="c" value="(.+?)"', str(body)).group(1) k = re.search('k=(.+?)" alt=', str(body)).group(1) params = {"c": c, "k": k} query_string = urlEncode(params) url = 'https://www.google.com' + str(captchaScrap[0]) + '?' + query_string filePath = 'special://home/userdata/addon_data/plugin.video.matrix/Captcha.raw' oRequestHandler = cRequestHandler(url) htmlcontent = oRequestHandler.request() downloaded_image = xbmcvfs.File(filePath, 'wb') downloaded_image.write(htmlcontent) downloaded_image.close() oSolver = cInputWindow(captcha=filePath, msg=text, roundnum=1) retArg = oSolver.get() allNumber = [int(s) for s in re.findall('([0-9])', str(retArg))] responseFinal = "" for rep in allNumber: responseFinal = responseFinal + '&response=' + str(rep) headers = { 'User-Agent': UA, 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3', 'Accept-Encoding': 'gzip, deflate', 'Referer': url, 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': str(len(params)) } params = 'c=' + c + responseFinal oRequestHandler = cRequestHandler(urlBase) oRequestHandler.setRequestType(1) oRequestHandler.addHeaderEntry('User-Agent', UA) oRequestHandler.addHeaderEntry( 'Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8') oRequestHandler.addHeaderEntry('Accept-Language', 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3') oRequestHandler.addHeaderEntry('Accept-Encoding', 'gzip, deflate') oRequestHandler.addHeaderEntry('Referer', url) oRequestHandler.addHeaderEntry('Content-Type', 'application/x-www-form-urlencoded') oRequestHandler.addHeaderEntry('Content-Length', str(len(params))) oRequestHandler.addParametersLine(params) sHtmlContent = oRequestHandler.request() token = re.search('<textarea dir="ltr" readonly>(.+?)<', sHtmlContent).group(1) if not token: dialogs = dialog() dialogs.VSinfo("Captcha non valide") return token
def _updateDialogVideoInfo(self): # Get the location of the information dialog XML file dialogXml = os_path_join(self.confpath, 'DialogVideoInfo.xml') log("DialogVideoInfo: Confluence dialog XML file: %s" % dialogXml) # Make sure the file exists (It should always exist) if not xbmcvfs.exists(dialogXml): log("DialogVideoInfo: Unable to find the file DialogVideoInfo.xml, skipping file", xbmc.LOGERROR) self.errorToLog = True return # Load the DialogVideoInfo.xml into a string dialogXmlFile = xbmcvfs.File(dialogXml, 'r') dialogXmlStr = dialogXmlFile.read() dialogXmlFile.close() # Now check to see if the skin file has already had the video extras bits added if 'script.videoextras' in dialogXmlStr: # Already have video extras referenced, so we do not want to do anything else # to this file log("DialogVideoInfo: Video extras already referenced in %s, skipping file" % dialogXml, xbmc.LOGINFO) self.errorToLog = True return # Now add the include link to the file dialogXmlStr = self._addIncludeToXml(dialogXmlStr) # Start by adding the onLoad section previousOnLoad = '<controls>' if previousOnLoad not in dialogXmlStr: # The file has had a standard component deleted, so quit log("DialogVideoInfo: Could not find controls command, skipping file", xbmc.LOGERROR) self.errorToLog = True return # Now add the Video Extras onLoad command after the allowoverlay one DIALOG_VIDEO_INFO_ONLOAD = '<onload condition="System.HasAddon(script.videoextras)">RunScript(script.videoextras,check,"$INFO[ListItem.FilenameAndPath]")</onload>\n\t' insertTxt = DIALOG_VIDEO_INFO_ONLOAD + previousOnLoad dialogXmlStr = dialogXmlStr.replace(previousOnLoad, insertTxt) # Now we need to add the button after the Final button previousButton = '<label>13511</label>' if previousButton not in dialogXmlStr: # The file has had a standard component deleted, so quit log("DialogVideoInfo: Could not find final button, skipping file", xbmc.LOGERROR) self.errorToLog = True return # Check to make sure we use a unique ID value for the button idOK = False idval = 101 while not idOK: idStr = "id=\"%d\"" % idval if idStr not in dialogXmlStr: idOK = True else: idval = idval + 1 # Now add the Video Extras button after the Final one DIALOG_VIDEO_INFO_BUTTON = '''\n\t\t\t\t\t</control>\n\t\t\t\t\t<control type="button" id="%d"> \t\t\t\t\t\t<description>Extras</description> \t\t\t\t\t\t<include>ButtonInfoDialogsCommonValues</include> \t\t\t\t\t\t<label>$ADDON[script.videoextras 32001]</label> \t\t\t\t\t\t<onclick>RunScript(script.videoextras,display,"$INFO[ListItem.FilenameAndPath]")</onclick> \t\t\t\t\t\t<visible>System.HasAddon(script.videoextras) + [Container.Content(movies) | Container.Content(episodes) | Container.Content(TVShows) | Container.Content(musicvideos)] + String.IsEmpty(Window(movieinformation).Property("HideVideoExtrasButton"))</visible>''' insertTxt = previousButton + (DIALOG_VIDEO_INFO_BUTTON % idval) dialogXmlStr = dialogXmlStr.replace(previousButton, insertTxt) # Now add the section for the icon overlay iconPrevious = 'VideoTypeHackFlaggingConditions</include>' if iconPrevious not in dialogXmlStr: log("DialogVideoInfo: Could not find point to add icon overlay, skipping overlay addition", xbmc.LOGERROR) self.errorToLog = True return DIALOG_VIDEO_INFO_ICON = '''\n\t\t\t\t\t<!-- Add the Video Extras Icon --> \t\t\t\t\t<include>VideoExtrasLargeIcon</include> \t\t\t\t</control> \t\t\t\t<control type="grouplist"> \t\t\t\t\t<description>Add the Video Extras Icon</description> \t\t\t\t\t<left>210</left> \t\t\t\t\t<top>480</top> \t\t\t\t\t<width>600</width> \t\t\t\t\t<align>left</align> \t\t\t\t\t<itemgap>2</itemgap> \t\t\t\t\t<orientation>horizontal</orientation> \t\t\t\t\t<include>VisibleFadeEffect</include> \t\t\t\t\t<visible>!Control.IsVisible(50) + Container.Content(tvshows) + !Container.Content(Episodes)</visible> \t\t\t\t\t<include>VideoExtrasLargeIcon</include>''' insertTxt = iconPrevious + DIALOG_VIDEO_INFO_ICON dialogXmlStr = dialogXmlStr.replace(iconPrevious, insertTxt) self._saveNewFile(dialogXml, dialogXmlStr)
def download(link, episode=""): subtitle_list = [] exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass"] downloadlink_pattern = "...<a href=\"(.+?)\" rel=\"nofollow\" onclick=\"DownloadSubtitle" uid = uuid.uuid4() if sys.version_info.major == 3: tempdir = os.path.join(__temp__, str(uid)) else: tempdir = os.path.join(__temp__, unicode(uid)) if not xbmcvfs.mkdirs(tempdir): log(__name__, "Failed to create temp directory " + tempdir) content, response_url = geturl(link) content = str(content) match = re.compile(downloadlink_pattern).findall(content) if match: downloadlink = main_url + match[0] viewstate = 0 previouspage = 0 subtitleid = 0 typeid = "zip" filmid = 0 if sys.version_info.major == 3: postparams = urllib.parse.urlencode( {'__EVENTTARGET': 's$lc$bcr$downloadLink', '__EVENTARGUMENT': '', '__VIEWSTATE': viewstate, '__PREVIOUSPAGE': previouspage, 'subtitleId': subtitleid, 'typeId': typeid, 'filmId': filmid}).encode() else: postparams = urllib.urlencode( {'__EVENTTARGET': 's$lc$bcr$downloadLink', '__EVENTARGUMENT': '', '__VIEWSTATE': viewstate, '__PREVIOUSPAGE': previouspage, 'subtitleId': subtitleid, 'typeId': typeid, 'filmId': filmid}) useragent = ("User-Agent=Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) " "Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)") headers = {'User-Agent': useragent, 'Referer': link} log(__name__, "Fetching subtitles using url '%s' with referer header '%s' and post parameters '%s'" % ( downloadlink, link, postparams)) if sys.version_info.major == 3: request = urllib.request.Request(downloadlink, postparams, headers) response = urllib.request.urlopen(request) else: request = urllib2.Request(downloadlink, postparams, headers) response = urllib2.urlopen(request) if response.getcode() != 200: log(__name__, "Failed to download subtitle file") return subtitle_list local_tmp_file = os.path.join(tempdir, "subscene.xxx") packed = False try: log(__name__, "Saving subtitles to '%s'" % local_tmp_file) if sys.version_info.major == 3: local_file_handle = xbmcvfs.File(local_tmp_file, "w") local_file_handle.write(bytearray(response.read())) else: local_file_handle = xbmcvfs.File(local_tmp_file, "wb") local_file_handle.write(response.read()) local_file_handle.close() log(__name__, "Checking archive type") # Check archive type (rar/zip/else) through the file header (rar=Rar!, zip=PK) myfile = xbmcvfs.File(local_tmp_file, "rb") myfile.seek(0,0) if myfile.read(1) == 'R': typeid = "rar" packed = True log(__name__, "Discovered RAR Archive") else: myfile.seek(0,0) if myfile.read(1) == 'P': typeid = "zip" packed = True log(__name__, "Discovered ZIP Archive") else: typeid = "srt" packed = False log(__name__, "Discovered a non-archive file") myfile.close() local_tmp_file = os.path.join(tempdir, "subscene." + typeid) xbmcvfs.rename(os.path.join(tempdir, "subscene.xxx"), local_tmp_file) log(__name__, "Saving to %s" % local_tmp_file) except: log(__name__, "Failed to save subtitle to %s" % local_tmp_file) #NOTE: RAR is not supported natively. The addon vfs.rar or vfs.libarchive is required and needs to be enabled for rar support. However, those addons aren't working in Kodi 19 yet. if packed: xbmc.sleep(500) log(__name__, "Extracting '%s' to '%s'" % (local_tmp_file, tempdir)) if sys.version_info.major == 3: xbmc.executebuiltin('Extract("%s","%s")' % (local_tmp_file, tempdir), True) else: xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (local_tmp_file, tempdir,)).encode('utf-8'), True) episode_pattern = None if episode != '': episode_pattern = re.compile(get_episode_pattern(episode), re.IGNORECASE) for dir in xbmcvfs.listdir(tempdir)[0]: for file in xbmcvfs.listdir(os.path.join(tempdir, dir))[1]: if os.path.splitext(file)[1] in exts: log(__name__, 'match '+episode+' '+file) if episode_pattern and not episode_pattern.search(file): continue log(__name__, "=== returning subtitle file %s" % file) subtitle_list.append(os.path.join(tempdir, dir, file)) for file in xbmcvfs.listdir(tempdir)[1]: if os.path.splitext(file)[1] in exts: log(__name__, 'match '+episode+' '+file) if episode_pattern and not episode_pattern.search(file): continue log(__name__, "=== returning subtitle file %s" % file) subtitle_list.append(os.path.join(tempdir, file)) if len(subtitle_list) == 0: if sys.version_info.major == 3: if episode: xbmc.executebuiltin('Notification(%s,%s)' % (__scriptname__, __language__(32002))) else: xbmc.executebuiltin('Notification(%s,%s)' % (__scriptname__, __language__(32003))) else: if episode: xbmc.executebuiltin((u'Notification(%s,%s)' % (__scriptname__, __language__(32002))).encode('utf-8')) else: xbmc.executebuiltin((u'Notification(%s,%s)' % (__scriptname__, __language__(32003))).encode('utf-8')) return subtitle_list
[x for x in ACTIONS.keys() if x not in actions]) selected_actions = d.multiselect(command, add_actions) if selected_actions: actions = actions + [ add_actions[x] for x in selected_actions ] edit_commands[command] = actions elif edit_action == 1: command = command_keys[command_index] actions = edit_commands[command] selected_actions = d.multiselect(command, actions) if selected_actions: new_actions = [ actions[x] for x in range(len(actions)) if x not in selected_actions ] edit_commands[command] = new_actions elif main_action == 1: edit_commands = COMMANDS elif main_action == 2: save_commands = edit_commands.copy() for command in save_commands: actions = save_commands[command] actions = [ACTIONS[x] for x in actions] save_commands[command] = actions f = xbmcvfs.File( 'special://profile/addon_data/script.tvguide.fullscreen/commands.json', 'wb') f.write(json.dumps(save_commands, indent=2)) f.close() quit()
def doDownloadFilm(self, filmid, quality): if self.settings.downloadpath: film = self.db.RetrieveFilmInfo(filmid) if film is None: # film not found - should never happen return # check if the download path is reachable if not xbmcvfs.exists(self.settings.downloadpath): self.notifier.ShowError(self.language(30952), self.language(30979)) return # get the best url if quality == '0' and film.url_video_sd: videourl = film.url_video_sd elif quality == '2' and film.url_video_hd: videourl = film.url_video_hd else: videourl = film.url_video # prepare names showname = mvutils.cleanup_filename(film.show)[:64] filestem = mvutils.cleanup_filename(film.title)[:64] extension = os.path.splitext(videourl)[1] if not extension: extension = u'.mp4' if not filestem: filestem = u'Film-{}'.format(film.id) if not showname: showname = filestem # prepare download directory and determine episode number dirname = self.settings.downloadpath + showname + '/' episode = 1 if xbmcvfs.exists(dirname): ( _, epfiles, ) = xbmcvfs.listdir(dirname) for epfile in epfiles: match = re.search('^.* [eE][pP]([0-9]*)\.[^/]*$', epfile) if match and len(match.groups()) > 0: if episode <= int(match.group(1)): episode = int(match.group(1)) + 1 else: xbmcvfs.mkdir(dirname) # prepare resulting filenames fileepi = filestem + u' - EP%04d' % episode movname = dirname + fileepi + extension srtname = dirname + fileepi + u'.srt' ttmname = dirname + fileepi + u'.ttml' nfoname = dirname + fileepi + u'.nfo' # download video bgd = KodiBGDialog() bgd.Create(self.language(30974), fileepi + extension) try: bgd.Update(0) mvutils.url_retrieve_vfs(videourl, movname, bgd.UrlRetrieveHook) bgd.Close() self.notifier.ShowNotification( 30960, self.language(30976).format(videourl)) except Exception as err: bgd.Close() self.error('Failure downloading {}: {}', videourl, err) self.notifier.ShowError( 30952, self.language(30975).format(videourl, err)) # download subtitles if film.url_sub: bgd = KodiBGDialog() bgd.Create(30978, fileepi + u'.ttml') try: bgd.Update(0) mvutils.url_retrieve_vfs(film.url_sub, ttmname, bgd.UrlRetrieveHook) try: ttml2srt(xbmcvfs.File(ttmname, 'r'), xbmcvfs.File(srtname, 'w')) except Exception as err: self.info('Failed to convert to srt: {}', err) bgd.Close() except Exception as err: bgd.Close() self.error('Failure downloading {}: {}', film.url_sub, err) # create NFO Files self._make_nfo_files(film, episode, dirname, nfoname, videourl) else: self.notifier.ShowError(30952, 30958)
def _cacheSave(self, data): self.cacheData = data file = xbmcvfs.File(self.cachePath, 'w') file.write(json.dumps(data)) file.close()
data = json.loads(j) headend = "" provider = "" if "Message" not in data: providers = [x["Name"] for x in data] index = d.select("%s provider:" % country, providers) if index == -1: quit() headend = data[index]["Value"] provider = data[index]["Name"] #log((name,provider,country,headend)) filename = 'special://profile/addon_data/script.tvguide.fullscreen/yo.json' providers = {} try: f = xbmcvfs.File(filename, 'rb') providers = json.load(f) f.close() except: pass providers[str((name, provider, country, headend))] = (name, provider, country, headend) f = xbmcvfs.File(filename, 'wb') json.dump(providers, f, indent=2) f.close() elif select == 1: filename = 'special://profile/addon_data/script.tvguide.fullscreen/yo.json' providers = {} try:
def move_file(self, source, dest_folder): """Move a file to a new destination. Will create destination if it does not exist. Example: result = move_file(a, b) :type source: str :param source: the source path (absolute) :type dest_folder: str :param dest_folder: the destination path (absolute) :rtype: int :return: 1 if (all stacked) files were moved, 0 if not, -1 if errors occurred """ if isinstance(source, unicode): source = source.encode("utf-8") paths = self.unstack(source) success = [] files_moved_successfully = 0 dest_folder = xbmc.makeLegalFilename(dest_folder) if self.is_excluded(paths[0]): debug("Detected a file on an excluded path. Aborting.") return 0 for p in paths: debug("Attempting to move %r to %r." % (p, dest_folder)) if xbmcvfs.exists(p): if not xbmcvfs.exists(dest_folder): if xbmcvfs.mkdirs(dest_folder): debug("Created destination %r." % dest_folder) else: debug( "Destination %r could not be created." % dest_folder, xbmc.LOGERROR) return -1 new_path = os.path.join(dest_folder, os.path.basename(p)) # TODO: This check might not make sense after ensuring the folder exists if xbmcvfs.exists(new_path): debug( "A file with the same name already exists in the holding folder. Checking file sizes." ) existing_file = xbmcvfs.File(new_path) file_to_move = xbmcvfs.File(p) if file_to_move.size() > existing_file.size(): debug( "This file is larger than the existing file. Replacing it with this one." ) existing_file.close() file_to_move.close() if bool( xbmcvfs.delete(new_path) and bool(xbmcvfs.rename(p, new_path))): files_moved_successfully += 1 else: return -1 else: debug( "This file isn't larger than the existing file. Deleting it instead of moving." ) existing_file.close() file_to_move.close() if bool(xbmcvfs.delete(p)): files_moved_successfully += 1 else: return -1 else: debug("Moving %r to %r." % (p, new_path)) move_success = bool(xbmcvfs.rename(p, new_path)) copy_success, delete_success = False, False if not move_success: debug("Move failed, falling back to copy and delete.", xbmc.LOGWARNING) copy_success = bool(xbmcvfs.copy(p, new_path)) if copy_success: debug( "Copied successfully, attempting delete of source file." ) delete_success = bool(xbmcvfs.delete(p)) if not delete_success: debug( "Could not remove source file. Please remove the file manually.", xbmc.LOGWARNING) else: debug( "Copying failed, please make sure you have appropriate permissions.", xbmc.LOGFATAL) return -1 if move_success or (copy_success and delete_success): files_moved_successfully += 1 else: debug("File %r is no longer available." % p, xbmc.LOGWARNING) return 1 if len(paths) == files_moved_successfully else -1
import xbmc import xbmcaddon import xbmcgui import xbmcvfs import login ADDON_ID = 'plugin.video.bob' HOME = xbmc.translatePath('special://home') ADDON_DATA = xbmc.translatePath('special://profile/addon_data') ADDONS = os.path.join(HOME, 'addons') BOB_DATA = os.path.join(ADDON_DATA, ADDON_ID) BOB_COOKIE = os.path.join(BOB_DATA, 'cookies') if 'credits' in sys.argv[0]: try: f = xbmcvfs.File('special://home/addons/plugin.video.bob/credits.txt') text = f.read() f.close() if xbmc.getInfoLabel('System.ProfileName') != "Master user": you = xbmc.getInfoLabel('System.ProfileName') elif xbmc.getCondVisibility( 'System.Platform.Windows') == True or xbmc.getCondVisibility( 'System.Platform.OSX') == True: if "Users\\" in HOME: proyou = str(HOME).split("Users\\") preyou = str(proyou[1]).split("\\") you = preyou[0] else: you = "You" else: you = "You"
def doDownload(url, dest, title, image, headers): headers = json.loads(urllib.unquote_plus(headers)) url = urllib.unquote_plus(url) title = urllib.unquote_plus(title) image = urllib.unquote_plus(image) dest = urllib.unquote_plus(dest) file = dest.rsplit(os.sep, 1)[-1] resp = getResponse(url, headers, 0) if not resp: xbmcgui.Dialog().ok( title, dest, u'A let\u00F6lt\u00E9s meghi\u00FAsult'.encode('utf-8'), u'Nem \u00E9rkezett v\u00E1lasz a szervert\u0151l'.encode('utf-8')) return try: content = int(resp.headers['Content-Length']) except: content = 0 try: resumable = 'bytes' in resp.headers['Accept-Ranges'].lower() except: resumable = False #print "Download Header" #print resp.headers if resumable: print "Download is resumable" if content < 1: xbmcgui.Dialog().ok( title, file, u'Ismeretlen f\u00E1jlm\u00E9ret'.encode('utf-8'), u'Nem siker\u00FClt a let\u00F6lt\u00E9s'.encode('utf-8')) return size = 1024 * 1024 mb = content / (1024 * 1024) if content < size: size = content total = 0 notify = 0 errors = 0 count = 0 resume = 0 sleep = 0 down_text1 = u'Let\u00F6lt\u00E9s j\u00F3v\u00E1hagy\u00E1sa'.encode( 'utf-8') down_text2 = u'A f\u00E1jl m\u00E9rete'.encode('utf-8') down_text3 = u'Folytatja a let\u00F6lt\u00E9st?'.encode('utf-8') down_text4 = u'Let\u00F6lt\u00E9s'.encode('utf-8') down_text5 = u'M\u00E9gsem'.encode('utf-8') down_text6 = u'Let\u00F6lt\u00E9si folyamat'.encode('utf-8') if xbmcgui.Dialog().yesno('%s - %s' % (title, down_text1), file, '%s %dMB' % (down_text2, mb), down_text3, down_text4, down_text5) == 1: return print 'Download File Size : %dMB %s ' % (mb, dest) #f = open(dest, mode='wb') f = xbmcvfs.File(dest, 'w') chunk = None chunks = [] while True: downloaded = total for c in chunks: downloaded += len(c) percent = min(100 * downloaded / content, 100) if percent >= notify: xbmc.executebuiltin( "XBMC.Notification(%s,%s,%i,%s)" % ('%s - %s%% - %s' % (down_text6, str(percent), title), dest, 10000, image)) print 'Download percent : %s %s %dMB downloaded : %sMB File Size : %sMB' % ( str(percent) + '%', dest, mb, downloaded / 1000000, content / 1000000) notify += 10 chunk = None error = False try: chunk = resp.read(size) if not chunk: if percent < 99: error = True else: while len(chunks) > 0: c = chunks.pop(0) f.write(c) del c f.close() print '%s download complete' % (dest) return done(title, dest, True) except Exception, e: print str(e) error = True sleep = 10 errno = 0 if hasattr(e, 'errno'): errno = e.errno if errno == 10035: # 'A non-blocking socket operation could not be completed immediately' pass if errno == 10054: #'An existing connection was forcibly closed by the remote host' errors = 10 #force resume sleep = 30 if errno == 11001: # 'getaddrinfo failed' errors = 10 #force resume sleep = 30 if chunk: errors = 0 chunks.append(chunk) if len(chunks) > 5: c = chunks.pop(0) f.write(c) total += len(c) del c if error: errors += 1 count += 1 print '%d Error(s) whilst downloading %s' % (count, dest) xbmc.sleep(sleep * 1000) if (resumable and errors > 0) or errors >= 10: if (not resumable and resume >= 50) or resume >= 500: #Give up! print '%s download canceled - too many error whilst downloading' % ( dest) return done(title, dest, False) resume += 1 errors = 0 if resumable: chunks = [] #create new response print 'Download resumed (%d) %s' % (resume, dest) resp = getResponse(url, headers, total) else: #use existing response pass
import os import re import xbmc import xbmcgui import xbmcaddon import xbmcvfs from rpc import RPC ADDON = xbmcaddon.Addon(id='script.tvguide.Vader') file_name = 'special://profile/addon_data/script.tvguide.Vader/folders.list' f = xbmcvfs.File(file_name) items = f.read().splitlines() f.close() unique = set(items) file_name = 'special://profile/addon_data/script.tvguide.Vader/addons.ini' if int(ADDON.getSetting('addons.ini.type')) == 1: customFile = str(ADDON.getSetting('addons.ini.file')) if os.path.exists(customFile) and os.access(customFile,os.W_OK): file_name = customFile plugins = {} logos = {} for path in unique: if path.startswith('@'): method = 1 path = path[1:] else: method = 0 match = re.match(r"plugin://(.*?)/",path)
def get_response(img, cookie): #on telecharge l'image import xbmcvfs dialogs = dialog() filename = "special://home/userdata/addon_data/plugin.video.vstream/Captcha.raw" #PathCache = xbmc.translatePath(xbmcaddon.Addon('plugin.video.vstream').getAddonInfo("profile")) #filename = os.path.join(PathCache, 'Captcha.raw') hostComplet = re.sub(r'(https*:\/\/[^/]+)(\/*.*)', '\\1', img) host = re.sub(r'https*:\/\/', '', hostComplet) url = img oRequestHandler = cRequestHandler(url) oRequestHandler.addHeaderEntry('User-Agent', UA) #oRequestHandler.addHeaderEntry('Referer', url) oRequestHandler.addHeaderEntry('Cookie', cookie) htmlcontent = oRequestHandler.request() NewCookie = oRequestHandler.GetCookies() downloaded_image = xbmcvfs.File(filename, 'wb') #downloaded_image = file(filename, "wb") downloaded_image.write(htmlcontent) downloaded_image.close() #on affiche le dialogue solution = '' if (True): ####nouveau captcha try: ##affichage du dialog perso class XMLDialog(xbmcgui.WindowXMLDialog): #""" #Dialog class for captcha #""" def __init__(self, *args, **kwargs): xbmcgui.WindowXMLDialog.__init__(self) pass def onInit(self): #image background captcha self.getControl(1).setImage(filename.encode("utf-8"), False) #image petit captcha memory fail self.getControl(2).setImage(filename.encode("utf-8"), False) self.getControl(2).setVisible(False) ##Focus clavier self.setFocus(self.getControl(21)) def onClick(self, controlId): if controlId == 20: #button Valider solution = self.getControl(5000).getLabel() xbmcgui.Window(10101).setProperty('captcha', solution) self.close() return elif controlId == 30: #button fermer self.close() return elif controlId == 21: #button clavier self.getControl(2).setVisible(True) kb = xbmc.Keyboard( self.getControl(5000).getLabel(), '', False) kb.doModal() if (kb.isConfirmed()): self.getControl(5000).setLabel(kb.getText()) self.getControl(2).setVisible(False) else: self.getControl(2).setVisible(False) def onFocus(self, controlId): self.controlId = controlId def _close_dialog(self): self.close() def onAction(self, action): #touche return 61448 if action.getId() in (9, 10, 11, 30, 92, 216, 247, 257, 275, 61467, 61448): self.close() path = "special://home/addons/plugin.video.vstream" #path = cConfig().getAddonPath().decode("utf-8") wd = XMLDialog('DialogCaptcha.xml', path, 'default', '720p') wd.doModal() del wd finally: solution = xbmcgui.Window(10101).getProperty('captcha') if solution == '': dialogs.VSinfo("Vous devez taper le captcha") else: #ancien Captcha try: img = xbmcgui.ControlImage(450, 0, 400, 130, filename.encode("utf-8")) wdlg = xbmcgui.WindowDialog() wdlg.addControl(img) wdlg.show() #xbmc.sleep(3000) kb = xbmc.Keyboard('', 'Tapez les Lettres/chiffres de l\'image', False) kb.doModal() if (kb.isConfirmed()): solution = kb.getText() if solution == '': dialogs.VSinfo("Vous devez taper le captcha") else: dialogs.VSinfo("Vous devez taper le captcha") finally: wdlg.removeControl(img) wdlg.close() return solution, NewCookie
def _cacheLoad(self): if self.cacheData == None: file = xbmcvfs.File(self.cachePath) self.cacheData = json.loads(file.read()) file.close() return self.cacheData
def get(self, query, imdb_id, season, episode): def _notification(line, _time=3500): if self.show_notification: return notification(line, _time) else: return if self.subs_action == 'Off': return xbmc.sleep(2500) language = self.language_dict[self.settings_language1] language2 = self.language_dict[self.settings_language2] try: available_sub_language = xbmc.Player().getSubtitles() except: available_sub_language = '' if available_sub_language in (language, language2): if self.auto_enable == 'true': xbmc.Player().showSubtitles(True) return _notification('Local Subtitles Found') import os _notification('Searching OPENSUBTITLES...') chosen_sub = None imdb_id = re.sub('[^0-9]', '', imdb_id) result = self.opensubtitles.search(query, imdb_id, language, season, episode) if not result or len(result) == 0: language = self.language_dict[self.settings_language2] if language == None: return _notification('No Subtitles Found') _notification('Searching Secondary language...', _time=1500) result = self.opensubtitles.search(query, imdb_id, language, season, episode) if not result or len(result) == 0: return _notification('No Subtitles Found') try: video_path = self.getPlayingFile() except: video_path = '' if '|' in video_path: video_path = video_path.split('|')[0] video_path = os.path.basename(video_path) if self.subs_action == 'Select': from modules.utils import selection_dialog xbmc.Player().pause() choices = [ i for i in result if i['SubLanguageID'] == self.language_dict[ self.settings_language1] and i['SubSumCD'] == '1' ] choices += [ i for i in result if i['SubLanguageID'] == self.language_dict[ self.settings_language2] and i['SubSumCD'] == '1' ] dialog_list = [ '%02d | [B]%s[/B] |[I]%s[/I]' % (c, i['SubLanguageID'].upper(), i['MovieReleaseName']) for c, i in enumerate(choices, 1) ] string = 'SUBTITLES - %s' % video_path chosen_sub = selection_dialog(dialog_list, choices, string) xbmc.Player().pause() if not chosen_sub: return _notification('No Subtitles Selected', _time=1500) else: try: chosen_sub = [ i for i in result if i['MovieReleaseName'].lower() in video_path.lower() and i['SubLanguageID'] == language and i['SubSumCD'] == '1' ][0] except: pass if not chosen_sub: fmt = re.split('\.|\(|\)|\[|\]|\s|\-', video_path) fmt = [i.lower() for i in fmt] fmt = [i for i in fmt if i in self.quality] if season and fmt == '': fmt = 'hdtv' result = [i for i in result if i['SubSumCD'] == '1'] filter = [ i for i in result if i['SubLanguageID'] == language and any( x in i['MovieReleaseName'].lower() for x in fmt) and any( x in i['MovieReleaseName'].lower() for x in self.quality) ] filter += [ i for i in result if any(x in i['MovieReleaseName'].lower() for x in self.quality) ] filter += [i for i in result if i['SubLanguageID'] == language] if len(filter) > 0: chosen_sub = filter[0] else: chosen_sub = result[0] _notification( 'No Suitable Subtitles Found. Loading First Result') try: lang = xbmc.convertLanguage(chosen_sub['SubLanguageID'], xbmc.ISO_639_1) except: lang = chosen_sub['SubLanguageID'] subtitle = xbmc.translatePath('special://temp/') subtitle = os.path.join(subtitle, 'FEN_Subs.%s.srt' % lang) download_url = chosen_sub['SubDownloadLink'] content = self.opensubtitles.download(download_url) file = xbmcvfs.File(subtitle, 'w') file.write(str(content)) file.close() xbmc.sleep(1000) return xbmc.Player().setSubtitles(subtitle)
def doDownload(url, dest, dp): try: headers = dict(urlparse.parse_qsl(url.rsplit('|', 1)[1])) except: headers = dict('') if 'openload' in url: headers = openloadhdr if 'spankbang.com' in url: url = getVideoLink(url, url) url = url.split('|')[0] file = dest.rsplit(os.sep, 1)[-1] resp = getResponse(url, headers, 0) if not resp: xbmcgui.Dialog().ok("Ultimate Whitecream", 'Download failed', 'No response from server') return False try: content = int(resp.headers['Content-Length']) except: content = 0 try: resumable = 'bytes' in resp.headers['Accept-Ranges'].lower() except: resumable = False if resumable: print "Download is resumable" if content < 1: xbmcgui.Dialog().ok("Ultimate Whitecream", 'Unknown filesize', 'Unable to download') return False size = 8192 mb = content / (1024 * 1024) if content < size: size = content total = 0 errors = 0 count = 0 resume = 0 sleep = 0 print 'Download File Size : %dMB %s ' % (mb, dest) f = xbmcvfs.File(dest, 'w') chunk = None chunks = [] while True: downloaded = total for c in chunks: downloaded += len(c) percent = min(100 * downloaded / content, 100) _pbhook(downloaded, content, url, dp) chunk = None error = False try: chunk = resp.read(size) if not chunk: if percent < 99: error = True else: while len(chunks) > 0: c = chunks.pop(0) f.write(c) del c f.close() print '%s download complete' % (dest) return True except Exception, e: print str(e) error = True sleep = 10 errno = 0 if hasattr(e, 'errno'): errno = e.errno if errno == 10035: # 'A non-blocking socket operation could not be completed immediately' pass if errno == 10054: #'An existing connection was forcibly closed by the remote host' errors = 10 #force resume sleep = 30 if errno == 11001: # 'getaddrinfo failed' errors = 10 #force resume sleep = 30 if chunk: errors = 0 chunks.append(chunk) if len(chunks) > 5: c = chunks.pop(0) f.write(c) total += len(c) del c if error: errors += 1 count += 1 print '%d Error(s) whilst downloading %s' % (count, dest) xbmc.sleep(sleep * 1000) if (resumable and errors > 0) or errors >= 10: if (not resumable and resume >= 50) or resume >= 500: #Give up! print '%s download canceled - too many error whilst downloading' % ( dest) return False resume += 1 errors = 0 if resumable: chunks = [] #create new response print 'Download resumed (%d) %s' % (resume, dest) resp = getResponse(url, headers, total) else: #use existing response pass
def __init__(self, filename): self.vfsfile = xbmcvfs.File(filename) self.size = self.vfsfile.size() self.bytesRead = 0
def fetchFile(self, force=False): retVal = self.FETCH_NOT_NEEDED fetch = False if not os.path.exists( self.filePath): # always fetch if file doesn't exist! fetch = True elif force == True: fetch = True else: interval = int(self.addon.getSetting('xmltv.interval')) if interval != self.INTERVAL_ALWAYS: modTime = datetime.datetime.fromtimestamp( os.path.getmtime(self.filePath)) td = datetime.datetime.now() - modTime # need to do it this way cause Android doesn't support .total_seconds() :( diff = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 if ((interval == self.INTERVAL_12 and diff >= 43200) or (interval == self.INTERVAL_24 and diff >= 86400) or (interval == self.INTERVAL_48 and diff >= 172800) or (interval == self.INTERVAL_7 and diff >= 604800) or (interval == self.INTERVAL_14 and diff >= 1209600)): fetch = True else: fetch = True if fetch: user = '' password = '' new_md5 = '' auth = None if self.addon.getSetting('authentication') == 'true': user = self.addon.getSetting('user') password = self.addon.getSetting('password') auth = (user, password) tmpFile = os.path.join(self.basePath, self.fileName + '.tmp') if self.fileType == self.TYPE_DEFAULT: xbmc.log( '[script.tvguide.fullscreen] file is in remote location: %s' % self.fileUrl, xbmc.LOGDEBUG) if xbmcvfs.exists(self.filePath): st = xbmcvfs.Stat(self.fileUrl) src_modified = st.st_mtime() st = xbmcvfs.Stat(self.filePath) dst_modified = st.st_mtime() if src_modified <= dst_modified: return self.FETCH_NOT_NEEDED if not xbmcvfs.copy(self.fileUrl, tmpFile): xbmc.log( '[script.tvguide.fullscreen] Remote file couldn\'t be copied: %s' % self.fileUrl, xbmc.LOGERROR) else: if self.addon.getSetting('md5') == 'true': file = self.filePath + ".md5" url = self.fileUrl + ".md5" old_md5 = xbmcvfs.File(file, "rb").read() try: r = requests.get(url, auth=auth) if r.status_code == requests.codes.ok: new_md5 = r.text.encode('ascii', 'ignore')[:32] except Exception as detail: xbmc.log( '[script.tvguide.fullscreen] Missing md5: %s.md5 (%s)' % (self.fileUrl, detail), xbmc.LOGERROR) #log((old_md5,new_md5)) if old_md5 and (old_md5 == new_md5) and ( self.addon.getSetting('xmltv.refresh') == 'false'): return self.FETCH_NOT_NEEDED f = open(tmpFile, 'wb') xbmc.log( '[script.tvguide.fullscreen] file is on the internet: %s' % self.fileUrl, xbmc.LOGDEBUG) total = 0 fileUrl = self.fileUrl if ADDON.getSetting('gz') == 'true': fileUrl = fileUrl + '.gz' try: r = requests.get(fileUrl, auth=auth, stream=True, verify=False) if r.status_code != requests.codes.ok: if ADDON.getSetting('gz') == 'true': r = requests.get(self.fileUrl, auth=auth, stream=True, verify=False) if r.status_code != requests.codes.ok: xbmc.log( '[script.tvguide.fullscreen] no file: %s' % self.fileUrl, xbmc.LOGERROR) xbmcgui.Dialog().notification( "TV Guide Fullscreen", "bad status code %s" % self.fileUrl, xbmcgui.NOTIFICATION_ERROR) else: xbmc.log( '[script.tvguide.fullscreen] no file: %s' % fileUrl, xbmc.LOGERROR) xbmcgui.Dialog().notification( "TV Guide Fullscreen", "bad status code %s " % fileUrl, xbmcgui.NOTIFICATION_ERROR) return self.FETCH_NOT_NEEDED if "Content-Length" in r.headers: total = int(r.headers['Content-Length']) except Exception as detail: xbmc.log( '[script.tvguide.fullscreen] bad request: %s (%s)' % (fileUrl, detail), xbmc.LOGERROR) xbmcgui.Dialog().notification( "TV Guide Fullscreen", "failed to download %s " % fileUrl, xbmcgui.NOTIFICATION_ERROR) return self.FETCH_NOT_NEEDED title = fileUrl.split('/')[-1] d = xbmcgui.DialogProgressBG() d.create('TV Guide Fullscreen', 'downloading %s' % title) chunk_size = 16 * 1024 size = 0 oldtime = time.time() for chunk in r.iter_content(chunk_size): f.write(chunk) size = size + chunk_size if total: percent = 100.0 * size / total now = time.time() diff = now - oldtime if diff > 1: d.update(int(percent)) oldtime = now f.close() d.update(100, message="Done") d.close() if os.path.exists(self.filePath): try: os.remove(self.filePath) except: return self.FETCH_NOT_NEEDED try: magic = xbmcvfs.File(tmpFile, "rb").read(3) if magic == "\x1f\x8b\x08": g = gzip.open(tmpFile) data = g.read() xbmcvfs.File(self.filePath, "wb").write(data) else: xbmcvfs.copy(tmpFile, self.filePath) xbmcvfs.delete(tmpFile) except: return self.FETCH_NOT_NEEDED if new_md5 and (self.addon.getSetting('md5') == 'true'): md5 = hashlib.md5() md5.update(xbmcvfs.File(self.filePath, "rb").read()) md5_file = md5.hexdigest() if md5_file != new_md5: xbmc.log( '[script.tvguide.fullscreen] md5 mismatch: %s calculated:%s server:%s' % (self.fileUrl, md5_file, new_md5), xbmc.LOGERROR) xbmcgui.Dialog().notification("TV Guide Fullscreen", "failed md5 check %s", xbmcgui.NOTIFICATION_ERROR) else: xbmcvfs.File(self.filePath + ".md5", "wb").write(new_md5) retVal = self.FETCH_OK xbmc.log( '[script.tvguide.fullscreen] file %s was downloaded' % self.filePath, xbmc.LOGDEBUG) return retVal
def write_to_file(filepath, content): f = xbmcvfs.File(filepath, 'w') f.write(content) f.close()
def file(path, mode=""): return xbmcvfs.File(path, mode)
def downloadfor(self, mediaitem, allartwork=True): if self.fileerror_count >= FILEERROR_LIMIT: return False, '' if not info.can_saveartwork(mediaitem): return False, '' to_download = get_downloadable_art(mediaitem, allartwork) if not to_download: return False, '' services_hit = False error = '' localfiles = get_local_art(mediaitem, allartwork) for arttype, url in to_download.items(): hostname = urlparse.urlparse(url).netloc if self.provider_errors.get(hostname, 0) >= PROVIDERERROR_LIMIT: continue full_basefilepath = info.build_artwork_basepath(mediaitem, arttype) if not full_basefilepath: continue if self.debug: mediaitem.downloadedart[arttype] = full_basefilepath + '.ext' continue result, err = self.doget(url) if err: error = err self.provider_errors[hostname] = self.provider_errors.get( hostname, 0) + 1 continue if not result: # 404 URL dead, wipe it so we can add another one later mediaitem.downloadedart[arttype] = None continue self.size += int(result.headers.get('content-length', 0)) services_hit = True ext = get_file_extension(result.headers.get('content-type'), url) if not ext: log("Can't determine extension for '{0}'\nfor image type '{1}'" .format(url, arttype)) continue full_basefilepath += '.' + ext if xbmcvfs.exists(full_basefilepath): if extrafanart_name_used(full_basefilepath, localfiles): # REVIEW: can this happen in any other circumstance? full_basefilepath = get_next_filename( full_basefilepath, localfiles) localfiles.append(full_basefilepath) if xbmcvfs.exists( full_basefilepath) and settings.recycle_removed: recyclefile(full_basefilepath) else: folder = os.path.dirname(full_basefilepath) if not xbmcvfs.exists(folder): xbmcvfs.mkdirs(folder) # For now this just downloads the whole thing in memory, then saves it to file. # Maybe chunking it will be better when GIFs are handled file_ = xbmcvfs.File(full_basefilepath, 'wb') with closing(file_): if not file_.write(result.content): self.fileerror_count += 1 raise FileError( L(CANT_WRITE_TO_FILE).format(full_basefilepath)) self.fileerror_count = 0 mediaitem.downloadedart[arttype] = full_basefilepath log("downloaded '{0}'\nto image file '{1}'".format( url, full_basefilepath)) return services_hit, error
def _updateDialogVideoInfo(self): # Get the location of the information dialog XML file dialogXml = os_path_join(self.estuarypath, 'DialogVideoInfo.xml') log("DialogVideoInfo: Estuary dialog XML file: %s" % dialogXml) # Make sure the file exists (It should always exist) if not xbmcvfs.exists(dialogXml): log( "DialogVideoInfo: Unable to find the file DialogVideoInfo.xml, skipping file", xbmc.LOGERROR) self.errorToLog = True return # Load the DialogVideoInfo.xml into a string dialogXmlFile = xbmcvfs.File(dialogXml, 'r') dialogXmlStr = dialogXmlFile.read() dialogXmlFile.close() # Now check to see if the skin file has already had the video extras bits added if 'script.videoextras' in dialogXmlStr: # Already have video extras referenced, so we do not want to do anything else # to this file log( "DialogVideoInfo: Video extras already referenced in %s, skipping file" % dialogXml, xbmc.LOGINFO) self.errorToLog = True return # Start by adding the onLoad section previousOnLoad = '<controls>' if previousOnLoad not in dialogXmlStr: # The file has had a standard component deleted, so quit log( "DialogVideoInfo: Could not find controls command, skipping file", xbmc.LOGERROR) self.errorToLog = True return # Now add the Video Extras onLoad command after the allowoverlay one DIALOG_VIDEO_INFO_ONLOAD = '<onload condition="System.HasAddon(script.videoextras)">RunScript(script.videoextras,check,"$INFO[ListItem.FilenameAndPath]")</onload>\n\t' insertTxt = DIALOG_VIDEO_INFO_ONLOAD + previousOnLoad dialogXmlStr = dialogXmlStr.replace(previousOnLoad, insertTxt) # Now we need to add the button after the Final button previousButton = '<param name="label" value="$LOCALIZE[208]" />' if previousButton not in dialogXmlStr: # The file has had a standard component deleted, so quit log("DialogVideoInfo: Could not find play button, skipping file", xbmc.LOGERROR) self.errorToLog = True return # Check to make sure we use a unique ID value for the button idOK = False idval = 200 while not idOK: idStr = '<param name="id" value="%d"' % idval if idStr not in dialogXmlStr: idOK = True else: idval = idval + 1 # Now add the Video Extras button after the Play one DIALOG_VIDEO_INFO_BUTTON = '''\n\t\t\t\t\t</include>\n\t\t\t\t\t<include content="InfoDialogButton"> \t\t\t\t\t\t<param name="id" value="%d" /> \t\t\t\t\t\t<param name="icon" value="special://masterprofile/../addons/script.videoextras/resources/skins/icons/overlay3.png" /> \t\t\t\t\t\t<param name="label" value="$ADDON[script.videoextras 32001]" /> \t\t\t\t\t\t<param name="onclick_1" value="Action(close)" /> \t\t\t\t\t\t<param name="onclick_2" value="RunScript(script.videoextras,display,$INFO[ListItem.FilenameAndPath])" /> \t\t\t\t\t\t<param name="visible" value="System.HasAddon(script.videoextras) + [String.IsEqual(ListItem.DBType,movie) | String.IsEqual(ListItem.DBType,tvshow) | String.IsEqual(ListItem.DBType,season) | String.IsEqual(ListItem.DBType,episode)] + IsEmpty(Window(movieinformation).Property(HideVideoExtrasButton))" />''' insertTxt = previousButton + (DIALOG_VIDEO_INFO_BUTTON % idval) dialogXmlStr = dialogXmlStr.replace(previousButton, insertTxt) self._saveNewFile(dialogXml, dialogXmlStr)
def loadCollection(self, collectionFile, removeDisabled=True): log("CollectSets: Loading collection %s" % collectionFile) if not xbmcvfs.exists(collectionFile): log( "CollectSets: Failed to load collection file: %s" % collectionFile, xbmc.LOGERROR) return None # Load all of the videos that are disabled disabledVideos = [] if removeDisabled: disabledVideos = self.getDisabledVideos() collectionDetails = None try: # Load the file as a string collectionFileRef = xbmcvfs.File(collectionFile, 'r') collectionStr = collectionFileRef.read() collectionFileRef.close() collectionElem = ET.ElementTree(ET.fromstring(collectionStr)) collectionName = collectionElem.find('collection') if collectionName in [None, ""]: return None collectionDetails = {'name': None, 'image': None, 'videos': []} collectionDetails['name'] = collectionName.text log("CollectSets: Collection Name is %s" % collectionDetails['name']) # Record which sets are builtin to the addon collectionDetails['builtin'] = 'false' builtinElem = collectionElem.getroot().find('builtin') if builtinElem not in [None, ""]: if builtinElem.text == 'true': collectionDetails['builtin'] = 'true' isEncoded = False encodedElem = collectionElem.getroot().find('encoded') if encodedElem not in [None, ""]: if encodedElem.text == 'true': isEncoded = True imageElem = collectionElem.getroot().find('image') if imageElem not in [None, ""]: collectionDetails['image'] = imageElem.text # Get the videos that are in the collection for elemItem in collectionElem.findall('video'): video = { 'name': None, 'filename': None, 'image': ICON, 'duration': None, 'primary': None, 'enabled': True } nameElem = elemItem.find('name') if nameElem not in [None, ""]: video['name'] = nameElem.text filenameElem = elemItem.find('filename') if filenameElem not in [None, ""]: video['filename'] = filenameElem.text imageElem = elemItem.find('image') if imageElem not in [None, ""]: video['image'] = imageElem.text durationElem = elemItem.find('duration') if durationElem not in [None, "", 0]: if durationElem.text not in [None, "", 0]: video['duration'] = int(durationElem.text) primaryElem = elemItem.find('primary') if nameElem not in [None, ""]: if isEncoded: video['primary'] = base64.b64decode(primaryElem.text) else: video['primary'] = primaryElem.text # Check if this video is in the disabled list if video['filename'] in disabledVideos: video['enabled'] = False collectionDetails['videos'].append(video) except: log( "CollectSets: Failed to read collection file %s" % collectionFile, xbmc.LOGERROR) log("CollectSets: %s" % traceback.format_exc(), xbmc.LOGERROR) return collectionDetails
def favourites(folder_path): items = [] favourites_file = "%sfavourites.xml" % folder_path f = xbmcvfs.File(favourites_file, "rb") data = f.read() favourites = re.findall("<favourite.*?</favourite>", data) for fav in favourites: url = '' match = re.search( '<favourite name="(.*?)" filetype="(.*?)" thumb="(.*?)">(.*?)<', fav) if match: label = match.group(1) filetype = match.group(2) thumbnail = match.group(3) url = match.group(4) if url: context_items = [] if plugin.get_setting('add') == 'false': context_items.append( ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Add Menu', 'ActivateWindow(10001,"%s")' % (plugin.url_for('add', path=folder_path)))) if plugin.get_setting('sort') == 'false': context_items.append( ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Move', 'XBMC.RunPlugin(%s)' % (plugin.url_for(move_favourite, favourites_file=favourites_file, name=label, url=url)))) context_items.append( ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Move to Folder', 'XBMC.RunPlugin(%s)' % (plugin.url_for(move_favourite_to_folder, favourites_file=favourites_file, name=label, url=url, thumbnail=thumbnail, filetype=filetype)))) context_items.append( ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Remove', 'XBMC.RunPlugin(%s)' % (plugin.url_for(remove_favourite, favourites_file=favourites_file, name=label, url=url)))) context_items.append( ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Rename', 'XBMC.RunPlugin(%s)' % (plugin.url_for(rename_favourite, favourites_file=favourites_file, name=label, fav=fav)))) context_items.append( ("[COLOR yellow][B]%s[/B][/COLOR] " % 'Change Image', 'XBMC.RunPlugin(%s)' % (plugin.url_for(change_favourite_thumbnail, favourites_file=favourites_file, thumbnail=thumbnail, fav=fav)))) if filetype == "file": is_playable = True else: is_playable = False items.append({ 'label': unescape(label), 'path': url, #plugin.url_for('execute',url=unescape(url)), #'path': plugin.url_for('play',url=unescape(url)), 'thumbnail': unescape(thumbnail), 'context_menu': context_items, 'is_playable': is_playable, 'info_type': 'Video', 'info': { "mediatype": "episode", "title": unescape(label) }, }) plugin.set_content("episodes") return items
def doDownload(url, dest, title, image, headers): headers = json.loads(urllib.unquote_plus(headers)) url = urllib.unquote_plus(url) title = urllib.unquote_plus(title) image = urllib.unquote_plus(image) dest = urllib.unquote_plus(dest) file = dest.rsplit(os.sep, 1)[-1] resp = getResponse(url, headers, 0) if not resp: xbmcgui.Dialog().ok(title, dest, 'Download failed', 'No response from server') return try: content = int(resp.headers['Content-Length']) except Exception: content = 0 try: resumable = 'bytes' in resp.headers['Accept-Ranges'].lower() except Exception: resumable = False # print "Download Header" # print resp.headers if resumable: print "Download is resumable" if content < 1: xbmcgui.Dialog().ok(title, file, 'Unknown filesize', 'Unable to download') return size = 1024 * 1024 mb = content / (1024 * 1024) if content < size: size = content total = 0 notify = 0 errors = 0 count = 0 resume = 0 sleep = 0 if xbmcgui.Dialog().yesno(title + ' - Confirm Download', file, 'Complete file is %dMB' % mb, 'Continue with download?', 'Confirm', 'Cancel') == 1: return print 'Download File Size : %dMB %s ' % (mb, dest) # f = open(dest, mode='wb') f = xbmcvfs.File(dest, 'w') chunk = None chunks = [] while True: downloaded = total for c in chunks: downloaded += len(c) percent = min(100 * downloaded / content, 100) if percent >= notify: xbmc.executebuiltin("XBMC.Notification(%s,%s,%i,%s)" % (title + ' - Download Progress - ' + str(percent) + '%', dest, 10000, image)) print 'Download percent : %s %s %dMB downloaded : %sMB File Size : %sMB' % ( str(percent) + '%', dest, mb, downloaded / 1000000, content / 1000000) notify += 10 chunk = None error = False try: chunk = resp.read(size) if not chunk: if percent < 99: error = True else: while len(chunks) > 0: c = chunks.pop(0) f.write(c) del c f.close() print '%s download complete' % (dest) return done(title, dest, True) except Exception, e: print str(e) error = True sleep = 10 errno = 0 if hasattr(e, 'errno'): errno = e.errno if errno == 10035: # 'A non-blocking socket operation could not be completed immediately' pass if errno == 10054: # 'An existing connection was forcibly closed by the remote host' errors = 10 # force resume sleep = 30 if errno == 11001: # 'getaddrinfo failed' errors = 10 # force resume sleep = 30 if chunk: errors = 0 chunks.append(chunk) if len(chunks) > 5: c = chunks.pop(0) f.write(c) total += len(c) del c if error: errors += 1 count += 1 print '%d Error(s) whilst downloading %s' % (count, dest) xbmc.sleep(sleep * 1000) if (resumable and errors > 0) or errors >= 10: if (not resumable and resume >= 50) or resume >= 500: # Give up! print '%s download canceled - too many error whilst downloading' % ( dest) return done(title, dest, False) resume += 1 errors = 0 if resumable: chunks = [] # create new response print 'Download resumed (%d) %s' % (resume, dest) resp = getResponse(url, headers, total) else: # use existing response pass
import os import xbmc import xbmcgui import xbmcaddon import xbmcvfs import json id_shortcuts = {} file_name = 'special://profile/addon_data/script.jedi.guide/channel_id_title.ini' f = xbmcvfs.File(file_name, 'rb') data = f.read() f.close() id_shortcuts = {} if data: lines = data.splitlines() for line in lines: id_shortcut = line.split("=") if len(id_shortcut) == 2: id_shortcuts[id_shortcut[0]] = id_shortcut[1] shortcut_file_name = 'special://profile/addon_data/script.jedi.guide/channel_id_shortcut.ini' f = xbmcvfs.File(shortcut_file_name, 'rb') data = f.read() f.close() if data: lines = data.splitlines() for line in lines: id_shortcut = line.split("=") if len(id_shortcut) == 2:
def file(filename, type): return xbmcvfs.File(filename, type)
def Download(id, url, filename, stack=False): subtitle_list = [] ## Cleanup temp dir, we recomend you download/unzip your subs in temp folder and ## pass that to XBMC to copy and activate if xbmcvfs.exists(__temp__): try: rmtree(__temp__) except: Notify('Error cleanup', 'error') pass xbmcvfs.mkdirs(__temp__) log_my('Download from id', url) sub = get_sub(id, url, filename) if (sub.has_key('data') and sub.has_key('fname')): log_my('{0}'.format(sub['fname']), 'saving') ff = os.path.join(__temp__, sub['fname']) subFile = xbmcvfs.File(ff, 'wb') subFile.write(sub['data']) subFile.close() xbmc.sleep(500) Notify('{0}'.format(sub['fname']), 'load') if id == 'unacs': xbmcvfs.delete(ff) headers = { "Host": "subsunacs.net", "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate, br", "DNT": "1", "Connection": "keep-alive", "Upgrade-Insecure-Requests": "1", "Cache-Control": "max-age=0", } url = 'https://subsunacs.net' + url + '!' req = requests.get(url, headers=headers) match = re.compile('<a href="(.+?)">(.+?)</a></label>').findall( req.text) for suburl, subname in match: subname = subname.encode('cp1251', 'ignore').decode( 'cp1251', 'ignore').encode('utf-8', 'ignore').replace(' ', '.') #suname = subname.encode('utf-8') subtitri = __temp__ + subname try: url2 = 'https://subsunacs.net' + suburl req2 = requests.get(url2, headers=headers) f = open(subtitri, 'wb') f.write(req2.content) f.close() xbmc.sleep(1000) except: pass else: if __addon__.getSetting('xbmc_extractor') == 'true': if '.zip' in ff: xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % ( ff, __temp__, )).encode('utf-8'), True) xbmcvfs.delete(ff) #check for rars after zip extraction unextracted_rars = xbmcvfs.listdir(__temp__) for rars in unextracted_rars[1]: if rars.endswith('.rar'): src = 'archive' + '://' + urllib.quote_plus( __temp__ + rars) + '/' (cdirs, cfiles) = xbmcvfs.listdir(src) for cfile in cfiles: fsrc = '%s%s' % (src, cfile) xbmcvfs.copy(fsrc, __temp__ + cfile) else: src = 'archive' + '://' + urllib.quote_plus(ff) + '/' (cdirs, cfiles) = xbmcvfs.listdir(src) for cfile in cfiles: fsrc = '%s%s' % (src, cfile) xbmcvfs.copy(fsrc, __temp__ + cfile) elif __addon__.getSetting('rarlab') == 'true': import rarfile if '.rar' in ff: archive = rarfile.RarFile(ff) archive.extract(__temp__) xbmcvfs.delete(ff) else: xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % ( ff, __temp__, )).encode('utf-8'), True) xbmcvfs.delete(ff) #check for rars after zip extraction unextracted_rars = xbmcvfs.listdir(__temp__) for rars in unextracted_rars[1]: if rars.endswith('.rar'): archive = rarfile.RarFile(__temp__ + rars) archive.extract(__temp__) elif __addon__.getSetting('extract_me') == 'true': if '.zip' in ff: xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % ( ff, __temp__, )).encode('utf-8'), True) xbmcvfs.delete(ff) #check for rars after zip extraction unextracted_rars = xbmcvfs.listdir(__temp__) for rars in unextracted_rars[1]: if rars.endswith('.rar'): s = requests.Session() r = s.get('https://extract.me/upload/') mycook = re.search( 'uid=(.+?);', r.headers['Set-Cookie']).group(1) fname = rars files = { 'files': (fname, open(__temp__ + rars, 'rb'), "application/octet-stream") } payload = {'uid': mycook, 'files': filename} r = s.post('https://extract.me/upload/', files=files, data=payload) tmp_filename = r.json()['files'][0]['tmp_filename'] name = r.json()['files'][0]['name'] nexpayload = { 'tmp_filename': tmp_filename, 'archive_filename': name, 'password': '' } r = s.post('https://extract.me/unpack/', data=nexpayload) compres_to_zip = s.post( 'https://extract.me/compress/zip/' + mycook + '/' + tmp_filename) zipped = compres_to_zip.json()['download_url'] nexturl = 'https://extract.me/' + mycook + zipped ziper = s.get(nexturl) zf = re.search('.*\/(.+?\.zip)', zipped).group(1) zname = __temp__ + zf f = open(zname, 'wb+') f.write(ziper.content) f.close() #xbmc.executebuiltin(('XBMC.Extract doent extract zips lol import zipfile #xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (zname,__temp__,)).encode('utf-8'), True) #xbmc.sleep(500) with zipfile.ZipFile(zname, 'r') as zip_ref: zip_ref.extractall(__temp__) else: s = requests.Session() r = s.get('https://extract.me/upload/') mycook = re.search('uid=(.+?);', r.headers['Set-Cookie']).group(1) fname = sub['fname'] files = { 'files': (fname, open(ff, 'rb'), "application/octet-stream") } payload = {'uid': mycook, 'files': filename} r = s.post('https://extract.me/upload/', files=files, data=payload) tmp_filename = r.json()['files'][0]['tmp_filename'] name = r.json()['files'][0]['name'] nexpayload = { 'tmp_filename': tmp_filename, 'archive_filename': name, 'password': '' } r = s.post('https://extract.me/unpack/', data=nexpayload) compres_to_zip = s.post( 'https://extract.me/compress/zip/' + mycook + '/' + tmp_filename) zipped = compres_to_zip.json()['download_url'] nexturl = 'https://extract.me/' + mycook + zipped ziper = s.get(nexturl) zf = re.search('.*\/(.+?\.zip)', zipped).group(1) f = open(__temp__ + zf, 'wb+') f.write(ziper.content) f.close() xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % ( __temp__ + zf, __temp__, )).encode('utf-8'), True) elif __addon__.getSetting('online-convert-com') == 'true': if '.zip' in ff: xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % ( ff, __temp__, )).encode('utf-8'), True) xbmcvfs.delete(ff) #check for rars after zip extraction We try to extract from xbmc because not to wasting minutes in OCdotCom unextracted_rars = xbmcvfs.listdir(__temp__) for rars in unextracted_rars[1]: if rars.endswith('.rar'): src = 'archive' + '://' + urllib.quote_plus( __temp__ + rars) + '/' (cdirs, cfiles) = xbmcvfs.listdir(src) for cfile in cfiles: fsrc = '%s%s' % (src, cfile) xbmcvfs.copy(fsrc, __temp__ + cfile) else: api_key = __addon__.getSetting('ocapi') newendpoint = 'http://api2.online-convert.com/jobs' data = { "conversion": [{ "category": "archive", "target": "zip" }] } head = { 'x-oc-api-key': api_key, 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' } res = requests.post(newendpoint, data=json.dumps(data), headers=head) match = re.compile( 'id":"(.+?)".+?server":"(.+?)"').findall(res.text) for idj, servurl in match: servurl = servurl.replace('\/', '/') nextendpont = servurl + '/upload-file/' + idj file = {'file': open(ff, 'rb')} head = {'x-oc-api-key': api_key} res = requests.post(nextendpont, files=file, headers=head) xbmc.sleep(2000) res = requests.get(newendpoint, headers=head) match2 = re.compile('"uri":"(http.+?zip)"').findall( res.text) for dlzip in match2: zipfile = dlzip.replace('\/', '/') subfile = zipfile.split("/")[-1] r = requests.get(zipfile) with open((__temp__ + subfile), 'wb') as f: f.write(r.content) xbmc.sleep(500) f.close() xbmc.sleep(1000) delurl = 'http://api2.online-convert.com/jobs/' + idj head = { 'x-oc-api-key': api_key, 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' } res = requests.delete(delurl, headers=head) xbmc.sleep(500) jj = __temp__ + subfile xbmc.executebuiltin( ('XBMC.Extract("%s","%s")' % (jj, __temp__)), True) elif __addon__.getSetting('android_rar') == 'true': if 'zip' in ff: xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % ( ff, __temp__, )).encode('utf-8'), True) else: app = 'com.rarlab.rar' intent = 'android.intent.action.VIEW' dataType = 'application/rar' dataURI = ff arch = 'StartAndroidActivity("%s", "%s", "%s", "%s")' % ( app, intent, dataType, dataURI) xbmc.executebuiltin(arch) if __addon__.getSetting('android_rar') == 'true': timer = __addon__.getSetting('ar_wait_time') xbmc.sleep(int(timer) * 1000) dirs, files = xbmcvfs.listdir(__temp__) files.extend(dirs) appendsubfiles(subtitle_list, __temp__, files) if len(subtitle_list) >= 2: subtitle_list = select_1(subtitle_list) if xbmcvfs.exists(subtitle_list[0]): return subtitle_list else: Notify('Error', 'Bad format or ....') return []