switched router to itty-router, updated repo url in index

This commit is contained in:
uh wot 2021-11-21 01:44:24 +01:00
parent 763acaf182
commit c5e2d749e9
Signed by: uhwot
GPG Key ID: CB2454984587B781
8 changed files with 57 additions and 173 deletions

View File

@ -1,25 +0,0 @@
## Router
Selects the logic to respond to requests based on the `request` method and URL. Can be used with REST APIs or apps that require basic routing logic.
[`index.js`](https://github.com/cloudflare/worker-template-router/blob/master/index.js) is the content of the Workers script.
#### Wrangler
You can use [wrangler](https://github.com/cloudflare/wrangler) to generate a new Cloudflare Workers project based on this template by running the following command from your terminal:
```
wrangler generate myapp https://github.com/cloudflare/worker-template-router
```
Before publishing your code you need to edit `wrangler.toml` file and add your Cloudflare `account_id` - more information about publishing your code can be found [in the documentation](https://workers.cloudflare.com/docs/quickstart/configuring-and-publishing/).
Once you are ready, you can publish your code by running the following command:
```
wrangler publish
```
#### Serverless
To deploy using serverless add a [`serverless.yml`](https://serverless.com/framework/docs/providers/cloudflare/) file.

6
dist/worker.js vendored

File diff suppressed because one or more lines are too long

View File

@ -19,7 +19,7 @@
</head> </head>
<body> <body>
<h1>dzserver</h1> <h1>dzserver</h1>
<h2><a href="https://git.freezer.life/uhwot/dzserver">source code</a></h2> <h2><a href="https://git.freezerapp.xyz/uhwot/dzserver">source code</a></h2>
<br> <br>
<p>how 2 use:</p> <p>how 2 use:</p>

View File

@ -1,9 +1,7 @@
const Router = require('./router') import { Router } from 'itty-router'
const ID3Writer = require('browser-id3-writer'); const ID3Writer = require('browser-id3-writer');
addEventListener('fetch', event => { const router = Router()
event.respondWith(handleRequest(event.request))
})
const client_id = "447462" const client_id = "447462"
const client_secret = "a83bf7f38ad2f137e444727cfc3775cf" const client_secret = "a83bf7f38ad2f137e444727cfc3775cf"
@ -65,13 +63,27 @@ async function gw_api_call(method, params) {
return json.results return json.results
} }
async function handler(type, request) { let license_token
let checkForm
let sid
let access_token
router.get('/:type/:id', async request => {
const { query } = request
const url = new URL(request.url) const url = new URL(request.url)
const id = url.pathname.split('/')[2] 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 (id === NaN || (type !== 'track' && id < 0)) {
return new Response("Invalid ID", { status: 400, headers: { 'content-type': 'text/plain' } })
}
// cookie/token stuff isn't needed for m3u8 playlists // cookie/token stuff isn't needed for m3u8 playlists
if (type === 'track') { if (type === 'track') {
if (id[0] !== '-') { // checks if not user-upped track if (id >= 0) { // checks if not user-upped track
license_token = await KV.get('license_token') license_token = await KV.get('license_token')
checkForm = await KV.get('checkForm') checkForm = await KV.get('checkForm')
sid = await KV.get('sid') sid = await KV.get('sid')
@ -105,8 +117,8 @@ async function handler(type, request) {
} }
} }
format = url.searchParams.get('f') let format = query.f
if (format === null) { if (format === undefined) {
format = '320' format = '320'
} else { } else {
format = format.toLowerCase() format = format.toLowerCase()
@ -114,7 +126,7 @@ async function handler(type, request) {
let nums = [] let nums = []
Object.values(formats).forEach(f => nums.push(f.num)) Object.values(formats).forEach(f => nums.push(f.num))
index = nums.indexOf(format) let index = nums.indexOf(format)
if (index === -1) { if (index === -1) {
return new Response('Invalid format', { status: 400, headers: { 'content-type': 'text/plain' } }) return new Response('Invalid format', { status: 400, headers: { 'content-type': 'text/plain' } })
} }
@ -122,7 +134,7 @@ async function handler(type, request) {
} }
} }
let tagging = url.searchParams.get('t') let tagging = query.t
tagging = (tagging === 'true' || tagging === '1') && ['misc', '128', '320'].includes(format) tagging = (tagging === 'true' || tagging === '1') && ['misc', '128', '320'].includes(format)
switch (type) { switch (type) {
@ -132,12 +144,12 @@ async function handler(type, request) {
case 'playlist': case 'playlist':
return await m3u8(type, id, format, tagging, url.host) return await m3u8(type, id, format, tagging, url.host)
} }
} })
async function track(id, format, tagging) { async function track(id, format, tagging) {
// other users' user-upped tracks cannot be downloaded with the gw-light API // other users' user-upped tracks cannot be downloaded with the gw-light API
let json; let json;
if (id[0] !== '-') { if (id >= 0) {
json = await gw_api_call('song.getData', { 'SNG_ID': id }) json = await gw_api_call('song.getData', { 'SNG_ID': id })
if (json.constructor.name === 'Response') { if (json.constructor.name === 'Response') {
return json return json
@ -236,7 +248,7 @@ async function track(id, format, tagging) {
.setFrame('TPE2', json.ART_NAME) .setFrame('TPE2', json.ART_NAME)
if (json.ARTISTS !== undefined) { if (json.ARTISTS !== undefined) {
artist_list = []; let artist_list = [];
for (const a of json.ARTISTS) { for (const a of json.ARTISTS) {
artist_list.push(a.ART_NAME) artist_list.push(a.ART_NAME)
} }
@ -289,7 +301,7 @@ async function track(id, format, tagging) {
id = json.FALLBACK.SNG_ID id = json.FALLBACK.SNG_ID
} }
const cipher = new wasm.Cipher(id) const cipher = new wasm.Cipher(String(id))
const length = parseInt(track.headers.get('Content-Length')) const length = parseInt(track.headers.get('Content-Length'))
@ -368,9 +380,11 @@ async function m3u8(type, id, format, tagging, host) {
return new Response(list, { status: 200, headers: { 'content-type': 'audio/mpegurl' } }) return new Response(list, { status: 200, headers: { 'content-type': 'audio/mpegurl' } })
} }
async function indexHandler() { router.get('/', () => {
return new Response(require('./index.html'), { status: 200, headers: { 'content-type': 'text/html' } }) return new Response(require('./index.html'), { status: 200, headers: { 'content-type': 'text/html' } })
} })
router.all("*", () => new Response("not found", { status: 404, headers: { 'content-type': 'text/plain' } }))
async function handleRequest(request) { async function handleRequest(request) {
const r = new Router() const r = new Router()
@ -382,3 +396,7 @@ async function handleRequest(request) {
const resp = await r.route(request) const resp = await r.route(request)
return resp return resp
} }
addEventListener('fetch', event =>
event.respondWith(router.handle(event.request))
)

11
package-lock.json generated
View File

@ -10,6 +10,7 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"browser-id3-writer": "^4.4.0", "browser-id3-writer": "^4.4.0",
"itty-router": "^2.4.4",
"serverless-cloudflare-workers": "^1.2.0" "serverless-cloudflare-workers": "^1.2.0"
}, },
"devDependencies": { "devDependencies": {
@ -2399,6 +2400,11 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/itty-router": {
"version": "2.4.4",
"resolved": "https://registry.npmjs.org/itty-router/-/itty-router-2.4.4.tgz",
"integrity": "sha512-mp5i47ZotK94FHondKJTZn/0dBAFzFpZpiHWn+aCgr/sg9cIVzt1gvLCKsXMkcHgKejb9GdhqvOfh7VYJJlQoQ=="
},
"node_modules/jest-worker": { "node_modules/jest-worker": {
"version": "27.0.6", "version": "27.0.6",
"resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.0.6.tgz", "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.0.6.tgz",
@ -6806,6 +6812,11 @@
"resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz",
"integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=" "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8="
}, },
"itty-router": {
"version": "2.4.4",
"resolved": "https://registry.npmjs.org/itty-router/-/itty-router-2.4.4.tgz",
"integrity": "sha512-mp5i47ZotK94FHondKJTZn/0dBAFzFpZpiHWn+aCgr/sg9cIVzt1gvLCKsXMkcHgKejb9GdhqvOfh7VYJJlQoQ=="
},
"jest-worker": { "jest-worker": {
"version": "27.0.6", "version": "27.0.6",
"resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.0.6.tgz", "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.0.6.tgz",

View File

@ -16,6 +16,7 @@
}, },
"dependencies": { "dependencies": {
"browser-id3-writer": "^4.4.0", "browser-id3-writer": "^4.4.0",
"itty-router": "^2.4.4",
"serverless-cloudflare-workers": "^1.2.0" "serverless-cloudflare-workers": "^1.2.0"
} }
} }

121
router.js
View File

@ -1,121 +0,0 @@
/**
* Helper functions that when passed a request will return a
* boolean indicating if the request uses that HTTP method,
* header, host or referrer.
*/
const Method = method => req =>
req.method.toLowerCase() === method.toLowerCase()
const Connect = Method('connect')
const Delete = Method('delete')
const Get = Method('get')
const Head = Method('head')
const Options = Method('options')
const Patch = Method('patch')
const Post = Method('post')
const Put = Method('put')
const Trace = Method('trace')
const Header = (header, val) => req => req.headers.get(header) === val
const Host = host => Header('host', host.toLowerCase())
const Referrer = host => Header('referrer', host.toLowerCase())
const Path = regExp => req => {
const url = new URL(req.url)
const path = url.pathname
const match = path.match(regExp) || []
return match[0] === path
}
/**
* The Router handles determines which handler is matched given the
* conditions present for each request.
*/
class Router {
constructor() {
this.routes = []
}
handle(conditions, handler) {
this.routes.push({
conditions,
handler,
})
return this
}
connect(url, handler) {
return this.handle([Connect, Path(url)], handler)
}
delete(url, handler) {
return this.handle([Delete, Path(url)], handler)
}
get(url, handler) {
return this.handle([Get, Path(url)], handler)
}
head(url, handler) {
return this.handle([Head, Path(url)], handler)
}
options(url, handler) {
return this.handle([Options, Path(url)], handler)
}
patch(url, handler) {
return this.handle([Patch, Path(url)], handler)
}
post(url, handler) {
return this.handle([Post, Path(url)], handler)
}
put(url, handler) {
return this.handle([Put, Path(url)], handler)
}
trace(url, handler) {
return this.handle([Trace, Path(url)], handler)
}
all(handler) {
return this.handle([], handler)
}
route(req) {
const route = this.resolve(req)
if (route) {
return route.handler(req)
}
return new Response('resource not found', {
status: 404,
statusText: 'not found',
headers: {
'content-type': 'text/plain',
},
})
}
/**
* resolve returns the matching route for a request that returns
* true for all conditions (if any).
*/
resolve(req) {
return this.routes.find(r => {
if (!r.conditions || (Array.isArray(r) && !r.conditions.length)) {
return true
}
if (typeof r.conditions === 'function') {
return r.conditions(req)
}
return r.conditions.every(c => c(req))
})
}
}
module.exports = Router

View File

@ -7,4 +7,4 @@ kv_namespaces = [
{ binding = "KV", id = "974c0967a84e415daa054bbbcc7f80c6", preview_id = "cfcc6491f3484cbca664913836635113" } { binding = "KV", id = "974c0967a84e415daa054bbbcc7f80c6", preview_id = "cfcc6491f3484cbca664913836635113" }
] ]
vars = { ARL = "amogus" } vars = { ARL = "amogus" }
compatibility_date = "2021-11-09" compatibility_date = "2021-11-21"