예제 #1
0
def ncm_converter(ncm_path, mp3_path):
    logging.info("Converting %s -> %s", ncm_path, mp3_path)
    try:
        dump(ncm_path, mp3_path, False)
    except Exception:
        err = traceback.format_exc()
        logging.error("Convert failed for %s -> %s \n%s\n", ncm_path, mp3_path,
                      err)
        return err
예제 #2
0
 def dumper(self):
     files,fileType = QFileDialog.getOpenFileNames(self,
                                                   "请选择ncm文件",
                                                   "./",
                                                   "NeteaseCloudMusic Files (*.ncm)")
     if files:
         outputPath = QFileDialog.getExistingDirectory(self,
                                                       '请选择输出文件夹',
                                                       '/'.join(files[0].split('/')[:-1])) # 初始输出文件夹为第一个ncm文件所在目录
         if outputPath:
             self.dumpingdialog.show()
             filesTotal, filesDumped = len(files), 0
             self.dumpingdialog.ui.label.setText(f'转换中\n{filesDumped}/{filesTotal}')
             for file in files:
                 dump(file,outputPath+'/'+file.split('/')[-1][:-3]+'mp3')
                 filesDumped += 1
                 self.dumpingdialog.ui.label.setText(f'转换中\n{filesDumped}/{filesTotal}')
             self.dumpingdialog.setWindowTitle('转换完毕!')
             self.dumpingdialog.ui.label.setText('转换完毕!')
예제 #3
0
def ncm_converter(ncm_path: "str") -> "dict":
    ncm = pathlib.Path(ncm_path)
    tmp_name = ncm.with_suffix(".temp")
    logging.info("Converting %s -> %s", ncm_path, tmp_name)
    status = {"status": False, "filepath": None, "message": None}
    try:
        dump(ncm_path, tmp_name, False)
        ext = filetype.guess_extension(tmp_name)
        real_name = tmp_name.rename(ncm.with_suffix(f".{ext}"))
        status["status"] = True
        status["filepath"] = real_name
        logging.info("real filename is %s", real_name)
    except Exception:
        err = traceback.format_exc()
        logging.error("Convert failed for %s -> %s \n%s\n", ncm_path, tmp_name,
                      err)
        status["error"] = err
    finally:
        return status
예제 #4
0
 def ok(self):
     if not self.sourcePathLabel.text():
         messageWindow = QDialog()
         message = Ui_Message()
         message.setupUi(messageWindow, "未选择ncm文件所在位置,请先选择ncm所在文件夹!!!")
         messageWindow.setWindowModality(Qt.ApplicationModal)
         messageWindow.setFixedSize(messageWindow.width(),
                                    messageWindow.height())
         messageWindow.show()
         messageWindow.exec_()
     elif len(self.sourceFiles) == 0:
         messageWindow = QDialog()
         message = Ui_Message()
         message.setupUi(messageWindow, "您选择的文件夹中不包含ncm文件,请重新选择!!!")
         messageWindow.setWindowModality(Qt.ApplicationModal)
         messageWindow.show()
         messageWindow.exec_()
     else:
         self.showMessage("(* ̄︶ ̄)~~选中的文件正在转码中~~(* ̄︶ ̄)")
         for i in range(0, len(self.sourceFiles)):
             self.showMessage("转化中 --- {}%".format(
                 str((i + 1) * 100 / len(self.sourceFiles))))
             self.showMessage("正在转化 --- " + self.sourceFiles[i])
             try:
                 self.logger.info(
                     "转化中 ---> {}".format(self.sourcePath + "/" +
                                          self.sourceFiles[i]))
                 mp3file = dump(self.sourcePath + "/" + self.sourceFiles[i],
                                self.name_format)
                 self.showMessage("已生成 --- " + mp3file)
                 self.logger.info("生成文件 --- " + mp3file)
             except Exception as e:
                 self.logger.error(e)
         self.showMessage("转化完成")
         complateMessage = QMessageBox()
         complateMessage.setWindowFlags(QtCore.Qt.FramelessWindowHint)
         complateMessage.setWindowModality(Qt.ApplicationModal)
         reply = complateMessage.question(self.ncmTransfer, "完成选择",
                                          "确认退出吗?",
                                          QMessageBox.Yes | QMessageBox.No,
                                          QMessageBox.No)
         if reply == QMessageBox.Yes:
             self.ncmTransfer.accept()  # 接受关闭事件
         self.clearAll()
         self.message.clear()
예제 #5
0
    if not os.path.isdir(args.output):
        print('output is not a folder')
        exit()

files = []
for path in args.input:
    path = os.path.abspath(path)
    if not os.path.exists(path):
        continue
    if os.path.isdir(path):
        files += [
            os.path.join(path, name) for name in os.listdir(path)
            if os.path.splitext(name)[-1] == '.ncm'
        ]
    else:
        files += [path]

if sys.version[0] == '2':
    files = [path.decode(sys.stdin.encoding) for path in files]

if not files:
    print('empty input')
    exit()

