def __downloadCover__(conf, album): if album == None: return path = __getAlbumPath__(conf, album) + '/cover.jpg' url = API.getCoverUrl(album.cover, "1280", "1280") if url is not None: downloadFile(url, path)
def downloadTrack(self, track_id=None): while_count = 9999 while while_count > 0: while_count -= 1 if track_id is not None: while_count = 0 sID = track_id else: print("----------------TRACK------------------") sID = printChoice("Enter TrackID(Enter '0' go back):", True, 0) if sID == 0: return aTrackInfo = self.tool.getTrack(sID) if self.tool.errmsg != "": printErr(0,"Get TrackInfo Err! " + self.tool.errmsg) return aAlbumInfo = self.tool.getAlbum(aTrackInfo['album']['id']) if self.tool.errmsg != "": printErr(0,"Get TrackInfo Err! " + self.tool.errmsg) return # t = self.tool.getTrackContributors(sID) print("[AlbumTitle ] %s" % (aAlbumInfo['title'])) print("[TrackTitle ] %s" % (aTrackInfo['title'])) print("[Duration ] %s" % (aTrackInfo['duration'])) print("[TrackNumber] %s" % (aTrackInfo['trackNumber'])) print("[Version ] %s\n" % (aTrackInfo['version'])) # Creat OutputDir targetDir = self.__creatAlbumDir(aAlbumInfo) # download cover coverPath = targetDir + '/' + pathHelper.replaceLimitChar(aAlbumInfo['title'], '-') + '.jpg' coverUrl = self.tool.getAlbumArtworkUrl(aAlbumInfo['cover']) netHelper.downloadFile(coverUrl, coverPath) # download streamInfo = self.tool.getStreamUrl(sID, self.config.quality) if self.tool.errmsg != "": printErr(14, aTrackInfo['title'] + "(Get Stream Url Err!" + self.tool.errmsg + ")") continue fileType = self._getSongExtension(streamInfo['url']) filePath = self.__getAlbumSongSavePath(targetDir, aAlbumInfo, aTrackInfo, fileType) # filePath = targetDir + "/" + pathHelper.replaceLimitChar(aTrackInfo['title'],'-') + fileType paraList = {'album':aAlbumInfo, 'title': aTrackInfo['title'], 'trackinfo':aTrackInfo, 'url': streamInfo['url'], 'path': filePath, 'retry': 3, 'key':streamInfo['encryptionKey'], 'coverpath': coverPath} self.thread.start(self.__thradfunc_dl, paraList) # wait all download thread self.thread.waitAll() self.tool.removeTmpFile(targetDir) return
def __thradfunc_dl(self, paraList): count = 1 printRet = True pstr = paraList['title'] + "(Download Err!)" redownload = True needDl = True bIsSuccess = False albumInfo = None index = None coverpath = None if 'redownload' in paraList: redownload = paraList['redownload'] if 'retry' in paraList: count = count + paraList['retry'] if 'show' in paraList: printRet = paraList['show'] if 'album' in paraList: albumInfo = paraList['album'] if 'index' in paraList: index = paraList['index'] if 'coverpath' in paraList: coverpath = paraList['coverpath'] if redownload is False: needDl = self.__isNeedDownload(paraList['path'], paraList['url']) if needDl: try: while count > 0: count = count - 1 check = netHelper.downloadFile(paraList['url'], paraList['path']) if check is True: if paraList['key'] == '': break key, nonce = decrypt_security_token(paraList['key']) decrypt_file(paraList['path'], key, nonce) break if check: self.tool.setTrackMetadata(paraList['trackinfo'], paraList['path'], albumInfo, index, coverpath) pstr = paraList['title'] bIsSuccess = True except: pass else: pstr = paraList['title'] bIsSuccess = True if printRet: if (bIsSuccess): printSUCCESS(14, pstr) else: printErr(14, pstr) return
def __threadfunc__(url, filepath, progress): retrycount = 3 try: while retrycount > 0: retrycount = retrycount - 1 check = netHelper.downloadFile(url, filepath, 30) if check: break except: pass progress.step()
def _downloadFiles(self): check = pathHelper.remove(self.tmpPath) check = pathHelper.mkdirs(self.tmpPath) if self.netVer.mainFile is None: return False if self.netVer.isZip == 0: plist = [] plist.append(self.netVer.mainFile) for item in self.netVer.elseFileList: plist.append(item) for item in plist: urlpath = self.netUrl + '//' + item topath = self.tmpPath + '\\' + item if netHelper.downloadFile(urlpath, topath) is False: return False else: urlpath = self.netUrl + '//' + self.netVer.zipFile topath = self.tmpPath + '\\' + self.netVer.zipFile if netHelper.downloadFile(urlpath, topath) is False: return False return zipHelper.unzip(topath, self.tmpPath) return True
def __thradfunc_dl(self, url, filepath, retrycount): check = False try: while retrycount > 0: retrycount = retrycount - 1 check = netHelper.downloadFile(url, filepath, 30) if check: break except: pass self.completeCount = self.completeCount + 1 if self.progress is not None: self.progress.step() return
def __downloadTrack__(conf: Settings, track, album=None, playlist=None): try: msg, stream = API.getStreamUrl(track.id, conf.audioQuality) if not isNull(msg) or stream is None: Printf.err(track.title + "." + msg) return path = __getTrackPath__(conf, track, stream, album, playlist) # check exist if conf.checkExist and __isNeedDownload__(path, stream.url) == False: playSong(track, path) Printf.success(getFileName(path) + " (skip:already exists!)") return # Printf.info("Download \"" + track.title + "\" Codec: " + stream.codec) if conf.multiThreadDownload: check, err = downloadFileMultiThread( stream.url, path + '.part', stimeout=20, showprogress=conf.showProgress) else: check, err = downloadFile(stream.url, path + '.part', stimeout=20, showprogress=conf.showProgress) if not check: Printf.err("Download failed! " + getFileName(path) + ' (' + str(err) + ')') return # encrypted -> decrypt and remove encrypted file if isNull(stream.encryptionKey): os.replace(path + '.part', path) else: key, nonce = decrypt_security_token(stream.encryptionKey) decrypt_file(path + '.part', path, key, nonce) os.remove(path + '.part') path = __convertToM4a__(path, stream.codec) # contributors contributors = API.getTrackContributors(track.id) __setMetaData__(track, album, path, contributors) # Printf.success(getFileName()) playSong(track, path) except Exception as e: Printf.err("Download failed! " + track.title + ' (' + str(e) + ')')
def downloadAlbum(self): while True: print("----------------ALBUM------------------") sID = printChoice("Enter AlbumID(Enter '0' go back):", True, 0) if sID == 0: return aAlbumInfo = self.tool.getAlbum(sID) if self.tool.errmsg != "": printErr(0, "Get AlbumInfo Err! " + self.tool.errmsg) continue print("[Title] %s" % (aAlbumInfo['title'])) print("[SongNum] %s\n" % (aAlbumInfo['numberOfTracks'])) # Get Tracks aAlbumTracks = self.tool.getAlbumTracks(sID) if self.tool.errmsg != "": printErr(0, "Get AlbumTracks Err!" + self.tool.errmsg) return # Creat OutputDir targetDir = self.__creatAlbumDir(aAlbumInfo) # write msg string = self.tool.convertAlbumInfoToString( aAlbumInfo, aAlbumTracks) with open(targetDir + "/AlbumInfo.txt", 'w', encoding='utf-8') as fd: fd.write(string) # download cover coverPath = targetDir + '/' + pathHelper.replaceLimitChar( aAlbumInfo['title'], '-') + '.jpg' coverUrl = self.tool.getAlbumArtworkUrl(aAlbumInfo['cover']) netHelper.downloadFile(coverUrl, coverPath) # check exist files redownload = True existFiles = pathHelper.getDirFiles(targetDir) for item in existFiles: if '.txt' in item: continue if '.jpg' in item: continue check = printChoice( "Some TrackFile Exist.Is Redownload?(y/n):") if check != 'y' and check != 'yes': redownload = False break # download album tracks for item in aAlbumTracks['items']: streamInfo = self.tool.getStreamUrl(str(item['id']), self.config.quality) if self.tool.errmsg != "": printErr( 14, item['title'] + "(Get Stream Url Err!" + self.tool.errmsg + ")") continue fileType = self._getSongExtension(streamInfo['url']) filePath = self.__getAlbumSongSavePath(targetDir, aAlbumInfo, item, fileType) paraList = { 'album': aAlbumInfo, 'redownload': redownload, 'title': item['title'], 'trackinfo': item, 'url': streamInfo['url'], 'path': filePath, 'retry': 3, 'key': streamInfo['encryptionKey'] } self.thread.start(self.__thradfunc_dl, paraList) # wait all download thread self.thread.waitAll() self.tool.removeTmpFile(targetDir) return
def __thradfunc_dl(self, paraList): count = 1 printRet = True pstr = paraList['title'] + "(Download Err!)" redownload = True needDl = True bIsSuccess = False albumInfo = None index = None coverpath = None if 'redownload' in paraList: redownload = paraList['redownload'] if 'retry' in paraList: count = count + paraList['retry'] if 'show' in paraList: printRet = paraList['show'] if 'album' in paraList: albumInfo = paraList['album'] if 'index' in paraList: index = paraList['index'] if 'coverpath' in paraList: coverpath = paraList['coverpath'] if redownload is False: needDl = self.__isNeedDownload(paraList['path'], paraList['url']) # DEBUG # self.tool.setTrackMetadata(paraList['trackinfo'], paraList['path'], albumInfo, index, coverpath) showprogress = False if int(self.config.threadnum) <= 1 and self.showpro: showprogress = True Contributors = self.tool.getTrackContributors( paraList['trackinfo']['id']) if needDl: try: while count > 0: count = count - 1 check = netHelper.downloadFile(paraList['url'], paraList['path'] + '.part', showprogress=showprogress, stimeout=20) if check is True: if paraList['key'] == '': # unencrypted -> just move into place os.replace(paraList['path'] + '.part', paraList['path']) break else: # encrypted -> decrypt and remove encrypted file key, nonce = decrypt_security_token( paraList['key']) decrypt_file(paraList['path'] + '.part', paraList['path'], key, nonce) os.remove(paraList['path'] + '.part') break if check: bIsSuccess = True paraList['path'] = self.tool.covertMp4toM4a( paraList['path']) self.tool.setTrackMetadata(paraList['trackinfo'], paraList['path'], albumInfo, index, coverpath, Contributors) pstr = paraList['title'] except Exception as e: printErr(14, str(e) + " while downloading " + paraList['url']) else: pstr = paraList['title'] bIsSuccess = True if printRet: if (bIsSuccess): printSUCCESS(14, pstr) else: printErr(14, pstr) return
def downloadPlaylist(self, playlist_id=None): while True: targetDir = self.config.outputdir + "/Playlist/" if playlist_id is None: print("--------------PLAYLIST-----------------") sID = printChoice("Enter PlayListID(Enter '0' go back):") if sID == '0': return else: sID = playlist_id aPlaylistInfo, aItemInfo = self.tool.getPlaylist(sID) if self.tool.errmsg != "": printErr(0, "Get PlaylistInfo Err! " + self.tool.errmsg) return print("[Title] %s" % (aPlaylistInfo['title'])) print("[Type] %s" % (aPlaylistInfo['type'])) print("[NumberOfTracks] %s" % (aPlaylistInfo['numberOfTracks'])) print("[NumberOfVideos] %s" % (aPlaylistInfo['numberOfVideos'])) print("[Duration] %s\n" % (aPlaylistInfo['duration'])) # Creat OutputDir targetDir = targetDir + pathHelper.replaceLimitChar( aPlaylistInfo['title'], '-') targetDir = os.path.abspath(targetDir).strip() pathHelper.mkdirs(targetDir) # write msg string = self.tool.convertPlaylistInfoToString( aPlaylistInfo, aItemInfo) with codecs.open(targetDir + "/PlaylistInfo.txt", 'w', 'utf-8') as fd: fd.write(string) # download cover coverPath = targetDir + '/' + pathHelper.replaceLimitChar( aPlaylistInfo['title'], '-') + '.jpg' coverUrl = self.tool.getPlaylistArtworkUrl(aPlaylistInfo['uuid']) check = netHelper.downloadFile(coverUrl, coverPath) # download track bBreakFlag = False bFirstTime = True errIndex = [] index = 0 while bBreakFlag is False: self.check.clear() index = 0 tmpcoverpath = [] for item in aItemInfo: type = item['type'] item = item['item'] if type != 'track': continue index = index + 1 if bFirstTime is False: if self.check.isInErr(index - 1, errIndex) == False: continue streamInfo = self.tool.getStreamUrl( str(item['id']), self.config.quality) # streamInfo = self.tool.getStreamUrl(str(item['id']), 'DOLBY_ATMOS') if self.tool.errmsg != "" or not streamInfo: printErr( 14, item['title'] + "(Get Stream Url Err!!" + self.tool.errmsg + ")") continue aAlbumInfo = self.tool.getAlbum(item['album']['id']) fileType = self._getSongExtension(streamInfo['url']) # change targetDir targetDir2 = targetDir if self.config.plfile2arfolder == "True": targetDir2 = self.__creatAlbumDir(aAlbumInfo) filePath = self.__getAlbumSongSavePath( targetDir2, aAlbumInfo, item, fileType) paraList = { 'album': aAlbumInfo, 'title': item['title'], 'trackinfo': item, 'url': streamInfo['url'], 'path': filePath, 'retry': 3, 'key': streamInfo['encryptionKey'] } else: seq = self.tool.getIndexStr(index, len(aItemInfo)) filePath = targetDir2 + '/' + seq + " " + pathHelper.replaceLimitChar( item['title'], '-') + fileType paraList = { 'album': aAlbumInfo, 'index': index, 'title': item['title'], 'trackinfo': item, 'url': streamInfo['url'], 'path': filePath, 'retry': 3, 'key': streamInfo['encryptionKey'] } try: coverPath = targetDir2 + '/' + pathHelper.replaceLimitChar( aAlbumInfo['title'], '-') + '.jpg' coverUrl = self.tool.getAlbumArtworkUrl( aAlbumInfo['cover']) netHelper.downloadFile(coverUrl, coverPath) paraList['coverpath'] = coverPath tmpcoverpath.append(coverPath) except: cmdHelper.myprint( "Could not download artwork for '{}'".format( item['title']), cmdHelper.TextColor.Red, None) if self.config.onlym4a == "True": self.check.addPath(filePath.replace(".mp4", ".m4a")) else: self.check.addPath(filePath) self.thread.start(self.__thradfunc_dl, paraList) self.thread.waitAll() self.tool.removeTmpFile(targetDir) # remove cover if self.config.savephoto != 'True': for item in tmpcoverpath: pathHelper.remove(item) bBreakFlag = True bFirstTime = False # check isErr, errIndex = self.check.checkPaths() if isErr: check = printChoice( "[Err]\t\t" + str(len(errIndex)) + " Tracks Download Failed.Try Again?(y/n):") if check == 'y' or check == 'Y': bBreakFlag = False # download video for item in aItemInfo: type = item['type'] item = item['item'] if type != 'video': continue filePath = targetDir + '/' + pathHelper.replaceLimitChar( item['title'], '-') + ".mp4" filePath = os.path.abspath(filePath) if os.access(filePath, 0): os.remove(filePath) videoID = item['id'] resolutionList, urlList = self.tool.getVideoResolutionList( videoID) if urlList is None: printErr(14, item['title'] + '(' + self.tool.errmsg + ')') else: selectIndex = self.__getVideoResolutionIndex( resolutionList) if self.ffmpeg.mergerByM3u8_Multithreading2( urlList[int(selectIndex)], filePath, showprogress=self.showpro): printSUCCESS(14, item['title']) else: printErr(14, item['title'] + "(Download Or Merger Err!)") if playlist_id is not None: return return
def downloadAlbum(self, album_id=None, redl_flag=None): while_count = 9999 while while_count > 0: while_count -= 1 if album_id is not None: while_count = 0 sID = album_id else: print("----------------ALBUM------------------") sID = printChoice("Enter AlbumID(Enter '0' go back):", True, 0) if sID == 0: return aAlbumInfo = self.tool.getAlbum(sID) if self.tool.errmsg != "": printErr(0, "Get AlbumInfo Err! " + self.tool.errmsg) continue print("[Title] %s" % (aAlbumInfo['title'])) print("[SongNum] %s\n" % (aAlbumInfo['numberOfTracks'])) # Get Tracks aAlbumTracks = self.tool.getAlbumTracks(sID) if self.tool.errmsg != "": printErr(0, "Get AlbumTracks Err!" + self.tool.errmsg) continue aAlbumVideos = self.tool.getAlbumVideos(sID) # Creat OutputDir targetDir = self.__creatAlbumDir(aAlbumInfo) # write msg string = self.tool.convertAlbumInfoToString( aAlbumInfo, aAlbumTracks) with codecs.open(targetDir + "/AlbumInfo.txt", 'w', 'utf-8') as fd: fd.write(string) # download cover coverPath = targetDir + '/' + pathHelper.replaceLimitChar( aAlbumInfo['title'], '-') + '.jpg' if aAlbumInfo['cover'] is not None: coverUrl = self.tool.getAlbumArtworkUrl(aAlbumInfo['cover']) netHelper.downloadFile(coverUrl, coverPath) # check exist files redownload = True if redl_flag is None: existFiles = pathHelper.getDirFiles(targetDir) for item in existFiles: if '.txt' in item: continue if '.jpg' in item: continue check = printChoice( "Some tracks already exist. Redownload?(y/n):") if not cmdHelper.isInputYes(check): redownload = False break else: redownload = redl_flag # download album tracks for item in aAlbumTracks['items']: streamInfo = self.tool.getStreamUrl(str(item['id']), self.config.quality) if self.tool.errmsg != "" or not streamInfo: printErr( 14, item['title'] + "(Get Stream Url Err!" + self.tool.errmsg + ")") continue fileType = self._getSongExtension(streamInfo['url']) filePath = self.__getAlbumSongSavePath(targetDir, aAlbumInfo, item, fileType) paraList = { 'album': aAlbumInfo, 'redownload': redownload, 'title': item['title'], 'trackinfo': item, 'url': streamInfo['url'], 'path': filePath, 'retry': 3, 'key': streamInfo['encryptionKey'], 'coverpath': coverPath } self.thread.start(self.__thradfunc_dl, paraList) # wait all download thread self.thread.waitAll() self.tool.removeTmpFile(targetDir) # remove cover if self.config.savephoto != 'True': pathHelper.remove(coverPath) # download video for item in aAlbumVideos: item = item['item'] filePath = targetDir + '/' + pathHelper.replaceLimitChar( item['title'], '-') + ".mp4" filePath = os.path.abspath(filePath) if os.access(filePath, 0): os.remove(filePath) try: resolutionList, urlList = self.tool.getVideoResolutionList( item['id']) selectIndex = self.__getVideoResolutionIndex( resolutionList) if self.ffmpeg.mergerByM3u8_Multithreading2( urlList[int(selectIndex)], filePath, showprogress=self.showpro): printSUCCESS(14, item['title']) else: printErr(14, item['title']) except: printErr(14, item['title']) # return return
def downloadPlaylist(self): while True: targetDir = self.config.outputdir + "/Playlist/" print("--------------PLAYLIST-----------------") sID = printChoice("Enter PlayListID(Enter '0' go back):") if sID == '0': return aPlaylistInfo, aItemInfo = self.tool.getPlaylist(sID) if self.tool.errmsg != "": printErr(0, "Get PlaylistInfo Err! " + self.tool.errmsg) return print("[Title] %s" % (aPlaylistInfo['title'])) print("[Type] %s" % (aPlaylistInfo['type'])) print("[NumberOfTracks] %s" % (aPlaylistInfo['numberOfTracks'])) print("[NumberOfVideos] %s" % (aPlaylistInfo['numberOfVideos'])) print("[Duration] %s\n" % (aPlaylistInfo['duration'])) # Creat OutputDir targetDir = targetDir + pathHelper.replaceLimitChar( aPlaylistInfo['title'], '-') targetDir = os.path.abspath(targetDir) pathHelper.mkdirs(targetDir) # write msg string = self.tool.convertPlaylistInfoToString( aPlaylistInfo, aItemInfo) with open(targetDir + "/PlaylistInfo.txt", 'w', encoding='utf-8') as fd: fd.write(string) # download cover coverPath = targetDir + '/' + pathHelper.replaceLimitChar( aPlaylistInfo['title'], '-') + '.jpg' coverUrl = self.tool.getPlaylistArtworkUrl(aPlaylistInfo['uuid']) check = netHelper.downloadFile(coverUrl, coverPath) # download track bBreakFlag = False bFirstTime = True errIndex = [] index = 0 while bBreakFlag is False: self.check.clear() index = 0 for item in aItemInfo: type = item['type'] item = item['item'] if type != 'track': continue index = index + 1 if bFirstTime is False: if self.check.isInErr(index - 1, errIndex) == False: continue streamInfo = self.tool.getStreamUrl( str(item['id']), self.config.quality) if self.tool.errmsg != "": printErr( 14, item['title'] + "(Get Stream Url Err!!" + self.tool.errmsg + ")") continue fileType = self._getSongExtension(streamInfo['url']) filePath = targetDir + '/' + pathHelper.replaceLimitChar( item['title'], '-') + fileType paraList = { 'index': index, 'title': item['title'], 'trackinfo': item, 'url': streamInfo['url'], 'path': filePath, 'retry': 3, 'key': streamInfo['encryptionKey'] } self.check.addPath(filePath) if not os.path.isfile(filePath): self.thread.start(self.__thradfunc_dl, paraList) self.thread.waitAll() self.tool.removeTmpFile(targetDir) bBreakFlag = True bFirstTime = False # check isErr, errIndex = self.check.checkPaths() if isErr: check = printChoice( "[Err]\t\t" + len(errIndex) + " Tracks Download Failed.Try Again?(y/n):") if check == 'y' or check == 'Y': bBreakFlag = False # download video for item in aItemInfo: type = item['type'] item = item['item'] if type != 'video': continue filePath = targetDir + '/' + pathHelper.replaceLimitChar( item['title'], '-') + ".mp4" filePath = os.path.abspath(filePath) if os.access(filePath, 0): os.remove(filePath) videoID = item['id'] resolutionList, urlList = self.tool.getVideoResolutionList( videoID) if urlList is None: printErr(14, item['title'] + '(' + self.tool.errmsg + ')') else: selectIndex = self.__getVideoResolutionIndex( resolutionList) if self.ffmpeg.mergerByM3u8_Multithreading( urlList[selectIndex], filePath, showprogress=False): printSUCCESS(14, item['title']) else: printErr(14, item['title'] + "(Download Or Merger Err!)") return
# -*- coding: utf-8 -*- from colorama import init import socks import requests import sys import os import time sys.path.append('./') import aigpy.zipHelper as zipHelper import aigpy.netHelper as netHelper from aigpy.updateHelper import updateTool import aigpy.ffmpegHelper as ffmpegHelper from aigpy.serverHelper import ServerTool if __name__ == '__main__': os.system("pip install aigpy --upgrade") bo = netHelper.downloadFile('http://down.2zzt.com/uploads/cu/cu2.3.zip', 'e:\\1.zip', showprogress=True) init(autoreset=True) print("\033[0;30;40m\tHello World\033[0m") # 黑色 print("\033[0;31;40m\tHello World\033[0m") # 红色 print("\033[0;32;40m\tHello World\033[0m") # 绿色 print("\033[0;33;40m\tHello World\033[0m") # 黄色 print("\033[0;34;40m\tHello World\033[0m") # 蓝色 print("\033[0;35;40m\tHello World\033[0m") # 紫色 print("\033[0;36;40m\tHello World\033[0m") # 浅蓝 print("\033[0;37;40m\tHello World\033[0m") # 白色
def _getNetVerinfo(self): tmpFile = self.curPath + '\\' + 'aigpy-tmp.ini' if not netHelper.downloadFile(self.netUrl + '//' + self.verName, tmpFile): return False return self.netVer.readFile(tmpFile)