コード例 #1
0
    def setTag(self, tag, srcfile, coverpath=None):
        path = pathHelper.getDirName(srcfile)
        name = pathHelper.getFileNameWithoutExtension(srcfile)
        ext = pathHelper.getFileExtension(srcfile)
        oext = ext

        if 'm4a' in ext or 'mp4' in ext:
            oext = '.mp3'
        if 'mp3' not in oext:
            coverpath = None
        tmpfile = path + '/' + 'TMP' + name + oext

        try:
            data = AudioSegment.from_file(srcfile, format=ext[1:])
            check = data.export(tmpfile,
                                format=oext[1:],
                                tags=tag,
                                cover=coverpath)
            check.close()
        except Exception as e:
            pathHelper.remove(tmpfile)
            return

        if fileHelper.getFileSize(tmpfile) > 0:
            pathHelper.remove(srcfile)
            os.rename(tmpfile, path + '/' + name + oext)
        else:
            pathHelper.remove(tmpfile)
コード例 #2
0
 def setTrackMetadata(self, track_info, file_path, album_info, index):
     path = pathHelper.getDirName(file_path)
     name = pathHelper.getFileNameWithoutExtension(file_path)
     exte = pathHelper.getFileExtension(file_path)
     tmpfile = path + '/' + self.tmpfileFlag + name + exte
     try:
         tag = {
             'Artist': track_info['artist']['name'],
             'Album': track_info['album']['title'],
             'Title': track_info['title'],
             'CopyRight': track_info['copyright'],
             'Track': track_info['trackNumber']
         }
         if index is not None:
             tag['Track'] = str(index)
         if album_info is not None:
             tag['Date'] = album_info['releaseDate']
             tag['Year'] = album_info['releaseDate'].split('-')[0]
         # tmp file
         pathHelper.copyFile(file_path, tmpfile)
         # set metadata
         ext = os.path.splitext(tmpfile)[1][1:]
         data = AudioSegment.from_file(tmpfile, ext)
         check = data.export(tmpfile, format=ext, tags=tag)
         # check file size
         if fileHelper.getFileSize(tmpfile) > 0:
             pathHelper.remove(file_path)
             pathHelper.copyFile(tmpfile, file_path)
     except:
         pass
     if os.access(tmpfile, 0):
         pathHelper.remove(tmpfile)
コード例 #3
0
def download(url, descpath, threadnum=15):
    '''Download file by m3u8-url'''
    try:
        urllist = paresUrl(url)
        if len(urllist) <= 0:
            return False

        threads = ThreadTool(threadnum)

        # Creat tmpdir
        path = getDirName(descpath)
        tmpPath = getDiffTmpPathName(path)
        if mkdirs(tmpPath) is False:
            return False

        # Progress
        progress = ProgressTool(len(urllist), 20)

        # Download files
        files = []
        for i, item in enumerate(urllist):
            filepath = tmpPath + '/' + str(i) + '.ts'
            files.append(filepath)
            threads.start(__threadfunc__, item, filepath, progress)
        threads.waitAll()

        # merger
        __merger__(files, descpath)
        shutil.rmtree(tmpPath)
        threads.close()
        return True
    except:
        shutil.rmtree(tmpPath)
        return False
コード例 #4
0
def downloadFile(url: str,
                 fileName: str,
                 stimeout=3.05,
                 showProgress: bool = False,
                 append: bool = False):
    try:
        response = urlopen(url, timeout=stimeout)

        totalSize = response.length
        fileSize, unit = unitFix(totalSize, Unit.BYTE, Unit.MB)
        if showProgress:
            progress = ProgressTool(fileSize, 15, unit=unit.name)

        # mkdir
        path = getDirName(fileName)
        mkdirs(path)

        curcount = 0
        chunksize = 16 * 1024
        mode = 'wb' if not append else 'ab'
        with open(fileName, mode) as f:
            while True:
                chunk = response.read(chunksize)
                curcount += len(chunk)
                if showProgress:
                    progress.setCurCount(convert(curcount, Unit.BYTE, unit))
                f.write(chunk)
                if curcount >= totalSize:
                    break
            return True, None
    except Exception as e:
        return False, e
