musescore-downloader/src/file.ts

76 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-10-26 18:53:55 +00:00
/* eslint-disable no-extend-native */
import scoreinfo from './scoreinfo'
2020-11-19 05:51:18 +00:00
import { onPackLoad, loadAllPacks } from './webpack-hook'
type FileType = 'img' | 'mp3' | 'midi'
2020-11-18 23:35:45 +00:00
const AUTH_REG = /,((\d+\.\..+?)?function\(\)\{var \w=Array.prototype.slice.*?)\)(\[|\.then)/
2020-11-19 05:51:18 +00:00
enum PACK_HINT {
img = 'getImageRef',
midi = 'midi:',
mp3 = 'setVolume:',
}
2020-11-17 17:09:49 +00:00
2020-10-22 20:52:33 +00:00
/**
* I know this is super hacky.
*/
2020-11-18 23:35:45 +00:00
const magicHookConstr = async (type: FileType) => {
2020-11-17 17:09:49 +00:00
// request pack
2020-11-19 05:51:18 +00:00
await loadAllPacks()
2020-11-17 17:09:49 +00:00
return new Promise<string>((resolve) => {
onPackLoad((pack) => {
2020-11-19 05:51:18 +00:00
Object.values(pack[1]).forEach((mod) => {
const str = mod.toString()
if (!str.includes(PACK_HINT[type])) {
return
}
const m = str.match(AUTH_REG)
if (m) {
const code = m[1]
try {
// eslint-disable-next-line no-new-func, @typescript-eslint/no-implied-eval
const magic = Function(`return (${code})`)()
resolve(magic)
} catch (err) {
console.error(err)
2020-11-18 18:57:56 +00:00
}
2020-11-19 05:51:18 +00:00
}
})
2020-11-17 17:09:49 +00:00
})
2020-11-05 21:47:50 +00:00
})
2020-11-17 17:09:49 +00:00
}
const magics: Record<FileType, Promise<string>> = {
2020-11-18 18:57:56 +00:00
img: magicHookConstr('img'),
midi: magicHookConstr('midi'),
mp3: magicHookConstr('mp3'),
2020-11-17 17:09:49 +00:00
}
2020-10-22 20:52:33 +00:00
2020-11-13 23:27:28 +00:00
const getApiUrl = (type: FileType, index: number): string => {
2020-11-17 17:09:49 +00:00
return `/api/jmuse?id=${scoreinfo.id}&type=${type}&index=${index}&v2=1`
2020-11-13 23:27:28 +00:00
}
2020-10-22 20:52:33 +00:00
2020-11-13 23:27:28 +00:00
const getApiAuth = async (type: FileType, index: number): Promise<string> => {
2020-11-17 17:09:49 +00:00
// eslint-disable-next-line no-void
void index
return magics[type]
2020-11-13 23:27:28 +00:00
}
export const getFileUrl = async (type: FileType, index = 0): Promise<string> => {
const url = getApiUrl(type, index)
const auth = await getApiAuth(type, index)
const r = await fetch(url, {
headers: {
Authorization: auth,
},
})
2020-11-13 23:27:28 +00:00
const { info } = await r.json()
return info.url as string
}