for path in files:
    try:
        save = ncmdump.dump(path, name_format, args.skip)
        if save: print(os.path.split(save)[-1])
        if args.delete: os.remove(path)
    except KeyboardInterrupt:
        exit()
예제 #6
0
print("如果您不知道路径在哪里,在网易云客户端中点击:设置 --> 下载设置,即可看到下载路径。")
print("如留空,默认: C:\\CloudMusic\\")
download_folder = input("下载路径:") or "C:\\CloudMusic\\"
os.system('cls')
waiting = True
print("当前下载路径:" + download_folder)
print("您现在可以在网易云音乐客户端中直接下载歌曲,本工具会自动将ncm转换成mp3格式。")
print("等待转换...")

def all_files(root, patterns='*', single_level=False, yield_folder=False):
    patterns = patterns.split(';')
    for path, subdirs, files in os.walk(root):
        if yield_folder:
            files.extend(subdirs)
        files.sort()
        for fname in files:
            for pt in patterns:
                if fnmatch.fnmatch(fname, pt):
                    yield os.path.join(path, fname)
                    break
        if single_level:
            break
while 1:
    thefile=list(all_files(download_folder, '*.ncm'))
    for item in thefile:
        if(waiting == True):
            waiting = False
            os.system('cls')
        print (dump(item),"转换成功!")
        delete = os.remove(item)
예제 #7
0
def main():
    parser = argparse.ArgumentParser(prog='ncmdump')
    parser.add_argument('input',
                        metavar='input',
                        nargs='*',
                        default=['.'],
                        help='ncm file or folder path')
    parser.add_argument('-f',
                        metavar='format',
                        dest='format',
                        default='',
                        help='customize naming format')
    parser.add_argument('-o',
                        metavar='output',
                        dest='output',
                        help='customize saving folder')
    parser.add_argument('-d',
                        dest='delete',
                        action='store_true',
                        help='delete source after conversion')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-c',
                       dest='cover',
                       action='store_true',
                       help='overwrite file with the same name')
    group.add_argument('-s',
                       dest='skip',
                       action='store_true',
                       help='skip conversion if file exist')
    args = parser.parse_args()

    def validate_name(name):
        pattern = {
            u'\\': u'\',
            u'/': u'/',
            u':': u':',
            u'*': u'*',
            u'?': u'?',
            u'"': u'"',
            u'<': u'<',
            u'>': u'>',
            u'|': u'|'
        }
        for character in pattern:
            name = name.replace(character, pattern[character])
        return name

    def validate_collision(path):
        index = 1
        origin = path
        while os.path.exists(path):
            path = '({})'.format(index).join(os.path.splitext(origin))
            index += 1
        return path

    def name_format(path, meta):
        information = {
            'artist':
            ','.join([artist[0] for artist in meta.get('artist')])
            if 'artist' in meta else None,
            'title':
            meta.get('musicName'),
            'album':
            meta.get('album')
        }

        def substitute(matched):
            key = matched.group(1)
            if key in information:
                return information[key]
            else:
                return key

        name = re.sub(r'%(.+?)%', substitute, args.format)
        name = os.path.splitext(
            os.path.split(path)[1])[0] if not name else name
        name = validate_name(name)
        name += '.' + meta['format']
        folder = args.output if args.output else os.path.dirname(path)
        save = os.path.join(folder, name)
        if not (args.cover or args.skip):
            save = validate_collision(save)
        return save

    if args.output:
        args.output = os.path.abspath(args.output)
        if not os.path.exists(args.output):
            print('output does not exist')
            exit()
        if not os.path.isdir(args.output):
            print('output is not a folder')
            exit()

    files: List[str] = []
    for path in args.input:
        path = os.path.abspath(path)
        if not os.path.exists(path):
            continue
        if os.path.isdir(path):
            files += [
                os.path.join(path, name) for name in os.listdir(path)
                if os.path.splitext(name)[-1] == '.ncm'
            ]
        else:
            files += [path]

    if not files:
        print('empty input')
        exit()

    for path in files:
        try:
            save = dump(path, name_format, args.skip)
            if save:
                print(os.path.split(save)[-1])
            if args.delete:
                os.remove(path)
        except KeyboardInterrupt:
            exit()
예제 #8
0
파일: app.py 프로젝트: Dreoka/ncmdump
    if not os.path.isdir(args.output):
        print('output is not a folder')
        exit()

files = []
for item in args.input:
    item = os.path.abspath(item)
    if not os.path.exists(item):
        continue
    if os.path.isdir(item):
        files += [
            os.path.join(item, _file) for _file in os.listdir(item)
            if os.path.splitext(_file)[-1] == '.ncm'
        ]
    else:
        flles += [item]

if sys.version[0] == '2':
    files = [file_name.decode(sys.stdin.encoding) for file_name in files]

if not files:
    print('empty input')
    exit()

for _file in files:
    try:
        _save = ncmdump.dump(_file, name_format)
        print(os.path.split(_save)[-1])
        if args.delete: os.remove(_file)
    except KeyboardInterrupt:
        exit()