コード例 #5
0
    def mergerByFiles(self, srcfilepaths, filepath, showshell=False):
        """
        #Func    :   合并文件       
        #Param   :   srcfilepaths   [in] 文件名数组     
        #Param   :   filepath       [in] 目标文件名     
        #Param   :   showshell      [in] 是否显示cmd信息        
        #Return  :   True/False 
        """
        filepath = os.path.abspath(filepath)
        res = -1
        tmpfile = filepath + "TMP.txt"
        paths = srcfilepaths
        group = None
        groupnum = 50
        try:
            # 先分组合并,再一起合并
            if len(srcfilepaths) > groupnum:
                dirName = pathHelper.getDirName(filepath)
                group = pathHelper.getDiffTmpPathName(dirName)
                if pathHelper.mkdirs(group) is False:
                    return False

                newPaths = []
                array = [
                    srcfilepaths[i:i + groupnum]
                    for i in range(0, len(srcfilepaths), groupnum)
                ]
                for index, item in enumerate(array):
                    file = group + '/' + str(index) + ".mp4"
                    newPaths.append(file)
                    if self.mergerByFiles(item, file, showshell) is False:
                        return False
                paths = newPaths

            # 创建临时文件,将要合并的文件名列表写入
            with open(tmpfile, 'w') as fd:
                for item in paths:
                    item = os.path.abspath(item)
                    fd.write('file \'' + item + '\'\n')

            # 调用ffmpeg进行合并
            cmd = "ffmpeg -f concat -safe 0 -i \"" + tmpfile + "\" -c copy \"" + filepath + "\""
            res = self.__process(cmd, 3, showshell, filepath)
        except:
            pass

        if os.access(tmpfile, 0):
            os.remove(tmpfile)
        if group is not None:
            shutil.rmtree(group)
        return res
コード例 #6
0
ファイル: fileHelper.py プロジェクト: AIGMix/AIGPY
def createEmptyFile(filePath: str, size: int):
    try:
        # Create dir
        path = getDirName(filePath)
        if mkdirs(path) is False:
            return False

        # Create empty file
        fp = open(filePath, "wb")
        fp.truncate(size)
        fp.close()
        return True
    except:
        return False
コード例 #7
0
    def mergerByM3u8_Multithreading(self,
                                    url,
                                    filepath,
                                    showprogress=False,
                                    showshell=False):
        """
        #Func    :   多线程下载并合并文件(使用M3u8的url)        
        #Param   :   url             [in] 链接
        #Param   :   filepath        [in] 目标文件名
        #Param   :   showprogress    [in] 是否显示进度条
        #Param   :   showshell       [in] 是否显示cmd信息
        #Return  :   True/False
        """
        try:
            # Get urllist
            urllist = self.__parseM3u8(url)
            if len(urllist) <= 0:
                return False

            # Creat tmpdir
            path = pathHelper.getDirName(filepath)
            tmpPath = pathHelper.getDiffTmpPathName(path)
            if pathHelper.mkdirs(tmpPath) is False:
                return False

            # Progress
            self.progress = None
            if showprogress:
                self.progress = ProgressTool(len(urllist))

            # Download files
            allpath = []
            self.waitCount = len(urllist)
            self.completeCount = 0
            for i, item in enumerate(urllist):
                index = i + 100001
                path = tmpPath + '/' + str(index) + ".ts"
                path = os.path.abspath(path)
                allpath.append(path)
                if os.path.exists(path):
                    os.remove(path)
                self.thread.start(self.__thradfunc_dl, item, path, 3)
            self.thread.waitAll()
            ret = self.mergerByTs(tmpPath, filepath, showshell)
            # ret = self.mergerByFiles(allpath, filepath, showshell)
            shutil.rmtree(tmpPath)
            return ret
        except:
            return False
コード例 #8
0
    def mergerByM3u8_Multithreading2(self, url, filepath, showprogress=False, showshell=False):
        try:
            # Get urllist
            urllist = self.__parseM3u8(url)
            if len(urllist) <= 0:
                return False

            sdir = pathHelper.getDirName(filepath)
            pathHelper.mkdirs(sdir)

            ext    = pathHelper.getFileExtension(filepath)
            tspath = filepath.replace(ext, '.ts')
            pathHelper.remove(tspath)
            if not netHelper.downloadFileByUrls(urllist, tspath, 30, True):
                return False
            if self.covertFile(tspath, filepath):
                pathHelper.remove(tspath)
                return True
            return False
        except:
            return False