musescore-downloader/src/file.ts

66 lines
1.7 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-14 18:33:42 +00:00
import { webpackHook, webpackGlobalOverride, ALL } from './webpack-hook'
2020-11-14 22:23:22 +00:00
let authModuleId: string
2020-11-14 18:33:42 +00:00
const AUTH_FN = '+3],22,-1044525330)'
2020-11-13 23:27:28 +00:00
const MAGIC_ARG_INDEX = 1
type FileType = 'img' | 'mp3' | 'midi'
2020-10-22 20:52:33 +00:00
/**
* I know this is super hacky.
*/
let magic: Promise<string> | string = new Promise((resolve) => {
2020-11-12 14:46:06 +00:00
// todo: hook module by what it does, not what it is called
2020-11-14 18:33:42 +00:00
webpackGlobalOverride(ALL, (n, r, t) => { // override
2020-11-13 23:27:28 +00:00
const fn = n.exports
2020-11-14 18:33:42 +00:00
if (typeof fn === 'function' && fn.toString().includes(AUTH_FN)) {
2020-11-14 22:23:22 +00:00
if (!authModuleId && n.i) {
authModuleId = n.i
n.exports = (...args) => {
if (magic instanceof Promise) {
magic = args[MAGIC_ARG_INDEX]
resolve(magic)
}
return fn(...args) as string
2020-11-14 18:33:42 +00:00
}
2020-11-13 23:27:28 +00:00
}
2020-11-12 18:29:10 +00:00
}
2020-11-05 21:47:50 +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 => {
return `/api/jmuse?id=${scoreinfo.id}&type=${type}&index=${index}`
}
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-09 19:10:01 +00:00
if (magic instanceof Promise) {
2020-10-22 20:52:33 +00:00
// force to retrieve the MAGIC
const el = document.querySelectorAll('.SD7H- > button')[3] as HTMLButtonElement
2020-10-22 20:52:33 +00:00
el.click()
magic = await magic
}
2020-11-13 23:27:28 +00:00
const str = String(scoreinfo.id) + type + String(index)
2020-11-14 22:23:22 +00:00
const fn: (str: string, magic: string) => string = webpackHook(authModuleId)
2020-11-13 23:27:28 +00:00
return fn(str, magic)
}
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
}