替换程序中所有同步API的调用

pull/225/head
lyswhut 2020-04-26 22:08:23 +08:00
parent cdbedf3d64
commit 9ff5147418
9 changed files with 73 additions and 43 deletions

View File

@ -13,6 +13,7 @@
- 略微加深音量条底色 - 略微加深音量条底色
- 优化其他界面细节 - 优化其他界面细节
- 优化英语翻译,感谢 @CPCer - 优化英语翻译,感谢 @CPCer
- 优化程序的流畅度
### 更变 ### 更变

View File

@ -1,4 +1,5 @@
const fs = require('fs') const fs = require('fs')
const fsPromises = fs.promises
const path = require('path') const path = require('path')
const getImgSize = require('image-size') const getImgSize = require('image-size')
const request = require('request') const request = require('request')
@ -8,8 +9,7 @@ const FlacProcessor = require('./flac-metadata')
const extReg = /^(\.(?:jpe?g|png)).*$/ const extReg = /^(\.(?:jpe?g|png)).*$/
const vendor = 'reference libFLAC 1.2.1 20070917' const vendor = 'reference libFLAC 1.2.1 20070917'
const writeMeta = async(filePath, meta, picPath) => {
const writeMeta = (filePath, meta, picPath) => {
const comments = Object.keys(meta).map(key => `${key.toUpperCase()}=${meta[key] || ''}`) const comments = Object.keys(meta).map(key => `${key.toUpperCase()}=${meta[key] || ''}`)
const data = { const data = {
vorbis: { vorbis: {
@ -18,7 +18,8 @@ const writeMeta = (filePath, meta, picPath) => {
}, },
} }
if (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 imgSize = getImgSize(apicData)
let mime_type let mime_type
let bitsPerPixel let bitsPerPixel

View File

@ -298,7 +298,7 @@ export default {
offset: 150, offset: 150,
}) })
}, },
play() { async play() {
console.log('play', this.playIndex) console.log('play', this.playIndex)
this.checkDelayNextTimeout() this.checkDelayNextTimeout()
let targetSong = this.targetSong = this.list[this.playIndex] let targetSong = this.targetSong = this.list[this.playIndex]
@ -308,7 +308,7 @@ export default {
if (this.listId == 'download') { if (this.listId == 'download') {
const filePath = path.join(this.setting.download.savePath, targetSong.fileName) const filePath = path.join(this.setting.download.savePath, targetSong.fileName)
// console.log(filePath) // 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() return this.list.length == 1 ? null : this.handleNext()
} }
this.musicInfo.songmid = targetSong.musicInfo.songmid this.musicInfo.songmid = targetSong.musicInfo.songmid
@ -341,14 +341,15 @@ export default {
this.handleNext() this.handleNext()
}, 5000) }, 5000)
}, },
handleNext() { async handleNext() {
// if (this.list.listName === null) return // if (this.list.listName === null) return
let list let list
if (this.listId == 'download') { if (this.listId == 'download') {
list = this.list.filter(s => { list = []
const filePath = path.join(this.setting.download.savePath, s.fileName) for (const item of this.list) {
return !(!checkPath(filePath) || !s.isComplate || /\.ape$/.test(filePath)) 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) { } else if (this.isAPITemp) {
list = this.list.filter(s => s.source == 'kw') list = this.list.filter(s => s.source == 'kw')
} else { } else {

View File

@ -31,14 +31,21 @@ const getters = {
downloadStatus: state => state.downloadStatus, downloadStatus: state => state.downloadStatus,
} }
const checkPath = path => { const checkPath = path => new Promise((resolve, reject) => {
try { fs.access(path, fs.constants.F_OK | fs.constants.W_OK, err => {
if (!fs.existsSync(path)) fs.mkdirSync(path, { recursive: true }) if (err) {
} catch (error) { if (err.code === 'ENOENT') {
return error.message fs.mkdir(path, { recursive: true }, err => {
} if (err) return reject(err)
return false resolve()
} })
return
}
return reject(err)
}
resolve()
})
})
const getExt = type => { const getExt = type => {
switch (type) { switch (type) {
@ -161,7 +168,7 @@ const deleteFile = path => new Promise((resolve, reject) => {
// actions // actions
const actions = { const actions = {
createDownload({ state, rootState, commit }, { musicInfo, type }) { async createDownload({ state, rootState, commit }, { musicInfo, type }) {
let ext = getExt(type) let ext = getExt(type)
if (checkList(state.list, musicInfo, type, ext)) return if (checkList(state.list, musicInfo, type, ext)) return
const downloadInfo = { const downloadInfo = {
@ -185,7 +192,7 @@ const actions = {
downloadInfo.filePath = path.join(rootState.setting.download.savePath, downloadInfo.fileName) downloadInfo.filePath = path.join(rootState.setting.download.savePath, downloadInfo.fileName)
commit('addTask', downloadInfo) commit('addTask', downloadInfo)
try { // 删除同路径下的同名文件 try { // 删除同路径下的同名文件
fs.unlinkSync(downloadInfo.filePath) await deleteFile(downloadInfo.filePath)
} catch (err) { } catch (err) {
if (err.code !== 'ENOENT') return commit('setStatusText', { downloadInfo, text: '文件删除失败' }) if (err.code !== 'ENOENT') return commit('setStatusText', { downloadInfo, text: '文件删除失败' })
} }
@ -202,7 +209,7 @@ const actions = {
createDownloadMultiple({ state, rootState }, { list, type }) { createDownloadMultiple({ state, rootState }, { list, type }) {
addTask([...list], type, this) 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 }) if (downloadInfo && downloadInfo != state.downloadStatus.WAITING) commit('setStatus', { downloadInfo, status: state.downloadStatus.WAITING })
let result = getStartTask(state.list, state.downloadStatus, rootState.setting.download.maxDownloadNum) let result = getStartTask(state.list, state.downloadStatus, rootState.setting.download.maxDownloadNum)
@ -216,8 +223,11 @@ const actions = {
// 开始任务 // 开始任务
commit('onStart', downloadInfo) commit('onStart', downloadInfo)
commit('setStatusText', { downloadInfo, text: '任务初始化中' }) commit('setStatusText', { downloadInfo, text: '任务初始化中' })
let msg = checkPath(rootState.setting.download.savePath) try {
if (msg) return commit('setStatusText', '检查下载目录出错: ' + msg) await checkPath(rootState.setting.download.savePath)
} catch (error) {
if (error) return commit('setStatusText', '检查下载目录出错: ' + error.message)
}
const _this = this const _this = this
const options = { const options = {
url: downloadInfo.url, url: downloadInfo.url,
@ -312,7 +322,7 @@ const actions = {
this.dispatch('download/startTask') this.dispatch('download/startTask')
}) })
}, },
removeTaskMultiple({ commit, rootState, state }, list) { async removeTaskMultiple({ commit, rootState, state }, list) {
list.forEach(item => { list.forEach(item => {
let index = state.list.indexOf(item) let index = state.list.indexOf(item)
if (index < 0) return if (index < 0) return

View File

@ -74,7 +74,9 @@ export default ({
debugDownload && console.log('Downloading: ', url) debugDownload && console.log('Downloading: ', url)
dl.start() dl.start().catch(err => {
onError(err)
})
return dl return dl
} }

View File

@ -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)
})
})
/** /**
* 选择路径 * 选择路径

View File

@ -3,7 +3,7 @@ import needle from 'needle'
import { debugRequest } from './env' import { debugRequest } from './env'
import { requestMsg } from './message' import { requestMsg } from './message'
import { bHh } from './music/options' import { bHh } from './music/options'
import { deflateRawSync } from 'zlib' import { deflateRaw } from 'zlib'
import { getProxyInfo } from './index' import { getProxyInfo } from './index'
// import fs from 'fs' // import fs from 'fs'
@ -48,10 +48,11 @@ const defaultHeaders = {
const buildHttpPromose = (url, options) => { const buildHttpPromose = (url, options) => {
let requestObj let requestObj
let cancelFn let cancelFn
let isCancelled = false
let p = new Promise((resolve, reject) => { let p = new Promise((resolve, reject) => {
cancelFn = reject cancelFn = reject
debugRequest && console.log(`\n---send request------${url}------------`) 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() // options.isShowProgress && window.api.hideProgress()
debugRequest && console.log(`\n---response------${url}------------`) debugRequest && console.log(`\n---response------${url}------------`)
debugRequest && console.log(body) debugRequest && console.log(body)
@ -68,12 +69,15 @@ const buildHttpPromose = (url, options) => {
return reject(err) return reject(err)
} }
resolve(resp) resolve(resp)
}).then(ro => {
requestObj = ro
if (isCancelled) obj.cancelHttp()
}) })
}) })
const obj = { const obj = {
promise: p, promise: p,
cancelHttp() { cancelHttp() {
if (!requestObj) return if (!requestObj) return isCancelled = true
cancelFn(new Error(requestMsg.cancelRequest)) cancelFn(new Error(requestMsg.cancelRequest))
cancelHttp(requestObj) cancelHttp(requestObj)
requestObj = null 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 regx = /(?:\d\w)+/g
const fetchData = (url, method, { const fetchData = async(url, method, {
headers = {}, headers = {},
format = 'json', format = 'json',
timeout = 15000, timeout = 15000,
@ -263,7 +274,7 @@ const fetchData = (url, method, {
s = s.replace(s.substr(-1), '') s = s.replace(s.substr(-1), '')
s = Buffer.from(s, 'base64').toString() s = Buffer.from(s, 'base64').toString()
let v = process.versions.app.split('.').map(n => n.length < 3 ? n.padStart(3, '0') : n).join('') 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] delete headers[bHh]
} }
return request(url, { return request(url, {

View File

@ -262,9 +262,9 @@ export default {
this.handleStartTask(index) this.handleStartTask(index)
} }
}, },
handlePlay(index) { async handlePlay(index) {
const targetSong = this.list[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) }) this.setList({ list: this.list, listId: 'download', index: this.list.findIndex(i => i.key === targetSong.key) })
}, },
handleListBtnClick(info) { handleListBtnClick(info) {
@ -333,9 +333,9 @@ export default {
} }
this.removeAllSelect() this.removeAllSelect()
}, },
handleOpenFolder(index) { async handleOpenFolder(index) {
let path = this.list[index].filePath let path = this.list[index].filePath
if (!checkPath(path)) return if (!await checkPath(path)) return
openDirInExplorer(path) openDirInExplorer(path)
}, },
handleSearch(index) { handleSearch(index) {

View File

@ -413,10 +413,10 @@ export default {
handleOpenDir(dir) { handleOpenDir(dir) {
openDirInExplorer(dir) openDirInExplorer(dir)
}, },
importSetting(path) { async importSetting(path) {
let settingData let settingData
try { try {
settingData = JSON.parse(fs.readFileSync(path, 'utf8')) settingData = JSON.parse(await fs.promises.readFile(path, 'utf8'))
} catch (error) { } catch (error) {
return return
} }
@ -435,10 +435,10 @@ export default {
console.log(err) console.log(err)
}) })
}, },
importPlayList(path) { async importPlayList(path) {
let listData let listData
try { try {
listData = JSON.parse(fs.readFileSync(path, 'utf8')) listData = JSON.parse(await fs.promises.readFile(path, 'utf8'))
} catch (error) { } catch (error) {
return return
} }
@ -465,10 +465,10 @@ export default {
console.log(err) console.log(err)
}) })
}, },
importAllData(path) { async importAllData(path) {
let allData let allData
try { try {
allData = JSON.parse(fs.readFileSync(path, 'utf8')) allData = JSON.parse(await fs.promises.readFile(path, 'utf8'))
} catch (error) { } catch (error) {
return return
} }