def create_legal_filename(title, year): filename = title if year: filename += ' %s' % (year) filename = re.sub(r'(?!%s)[^\w\-_\.]', '.', filename) filename = re.sub('\.+', '.', filename) xbmc.makeLegalFilename(filename) return filename
def downloadMovie(self, url, path, title, extension): if not os.path.exists(path): common.log('Path does not exist') return None if title == '': common.log('No title given') return None file_path = xbmc.makeLegalFilename(os.path.join(path, title + extension)) file_path = urllib.unquote_plus(file_path) # Overwrite existing file? if os.path.isfile(file_path): self.pDialog = xbmcgui.Dialog() if not common.ask('File already exists. Overwrite?\n' + os.path.basename(file_path)): title = common.showOSK(urllib.unquote_plus(title), common.translate(30102)) if not title: return None file_path = xbmc.makeLegalFilename(os.path.join(path, title + extension)) file_path = urllib.unquote_plus(file_path) success = self.__download(url, file_path) if success: return file_path else: return None
def CleanExpired(self): #delete files more than an hour old self.Notification('Hulu Library','Removing Expired Content') #delete old tv show files dir = xbmc.makeLegalFilename(TV_SHOWS_PATH) dirs, trash = xbmcvfs.listdir(dir) for show in dirs: show = xbmc.makeLegalFilename(os.path.join(dir, show)) trash, files = xbmcvfs.listdir(show) for file in files: path = xbmc.makeLegalFilename(os.path.join(show,file)) if (sys.platform == 'win32'): path = path.replace('smb:','') if (time.mktime(time.strptime(time.ctime(os.path.getmtime(path)))) < (time.mktime(time.localtime()) - 3600)): xbmcvfs.delete(path) #delete old movie files dir = xbmc.makeLegalFilename(MOVIE_PATH) trash, movies = xbmcvfs.listdir(dir) for movie in movies: path = xbmc.makeLegalFilename(os.path.join(dir, movie)) if (sys.platform == 'win32'): path = path.replace('smb:','') if time.mktime(time.strptime(time.ctime(os.path.getmtime(path)))) < (time.mktime(time.localtime()) - 3600): xbmcvfs.delete(path) xbmc.log(path) self.Notification('Hulu Library','Expired Content Removed')
def _lib_folders(section): section_dir = xbmc.translatePath( xbmc.makeLegalFilename('/'.join([library_path(), section]))) return [ xbmc.makeLegalFilename('/'.join([section_dir, folder.decode('utf-8')])) for folder in xbmcvfs.listdir(section_dir)[0] ]
def filename_from_title(title, video_type): if video_type == 'tvshow': filename = '%s S%sE%s.strm' filename = filename % (title, '%s', '%s') else: filename = '%s.strm' % title filename = re.sub(r'(?!%s)[^\w\-_\. ]', '_', filename) xbmc.makeLegalFilename(filename) return filename
def legal_filename(filename): try: filename = filename.strip() filename = re.sub(r'(?!%s)[^\w\-_\.]', '.', filename) filename = re.sub('\.+', '.', filename) filename = re.sub(re.compile('(CON|PRN|AUX|NUL|COM\d|LPT\d)\.', re.I), '\\1_', filename) xbmc.makeLegalFilename(filename) return filename except: return filename
def export_item(item_task, library_home): """Create strm file for an item and add it to the library""" # Paths must be legal to ensure NFS compatibility destination_folder = xbmc.makeLegalFilename(os.path.join( library_home, item_task['section'], item_task['destination'])) export_filename = xbmc.makeLegalFilename(os.path.join( destination_folder.decode('utf-8'), item_task['filename'] + '.strm')) _add_to_library(item_task['videoid'], export_filename) _create_destination_folder(destination_folder) _write_strm_file(item_task, export_filename) common.debug('Exported {}'.format(item_task['title']))
def filename_from_title(title, video_type, year=None): if video_type == VIDEO_TYPES.TVSHOW: filename = '%s S%sE%s.strm' filename = filename % (title, '%s', '%s') else: if year: title = '%s (%s)' % (title, year) filename = '%s.strm' % title filename = re.sub(r'(?!%s)[^\w\-_\.]', '.', filename) filename = re.sub('\.+', '.', filename) xbmc.makeLegalFilename(filename) return filename
def legal_filename(filename): try: filename = filename.strip() filename = re.sub(r"(?!%s)[^\w\-_\.]", ".", filename) filename = re.sub("\.+", ".", filename) filename = re.sub( re.compile("(CON|PRN|AUX|NUL|COM\d|LPT\d)\.", re.I), "\\1_", filename ) xbmc.makeLegalFilename(filename) return filename except: return filename
def copy(orgfilename, newfilename): orgfilename = xbmc.makeLegalFilename(orgfilename) newfilename = xbmc.makeLegalFilename(newfilename) if VFS_AVAILABLE == True: xbmcvfs.copy(orgfilename, newfilename) else: try: shutil.copy(orgfilename, newfilename) except: return False return True
def filename_from_title(title, video_type, year=None): if video_type == VIDEO_TYPES.TVSHOW: filename = '%s S%sE%s' filename = filename % (title, '%s', '%s') else: if year: title = '%s.%s' % (title, year) filename = title filename = re.sub(r'(?!%s)[^\w\-_\.]', '.', filename) filename = re.sub('\.+', '.', filename) filename = re.sub(re.compile('(CON|PRN|AUX|NUL|COM\d|LPT\d)\.', re.I), '\\1_', filename) xbmc.makeLegalFilename(filename) return filename
def filename_from_title(title, video_type, year=None): if video_type == VIDEO_TYPES.TVSHOW: filename = "%s S%sE%s.strm" filename = filename % (title, "%s", "%s") else: if year: title = "%s (%s)" % (title, year) filename = "%s.strm" % title filename = re.sub(r"(?!%s)[^\w\-_\.]", ".", filename) filename = re.sub("\.+", ".", filename) xbmc.makeLegalFilename(filename) return filename
def writeFiles(self,fileList,source,dest): utils.log("Writing files to: " + dest) self.filesTotal = len(fileList) self.filesLeft = self.filesTotal #write each file from source to destination for aFile in fileList: if(not self.checkCancel()): utils.log('Writing file: ' + source + aFile,xbmc.LOGDEBUG) self.updateProgress(aFile) if (aFile.startswith("-")): vfs.mkdir(xbmc.makeLegalFilename(dest + aFile[1:],False)) else: vfs.copy(xbmc.makeLegalFilename(source + aFile),xbmc.makeLegalFilename(dest + aFile,False))
def _get_legal_filepath(self, title, url, id_=0): # set our default filename and extension file_, ext = os.path.splitext(os.path.basename(url)) # does user want to use title as filename file_ = [file_, title][self.m_addon.getSetting("trailer.use.title")] # set identifier trailer_id = "" if (id_ > 0): trailer_id = " ({id})".format(id="ABCDEFGHIJKLMNOPQRSTUVWXYZ"[id_]) # set our default trailer text trailer = ["", "-trailer"][self.m_addon.getSetting("trailer.add.trailer")] # set our default file path (if play_mode is temp, download to cache folder) if (self.m_addon.getSetting("trailer.play.mode") == 1): filepath = "special://temp/" else: filepath = self.m_addon.getSetting("trailer.save.folder") or "special://temp/" # do we want to save with movie if (self.m_addon.getSetting("trailer.save.movie")): filepath, file_, trailer = self._get_movie_path( title, filepath, file_, trailer ) # set final filename file_ = "{name}{id}{trailer}{ext}".format( name=os.path.splitext(file_)[0], id=trailer_id, trailer=trailer, ext=ext ) # FIXME: may need changing for temorary download # if file already exists add an ID and try again if (filepath != "special://temp/" and xbmcvfs.exists(xbmc.makeLegalFilename(xbmc.validatePath( os.path.join( xbmc.translatePath(filepath), file_ ) )).decode("UTF-8"))): return self._get_legal_filepath(title, url, id_ + 1) # return final path return xbmc.makeLegalFilename(xbmc.validatePath( os.path.join( xbmc.translatePath(filepath), file_ ) )).decode("UTF-8")
def delDirContent(self, r_path): """ Delete the content of a directory ( file and sub direstories) but not the directory itself path: directory path """ #print "delDirContent" #print path result = True path = xbmc.makeLegalFilename(r_path) if os.path.isdir(path): dirItems = os.listdir(path) for item in dirItems: itemFullPath = os.path.join(path, item) try: if os.path.isfile(itemFullPath): # Fichier os.remove(itemFullPath) elif os.path.isdir(itemFullPath): # Repertoire self.deleteDir(itemFullPath) except: result = False print "delDirContent: Exception la suppression du contenu du reperoire: %s" % path print_exc() else: print "delDirContent: %s n'est pas un repertoire" % path result = False return result
def deleteDir(self, r_path): """ Delete a directory and all its content (files and subdirs) Note: the directory does NOT need to be empty Return True if success, False otherwise """ result = True path = xbmc.makeLegalFilename(r_path) if os.path.isdir(path): dirItems = os.listdir(path) for item in dirItems: itemFullPath = os.path.join(path, item) try: if os.path.isfile(itemFullPath): # Fichier os.remove(itemFullPath) elif os.path.isdir(itemFullPath): # Repertoire self.deleteDir(itemFullPath) except: result = False print "deleteDir: Exception deleting directory: %s" % path print_exc() # Suppression du repertoire pere try: os.rmdir(path) except: result = False print "deleteDir: Exception deleting directory: %s" % path print_exc() else: print "deleteDir: %s is not a directory" % path result = False return result
def getVideoLength(self, filename): filename = xbmc.makeLegalFilename(filename) self.log("getVideoLength " + filename) if len(filename) == 0: self.log("No file name specified") return 0 self.log("os name is " + os.name) if os.path.exists(filename) == False: if filename[0:6].lower() == 'smb://': filename = self.handleSMB(filename) else: self.log("Unable to open the file") return 0 base, ext = os.path.splitext(filename) ext = ext.lower() if ext in self.AVIExts: self.parser = AVIParser.AVIParser() elif ext in self.MP4Exts: self.parser = MP4Parser.MP4Parser() elif ext in self.MKVExts: self.parser = MKVParser.MKVParser() elif ext in self.FLVExts: self.parser = FLVParser.FLVParser() else: self.log("No parser found for extension " + ext) return 0 return self.parser.determineLength(filename)
def DownloadVideo(url, title): fileName = url.split('?')[0].strip() extension = os.path.splitext(fileName)[1][1:].strip() #remove invalid file characters title = title.replace("/","") title = title + "." + extension if settings.getSetting('download_path') == '': try: downloadPath = xbmcgui.Dialog().browse(3, language(30002),'files', '', False, False, '') if downloadPath == '': return None settings.setSetting(id='download_path', value=downloadPath) if not os.path.exists(downloadPath): os.mkdir(downloadPath) except: pass filePath = xbmc.makeLegalFilename(os.path.join(settings.getSetting('download_path'), title)) if os.path.isfile(filePath): return None global pDialog global pFileName pFileName = title pDialog = xbmcgui.DialogProgress() pDialog.create('OneClickMoviez', language(30003), language(30004)) try: print 'DownloadVideoURL:',url print 'DownloadVideoFilePath:',filePath urllib.urlretrieve(url, filePath, VideoReportHook) #urllib.urlretrieve(url, filePath) print 'DownloadedVideo' pDialog.close() return filePath except Exception, e: print "URLRetrieve Error:",e pass
def createGenrePlaylist(self, pltype, chtype, genre): if isinstance(genre, str): filegenre = genre.decode('ascii', 'ignore').encode( 'ascii' ) #note: this removes the character and encodes back to string. elif isinstance(genre, unicode): filegenre = genre.encode('ascii', 'ignore') flename = xbmc.makeLegalFilename(u''.join( (GEN_CHAN_LOC, pltype, '_', filegenre, '.xsp')).encode('utf-8').strip()) try: fle = FileAccess.open(flename, "w") except: self.log(LANGUAGE(30034) + ' ' + flename, xbmc.LOGERROR) return '' self.writeXSPHeader(fle, pltype, self.getChannelName(chtype, genre)) genre = self.cleanString(genre) fle.write(' <rule field="genre" operator="is">\n') fle.write(' <value>' + genre + '</value>\n') fle.write(' </rule>\n') self.writeXSPFooter(fle, 0, "random") fle.close() return flename
def add_to_library(video_type, url, title, img, year, imdbnum, movie_num=''): try: IW_addon.log('Creating .strm for %s %s %s %s %s %s' % (video_type, title, imdbnum, url, img, year)) except: pass if video_type == 'tvshow': save_path = IW_addon.get_setting('tvshow-folder') save_path = xbmc.translatePath(save_path) strm_string = IW_addon.build_plugin_url( {'mode': 'NightlyNewsSubMenu','dialog': '1'}) if year: title = '%s (%s)' % (title, year) filename = filename_from_title(title + ' s1e1', 'movie') title = re.sub(r'[^\w\-_\. ]', '_', title) titles = title final_path = os.path.join(save_path, title, filename) final_path = xbmc.makeLegalFilename(final_path) if not xbmcvfs.exists(os.path.dirname(final_path)): try: try: xbmcvfs.mkdirs(os.path.dirname(final_path)) except: os.path.mkdir(os.path.dirname(final_path)) except Exception, e: try: IW_addon.log('Failed to create directory %s' % final_path) except: pass try: file_desc = xbmcvfs.File(final_path, 'w') file_desc.write(strm_string) file_desc.close() except Exception, e: IW_addon.log('Failed to create .strm file: %s\n%s' % (final_path, e))
def createGenreMixedPlaylist(self, genre): if isinstance(genre, str): filegenre = genre.decode('ascii', 'ignore').encode( 'ascii' ) #note: this removes the character and encodes back to string. elif isinstance(genre, unicode): filegenre = genre.encode('ascii', 'ignore') flename = xbmc.makeLegalFilename(u''.join( (GEN_CHAN_LOC, 'Mixed_', filegenre, '.xsp')).encode('utf-8').strip()) try: fle = FileAccess.open(flename, "w") except: self.log(LANGUAGE(30034) + ' ' + flename, xbmc.LOGERROR) return '' epname = os.path.basename( self.createGenrePlaylist('episodes', 3, genre)) moname = os.path.basename(self.createGenrePlaylist('movies', 4, genre)) self.writeXSPHeader(fle, 'mixed', self.getChannelName(5, genre)) fle.write(' <rule field="playlist" operator="is">' + epname + '</rule>\n') fle.write(' <rule field="playlist" operator="is">' + moname + '</rule>\n') self.writeXSPFooter(fle, 0, "random") fle.close() return flename
def downloadfileGzipped(url, pathfichero): logger.info("url=" + url) nombrefichero = pathfichero logger.info("filename=" + nombrefichero) import xbmc nombrefichero = xbmc.makeLegalFilename(nombrefichero) logger.info("filename=" + nombrefichero) patron = "(http://[^/]+)/.+" matches = re.compile(patron, re.DOTALL).findall(url) if len(matches): logger.info("Main URL: " + matches[0]) url1 = matches[0] else: url1 = url txheaders = { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; ' 'Media Center PC 5.0; .NET CLR 3.0.04506)', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'es-es,es;q=0.8,en-us;q=0.5,en;q=0.3', 'Accept-Encoding': 'gzip,deflate', 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Keep-Alive': '115', 'Connection': 'keep-alive', 'Referer': url1, } txdata = "" # Crea el diálogo de progreso from platformcode import platformtools progreso = platformtools.dialog_progress("addon", config.get_localized_string(60200), url.split("|")[0], nombrefichero) # Timeout del socket a 60 segundos socket.setdefaulttimeout(10) h = urllib2.HTTPHandler(debuglevel=0) request = urllib2.Request(url, txdata, txheaders) # if existSize > 0: # request.add_header('Range', 'bytes=%d-' % (existSize, )) opener = urllib2.build_opener(h) urllib2.install_opener(opener) try: connexion = opener.open(request) except urllib2.HTTPError, e: logger.error("error %d (%s) al abrir la url %s" % (e.code, e.msg, url)) # print e.code # print e.msg # print e.hdrs # print e.fp progreso.close() # El error 416 es que el rango pedido es mayor que el fichero => es que ya está completo if e.code == 416: return 0 else: return -2
def delDirContent(self, r_path): """ Delete the content of a directory ( file and sub direstories) but not the directory itself path: directory path """ # print "delDirContent" # print path result = True path = xbmc.makeLegalFilename(r_path) if os.path.isdir(path): dirItems = os.listdir(path) for item in dirItems: itemFullPath = os.path.join(path, item) try: if os.path.isfile(itemFullPath): # Fichier os.remove(itemFullPath) elif os.path.isdir(itemFullPath): # Repertoire self.deleteDir(itemFullPath) except: result = False print "delDirContent: Exception la suppression du contenu du reperoire: %s" % path print_exc() else: print "delDirContent: %s n'est pas un repertoire" % path result = False return result
def _get_item(mediatype, filename): # To ensure compatibility with previously exported items, # make the filename legal fname = xbmc.makeLegalFilename(filename) untranslated_path = os.path.dirname(fname).decode("utf-8") translated_path = os.path.dirname( xbmc.translatePath(fname).decode("utf-8")) shortname = os.path.basename(xbmc.translatePath(fname).decode("utf-8")) # We get the data from Kodi library using filters. # This is much faster than loading all episodes in memory # First build the path filter, we may have to search in both special and translated path path_filter = {'field': 'path', 'operator': 'startswith', 'value': translated_path} \ if fname[:10] != 'special://' \ else {'or': [ {'field': 'path', 'operator': 'startswith', 'value': translated_path}, {'field': 'path', 'operator': 'startswith', 'value': untranslated_path} ]} # Now build the all request and call the json-rpc function through common.get_library_items library_item = common.get_library_items( mediatype, { 'and': [ path_filter, { 'field': 'filename', 'operator': 'is', 'value': shortname } ] })[0] if not library_item: raise ItemNotFound return common.get_library_item_details(mediatype, library_item[mediatype + 'id'])
def export_item(item_task, library_home): """Create strm file for an item and add it to the library""" # Paths must be legal to ensure NFS compatibility destination_folder = g.py2_decode(xbmc.makeLegalFilename('/'.join( [library_home, item_task['section'], item_task['destination']]))) _create_destination_folder(destination_folder) if item_task['is_strm']: export_filename = g.py2_decode(xbmc.makeLegalFilename('/'.join( [destination_folder, item_task['filename'] + '.strm']))) _add_to_library(item_task['videoid'], export_filename, (item_task['nfo_data'] is not None)) _write_strm_file(item_task, export_filename) if item_task['nfo_data'] is not None: nfo_filename = g.py2_decode(xbmc.makeLegalFilename('/'.join( [destination_folder, item_task['filename'] + '.nfo']))) _write_nfo_file(item_task['nfo_data'], nfo_filename) common.debug('Exported {}', item_task['title'])
def downloadFile(url): if __settings__.getSetting('download_path') == '': try: dl_path = xbmcgui.Dialog().browse(0, __language__(30017),'files', '', False, False) __settings__.setSetting(id='download_path', value=dl_path) if not os.path.exists(dl_path): os.mkdir(dl_path) except:pass name ='' extl = url.split('/') for i in extl: name=i file_path = xbmc.makeLegalFilename(os.path.join(__settings__.getSetting('download_path'), name)) if os.path.isfile(file_path): return None try: urllib.urlretrieve(url, file_path, report_hook) if enable_debug: xbmc.output('Picture ' + str(url) + ' downloaded to ' + repr(file_path)) return file_path except IOError: return None except Exception,e: print e pass
def fetchBinary(url): fn = '' try: fn = os.path.join(DIR_USERDATA, os.path.basename(url)) fn = xbmc.translatePath(fn) fn = xbmc.makeLegalFilename(fn) log('fetchBinary() url=%s fn=%s' % (url, fn)) if not os.path.isfile(fn): opener = urllib.FancyURLopener() fn, resp = opener.retrieve(url, fn) opener.close() os.path.isfile(fn) except: msg = sys.exc_info()[1] print msg url = 'http://xbmc.svn.sourceforge.net/svnroot/xbmc/trunk/XBMC/skin/Project%20Mayhem%20III/media/defaultVideoBig.png' fn = os.path.join(DIR_USERDATA, 'defaultVideoBig.png') fn = xbmc.translatePath(fn) log('fetchBinary() url=%s fn=%s' % (url, fn)) if not os.path.isfile(fn): opener = urllib.FancyURLopener() fn, resp = opener.retrieve(url, fn) opener.close() os.path.isfile(fn) if fn and os.path.isfile(fn): return fn else: return ''
def add2lib(url, name, infol, img, fanart, year): addon.log('Add To Library %s , %s, %s' % (name, year, url)) path = xbmc.translatePath(addon.get_setting('movie-folder')) string = 'plugin://plugin.video.mutttsnutz/?mode=playstream&url=' + url + '&name=' + name + '&infol=' filename = '%s.strm' % name path = xbmc.makeLegalFilename( xbmc.translatePath(os.path.join(path, name, filename))) if not xbmcvfs.exists(os.path.dirname(path)): try: try: xbmcvfs.mkdirs(os.path.dirname(path)) except: os.mkdir(os.path.dirname(path)) except: addon.log('FAILED to create directory') if xbmcvfs.exists(path): addon.log(name + ' Already in the library') notification(addon.get_name() + ' allready added', name, img) return notification(addon.get_name() + ' adding to library', name + ' adding to library', img) strm = xbmcvfs.File(path, 'w') strm.write(string) strm.close() xbmc.executebuiltin("UpdateLibrary(video)")
def createShowPlaylist(self, show, setting2): order = 'random' try: setting = int(setting2) if setting & MODE_ORDERAIRDATE > 0: order = 'airdate' except: pass flename = xbmc.makeLegalFilename(GEN_CHAN_LOC + 'Show_' + show + '_' + order + '.xsp') try: fle = open(flename, "w") except: self.Error('Unable to open the cache file ' + flename, xbmc.LOGERROR) return '' self.writeXSPHeader(fle, 'episodes', self.getChannelName(6, show)) show = self.cleanString(show) fle.write(' <rule field="tvshow" operator="is">' + show + '</rule>\n') self.writeXSPFooter(fle, 250, order) fle.close() return flename
def downloadfileGzipped(url,pathfichero): xbmc.output("[downloadtools.py] downloadfileGzipped: url="+url) nombrefichero = pathfichero xbmc.output("[downloadtools.py] downloadfileGzipped: nombrefichero="+nombrefichero) nombrefichero = xbmc.makeLegalFilename(nombrefichero) xbmc.output("[downloadtools.py] downloadfileGzipped: nombrefichero="+nombrefichero) patron = "(http://[^/]+)/.+" matches = re.compile(patron,re.DOTALL).findall(url) if len(matches): xbmc.output("[downloadtools.py] URL principal :"+matches[0]) url1= matches[0] else: url1 = url txheaders = {'User-Agent':'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)', 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language':'es-es,es;q=0.8,en-us;q=0.5,en;q=0.3', 'Accept-Encoding':'gzip,deflate', 'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'Keep-Alive':'115', 'Connection':'keep-alive', 'Referer':url1, } txdata = "" # Crea el diálogo de progreso progreso = xbmcgui.DialogProgress() progreso.create( 'Pelisalacarta' , "Descargando file..." , url , nombrefichero ) # Timeout del socket a 60 segundos socket.setdefaulttimeout(10) h=urllib2.HTTPHandler(debuglevel=0) request = urllib2.Request(url, txdata, txheaders) #if existSize > 0: # request.add_header('Range', 'bytes=%d-' % (existSize, )) opener = urllib2.build_opener(h) urllib2.install_opener(opener) try: connexion = opener.open(request) except urllib2.HTTPError,e: xbmc.output("[downloadtools.py] downloadfile: error %d (%s) al abrir la url %s" % (e.code,e.msg,url)) #print e.code #print e.msg #print e.hdrs #print e.fp f.close() progreso.close() # El error 416 es que el rango pedido es mayor que el fichero => es que ya está completo if e.code==416: return 0 else: return -2
def createNetworkPlaylist(self, network): flename = xbmc.makeLegalFilename(GEN_CHAN_LOC + 'Network_' + network + '.xsp') try: fle = FileAccess.open(flename, "w") except: self.log(LANGUAGE(30034) + ' ' + flename, xbmc.LOGERROR) return '' self.writeXSPHeader(fle, "episodes", self.getChannelName(1, network)) network = network.lower() added = False fle.write(' <rule field="tvshow" operator="is">\n') for i in range(len(self.showList)): if self.showList[i][1].lower() == network: theshow = self.cleanString(self.showList[i][0]) fle.write(' <value>' + theshow + '</value>\n') added = True fle.write(' </rule>\n') self.writeXSPFooter(fle, 0, "random") fle.close() if added == False: return '' return flename
def add2lib( url, name, infol, img, fanart, year ): img = 'http://oi62.tinypic.com/dvgj1t.jpg' addon.log('Add To Library %s , %s, %s' % (name,year,url)) path = xbmc.translatePath( addon.get_setting('movie-folder') ) string = 'plugin://plugin.video.mutttsnutz/?mode=playstream&url='+url+'&name='+name+'&infol=' filename = '%s.strm' % name path = xbmc.makeLegalFilename( xbmc.translatePath(os.path.join( path, name, filename ))) if not xbmcvfs.exists(os.path.dirname(path)): try: try: xbmcvfs.mkdirs(os.path.dirname(path)) except: os.mkdir(os.path.dirname(path)) except: addon.log('FAILED to create directory') if xbmcvfs.exists(path): addon.log( name+' Already in the library' ) notification( addon.get_name()+' allready added', name, img) return notification( addon.get_name()+' adding to library', name+' adding to library', img) strm = xbmcvfs.File(path, 'w') strm.write(string) strm.close() xbmc.executebuiltin("UpdateLibrary(video)")
def createShowPlaylist(self, show, setting2): order = 'random' try: setting = int(setting2) if setting & MODE_ORDERAIRDATE > 0: order = 'episode' except: pass flename = xbmc.makeLegalFilename(GEN_CHAN_LOC + 'Show_' + show + '_' + order + '.xsp') try: fle = FileAccess.open(flename, "w") except: self.log(LANGUAGE(30034) + ' ' + flename, xbmc.LOGERROR) return '' self.writeXSPHeader(fle, 'episodes', self.getChannelName(6, show)) show = self.cleanString(show) fle.write(' <rule field="tvshow" operator="is">\n') fle.write(' <value>' + show + '</value>\n') fle.write(' </rule>\n') self.writeXSPFooter(fle, 0, order) fle.close() return flename
def createNetworkPlaylist(self, network): flename = xbmc.makeLegalFilename(GEN_CHAN_LOC + 'Network_' + network + '.xsp') try: fle = open(flename, "w") except: self.Error('Unable to open the cache file ' + flename, xbmc.LOGERROR) return '' self.writeXSPHeader(fle, "episodes", self.getChannelName(1, network)) network = network.lower() added = False for i in range(len(self.showList)): if self.threadPause() == False: fle.close() return '' if self.showList[i][1].lower() == network: theshow = self.cleanString(self.showList[i][0]) fle.write(' <rule field="tvshow" operator="is">' + theshow + '</rule>\n') added = True self.writeXSPFooter(fle, 250, "random") fle.close() if added == False: return '' return flename
def fetchBinary(url): fn = '' try: fn = os.path.join(DIR_USERDATA, os.path.basename(url)) fn = xbmc.translatePath(fn) fn = xbmc.makeLegalFilename(fn) log('fetchBinary() url=%s fn=%s' % (url,fn)) if not os.path.isfile(fn): opener = urllib.FancyURLopener() fn, resp = opener.retrieve(url, fn) opener.close() os.path.isfile(fn) except: msg = sys.exc_info()[ 1 ] print msg url = 'http://xbmc.svn.sourceforge.net/svnroot/xbmc/trunk/XBMC/skin/Project%20Mayhem%20III/media/defaultVideoBig.png' fn = os.path.join(DIR_USERDATA, 'defaultVideoBig.png') fn = xbmc.translatePath(fn) log('fetchBinary() url=%s fn=%s' % (url,fn)) if not os.path.isfile(fn): opener = urllib.FancyURLopener() fn, resp = opener.retrieve(url, fn) opener.close() os.path.isfile(fn) if fn and os.path.isfile(fn): return fn else: return ''
def download(addon, filename, url, local, notifyFinishDialog=True, headers={}): try: util.info('Downloading %s to %s' % (url, local)) except: util.info('Downloading ' + url) local = xbmc.makeLegalFilename(local) try: filename = util.replace_diacritic(util.decode_html(filename)) except: filename = 'Video soubor' icon = os.path.join(addon.getAddonInfo('path'), 'icon.png') notifyEnabled = addon.getSetting('download-notify') == 'true' notifyEvery = addon.getSetting('download-notify-every') notifyPercent = 1 if int(notifyEvery) == 0: notifyPercent = 10 if int(notifyEvery) == 1: notifyPercent = 5 def encode(string): return u' '.join(string).encode('utf-8') def notify(title, message, time=3000): try: xbmcgui.Dialog().notification(encode(title), encode(message), time=time, icon=icon, sound=False) except: traceback.print_exc() error('unable to show notification') def callback(percent, speed, est, filename): if percent == 0 and speed == 0: notify(xbmc.getLocalizedString(13413), filename) return if notifyEnabled: if percent > 0 and percent % notifyPercent == 0: esTime = '%ss' % est if est > 60: esTime = '%sm' % int(est / 60) message = xbmc.getLocalizedString( 24042) % percent + ' - %s KB/s %s' % (speed, esTime) notify(message, filename) downloader = Downloader(callback) result = downloader.download(url, local, filename, headers) try: if result == True: if xbmc.Player().isPlaying(): notify(xbmc.getLocalizedString(20177), filename) else: if notifyFinishDialog: xbmcgui.Dialog().ok(xbmc.getLocalizedString(20177), filename) else: notify(xbmc.getLocalizedString(20177), filename) else: notify(xbmc.getLocalizedString(257), filename) xbmcgui.Dialog().ok(filename, xbmc.getLocalizedString(257) + ' : ' + result) except: traceback.print_exc()
def get_items(self): """ fetch the idItem, idFile, and path+filename of all items in the Library, then stat each file to get the CTIME / MTIME (creation time). Returns a list of tuples containing (ctime, idItem, idFile, filename, title) eg: [ (12312312312, 1, 5, "c:/Movies/Gladiator (2000)/gladiator.mkv", "Gladiator"), (12423234223, 2, 4, "smb://*****:*****@server/Movies/Something (2010)/something.avi", "Something") ] """ item_list = [] xbmc.executehttpapi("SetResponseFormat()") xbmc.executehttpapi("SetResponseFormat(OpenRecord,%s)" % ("<record>", )) xbmc.executehttpapi("SetResponseFormat(CloseRecord,%s)" % ("</record>", )) if self.library == MOVIES: items_sql = "select idMovie,idFile,strPath,strFileName,c00 from movieview" elif self.library == TV_EPISODES: items_sql = "select idEpisode,idFile,strPath,strFileName,c00 from episodeview" elif self.library == MUSIC_VIDEOS: items_sql = "select idMVideo,idFile,strPath,strFileName,c00 from musicvideoview" if self.library in (MOVIES, TV_EPISODES, MUSIC_VIDEOS): sql_result = xbmc.executehttpapi( "QueryVideoDatabase(%s)" % quote_plus(items_sql), ) records = re.findall("<record>(.+?)</record>", sql_result, re.DOTALL) for record in records: fields = re.findall("<field>(.*?)</field>", record, re.DOTALL) idItem = int(fields[0]) idFile = int(fields[1]) # only choose the first file from a stack if fields[3].startswith('stack://'): fields[3] = fields[3][8:].split(' , ')[0].replace(',,', ',') strPath = xbmc.makeLegalFilename(fields[2]) strFileName = xbmc.makeLegalFilename(fields[3]) fullFilePath = xbmc.makeLegalFilename( os.path.join(strPath, strFileName)) strTitle = fields[4] try: ctime = os.stat(fullFilePath)[self.sort_key] item_list.append( (ctime, idItem, idFile, fullFilePath, strTitle)) except OSError, e: xbmc.log("[media-sort] OSerror: %s, file: %s" % (e.strerror, e.filename))
def makeThumbFilename(self, url): split_info = urlparse.urlsplit(url) basename = split_info[2].replace('/media','').replace('/imdb','').replace('/','').replace('\\','').replace('_','') # restrict length l = len(basename) if l > 30: basename = basename[(l-30):] return xbmc.makeLegalFilename(os.path.join(DIR_IMDB_CACHE, self.IMDB_PREFIX + basename)), basename
def move_file(self, source, dest_folder): """Move a file to a new destination. Will create destination if it does not exist. Example: success = move_file(a, b) :type source: str # TODO: Check p. :param source: the source path (absolute) :type dest_folder: str :param dest_folder: the destination path (absolute) :rtype: bool :return: True if (at least one) file was moved successfully, False otherwise. """ if isinstance(source, unicode): source = source.encode("utf-8") paths = self.unstack(source) success = [] dest_folder = xbmc.makeLegalFilename(dest_folder) if self.is_excluded(paths[0]): debug("Detected a file on an excluded path. Aborting.") return False 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 False new_path = os.path.join(dest_folder, os.path.basename(p)) 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() success.append(bool(xbmcvfs.delete(new_path) and xbmcvfs.rename(p, new_path))) else: debug("This file isn't larger than the existing file. Deleting it instead of moving.") existing_file.close() file_to_move.close() success.append(bool(xbmcvfs.delete(p))) else: debug("Moving %r to %r." % (p, new_path)) success.append(bool(xbmcvfs.rename(p, new_path))) else: debug("File %r no longer exists." % p, xbmc.LOGWARNING) success.append(False) return any(success)
def install_skin(self, name, url): from resources.libs.downloader import Downloader from resources.libs import db from resources.libs import extract from resources.libs.common import logging from resources.libs import skin from resources.libs.common import tools progress_dialog = xbmcgui.DialogProgress() response = tools.open_url(url, check=False) if not response: logging.log_notify( "[COLOR {0}]Instalador de Add-ons[/COLOR]".format( CONFIG.COLOR1), '[COLOR {0}]{1}:[/COLOR] [COLOR {2}]Url del Zip Inválida![/COLOR]' .format(CONFIG.COLOR1, name, CONFIG.COLOR2)) return if not os.path.exists(CONFIG.PACKAGES): os.makedirs(CONFIG.PACKAGES) progress_dialog.create( CONFIG.ADDONTITLE, '[COLOR {0}][B]Descargando:[/B][/COLOR] [COLOR {1}]{2}[/COLOR]'. format(CONFIG.COLOR2, CONFIG.COLOR1, name) + '\n' + '' + '\n' + '[COLOR {0}]Espere por Favor[/COLOR]'.format(CONFIG.COLOR2)) urlsplits = url.split('/') lib = xbmc.makeLegalFilename( os.path.join(CONFIG.PACKAGES, urlsplits[-1])) try: os.remove(lib) except: pass Downloader().download(url, lib) title = '[COLOR {0}][B]Instalando:[/B][/COLOR] [COLOR {1}]{2}[/COLOR]'.format( CONFIG.COLOR2, CONFIG.COLOR1, name) progress_dialog.update( 0, title + '\n' + '' + '\n' + '[COLOR {0}]Espere por Favor[/COLOR]'.format(CONFIG.COLOR2)) percent, errors, error = extract.all(lib, CONFIG.HOME, title=title) installed = db.grab_addons(lib) db.addon_database(installed, 1, True) progress_dialog.close() logging.log_notify( "[COLOR {0}]Instalador de Add-ons[/COLOR]".format(CONFIG.COLOR1), '[COLOR {0}]{1}: Instalado![/COLOR]'.format(CONFIG.COLOR2, name)) xbmc.executebuiltin('UpdateAddonRepos()') xbmc.executebuiltin('UpdateLocalAddons()') for item in installed: if item.startswith('skin.') and not item == 'skin.shortcuts': if not CONFIG.BUILDNAME == '' and CONFIG.DEFAULTIGNORE == 'true': CONFIG.set_setting('defaultskinignore', 'true') skin.switch_to_skin(item, 'Skin Installer') xbmc.executebuiltin('Container.Refresh()')
def download_media(url, path, file_name): try: progress = int(kodi.get_setting('down_progress')) active = not progress == PROGRESS.OFF background = progress == PROGRESS.BACKGROUND with kodi.ProgressDialog('Premiumize Cloud', i18n('downloading') % (file_name), background=background, active=active) as pd: request = urllib2.Request(url) request.add_header('User-Agent', USER_AGENT) request.add_unredirected_header('Host', request.get_host()) response = urllib2.urlopen(request) content_length = 0 if 'Content-Length' in response.info(): content_length = int(response.info()['Content-Length']) file_name = file_name.replace('.strm', get_extension(url, response)) full_path = os.path.join(path, file_name) log_utils.log('Downloading: %s -> %s' % (url, full_path), log_utils.LOGDEBUG) path = xbmc.makeLegalFilename(path) try: try: xbmcvfs.mkdirs(path) except: os.makedirs(path) except Exception as e: log_utils.log('Dir Create Failed: %s' % (e), log_utils.LOGDEBUG) if not xbmcvfs.exists(path): raise Exception(i18n('failed_create_dir')) file_desc = xbmcvfs.File(full_path, 'w') total_len = 0 cancel = False while True: data = response.read(CHUNK_SIZE) if not data: break if pd.is_canceled(): cancel = True break total_len += len(data) if not file_desc.write(data): raise Exception(i18n('failed_write_file')) percent_progress = (total_len) * 100 / content_length if content_length > 0 else 0 log_utils.log('Position : %s / %s = %s%%' % (total_len, content_length, percent_progress), log_utils.LOGDEBUG) pd.update(percent_progress) file_desc.close() if not cancel: kodi.notify(msg=i18n('download_complete') % (file_name), duration=5000) log_utils.log('Download Complete: %s -> %s' % (url, full_path), log_utils.LOGDEBUG) except Exception as e: log_utils.log('Error (%s) during download: %s -> %s' % (str(e), url, file_name), log_utils.LOGERROR) kodi.notify(msg=i18n('download_error') % (str(e), file_name), duration=5000)
def getStreamsPodcast(self, directory, category): debug("> getStreamsPodcast() directory=%s category=%s" %(directory,category)) self.streamDetails = [] feedElementDict = {'description':[],'pubDate':[],'link':[],'itunes:duration':[]} try: url = self.categoriesDict[self.source][directory][category] except: messageOK(__language__(402),__language__(300),category) else: dialogProgress.create(__language__(403), __language__(407), directory, category) doc = fetchURL(url) if doc: try: # station code, url, title, img src regex = 'cell_(\w+).*?<h3><a href="(.*?)">(.*?)</.*?img src="(.*?)"' matches = parseDocList(doc, regex, 'results_cells', 'begin footer') for match in matches: station = match[0] link = match[1] if link[-1] == '/': link = link[:-1] prog = link.split('/')[-1] # eg /radio/podcasts/dancehall -> dancehall rssLink = self.URL_PODCAST.replace('$STATION', station).replace('$PROG',prog) title = cleanHTML(decodeEntities(match[2])) imgURL = match[3] fn = "%s_%s%s" % (station,prog,imgURL[-4:]) imgFilename = os.path.join(DIR_USERDATA, xbmc.makeLegalFilename(fn)) success = self.rssparser.feed(url=rssLink) if success: rssItems = self.rssparser.parse("item", feedElementDict) for rssItem in rssItems: longDesc = rssItem.getElement('description') showDate = rssItem.getElement('pubDate') shortDate = searchRegEx(showDate, '((.*?\d\d\d\d))') # Thu, 20 Mar 2008 mediaURL = rssItem.getElement('link') duration = "%smins" % searchRegEx(rssItem.getElement('itunes:duration'), '(\d+)') shortDesc = longDesc[:40] self.streamDetails.append([title,mediaURL,imgURL,imgFilename,station,shortDesc,duration,shortDate,longDesc]) if DEBUG: print self.streamDetails[-1] # get thumb icons if self.streamDetails: self.getIcons() except: print "bad scrape" dialogProgress.close() if not self.streamDetails: messageOK(__language__(301), directory, category ) debug("streamDetails=%s" % self.streamDetails) success = (self.streamDetails != []) debug("< getStreamsPodcast() success="+str(success)) return success
def listDirFiles(self, r_path): """ List the files of a directory @param path: path of directory we want to list the content of """ path = xbmc.makeLegalFilename(r_path) print "listDirFiles: Liste le repertoire: %s" % path dirList = os.listdir(str(path)) return dirList
def write_file(path, content): try: path = xbmc.makeLegalFilename(path) if not isinstance(content, basestring): content = str(content) file = control.openFile(path, 'w') file.write(str(content)) file.close() except Exception as e: pass
def write_file2(path): content = None try: path = xbmc.makeLegalFilename(path) file = control.openFile(path, 'r') content = file.read() file.close() except Exception as e: pass return content
def downloadfile(url,nombrefichero): logger.info("[downloadtools.py] downloadfile: url="+url) logger.info("[downloadtools.py] downloadfile: nombrefichero="+nombrefichero) # antes #f=open(nombrefichero,"wb") try: import xbmc nombrefichero = xbmc.makeLegalFilename(nombrefichero) except: pass logger.info("[downloadtools.py] downloadfile: nombrefichero="+nombrefichero) # despues if os.path.exists(nombrefichero): f = open(nombrefichero, 'r+b') existSize = os.path.getsize(nombrefichero) logger.info("[downloadtools.py] downloadfile: el fichero existe, size=%d" % existSize) grabado = existSize f.seek(existSize) else: existSize = 0 logger.info("[downloadtools.py] downloadfile: el fichero no existe") f = open(nombrefichero, 'wb') grabado = 0 # Crea el diálogo de progreso import xbmcgui progreso = xbmcgui.DialogProgress() progreso.create( config.getPluginId() , "Descargando vídeo..." , url , nombrefichero ) # Timeout del socket a 60 segundos socket.setdefaulttimeout(10) h=urllib2.HTTPHandler(debuglevel=0) request = urllib2.Request(url) if existSize > 0: request.add_header('Range', 'bytes=%d-' % (existSize, )) opener = urllib2.build_opener(h) urllib2.install_opener(opener) try: connexion = opener.open(request) except urllib2.HTTPError,e: logger.info("[downloadtools.py] downloadfile: error %d (%s) al abrir la url %s" % (e.code,e.msg,url)) #print e.code #print e.msg #print e.hdrs #print e.fp f.close() progreso.close() # El error 416 es que el rango pedido es mayor que el fichero => es que ya está completo if e.code==416: return 0 else: return -2
def install_addon_pack(self, name, url): from resources.libs.downloader import Downloader from resources.libs import db from resources.libs import extract from resources.libs.common import logging from resources.libs.common import tools if 64 - 64: o00ooo0 / OoOoOO00 - O0 - I11i O0oOoOOOoOO = xbmcgui.DialogProgress() if 38 - 38: I1i1iI1i oo0Ooo0 = tools.open_url(url, check=True) if 7 - 7: O0.o0OO0 % I1ii11iIi11i - I1IiiI - iIii1I11I1II1 if not oo0Ooo0: logging.log_notify( "[COLOR {0}]Addon Installer[/COLOR]".format(CONFIG.COLOR1), '[COLOR {0}]{1}:[/COLOR] [COLOR {2}]Invalid Zip Url![/COLOR]'. format(CONFIG.COLOR1, name, CONFIG.COLOR2)) return if 36 - 36: Oo0ooO0oo0oO % o00ooo0 % Oo0Ooo - I1ii11iIi11i if not os.path.exists(CONFIG.PACKAGES): os.makedirs(CONFIG.PACKAGES) if 22 - 22: iIii1I11I1II1 / Oo0Ooo * I1ii11iIi11i % o0OO0 O0oOoOOOoOO.create( CONFIG.ADDONTITLE, '[COLOR {0}][B]Baixando:[/B][/COLOR] [COLOR {1}]{2}[/COLOR]'. format(CONFIG.COLOR2, CONFIG.COLOR1, name) + '\n' + '' + '\n' + '[COLOR {0}]Por favor, aguarde[/COLOR]'.format(CONFIG.COLOR2)) Ii11Ii1I = url.split('/') O00oO = xbmc.makeLegalFilename( os.path.join(CONFIG.PACKAGES, Ii11Ii1I[-1])) try: os.remove(O00oO) except: pass Downloader().download(url, O00oO) I1 = '[COLOR {0}][B]Baixando:[/B][/COLOR] [COLOR {1}]{2}[/COLOR]'.format( CONFIG.COLOR2, CONFIG.COLOR1, name) O0oOoOOOoOO.update( 0, I1 + '\n' + '' + '\n' + '[COLOR {0}]Por favor, aguarde[/COLOR]'.format(CONFIG.COLOR2)) OO00Oo, O0OOO0OOoO0O, O00Oo000ooO0 = extract.all(O00oO, CONFIG.ADDONS, title=I1) IiiIII111iI = db.grab_addons(O00oO) db.addon_database(IiiIII111iI, 1, True) O0oOoOOOoOO.close() logging.log_notify( "[COLOR {0}]Addon Installer[/COLOR]".format(CONFIG.COLOR1), '[COLOR {0}]{1}: Instalado![/COLOR]'.format(CONFIG.COLOR2, name)) xbmc.executebuiltin('UpdateAddonRepos()') xbmc.executebuiltin('UpdateLocalAddons()') xbmc.executebuiltin('Container.Refresh()') if 85 - 85: oO0o % i11iIiiIii - o0OO0 * OoooooooOO / I1IiiI % I1IiiI if 1 - 1: OoO0O00 - oO0o.I11i.OoO0O00 / Oo0Ooo + I11i
def update_kodi_library(self, data=None): # pylint: disable=unused-argument # Update only the elements in the addon export folder for faster processing with a large library (on Kodi 18.x) # If a scan is already in progress, the scan is delayed until onScanFinished event if not self.scan_in_progress: common.debug('Kodi library update requested from library auto-update') self.scan_awaiting = False common.scan_library( xbmc.makeLegalFilename( xbmc.translatePath( kodi_library.library_path()))) else: self.scan_awaiting = True
def update_kodi_library(self, data=None): # Update only the elements in the addon export folder # for faster processing with a large library. # If a scan is already in progress, the scan is delayed until onScanFinished event common.debug('Library update requested for library updater service') if not self.scan_in_progress: self.scan_awaiting = False common.scan_library( xbmc.makeLegalFilename( xbmc.translatePath(library.library_path()))) else: self.scan_awaiting = True