musescore-downloader/src/file.ts

65 lines
1.7 KiB
TypeScript
Raw Normal View History

import scoreinfo from './scoreinfo'
2020-10-21 14:58:24 +00:00
import { webpackHook } from './webpack-hook'
2020-10-21 14:51:40 +00:00
const FILE_URL_MODULE_ID = 'iNJA'
2020-10-25 21:55:48 +00:00
const MAGIC_REG = /^\d+(img|mp3|midi)\d(.+)$/
type FileType = 'img' | 'mp3' | 'midi'
2020-10-21 14:51:40 +00:00
const getApiUrl = (id: number, type: FileType, index: number): string => {
// proxy
2020-10-21 14:51:40 +00:00
return `https://musescore.now.sh/api/jmuse?id=${id}&type=${type}&index=${index}`
}
2020-10-22 20:52:33 +00:00
/**
* I know this is super hacky.
*/
let magic: Promise<string> | string = new Promise((resolve) => {
2020-10-25 21:55:48 +00:00
// reserve for future hook update
2020-10-25 03:19:41 +00:00
const method = 'encodeURIComponent'
const _fn = window[method]
2020-10-22 20:52:33 +00:00
2020-10-25 03:19:41 +00:00
// This script can run before anything on the page,
// so setting `encodeURIComponent` to be non-configurable and non-writable is no use.
window[method] = (s) => {
2020-10-25 21:55:48 +00:00
const m = s.toString().match(MAGIC_REG)
2020-10-22 20:52:33 +00:00
if (m) {
// the auth string will be encoded using `encodeURIComponent` before `md5`,
// so hook here
resolve(m[2])
magic = m[2]
2020-10-25 03:19:41 +00:00
window[method] = _fn // detach
2020-10-22 20:52:33 +00:00
}
2020-10-25 03:19:41 +00:00
return _fn(s)
2020-10-22 20:52:33 +00:00
}
})
2020-10-21 14:51:40 +00:00
export const getFileUrl = async (type: FileType, index = 0): Promise<string> => {
const fileUrlModule = webpackHook(FILE_URL_MODULE_ID, {
2020-10-21 14:39:28 +00:00
'6Ulw' (_, r, t) { // override
t.d(r, 'a', () => {
return type
})
},
2020-10-21 14:51:40 +00:00
'VSrV' (_, r, t) { // override
t.d(r, 'b', () => {
return getApiUrl
})
},
2020-10-21 14:39:28 +00:00
})
2020-10-22 20:52:33 +00:00
const fn: (id: number, index: number, cb: (url: string) => any, magic: string) => string = fileUrlModule.default
if (typeof magic !== 'string') {
// force to retrieve the MAGIC
const el = document.querySelectorAll('._13vRI')[6] as HTMLButtonElement
el.click()
magic = await magic
}
2020-10-21 14:51:40 +00:00
return new Promise((resolve) => {
2020-10-22 20:52:33 +00:00
return fn(scoreinfo.id, index, resolve, magic as string)
})
}