switched to different method of getting stream urls cause of retarded quota

This commit is contained in:
uh wot 2021-09-01 21:40:01 +02:00
parent e28ad54c6b
commit 695fd9ebc2
Signed by: uhwot
GPG Key ID: CB2454984587B781
5 changed files with 166 additions and 89 deletions

6
dist/worker.js vendored

File diff suppressed because one or more lines are too long

View File

@ -31,7 +31,7 @@
<p>params are:</p>
<p><b>t: tagging</b>, boolean</p>
<p><b>f: format</b>, can be one of these:</p>
<p>aac_96, 64, 128, 320, flac, mp4_ra1, mp4_ra2, mp4_ra3, mhm1_ra1, mhm1_ra2, mhm1, sbc_256, misc</p>
<p>aac_96, 64, 128, 320, flac, mp4_ra1, mp4_ra2, mp4_ra3, mhm1_ra1, mhm1_ra2, mhm1_ra3, sbc_256, misc</p>
<p>available formats depend on the track</p>
</body>
</html>

230
index.js
View File

@ -16,12 +16,89 @@ const format_string_to_num = {
'mp4_ra3': '15',
'mhm1_ra1': '16',
'mhm1_ra2': '17',
'mhm1': '18',
'mhm1_ra3': '18',
'sbc_256': '12',
'misc': '0',
}
const format_string_to_gw = {
'aac_96': 'AAC_96',
'64': 'MP3_64',
'128': 'MP3_128',
'320': 'MP3_320',
'flac': 'FLAC',
'mp4_ra1': 'MP4_RA1',
'mp4_ra2': 'MP4_RA2',
'mp4_ra3': 'MP4_RA3',
'mhm1_ra1': 'MHM1_RA1',
'mhm1_ra2': 'MHM1_RA2',
'mhm1_ra3': 'MHM1_RA3',
'sbc_256': 'SBC_256',
'misc': 'MP3_MISC',
}
async function gw_api_call(method, params) {
if (method === 'deezer.getUserData') {
checkForm = ''
}
if (!params) {
params = {}
}
let cookies = `arl=${ARL}`
if (sid) {
cookies += `; sid=${sid}`
}
const headers = new Headers({ 'cookie': cookies })
const init = {
method: 'POST',
headers: headers,
body: JSON.stringify(params),
}
const response = await fetch(`https://www.deezer.com/ajax/gw-light.php?method=${method}&input=3&api_version=1.0&api_token=${checkForm}`, init)
const json = await response.json()
if (json.error.length !== 0) {
return new Response(JSON.stringify(json.error), { status: 500, headers: { 'content-type': 'application/json' } })
}
if (method === "deezer.getUserData") {
checkForm = json.results.checkForm
await KV.put('checkForm', checkForm)
sid = response.headers.get('set-cookie').split(',').map(v => v.trimStart())[0]
sid = sid.match(/^sid=(fr[\da-f]+)/)[1]
await KV.put('sid', sid)
}
return json.results
}
async function handler(type, request) {
license_token = await KV.get('license_token')
checkForm = await KV.get('checkForm')
sid = await KV.get('sid')
if (license_token === null) {
const user_data = await gw_api_call('deezer.getUserData')
if (user_data.constructor.name === 'Response') {
return user_data
}
if (user_data.USER.USER_ID === 0) {
return new Response('Invalid arl', { status: 500, headers: { 'content-type': 'text/plain' } })
}
license_token = user_data.USER.OPTIONS.license_token
const expiration = user_data.USER.OPTIONS.expiration_timestamp
await KV.put('license_token', license_token, { expiration: expiration })
}
const url = new URL(request.url)
const id = url.pathname.split('/')[2]
@ -52,36 +129,60 @@ async function handler(type, request) {
}
async function track(id, format, tagging) {
const response = await fetch(`https://api.deezer.com/streaming_url.php?access_token=${ACCESS_TOKEN}&track_id=${id}`)
const json = await response.json()
if (json.error !== undefined) {
return new Response(JSON.stringify(json.error), { status: 403, headers: { 'content-type': "application/json" } })
const json = await gw_api_call('song.getData', { 'SNG_ID': id })
if (json.constructor.name === 'Response') {
return json
}
if (json.id < 0) { // user-uploaded track
if (parseInt(json.SNG_ID) < 0) { // user-uploaded track
format = 'misc'
}
if (json['FILESIZE_' + format_string_to_gw[format]] == false) {
return new Response('Format unavailable', { status: 403, headers: { 'content-type': 'text/plain' } })
}
const wasm = await import('./pkg')
encrypted = !['320', 'flac'].includes(format)
if (!encrypted) { // server-side stream url
legacy_url = !['320', 'flac'].includes(format)
if (!legacy_url) { // server-side stream url
// needed if track has fallback, like https://www.deezer.com/track/11835714
let urls
if (!json.alternative) {
urls = json
let track_token
if (json.FALLBACK !== undefined) {
track_token = json.FALLBACK.TRACK_TOKEN
} else {
const temp = await fetch(`https://api.deezer.com/streaming_url.php?access_token=${ACCESS_TOKEN}&track_id=${json.alternative.id}`)
urls = await temp.json()
track_token = json.TRACK_TOKEN
}
result = urls['url_' + format]
if (result === undefined) {
return new Response('Format unavailable', { status: 403, headers: { 'content-type': 'text/plain' } })
const body = {
license_token: license_token,
media: [
{
type: "FULL",
formats: [
{
cipher: "BF_CBC_STRIPE",
format: format_string_to_gw[format]
}
]
}
],
track_tokens: [ track_token ]
}
result = wasm.decrypt_stream_url(result)
const init = {
method: 'POST',
body: JSON.stringify(body)
}
const resp = await fetch('https://media.deezer.com/v1/get_url', init)
if (resp.status !== 200) {
return new Response("Couldn't get stream URL", { status: 403, headers: { 'content-type': 'text/plain' } })
}
const media_json = await resp.json()
result = media_json.data[0].media[0].sources[0].url
} else { // legacy stream url
result = await legacy_track_url(json, format, wasm.legacy_stream_url)
if (typeof result === 'object') {
@ -89,55 +190,48 @@ async function track(id, format, tagging) {
}
}
let track
if (tagging || encrypted) {
track = await fetch(result)
if (track.status !== 200) {
return new Response("Couldn't get track stream", { status: 403, headers: { 'content-type': 'text/plain' } })
}
const track = await fetch(result)
if (track.status !== 200) {
return new Response("Couldn't get track stream", { status: 403, headers: { 'content-type': 'text/plain' } })
}
let id3
if (tagging) {
id3 = new ID3Writer(Buffer.alloc(0));
id3.padding = 0
id3.setFrame('TIT2', json.title)
.setFrame('TALB', json.album.title)
.setFrame('TPE2', json.artist.name)
id3.setFrame('TIT2', json.SNG_TITLE)
.setFrame('TALB', json.ALB_TITLE)
.setFrame('TPE2', json.ART_NAME)
if (json.contributors !== undefined) {
contr_list = [];
for (const c of json.contributors) {
contr_list.push(c.name)
if (json.ARTISTS !== undefined) {
artist_list = [];
for (const a of json.ARTISTS) {
artist_list.push(a.ART_NAME)
}
id3.setFrame('TPE1', contr_list)
id3.setFrame('TPE1', artist_list)
}
if (json.track_position !== undefined) {
id3.setFrame('TRCK', json.track_position)
if (json.TRACK_NUMBER !== undefined) {
id3.setFrame('TRCK', json.TRACK_NUMBER)
}
if (json.disk_number !== undefined) {
id3.setFrame('TPOS', json.disk_number)
if (json.DISK_NUMBER !== undefined) {
id3.setFrame('TPOS', json.DISK_NUMBER)
}
if (json.isrc !== "") {
id3.setFrame('TSRC', json.isrc)
if (json.ISRC !== "") {
id3.setFrame('TSRC', json.ISRC)
}
if (json.bpm !== undefined) {
id3.setFrame('TBPM', json.bpm)
}
if (json.release_date !== undefined) {
const split = json.release_date.split('-')
if (json.PHYSICAL_RELEASE_DATE !== undefined) {
const split = json.PHYSICAL_RELEASE_DATE.split('-')
id3.setFrame('TYER', split[0])
id3.setFrame('TDAT', split[2] + split[1])
}
if (json.md5_image !== "") {
const url = `https://cdns-images.dzcdn.net/images/cover/${json.md5_image}/1000x1000-000000-80-0-0.jpg`
if (json.ALB_PICTURE !== "") {
const url = `https://cdns-images.dzcdn.net/images/cover/${json.ALB_PICTURE}/1000x1000-000000-80-0-0.jpg`
const cover = await fetch(url)
const coverBuffer = await cover.arrayBuffer()
@ -152,31 +246,23 @@ async function track(id, format, tagging) {
}
let { readable, writable } = new TransformStream()
let writer
if (tagging || encrypted) {
writer = writable.getWriter()
}
const writer = writable.getWriter()
if (tagging) {
writer.write(id3.arrayBuffer)
}
// needed if track has fallback, like https://www.deezer.com/track/11835714
if (json.alternative) {
id = json.alternative.id.toString()
}
if (encrypted) {
const cipher = new wasm.Cipher(id)
const length = parseInt(track.headers.get('Content-Length'))
pipeDecryptedStream(writer, track.body, length, cipher)
} else if (tagging) {
writer.releaseLock()
track.body.pipeTo(writable)
} else {
return new Response(null, { status: 302, headers: { 'location': result } })
if (json.FALLBACK) {
id = json.FALLBACK.SNG_ID
}
const cipher = new wasm.Cipher(id)
const length = parseInt(track.headers.get('Content-Length'))
pipeDecryptedStream(writer, track.body, length, cipher)
return new Response(readable, { status: 200, headers: { 'content-type': 'audio/mpeg' } })
}
@ -217,25 +303,21 @@ async function pipeDecryptedStream(writer, body, length, cipher) {
function legacy_track_url(json, format, url_func) {
// needed if track has fallback, like https://www.deezer.com/track/11835714
if (json.alternative) {
json = json.alternative
if (json.FALLBACK) {
json = json.FALLBACK
}
const id = json.id
const md5_origin = json.md5_origin
const media_version = json.media_version
if (json['filesize_' + format] == false) {
return new Response('Format unavailable', { status: 403, headers: { 'content-type': 'text/plain' } })
}
const id = json.SNG_ID.toString()
const md5_origin = json.MD5_ORIGIN
const media_version = json.MEDIA_VERSION
format = format_string_to_num[format]
return url_func(md5_origin, format, id.toString(), media_version)
return url_func(md5_origin, format, id, media_version)
}
async function m3u8(type, id, format, tagging, host) {
const response = await fetch(`https://api.deezer.com/${type}/${id}?access_token=${ACCESS_TOKEN}&limit=-1`)
const response = await fetch(`https://api.deezer.com/${type}/${id}?limit=-1`)
const json = await response.json()
if (json.error !== undefined) {
return new Response(JSON.stringify(json.error), { status: 403, headers: { 'content-type': "application/json" } })

View File

@ -1,14 +1,13 @@
use wasm_bindgen::prelude::*;
use blowfish::Blowfish;
use aes::{Aes128, Aes256};
use aes::Aes128;
use block_modes::{BlockMode, Cbc, Ecb};
use block_modes::block_padding::{NoPadding, ZeroPadding};
use md5::{Md5, Digest};
type BfCbc = Cbc<Blowfish, NoPadding>;
type Aes128Ecb = Ecb<Aes128, ZeroPadding>;
type Aes256Ecb = Ecb<Aes256, ZeroPadding>;
const TRACK_CDN_KEY: [u8; 16] = [106, 111, 54, 97, 101, 121, 54, 104, 97, 105, 100, 50, 84, 101, 105, 104];
const BF_SECRET: [u8; 16] = [103, 52, 101, 108, 53, 56, 119, 99, 48, 122, 118, 102, 57, 110, 97, 49];
@ -63,12 +62,4 @@ pub fn legacy_stream_url(md5_origin: &str, format: &str, id: &str, media_version
let ciphertext = cipher.encrypt_vec(&metadata_hash);
format!("https://cdns-proxy-{}.dzcdn.net/mobile/1/{}", md5_origin.chars().next().unwrap(), hex::encode(ciphertext))
}
#[wasm_bindgen]
pub fn decrypt_stream_url(url: &str) -> String {
let url = hex::decode(url).unwrap();
let cipher = Aes256Ecb::new_from_slices("2f5b4c9785ddc367975b83d90dc46f5c".as_bytes(), Default::default()).unwrap();
let url = cipher.decrypt_vec(&url).unwrap();
String::from_utf8_lossy(&url).into_owned()
}

View File

@ -2,4 +2,8 @@ name = "dz"
type = "webpack"
webpack_config = "webpack.config.js"
account_id = "03479b0523a52b140e0dabac40cb0fc8"
workers_dev = true
workers_dev = true
kv_namespaces = [
{ binding = "KV", id = "974c0967a84e415daa054bbbcc7f80c6", preview_id = "cfcc6491f3484cbca664913836635113" }
]
vars = { ARL = "haha nope" }