initial commit
commit
55346005ef
|
@ -0,0 +1,2 @@
|
|||
dist
|
||||
node_modules
|
|
@ -0,0 +1,18 @@
|
|||
module.exports = {
|
||||
env: {
|
||||
es6: true,
|
||||
node: true,
|
||||
},
|
||||
extends: ['airbnb-typescript/base', 'prettier'],
|
||||
globals: {
|
||||
Atomics: 'readonly',
|
||||
SharedArrayBuffer: 'readonly',
|
||||
},
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
ecmaVersion: 2018,
|
||||
sourceType: 'module',
|
||||
},
|
||||
plugins: ['@typescript-eslint', 'prettier'],
|
||||
rules: {},
|
||||
};
|
|
@ -0,0 +1,2 @@
|
|||
node_modules
|
||||
dist
|
|
@ -0,0 +1,7 @@
|
|||
module.exports = {
|
||||
semi: true,
|
||||
printWidth: 100,
|
||||
singleQuote: true,
|
||||
trailingComma: 'all',
|
||||
bracketSpacing: true,
|
||||
};
|
|
@ -0,0 +1,20 @@
|
|||
FROM node:16-alpine as builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY package.json .
|
||||
COPY yarn.lock .
|
||||
COPY tsconfig.json .
|
||||
COPY src .
|
||||
RUN yarn install
|
||||
RUN yarn build
|
||||
|
||||
FROM node:16-alpine as runner
|
||||
|
||||
WORKDIR /app
|
||||
# reducing container size by eliminating build-only dependencies
|
||||
COPY package.json .
|
||||
ENV NODE_ENV=production
|
||||
RUN yarn install --prod
|
||||
COPY --from=builder /app/dist /app/dist
|
||||
EXPOSE 8009
|
||||
CMD ["yarn", "start"]
|
|
@ -0,0 +1,10 @@
|
|||
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
|
||||
Version 2, December 2004
|
||||
Copyright (C) 2004 Sam Hocevar
|
||||
14 rue de Plaisance, 75014 Paris, France
|
||||
Everyone is permitted to copy and distribute verbatim or modified
|
||||
copies of this license document, and changing it is allowed as long
|
||||
as the name is changed.
|
||||
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
0. You just DO WHAT THE FUCK YOU WANT TO.
|
|
@ -0,0 +1,3 @@
|
|||
# why-is-synapse
|
||||
|
||||
no, seriously. I have no idea how to actually fix broken medias on my Synapse server, so I created this [bodge](https://en.wiktionary.org/wiki/bodge) to workaround this.
|
|
@ -0,0 +1,32 @@
|
|||
{
|
||||
"name": "why-is-synapse",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"repository": "https://git.sakamoto.pl/selfisekai/why-is-synapse.git",
|
||||
"author": "Lauren Liberda <lauren@selfisekai.rocks>",
|
||||
"license": "WTFPL",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"dev": "ts-node src/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@koa/router": "^10.0.0",
|
||||
"got": "^11.8.2",
|
||||
"koa": "^2.13.1",
|
||||
"sharp": "^0.28.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/koa": "^2.13.1",
|
||||
"@types/koa__router": "^8.0.4",
|
||||
"@types/sharp": "^0.28.1",
|
||||
"@typescript-eslint/eslint-plugin": "^4.23.0",
|
||||
"@typescript-eslint/parser": "^4.23.0",
|
||||
"eslint": "^7.26.0",
|
||||
"eslint-config-airbnb-typescript": "^12.3.1",
|
||||
"eslint-config-prettier": "^8.3.0",
|
||||
"prettier": "^2.3.0",
|
||||
"ts-node": "^9.1.1",
|
||||
"typescript": "^4.2.4"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,192 @@
|
|||
import Koa from 'koa';
|
||||
import Router from '@koa/router';
|
||||
import Got, { Response } from 'got';
|
||||
import sharp from 'sharp';
|
||||
import dns from 'dns/promises';
|
||||
import assert from 'assert';
|
||||
|
||||
const { DEST_SERVER, SERVER_PRETTY_NAME, LISTENING_PORT } = process.env;
|
||||
assert(DEST_SERVER, 'missing DEST_SERVER env variable');
|
||||
assert(SERVER_PRETTY_NAME, 'missing SERVER_PRETTY_NAME env variable');
|
||||
const FUCKED_UP_SERVERS = ['matrix.org'];
|
||||
const got = Got.extend({
|
||||
headers: {
|
||||
'User-Agent': 'why-is-synapse (https://git.sakamoto.pl/selfisekai/why-is-synapse)',
|
||||
},
|
||||
throwHttpErrors: false,
|
||||
hooks: {
|
||||
beforeRequest: [(req) => console.log(`${req.method} ${req.url.href}`)],
|
||||
},
|
||||
});
|
||||
|
||||
const serverHostnameCache = new Map<string, string>();
|
||||
|
||||
const getServerHostname = async (serverName: string) => {
|
||||
const cached = serverHostnameCache.get(serverName);
|
||||
if (cached) return cached;
|
||||
|
||||
const jsonRes = await got.get(`https://${serverName}/.well-known/matrix/server`);
|
||||
if (jsonRes.statusCode === 200) {
|
||||
let res = JSON.parse(jsonRes.body)['m.server'];
|
||||
if (typeof res === 'string') {
|
||||
if (!res.includes(':')) {
|
||||
res += ':8448'; // default port per spec
|
||||
}
|
||||
serverHostnameCache.set(serverName, res);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
const dnsRes = await dns.resolveSrv(`_matrix._tcp.${serverName}`).catch(() => []);
|
||||
if (dnsRes.length > 0) {
|
||||
dnsRes.sort((a, b) => a.priority - b.priority);
|
||||
console.log(dnsRes);
|
||||
const res = `${dnsRes[0].name}:${dnsRes[0].port}`;
|
||||
serverHostnameCache.set(serverName, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
// if there are no SRV/well-known specs, assume the defaults
|
||||
return `${serverName}:8448`;
|
||||
};
|
||||
|
||||
const koa = new Koa();
|
||||
const router = new Router({
|
||||
prefix: '/_matrix',
|
||||
});
|
||||
const media = new Router();
|
||||
|
||||
media.get(
|
||||
['/download/:serverName/:mediaId', '/download/:serverName/:mediaId/:filename'],
|
||||
async (ctx) => {
|
||||
const { serverName, mediaId, filename } = ctx.params;
|
||||
|
||||
function sendFile(f: Response<Buffer>) {
|
||||
ctx.res.statusCode = 200;
|
||||
(
|
||||
['content-type', filename ? 'content-disposition' : null].filter(
|
||||
(header) => header,
|
||||
) as string[]
|
||||
).forEach((header) => {
|
||||
if (!f) return; // typescript is bork
|
||||
const val = f.headers[header];
|
||||
if (!val) return;
|
||||
ctx.res.setHeader(header, val);
|
||||
});
|
||||
if (filename) {
|
||||
ctx.res.setHeader('content-disposition', `attachment; filename="${filename}"`);
|
||||
}
|
||||
ctx.res.write(f.body);
|
||||
ctx.res.end();
|
||||
}
|
||||
|
||||
let file: Response<Buffer> | null = null;
|
||||
if (!FUCKED_UP_SERVERS.includes(serverName)) {
|
||||
file = await got.get(`${DEST_SERVER}/_matrix/media/r0/download/${serverName}/${mediaId}`, {
|
||||
responseType: 'buffer',
|
||||
});
|
||||
if (file && file.statusCode === 200) {
|
||||
sendFile(file);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (serverName === SERVER_PRETTY_NAME) {
|
||||
ctx.res.statusCode = 500;
|
||||
return;
|
||||
}
|
||||
|
||||
const remoteHost = await getServerHostname(serverName);
|
||||
file = await got.get(
|
||||
`https://${remoteHost}/_matrix/media/r0/download/${serverName}/${mediaId}`,
|
||||
{
|
||||
responseType: 'buffer',
|
||||
},
|
||||
);
|
||||
if (file && file.statusCode === 200) {
|
||||
sendFile(file);
|
||||
return;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
media.get('/thumbnail/:serverName/:mediaId', async (ctx) => {
|
||||
const { serverName, mediaId } = ctx.params;
|
||||
if (typeof ctx.query.width !== 'string' || typeof ctx.query.height !== 'string') return;
|
||||
const width = parseInt(ctx.query.width, 10);
|
||||
const height = parseInt(ctx.query.height, 10);
|
||||
|
||||
let file: Response<Buffer> | null = null;
|
||||
if (!FUCKED_UP_SERVERS.includes(serverName)) {
|
||||
file = await got.get(`${DEST_SERVER}/_matrix/media/r0/download/${serverName}/${mediaId}`, {
|
||||
responseType: 'buffer',
|
||||
});
|
||||
}
|
||||
|
||||
if (!file || file.statusCode !== 200) {
|
||||
if (serverName === SERVER_PRETTY_NAME) {
|
||||
ctx.res.statusCode = 500;
|
||||
return;
|
||||
}
|
||||
const remoteHost = await getServerHostname(serverName);
|
||||
file = await got.get(
|
||||
`https://${remoteHost}/_matrix/media/r0/download/${serverName}/${mediaId}`,
|
||||
{
|
||||
responseType: 'buffer',
|
||||
},
|
||||
);
|
||||
}
|
||||
if (file && file.statusCode === 200) {
|
||||
const img = await sharp(file.body).resize(width, height).toBuffer({ resolveWithObject: true });
|
||||
ctx.res.statusCode = 200;
|
||||
ctx.res.setHeader('content-type', `image/${img.info.format}`);
|
||||
ctx.res.write(img.data);
|
||||
ctx.res.end();
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
media.post('/upload', async (ctx) => {
|
||||
for (let retry = 0; retry < 15; retry += 1) {
|
||||
const res = await got.post(`${DEST_SERVER}/_matrix/media/r0/upload`, {
|
||||
body: ctx.body,
|
||||
headers: {
|
||||
authorization: ctx.headers['authorization'],
|
||||
'content-type': ctx.headers['content-type'],
|
||||
},
|
||||
responseType: 'buffer',
|
||||
});
|
||||
if (res.statusCode === 200) {
|
||||
ctx.res.statusCode = 200;
|
||||
ctx.res.setHeader('content-type', 'application/json');
|
||||
ctx.res.write(res.body);
|
||||
ctx.res.end();
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
router.use('/media/r0', media.routes(), media.allowedMethods());
|
||||
|
||||
router.all('/:idc+', async (ctx) => {
|
||||
const req = await got(DEST_SERVER + ctx.path + '?' + ctx.querystring, {
|
||||
// @ts-ignore
|
||||
method: ctx.req.method,
|
||||
body: ctx.body,
|
||||
responseType: 'buffer',
|
||||
headers: {
|
||||
Authorization: ctx.headers['authorization'],
|
||||
},
|
||||
});
|
||||
ctx.res.statusCode = req.statusCode;
|
||||
Object.keys(req.headers).forEach((h) => {
|
||||
const val = req.headers[h];
|
||||
if (typeof val === 'undefined') return;
|
||||
ctx.res.setHeader(h, val);
|
||||
});
|
||||
ctx.res.write(req.body);
|
||||
ctx.res.end();
|
||||
});
|
||||
|
||||
koa.use(router.routes()).use(router.allowedMethods());
|
||||
koa.listen(parseInt(LISTENING_PORT || '8009', 10));
|
|
@ -0,0 +1,71 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig.json to read more about this file */
|
||||
|
||||
/* Basic Options */
|
||||
// "incremental": true, /* Enable incremental compilation */
|
||||
"target": "esnext" /* 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": [], /* 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', 'react', 'react-jsx' or 'react-jsxdev'. */
|
||||
// "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": "./", /* 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": true, /* 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. */
|
||||
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
|
||||
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
|
||||
|
||||
/* 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": [], /* 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. */
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue