updated dependencies, added IPLS tag, rewrote stuff with epic itty-router features

This commit is contained in:
uh wot 2023-07-01 21:12:45 +02:00
parent c09a27e99b
commit 7f6c507926
Signed by: uhwot
GPG Key ID: CB2454984587B781
7 changed files with 998 additions and 614 deletions

6
.gitignore vendored
View File

@ -3,6 +3,8 @@ node_modules/
wasm/pkg/
wasm/target
wasm/Cargo.lock
wasm/wasm-pack.log
wasm/.cargo-ok
wasm/.cargo-ok
.wrangler
.dev.vars

182
main.js
View File

@ -1,10 +1,8 @@
import html from './index.html'
import index_html from './index.html'
import { Cipher, legacy_stream_url } from './wasm/pkg'
import { Router } from 'itty-router'
import ID3Writer from 'browser-id3-writer'
const router = Router()
import { error, json as jsonResp, html, Router, createResponse } from 'itty-router'
import { ID3Writer } from 'browser-id3-writer'
const client_id = "447462"
const client_secret = "a83bf7f38ad2f137e444727cfc3775cf"
@ -25,7 +23,49 @@ const formats = {
misc: { num: '0', gw: 'MP3_MISC', mime: 'audio/mpeg', ext: 'mp3' },
}
async function gw_api_call(method, params) {
async function track_req(request, env) {
const { query } = request
let { type, id } = request.params
if (!['track', 'album', 'playlist'].includes(type)) {
return error(404)
}
id = parseInt(id)
if (isNaN(id) || (type !== 'track' && id < 0)) {
return error(400, 'Invalid ID')
}
let format = query.f
if (format === undefined) {
format = '320'
} else {
format = format.toLowerCase()
if (formats[format] === undefined) {
let nums = []
Object.values(formats).forEach(f => nums.push(f.num))
let index = nums.indexOf(format)
if (index === -1) {
return error(400, 'Invalid format')
}
format = Object.keys(formats)[index]
}
}
let tagging = query.t
tagging = (tagging === 'true' || tagging === '1') && (['misc', '128', '320'].includes(format) || type !== 'track')
switch (type) {
case 'track':
return await track(env, id, format, tagging, request.headers.get('range'))
case 'album':
case 'playlist':
return await m3u8(type, id, format, tagging, request.headers.get('host'))
}
}
async function gw_api_call(env, method, params) {
if (method === 'deezer.getUserData') {
checkForm = ''
}
@ -34,7 +74,7 @@ async function gw_api_call(method, params) {
params = {}
}
let cookies = `arl=${ARL}`
let cookies = `arl=${env.ARL}`
if (sid) {
cookies += `; sid=${sid}`
}
@ -54,116 +94,74 @@ async function gw_api_call(method, params) {
const json = await response.json()
if (json.error.length !== 0) {
return new Response(JSON.stringify(json.error), { status: 500, headers: { 'content-type': 'application/json' } })
return error(500, {error: json.error})
}
if (method === 'deezer.getUserData') {
checkForm = json.results.checkForm
await KV.put('checkForm', checkForm)
await env.KV.put('checkForm', checkForm)
sid = json.results.SESSION_ID
await KV.put('sid', sid)
await env.KV.put('sid', sid)
}
return json.results
}
router.get('/:type/:id', async request => {
const { query } = request
let { type, id } = request.params
if (!['track', 'album', 'playlist'].includes(type)) {
return new Response("not found", { status: 404, headers: { 'content-type': 'text/plain' } })
}
id = parseInt(id)
if (isNaN(id) || (type !== 'track' && id < 0)) {
return new Response("Invalid ID", { status: 400, headers: { 'content-type': 'text/plain' } })
}
let format = query.f
if (format === undefined) {
format = '320'
} else {
format = format.toLowerCase()
if (formats[format] === undefined) {
let nums = []
Object.values(formats).forEach(f => nums.push(f.num))
let index = nums.indexOf(format)
if (index === -1) {
return new Response('Invalid format', { status: 400, headers: { 'content-type': 'text/plain' } })
}
format = Object.keys(formats)[index]
}
}
let tagging = query.t
tagging = (tagging === 'true' || tagging === '1') && (['misc', '128', '320'].includes(format) || type !== 'track')
switch (type) {
case 'track':
return await track(id, format, tagging, request.headers.get('range'))
case 'album':
case 'playlist':
return await m3u8(type, id, format, tagging, request.headers.get('host'))
}
})
let license_token
let checkForm
let sid
async function auth_gw() {
license_token = await KV.get('license_token')
checkForm = await KV.get('checkForm')
sid = await KV.get('sid')
async function auth_gw(env) {
license_token = await env.KV.get('license_token')
checkForm = await env.KV.get('checkForm')
sid = await env.KV.get('sid')
if (license_token === null) {
const user_data = await gw_api_call('deezer.getUserData')
const user_data = await gw_api_call(env, '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' } })
return error(500, 'Invalid arl')
}
license_token = user_data.USER.OPTIONS.license_token
await KV.put('license_token', license_token, { expirationTtl: 3600 })
await env.KV.put('license_token', license_token, { expirationTtl: 3600 })
}
}
let access_token
async function auth_dzapi() {
access_token = await KV.get('access_token')
async function auth_dzapi(env) {
access_token = await env.KV.get('access_token')
if (access_token === null) {
const response = await fetch(`https://connect.deezer.com/oauth/access_token.php?grant_type=client_credentials&client_id=${client_id}&client_secret=${client_secret}&output=json`)
const json = await response.json()
if (json.error !== undefined) {
return new Response("Couldn't get access token from Deezer", { status: 500, headers: { 'content-type': 'text/plain' } })
return error(500, "Couldn't get access token from Deezer")
}
access_token = json.access_token
await KV.put('access_token', access_token, { expirationTtl: parseInt(json.expires) })
await env.KV.put('access_token', access_token, { expirationTtl: parseInt(json.expires) })
}
}
async function track(id, format, tagging, range_header) {
async function track(env, id, format, tagging, range_header) {
// other users' user-upped tracks cannot be downloaded with the gw-light API
let json;
if (id >= 0) {
let err_auth = await auth_gw()
let err_auth = await auth_gw(env)
if (err_auth) {
return err_auth
}
json = await gw_api_call('song.getData', { 'SNG_ID': id })
json = await gw_api_call(env, 'song.getData', { 'SNG_ID': id })
if (json.constructor.name === 'Response') {
return json
}
} else { // user-upped track
let err_auth = await auth_dzapi()
let err_auth = await auth_dzapi(env)
if (err_auth) {
return err_auth
}
@ -171,7 +169,7 @@ async function track(id, format, tagging, range_header) {
const response = await fetch(`https://api.deezer.com/track/${id}?access_token=${access_token}`)
json = await response.json()
if (json.error !== undefined) {
return new Response(JSON.stringify(json.error), { status: 403, headers: { 'content-type': "application/json" } })
return error(403, {error: json.error})
}
json = {
@ -191,7 +189,7 @@ async function track(id, format, tagging, range_header) {
}
if (json['FILESIZE_' + formats[format].gw] == false) {
return new Response('Format unavailable', { status: 403, headers: { 'content-type': 'text/plain' } })
return error(403, 'Format unavailable')
}
let range_req = false
@ -241,7 +239,7 @@ async function track(id, format, tagging, range_header) {
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' } })
return error(403, "Couldn't get stream URL")
}
const media_json = await resp.json()
@ -249,7 +247,7 @@ async function track(id, format, tagging, range_header) {
if (media_json.data[0].media !== undefined) {
track_url = media_json.data[0].media[0].sources[0].url
} else {
return new Response("Couldn't get stream URL", { status: 403, headers: { 'content-type': 'text/plain' } })
return error(403, "Couldn't get stream URL")
}
} else { // legacy stream url
track_url = legacy_track_url(json, format)
@ -287,6 +285,17 @@ async function track(id, format, tagging, range_header) {
id3.setFrame('TPE1', artist_list)
}
if (json.SNG_CONTRIBUTORS !== undefined) {
let involved_people = []
for (const [role, contributors] of Object.entries(json.SNG_CONTRIBUTORS)) {
for (const contributor of contributors) {
involved_people.push([role, contributor])
}
}
id3.setFrame('IPLS', involved_people)
}
if (json.TRACK_NUMBER !== undefined) {
id3.setFrame('TRCK', json.TRACK_NUMBER)
}
@ -338,7 +347,7 @@ async function track(id, format, tagging, range_header) {
}
if (range_start < 0 || range_end < range_start) {
return new Response('Invalid range', { status: 416, headers: { 'content-type': 'text/plain' } })
return error(416, 'Invalid range')
}
trk_range_start = range_start
@ -387,9 +396,9 @@ async function track(id, format, tagging, range_header) {
track = await fetch(track_url, init)
if (![200, 206].includes(track.status)) {
if (track.status === 416) {
return new Response('Invalid range', { status: 416, headers: { 'content-type': 'text/plain' } })
return error(416, 'Invalid range')
}
return new Response("Couldn't get track stream", { status: 403, headers: { 'content-type': 'text/plain' } })
return error(403, "Couldn't get track stream")
}
let track_size
@ -484,11 +493,13 @@ function legacy_track_url(json, format) {
return legacy_stream_url(md5_origin, format, id, media_version)
}
const m3u8Resp = createResponse('audio/mpegurl')
async function m3u8(type, id, format, tagging, host) {
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' } })
return error(403, {error: json.error})
}
let list = '#EXTM3U\n'
@ -502,15 +513,20 @@ async function m3u8(type, id, format, tagging, host) {
list += `#EXTINF:${track.duration},${track.title}\n${result}\n`
}
return new Response(list, { status: 200, headers: { 'content-type': 'audio/mpegurl' } })
return m3u8Resp(list)
}
router.get('/', () => {
return new Response(html, { status: 200, headers: { 'content-type': 'text/html' } })
})
const router = Router()
router.all("*", () => new Response("not found", { status: 404, headers: { 'content-type': 'text/plain' } }))
router
.get('/:type/:id', track_req)
.get('/', () => html(index_html))
.all("*", () => error(404))
addEventListener('fetch', event =>
event.respondWith(router.handle(event.request))
)
export default {
fetch: (req, env, ctx) =>
router
.handle(req, env, ctx)
.then(jsonResp)
.catch(error), // catch errors
}

View File

@ -5,17 +5,17 @@
"main": "index.js",
"scripts": {
"dev": "wrangler dev",
"dev_local": "wrangler dev --local",
"publish": "wrangler publish",
"dev_remote": "wrangler dev --remote",
"publish": "wrangler deploy",
"wasm_build": "node wasm_build.mjs"
},
"author": "uh_wot <uhwot@protonmail.com>",
"license": "MIT",
"devDependencies": {
"wrangler": "^2.1.15"
"wrangler": "^3.1.1"
},
"dependencies": {
"browser-id3-writer": "^4.4.0",
"itty-router": "^2.6.6"
"browser-id3-writer": "^6.0.0",
"itty-router": "^4.0.13"
}
}

347
wasm/Cargo.lock generated Normal file
View File

@ -0,0 +1,347 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aes"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac1f845298e95f983ff1944b728ae08b8cebab80d684f0a832ed0fc74dfa27e2"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
]
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "block-padding"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93"
dependencies = [
"generic-array",
]
[[package]]
name = "blowfish"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7"
dependencies = [
"byteorder",
"cipher",
]
[[package]]
name = "bumpalo"
version = "3.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1"
[[package]]
name = "byteorder"
version = "1.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610"
[[package]]
name = "cbc"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6"
dependencies = [
"cipher",
]
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
dependencies = [
"cfg-if",
"wasm-bindgen",
]
[[package]]
name = "cpufeatures"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03e69e28e9f7f77debdedbaafa2866e1de9ba56df55a8bd7cfc724c25a09987c"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "dzserver"
version = "0.1.0"
dependencies = [
"aes",
"blowfish",
"cbc",
"cipher",
"hex",
"md-5",
"wasm-bindgen",
"wasm-bindgen-test",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "inout"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5"
dependencies = [
"block-padding",
"generic-array",
]
[[package]]
name = "js-sys"
version = "0.3.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "libc"
version = "0.2.147"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
[[package]]
name = "log"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4"
[[package]]
name = "md-5"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6365506850d44bff6e2fbcb5176cf63650e48bd45ef2fe2665ae1570e0f4b9ca"
dependencies = [
"digest",
]
[[package]]
name = "once_cell"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]
name = "proc-macro2"
version = "1.0.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b368fba921b0dce7e60f5e04ec15e565b3303972b42bcfde1d0713b881959eb"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "573015e8ab27661678357f27dc26460738fd2b6c86e46f386fde94cb5d913105"
dependencies = [
"proc-macro2",
]
[[package]]
name = "scoped-tls"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"
[[package]]
name = "syn"
version = "2.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2efbeae7acf4eabd6bcdcbd11c92f45231ddda7539edc7806bd1a04a03b24616"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typenum"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"
[[package]]
name = "unicode-ident"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0"
[[package]]
name = "version_check"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "wasm-bindgen"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342"
dependencies = [
"cfg-if",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd"
dependencies = [
"bumpalo",
"log",
"once_cell",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03"
dependencies = [
"cfg-if",
"js-sys",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1"
[[package]]
name = "wasm-bindgen-test"
version = "0.3.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e6e302a7ea94f83a6d09e78e7dc7d9ca7b186bc2829c24a22d0753efd680671"
dependencies = [
"console_error_panic_hook",
"js-sys",
"scoped-tls",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test-macro",
]
[[package]]
name = "wasm-bindgen-test-macro"
version = "0.3.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecb993dd8c836930ed130e020e77d9b2e65dd0fbab1b67c790b0f5d80b11a575"
dependencies = [
"proc-macro2",
"quote",
]
[[package]]
name = "web-sys"
version = "0.3.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b"
dependencies = [
"js-sys",
"wasm-bindgen",
]

View File

@ -11,7 +11,7 @@ crate-type = ["cdylib", "rlib"]
blowfish = "0.9"
aes = "0.8"
md-5 = "0.10"
cipher = { version = "0.4", features = ["block-padding"] }
cipher = { version = "0.4", features = ["block-padding", "alloc"] }
cbc = "0.1"
hex = "0.4"

View File

@ -12,7 +12,7 @@ const js_path = `pkg/${pkg_name}.js`
let loader_js = fs.readFileSync(js_path, 'utf8')
loader_js = `import wasmModule from './${pkg_name}_bg.wasm'\n\n` + loader_js
loader_js = loader_js.replace('const { TextDecoder, TextEncoder } = require(String.raw`util`);\n', '')
loader_js = loader_js.replace('const { TextDecoder, TextEncoder } = require(`util`);\n', '')
loader_js = loader_js.replace(`const path = require('path').join(__dirname, '${pkg_name}_bg.wasm');\n`, '')
loader_js = loader_js.replace("const bytes = require('fs').readFileSync(path);\n\n", '')
loader_js = loader_js.replace('const wasmModule = new WebAssembly.Module(bytes);\n', '')

1063
yarn.lock

File diff suppressed because it is too large Load Diff