musescore-downloader/src/file.ts

65 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-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-26 18:53:55 +00:00
const target = String.prototype
const method = 'charCodeAt'
const _fn = target[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,
2020-10-26 18:53:55 +00:00
// so setting this function to be non-configurable and non-writable is no use.
target[method] = function (i) {
const m = this.match(MAGIC_REG)
2020-10-22 20:52:33 +00:00
if (m) {
resolve(m[2])
magic = m[2]
2020-10-26 18:53:55 +00:00
target[method] = _fn // detach
2020-10-22 20:52:33 +00:00
}
2020-10-26 18:53:55 +00:00
return _fn.call(this, i) as number
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-26 18:53:55 +00:00
const fn: (id: number, index: number, cb: (url: string) => any, magic: string) => string = fileUrlModule.a
2020-10-22 20:52:33 +00:00
if (typeof magic !== 'string') {
// 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-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)
})
}