diff --git a/deno.json b/deno.json new file mode 100644 index 0000000..e9eefb2 --- /dev/null +++ b/deno.json @@ -0,0 +1,14 @@ +{ + "tasks": { + "serve": "deno run --allow-net=\"https://git.cohabit.fr,localhost:$PORT,127.0.0.1:$PORT,0.0.0.0:$PORT\" ./server.ts" + }, + "fmt": { + "singleQuote": true, + "semiColons": false, + "useTabs": true + }, + "imports": { + "@std/media-types": "jsr:@std/media-types@^0.224.1", + "@std/path": "jsr:@std/path@^0.225.2" + } +} diff --git a/deno.lock b/deno.lock new file mode 100644 index 0000000..211c70a --- /dev/null +++ b/deno.lock @@ -0,0 +1,27 @@ +{ + "version": "3", + "packages": { + "specifiers": { + "jsr:@std/assert@^0.226.0": "jsr:@std/assert@0.226.0", + "jsr:@std/path@^0.225.2": "jsr:@std/path@0.225.2" + }, + "jsr": { + "@std/assert@0.226.0": { + "integrity": "0dfb5f7c7723c18cec118e080fec76ce15b4c31154b15ad2bd74822603ef75b3" + }, + "@std/path@0.225.2": { + "integrity": "0f2db41d36b50ef048dcb0399aac720a5348638dd3cb5bf80685bf2a745aa506", + "dependencies": [ + "jsr:@std/assert@^0.226.0" + ] + } + } + }, + "remote": {}, + "workspace": { + "dependencies": [ + "jsr:@std/media-types@^0.224.1", + "jsr:@std/path@^0.225.2" + ] + } +} diff --git a/server.ts b/server.ts new file mode 100644 index 0000000..80268d0 --- /dev/null +++ b/server.ts @@ -0,0 +1,39 @@ +import { contentType } from '@std/media-types' +import { extname } from '@std/path' +import { getBaseUrl, getSourceUrl } from './src/url_utils.ts' +import { toUser, toUserDomain } from './src/user_utils.ts' + +Deno.serve({ port: Number(Deno.env.get('PORT') ?? 8000) }, async (req) => { + const reqUrl = new URL(req.url) + + // Get and check user-domain and user-login + const rawUserDomain = reqUrl.hostname.split('.')[0] + const userDomain = toUserDomain(rawUserDomain) + const user = toUser(userDomain) + + console.log(`Getting portfolio of > @${user}`) + + // Get relative source path + const filePath = `.${reqUrl.pathname}` + + // Get source base url ("/dist" if available, "/" else) + const baseUrl = await getBaseUrl(user) + const fileUrl = getSourceUrl(filePath, baseUrl) + + // Get source and mime type + const response = await fetch(fileUrl) + const ext = extname(fileUrl.pathname) + const mimeType = contentType(ext) ?? 'text/plain; charset=utf-8' // Assume plain text as default. + + if (response.ok) { + // Update content-type if not bin file + if (response.headers.get('Content-Type') !== 'application/octet-stream') { + response.headers.set('Content-Type', mimeType) + } + + // Stream original file to user + return response + } + + return response +})