From bb9a76a2a1852350318998f77966c96b54887295 Mon Sep 17 00:00:00 2001 From: Flam3rboy <34555296+Flam3rboy@users.noreply.github.com> Date: Sat, 28 Nov 2020 19:31:04 +0100 Subject: [PATCH] :tada: standard client finished --- .DS_Store | Bin 0 -> 6148 bytes .vscode/launch.json | 24 +++++++++++ client/index.html | 82 +++++++++++++++++++++++++++++++++++++ package-lock.json | Bin 0 -> 46367 bytes package.json | 31 ++++++++++++++ src/Server.ts | 72 ++++++++++++++++++++++++++++++++ src/Utils.ts | 47 +++++++++++++++++++++ src/index.ts | 4 ++ src/routes/assets/index.ts | 30 ++++++++++++++ tsconfig.json | 69 +++++++++++++++++++++++++++++++ 10 files changed, 359 insertions(+) create mode 100644 .DS_Store create mode 100644 .vscode/launch.json create mode 100644 client/index.html create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 src/Server.ts create mode 100644 src/Utils.ts create mode 100644 src/index.ts create mode 100644 src/routes/assets/index.ts create mode 100644 tsconfig.json diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..348b5e54cf4a7f040e0e76f2b9cbeffd7a4cd976 GIT binary patch literal 6148 zcmeHK&1%~~5Z<-jREnUe&_fM5EcDQe4=#@Dt5B1i3JFnY4o&Jxm0AnLDoApCFb0ta z$OEL;w0V%E@6addxih=#fN*kbY03=Dexuo$S?OD`Ka4T%PvcjNxr{Lj6tQJPbBAC* z>WZ|C2a&59l2y^HJc+VAT8SpdzsLa2-5UGEGM2K0HRtbFbdsfI)$jl0t#;?p+GERJ zcO2)5V;={Td=^w;H7)(H7`q!m8YfX$9HwzKIY{JomYgPXw|E;?N%0@O?OZWjsgOSsq zkXbIjfPa~@j3p!nhyh~YVKQJ=Gs}6HuTO7H3=jiU33yiEZ^ iZN(6aTk&&HCEyom0D1;%jo<;HgMgxe8e-tDGVmMMQ(|5K literal 0 HcmV?d00001 diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..13ff7ca9 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,24 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "sourceMaps": true, + "type": "node", + "request": "launch", + "name": "Launch Program", + "program": "${workspaceFolder}/dist/index.js", + "preLaunchTask": "tsc: build - tsconfig.json", + "outFiles": ["${workspaceFolder}/dist/**/*.js"] + }, + { + "name": "Debug current file", + "program": "${file}", + "request": "launch", + "skipFiles": ["/**"], + "type": "node" + } + ] +} diff --git a/client/index.html b/client/index.html new file mode 100644 index 00000000..fc7b7a68 --- /dev/null +++ b/client/index.html @@ -0,0 +1,82 @@ + + + + + + Discord Open Source Client + + +
+ + + + + + + + + + diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..2b13235caeeb74774056337d7af6006f0246f6e5 GIT binary patch literal 46367 zcmeHw*|OqDlIVMXMOx0=a5*3$5RBbw8&-kX_vN9k3GJW_Ni1Tf``fRFKoH^x5LBM( z?CiG6vV%al!gmjM59fdW^6lGqgVV+D|Ml&=pgO#13rR<`ccPs%Ezxkyt<8(y{|~wi z-g8vbKz9-!>5ug3UCrdzlB$W5%crD&w=HhAsx3NjyK8Sn|2>Q2*PQIX_dfs;V8W-T zSNGuicWEjQOYzs(7?%C#`tJ)OEKv{*Ud3SgpZvG$S)!8?4;Cx|t>OFc)CWO-6fR$e z2cB;-OhHUaqRT7(edI^>gT`m5l0en50KSbdy0RDo3$fmXv1@ttxN^RGhwkDeS0j;F0 zT6MH)la+oU-LB11^`8G6&YrB%zjQr2mbq*v?z_S^NT zPeqG24MXI8`u^wTYhj^63;xgeWWPd;B6;S6`p9H1Px}5E$x*J|`N7Q^+NEzKq zX-uXTl2e+KGm1?KGrIT^sRL1eftFXDjiTj^DR_~VXV^f?^Q+_u-g8MjDsXLVxeRbU@4^4SMx<&=WL9V>3MW0!IpMy4M z$l}!*ykgIE)ek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ozc%1Svh3Ue z7x2rsSGT`x7qnfRb1td?ljdQaQ4j7z1e(48^F-|&u{haP-;R^Ph zpMQhm5-j>w5N)llgaIpw1!I>Rt^pq0@COZbaM0uo96z=Kz%Q-V$l~1HG~#^;QQSuJ zSYF>RUZ5gY|9lg+qxp;#&c0^4cF3XtS^kNpV~3Z1K2jPbFX2v%fV%$v$GA`$?aDj2x3lKasqWZDqp|fgVKT|rIarn3Z#G=S~(qRf- z$BakOFU;fE+|sD=MZOFO;U6wi#%0_saA4r=TYtvvX1t&p zjodpi#|0|FDk#~0^|mERoN|~Cr#T+cE5=8A#3nt~oBxjPcD2#%lQ?1Fz_%;WQ6(^$5 z{&lA2hWP!d=n{o{xDFGSUBMy@e!?-g(L#@> z`Cc1w8y1gXdhFfM2G2dmmW%)@B5Cm251F5)-~QNq+6SlG{+UP8hFFFlFuTh&2+dyh z-8f)i9DWJBL&4tDhRZLTD0@SJOIv@m9eC%bLVoIbu+cUkIGOP0&4LZFA>1Pz#fe{f zlIu;c<;($R9@ypX5>A4>MIm27e(*~n32jBne%xjI-zWe3d`*o0i&uaaS zyA>3%LlGHwR;V6youi08MdfGT?wltF`LoD?#4zd->g1}3Z@1ywp;@c`y*tr%R1^K8 z71W->t!Qw6%n=ILZ8+Lu;EvFLh6*P(YxGxC&h;YhV|o@{-)_k+V4xJoQ5fY&R(gw z!NmuLoo0)^9PaoBx>PjM`uqxT{#k~UMw^mw0S&rX@q`(2L6@91@&>{51D}$C%?|qF z{Pg<2^mx&bfL(gaq7B14%Jt*Nc!pOT>dw8l?AJHr*w{_b4D8Cc2;m6ilP!NTgfoP| TPd-31wANo^{N-Q%_Lu(;72T)C literal 0 HcmV?d00001 diff --git a/package.json b/package.json new file mode 100644 index 00000000..0e3eca53 --- /dev/null +++ b/package.json @@ -0,0 +1,31 @@ +{ + "name": "discord-server-opensource", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Trenite/discord-server-opensource.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/Trenite/discord-server-opensource/issues" + }, + "homepage": "https://github.com/Trenite/discord-server-opensource#readme", + "devDependencies": { + "@types/node": "^14.14.10", + "typescript": "^4.1.2" + }, + "dependencies": { + "@types/express": "^4.17.9", + "@types/node-fetch": "^2.5.7", + "express": "^4.17.1", + "express-cache-middleware": "^1.0.1", + "node-fetch": "^2.6.1" + } +} diff --git a/src/Server.ts b/src/Server.ts new file mode 100644 index 00000000..ca03e0d2 --- /dev/null +++ b/src/Server.ts @@ -0,0 +1,72 @@ +import express, { Application, Router } from "express"; +import { traverseDirectory } from "./Utils"; +import { Server as HTTPServer } from "http"; +import fetch from "node-fetch"; +import fs from "fs/promises"; + +export type ServerOptions = { + port: number; +}; + +export class Server { + private app: Application; + private http: HTTPServer; + private options: ServerOptions; + private routes: Router[]; + private initalized: Promise; + + constructor(opts: ServerOptions = { port: 8080 }) { + this.options = opts; + + this.app = express(); + + this.initalized = this.init(); + } + + async init() { + // recursively loads files in routes/ + this.routes = await this.registerRoutes(__dirname + "/routes/"); + // const indexHTML = await (await fetch("https://discord.com/app")).buffer(); + const indexHTML = await fs.readFile(__dirname + "/../client/index.html"); + + this.app.get("*", (req, res) => { + res.set("Cache-Control", "public, max-age=" + 60 * 60 * 24); + res.set("content-type", "text/html"); + res.send(indexHTML); + }); + } + + async start() { + await this.initalized; + await new Promise((res) => this.app.listen(this.options.port, () => res())); + console.log(`[Server] started on ${this.options.port}`); + } + + async registerRoutes(root: string) { + return await traverseDirectory({ dirname: root, recursive: true }, this.registerRoute.bind(this, root)); + } + + registerRoute(root: string, file: string): any { + if (root.endsWith("/") || root.endsWith("\\")) root = root.slice(0, -1); // removes slash at the end of the root dir + let path = file.replace(root, ""); // remove root from path and + path = path.split(".").slice(0, -1).join("."); // trancate .js/.ts file extension of path + if (path.endsWith("/index")) path = path.slice(0, -6); // delete index from path + + try { + var router = require(file); + if (router.router) router = router.router; + if (router.default) router = router.default; + if (!router || router.prototype.constructor.name !== "router") + throw `File doesn't export any default router`; + this.app.use(path, router); + console.log(`[Server] Route ${path} registerd`); + return router; + } catch (error) { + console.error(new Error(`[Server] Failed to register route ${file}: ${error}`)); + } + } + + async stop() { + return new Promise((res) => this.http.close(() => res())); + } +} diff --git a/src/Utils.ts b/src/Utils.ts new file mode 100644 index 00000000..09d8e8c6 --- /dev/null +++ b/src/Utils.ts @@ -0,0 +1,47 @@ +import fs from "fs/promises"; + +declare global { + interface Array { + flat(): T; + } +} + +Array.prototype.flat = function () { + return this.reduce((acc, val) => (Array.isArray(val) ? acc.concat(val.flat()) : acc.concat(val)), []); +}; + +export interface traverseDirectoryOptions { + dirname: string; + filter?: RegExp; + excludeDirs?: RegExp; + recursive?: boolean; +} + +const DEFAULT_EXCLUDE_DIR = /^\./; +const DEFAULT_FILTER = /^([^\.].*)\.js$/; + +export async function traverseDirectory( + options: traverseDirectoryOptions, + action: (path: string) => T +): Promise { + if (!options.filter) options.filter = DEFAULT_FILTER; + if (!options.excludeDirs) options.excludeDirs = DEFAULT_EXCLUDE_DIR; + + const routes = await fs.readdir(options.dirname); + const promises = []>routes.map(async (file) => { + const path = options.dirname + file; + const stat = await fs.lstat(path); + if (path.match(options.excludeDirs)) return; + + if (stat.isFile() && path.match(options.filter)) { + return action(path); + } else if (options.recursive && stat.isDirectory()) { + return traverseDirectory({ ...options, dirname: path + "/" }, action); + } + }); + const result = await Promise.all(promises); + + const t = <(T | undefined)[]>result.flat(); + + return t.filter((x) => x != undefined); +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 00000000..8765d6dc --- /dev/null +++ b/src/index.ts @@ -0,0 +1,4 @@ +import { Server } from "./Server"; + +const server = new Server(); +server.start().catch(console.error); diff --git a/src/routes/assets/index.ts b/src/routes/assets/index.ts new file mode 100644 index 00000000..d3683f43 --- /dev/null +++ b/src/routes/assets/index.ts @@ -0,0 +1,30 @@ +import { Router } from "express"; +import fetch from "node-fetch"; + +const router = Router(); +const cache = new Map(); +const assetEndpoint = "https://discord.com/assets/"; + +export async function getCache(key: string): Promise { + let cachedRessource = cache.get(key); + + if (!cachedRessource) { + const res = await fetch(assetEndpoint + key); + // @ts-ignore + res.bufferResponse = await res.buffer(); + cache.set(key, res); + cachedRessource = res; + } + + return cachedRessource; +} + +router.get("/:hash", async (req, res) => { + res.set("Cache-Control", "public, max-age=" + 60 * 60 * 24); + const cache = await getCache(req.params.hash); + res.set("content-type", cache.headers.get("content-type")); + // @ts-ignore + res.send(cache.bufferResponse); +}); + +export default router; diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..2f90c121 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,69 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig.json to read more about this file */ + + /* Basic Options */ + // "incremental": true, /* Enable incremental compilation */ + "target": "ES6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, + "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, + "lib": ["ES2015", "DOM"] /* Specify library files to be included in the compilation. */, + "allowJs": true /* Allow javascript files to be compiled. */, + "checkJs": true /* Report errors in .js files. */, + // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ + "declaration": true /* Generates corresponding '.d.ts' file. */, + "declarationMap": true /* Generates a sourcemap for each corresponding '.d.ts' file. */, + "sourceMap": true /* Generates corresponding '.map' file. */, + // "outFile": "./", /* Concatenate and emit output to single file. */ + "outDir": "./dist/" /* Redirect output structure to the directory. */, + "rootDir": "./src/" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */, + // "composite": true, /* Enable project compilation */ + // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ + // "removeComments": true, /* Do not emit comments to output. */ + // "noEmit": true, /* Do not emit outputs. */ + // "importHelpers": true, /* Import emit helpers from 'tslib'. */ + // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ + // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ + + /* Strict Type-Checking Options */ + "strict": true /* Enable all strict type-checking options. */, + "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */, + // "strictNullChecks": true, /* Enable strict null checks. */ + // "strictFunctionTypes": true, /* Enable strict checking of function types. */ + // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ + "strictPropertyInitialization": false /* Enable strict checking of property initialization in classes. */, + // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ + "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */, + + /* Additional Checks */ + // "noUnusedLocals": true, /* Report errors on unused locals. */ + // "noUnusedParameters": true, /* Report errors on unused parameters. */ + // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ + // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ + + /* Module Resolution Options */ + // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ + // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ + // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ + // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ + // "typeRoots": [], /* List of folders to include type definitions from. */ + "types": ["node"] /* Type declaration files to be included in compilation. */, + // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ + "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, + // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + + /* Source Map Options */ + // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ + // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ + + /* Experimental Options */ + // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ + // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ + + /* Advanced Options */ + "skipLibCheck": true /* Skip type checking of declaration files. */, + "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ + } +}