musescore-downloader/src/file.ts

84 lines
2.0 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-20 14:30:06 +00:00
import { onPackLoad, getObfuscationCtx, OBFUSCATED_REG } from './webpack-hook'
type FileType = 'img' | 'mp3' | 'midi'
2020-11-19 22:54:41 +00:00
const AUTH_REG = `(\\+?${OBFUSCATED_REG.source}?)+`
const AUTH_CTX_REG = `,(${AUTH_REG})\\)(\\[|\\.then)`
2020-11-18 23:35:45 +00:00
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-20 14:30:06 +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
}
2020-11-19 22:54:41 +00:00
const m = str.match(AUTH_CTX_REG)
2020-11-19 05:51:18 +00:00
if (m) {
try {
2020-11-19 22:54:41 +00:00
const deObf = getObfuscationCtx(mod)
const authExp = m[1]
const reg = new RegExp(OBFUSCATED_REG)
2020-11-19 22:54:41 +00:00
let magic = ''
let r: RegExpMatchArray | null
while ((r = reg.exec(authExp)) !== null) {
2020-11-19 22:54:41 +00:00
magic += deObf(+r[2], r[3])
}
2020-11-19 05:51:18 +00:00
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
}