优化自定义源调用处理逻辑

This commit is contained in:
lyswhut 2024-01-30 17:57:03 +08:00
parent 74692efe24
commit 4db5f0394c
7 changed files with 44 additions and 34 deletions

View File

@ -232,18 +232,18 @@ globalThis.lx_setup = (key, id, name, description, version, author, homepage, ra
const jsCall = (action, data) => { const jsCall = (action, data) => {
// console.log('jsCall', action, data) // console.log('jsCall', action, data)
switch (action) { switch (action) {
case '__run_error__':
if (!isInitedApi) isInitedApi = true
return
case '__set_timeout__': case '__set_timeout__':
handleSetTimeout(data) handleSetTimeout(data)
break return
case 'request': case 'request':
handleRequest(data) handleRequest(data)
break return
case 'response': case 'response':
handleNativeResponse(data) handleNativeResponse(data)
break return
default:
break
} }
return 'Unknown action: ' + action return 'Unknown action: ' + action
} }
@ -254,7 +254,7 @@ globalThis.lx_setup = (key, id, name, description, version, author, homepage, ra
writable: false, writable: false,
value: (_key, action, data) => { value: (_key, action, data) => {
if (key != _key) return 'Invalid key' if (key != _key) return 'Invalid key'
return jsCall(action, JSON.parse(data)) return data == null ? jsCall(action) : jsCall(action, JSON.parse(data))
}, },
}) })
@ -496,19 +496,6 @@ globalThis.lx_setup = (key, id, name, description, version, author, homepage, ra
globalThis.setTimeout = _setTimeout globalThis.setTimeout = _setTimeout
globalThis.clearTimeout = _clearTimeout globalThis.clearTimeout = _clearTimeout
globalThis.window = globalThis
globalThis.document = {
getElementsByTagName(name) {
if (name == 'script') {
return [
Object.freeze({
innerText: globalThis.lx.currentScriptInfo.rawScript,
}),
]
}
return null
},
}
const freezeObject = (obj) => { const freezeObject = (obj) => {
if (typeof obj != 'object') return if (typeof obj != 'object') return

View File

@ -165,23 +165,29 @@ public class QuickJS {
return ""; return "";
} catch (Exception e) { } catch (Exception e) {
Log.e("UserApi", "load script error: " + e.getMessage()); Log.e("UserApi", "load script error: " + e.getMessage());
try {
callJS("__run_error__");
} catch (Exception ignored) {}
if (inited) return "";
inited = true;
return e.getMessage(); return e.getMessage();
} }
} }
return "create JavaScript Env failed"; return "create JavaScript Env failed";
} }
public Object callJS(String action, Object... args) { public Object callJS(String action) {
Object[] params; Object[] params = new Object[]{this.key, action};
if (args == null) { return callJS(params);
params = new Object[]{this.key, action};
} else {
Object[] params2 = new Object[args.length + 2];
params2[0] = this.key;
params2[1] = action;
System.arraycopy(args, 0, params2, 2, args.length);
params = params2;
} }
public Object callJS(String action, Object... args) {
Object[] params = new Object[args.length + 2];
params[0] = this.key;
params[1] = action;
System.arraycopy(args, 0, params, 2, args.length);
return callJS(params);
}
public Object callJS(Object[] params) {
try { try {
return this.jsContext.getGlobalObject().getJSFunction("__lx_native__").call(params); return this.jsContext.getGlobalObject().getJSFunction("__lx_native__").call(params);
} catch (Exception e) { } catch (Exception e) {

View File

@ -53,6 +53,7 @@ global.lx = {
qualityList: {}, qualityList: {},
apis: {}, apis: {},
apiInitPromise: [Promise.resolve(false), true, () => {}],
jumpMyListPosition: false, jumpMyListPosition: false,

View File

@ -8,8 +8,18 @@ import apiSourceInfo from '@/utils/musicSdk/api-source-info'
export const setApiSource = (apiId: string) => { export const setApiSource = (apiId: string) => {
if (global.lx.apiInitPromise[1]) {
global.lx.apiInitPromise[0] = new Promise(resolve => {
global.lx.apiInitPromise[1] = false
global.lx.apiInitPromise[2] = (result: boolean) => {
global.lx.apiInitPromise[1] = true
resolve(result)
}
})
}
if (/^user_api/.test(apiId)) { if (/^user_api/.test(apiId)) {
setUserApi(apiId).catch(err => { setUserApi(apiId).catch(err => {
if (!global.lx.apiInitPromise[1]) global.lx.apiInitPromise[2](false)
console.log(err) console.log(err)
let api = apiSourceInfo.find(api => !api.disabled) let api = apiSourceInfo.find(api => !api.disabled)
if (!api) return if (!api) return
@ -19,6 +29,7 @@ export const setApiSource = (apiId: string) => {
// @ts-expect-error // @ts-expect-error
global.lx.qualityList = musicSdk.supportQuality[apiId] ?? {} global.lx.qualityList = musicSdk.supportQuality[apiId] ?? {}
destroyUserApi() destroyUserApi()
if (!global.lx.apiInitPromise[1]) global.lx.apiInitPromise[2](true)
// apiSource.value = apiId // apiSource.value = apiId
// void setUserApiAction(apiId) // void setUserApiAction(apiId)
} }

View File

@ -133,6 +133,7 @@ export default async(setting: LX.AppSetting) => {
}) })
} }
} }
if (!global.lx.apiInitPromise[1]) global.lx.apiInitPromise[2](status)
} }
const showUpdateAlert = ({ name, log, updateUrl }: UpdateInfoParams) => { const showUpdateAlert = ({ name, log, updateUrl }: UpdateInfoParams) => {
if (updateUrl) { if (updateUrl) {

View File

@ -53,7 +53,7 @@ export const getOtherSource = async(musicInfo: LX.Music.MusicInfo | LX.Download.
let timeout: null | number = BackgroundTimer.setTimeout(() => { let timeout: null | number = BackgroundTimer.setTimeout(() => {
timeout = null timeout = null
reject(new Error('find music timeout')) reject(new Error('find music timeout'))
}, 20_000) }, 15_000)
findMusic(searchMusicInfo).then((otherSource) => { findMusic(searchMusicInfo).then((otherSource) => {
resolve(otherSource.map(toNewMusicInfo) as LX.Music.MusicInfoOnline[]) resolve(otherSource.map(toNewMusicInfo) as LX.Music.MusicInfoOnline[])
}).catch(reject).finally(() => { }).catch(reject).finally(() => {
@ -164,6 +164,8 @@ export const getOnlineOtherSourceMusicUrl = async({ musicInfos, quality, onToggl
quality: LX.Quality quality: LX.Quality
isFromCache: boolean isFromCache: boolean
}> => { }> => {
if (!await global.lx.apiInitPromise[0]) throw new Error('source init failed')
let musicInfo: LX.Music.MusicInfoOnline | null = null let musicInfo: LX.Music.MusicInfoOnline | null = null
let itemQuality: LX.Quality | null = null let itemQuality: LX.Quality | null = null
// eslint-disable-next-line no-cond-assign // eslint-disable-next-line no-cond-assign
@ -189,7 +191,7 @@ export const getOnlineOtherSourceMusicUrl = async({ musicInfos, quality, onToggl
} catch (err: any) { } catch (err: any) {
reqPromise = Promise.reject(err) reqPromise = Promise.reject(err)
} }
retryedSource.includes(musicInfo.source) // retryedSource.includes(musicInfo.source)
// eslint-disable-next-line @typescript-eslint/promise-function-async // eslint-disable-next-line @typescript-eslint/promise-function-async
return reqPromise.then(({ url, type }: { url: string, type: LX.Quality }) => { return reqPromise.then(({ url, type }: { url: string, type: LX.Quality }) => {
return { musicInfo, url, quality: type, isFromCache: false } return { musicInfo, url, quality: type, isFromCache: false }
@ -216,6 +218,7 @@ export const handleGetOnlineMusicUrl = async({ musicInfo, quality, onToggleSourc
quality: LX.Quality quality: LX.Quality
isFromCache: boolean isFromCache: boolean
}> => { }> => {
if (!await global.lx.apiInitPromise[0]) throw new Error('source init failed')
// console.log(musicInfo.source) // console.log(musicInfo.source)
const targetQuality = quality ?? getPlayQuality(settingState.setting['player.isPlayHighQuality'], musicInfo) const targetQuality = quality ?? getPlayQuality(settingState.setting['player.isPlayHighQuality'], musicInfo)
@ -279,7 +282,7 @@ export const getOnlineOtherSourcePicUrl = async({ musicInfos, onToggleSource, is
} catch (err: any) { } catch (err: any) {
reqPromise = Promise.reject(err) reqPromise = Promise.reject(err)
} }
retryedSource.includes(musicInfo.source) // retryedSource.includes(musicInfo.source)
return reqPromise.then((url: string) => { return reqPromise.then((url: string) => {
return { musicInfo, url, isFromCache: false } return { musicInfo, url, isFromCache: false }
// eslint-disable-next-line @typescript-eslint/promise-function-async // eslint-disable-next-line @typescript-eslint/promise-function-async
@ -366,7 +369,7 @@ export const getOnlineOtherSourceLyricInfo = async({ musicInfos, onToggleSource,
} catch (err: any) { } catch (err: any) {
reqPromise = Promise.reject(err) reqPromise = Promise.reject(err)
} }
retryedSource.includes(musicInfo.source) // retryedSource.includes(musicInfo.source)
return reqPromise.then(async(lyricInfo: LX.Music.LyricInfo) => { return reqPromise.then(async(lyricInfo: LX.Music.LyricInfo) => {
return existTimeExp.test(lyricInfo.lyric) ? { return existTimeExp.test(lyricInfo.lyric) ? {
lyricInfo, lyricInfo,

1
src/types/app.d.ts vendored
View File

@ -36,6 +36,7 @@ interface GlobalData {
qualityList: LX.QualityList qualityList: LX.QualityList
apis: Partial<LX.UserApi.UserApiSources> apis: Partial<LX.UserApi.UserApiSources>
apiInitPromise: [Promise<boolean>, boolean, (success: boolean) => void]
jumpMyListPosition: boolean jumpMyListPosition: boolean