musescore-downloader/src/mscz.ts

37 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-05-18 22:44:45 +00:00
2020-11-24 17:35:14 +00:00
import { assertRes, getFetch } from './utils'
2020-11-24 07:51:43 +00:00
import { ScoreInfo } from './scoreinfo'
2020-05-18 22:44:45 +00:00
const MSCZ_BUF_SYM = Symbol('msczBufferP')
2020-05-18 22:44:45 +00:00
2020-11-24 10:02:14 +00:00
export const fetchMscz = async (scoreinfo: ScoreInfo, _fetch = getFetch()): Promise<ArrayBuffer> => {
let msczBufferP = scoreinfo.store.get(MSCZ_BUF_SYM) as Promise<ArrayBuffer> | undefined
2020-05-18 22:44:45 +00:00
if (!msczBufferP) {
2020-11-14 18:37:46 +00:00
const url = scoreinfo.msczCidUrl
2020-05-18 22:44:45 +00:00
msczBufferP = (async (): Promise<ArrayBuffer> => {
2020-11-24 09:03:06 +00:00
const r0 = await _fetch(url)
// ipfs-http-gateway specific error
// may read further error msg as json
if (r0.status !== 500) {
assertRes(r0)
}
2020-11-24 09:03:06 +00:00
const cidRes = await r0.json()
2020-11-24 21:50:52 +00:00
const r = await _fetch(scoreinfo.loadMsczUrl(cidRes))
2020-11-21 05:38:10 +00:00
assertRes(r)
2020-05-18 22:44:45 +00:00
const data = await r.arrayBuffer()
return data
})()
scoreinfo.store.set(MSCZ_BUF_SYM, msczBufferP)
2020-05-18 22:44:45 +00:00
}
return msczBufferP
}
2020-11-24 17:35:14 +00:00
export const downloadMscz = async (scoreinfo: ScoreInfo, saveAs: typeof import('file-saver').saveAs): Promise<void> => {
2020-11-24 07:51:43 +00:00
const data = new Blob([await fetchMscz(scoreinfo)])
2020-05-18 22:44:45 +00:00
const filename = scoreinfo.fileName
saveAs(data, `${filename}.mscz`)
}