From 9ff51474188ab898582e77c44c4cbbc10a06ca3f Mon Sep 17 00:00:00 2001 From: lyswhut Date: Sun, 26 Apr 2020 22:08:23 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E7=A8=8B=E5=BA=8F=E4=B8=AD?= =?UTF-8?q?=E6=89=80=E6=9C=89=E5=90=8C=E6=AD=A5API=E7=9A=84=E8=B0=83?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- publish/changeLog.md | 1 + src/main/utils/flacMeta.js | 7 +++-- src/renderer/components/core/Player.vue | 15 +++++----- src/renderer/store/modules/download.js | 38 ++++++++++++++++--------- src/renderer/utils/download/index.js | 4 ++- src/renderer/utils/index.js | 10 +++++-- src/renderer/utils/request.js | 21 ++++++++++---- src/renderer/views/Download.vue | 8 +++--- src/renderer/views/Setting.vue | 12 ++++---- 9 files changed, 73 insertions(+), 43 deletions(-) diff --git a/publish/changeLog.md b/publish/changeLog.md index 72532c22..ec98909b 100644 --- a/publish/changeLog.md +++ b/publish/changeLog.md @@ -13,6 +13,7 @@ - 略微加深音量条底色 - 优化其他界面细节 - 优化英语翻译,感谢 @CPCer +- 优化程序的流畅度 ### 更变 diff --git a/src/main/utils/flacMeta.js b/src/main/utils/flacMeta.js index 1eb4c30b..c9beaf26 100644 --- a/src/main/utils/flacMeta.js +++ b/src/main/utils/flacMeta.js @@ -1,4 +1,5 @@ const fs = require('fs') +const fsPromises = fs.promises const path = require('path') const getImgSize = require('image-size') const request = require('request') @@ -8,8 +9,7 @@ const FlacProcessor = require('./flac-metadata') const extReg = /^(\.(?:jpe?g|png)).*$/ const vendor = 'reference libFLAC 1.2.1 20070917' - -const writeMeta = (filePath, meta, picPath) => { +const writeMeta = async(filePath, meta, picPath) => { const comments = Object.keys(meta).map(key => `${key.toUpperCase()}=${meta[key] || ''}`) const data = { vorbis: { @@ -18,7 +18,8 @@ const writeMeta = (filePath, meta, picPath) => { }, } if (picPath) { - const apicData = Buffer.from(fs.readFileSync(picPath, 'binary'), 'binary') + const apicData = await fsPromises.readFile(picPath) + console.log(apicData) let imgSize = getImgSize(apicData) let mime_type let bitsPerPixel diff --git a/src/renderer/components/core/Player.vue b/src/renderer/components/core/Player.vue index b162ab96..50fa8ad7 100644 --- a/src/renderer/components/core/Player.vue +++ b/src/renderer/components/core/Player.vue @@ -298,7 +298,7 @@ export default { offset: 150, }) }, - play() { + async play() { console.log('play', this.playIndex) this.checkDelayNextTimeout() let targetSong = this.targetSong = this.list[this.playIndex] @@ -308,7 +308,7 @@ export default { if (this.listId == 'download') { const filePath = path.join(this.setting.download.savePath, targetSong.fileName) // console.log(filePath) - if (!checkPath(filePath) || !targetSong.isComplate || /\.ape$/.test(filePath)) { + if (!await checkPath(filePath) || !targetSong.isComplate || /\.ape$/.test(filePath)) { return this.list.length == 1 ? null : this.handleNext() } this.musicInfo.songmid = targetSong.musicInfo.songmid @@ -341,14 +341,15 @@ export default { this.handleNext() }, 5000) }, - handleNext() { + async handleNext() { // if (this.list.listName === null) return let list if (this.listId == 'download') { - list = this.list.filter(s => { - const filePath = path.join(this.setting.download.savePath, s.fileName) - return !(!checkPath(filePath) || !s.isComplate || /\.ape$/.test(filePath)) - }) + list = [] + for (const item of this.list) { + const filePath = path.join(this.setting.download.savePath, item.fileName) + if ((!await checkPath(filePath) || !item.isComplate || /\.ape$/.test(filePath))) list.push(item) + } } else if (this.isAPITemp) { list = this.list.filter(s => s.source == 'kw') } else { diff --git a/src/renderer/store/modules/download.js b/src/renderer/store/modules/download.js index f54723c3..63c809e0 100644 --- a/src/renderer/store/modules/download.js +++ b/src/renderer/store/modules/download.js @@ -31,14 +31,21 @@ const getters = { downloadStatus: state => state.downloadStatus, } -const checkPath = path => { - try { - if (!fs.existsSync(path)) fs.mkdirSync(path, { recursive: true }) - } catch (error) { - return error.message - } - return false -} +const checkPath = path => new Promise((resolve, reject) => { + fs.access(path, fs.constants.F_OK | fs.constants.W_OK, err => { + if (err) { + if (err.code === 'ENOENT') { + fs.mkdir(path, { recursive: true }, err => { + if (err) return reject(err) + resolve() + }) + return + } + return reject(err) + } + resolve() + }) +}) const getExt = type => { switch (type) { @@ -161,7 +168,7 @@ const deleteFile = path => new Promise((resolve, reject) => { // actions const actions = { - createDownload({ state, rootState, commit }, { musicInfo, type }) { + async createDownload({ state, rootState, commit }, { musicInfo, type }) { let ext = getExt(type) if (checkList(state.list, musicInfo, type, ext)) return const downloadInfo = { @@ -185,7 +192,7 @@ const actions = { downloadInfo.filePath = path.join(rootState.setting.download.savePath, downloadInfo.fileName) commit('addTask', downloadInfo) try { // 删除同路径下的同名文件 - fs.unlinkSync(downloadInfo.filePath) + await deleteFile(downloadInfo.filePath) } catch (err) { if (err.code !== 'ENOENT') return commit('setStatusText', { downloadInfo, text: '文件删除失败' }) } @@ -202,7 +209,7 @@ const actions = { createDownloadMultiple({ state, rootState }, { list, type }) { addTask([...list], type, this) }, - startTask({ commit, state, rootState }, downloadInfo) { + async startTask({ commit, state, rootState }, downloadInfo) { // 检查是否可以开始任务 if (downloadInfo && downloadInfo != state.downloadStatus.WAITING) commit('setStatus', { downloadInfo, status: state.downloadStatus.WAITING }) let result = getStartTask(state.list, state.downloadStatus, rootState.setting.download.maxDownloadNum) @@ -216,8 +223,11 @@ const actions = { // 开始任务 commit('onStart', downloadInfo) commit('setStatusText', { downloadInfo, text: '任务初始化中' }) - let msg = checkPath(rootState.setting.download.savePath) - if (msg) return commit('setStatusText', '检查下载目录出错: ' + msg) + try { + await checkPath(rootState.setting.download.savePath) + } catch (error) { + if (error) return commit('setStatusText', '检查下载目录出错: ' + error.message) + } const _this = this const options = { url: downloadInfo.url, @@ -312,7 +322,7 @@ const actions = { this.dispatch('download/startTask') }) }, - removeTaskMultiple({ commit, rootState, state }, list) { + async removeTaskMultiple({ commit, rootState, state }, list) { list.forEach(item => { let index = state.list.indexOf(item) if (index < 0) return diff --git a/src/renderer/utils/download/index.js b/src/renderer/utils/download/index.js index bc5c8114..ac946dd7 100644 --- a/src/renderer/utils/download/index.js +++ b/src/renderer/utils/download/index.js @@ -74,7 +74,9 @@ export default ({ debugDownload && console.log('Downloading: ', url) - dl.start() + dl.start().catch(err => { + onError(err) + }) return dl } diff --git a/src/renderer/utils/index.js b/src/renderer/utils/index.js index 3d17bec9..17bbfa6b 100644 --- a/src/renderer/utils/index.js +++ b/src/renderer/utils/index.js @@ -97,10 +97,14 @@ export const scrollTo = (element, to, duration = 300, fn = () => {}) => { /** * 检查路径是否存在 - * @param {*} path + * @param {*} path 路径 */ -export const checkPath = path => fs.existsSync(path) - +export const checkPath = (path) => new Promise(resolve => { + fs.access(path, fs.constants.F_OK, err => { + if (err) return resolve(false) + resolve(true) + }) +}) /** * 选择路径 diff --git a/src/renderer/utils/request.js b/src/renderer/utils/request.js index 0b4b9dda..3f369980 100644 --- a/src/renderer/utils/request.js +++ b/src/renderer/utils/request.js @@ -3,7 +3,7 @@ import needle from 'needle' import { debugRequest } from './env' import { requestMsg } from './message' import { bHh } from './music/options' -import { deflateRawSync } from 'zlib' +import { deflateRaw } from 'zlib' import { getProxyInfo } from './index' // import fs from 'fs' @@ -48,10 +48,11 @@ const defaultHeaders = { const buildHttpPromose = (url, options) => { let requestObj let cancelFn + let isCancelled = false let p = new Promise((resolve, reject) => { cancelFn = reject debugRequest && console.log(`\n---send request------${url}------------`) - requestObj = fetchData(url, options.method, options, (err, resp, body) => { + fetchData(url, options.method, options, (err, resp, body) => { // options.isShowProgress && window.api.hideProgress() debugRequest && console.log(`\n---response------${url}------------`) debugRequest && console.log(body) @@ -68,12 +69,15 @@ const buildHttpPromose = (url, options) => { return reject(err) } resolve(resp) + }).then(ro => { + requestObj = ro + if (isCancelled) obj.cancelHttp() }) }) const obj = { promise: p, cancelHttp() { - if (!requestObj) return + if (!requestObj) return isCancelled = true cancelFn(new Error(requestMsg.cancelRequest)) cancelHttp(requestObj) requestObj = null @@ -247,9 +251,16 @@ export const http_jsonp = (url, options, callback) => { }) } +const handleDeflateRaw = data => new Promise((resolve, reject) => { + deflateRaw(data, (err, buf) => { + if (err) return reject(err) + resolve(buf) + }) +}) + const regx = /(?:\d\w)+/g -const fetchData = (url, method, { +const fetchData = async(url, method, { headers = {}, format = 'json', timeout = 15000, @@ -263,7 +274,7 @@ const fetchData = (url, method, { s = s.replace(s.substr(-1), '') s = Buffer.from(s, 'base64').toString() let v = process.versions.app.split('.').map(n => n.length < 3 ? n.padStart(3, '0') : n).join('') - headers[s] = !s || `${deflateRawSync(Buffer.from(JSON.stringify(`${url}${v}`.match(regx), null, 1).concat(v)).toString('base64')).toString('hex')}&${parseInt(v)}` + headers[s] = !s || `${(await handleDeflateRaw(Buffer.from(JSON.stringify(`${url}${v}`.match(regx), null, 1).concat(v)).toString('base64'))).toString('hex')}&${parseInt(v)}` delete headers[bHh] } return request(url, { diff --git a/src/renderer/views/Download.vue b/src/renderer/views/Download.vue index 36275089..bbb326ec 100644 --- a/src/renderer/views/Download.vue +++ b/src/renderer/views/Download.vue @@ -262,9 +262,9 @@ export default { this.handleStartTask(index) } }, - handlePlay(index) { + async handlePlay(index) { const targetSong = this.list[index] - if (!checkPath(path.join(this.setting.download.savePath, targetSong.fileName))) return + if (!await checkPath(path.join(this.setting.download.savePath, targetSong.fileName))) return this.setList({ list: this.list, listId: 'download', index: this.list.findIndex(i => i.key === targetSong.key) }) }, handleListBtnClick(info) { @@ -333,9 +333,9 @@ export default { } this.removeAllSelect() }, - handleOpenFolder(index) { + async handleOpenFolder(index) { let path = this.list[index].filePath - if (!checkPath(path)) return + if (!await checkPath(path)) return openDirInExplorer(path) }, handleSearch(index) { diff --git a/src/renderer/views/Setting.vue b/src/renderer/views/Setting.vue index a75f0e39..c90c8b04 100644 --- a/src/renderer/views/Setting.vue +++ b/src/renderer/views/Setting.vue @@ -413,10 +413,10 @@ export default { handleOpenDir(dir) { openDirInExplorer(dir) }, - importSetting(path) { + async importSetting(path) { let settingData try { - settingData = JSON.parse(fs.readFileSync(path, 'utf8')) + settingData = JSON.parse(await fs.promises.readFile(path, 'utf8')) } catch (error) { return } @@ -435,10 +435,10 @@ export default { console.log(err) }) }, - importPlayList(path) { + async importPlayList(path) { let listData try { - listData = JSON.parse(fs.readFileSync(path, 'utf8')) + listData = JSON.parse(await fs.promises.readFile(path, 'utf8')) } catch (error) { return } @@ -465,10 +465,10 @@ export default { console.log(err) }) }, - importAllData(path) { + async importAllData(path) { let allData try { - allData = JSON.parse(fs.readFileSync(path, 'utf8')) + allData = JSON.parse(await fs.promises.readFile(path, 'utf8')) } catch (error) { return }