From 15dba7b92f1bba86e3d61b30aa53210da3f7ff65 Mon Sep 17 00:00:00 2001 From: Emmm Monster <58943012+emmmx@users.noreply.github.com> Date: Mon, 24 May 2021 05:04:16 +0800 Subject: [PATCH] refactor(.ncm): typescript & class --- package-lock.json | 6 + package.json | 1 + src/decrypt/entity.ts | 2 +- src/decrypt/ncm.js | 171 ---------------------- src/decrypt/ncm.ts | 235 ++++++++++++++++++++++++++++++ src/decrypt/utils.ts | 2 +- src/shims-browser-id3-writer.d.ts | 2 +- 7 files changed, 245 insertions(+), 174 deletions(-) delete mode 100644 src/decrypt/ncm.js create mode 100644 src/decrypt/ncm.ts diff --git a/package-lock.json b/package-lock.json index 72e4aa1..7f54c3b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1722,6 +1722,12 @@ "@types/node": "*" } }, + "@types/crypto-js": { + "version": "4.0.1", + "resolved": "http://mirrors.cloud.tencent.com/npm/@types%2fcrypto-js/-/crypto-js-4.0.1.tgz", + "integrity": "sha512-6+OPzqhKX/cx5xh+yO8Cqg3u3alrkhoxhE5ZOdSEv0DOzJ13lwJ6laqGU0Kv6+XDMFmlnGId04LtY22PsFLQUw==", + "dev": true + }, "@types/debug": { "version": "4.1.5", "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.5.tgz", diff --git a/package.json b/package.json index 3aaeec3..f4e520e 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "vue-property-decorator": "^9.1.2" }, "devDependencies": { + "@types/crypto-js": "^4.0.1", "@vue/cli-plugin-babel": "^4.5.13", "@vue/cli-plugin-pwa": "^4.5.13", "@vue/cli-plugin-typescript": "^4.5.13", diff --git a/src/decrypt/entity.ts b/src/decrypt/entity.ts index 55faead..a76b9f8 100644 --- a/src/decrypt/entity.ts +++ b/src/decrypt/entity.ts @@ -9,7 +9,7 @@ export interface DecryptResult { ext: string file: string - picture: string + picture?: string message?: string rawExt?: string diff --git a/src/decrypt/ncm.js b/src/decrypt/ncm.js deleted file mode 100644 index 70f373b..0000000 --- a/src/decrypt/ncm.js +++ /dev/null @@ -1,171 +0,0 @@ -import { - AudioMimeType, - BytesHasPrefix, - GetArrayBuffer, - GetImageFromURL, - GetMetaFromFile, - SniffAudioExt, WriteMetaToFlac, WriteMetaToMp3 -} from "@/decrypt/utils.ts"; -import {parseBlob as metaParseBlob} from "music-metadata-browser"; -import jimp from 'jimp'; - -const CryptoJS = require("crypto-js"); -const CORE_KEY = CryptoJS.enc.Hex.parse("687a4852416d736f356b496e62617857"); -const META_KEY = CryptoJS.enc.Hex.parse("2331346C6A6B5F215C5D2630553C2728"); -const MagicHeader = [0x43, 0x54, 0x45, 0x4E, 0x46, 0x44, 0x41, 0x4D]; - - -export async function Decrypt(file, raw_filename, _) { - const fileBuffer = await GetArrayBuffer(file); - const dataView = new DataView(fileBuffer); - - if (!BytesHasPrefix(new Uint8Array(fileBuffer, 0, 8), MagicHeader)) - return {status: false, message: "此ncm文件已损坏"}; - - const keyDataObj = getKeyData(dataView, fileBuffer, 10); - const keyBox = getKeyBox(keyDataObj.data); - - const musicMetaObj = getMetaData(dataView, fileBuffer, keyDataObj.offset); - const musicMeta = musicMetaObj.data; - let audioOffset = musicMetaObj.offset + dataView.getUint32(musicMetaObj.offset + 5, true) + 13; - let audioData = new Uint8Array(fileBuffer, audioOffset); - - let lenAudioData = audioData.length; - for (let cur = 0; cur < lenAudioData; ++cur) audioData[cur] ^= keyBox[cur & 0xff]; - - if (musicMeta.album === undefined) musicMeta.album = ""; - - const artists = []; - if (!!musicMeta.artist) musicMeta.artist.forEach(arr => artists.push(arr[0])); - const info = GetMetaFromFile(raw_filename, musicMeta.musicName, artists.join("; ")) - if (artists.length === 0) artists.push(info.artist); - - if (musicMeta.format === undefined) musicMeta.format = SniffAudioExt(audioData); - - const imageInfo = await GetImageFromURL(musicMeta.albumPic); - - const mime = AudioMimeType[musicMeta.format] - try { - let musicBlob = new Blob([audioData], {type: mime}); - const originalMeta = await metaParseBlob(musicBlob); - let shouldWrite = !originalMeta.common.album && !originalMeta.common.artists && !originalMeta.common.title - if (shouldWrite || imageInfo) { - while (imageInfo && imageInfo.buffer.byteLength >= 1 << 24) { - let img = await jimp.read(Buffer.from(imageInfo.buffer)) - await img.resize(Math.round(img.getHeight() / 2), jimp.AUTO) - imageInfo.buffer = await img.getBufferAsync("image/jpeg") - } - const newMeta = {title: info.title, artists, album: musicMeta.album, picture: imageInfo?.buffer} - if (musicMeta.format === "mp3") { - audioData = WriteMetaToMp3(audioData.buffer, newMeta, originalMeta) - } else if (musicMeta.format === "flac") { - audioData = WriteMetaToFlac(Buffer.from(audioData), newMeta, originalMeta) - } - } - } catch (e) { - console.warn("Error while appending cover image to file ", e) - } - - const musicData = new Blob([audioData], {type: mime}) - - return { - status: true, - title: info.title, - artist: info.artist, - ext: musicMeta.format, - album: musicMeta.album, - picture: imageInfo.url, - file: URL.createObjectURL(musicData), - mime: mime - } -} - - -function getKeyData(dataView, fileBuffer, offset) { - const keyLen = dataView.getUint32(offset, true); - offset += 4; - const cipherText = new Uint8Array(fileBuffer, offset, keyLen).map( - uint8 => uint8 ^ 0x64 - ); - offset += keyLen; - - const plainText = CryptoJS.AES.decrypt( - {ciphertext: CryptoJS.lib.WordArray.create(cipherText)}, - CORE_KEY, - { - mode: CryptoJS.mode.ECB, - padding: CryptoJS.pad.Pkcs7 - } - ); - - const result = new Uint8Array(plainText.sigBytes); - - const words = plainText.words; - const sigBytes = plainText.sigBytes; - for (let i = 0; i < sigBytes; i++) { - result[i] = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; - } - - return {offset: offset, data: result.slice(17)}; -} - -function getKeyBox(keyData) { - const box = new Uint8Array(Array(256).keys()); - - const keyDataLen = keyData.length; - - let j = 0; - - for (let i = 0; i < 256; i++) { - j = (box[i] + j + keyData[i % keyDataLen]) & 0xff; - [box[i], box[j]] = [box[j], box[i]]; - } - - return box.map((_, i, arr) => { - i = (i + 1) & 0xff; - const si = arr[i]; - const sj = arr[(i + si) & 0xff]; - return arr[(si + sj) & 0xff]; - }); -} - -/** - * @typedef {Object} MusicMetaType - * @property {Number} musicId - * @property {String} musicName - * @property {[[String, Number]]} artist - * @property {String} album - * @property {"flac"|"mp3"} format - * @property {String} albumPic - */ - -function getMetaData(dataView, fileBuffer, offset) { - const metaDataLen = dataView.getUint32(offset, true); - offset += 4; - if (metaDataLen === 0) return {data: {}, offset: offset}; - - const cipherText = new Uint8Array(fileBuffer, offset, metaDataLen).map( - data => data ^ 0x63 - ); - offset += metaDataLen; - - const plainText = CryptoJS.AES.decrypt({ - ciphertext: CryptoJS.enc.Base64.parse( - CryptoJS.lib.WordArray.create(cipherText.slice(22)).toString(CryptoJS.enc.Utf8) - ) - }, - META_KEY, - {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7} - ).toString(CryptoJS.enc.Utf8); - const labelIndex = plainText.indexOf(":"); - let result = JSON.parse(plainText.slice(labelIndex + 1)); - if (plainText.slice(0, labelIndex) === "dj") { - result = result.mainMusic; - } - if (!!result.albumPic && result.albumPic !== "") - result.albumPic = result.albumPic.replace("http://", "https://") + "?param=500y500"; - - return {data: result, offset: offset}; -} - - diff --git a/src/decrypt/ncm.ts b/src/decrypt/ncm.ts new file mode 100644 index 0000000..88a5350 --- /dev/null +++ b/src/decrypt/ncm.ts @@ -0,0 +1,235 @@ +import { + AudioMimeType, + BytesHasPrefix, + GetArrayBuffer, + GetImageFromURL, + GetMetaFromFile, IMusicMeta, + SniffAudioExt, + WriteMetaToFlac, + WriteMetaToMp3 +} from "@/decrypt/utils.ts"; +import {parseBlob as metaParseBlob} from "music-metadata-browser"; +import jimp from 'jimp'; + +import CryptoJS from "crypto-js"; +import {DecryptResult} from "@/decrypt/entity"; + +const CORE_KEY = CryptoJS.enc.Hex.parse("687a4852416d736f356b496e62617857"); +const META_KEY = CryptoJS.enc.Hex.parse("2331346C6A6B5F215C5D2630553C2728"); +const MagicHeader = [0x43, 0x54, 0x45, 0x4E, 0x46, 0x44, 0x41, 0x4D]; + + +export async function Decrypt(file: File, raw_filename: string, _: string): Promise { + return (new NcmDecrypt(await GetArrayBuffer(file), raw_filename)).decrypt() +} + + +interface NcmMusicMeta { + //musicId: number + musicName?: string + artist?: Array[] + format?: string + album?: string + albumPic?: string +} + +interface NcmDjMeta { + mainMusic: NcmMusicMeta +} + + +class NcmDecrypt { + raw: ArrayBuffer + view: DataView + offset: number = 0 + filename: string + format: string = "" + mime: string = "" + audio?: Uint8Array + blob?: Blob + oriMeta?: NcmMusicMeta + newMeta?: IMusicMeta + image?: { mime: string, buffer: ArrayBuffer, url: string } + + constructor(buf: ArrayBuffer, filename: string) { + const prefix = new Uint8Array(buf, 0, 8) + if (!BytesHasPrefix(prefix, MagicHeader)) throw Error("此ncm文件已损坏") + this.offset = 10 + this.raw = buf + this.view = new DataView(buf) + this.filename = filename + } + + _getKeyData(): Uint8Array { + const keyLen = this.view.getUint32(this.offset, true); + this.offset += 4; + const cipherText = new Uint8Array(this.raw, this.offset, keyLen) + .map(uint8 => uint8 ^ 0x64); + this.offset += keyLen; + + const plainText = CryptoJS.AES.decrypt( + // @ts-ignore + {ciphertext: CryptoJS.lib.WordArray.create(cipherText)}, + CORE_KEY, + {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7} + ); + + const result = new Uint8Array(plainText.sigBytes); + + const words = plainText.words; + const sigBytes = plainText.sigBytes; + for (let i = 0; i < sigBytes; i++) { + result[i] = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; + } + + return result.slice(17) + } + + _getKeyBox(): Uint8Array { + const keyData = this._getKeyData() + const box = new Uint8Array(Array(256).keys()); + + const keyDataLen = keyData.length; + + let j = 0; + + for (let i = 0; i < 256; i++) { + j = (box[i] + j + keyData[i % keyDataLen]) & 0xff; + [box[i], box[j]] = [box[j], box[i]]; + } + + return box.map((_, i, arr) => { + i = (i + 1) & 0xff; + const si = arr[i]; + const sj = arr[(i + si) & 0xff]; + return arr[(si + sj) & 0xff]; + }); + } + + _getMetaData(): NcmMusicMeta { + const metaDataLen = this.view.getUint32(this.offset, true); + this.offset += 4; + if (metaDataLen === 0) return {}; + + const cipherText = new Uint8Array(this.raw, this.offset, metaDataLen) + .map(data => data ^ 0x63); + this.offset += metaDataLen; + + const plainText = CryptoJS.AES.decrypt( + //@ts-ignore + { + ciphertext: CryptoJS.enc.Base64.parse( + //@ts-ignore + CryptoJS.lib.WordArray.create(cipherText.slice(22)).toString(CryptoJS.enc.Utf8) + ) + }, + META_KEY, + {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7} + ).toString(CryptoJS.enc.Utf8); + + const labelIndex = plainText.indexOf(":"); + let result: NcmMusicMeta; + if (plainText.slice(0, labelIndex) === "dj") { + const tmp: NcmDjMeta = JSON.parse(plainText.slice(labelIndex + 1)); + result = tmp.mainMusic; + } else { + result = JSON.parse(plainText.slice(labelIndex + 1)); + } + if (!!result.albumPic) { + result.albumPic = result.albumPic.replace("http://", "https://") + "?param=500y500" + } + return result + } + + _getAudio(keyBox: Uint8Array): Uint8Array { + this.offset += this.view.getUint32(this.offset + 5, true) + 13 + const audioData = new Uint8Array(this.raw, this.offset) + let lenAudioData = audioData.length + for (let cur = 0; cur < lenAudioData; ++cur) audioData[cur] ^= keyBox[cur & 0xff] + return audioData + } + + async _buildMeta() { + if (!this.oriMeta) throw Error("invalid sequence") + + const info = GetMetaFromFile(this.filename, this.oriMeta.musicName) + + // build artists + let artists: string[] = []; + if (!!this.oriMeta.artist) { + this.oriMeta.artist.forEach(arr => artists.push(arr[0])); + } + + if (artists.length === 0 && !!info.artist) { + artists = info.artist.split(',') + .map(val => val.trim()).filter(val => val != ""); + } + + if (this.oriMeta.albumPic) try { + this.image = await GetImageFromURL(this.oriMeta.albumPic) + while (this.image && this.image.buffer.byteLength >= 1 << 24) { + let img = await jimp.read(Buffer.from(this.image.buffer)) + await img.resize(Math.round(img.getHeight() / 2), jimp.AUTO) + this.image.buffer = await img.getBufferAsync("image/jpeg") + } + } catch (e) { + console.log("get cover image failed", e) + } + + + this.newMeta = {title: info.title, artists, album: this.oriMeta.album, picture: this.image?.buffer} + } + + async _writeMeta() { + if (!this.audio || !this.newMeta) throw Error("invalid sequence") + + if (!this.blob) this.blob = new Blob([this.audio], {type: this.mime}) + const ori = await metaParseBlob(this.blob); + + let shouldWrite = !ori.common.album && !ori.common.artists && !ori.common.title + if (shouldWrite || this.newMeta.picture) { + if (this.format === "mp3") { + this.audio = WriteMetaToMp3(Buffer.from(this.audio), this.newMeta, ori) + } else if (this.format === "flac") { + this.audio = WriteMetaToFlac(Buffer.from(this.audio), this.newMeta, ori) + } else { + console.info(`writing meta for ${this.format} is not being supported for now`) + return + } + this.blob = new Blob([this.audio], {type: this.mime}) + } + } + + gatherResult(): DecryptResult { + if (!this.newMeta) throw Error("bad sequence") + return { + status: true, + title: this.newMeta.title, + artist: this.newMeta.artists?.join("; "), + ext: this.format, + album: this.newMeta.album, + picture: this.image?.url, + file: URL.createObjectURL(this.blob), + mime: this.mime + } + } + + async decrypt() { + const keyBox = this._getKeyBox() + this.oriMeta = this._getMetaData() + this.audio = this._getAudio(keyBox) + this.format = this.oriMeta.format || SniffAudioExt(this.audio) + this.mime = AudioMimeType[this.format] + await this._buildMeta() + try { + await this._writeMeta() + } catch (e) { + console.warn("write meta data failed", e) + } + return this.gatherResult() + } + + +} + + diff --git a/src/decrypt/utils.ts b/src/decrypt/utils.ts index 194a836..c2db07d 100644 --- a/src/decrypt/utils.ts +++ b/src/decrypt/utils.ts @@ -119,7 +119,7 @@ export interface IMusicMeta { picture_desc?: string } -export function WriteMetaToMp3(audioData: ArrayBuffer, info: IMusicMeta, original: IAudioMetadata) { +export function WriteMetaToMp3(audioData: Buffer, info: IMusicMeta, original: IAudioMetadata) { const writer = new ID3Writer(audioData); // reserve original data diff --git a/src/shims-browser-id3-writer.d.ts b/src/shims-browser-id3-writer.d.ts index acd09de..48113af 100644 --- a/src/shims-browser-id3-writer.d.ts +++ b/src/shims-browser-id3-writer.d.ts @@ -4,7 +4,7 @@ declare module "browser-id3-writer" { setFrame(name: string, value: string | object | string[]) - addTag(): ArrayBuffer + addTag(): Uint8Array } }