Delete api
Browse files- api/.env +0 -12
- api/.env-example +0 -12
- api/.eslintignore +0 -5
- api/.eslintrc.js +0 -95
- api/.gitignore +0 -4
- api/package.json +0 -90
- api/prisma/migrations/20220420012853_init/migration.sql +0 -107
- api/prisma/migrations/20220525012308_add_password_files/migration.sql +0 -2
- api/prisma/migrations/migration_lock.toml +0 -3
- api/prisma/schema.prisma +0 -87
- api/src/Types.ts +0 -11
- api/src/api/base/Endpoint.ts +0 -151
- api/src/api/index.ts +0 -5
- api/src/api/middlewares/Auth.ts +0 -119
- api/src/api/middlewares/Key.ts +0 -10
- api/src/api/middlewares/TGClient.ts +0 -15
- api/src/api/middlewares/TGSessionAuth.ts +0 -32
- api/src/api/v1/Auth.ts +0 -468
- api/src/api/v1/Config.ts +0 -93
- api/src/api/v1/Dialogs.ts +0 -92
- api/src/api/v1/Files.ts +0 -1366
- api/src/api/v1/Messages.ts +0 -326
- api/src/api/v1/Users.ts +0 -184
- api/src/api/v1/Utils.ts +0 -23
- api/src/api/v1/index.ts +0 -22
- api/src/index.ts +0 -105
- api/src/model/index.ts +0 -3
- api/src/model/migrations/dump.20220406.sql +0 -11
- api/src/model/migrations/dump.sql +0 -244
- api/src/service/Cache.ts +0 -63
- api/src/utils/Constant.ts +0 -36
- api/src/utils/FilterQuery.ts +0 -74
- api/src/utils/ObjectParser.ts +0 -5
- api/src/utils/StringParser.ts +0 -5
- api/tsconfig.json +0 -24
- api/vercel.json +0 -21
api/.env
DELETED
|
@@ -1,12 +0,0 @@
|
|
| 1 |
-
ENV=production
|
| 2 |
-
PORT=4000
|
| 3 |
-
|
| 4 |
-
TG_API_ID=20248870
|
| 5 |
-
TG_API_HASH=0111cdf5090cde6669bc03c8bf10e733
|
| 6 |
-
ADMIN_USERNAME=UMythus
|
| 7 |
-
|
| 8 |
-
DATABASE_URL=postgres://teledrive_4k6v_user:HRPEVgDQs52tyntHz69PfeEqzgPW8Jd6@dpg-cihfmgdph6erq6ifg6gg-a/teledrive_4k6v
|
| 9 |
-
|
| 10 |
-
IS_MAINTENANCE=
|
| 11 |
-
|
| 12 |
-
CACHE_FILES_LIMIT=20GB
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/.env-example
DELETED
|
@@ -1,12 +0,0 @@
|
|
| 1 |
-
ENV=production
|
| 2 |
-
PORT=4000
|
| 3 |
-
|
| 4 |
-
TG_API_ID=
|
| 5 |
-
TG_API_HASH=
|
| 6 |
-
ADMIN_USERNAME=
|
| 7 |
-
|
| 8 |
-
DATABASE_URL=postgresql://postgres@localhost:5432/teledrive
|
| 9 |
-
|
| 10 |
-
IS_MAINTENANCE=
|
| 11 |
-
|
| 12 |
-
CACHE_FILES_LIMIT=20GB
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/.eslintignore
DELETED
|
@@ -1,5 +0,0 @@
|
|
| 1 |
-
.vscode
|
| 2 |
-
node_modules
|
| 3 |
-
dist
|
| 4 |
-
cert
|
| 5 |
-
get_env.js
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/.eslintrc.js
DELETED
|
@@ -1,95 +0,0 @@
|
|
| 1 |
-
module.exports = {
|
| 2 |
-
root: true,
|
| 3 |
-
env: {
|
| 4 |
-
node: true
|
| 5 |
-
},
|
| 6 |
-
parser: '@typescript-eslint/parser',
|
| 7 |
-
plugins: [
|
| 8 |
-
'@typescript-eslint',
|
| 9 |
-
],
|
| 10 |
-
extends: [
|
| 11 |
-
'eslint:recommended',
|
| 12 |
-
// 'plugin:@typescript-eslint/eslint-recommended',
|
| 13 |
-
'plugin:@typescript-eslint/recommended',
|
| 14 |
-
],
|
| 15 |
-
rules: {
|
| 16 |
-
'@typescript-eslint/naming-convention': [
|
| 17 |
-
'error',
|
| 18 |
-
{
|
| 19 |
-
'selector': 'variable',
|
| 20 |
-
'format': ['camelCase', 'UPPER_CASE', 'PascalCase'],
|
| 21 |
-
'leadingUnderscore': 'allow'
|
| 22 |
-
},
|
| 23 |
-
{
|
| 24 |
-
'selector': 'typeLike',
|
| 25 |
-
'format': ['PascalCase']
|
| 26 |
-
}
|
| 27 |
-
],
|
| 28 |
-
'@typescript-eslint/indent': [
|
| 29 |
-
'error',
|
| 30 |
-
2
|
| 31 |
-
],
|
| 32 |
-
'@typescript-eslint/prefer-namespace-keyword': 'error',
|
| 33 |
-
'@typescript-eslint/quotes': [
|
| 34 |
-
'error',
|
| 35 |
-
'single',
|
| 36 |
-
{
|
| 37 |
-
'avoidEscape': true
|
| 38 |
-
}
|
| 39 |
-
],
|
| 40 |
-
'@typescript-eslint/semi': [
|
| 41 |
-
'error',
|
| 42 |
-
'never'
|
| 43 |
-
],
|
| 44 |
-
'@typescript-eslint/type-annotation-spacing': 'error',
|
| 45 |
-
'@typescript-eslint/member-delimiter-style': [
|
| 46 |
-
'error',
|
| 47 |
-
{
|
| 48 |
-
'multiline': {
|
| 49 |
-
'delimiter': 'comma',
|
| 50 |
-
'requireLast': false
|
| 51 |
-
},
|
| 52 |
-
'singleline': {
|
| 53 |
-
'delimiter': 'comma',
|
| 54 |
-
'requireLast': false
|
| 55 |
-
}
|
| 56 |
-
}
|
| 57 |
-
],
|
| 58 |
-
'@typescript-eslint/no-unused-vars': [
|
| 59 |
-
'warn',
|
| 60 |
-
{
|
| 61 |
-
'vars': 'all',
|
| 62 |
-
'args': 'all',
|
| 63 |
-
'varsIgnorePattern': '^\_.*$',
|
| 64 |
-
'argsIgnorePattern': '^\_.*$',
|
| 65 |
-
}
|
| 66 |
-
],
|
| 67 |
-
'@typescript-eslint/no-extra-parens': 'error',
|
| 68 |
-
'@typescript-eslint/brace-style': 'error',
|
| 69 |
-
'@typescript-eslint/no-use-before-define': 'off',
|
| 70 |
-
'@typescript-eslint/no-explicit-any': 'off',
|
| 71 |
-
'@typescript-eslint/explicit-function-return-type': 'off',
|
| 72 |
-
'@typescript-eslint/no-namespace': 'off',
|
| 73 |
-
'@typescript-eslint/no-inferrable-types': 'off',
|
| 74 |
-
'@typescript-eslint/no-empty-function': 'off',
|
| 75 |
-
'@typescript-eslint/no-empty-interface': 'off',
|
| 76 |
-
'no-null/no-null': 'off',
|
| 77 |
-
'no-useless-escape': 'off',
|
| 78 |
-
'no-trailing-spaces': 'error',
|
| 79 |
-
'no-var': 'error',
|
| 80 |
-
'prefer-const': 'error',
|
| 81 |
-
'spaced-comment': 'error',
|
| 82 |
-
'object-curly-spacing': ['error', 'always'],
|
| 83 |
-
'space-in-parens': ['error', 'never'],
|
| 84 |
-
'array-bracket-spacing': ['error', 'never'],
|
| 85 |
-
'space-before-function-paren': [
|
| 86 |
-
'error',
|
| 87 |
-
{
|
| 88 |
-
'named': 'never',
|
| 89 |
-
'anonymous': 'always',
|
| 90 |
-
'asyncArrow': 'always'
|
| 91 |
-
}
|
| 92 |
-
],
|
| 93 |
-
'@typescript-eslint/no-var-requires': 'off'
|
| 94 |
-
}
|
| 95 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/.gitignore
DELETED
|
@@ -1,4 +0,0 @@
|
|
| 1 |
-
node_modules
|
| 2 |
-
# Keep environment variables out of version control
|
| 3 |
-
.env
|
| 4 |
-
.vercel
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/package.json
DELETED
|
@@ -1,90 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"name": "api",
|
| 3 |
-
"version": "2.5.5",
|
| 4 |
-
"main": "dist/index.js",
|
| 5 |
-
"license": "MIT",
|
| 6 |
-
"private": true,
|
| 7 |
-
"scripts": {
|
| 8 |
-
"start": "nodemon dist/index.js --watch",
|
| 9 |
-
"prebuild": "prisma generate",
|
| 10 |
-
"build": "rimraf dist && eslint -c .eslintrc.js --ext .ts . && tsc",
|
| 11 |
-
"postbuild": "test -f keys || (node -e \"console.log(require('crypto').randomBytes(48).toString('base64'));\" > keys && node -e \"console.log(require('crypto').randomBytes(48).toString('base64'));\" >> keys)"
|
| 12 |
-
},
|
| 13 |
-
"dependencies": {
|
| 14 |
-
"@prisma/client": "^4.12.0",
|
| 15 |
-
"@types/moment": "^2.13.0",
|
| 16 |
-
"axios": "^0.21.4",
|
| 17 |
-
"bcryptjs": "^2.4.3",
|
| 18 |
-
"big-integer": "^1.6.48",
|
| 19 |
-
"check-disk-space": "^3.3.0",
|
| 20 |
-
"compression": "^1.7.4",
|
| 21 |
-
"content-disposition": "^0.5.3",
|
| 22 |
-
"cookie-parser": "^1.4.5",
|
| 23 |
-
"cors": "^2.8.5",
|
| 24 |
-
"crypto": "^1.0.1",
|
| 25 |
-
"crypto-js": "^4.1.1",
|
| 26 |
-
"curly-express": "^1.3.6",
|
| 27 |
-
"dotenv": "^10.0.0",
|
| 28 |
-
"express": "^4.17.1",
|
| 29 |
-
"express-ipinfo": "^1.0.0",
|
| 30 |
-
"express-list-endpoints": "^6.0.0",
|
| 31 |
-
"express-rate-limit": "^5.3.0",
|
| 32 |
-
"flatted": "^3.2.2",
|
| 33 |
-
"geoip-lite": "^1.4.2",
|
| 34 |
-
"human-format": "^1.0.0",
|
| 35 |
-
"input": "^1.0.1",
|
| 36 |
-
"ioredis": "^4.28.2",
|
| 37 |
-
"is-uuid": "^1.0.2",
|
| 38 |
-
"json-bigint": "^1.0.0",
|
| 39 |
-
"jsonwebtoken": "^8.5.1",
|
| 40 |
-
"moment": "^2.29.1",
|
| 41 |
-
"morgan": "^1.10.0",
|
| 42 |
-
"multer": "^1.4.3",
|
| 43 |
-
"nanoid": "^3.1.25",
|
| 44 |
-
"pg": "^8.7.1",
|
| 45 |
-
"pg-connection-string": "^2.5.0",
|
| 46 |
-
"prisma": "^4.12.0",
|
| 47 |
-
"redis": "^4.0.1",
|
| 48 |
-
"serialize-error": "^8.1.0",
|
| 49 |
-
"serverless-http": "^3.0.1",
|
| 50 |
-
"source-map-support": "^0.5.19",
|
| 51 |
-
"telegram": "^2.15.5",
|
| 52 |
-
"uuid-random": "^1.3.2",
|
| 53 |
-
"util": "0.12.5",
|
| 54 |
-
"path":"0.12.7"
|
| 55 |
-
},
|
| 56 |
-
"devDependencies": {
|
| 57 |
-
"@types/axios": "^0.14.0",
|
| 58 |
-
"@types/bcryptjs": "^2.4.2",
|
| 59 |
-
"@types/big-integer": "^0.0.31",
|
| 60 |
-
"@types/compression": "^1.7.2",
|
| 61 |
-
"@types/content-disposition": "^0.5.4",
|
| 62 |
-
"@types/cookie-parser": "^1.4.2",
|
| 63 |
-
"@types/cors": "^2.8.12",
|
| 64 |
-
"@types/crypto-js": "^4.0.2",
|
| 65 |
-
"@types/dotenv": "^8.2.0",
|
| 66 |
-
"@types/express": "^4.17.13",
|
| 67 |
-
"@types/express-list-endpoints": "^6.0.0",
|
| 68 |
-
"@types/express-rate-limit": "^5.1.3",
|
| 69 |
-
"@types/geoip-lite": "^1.4.1",
|
| 70 |
-
"@types/ioredis": "^4.28.7",
|
| 71 |
-
"@types/is-uuid": "^1.0.0",
|
| 72 |
-
"@types/jsonwebtoken": "^8.5.5",
|
| 73 |
-
"@types/morgan": "^1.9.3",
|
| 74 |
-
"@types/multer": "^1.4.7",
|
| 75 |
-
"@types/nanoid": "^3.0.0",
|
| 76 |
-
"@types/node": "^16.7.2",
|
| 77 |
-
"@types/pg": "^8.6.1",
|
| 78 |
-
"@types/pg-connection-string": "^2.0.0",
|
| 79 |
-
"@types/redis": "^4.0.11",
|
| 80 |
-
"@types/serialize-error": "^4.0.1",
|
| 81 |
-
"@types/source-map-support": "^0.5.4",
|
| 82 |
-
"@typescript-eslint/eslint-plugin": "^4.29.3",
|
| 83 |
-
"@typescript-eslint/parser": "^4.29.3",
|
| 84 |
-
"eslint": "^7.32.0",
|
| 85 |
-
"nodemon": "^2.0.12",
|
| 86 |
-
"reflect-metadata": "^0.1.13",
|
| 87 |
-
"rimraf": "^3.0.2",
|
| 88 |
-
"typescript": "^4.4.2"
|
| 89 |
-
}
|
| 90 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/prisma/migrations/20220420012853_init/migration.sql
DELETED
|
@@ -1,107 +0,0 @@
|
|
| 1 |
-
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
| 2 |
-
|
| 3 |
-
-- CreateTable
|
| 4 |
-
CREATE TABLE "config" (
|
| 5 |
-
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 6 |
-
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 7 |
-
"id" UUID NOT NULL DEFAULT uuid_generate_v4(),
|
| 8 |
-
"invitation_code" VARCHAR,
|
| 9 |
-
"disable_signup" BOOLEAN NOT NULL DEFAULT false,
|
| 10 |
-
"allow_server_storage_use" BOOLEAN NOT NULL DEFAULT false,
|
| 11 |
-
|
| 12 |
-
CONSTRAINT "pk_af2ddc24176f1572cbdd4b45992" PRIMARY KEY ("id")
|
| 13 |
-
);
|
| 14 |
-
|
| 15 |
-
-- CreateTable
|
| 16 |
-
CREATE TABLE "files" (
|
| 17 |
-
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 18 |
-
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 19 |
-
"id" UUID NOT NULL DEFAULT uuid_generate_v4(),
|
| 20 |
-
"name" VARCHAR NOT NULL,
|
| 21 |
-
"type" VARCHAR,
|
| 22 |
-
"message_id" VARCHAR,
|
| 23 |
-
"mime_type" VARCHAR,
|
| 24 |
-
"size" BIGINT,
|
| 25 |
-
"uploaded_at" TIMESTAMPTZ(6),
|
| 26 |
-
"upload_progress" DOUBLE PRECISION,
|
| 27 |
-
"user_id" UUID NOT NULL,
|
| 28 |
-
"parent_id" UUID,
|
| 29 |
-
"deleted_at" TIMESTAMPTZ(6),
|
| 30 |
-
"sharing_options" VARCHAR[],
|
| 31 |
-
"signed_key" VARCHAR,
|
| 32 |
-
"file_id" VARCHAR,
|
| 33 |
-
"link_id" UUID,
|
| 34 |
-
"forward_info" VARCHAR,
|
| 35 |
-
|
| 36 |
-
CONSTRAINT "PK_6c16b9093a142e0e7613b04a3d9" PRIMARY KEY ("id")
|
| 37 |
-
);
|
| 38 |
-
|
| 39 |
-
-- CreateTable
|
| 40 |
-
CREATE TABLE "rate_limits" (
|
| 41 |
-
"key" VARCHAR(255) NOT NULL,
|
| 42 |
-
"points" INTEGER NOT NULL DEFAULT 0,
|
| 43 |
-
"expire" BIGINT,
|
| 44 |
-
|
| 45 |
-
CONSTRAINT "rate_limits_pkey" PRIMARY KEY ("key")
|
| 46 |
-
);
|
| 47 |
-
|
| 48 |
-
-- CreateTable
|
| 49 |
-
CREATE TABLE "usages" (
|
| 50 |
-
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 51 |
-
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 52 |
-
"key" VARCHAR NOT NULL,
|
| 53 |
-
"usage" BIGINT NOT NULL,
|
| 54 |
-
"expire" TIMESTAMPTZ(6) NOT NULL,
|
| 55 |
-
|
| 56 |
-
CONSTRAINT "PK_7d8e95b6dd4c0e87cad4972da13" PRIMARY KEY ("key")
|
| 57 |
-
);
|
| 58 |
-
|
| 59 |
-
-- CreateTable
|
| 60 |
-
CREATE TABLE "users" (
|
| 61 |
-
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 62 |
-
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 63 |
-
"id" UUID NOT NULL DEFAULT uuid_generate_v4(),
|
| 64 |
-
"username" VARCHAR NOT NULL,
|
| 65 |
-
"name" VARCHAR,
|
| 66 |
-
"email" VARCHAR,
|
| 67 |
-
"tg_id" VARCHAR,
|
| 68 |
-
"plan" VARCHAR,
|
| 69 |
-
"settings" JSONB,
|
| 70 |
-
"role" VARCHAR,
|
| 71 |
-
|
| 72 |
-
CONSTRAINT "PK_a3ffb1c0c8416b9fc6f907b7433" PRIMARY KEY ("id")
|
| 73 |
-
);
|
| 74 |
-
|
| 75 |
-
-- CreateTable
|
| 76 |
-
CREATE TABLE "waitings" (
|
| 77 |
-
"created_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 78 |
-
"updated_at" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
| 79 |
-
"id" UUID NOT NULL DEFAULT uuid_generate_v4(),
|
| 80 |
-
"email" VARCHAR NOT NULL,
|
| 81 |
-
|
| 82 |
-
CONSTRAINT "PK_f0cfe98441cf0fb92db66ae71c4" PRIMARY KEY ("id")
|
| 83 |
-
);
|
| 84 |
-
|
| 85 |
-
-- CreateIndex
|
| 86 |
-
CREATE INDEX "files_link_id_idx" ON "files"("link_id");
|
| 87 |
-
|
| 88 |
-
-- CreateIndex
|
| 89 |
-
CREATE INDEX "files_message_id_idx" ON "files"("message_id");
|
| 90 |
-
|
| 91 |
-
-- CreateIndex
|
| 92 |
-
CREATE INDEX "files_parent_id_idx" ON "files"("parent_id");
|
| 93 |
-
|
| 94 |
-
-- CreateIndex
|
| 95 |
-
CREATE INDEX "files_user_id_idx" ON "files"("user_id");
|
| 96 |
-
|
| 97 |
-
-- CreateIndex
|
| 98 |
-
CREATE INDEX "tg_id" ON "users"("tg_id");
|
| 99 |
-
|
| 100 |
-
-- AddForeignKey
|
| 101 |
-
ALTER TABLE "files" ADD CONSTRAINT "files_links_fkey" FOREIGN KEY ("link_id") REFERENCES "files"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
| 102 |
-
|
| 103 |
-
-- AddForeignKey
|
| 104 |
-
ALTER TABLE "files" ADD CONSTRAINT "files_files_fkey" FOREIGN KEY ("parent_id") REFERENCES "files"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
| 105 |
-
|
| 106 |
-
-- AddForeignKey
|
| 107 |
-
ALTER TABLE "files" ADD CONSTRAINT "files_users_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/prisma/migrations/20220525012308_add_password_files/migration.sql
DELETED
|
@@ -1,2 +0,0 @@
|
|
| 1 |
-
-- AlterTable
|
| 2 |
-
ALTER TABLE "files" ADD COLUMN "password" VARCHAR;
|
|
|
|
|
|
|
|
|
api/prisma/migrations/migration_lock.toml
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
# Please do not edit this file manually
|
| 2 |
-
# It should be added in your version-control system (i.e. Git)
|
| 3 |
-
provider = "postgresql"
|
|
|
|
|
|
|
|
|
|
|
|
api/prisma/schema.prisma
DELETED
|
@@ -1,87 +0,0 @@
|
|
| 1 |
-
generator client {
|
| 2 |
-
provider = "prisma-client-js"
|
| 3 |
-
}
|
| 4 |
-
|
| 5 |
-
datasource db {
|
| 6 |
-
provider = "postgresql"
|
| 7 |
-
url = env("DATABASE_URL")
|
| 8 |
-
}
|
| 9 |
-
|
| 10 |
-
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by the Prisma Client.
|
| 11 |
-
model config {
|
| 12 |
-
created_at DateTime @default(now()) @db.Timestamptz(6)
|
| 13 |
-
updated_at DateTime @default(now()) @db.Timestamptz(6)
|
| 14 |
-
id String @id(map: "pk_af2ddc24176f1572cbdd4b45992") @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
|
| 15 |
-
invitation_code String? @db.VarChar
|
| 16 |
-
disable_signup Boolean @default(false)
|
| 17 |
-
allow_server_storage_use Boolean @default(false)
|
| 18 |
-
}
|
| 19 |
-
|
| 20 |
-
model files {
|
| 21 |
-
created_at DateTime @default(now()) @db.Timestamptz(6)
|
| 22 |
-
updated_at DateTime @default(now()) @db.Timestamptz(6)
|
| 23 |
-
id String @id(map: "PK_6c16b9093a142e0e7613b04a3d9") @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
|
| 24 |
-
name String @db.VarChar
|
| 25 |
-
type String? @db.VarChar
|
| 26 |
-
message_id String? @db.VarChar
|
| 27 |
-
mime_type String? @db.VarChar
|
| 28 |
-
size BigInt?
|
| 29 |
-
uploaded_at DateTime? @db.Timestamptz(6)
|
| 30 |
-
upload_progress Float?
|
| 31 |
-
user_id String @db.Uuid
|
| 32 |
-
parent_id String? @db.Uuid
|
| 33 |
-
deleted_at DateTime? @db.Timestamptz(6)
|
| 34 |
-
sharing_options String[] @db.VarChar
|
| 35 |
-
signed_key String? @db.VarChar
|
| 36 |
-
file_id String? @db.VarChar
|
| 37 |
-
link_id String? @db.Uuid
|
| 38 |
-
forward_info String? @db.VarChar
|
| 39 |
-
link files? @relation("filesTofiles_link_id", fields: [link_id], references: [id], onDelete: Cascade, map: "files_links_fkey")
|
| 40 |
-
parent files? @relation("filesTofiles_parent_id", fields: [parent_id], references: [id], onDelete: Cascade, map: "files_files_fkey")
|
| 41 |
-
users users @relation(fields: [user_id], references: [id], onDelete: Cascade, map: "files_users_fkey")
|
| 42 |
-
links files[] @relation("filesTofiles_link_id")
|
| 43 |
-
parents files[] @relation("filesTofiles_parent_id")
|
| 44 |
-
password String? @db.VarChar
|
| 45 |
-
|
| 46 |
-
@@index([link_id])
|
| 47 |
-
@@index([message_id])
|
| 48 |
-
@@index([parent_id])
|
| 49 |
-
@@index([user_id])
|
| 50 |
-
}
|
| 51 |
-
|
| 52 |
-
model rate_limits {
|
| 53 |
-
key String @id @db.VarChar(255)
|
| 54 |
-
points Int @default(0)
|
| 55 |
-
expire BigInt?
|
| 56 |
-
}
|
| 57 |
-
|
| 58 |
-
model usages {
|
| 59 |
-
created_at DateTime @default(now()) @db.Timestamptz(6)
|
| 60 |
-
updated_at DateTime @default(now()) @db.Timestamptz(6)
|
| 61 |
-
key String @id(map: "PK_7d8e95b6dd4c0e87cad4972da13") @db.VarChar
|
| 62 |
-
usage BigInt
|
| 63 |
-
expire DateTime @db.Timestamptz(6)
|
| 64 |
-
}
|
| 65 |
-
|
| 66 |
-
model users {
|
| 67 |
-
created_at DateTime @default(now()) @db.Timestamptz(6)
|
| 68 |
-
updated_at DateTime @default(now()) @db.Timestamptz(6)
|
| 69 |
-
id String @id(map: "PK_a3ffb1c0c8416b9fc6f907b7433") @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
|
| 70 |
-
username String @db.VarChar
|
| 71 |
-
name String? @db.VarChar
|
| 72 |
-
email String? @db.VarChar
|
| 73 |
-
tg_id String? @db.VarChar
|
| 74 |
-
plan String? @db.VarChar
|
| 75 |
-
settings Json?
|
| 76 |
-
role String? @db.VarChar
|
| 77 |
-
files files[]
|
| 78 |
-
|
| 79 |
-
@@index([tg_id], map: "tg_id")
|
| 80 |
-
}
|
| 81 |
-
|
| 82 |
-
model waitings {
|
| 83 |
-
created_at DateTime @default(now()) @db.Timestamptz(6)
|
| 84 |
-
updated_at DateTime @default(now()) @db.Timestamptz(6)
|
| 85 |
-
id String @id(map: "PK_f0cfe98441cf0fb92db66ae71c4") @default(dbgenerated("uuid_generate_v4()")) @db.Uuid
|
| 86 |
-
email String @db.VarChar
|
| 87 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/Types.ts
DELETED
|
@@ -1,11 +0,0 @@
|
|
| 1 |
-
import { users } from '@prisma/client'
|
| 2 |
-
import { TelegramClient } from 'telegram'
|
| 3 |
-
|
| 4 |
-
declare module 'http' {
|
| 5 |
-
interface IncomingMessage {
|
| 6 |
-
tg?: TelegramClient,
|
| 7 |
-
user?: users,
|
| 8 |
-
userAuth?: any,
|
| 9 |
-
authKey?: string
|
| 10 |
-
}
|
| 11 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/api/base/Endpoint.ts
DELETED
|
@@ -1,151 +0,0 @@
|
|
| 1 |
-
import { NextFunction, Request, RequestHandler, Response, Router } from 'express'
|
| 2 |
-
import { serializeError } from 'serialize-error'
|
| 3 |
-
|
| 4 |
-
interface RouteOptions {
|
| 5 |
-
path?: string,
|
| 6 |
-
middlewares?: RequestHandler[]
|
| 7 |
-
}
|
| 8 |
-
|
| 9 |
-
interface Route {
|
| 10 |
-
method: string,
|
| 11 |
-
basepath: string,
|
| 12 |
-
middlewares?: RequestHandler[],
|
| 13 |
-
path: string,
|
| 14 |
-
handler: RequestHandler
|
| 15 |
-
}
|
| 16 |
-
|
| 17 |
-
export const Endpoint = {
|
| 18 |
-
_handlers: [],
|
| 19 |
-
register: function (..._classes: any[]): Router {
|
| 20 |
-
const router = Router()
|
| 21 |
-
for (const route of this._handlers?.filter((handler: Route) => !!handler.basepath)) {
|
| 22 |
-
router[route.method](`${route.basepath}${route.path}`,
|
| 23 |
-
...(route.middlewares || []).map((middleware: RequestHandler) => this.RequestWrapper(middleware)), route.handler)
|
| 24 |
-
}
|
| 25 |
-
return router
|
| 26 |
-
},
|
| 27 |
-
API: function (basepath?: string): any {
|
| 28 |
-
return (cls: new () => any): void => {
|
| 29 |
-
this._handlers = this._handlers.map((handler: Route) => ({
|
| 30 |
-
...handler,
|
| 31 |
-
basepath: handler.basepath || basepath || `/${cls.name[0].toLowerCase()}${cls.name.slice(1)}`
|
| 32 |
-
}))
|
| 33 |
-
}
|
| 34 |
-
},
|
| 35 |
-
USE: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
|
| 36 |
-
return (_: any, method: string, descriptor: PropertyDescriptor): void => {
|
| 37 |
-
this._handlers.push(this._buildRouteHandler('use', method, descriptor, ...args))
|
| 38 |
-
}
|
| 39 |
-
},
|
| 40 |
-
GET: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
|
| 41 |
-
return (_: any, method: string, descriptor: PropertyDescriptor): void => {
|
| 42 |
-
this._handlers.push(this._buildRouteHandler('get', method, descriptor, ...args))
|
| 43 |
-
}
|
| 44 |
-
},
|
| 45 |
-
HEAD: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
|
| 46 |
-
return (_: any, method: string, descriptor: PropertyDescriptor): void => {
|
| 47 |
-
this._handlers.push(this._buildRouteHandler('head', method, descriptor, ...args))
|
| 48 |
-
}
|
| 49 |
-
},
|
| 50 |
-
POST: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
|
| 51 |
-
return (_: any, method: string, descriptor: PropertyDescriptor): void => {
|
| 52 |
-
this._handlers.push(this._buildRouteHandler('post', method, descriptor, ...args))
|
| 53 |
-
}
|
| 54 |
-
},
|
| 55 |
-
PATCH: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
|
| 56 |
-
return (_: any, method: string, descriptor: PropertyDescriptor): void => {
|
| 57 |
-
this._handlers.push(this._buildRouteHandler('patch', method, descriptor, ...args))
|
| 58 |
-
}
|
| 59 |
-
},
|
| 60 |
-
PUT: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
|
| 61 |
-
return (_: any, method: string, descriptor: PropertyDescriptor): void => {
|
| 62 |
-
this._handlers.push(this._buildRouteHandler('put', method, descriptor, ...args))
|
| 63 |
-
}
|
| 64 |
-
},
|
| 65 |
-
DELETE: function (...args: [(string | RouteOptions)?, RouteOptions?]): any {
|
| 66 |
-
return (_: any, method: string, descriptor: PropertyDescriptor): void => {
|
| 67 |
-
this._handlers.push(this._buildRouteHandler('delete', method, descriptor, ...args))
|
| 68 |
-
}
|
| 69 |
-
},
|
| 70 |
-
RequestWrapper: (target: RequestHandler): RequestHandler => {
|
| 71 |
-
return async function (req: Request, res: Response, next: NextFunction) {
|
| 72 |
-
let trial = 0
|
| 73 |
-
const execute = async () => {
|
| 74 |
-
try {
|
| 75 |
-
return await target(req, res, next)
|
| 76 |
-
} catch (error) {
|
| 77 |
-
if (/.*You need to call \.connect\(\)/gi.test(error.message) && trial < 5) {
|
| 78 |
-
await new Promise(res => setTimeout(res, ++trial * 1000))
|
| 79 |
-
req.tg?.connect()
|
| 80 |
-
return await execute()
|
| 81 |
-
}
|
| 82 |
-
if (process.env.ENV !== 'production') {
|
| 83 |
-
console.error('RequestWrapper', error)
|
| 84 |
-
}
|
| 85 |
-
req.tg?.disconnect()
|
| 86 |
-
const isValidCode = error.code && Number(error.code) > 99 && Number(error.code) < 599
|
| 87 |
-
return next(error.code ? {
|
| 88 |
-
status: isValidCode ? error.code : 500, body: {
|
| 89 |
-
error: error.message, details: serializeError(error)
|
| 90 |
-
}
|
| 91 |
-
} : error)
|
| 92 |
-
}
|
| 93 |
-
}
|
| 94 |
-
return await execute()
|
| 95 |
-
}
|
| 96 |
-
},
|
| 97 |
-
_buildRouteHandler: function (method: string, route: string, descriptor: PropertyDescriptor, ...args: [(string | RouteOptions)?, RouteOptions?]): Route {
|
| 98 |
-
// get path
|
| 99 |
-
let path = `/${route[0].toLowerCase()}${route.slice(1)}`
|
| 100 |
-
if (args[0]) {
|
| 101 |
-
if (typeof args[0] === 'string') {
|
| 102 |
-
path = args[0]
|
| 103 |
-
} else if (args[0]?.path) {
|
| 104 |
-
path = args[0].path
|
| 105 |
-
}
|
| 106 |
-
} else if (args[1]?.path) {
|
| 107 |
-
path = args[1].path
|
| 108 |
-
}
|
| 109 |
-
|
| 110 |
-
// build opts
|
| 111 |
-
let opts: RouteOptions = {}
|
| 112 |
-
if (args[0] && typeof args[0] === 'object') {
|
| 113 |
-
opts = args[0] as RouteOptions
|
| 114 |
-
} else if (args[1]) {
|
| 115 |
-
opts = args[1] as RouteOptions
|
| 116 |
-
}
|
| 117 |
-
|
| 118 |
-
return {
|
| 119 |
-
...opts,
|
| 120 |
-
method,
|
| 121 |
-
basepath: null,
|
| 122 |
-
path,
|
| 123 |
-
handler: async function (req: Request, res: Response, next: NextFunction) {
|
| 124 |
-
let trial = 0
|
| 125 |
-
const execute = async () => {
|
| 126 |
-
try {
|
| 127 |
-
await descriptor.value(req, res, next)
|
| 128 |
-
req.tg?.disconnect()
|
| 129 |
-
} catch (error) {
|
| 130 |
-
if (/.*You need to call \.connect\(\)/gi.test(error.message) && trial < 5) {
|
| 131 |
-
await new Promise(res => setTimeout(res, ++trial * 1000))
|
| 132 |
-
req.tg?.connect()
|
| 133 |
-
return await execute()
|
| 134 |
-
}
|
| 135 |
-
if (process.env.ENV !== 'production') {
|
| 136 |
-
console.error('handler', error.message)
|
| 137 |
-
}
|
| 138 |
-
req.tg?.disconnect()
|
| 139 |
-
const isValidCode = error.code && Number(error.code) > 99 && Number(error.code) < 599
|
| 140 |
-
return next(error.code ? {
|
| 141 |
-
status: isValidCode ? error.code : 500, body: {
|
| 142 |
-
error: error.message, details: serializeError(error)
|
| 143 |
-
}
|
| 144 |
-
} : error)
|
| 145 |
-
}
|
| 146 |
-
}
|
| 147 |
-
return await execute()
|
| 148 |
-
}
|
| 149 |
-
}
|
| 150 |
-
}
|
| 151 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/api/index.ts
DELETED
|
@@ -1,5 +0,0 @@
|
|
| 1 |
-
import { Router } from 'express'
|
| 2 |
-
import { V1 } from './v1'
|
| 3 |
-
|
| 4 |
-
export const API = Router()
|
| 5 |
-
.use('/v1', V1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/api/middlewares/Auth.ts
DELETED
|
@@ -1,119 +0,0 @@
|
|
| 1 |
-
import { NextFunction, Request, Response } from 'express'
|
| 2 |
-
import { verify } from 'jsonwebtoken'
|
| 3 |
-
import { Logger, TelegramClient } from 'telegram'
|
| 4 |
-
import { LogLevel } from 'telegram/extensions/Logger'
|
| 5 |
-
import { StringSession } from 'telegram/sessions'
|
| 6 |
-
import { prisma } from '../../model'
|
| 7 |
-
import { Redis } from '../../service/Cache'
|
| 8 |
-
import { API_JWT_SECRET, CONNECTION_RETRIES, TG_CREDS } from '../../utils/Constant'
|
| 9 |
-
|
| 10 |
-
export async function Auth(req: Request, _: Response, next: NextFunction): Promise<any> {
|
| 11 |
-
const authkey = (req.headers.authorization || req.cookies.authorization)?.replace(/^Bearer\ /gi, '')
|
| 12 |
-
if (!authkey) {
|
| 13 |
-
throw { status: 401, body: { error: 'Auth key is required' } }
|
| 14 |
-
}
|
| 15 |
-
|
| 16 |
-
let data: { session: string }
|
| 17 |
-
try {
|
| 18 |
-
data = verify(authkey, API_JWT_SECRET) as { session: string }
|
| 19 |
-
} catch (error) {
|
| 20 |
-
throw { status: 401, body: { error: 'Access token is invalid' } }
|
| 21 |
-
}
|
| 22 |
-
|
| 23 |
-
try {
|
| 24 |
-
const session = new StringSession(data.session)
|
| 25 |
-
req.tg = new TelegramClient(session, TG_CREDS.apiId, TG_CREDS.apiHash, {
|
| 26 |
-
connectionRetries: CONNECTION_RETRIES,
|
| 27 |
-
useWSS: false,
|
| 28 |
-
...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
|
| 29 |
-
})
|
| 30 |
-
} catch (error) {
|
| 31 |
-
throw { status: 401, body: { error: 'Invalid key' } }
|
| 32 |
-
}
|
| 33 |
-
await req.tg.connect()
|
| 34 |
-
req.authKey = authkey
|
| 35 |
-
|
| 36 |
-
const [userAuth, user] = await Redis.connect().getFromCacheFirst(`auth:${authkey}`, async () => {
|
| 37 |
-
let userAuth: any
|
| 38 |
-
try {
|
| 39 |
-
userAuth = await req.tg.getMe()
|
| 40 |
-
} catch (error) {
|
| 41 |
-
try {
|
| 42 |
-
await new Promise((resolve) => setTimeout(resolve, 2000))
|
| 43 |
-
await req.tg.connect()
|
| 44 |
-
userAuth = await req.tg.getMe()
|
| 45 |
-
} catch (error) {
|
| 46 |
-
await new Promise((resolve) => setTimeout(resolve, 2000))
|
| 47 |
-
await req.tg.connect()
|
| 48 |
-
userAuth = await req.tg.getMe()
|
| 49 |
-
}
|
| 50 |
-
}
|
| 51 |
-
|
| 52 |
-
const user = await prisma.users.findFirst({ where: { tg_id: userAuth['id'].toString() } })
|
| 53 |
-
if (!user) {
|
| 54 |
-
throw { status: 401, body: { error: 'User not found' } }
|
| 55 |
-
}
|
| 56 |
-
return [userAuth, user]
|
| 57 |
-
}, 54000)
|
| 58 |
-
|
| 59 |
-
req.user = user
|
| 60 |
-
req.userAuth = userAuth
|
| 61 |
-
|
| 62 |
-
return next()
|
| 63 |
-
}
|
| 64 |
-
|
| 65 |
-
export async function AuthMaybe(req: Request, _: Response, next: NextFunction): Promise<any> {
|
| 66 |
-
const authkey = (req.headers.authorization || req.cookies.authorization)?.replace(/^Bearer\ /gi, '')
|
| 67 |
-
if (authkey) {
|
| 68 |
-
let data: { session: string }
|
| 69 |
-
try {
|
| 70 |
-
data = verify(authkey, API_JWT_SECRET) as { session: string }
|
| 71 |
-
} catch (error) {
|
| 72 |
-
// throw { status: 401, body: { error: 'Access token is invalid' } }
|
| 73 |
-
return next()
|
| 74 |
-
}
|
| 75 |
-
|
| 76 |
-
try {
|
| 77 |
-
const session = new StringSession(data.session)
|
| 78 |
-
req.tg = new TelegramClient(session, TG_CREDS.apiId, TG_CREDS.apiHash, {
|
| 79 |
-
connectionRetries: CONNECTION_RETRIES,
|
| 80 |
-
useWSS: false,
|
| 81 |
-
...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
|
| 82 |
-
})
|
| 83 |
-
} catch (error) {
|
| 84 |
-
// throw { status: 401, body: { error: 'Invalid key' } }
|
| 85 |
-
return next()
|
| 86 |
-
}
|
| 87 |
-
await req.tg.connect()
|
| 88 |
-
req.authKey = authkey
|
| 89 |
-
|
| 90 |
-
const [userAuth, user] = await Redis.connect().getFromCacheFirst(`auth:${authkey}`, async () => {
|
| 91 |
-
let userAuth: any = null
|
| 92 |
-
try {
|
| 93 |
-
userAuth = await req.tg.getMe()
|
| 94 |
-
} catch (error) {
|
| 95 |
-
try {
|
| 96 |
-
await new Promise((resolve) => setTimeout(resolve, 2000))
|
| 97 |
-
await req.tg.connect()
|
| 98 |
-
userAuth = await req.tg.getMe()
|
| 99 |
-
} catch (error) {
|
| 100 |
-
await new Promise((resolve) => setTimeout(resolve, 2000))
|
| 101 |
-
await req.tg.connect()
|
| 102 |
-
userAuth = await req.tg.getMe()
|
| 103 |
-
}
|
| 104 |
-
}
|
| 105 |
-
|
| 106 |
-
const user = await prisma.users.findFirst({ where: { tg_id: userAuth['id'].toString() } })
|
| 107 |
-
if (!user) {
|
| 108 |
-
// throw { status: 401, body: { error: 'User not found' } }
|
| 109 |
-
return [userAuth, null]
|
| 110 |
-
}
|
| 111 |
-
return [userAuth, user]
|
| 112 |
-
}, 54000)
|
| 113 |
-
|
| 114 |
-
req.user = user
|
| 115 |
-
req.userAuth = userAuth
|
| 116 |
-
}
|
| 117 |
-
|
| 118 |
-
return next()
|
| 119 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/api/middlewares/Key.ts
DELETED
|
@@ -1,10 +0,0 @@
|
|
| 1 |
-
import { NextFunction, Request, Response } from 'express'
|
| 2 |
-
|
| 3 |
-
export async function AuthKey(req: Request, _: Response, next: NextFunction): Promise<any> {
|
| 4 |
-
const authkey = req.headers['token'] || req.query['token']
|
| 5 |
-
if (authkey !== process.env.UTILS_API_KEY) {
|
| 6 |
-
throw { status: 401, body: { error: 'Invalid key' } }
|
| 7 |
-
}
|
| 8 |
-
|
| 9 |
-
return next()
|
| 10 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/api/middlewares/TGClient.ts
DELETED
|
@@ -1,15 +0,0 @@
|
|
| 1 |
-
import { Logger, TelegramClient } from 'telegram'
|
| 2 |
-
import { LogLevel } from 'telegram/extensions/Logger'
|
| 3 |
-
import { StringSession } from 'telegram/sessions'
|
| 4 |
-
import { NextFunction, Request, Response } from 'express'
|
| 5 |
-
import { CONNECTION_RETRIES, TG_CREDS } from '../../utils/Constant'
|
| 6 |
-
|
| 7 |
-
export async function TGClient(req: Request, _: Response, next: NextFunction): Promise<any> {
|
| 8 |
-
const session = new StringSession('')
|
| 9 |
-
req.tg = new TelegramClient(session, TG_CREDS.apiId, TG_CREDS.apiHash, {
|
| 10 |
-
connectionRetries: CONNECTION_RETRIES,
|
| 11 |
-
useWSS: false,
|
| 12 |
-
...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
|
| 13 |
-
})
|
| 14 |
-
return next()
|
| 15 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/api/middlewares/TGSessionAuth.ts
DELETED
|
@@ -1,32 +0,0 @@
|
|
| 1 |
-
import { NextFunction, Request, Response } from 'express'
|
| 2 |
-
import { verify } from 'jsonwebtoken'
|
| 3 |
-
import { Logger, TelegramClient } from 'telegram'
|
| 4 |
-
import { LogLevel } from 'telegram/extensions/Logger'
|
| 5 |
-
import { StringSession } from 'telegram/sessions'
|
| 6 |
-
import { API_JWT_SECRET, CONNECTION_RETRIES, TG_CREDS } from '../../utils/Constant'
|
| 7 |
-
|
| 8 |
-
export async function TGSessionAuth(req: Request, _: Response, next: NextFunction): Promise<any> {
|
| 9 |
-
const authkey = (req.headers.authorization || req.cookies.authorization)?.replace(/^Bearer\ /gi, '')
|
| 10 |
-
if (!authkey) {
|
| 11 |
-
throw { status: 401, body: { error: 'Auth key is required' } }
|
| 12 |
-
}
|
| 13 |
-
|
| 14 |
-
let data: { session: string }
|
| 15 |
-
try {
|
| 16 |
-
data = verify(authkey, API_JWT_SECRET) as { session: string }
|
| 17 |
-
} catch (error) {
|
| 18 |
-
throw { status: 401, body: { error: 'Access token is invalid' } }
|
| 19 |
-
}
|
| 20 |
-
|
| 21 |
-
try {
|
| 22 |
-
const session = new StringSession(data.session)
|
| 23 |
-
req.tg = new TelegramClient(session, TG_CREDS.apiId, TG_CREDS.apiHash, {
|
| 24 |
-
connectionRetries: CONNECTION_RETRIES,
|
| 25 |
-
useWSS: false,
|
| 26 |
-
...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
|
| 27 |
-
})
|
| 28 |
-
} catch (error) {
|
| 29 |
-
throw { status: 401, body: { error: 'Invalid key' } }
|
| 30 |
-
}
|
| 31 |
-
return next()
|
| 32 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/api/v1/Auth.ts
DELETED
|
@@ -1,468 +0,0 @@
|
|
| 1 |
-
import { AES } from 'crypto-js'
|
| 2 |
-
import { Request, Response } from 'express'
|
| 3 |
-
import { sign, verify } from 'jsonwebtoken'
|
| 4 |
-
import { serializeError } from 'serialize-error'
|
| 5 |
-
import { Api, Logger, TelegramClient } from 'telegram'
|
| 6 |
-
import { LogLevel } from 'telegram/extensions/Logger'
|
| 7 |
-
import { generateRandomBytes } from 'telegram/Helpers'
|
| 8 |
-
import { computeCheck } from 'telegram/Password'
|
| 9 |
-
import { StringSession } from 'telegram/sessions'
|
| 10 |
-
import { prisma } from '../../model'
|
| 11 |
-
import { Redis } from '../../service/Cache'
|
| 12 |
-
import { API_JWT_SECRET, CONNECTION_RETRIES, COOKIE_AGE, FILES_JWT_SECRET, TG_CREDS } from '../../utils/Constant'
|
| 13 |
-
import { Endpoint } from '../base/Endpoint'
|
| 14 |
-
import { TGClient } from '../middlewares/TGClient'
|
| 15 |
-
import { TGSessionAuth } from '../middlewares/TGSessionAuth'
|
| 16 |
-
|
| 17 |
-
@Endpoint.API()
|
| 18 |
-
export class Auth {
|
| 19 |
-
|
| 20 |
-
@Endpoint.POST({ middlewares: [TGClient] })
|
| 21 |
-
public async sendCode(req: Request, res: Response): Promise<any> {
|
| 22 |
-
const { phoneNumber } = req.body
|
| 23 |
-
if (!phoneNumber) {
|
| 24 |
-
throw { status: 400, body: { error: 'Phone number is required' } }
|
| 25 |
-
}
|
| 26 |
-
|
| 27 |
-
await req.tg.connect()
|
| 28 |
-
const { phoneCodeHash, timeout } = await req.tg.invoke(new Api.auth.SendCode({
|
| 29 |
-
...TG_CREDS,
|
| 30 |
-
phoneNumber,
|
| 31 |
-
settings: new Api.CodeSettings({
|
| 32 |
-
allowFlashcall: true,
|
| 33 |
-
currentNumber: true,
|
| 34 |
-
allowAppHash: true,
|
| 35 |
-
})
|
| 36 |
-
}))
|
| 37 |
-
const session = req.tg.session.save()
|
| 38 |
-
const accessToken = sign({ session }, API_JWT_SECRET, { expiresIn: '3h' })
|
| 39 |
-
return res.cookie('authorization', `Bearer ${accessToken}`)
|
| 40 |
-
.send({ phoneCodeHash, timeout, accessToken })
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
@Endpoint.POST({ middlewares: [TGSessionAuth] })
|
| 44 |
-
public async reSendCode(req: Request, res: Response): Promise<any> {
|
| 45 |
-
const { phoneNumber, phoneCodeHash } = req.body
|
| 46 |
-
if (!phoneNumber || !phoneCodeHash) {
|
| 47 |
-
throw { status: 400, body: { error: 'Phone number and phone code hash are required' } }
|
| 48 |
-
}
|
| 49 |
-
|
| 50 |
-
await req.tg.connect()
|
| 51 |
-
const { phoneCodeHash: newPhoneCodeHash, timeout } = await req.tg.invoke(new Api.auth.ResendCode({
|
| 52 |
-
phoneNumber, phoneCodeHash }))
|
| 53 |
-
const session = req.tg.session.save()
|
| 54 |
-
const accessToken = sign({ session }, API_JWT_SECRET, { expiresIn: '3h' })
|
| 55 |
-
return res.cookie('authorization', `Bearer ${accessToken}`)
|
| 56 |
-
.send({ phoneCodeHash: newPhoneCodeHash, timeout, accessToken })
|
| 57 |
-
}
|
| 58 |
-
|
| 59 |
-
@Endpoint.POST({ middlewares: [TGSessionAuth] })
|
| 60 |
-
public async login(req: Request, res: Response): Promise<any> {
|
| 61 |
-
const { phoneNumber, phoneCode, phoneCodeHash, password, invitationCode } = req.body
|
| 62 |
-
if ((!phoneNumber || !phoneCode || !phoneCodeHash) && !password) {
|
| 63 |
-
if (!password) {
|
| 64 |
-
throw { status: 400, body: { error: 'Password is required' } }
|
| 65 |
-
}
|
| 66 |
-
throw { status: 400, body: { error: 'Phone number, phone code, and phone code hash are required' } }
|
| 67 |
-
}
|
| 68 |
-
|
| 69 |
-
await req.tg.connect()
|
| 70 |
-
let signIn: any
|
| 71 |
-
if (password) {
|
| 72 |
-
const data = await req.tg.invoke(new Api.account.GetPassword())
|
| 73 |
-
data.newAlgo['salt1'] = Buffer.concat([data.newAlgo['salt1'], generateRandomBytes(32)])
|
| 74 |
-
signIn = await req.tg.invoke(new Api.auth.CheckPassword({ password: await computeCheck(data, password) }))
|
| 75 |
-
} else {
|
| 76 |
-
signIn = await req.tg.invoke(new Api.auth.SignIn({ phoneNumber, phoneCode, phoneCodeHash }))
|
| 77 |
-
}
|
| 78 |
-
const userAuth = signIn['user']
|
| 79 |
-
if (!userAuth) {
|
| 80 |
-
throw { status: 400, body: { error: 'User not found/authorized' } }
|
| 81 |
-
}
|
| 82 |
-
|
| 83 |
-
let user = await prisma.users.findFirst({ where: { tg_id: userAuth.id.toString() } })
|
| 84 |
-
const config = await prisma.config.findFirst()
|
| 85 |
-
const username = userAuth.username || userAuth.phone || phoneNumber
|
| 86 |
-
if (!user) {
|
| 87 |
-
if (config?.disable_signup) {
|
| 88 |
-
throw { status: 403, body: { error: 'Signup is disabled' } }
|
| 89 |
-
}
|
| 90 |
-
|
| 91 |
-
if (config?.invitation_code && config?.invitation_code !== invitationCode) {
|
| 92 |
-
throw { status: 403, body: { error: 'Invalid invitation code' } }
|
| 93 |
-
}
|
| 94 |
-
|
| 95 |
-
user = await prisma.users.create({
|
| 96 |
-
data: {
|
| 97 |
-
username,
|
| 98 |
-
plan: 'premium',
|
| 99 |
-
name: `${userAuth.firstName || ''} ${userAuth.lastName || ''}`.trim() || username,
|
| 100 |
-
tg_id: userAuth.id.toString()
|
| 101 |
-
}
|
| 102 |
-
})
|
| 103 |
-
}
|
| 104 |
-
await prisma.users.update({
|
| 105 |
-
data: {
|
| 106 |
-
username,
|
| 107 |
-
plan: 'premium'
|
| 108 |
-
},
|
| 109 |
-
where: { id: user.id }
|
| 110 |
-
})
|
| 111 |
-
|
| 112 |
-
const session = req.tg.session.save()
|
| 113 |
-
const auth = {
|
| 114 |
-
session,
|
| 115 |
-
accessToken: sign({ session }, API_JWT_SECRET, { expiresIn: '15h' }),
|
| 116 |
-
refreshToken: sign({ session }, API_JWT_SECRET, { expiresIn: '1y' }),
|
| 117 |
-
expiredAfter: Date.now() + COOKIE_AGE
|
| 118 |
-
}
|
| 119 |
-
|
| 120 |
-
res
|
| 121 |
-
.cookie('authorization', `Bearer ${auth.accessToken}`, { maxAge: COOKIE_AGE, expires: new Date(auth.expiredAfter) })
|
| 122 |
-
.cookie('refreshToken', auth.refreshToken, { maxAge: 3.154e+10, expires: new Date(Date.now() + 3.154e+10) })
|
| 123 |
-
.send({ user, ...auth })
|
| 124 |
-
|
| 125 |
-
// sync all shared files in background, if any
|
| 126 |
-
prisma.files.findMany({
|
| 127 |
-
where: {
|
| 128 |
-
AND: [
|
| 129 |
-
{ user_id: user.id },
|
| 130 |
-
{
|
| 131 |
-
NOT: { signed_key: null }
|
| 132 |
-
}
|
| 133 |
-
]
|
| 134 |
-
}
|
| 135 |
-
}).then(files => files?.map(file => {
|
| 136 |
-
const signedKey = AES.encrypt(JSON.stringify({ file: { id: file.id }, session: req.tg.session.save() }), FILES_JWT_SECRET).toString()
|
| 137 |
-
prisma.files.update({
|
| 138 |
-
data: { signed_key: signedKey },
|
| 139 |
-
where: { id: file.id }
|
| 140 |
-
})
|
| 141 |
-
}))
|
| 142 |
-
}
|
| 143 |
-
|
| 144 |
-
@Endpoint.POST()
|
| 145 |
-
public async refreshToken(req: Request, res: Response): Promise<any> {
|
| 146 |
-
const refreshToken = req.body?.refreshToken || req.cookies?.refreshToken
|
| 147 |
-
if (!refreshToken) {
|
| 148 |
-
throw { status: 400, body: { error: 'Refresh token is required' } }
|
| 149 |
-
}
|
| 150 |
-
|
| 151 |
-
let data: { session: string }
|
| 152 |
-
try {
|
| 153 |
-
data = verify(refreshToken, API_JWT_SECRET) as { session: string }
|
| 154 |
-
} catch (error) {
|
| 155 |
-
throw { status: 400, body: { error: 'Refresh token is invalid' } }
|
| 156 |
-
}
|
| 157 |
-
|
| 158 |
-
try {
|
| 159 |
-
const session = new StringSession(data.session)
|
| 160 |
-
req.tg = new TelegramClient(session, TG_CREDS.apiId, TG_CREDS.apiHash, {
|
| 161 |
-
connectionRetries: CONNECTION_RETRIES,
|
| 162 |
-
useWSS: false,
|
| 163 |
-
...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
|
| 164 |
-
})
|
| 165 |
-
} catch (error) {
|
| 166 |
-
throw { status: 400, body: { error: 'Invalid key' } }
|
| 167 |
-
}
|
| 168 |
-
|
| 169 |
-
try {
|
| 170 |
-
await req.tg.connect()
|
| 171 |
-
const userAuth = await req.tg.getMe()
|
| 172 |
-
const user = await prisma.users.findFirst({ where: { tg_id: userAuth['id'].toString() } })
|
| 173 |
-
if (!user) {
|
| 174 |
-
throw { status: 404, body: { error: 'User not found' } }
|
| 175 |
-
}
|
| 176 |
-
await prisma.users.update({
|
| 177 |
-
data: {
|
| 178 |
-
username: req.userAuth?.username || req.userAuth?.phone || user.username,
|
| 179 |
-
plan: 'premium'
|
| 180 |
-
},
|
| 181 |
-
where: { id: user.id }
|
| 182 |
-
})
|
| 183 |
-
|
| 184 |
-
const session = req.tg.session.save()
|
| 185 |
-
const auth = {
|
| 186 |
-
session,
|
| 187 |
-
accessToken: sign({ session }, API_JWT_SECRET, { expiresIn: '15h' }),
|
| 188 |
-
refreshToken: sign({ session }, API_JWT_SECRET, { expiresIn: '100y' }),
|
| 189 |
-
expiredAfter: Date.now() + COOKIE_AGE
|
| 190 |
-
}
|
| 191 |
-
return res
|
| 192 |
-
.cookie('authorization', `Bearer ${auth.accessToken}`, { maxAge: COOKIE_AGE, expires: new Date(auth.expiredAfter) })
|
| 193 |
-
.cookie('refreshToken', auth.refreshToken, { maxAge: 3.154e+10, expires: new Date(Date.now() + 3.154e+10) })
|
| 194 |
-
.send({ user, ...auth })
|
| 195 |
-
} catch (error) {
|
| 196 |
-
throw { status: 400, body: { error: error.message || 'Something error', details: serializeError(error) } }
|
| 197 |
-
}
|
| 198 |
-
}
|
| 199 |
-
|
| 200 |
-
/**
|
| 201 |
-
* Initialize export login token to be a param for URL tg://login?token={{token}}
|
| 202 |
-
* @param req
|
| 203 |
-
* @param res
|
| 204 |
-
* @returns
|
| 205 |
-
*/
|
| 206 |
-
@Endpoint.GET({ middlewares: [TGClient] })
|
| 207 |
-
public async qrCode(req: Request, res: Response): Promise<any> {
|
| 208 |
-
await req.tg.connect()
|
| 209 |
-
const data = await req.tg.invoke(new Api.auth.ExportLoginToken({
|
| 210 |
-
...TG_CREDS,
|
| 211 |
-
exceptIds: []
|
| 212 |
-
}))
|
| 213 |
-
|
| 214 |
-
const session = req.tg.session.save()
|
| 215 |
-
const auth = {
|
| 216 |
-
session,
|
| 217 |
-
accessToken: sign({ session }, API_JWT_SECRET, { expiresIn: '15h' }),
|
| 218 |
-
refreshToken: sign({ session }, API_JWT_SECRET, { expiresIn: '100y' }),
|
| 219 |
-
expiredAfter: Date.now() + COOKIE_AGE
|
| 220 |
-
}
|
| 221 |
-
return res
|
| 222 |
-
.cookie('authorization', `Bearer ${auth.accessToken}`, { maxAge: COOKIE_AGE, expires: new Date(auth.expiredAfter) })
|
| 223 |
-
.cookie('refreshToken', auth.refreshToken, { maxAge: 3.154e+10, expires: new Date(Date.now() + 3.154e+10) })
|
| 224 |
-
.send({ loginToken: Buffer.from(data['token'], 'utf8').toString('base64url'), accessToken: auth.accessToken })
|
| 225 |
-
}
|
| 226 |
-
|
| 227 |
-
/**
|
| 228 |
-
* Sign in process with QR Code https://core.telegram.org/api/qr-login
|
| 229 |
-
* @param req
|
| 230 |
-
* @param res
|
| 231 |
-
* @returns
|
| 232 |
-
*/
|
| 233 |
-
@Endpoint.POST({ middlewares: [TGSessionAuth] })
|
| 234 |
-
public async qrCodeSignIn(req: Request, res: Response): Promise<any> {
|
| 235 |
-
const { password, session: sessionString, invitationCode } = req.body
|
| 236 |
-
|
| 237 |
-
// handle the 2fa password in the second call
|
| 238 |
-
if (password && sessionString) {
|
| 239 |
-
req.tg = new TelegramClient(new StringSession(sessionString), TG_CREDS.apiId, TG_CREDS.apiHash, {
|
| 240 |
-
connectionRetries: CONNECTION_RETRIES,
|
| 241 |
-
useWSS: false,
|
| 242 |
-
...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
|
| 243 |
-
})
|
| 244 |
-
await req.tg.connect()
|
| 245 |
-
|
| 246 |
-
const passwordData = await req.tg.invoke(new Api.account.GetPassword())
|
| 247 |
-
|
| 248 |
-
passwordData.newAlgo['salt1'] = Buffer.concat([passwordData.newAlgo['salt1'], generateRandomBytes(32)])
|
| 249 |
-
const signIn = await req.tg.invoke(new Api.auth.CheckPassword({
|
| 250 |
-
password: await computeCheck(passwordData, password)
|
| 251 |
-
}))
|
| 252 |
-
const userAuth = signIn['user']
|
| 253 |
-
if (!userAuth) {
|
| 254 |
-
throw { status: 400, body: { error: 'User not found/authorized' } }
|
| 255 |
-
}
|
| 256 |
-
|
| 257 |
-
let user = await prisma.users.findFirst({ where: { tg_id: userAuth.id.toString() } })
|
| 258 |
-
const config = await prisma.config.findFirst()
|
| 259 |
-
if (!user) {
|
| 260 |
-
if (config?.disable_signup) {
|
| 261 |
-
throw { status: 403, body: { error: 'Signup is disabled' } }
|
| 262 |
-
}
|
| 263 |
-
|
| 264 |
-
if (config?.invitation_code && config?.invitation_code !== invitationCode) {
|
| 265 |
-
throw { status: 403, body: { error: 'Invalid invitation code' } }
|
| 266 |
-
}
|
| 267 |
-
|
| 268 |
-
const username = userAuth.username || userAuth.phone
|
| 269 |
-
user = await prisma.users.create({
|
| 270 |
-
data: {
|
| 271 |
-
username,
|
| 272 |
-
plan: 'premium',
|
| 273 |
-
name: `${userAuth.firstName || ''} ${userAuth.lastName || ''}`.trim() || username,
|
| 274 |
-
tg_id: userAuth.id.toString()
|
| 275 |
-
}
|
| 276 |
-
})
|
| 277 |
-
}
|
| 278 |
-
|
| 279 |
-
await prisma.users.update({
|
| 280 |
-
data: {
|
| 281 |
-
username: userAuth.username || userAuth.phone,
|
| 282 |
-
plan: 'premium'
|
| 283 |
-
},
|
| 284 |
-
where: { id: user.id }
|
| 285 |
-
})
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
const session = req.tg.session.save()
|
| 289 |
-
const auth = {
|
| 290 |
-
session,
|
| 291 |
-
accessToken: sign({ session }, API_JWT_SECRET, { expiresIn: '15h' }),
|
| 292 |
-
refreshToken: sign({ session }, API_JWT_SECRET, { expiresIn: '1y' }),
|
| 293 |
-
expiredAfter: Date.now() + COOKIE_AGE
|
| 294 |
-
}
|
| 295 |
-
|
| 296 |
-
res
|
| 297 |
-
.cookie('authorization', `Bearer ${auth.accessToken}`, { maxAge: COOKIE_AGE, expires: new Date(auth.expiredAfter) })
|
| 298 |
-
.cookie('refreshToken', auth.refreshToken, { maxAge: 3.154e+10, expires: new Date(Date.now() + 3.154e+10) })
|
| 299 |
-
.send({ user, ...auth })
|
| 300 |
-
|
| 301 |
-
// sync all shared files in background, if any
|
| 302 |
-
prisma.files.findMany({
|
| 303 |
-
where: {
|
| 304 |
-
AND: [
|
| 305 |
-
{ user_id: user.id },
|
| 306 |
-
{
|
| 307 |
-
NOT: { signed_key: null }
|
| 308 |
-
}
|
| 309 |
-
]
|
| 310 |
-
}
|
| 311 |
-
}).then(files => files?.map(file => {
|
| 312 |
-
const signedKey = AES.encrypt(JSON.stringify({ file: { id: file.id }, session: req.tg.session.save() }), FILES_JWT_SECRET).toString()
|
| 313 |
-
prisma.files.update({
|
| 314 |
-
data: { signed_key: signedKey },
|
| 315 |
-
where: { id: file.id }
|
| 316 |
-
})
|
| 317 |
-
}))
|
| 318 |
-
return
|
| 319 |
-
}
|
| 320 |
-
|
| 321 |
-
// handle the second call for export login token, result case: success, need to migrate to other dc, or 2fa
|
| 322 |
-
await req.tg.connect()
|
| 323 |
-
try {
|
| 324 |
-
const data = await req.tg.invoke(new Api.auth.ExportLoginToken({
|
| 325 |
-
...TG_CREDS,
|
| 326 |
-
exceptIds: []
|
| 327 |
-
}))
|
| 328 |
-
|
| 329 |
-
// build response with user data and auth data
|
| 330 |
-
const buildResponse = (data: Record<string, any> & { user?: { id: string } })=> {
|
| 331 |
-
const session = req.tg.session.save()
|
| 332 |
-
const auth = {
|
| 333 |
-
session,
|
| 334 |
-
accessToken: sign({ session }, API_JWT_SECRET, { expiresIn: '15h' }),
|
| 335 |
-
refreshToken: sign({ session }, API_JWT_SECRET, { expiresIn: '1y' }),
|
| 336 |
-
expiredAfter: Date.now() + COOKIE_AGE
|
| 337 |
-
}
|
| 338 |
-
res
|
| 339 |
-
.cookie('authorization', `Bearer ${auth.accessToken}`, { maxAge: COOKIE_AGE, expires: new Date(auth.expiredAfter) })
|
| 340 |
-
.cookie('refreshToken', auth.refreshToken, { maxAge: 3.154e+10, expires: new Date(Date.now() + 3.154e+10) })
|
| 341 |
-
.send({ ...data, ...auth })
|
| 342 |
-
|
| 343 |
-
if (data.user?.id) {
|
| 344 |
-
// sync all shared files in background, if any
|
| 345 |
-
prisma.files.findMany({
|
| 346 |
-
where: {
|
| 347 |
-
AND: [
|
| 348 |
-
{ user_id: data.user.id },
|
| 349 |
-
{
|
| 350 |
-
NOT: { signed_key: null }
|
| 351 |
-
}
|
| 352 |
-
]
|
| 353 |
-
}
|
| 354 |
-
}).then(files => files?.map(file => {
|
| 355 |
-
const signedKey = AES.encrypt(JSON.stringify({ file: { id: file.id }, session: req.tg.session.save() }), FILES_JWT_SECRET).toString()
|
| 356 |
-
prisma.files.update({
|
| 357 |
-
data: { signed_key: signedKey },
|
| 358 |
-
where: { id: file.id }
|
| 359 |
-
})
|
| 360 |
-
}))
|
| 361 |
-
}
|
| 362 |
-
return
|
| 363 |
-
}
|
| 364 |
-
|
| 365 |
-
// handle to switch dc
|
| 366 |
-
if (data instanceof Api.auth.LoginTokenMigrateTo) {
|
| 367 |
-
await req.tg._switchDC(data.dcId)
|
| 368 |
-
const result = await req.tg.invoke(new Api.auth.ImportLoginToken({
|
| 369 |
-
token: data.token
|
| 370 |
-
}))
|
| 371 |
-
|
| 372 |
-
// result import login token success
|
| 373 |
-
if (result instanceof Api.auth.LoginTokenSuccess && result.authorization instanceof Api.auth.Authorization) {
|
| 374 |
-
const userAuth = result.authorization.user
|
| 375 |
-
let user = await prisma.users.findFirst({ where: { tg_id: userAuth.id.toString() } })
|
| 376 |
-
const config = await prisma.config.findFirst()
|
| 377 |
-
if (!user) {
|
| 378 |
-
if (config?.disable_signup) {
|
| 379 |
-
throw { status: 403, body: { error: 'Signup is disabled' } }
|
| 380 |
-
}
|
| 381 |
-
|
| 382 |
-
if (config?.invitation_code && config?.invitation_code !== invitationCode) {
|
| 383 |
-
throw { status: 403, body: { error: 'Invalid invitation code' } }
|
| 384 |
-
}
|
| 385 |
-
|
| 386 |
-
const username = userAuth['username'] || userAuth['phone']
|
| 387 |
-
user = await prisma.users.create({
|
| 388 |
-
data: {
|
| 389 |
-
username,
|
| 390 |
-
plan: 'premium',
|
| 391 |
-
name: `${userAuth['firstName'] || ''} ${userAuth['lastName'] || ''}`.trim() || username,
|
| 392 |
-
tg_id: userAuth.id.toString()
|
| 393 |
-
}
|
| 394 |
-
})
|
| 395 |
-
}
|
| 396 |
-
await prisma.users.update({
|
| 397 |
-
data: {
|
| 398 |
-
username: userAuth['username'] || userAuth['phone'],
|
| 399 |
-
plan: 'premium'
|
| 400 |
-
},
|
| 401 |
-
where: { id: user.id }
|
| 402 |
-
})
|
| 403 |
-
return buildResponse({ user })
|
| 404 |
-
}
|
| 405 |
-
return buildResponse({ data, result })
|
| 406 |
-
|
| 407 |
-
// handle if success
|
| 408 |
-
} else if (data instanceof Api.auth.LoginTokenSuccess && data.authorization instanceof Api.auth.Authorization) {
|
| 409 |
-
const userAuth = data.authorization.user
|
| 410 |
-
let user = await prisma.users.findFirst({ where: { tg_id: userAuth.id.toString() } })
|
| 411 |
-
const config = await prisma.config.findFirst()
|
| 412 |
-
if (!user) {
|
| 413 |
-
if (config?.disable_signup) {
|
| 414 |
-
throw { status: 403, body: { error: 'Signup is disabled' } }
|
| 415 |
-
}
|
| 416 |
-
|
| 417 |
-
if (config?.invitation_code && config?.invitation_code !== invitationCode) {
|
| 418 |
-
throw { status: 403, body: { error: 'Invalid invitation code' } }
|
| 419 |
-
}
|
| 420 |
-
|
| 421 |
-
const username = userAuth['username'] || userAuth['phone']
|
| 422 |
-
user = await prisma.users.create({
|
| 423 |
-
data: {
|
| 424 |
-
username,
|
| 425 |
-
plan: 'premium',
|
| 426 |
-
name: `${userAuth['firstName'] || ''} ${userAuth['lastName'] || ''}`.trim() || username,
|
| 427 |
-
tg_id: userAuth.id.toString()
|
| 428 |
-
}
|
| 429 |
-
})
|
| 430 |
-
}
|
| 431 |
-
await prisma.users.update({
|
| 432 |
-
data: {
|
| 433 |
-
username: userAuth['username'] || userAuth['phone'],
|
| 434 |
-
plan: 'premium'
|
| 435 |
-
},
|
| 436 |
-
where: { id: user.id }
|
| 437 |
-
})
|
| 438 |
-
return buildResponse({ user })
|
| 439 |
-
}
|
| 440 |
-
|
| 441 |
-
// data instanceof auth.LoginToken
|
| 442 |
-
return buildResponse({
|
| 443 |
-
loginToken: Buffer.from(data['token'], 'utf8').toString('base64url')
|
| 444 |
-
})
|
| 445 |
-
} catch (error) {
|
| 446 |
-
// handle if need 2fa password
|
| 447 |
-
if (error.errorMessage === 'SESSION_PASSWORD_NEEDED') {
|
| 448 |
-
error.session = req.tg.session.save()
|
| 449 |
-
}
|
| 450 |
-
throw error
|
| 451 |
-
}
|
| 452 |
-
}
|
| 453 |
-
|
| 454 |
-
@Endpoint.GET({ middlewares: [TGSessionAuth] })
|
| 455 |
-
public async me(req: Request, res: Response): Promise<any> {
|
| 456 |
-
await req.tg.connect()
|
| 457 |
-
const data = await req.tg.getMe()
|
| 458 |
-
return res.send({ user: data })
|
| 459 |
-
}
|
| 460 |
-
|
| 461 |
-
@Endpoint.POST({ middlewares: [TGSessionAuth] })
|
| 462 |
-
public async logout(req: Request, res: Response): Promise<any> {
|
| 463 |
-
await req.tg.connect()
|
| 464 |
-
const success = req.query.destroySession === '1' ? await req.tg.invoke(new Api.auth.LogOut()) : true
|
| 465 |
-
await Redis.connect().del(`auth:${req.authKey}`)
|
| 466 |
-
return res.clearCookie('authorization').clearCookie('refreshToken').send({ success })
|
| 467 |
-
}
|
| 468 |
-
}
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/api/v1/Config.ts
DELETED
|
@@ -1,93 +0,0 @@
|
|
| 1 |
-
import crypto from 'crypto'
|
| 2 |
-
import { Request, Response } from 'express'
|
| 3 |
-
import { prisma } from '../../model'
|
| 4 |
-
import { Redis } from '../../service/Cache'
|
| 5 |
-
import { Endpoint } from '../base/Endpoint'
|
| 6 |
-
import { Auth, AuthMaybe } from '../middlewares/Auth'
|
| 7 |
-
|
| 8 |
-
@Endpoint.API()
|
| 9 |
-
export class Config {
|
| 10 |
-
|
| 11 |
-
@Endpoint.GET('/', { middlewares: [AuthMaybe] })
|
| 12 |
-
public async retrieve(req: Request, res: Response): Promise<any> {
|
| 13 |
-
// admin creation
|
| 14 |
-
let admin = await prisma.users.findFirst({ where: { role: 'admin' } })
|
| 15 |
-
if (!admin && process.env.ADMIN_USERNAME) {
|
| 16 |
-
admin = await prisma.users.findFirst({ where: { username: process.env.ADMIN_USERNAME } })
|
| 17 |
-
if (!admin) {
|
| 18 |
-
throw { status: 404, body: { error: 'Admin user not found' } }
|
| 19 |
-
}
|
| 20 |
-
await prisma.users.update({
|
| 21 |
-
data: {
|
| 22 |
-
role: 'admin'
|
| 23 |
-
},
|
| 24 |
-
where: { id: admin.id }
|
| 25 |
-
})
|
| 26 |
-
await Redis.connect().del(`auth:${req.authKey}`)
|
| 27 |
-
}
|
| 28 |
-
|
| 29 |
-
// get or create base config
|
| 30 |
-
let config = await prisma.config.findFirst()
|
| 31 |
-
if (!config) {
|
| 32 |
-
config = await prisma.config.create({
|
| 33 |
-
data: {
|
| 34 |
-
disable_signup: false,
|
| 35 |
-
invitation_code: null
|
| 36 |
-
}
|
| 37 |
-
})
|
| 38 |
-
}
|
| 39 |
-
return res.send({ config: {
|
| 40 |
-
...config,
|
| 41 |
-
invitation_code: req.user?.role === 'admin' ? config.invitation_code : undefined
|
| 42 |
-
} })
|
| 43 |
-
}
|
| 44 |
-
|
| 45 |
-
@Endpoint.PATCH('/', { middlewares: [Auth] })
|
| 46 |
-
public async update(req: Request, res: Response): Promise<any> {
|
| 47 |
-
if (req.user.role !== 'admin') {
|
| 48 |
-
throw { status: 403, body: { error: 'Forbidden' } }
|
| 49 |
-
}
|
| 50 |
-
const { config } = req.body
|
| 51 |
-
if (!config) {
|
| 52 |
-
throw { status: 400, body: { error: 'Invalid request' } }
|
| 53 |
-
}
|
| 54 |
-
const model = await prisma.config.findFirst()
|
| 55 |
-
await prisma.config.update({
|
| 56 |
-
data: {
|
| 57 |
-
disable_signup: config.disable_signup,
|
| 58 |
-
...config.clear_invitation_code ? { invitation_code: null } : {}
|
| 59 |
-
},
|
| 60 |
-
where: { id: model.id }
|
| 61 |
-
})
|
| 62 |
-
return res.send({ config: model })
|
| 63 |
-
}
|
| 64 |
-
|
| 65 |
-
@Endpoint.POST('/resetInvitationCode', { middlewares: [Auth] })
|
| 66 |
-
public async resetInvitationCode(req: Request, res: Response): Promise<any> {
|
| 67 |
-
if (req.user.role !== 'admin') {
|
| 68 |
-
throw { status: 403, body: { error: 'Forbidden' } }
|
| 69 |
-
}
|
| 70 |
-
|
| 71 |
-
const code = crypto.randomBytes(9).toString('base64url')
|
| 72 |
-
const model = await prisma.config.findFirst()
|
| 73 |
-
await prisma.config.update({
|
| 74 |
-
data: {
|
| 75 |
-
invitation_code: code
|
| 76 |
-
},
|
| 77 |
-
where: { id: model.id }
|
| 78 |
-
})
|
| 79 |
-
return res.send({ config: model })
|
| 80 |
-
}
|
| 81 |
-
|
| 82 |
-
@Endpoint.POST('/validateInvitationCode')
|
| 83 |
-
public async validateInvitationCode(req: Request, res: Response): Promise<any> {
|
| 84 |
-
const model = await prisma.config.findFirst()
|
| 85 |
-
if (!model.invitation_code) {
|
| 86 |
-
return res.send({ valid: true })
|
| 87 |
-
}
|
| 88 |
-
const { code } = req.query
|
| 89 |
-
return res.send({
|
| 90 |
-
valid: model.invitation_code === code
|
| 91 |
-
})
|
| 92 |
-
}
|
| 93 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/api/v1/Dialogs.ts
DELETED
|
@@ -1,92 +0,0 @@
|
|
| 1 |
-
import { Api } from 'telegram'
|
| 2 |
-
import bigInt from 'big-integer'
|
| 3 |
-
import { Request, Response } from 'express'
|
| 4 |
-
import { Redis } from '../../service/Cache'
|
| 5 |
-
import { objectParser } from '../../utils/ObjectParser'
|
| 6 |
-
import { Endpoint } from '../base/Endpoint'
|
| 7 |
-
import { Auth } from '../middlewares/Auth'
|
| 8 |
-
|
| 9 |
-
@Endpoint.API()
|
| 10 |
-
export class Dialogs {
|
| 11 |
-
|
| 12 |
-
@Endpoint.GET('/', { middlewares: [Auth] })
|
| 13 |
-
public async find(req: Request, res: Response): Promise<any> {
|
| 14 |
-
const { offset, limit } = req.query
|
| 15 |
-
const dialogs = await Redis.connect().getFromCacheFirst(`dialogs:${req.user.id}:${JSON.stringify(req.query)}`, async () => {
|
| 16 |
-
return objectParser(await req.tg.getDialogs({
|
| 17 |
-
limit: Number(limit) || 0,
|
| 18 |
-
offsetDate: Number(offset) || undefined,
|
| 19 |
-
ignorePinned: false
|
| 20 |
-
}))
|
| 21 |
-
}, 2)
|
| 22 |
-
return res.send({ dialogs })
|
| 23 |
-
}
|
| 24 |
-
|
| 25 |
-
@Endpoint.GET('/:type/:id', { middlewares: [Auth] })
|
| 26 |
-
public async retrieve(req: Request, res: Response): Promise<any> {
|
| 27 |
-
const { type, id } = req.params
|
| 28 |
-
let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
|
| 29 |
-
if (type === 'channel') {
|
| 30 |
-
peer = new Api.InputPeerChannel({
|
| 31 |
-
channelId: bigInt(id),
|
| 32 |
-
accessHash: bigInt(req.query.accessHash as string) })
|
| 33 |
-
} else if (type === 'chat') {
|
| 34 |
-
peer = new Api.InputPeerChat({
|
| 35 |
-
chatId: bigInt(id)
|
| 36 |
-
})
|
| 37 |
-
} else if (type === 'user') {
|
| 38 |
-
peer = new Api.InputPeerUser({
|
| 39 |
-
userId: bigInt(id),
|
| 40 |
-
accessHash: bigInt(req.query.accessHash as string) })
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
const dialogs = await req.tg.invoke(new Api.messages.GetPeerDialogs({
|
| 44 |
-
peers: [new Api.InputDialogPeer({ peer })]
|
| 45 |
-
}))
|
| 46 |
-
|
| 47 |
-
const result = objectParser(dialogs) as any
|
| 48 |
-
return res.send({ dialog: {
|
| 49 |
-
...result,
|
| 50 |
-
dialog: result.dialogs[0],
|
| 51 |
-
message: result.messages[0],
|
| 52 |
-
chat: result.chats[0],
|
| 53 |
-
user: result.users[0],
|
| 54 |
-
dialogs: undefined,
|
| 55 |
-
messages: undefined,
|
| 56 |
-
chats: undefined,
|
| 57 |
-
users: undefined
|
| 58 |
-
} })
|
| 59 |
-
}
|
| 60 |
-
|
| 61 |
-
@Endpoint.GET('/:type/:id/avatar.jpg', { middlewares: [Auth] })
|
| 62 |
-
public async avatar(req: Request, res: Response): Promise<any> {
|
| 63 |
-
const { type, id } = req.params
|
| 64 |
-
let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
|
| 65 |
-
if (type === 'channel') {
|
| 66 |
-
peer = new Api.InputPeerChannel({
|
| 67 |
-
channelId: bigInt(id),
|
| 68 |
-
accessHash: bigInt(req.query.accessHash as string) })
|
| 69 |
-
} else if (type === 'chat') {
|
| 70 |
-
peer = new Api.InputPeerChat({
|
| 71 |
-
chatId: bigInt(id)
|
| 72 |
-
})
|
| 73 |
-
} else if (type === 'user') {
|
| 74 |
-
peer = new Api.InputPeerUser({
|
| 75 |
-
userId: bigInt(id),
|
| 76 |
-
accessHash: bigInt(req.query.accessHash as string) })
|
| 77 |
-
}
|
| 78 |
-
try {
|
| 79 |
-
const file = await req.tg.downloadProfilePhoto(peer)
|
| 80 |
-
if (!file?.length) {
|
| 81 |
-
return res.redirect('https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png')
|
| 82 |
-
}
|
| 83 |
-
res.setHeader('Content-Disposition', `inline; filename=avatar-${id}.jpg`)
|
| 84 |
-
res.setHeader('Content-Type', 'image/jpeg')
|
| 85 |
-
res.setHeader('Content-Length', file.length)
|
| 86 |
-
res.write(file)
|
| 87 |
-
return res.end()
|
| 88 |
-
} catch (error) {
|
| 89 |
-
return res.redirect('https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png')
|
| 90 |
-
}
|
| 91 |
-
}
|
| 92 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/api/v1/Files.ts
DELETED
|
@@ -1,1366 +0,0 @@
|
|
| 1 |
-
import { files, Prisma } from '@prisma/client'
|
| 2 |
-
import bigInt from 'big-integer'
|
| 3 |
-
import { compareSync, hashSync } from 'bcryptjs'
|
| 4 |
-
import checkDiskSpace from 'check-disk-space'
|
| 5 |
-
import contentDisposition from 'content-disposition'
|
| 6 |
-
import { AES, enc } from 'crypto-js'
|
| 7 |
-
import { Request, Response } from 'express'
|
| 8 |
-
import { appendFileSync, createReadStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'fs'
|
| 9 |
-
import moment from 'moment'
|
| 10 |
-
import multer from 'multer'
|
| 11 |
-
import { Api, Logger, TelegramClient } from 'telegram'
|
| 12 |
-
import { LogLevel } from 'telegram/extensions/Logger'
|
| 13 |
-
import { StringSession } from 'telegram/sessions'
|
| 14 |
-
import { prisma } from '../../model'
|
| 15 |
-
import { Redis } from '../../service/Cache'
|
| 16 |
-
import { CACHE_FILES_LIMIT, CONNECTION_RETRIES, FILES_JWT_SECRET, TG_CREDS } from '../../utils/Constant'
|
| 17 |
-
import { buildSort } from '../../utils/FilterQuery'
|
| 18 |
-
import { Endpoint } from '../base/Endpoint'
|
| 19 |
-
import { Auth, AuthMaybe } from '../middlewares/Auth'
|
| 20 |
-
import { Messages } from './Messages'
|
| 21 |
-
|
| 22 |
-
const CACHE_DIR = `${__dirname}/../../../../.cached`
|
| 23 |
-
|
| 24 |
-
@Endpoint.API()
|
| 25 |
-
export class Files {
|
| 26 |
-
|
| 27 |
-
@Endpoint.GET('/', { middlewares: [AuthMaybe] })
|
| 28 |
-
public async find(req: Request, res: Response): Promise<any> {
|
| 29 |
-
const { sort, offset, limit, shared, exclude_parts: excludeParts, full_properties: fullProperties, no_cache: noCache, t: _t, ...filters } = req.query
|
| 30 |
-
const parent = filters?.parent_id && filters.parent_id !== 'null' ? await prisma.files.findFirst({ where: { id: filters.parent_id as string } }) : null
|
| 31 |
-
if (filters?.parent_id && filters.parent_id !== 'null' && !parent) {
|
| 32 |
-
throw { status: 404, body: { error: 'Parent not found' } }
|
| 33 |
-
}
|
| 34 |
-
if (!req.user && !parent?.sharing_options?.includes('*')) {
|
| 35 |
-
throw { status: 404, body: { error: 'Parent not found' } }
|
| 36 |
-
}
|
| 37 |
-
|
| 38 |
-
const getFiles = async (): Promise<[files[], number]> => {
|
| 39 |
-
let where: Record<string, any> = { user_id: req.user?.id } // 'files.user_id = :user'
|
| 40 |
-
if (shared) {
|
| 41 |
-
if (parent?.sharing_options?.includes(req.user?.username) || parent?.sharing_options?.includes('*')) {
|
| 42 |
-
where = {}
|
| 43 |
-
} else {
|
| 44 |
-
// :user = any(files.sharing_options) and (files.parent_id is null or parent.sharing_options is null or cardinality(parent.sharing_options) = 0 or not :user = any(parent.sharing_options))
|
| 45 |
-
where = {
|
| 46 |
-
AND: [
|
| 47 |
-
{
|
| 48 |
-
sharing_options: {
|
| 49 |
-
has: req.user?.username
|
| 50 |
-
}
|
| 51 |
-
},
|
| 52 |
-
{
|
| 53 |
-
OR: [
|
| 54 |
-
{ parent_id: null },
|
| 55 |
-
{ parent: {
|
| 56 |
-
sharing_options: undefined }
|
| 57 |
-
},
|
| 58 |
-
{
|
| 59 |
-
parent: {
|
| 60 |
-
sharing_options: {
|
| 61 |
-
isEmpty: true
|
| 62 |
-
}
|
| 63 |
-
}
|
| 64 |
-
},
|
| 65 |
-
{
|
| 66 |
-
NOT: {
|
| 67 |
-
parent: {
|
| 68 |
-
sharing_options: {
|
| 69 |
-
has: req.user?.username
|
| 70 |
-
}
|
| 71 |
-
}
|
| 72 |
-
}
|
| 73 |
-
}
|
| 74 |
-
]
|
| 75 |
-
}
|
| 76 |
-
]
|
| 77 |
-
}
|
| 78 |
-
}
|
| 79 |
-
}
|
| 80 |
-
|
| 81 |
-
let select = null
|
| 82 |
-
if (fullProperties !== 'true' && fullProperties !== '1') {
|
| 83 |
-
select = {
|
| 84 |
-
created_at: true,
|
| 85 |
-
id: true,
|
| 86 |
-
name: true,
|
| 87 |
-
type: true,
|
| 88 |
-
message_id: true,
|
| 89 |
-
size: true,
|
| 90 |
-
uploaded_at: true,
|
| 91 |
-
upload_progress: true,
|
| 92 |
-
user_id: true,
|
| 93 |
-
parent_id: true,
|
| 94 |
-
sharing_options: true,
|
| 95 |
-
link_id: true,
|
| 96 |
-
forward_info: true,
|
| 97 |
-
password: true
|
| 98 |
-
}
|
| 99 |
-
}
|
| 100 |
-
if (shared && Object.keys(where).length) {
|
| 101 |
-
select['parent'] = true
|
| 102 |
-
}
|
| 103 |
-
|
| 104 |
-
const whereQuery: Prisma.filesWhereInput = {
|
| 105 |
-
AND: [
|
| 106 |
-
where,
|
| 107 |
-
...Object.keys(filters).reduce((res, k) => {
|
| 108 |
-
let obj = { [k]: filters[k] }
|
| 109 |
-
if (filters[k] === 'null') {
|
| 110 |
-
obj = { [k]: null }
|
| 111 |
-
}
|
| 112 |
-
if (/\.in$/.test(k)) {
|
| 113 |
-
obj = { [k.replace(/\.in$/, '')]: {
|
| 114 |
-
in: (filters[k] as string)
|
| 115 |
-
.replace(/^\(/, '')
|
| 116 |
-
.replace(/\'/g, '')
|
| 117 |
-
.replace(/\)$/, '')
|
| 118 |
-
.split(',')
|
| 119 |
-
} }
|
| 120 |
-
}
|
| 121 |
-
if (/\.like$/.test(k)) {
|
| 122 |
-
obj = { [k.replace(/\.like$/, '')]: {
|
| 123 |
-
startsWith: filters[k].toString()
|
| 124 |
-
} }
|
| 125 |
-
}
|
| 126 |
-
return [...res, obj]
|
| 127 |
-
}, []),
|
| 128 |
-
...excludeParts === 'true' || excludeParts === '1' ? [
|
| 129 |
-
{
|
| 130 |
-
OR: [ // (files.name ~ \'.part0*1$\' or files.name !~ \'.part[0-9]+$\')
|
| 131 |
-
{
|
| 132 |
-
AND: [
|
| 133 |
-
{ name: { contains: '.part0' } },
|
| 134 |
-
{ name: { endsWith: '1' } },
|
| 135 |
-
{ NOT: { name: { endsWith: '11' } } },
|
| 136 |
-
{ NOT: { name: { endsWith: '111' } } },
|
| 137 |
-
{ NOT: { name: { endsWith: '1111' } } },
|
| 138 |
-
{ NOT: { name: { endsWith: '21' } } },
|
| 139 |
-
{ NOT: { name: { endsWith: '31' } } },
|
| 140 |
-
{ NOT: { name: { endsWith: '41' } } },
|
| 141 |
-
{ NOT: { name: { endsWith: '51' } } },
|
| 142 |
-
{ NOT: { name: { endsWith: '61' } } },
|
| 143 |
-
{ NOT: { name: { endsWith: '71' } } },
|
| 144 |
-
{ NOT: { name: { endsWith: '81' } } },
|
| 145 |
-
{ NOT: { name: { endsWith: '91' } } },
|
| 146 |
-
]
|
| 147 |
-
},
|
| 148 |
-
{
|
| 149 |
-
NOT: { name: { contains: '.part' } }
|
| 150 |
-
}
|
| 151 |
-
]
|
| 152 |
-
}
|
| 153 |
-
] : []
|
| 154 |
-
],
|
| 155 |
-
}
|
| 156 |
-
return [
|
| 157 |
-
await prisma.files.findMany({
|
| 158 |
-
...select ? { select } : {},
|
| 159 |
-
where: whereQuery,
|
| 160 |
-
skip: Number(offset) || 0,
|
| 161 |
-
take: Number(limit) || 10,
|
| 162 |
-
orderBy: buildSort(sort as string)
|
| 163 |
-
}),
|
| 164 |
-
await prisma.files.count({ where: whereQuery })
|
| 165 |
-
]
|
| 166 |
-
}
|
| 167 |
-
|
| 168 |
-
const [files, length] = noCache === 'true' || noCache === '1' ? await getFiles() : await Redis.connect().getFromCacheFirst(`files:${req.user?.id || 'null'}:${JSON.stringify(req.query)}`, getFiles, 2)
|
| 169 |
-
return res.send({ files: files.map(file => ({ ...file, password: file.password ? '[REDACTED]' : null })), length })
|
| 170 |
-
}
|
| 171 |
-
|
| 172 |
-
@Endpoint.GET('/stats', { middlewares: [Auth] })
|
| 173 |
-
public async stats(req: Request, res: Response): Promise<any> {
|
| 174 |
-
const totalFilesSize = await prisma.files.aggregate({
|
| 175 |
-
_sum: { size: true }
|
| 176 |
-
})
|
| 177 |
-
const totalUserFilesSize = await prisma.files.aggregate({
|
| 178 |
-
_sum: { size: true },
|
| 179 |
-
where: {
|
| 180 |
-
user_id: req.user.id
|
| 181 |
-
}
|
| 182 |
-
})
|
| 183 |
-
|
| 184 |
-
try {
|
| 185 |
-
mkdirSync(`${CACHE_DIR}`, { recursive: true })
|
| 186 |
-
} catch (error) {
|
| 187 |
-
// ignore
|
| 188 |
-
}
|
| 189 |
-
const cachedSize = readdirSync(`${CACHE_DIR}`)
|
| 190 |
-
.filter(filename => statSync(`${CACHE_DIR}/${filename}`).isFile())
|
| 191 |
-
.reduce((res, file) => res + statSync(`${CACHE_DIR}/${file}`).size, 0)
|
| 192 |
-
return res.send({
|
| 193 |
-
stats: {
|
| 194 |
-
system: await checkDiskSpace(__dirname),
|
| 195 |
-
totalFilesSize: totalFilesSize._sum.size,
|
| 196 |
-
totalUserFilesSize: totalUserFilesSize._sum.size,
|
| 197 |
-
cachedSize
|
| 198 |
-
}
|
| 199 |
-
})
|
| 200 |
-
}
|
| 201 |
-
|
| 202 |
-
@Endpoint.POST('/', { middlewares: [Auth] })
|
| 203 |
-
public async save(req: Request, res: Response): Promise<any> {
|
| 204 |
-
const { messageId } = req.query
|
| 205 |
-
const { file } = req.body
|
| 206 |
-
if (!file) {
|
| 207 |
-
throw { status: 400, body: { error: 'File is required in body.' } }
|
| 208 |
-
}
|
| 209 |
-
|
| 210 |
-
let message: any = {}
|
| 211 |
-
if (messageId) {
|
| 212 |
-
if (!file.forward_info) {
|
| 213 |
-
throw { status: 400, body: { error: 'Forward info is required in body.' } }
|
| 214 |
-
}
|
| 215 |
-
|
| 216 |
-
let chat: any
|
| 217 |
-
if (file.forward_info && file.forward_info.match(/^channel\//gi)) {
|
| 218 |
-
const [type, peerId, _id, accessHash] = file.forward_info.split('/')
|
| 219 |
-
let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
|
| 220 |
-
if (type === 'channel') {
|
| 221 |
-
peer = new Api.InputPeerChannel({
|
| 222 |
-
channelId: bigInt(peerId),
|
| 223 |
-
accessHash: bigInt(accessHash as string) })
|
| 224 |
-
chat = await req.tg.invoke(new Api.channels.GetMessages({
|
| 225 |
-
channel: peer,
|
| 226 |
-
id: [new Api.InputMessageID({ id: Number(messageId) })]
|
| 227 |
-
}))
|
| 228 |
-
}
|
| 229 |
-
} else {
|
| 230 |
-
chat = await req.tg.invoke(new Api.messages.GetMessages({
|
| 231 |
-
id: [new Api.InputMessageID({ id: Number(messageId) })]
|
| 232 |
-
})) as any
|
| 233 |
-
}
|
| 234 |
-
|
| 235 |
-
if (!chat?.['messages']?.[0]) {
|
| 236 |
-
throw { status: 404, body: { error: 'Message not found' } }
|
| 237 |
-
}
|
| 238 |
-
|
| 239 |
-
const mimeType = chat['messages'][0].media.photo ? 'image/jpeg' : chat['messages'][0].media.document.mimeType || 'unknown'
|
| 240 |
-
const name = chat['messages'][0].media.photo ? `${chat['messages'][0].media.photo.id}.jpg` : chat['messages'][0].media.document.attributes?.find((atr: any) => atr.fileName)?.fileName || `${chat['messages'][0].media?.document.id}.${mimeType.split('/').pop()}`
|
| 241 |
-
|
| 242 |
-
const getSizes = ({ size, sizes }) => sizes ? sizes.pop() : size
|
| 243 |
-
const size = chat['messages'][0].media.photo ? getSizes(chat['messages'][0].media.photo.sizes.pop()) : chat['messages'][0].media.document?.size
|
| 244 |
-
let type = chat['messages'][0].media.photo || mimeType.match(/^image/gi) ? 'image' : null
|
| 245 |
-
if (chat['messages'][0].media.document?.mimeType.match(/^video/gi) || name.match(/\.mp4$/gi) || name.match(/\.mkv$/gi) || name.match(/\.mov$/gi)) {
|
| 246 |
-
type = 'video'
|
| 247 |
-
} else if (chat['messages'][0].media.document?.mimeType.match(/pdf$/gi) || name.match(/\.doc$/gi) || name.match(/\.docx$/gi) || name.match(/\.xls$/gi) || name.match(/\.xlsx$/gi)) {
|
| 248 |
-
type = 'document'
|
| 249 |
-
} else if (chat['messages'][0].media.document?.mimeType.match(/audio$/gi) || name.match(/\.mp3$/gi) || name.match(/\.ogg$/gi)) {
|
| 250 |
-
type = 'audio'
|
| 251 |
-
}
|
| 252 |
-
|
| 253 |
-
message = {
|
| 254 |
-
name,
|
| 255 |
-
message_id: chat['messages'][0].id.toString(),
|
| 256 |
-
mime_type: mimeType,
|
| 257 |
-
size,
|
| 258 |
-
user_id: req.user.id,
|
| 259 |
-
uploaded_at: new Date(chat['messages'][0].date * 1000),
|
| 260 |
-
type
|
| 261 |
-
}
|
| 262 |
-
}
|
| 263 |
-
return res.send({ file: await prisma.files.create({
|
| 264 |
-
data: {
|
| 265 |
-
...file,
|
| 266 |
-
...message
|
| 267 |
-
}
|
| 268 |
-
}) })
|
| 269 |
-
}
|
| 270 |
-
|
| 271 |
-
@Endpoint.POST({ middlewares: [Auth] })
|
| 272 |
-
public async addFolder(req: Request, res: Response): Promise<any> {
|
| 273 |
-
const { file: data } = req.body
|
| 274 |
-
const count = await prisma.files.count({
|
| 275 |
-
where: {
|
| 276 |
-
AND: [
|
| 277 |
-
{ type: 'folder' },
|
| 278 |
-
{ user_id: req.user.id },
|
| 279 |
-
{ name: { startsWith: data?.name || 'New Folder' } },
|
| 280 |
-
{ parent_id: data?.parent_id || null },
|
| 281 |
-
{ link_id: data?.link_id || null }
|
| 282 |
-
]
|
| 283 |
-
}
|
| 284 |
-
})
|
| 285 |
-
const parent = data?.parent_id ? await prisma.files.findUnique({
|
| 286 |
-
where: { id: data.parent_id }
|
| 287 |
-
}) : null
|
| 288 |
-
|
| 289 |
-
return res.send({ file: await prisma.files.create({
|
| 290 |
-
data: {
|
| 291 |
-
name: (data?.name || 'New Folder') + `${count ? ` (${count})` : ''}`,
|
| 292 |
-
mime_type: 'teledrive/folder',
|
| 293 |
-
user_id: req.user.id,
|
| 294 |
-
type: 'folder',
|
| 295 |
-
uploaded_at: new Date(),
|
| 296 |
-
link_id: data?.link_id,
|
| 297 |
-
...parent ? {
|
| 298 |
-
parent_id: parent.id,
|
| 299 |
-
sharing_options: parent.sharing_options,
|
| 300 |
-
signed_key: parent.signed_key
|
| 301 |
-
} : {}
|
| 302 |
-
}
|
| 303 |
-
}) })
|
| 304 |
-
}
|
| 305 |
-
|
| 306 |
-
@Endpoint.POST({ middlewares: [Auth] })
|
| 307 |
-
public async cloneFile(req: Request, res: Response): Promise<any> {
|
| 308 |
-
const { file: body } = req.body
|
| 309 |
-
const source = await prisma.files.findUnique({ where: { id: body.key } })
|
| 310 |
-
const files = await prisma.files.findMany({
|
| 311 |
-
where: {
|
| 312 |
-
AND: [
|
| 313 |
-
{ name: source.name.endsWith('.part001') ? { startsWith: source.name.replace(/\.part0*\d+$/, '.part') } : source.name },
|
| 314 |
-
{ user_id: req.user?.id },
|
| 315 |
-
{ parent_id: source.parent_id },
|
| 316 |
-
]
|
| 317 |
-
}
|
| 318 |
-
})
|
| 319 |
-
|
| 320 |
-
const countExists = await prisma.files.count({
|
| 321 |
-
where: {
|
| 322 |
-
AND: [
|
| 323 |
-
{ name: source.name.endsWith('.part001') ? { startsWith: source.name.replace(/\.part0*\d+$/, ''), endsWith: '.part001' } : { startsWith: source.name } },
|
| 324 |
-
{ user_id: req.user?.id },
|
| 325 |
-
{ parent_id: body.parent_id }
|
| 326 |
-
]
|
| 327 |
-
}
|
| 328 |
-
})
|
| 329 |
-
|
| 330 |
-
delete body.key
|
| 331 |
-
let countFiles = 0
|
| 332 |
-
for (const file of files) {
|
| 333 |
-
const { forward_info: forwardInfo, message_id: msgId, mime_type: mimeType } = file
|
| 334 |
-
let infoFrom, infoTo
|
| 335 |
-
if (forwardInfo) {
|
| 336 |
-
const [type, id, _id, accessHash] = forwardInfo?.split('/')
|
| 337 |
-
infoFrom = {
|
| 338 |
-
id,
|
| 339 |
-
type,
|
| 340 |
-
accessHash
|
| 341 |
-
}
|
| 342 |
-
}
|
| 343 |
-
if ((req.user.settings as Prisma.JsonObject).saved_location) {
|
| 344 |
-
const [type, id, _, accessHash] = ((req.user.settings as Prisma.JsonObject).saved_location as string).split('/')
|
| 345 |
-
infoTo = {
|
| 346 |
-
id,
|
| 347 |
-
type,
|
| 348 |
-
accessHash
|
| 349 |
-
}
|
| 350 |
-
}
|
| 351 |
-
|
| 352 |
-
req.body['from'] = infoFrom
|
| 353 |
-
req.body['to'] = infoTo || 'me'
|
| 354 |
-
req.params = {
|
| 355 |
-
msgId,
|
| 356 |
-
silent: String(true),
|
| 357 |
-
dropAuthor: String(true),
|
| 358 |
-
cloneFile: String(true)
|
| 359 |
-
}
|
| 360 |
-
const chat = await new Messages().forward(req, res)
|
| 361 |
-
|
| 362 |
-
const newForwardInfo = infoTo ? `${infoTo.type}/${infoTo.id}/${chat.updates[0].id.toString()}/${infoTo.accessHash}` : null
|
| 363 |
-
const message = {
|
| 364 |
-
size: Number(file.size),
|
| 365 |
-
message_id: chat.updates[0].id.toString(),
|
| 366 |
-
mime_type: mimeType,
|
| 367 |
-
forward_info: newForwardInfo,
|
| 368 |
-
uploaded_at: new Date(chat.date * 1000)
|
| 369 |
-
}
|
| 370 |
-
|
| 371 |
-
const response = await prisma.files.create({
|
| 372 |
-
data: {
|
| 373 |
-
...body,
|
| 374 |
-
name: files.length == 1 ? body.name + `${countExists ? ` (${countExists})` : ''}` : body.name.replace(/\.part0*\d+$/, '')+`${countExists ? ` (${countExists})` : ''}`+`.part${String(countFiles + 1).padStart(3, '0')}`,
|
| 375 |
-
...message
|
| 376 |
-
}
|
| 377 |
-
})
|
| 378 |
-
if (countFiles++ == 0)
|
| 379 |
-
res.send({ file: response })
|
| 380 |
-
}
|
| 381 |
-
}
|
| 382 |
-
|
| 383 |
-
@Endpoint.GET('/:id', { middlewares: [AuthMaybe] })
|
| 384 |
-
public async retrieve(req: Request, res: Response): Promise<any> {
|
| 385 |
-
const { id } = req.params
|
| 386 |
-
const { password } = req.query
|
| 387 |
-
const file = await prisma.files.findUnique({
|
| 388 |
-
where: { id }
|
| 389 |
-
})
|
| 390 |
-
|
| 391 |
-
const parent = file?.parent_id ? await prisma.files.findUnique({
|
| 392 |
-
where: { id: file.parent_id }
|
| 393 |
-
}) : null
|
| 394 |
-
if (!file || file.user_id !== req.user?.id && !file.sharing_options?.includes('*') && !file.sharing_options?.includes(req.user?.username)) {
|
| 395 |
-
if (!parent?.sharing_options?.includes(req.user?.username) && !parent?.sharing_options?.includes('*')) {
|
| 396 |
-
throw { status: 404, body: { error: 'File not found' } }
|
| 397 |
-
}
|
| 398 |
-
}
|
| 399 |
-
file.signed_key = file.signed_key || parent?.signed_key
|
| 400 |
-
|
| 401 |
-
if (file.password && req.user?.id !== file.user_id) {
|
| 402 |
-
if (!password) {
|
| 403 |
-
throw { status: 400, body: { error: 'Unauthorized' } }
|
| 404 |
-
}
|
| 405 |
-
if (!compareSync(password as string, file.password)) {
|
| 406 |
-
throw { status: 400, body: { error: 'Wrong passphrase' } }
|
| 407 |
-
}
|
| 408 |
-
}
|
| 409 |
-
|
| 410 |
-
let files = [file]
|
| 411 |
-
if (/.*\.part0*1$/gi.test(file?.name)) {
|
| 412 |
-
// if (req.user?.plan !== 'premium') {
|
| 413 |
-
// throw { status: 402, body: { error: 'Please upgrade your plan for view this file' } }
|
| 414 |
-
// }
|
| 415 |
-
files = await prisma.files.findMany({
|
| 416 |
-
where: {
|
| 417 |
-
AND: [
|
| 418 |
-
{
|
| 419 |
-
OR: [
|
| 420 |
-
{ id },
|
| 421 |
-
{ name: { startsWith: file.name.replace(/\.part0*1$/gi, '') } }
|
| 422 |
-
]
|
| 423 |
-
},
|
| 424 |
-
{ user_id: file.user_id },
|
| 425 |
-
{ parent_id: file.parent_id || null }
|
| 426 |
-
]
|
| 427 |
-
}
|
| 428 |
-
})
|
| 429 |
-
files[0].signed_key = file.signed_key = file.signed_key || parent?.signed_key
|
| 430 |
-
}
|
| 431 |
-
|
| 432 |
-
if (!req.user || file.user_id !== req.user?.id) {
|
| 433 |
-
await Files.initiateSessionTG(req, files)
|
| 434 |
-
await req.tg.connect()
|
| 435 |
-
}
|
| 436 |
-
|
| 437 |
-
return await Files.download(req, res, files)
|
| 438 |
-
}
|
| 439 |
-
|
| 440 |
-
@Endpoint.DELETE('/:id', { middlewares: [Auth] })
|
| 441 |
-
public async remove(req: Request, res: Response): Promise<any> {
|
| 442 |
-
const { id } = req.params
|
| 443 |
-
const { deleteMessage } = req.query
|
| 444 |
-
const file = await prisma.files.findFirst({
|
| 445 |
-
where: {
|
| 446 |
-
AND: [{ id }, { user_id: req.user.id }]
|
| 447 |
-
},
|
| 448 |
-
})
|
| 449 |
-
if (!file) {
|
| 450 |
-
throw { status: 404, body: { error: 'File not found' } }
|
| 451 |
-
}
|
| 452 |
-
|
| 453 |
-
const peerTelegram = async (file: files): Promise<any> => {
|
| 454 |
-
let peer: Api.InputPeerChannel | Api.InputPeerChat
|
| 455 |
-
if (file?.forward_info) {
|
| 456 |
-
const [type, peerId, _id, accessHash] = file.forward_info.split('/')
|
| 457 |
-
if (type === 'channel') {
|
| 458 |
-
peer = new Api.InputPeerChannel({
|
| 459 |
-
channelId: bigInt(peerId),
|
| 460 |
-
accessHash: bigInt(accessHash as string) })
|
| 461 |
-
} else if (type === 'chat') {
|
| 462 |
-
peer = new Api.InputPeerChat({
|
| 463 |
-
chatId: bigInt(peerId)
|
| 464 |
-
})
|
| 465 |
-
}
|
| 466 |
-
}
|
| 467 |
-
return peer
|
| 468 |
-
}
|
| 469 |
-
|
| 470 |
-
const removeFromTelegram = async (peer: any, file: files) => {
|
| 471 |
-
// Checks whether the peer is defined and is a channel
|
| 472 |
-
if (peer && 'accessHash' in peer) {
|
| 473 |
-
try {
|
| 474 |
-
await req.tg.invoke(new Api.channels.DeleteMessages({ id: [Number(file.message_id)], channel: peer }))
|
| 475 |
-
} catch (error) { /* ignore */ }
|
| 476 |
-
} else {
|
| 477 |
-
try {
|
| 478 |
-
await req.tg.invoke(new Api.messages.DeleteMessages({ id: [Number(file.message_id)], revoke: true }))
|
| 479 |
-
} catch (error) { /* ignore */ }
|
| 480 |
-
}
|
| 481 |
-
}
|
| 482 |
-
|
| 483 |
-
if (/.*\.part0*1$/gi.test(file?.name)) {
|
| 484 |
-
const files = await prisma.files.findMany({
|
| 485 |
-
where: {
|
| 486 |
-
AND: [
|
| 487 |
-
{
|
| 488 |
-
OR: [
|
| 489 |
-
{ id },
|
| 490 |
-
{ name: { startsWith: file.name.replace(/\.part0*1$/gi, '') } }
|
| 491 |
-
],
|
| 492 |
-
},
|
| 493 |
-
{ user_id: file.user_id },
|
| 494 |
-
{ parent_id: file.parent_id || null }
|
| 495 |
-
]
|
| 496 |
-
}
|
| 497 |
-
})
|
| 498 |
-
files.map(async (file: files) => {
|
| 499 |
-
await prisma.files.delete({ where: { id: file.id } })
|
| 500 |
-
if (deleteMessage && ['true', '1'].includes(deleteMessage as string)) {
|
| 501 |
-
const peer = await peerTelegram(file)
|
| 502 |
-
await removeFromTelegram(peer, file)
|
| 503 |
-
}
|
| 504 |
-
})
|
| 505 |
-
} else if (deleteMessage && ['true', '1'].includes(deleteMessage as string)) {
|
| 506 |
-
await prisma.files.delete({ where: { id } })
|
| 507 |
-
const peer = await peerTelegram(file)
|
| 508 |
-
await removeFromTelegram(peer, file)
|
| 509 |
-
} else {
|
| 510 |
-
await prisma.files.delete({ where: { id } })
|
| 511 |
-
}
|
| 512 |
-
return res.send({ file })
|
| 513 |
-
}
|
| 514 |
-
|
| 515 |
-
@Endpoint.PATCH('/:id', { middlewares: [Auth] })
|
| 516 |
-
public async update(req: Request, res: Response): Promise<any> {
|
| 517 |
-
const { id } = req.params
|
| 518 |
-
const { file } = req.body
|
| 519 |
-
if (!file) {
|
| 520 |
-
throw { status: 400, body: { error: 'File is required in body' } }
|
| 521 |
-
}
|
| 522 |
-
|
| 523 |
-
const currentFile = await prisma.files.findFirst({
|
| 524 |
-
where: {
|
| 525 |
-
AND: [{ id }, { user_id: req.user.id }]
|
| 526 |
-
}
|
| 527 |
-
})
|
| 528 |
-
if (!currentFile) {
|
| 529 |
-
throw { status: 404, body: { error: 'File not found' } }
|
| 530 |
-
}
|
| 531 |
-
|
| 532 |
-
const parent = file.parent_id ? await prisma.files.findUnique({
|
| 533 |
-
where: { id: file.parent_id }
|
| 534 |
-
}) : null
|
| 535 |
-
|
| 536 |
-
let key: string = currentFile.signed_key || parent?.signed_key
|
| 537 |
-
if (file.sharing_options?.length && !key) {
|
| 538 |
-
key = AES.encrypt(JSON.stringify({ file: { id: file.id }, session: req.tg.session.save() }), FILES_JWT_SECRET).toString()
|
| 539 |
-
}
|
| 540 |
-
|
| 541 |
-
if (!file.sharing_options?.length && !currentFile.sharing_options?.length && !parent?.sharing_options?.length) {
|
| 542 |
-
key = null
|
| 543 |
-
}
|
| 544 |
-
|
| 545 |
-
if (/.*\.part0*1$/gi.test(currentFile?.name)) {
|
| 546 |
-
const files = await prisma.files.findMany({
|
| 547 |
-
where: {
|
| 548 |
-
AND: [
|
| 549 |
-
{
|
| 550 |
-
OR: [
|
| 551 |
-
{ id },
|
| 552 |
-
{ name: { startsWith: currentFile.name.replace(/\.part0*1$/gi, '') } }
|
| 553 |
-
]
|
| 554 |
-
},
|
| 555 |
-
{ user_id: currentFile.user_id },
|
| 556 |
-
{ parent_id: currentFile.parent_id || null }
|
| 557 |
-
]
|
| 558 |
-
}
|
| 559 |
-
})
|
| 560 |
-
await Promise.all(files.map(async current => await prisma.files.update({
|
| 561 |
-
where: { id: current.id },
|
| 562 |
-
data: {
|
| 563 |
-
...file.name ? { name: current.name.replace(current.name.replace(/\.part0*\d+$/gi, ''), file.name) } : {},
|
| 564 |
-
...file.sharing_options !== undefined ? { sharing_options: file.sharing_options } : {},
|
| 565 |
-
...file.parent_id !== undefined ? { parent_id: file.parent_id } : {},
|
| 566 |
-
...parent && current.type === 'folder' ? {
|
| 567 |
-
sharing_options: parent.sharing_options
|
| 568 |
-
} : {},
|
| 569 |
-
signed_key: key,
|
| 570 |
-
...file.password !== undefined ? {
|
| 571 |
-
password: file.password !== null ? hashSync(file.password, 10) : null
|
| 572 |
-
} : {}
|
| 573 |
-
}
|
| 574 |
-
})))
|
| 575 |
-
} else {
|
| 576 |
-
await prisma.files.updateMany({
|
| 577 |
-
where: {
|
| 578 |
-
AND: [
|
| 579 |
-
{ id },
|
| 580 |
-
{ user_id: req.user.id }
|
| 581 |
-
],
|
| 582 |
-
},
|
| 583 |
-
data: {
|
| 584 |
-
...file.name ? { name: currentFile.name.replace(currentFile.name.replace(/\.part0*1$/gi, ''), file.name) } : {},
|
| 585 |
-
...file.sharing_options !== undefined ? { sharing_options: file.sharing_options } : {},
|
| 586 |
-
...file.parent_id !== undefined ? { parent_id: file.parent_id } : {},
|
| 587 |
-
...parent && currentFile.type === 'folder' ? {
|
| 588 |
-
sharing_options: parent.sharing_options
|
| 589 |
-
} : {},
|
| 590 |
-
signed_key: key,
|
| 591 |
-
...file.password !== undefined ? {
|
| 592 |
-
password: file.password !== null ? hashSync(file.password, 10) : null
|
| 593 |
-
} : {}
|
| 594 |
-
}
|
| 595 |
-
})
|
| 596 |
-
}
|
| 597 |
-
|
| 598 |
-
if (file.sharing_options !== undefined && currentFile.type === 'folder') {
|
| 599 |
-
const updateSharingOptions = async (currentFile: files) => {
|
| 600 |
-
const children = await prisma.files.findMany({
|
| 601 |
-
where: {
|
| 602 |
-
AND: [
|
| 603 |
-
{ parent_id: currentFile.id },
|
| 604 |
-
{ type: 'folder' }
|
| 605 |
-
]
|
| 606 |
-
}
|
| 607 |
-
})
|
| 608 |
-
for (const child of children) {
|
| 609 |
-
await prisma.files.updateMany({
|
| 610 |
-
where: {
|
| 611 |
-
AND: [
|
| 612 |
-
{ id: child.id },
|
| 613 |
-
{ user_id: req.user.id }
|
| 614 |
-
]
|
| 615 |
-
},
|
| 616 |
-
data: {
|
| 617 |
-
sharing_options: file.sharing_options,
|
| 618 |
-
signed_key: key || child.signed_key,
|
| 619 |
-
...file.password !== undefined ? {
|
| 620 |
-
password: file.password !== null ? hashSync(file.password, 10) : null
|
| 621 |
-
} : {}
|
| 622 |
-
}
|
| 623 |
-
})
|
| 624 |
-
await updateSharingOptions(child)
|
| 625 |
-
}
|
| 626 |
-
}
|
| 627 |
-
await updateSharingOptions(currentFile)
|
| 628 |
-
}
|
| 629 |
-
|
| 630 |
-
return res.send({ file: { id } })
|
| 631 |
-
}
|
| 632 |
-
|
| 633 |
-
@Endpoint.POST('/upload/:id?', { middlewares: [Auth, multer().single('upload')] })
|
| 634 |
-
public async upload(req: Request, res: Response): Promise<any> {
|
| 635 |
-
const { name, size, mime_type: mimetype, parent_id: parentId, relative_path: relativePath, total_part: totalPart, part } = req.query as Record<string, string>
|
| 636 |
-
|
| 637 |
-
if (!name || !size || !mimetype || !part || !totalPart) {
|
| 638 |
-
throw { status: 400, body: { error: 'Name, size, mimetype, part, and total part are required' } }
|
| 639 |
-
}
|
| 640 |
-
const file = req.file
|
| 641 |
-
if (!file) {
|
| 642 |
-
throw { status: 400, body: { error: 'File upload is required' } }
|
| 643 |
-
}
|
| 644 |
-
|
| 645 |
-
if (file.size > 512 * 1024) {
|
| 646 |
-
throw { status: 400, body: { error: 'Maximum file part size is 500kB' } }
|
| 647 |
-
}
|
| 648 |
-
|
| 649 |
-
// if ((!req.user?.plan || req.user?.plan === 'free') && /\.part\d+$/gi.test(name)) {
|
| 650 |
-
// throw { status: 402, body: { error: 'Payment required' } }
|
| 651 |
-
// }
|
| 652 |
-
|
| 653 |
-
let model: files
|
| 654 |
-
|
| 655 |
-
if (req.params?.id) {
|
| 656 |
-
model = await prisma.files.findUnique({
|
| 657 |
-
where: { id: req.params.id }
|
| 658 |
-
})
|
| 659 |
-
if (!model) {
|
| 660 |
-
throw { status: 404, body: { error: 'File not found' } }
|
| 661 |
-
}
|
| 662 |
-
} else {
|
| 663 |
-
let type = null
|
| 664 |
-
if (mimetype.match(/^image/gi)) {
|
| 665 |
-
type = 'image'
|
| 666 |
-
} else if (mimetype.match(/^video/gi) || name.match(/\.mp4$/gi) || name.match(/\.mkv$/gi) || name.match(/\.mov$/gi)) {
|
| 667 |
-
type = 'video'
|
| 668 |
-
} else if (mimetype.match(/pdf$/gi) || name.match(/\.doc$/gi) || name.match(/\.docx$/gi) || name.match(/\.xls$/gi) || name.match(/\.xlsx$/gi)) {
|
| 669 |
-
type = 'document'
|
| 670 |
-
} else if (mimetype.match(/audio$/gi) || name.match(/\.mp3$/gi) || name.match(/\.ogg$/gi)) {
|
| 671 |
-
type = 'audio'
|
| 672 |
-
} else {
|
| 673 |
-
type = 'unknown'
|
| 674 |
-
}
|
| 675 |
-
|
| 676 |
-
let currentParentId = parentId
|
| 677 |
-
if (relativePath) {
|
| 678 |
-
const paths = relativePath.split('/').slice(0, -1) || []
|
| 679 |
-
for (const i in paths) {
|
| 680 |
-
const path = paths[i]
|
| 681 |
-
const findFolder = await prisma.files.findFirst({
|
| 682 |
-
where: {
|
| 683 |
-
AND: [
|
| 684 |
-
{ type: 'folder' },
|
| 685 |
-
{ name: path },
|
| 686 |
-
{ parent_id: currentParentId || null }
|
| 687 |
-
]
|
| 688 |
-
}
|
| 689 |
-
})
|
| 690 |
-
if (findFolder) {
|
| 691 |
-
currentParentId = findFolder.id
|
| 692 |
-
} else {
|
| 693 |
-
const newFolder = await prisma.files.create({
|
| 694 |
-
data: {
|
| 695 |
-
name: path,
|
| 696 |
-
type: 'folder',
|
| 697 |
-
user_id: req.user.id,
|
| 698 |
-
mime_type: 'teledrive/folder',
|
| 699 |
-
uploaded_at: new Date(),
|
| 700 |
-
...currentParentId ? { parent_id: currentParentId } : {}
|
| 701 |
-
}
|
| 702 |
-
})
|
| 703 |
-
currentParentId = newFolder.id
|
| 704 |
-
}
|
| 705 |
-
}
|
| 706 |
-
}
|
| 707 |
-
|
| 708 |
-
model = await prisma.files.findFirst({
|
| 709 |
-
where: {
|
| 710 |
-
name: name,
|
| 711 |
-
mime_type: mimetype,
|
| 712 |
-
size: Number(size),
|
| 713 |
-
user_id: req.user.id,
|
| 714 |
-
type: type,
|
| 715 |
-
parent_id: currentParentId || null,
|
| 716 |
-
}
|
| 717 |
-
})
|
| 718 |
-
|
| 719 |
-
if (model) {
|
| 720 |
-
await prisma.files.update({
|
| 721 |
-
data: {
|
| 722 |
-
message_id: null,
|
| 723 |
-
uploaded_at: null,
|
| 724 |
-
upload_progress: 0
|
| 725 |
-
},
|
| 726 |
-
where: { id: model.id }
|
| 727 |
-
})
|
| 728 |
-
} else {
|
| 729 |
-
model = await prisma.files.create({
|
| 730 |
-
data: {
|
| 731 |
-
name: name,
|
| 732 |
-
mime_type: mimetype,
|
| 733 |
-
size: Number(size),
|
| 734 |
-
user_id: req.user.id,
|
| 735 |
-
type: type,
|
| 736 |
-
parent_id: currentParentId || null,
|
| 737 |
-
upload_progress: 0,
|
| 738 |
-
file_id: bigInt.randBetween('-1e100', '1e100').toString(),
|
| 739 |
-
forward_info: (req.user.settings as Prisma.JsonObject)?.saved_location as string || null,
|
| 740 |
-
}
|
| 741 |
-
})
|
| 742 |
-
}
|
| 743 |
-
}
|
| 744 |
-
|
| 745 |
-
// upload per part
|
| 746 |
-
let uploadPartStatus: boolean
|
| 747 |
-
const uploadPart = async () => await req.tg.invoke(new Api.upload.SaveBigFilePart({
|
| 748 |
-
fileId: bigInt(model.file_id),
|
| 749 |
-
filePart: Number(part),
|
| 750 |
-
fileTotalParts: Number(totalPart),
|
| 751 |
-
bytes: file.buffer
|
| 752 |
-
}))
|
| 753 |
-
|
| 754 |
-
try {
|
| 755 |
-
uploadPartStatus = await uploadPart()
|
| 756 |
-
} catch (error) {
|
| 757 |
-
try {
|
| 758 |
-
await new Promise((resolve) => setTimeout(resolve, 1000))
|
| 759 |
-
await req.tg?.connect()
|
| 760 |
-
uploadPartStatus = await uploadPart()
|
| 761 |
-
} catch (error) {
|
| 762 |
-
await new Promise((resolve) => setTimeout(resolve, 1000))
|
| 763 |
-
await req.tg?.connect()
|
| 764 |
-
uploadPartStatus = await uploadPart()
|
| 765 |
-
}
|
| 766 |
-
}
|
| 767 |
-
|
| 768 |
-
// model.size = bigInt(model.size).add(file.buffer.length).toString()
|
| 769 |
-
await prisma.files.update({
|
| 770 |
-
where: { id: model.id },
|
| 771 |
-
data: {
|
| 772 |
-
upload_progress: (Number(part) + 1) / Number(totalPart)
|
| 773 |
-
}
|
| 774 |
-
})
|
| 775 |
-
|
| 776 |
-
if (Number(part) < Number(totalPart) - 1) {
|
| 777 |
-
return res.status(202).send({ accepted: true, file: { id: model.id }, uploadPartStatus })
|
| 778 |
-
}
|
| 779 |
-
|
| 780 |
-
// begin to send
|
| 781 |
-
const sendData = async (forceDocument: boolean) => {
|
| 782 |
-
let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
|
| 783 |
-
if ((req.user.settings as Prisma.JsonObject)?.saved_location) {
|
| 784 |
-
const [type, peerId, _, accessHash] = ((req.user.settings as Prisma.JsonObject).saved_location as string).split('/')
|
| 785 |
-
if (type === 'channel') {
|
| 786 |
-
peer = new Api.InputPeerChannel({
|
| 787 |
-
channelId: bigInt(peerId),
|
| 788 |
-
accessHash: accessHash ? bigInt(accessHash as string) : null })
|
| 789 |
-
} else if (type === 'user') {
|
| 790 |
-
peer = new Api.InputPeerUser({
|
| 791 |
-
userId: bigInt(peerId),
|
| 792 |
-
accessHash: bigInt(accessHash as string) })
|
| 793 |
-
} else if (type === 'chat') {
|
| 794 |
-
peer = new Api.InputPeerChat({
|
| 795 |
-
chatId: bigInt(peerId) })
|
| 796 |
-
}
|
| 797 |
-
}
|
| 798 |
-
return await req.tg.sendFile(peer || 'me', {
|
| 799 |
-
file: new Api.InputFileBig({
|
| 800 |
-
id: bigInt(model.file_id),
|
| 801 |
-
parts: Number(totalPart),
|
| 802 |
-
name: model.name
|
| 803 |
-
}),
|
| 804 |
-
forceDocument,
|
| 805 |
-
caption: model.name,
|
| 806 |
-
fileSize: Number(model.size),
|
| 807 |
-
attributes: forceDocument ? [
|
| 808 |
-
new Api.DocumentAttributeFilename({ fileName: model.name })
|
| 809 |
-
] : undefined,
|
| 810 |
-
workers: 1
|
| 811 |
-
})
|
| 812 |
-
}
|
| 813 |
-
|
| 814 |
-
let data: Api.Message
|
| 815 |
-
try {
|
| 816 |
-
data = await sendData(false)
|
| 817 |
-
} catch (error) {
|
| 818 |
-
data = await sendData(true)
|
| 819 |
-
}
|
| 820 |
-
|
| 821 |
-
let forwardInfo = null
|
| 822 |
-
if ((req.user.settings as Prisma.JsonObject)?.saved_location) {
|
| 823 |
-
const [type, peerId, _, accessHash] = ((req.user.settings as Prisma.JsonObject).saved_location as string).split('/')
|
| 824 |
-
forwardInfo = `${type}/${peerId}/${data.id?.toString()}/${accessHash}`
|
| 825 |
-
}
|
| 826 |
-
|
| 827 |
-
await prisma.files.update({
|
| 828 |
-
data: {
|
| 829 |
-
message_id: data.id?.toString(),
|
| 830 |
-
uploaded_at: data.date ? new Date(data.date * 1000) : null,
|
| 831 |
-
upload_progress: null,
|
| 832 |
-
...forwardInfo ? { forward_info: forwardInfo } : {}
|
| 833 |
-
},
|
| 834 |
-
where: { id: model.id }
|
| 835 |
-
})
|
| 836 |
-
|
| 837 |
-
return res.status(202).send({ accepted: true, file: { id: model.id } })
|
| 838 |
-
}
|
| 839 |
-
|
| 840 |
-
@Endpoint.POST('/uploadBeta/:id?', { middlewares: [Auth] })
|
| 841 |
-
public async uploadBeta(req: Request, res: Response): Promise<any> {
|
| 842 |
-
const {
|
| 843 |
-
name,
|
| 844 |
-
size,
|
| 845 |
-
mime_type: mimetype,
|
| 846 |
-
parent_id: parentId,
|
| 847 |
-
relative_path: relativePath,
|
| 848 |
-
total_part: totalPart,
|
| 849 |
-
part,
|
| 850 |
-
message
|
| 851 |
-
} = req.body as Record<string, any>
|
| 852 |
-
|
| 853 |
-
let model: files
|
| 854 |
-
if (req.params?.id) {
|
| 855 |
-
model = await prisma.files.findUnique({
|
| 856 |
-
where: { id: req.params.id }
|
| 857 |
-
})
|
| 858 |
-
if (!model) {
|
| 859 |
-
throw { status: 404, body: { error: 'File not found' } }
|
| 860 |
-
}
|
| 861 |
-
}
|
| 862 |
-
|
| 863 |
-
if (!message) {
|
| 864 |
-
// if ((!req.user?.plan || req.user?.plan === 'free') && /\.part\d+$/gi.test(name)) {
|
| 865 |
-
// throw { status: 402, body: { error: 'Payment required' } }
|
| 866 |
-
// }
|
| 867 |
-
|
| 868 |
-
if (!model) {
|
| 869 |
-
let type = null
|
| 870 |
-
if (mimetype.match(/^image/gi)) {
|
| 871 |
-
type = 'image'
|
| 872 |
-
} else if (mimetype.match(/^video/gi) || name.match(/\.mp4$/gi) || name.match(/\.mkv$/gi) || name.match(/\.mov$/gi)) {
|
| 873 |
-
type = 'video'
|
| 874 |
-
} else if (mimetype.match(/pdf$/gi) || name.match(/\.doc$/gi) || name.match(/\.docx$/gi) || name.match(/\.xls$/gi) || name.match(/\.xlsx$/gi)) {
|
| 875 |
-
type = 'document'
|
| 876 |
-
} else if (mimetype.match(/audio$/gi) || name.match(/\.mp3$/gi) || name.match(/\.ogg$/gi)) {
|
| 877 |
-
type = 'audio'
|
| 878 |
-
} else {
|
| 879 |
-
type = 'unknown'
|
| 880 |
-
}
|
| 881 |
-
|
| 882 |
-
let currentParentId = parentId
|
| 883 |
-
if (relativePath) {
|
| 884 |
-
const paths = relativePath.split('/').slice(0, -1) || []
|
| 885 |
-
for (const i in paths) {
|
| 886 |
-
const path = paths[i]
|
| 887 |
-
const findFolder = await prisma.files.findFirst({
|
| 888 |
-
where: {
|
| 889 |
-
AND: [
|
| 890 |
-
{ type: 'folder' },
|
| 891 |
-
{ name: path },
|
| 892 |
-
{ user_id: req.user.id },
|
| 893 |
-
{ parent_id: currentParentId || null }
|
| 894 |
-
]
|
| 895 |
-
}
|
| 896 |
-
})
|
| 897 |
-
if (findFolder) {
|
| 898 |
-
currentParentId = findFolder.id
|
| 899 |
-
} else {
|
| 900 |
-
const newFolder = await prisma.files.create({
|
| 901 |
-
data: {
|
| 902 |
-
name: path,
|
| 903 |
-
type: 'folder',
|
| 904 |
-
user_id: req.user.id,
|
| 905 |
-
mime_type: 'teledrive/folder',
|
| 906 |
-
...currentParentId ? { parent_id: currentParentId } : {}
|
| 907 |
-
}
|
| 908 |
-
})
|
| 909 |
-
currentParentId = newFolder.id
|
| 910 |
-
}
|
| 911 |
-
}
|
| 912 |
-
}
|
| 913 |
-
|
| 914 |
-
model = await prisma.files.findFirst({
|
| 915 |
-
where: {
|
| 916 |
-
name: name,
|
| 917 |
-
mime_type: mimetype,
|
| 918 |
-
size: Number(size),
|
| 919 |
-
user_id: req.user.id,
|
| 920 |
-
type: type,
|
| 921 |
-
parent_id: currentParentId || null,
|
| 922 |
-
}
|
| 923 |
-
})
|
| 924 |
-
|
| 925 |
-
if (model) {
|
| 926 |
-
await prisma.files.update({
|
| 927 |
-
data: {
|
| 928 |
-
message_id: null,
|
| 929 |
-
uploaded_at: null,
|
| 930 |
-
upload_progress: 0
|
| 931 |
-
},
|
| 932 |
-
where: { id: model.id }
|
| 933 |
-
})
|
| 934 |
-
} else {
|
| 935 |
-
model = await prisma.files.create({
|
| 936 |
-
data: {
|
| 937 |
-
name: name,
|
| 938 |
-
mime_type: mimetype,
|
| 939 |
-
size: Number(size),
|
| 940 |
-
user_id: req.user.id,
|
| 941 |
-
type: type,
|
| 942 |
-
parent_id: currentParentId || null,
|
| 943 |
-
upload_progress: 0,
|
| 944 |
-
file_id: bigInt.randBetween('-1e100', '1e100').toString(),
|
| 945 |
-
forward_info: (req.user.settings as Prisma.JsonObject)?.saved_location as string || null,
|
| 946 |
-
}
|
| 947 |
-
})
|
| 948 |
-
}
|
| 949 |
-
}
|
| 950 |
-
|
| 951 |
-
// model.size = bigInt(model.size).add(file.buffer.length).toString()
|
| 952 |
-
await prisma.files.update({
|
| 953 |
-
data: {
|
| 954 |
-
upload_progress: (Number(part) + 1) / Number(totalPart)
|
| 955 |
-
},
|
| 956 |
-
where: { id: model.id }
|
| 957 |
-
})
|
| 958 |
-
|
| 959 |
-
// if (Number(part) < Number(totalPart) - 1) {
|
| 960 |
-
if (!message) {
|
| 961 |
-
return res.status(202).send({ accepted: true, file: { id: model.id, file_id: model.file_id, name: model.name, size: model.size, type: model.type } })
|
| 962 |
-
}
|
| 963 |
-
}
|
| 964 |
-
|
| 965 |
-
let forwardInfo: string
|
| 966 |
-
if ((req.user.settings as Prisma.JsonObject)?.saved_location) {
|
| 967 |
-
const [type, peerId, _, accessHash] = ((req.user.settings as Prisma.JsonObject).saved_location as string).split('/')
|
| 968 |
-
forwardInfo = `${type}/${peerId}/${message.id?.toString()}/${accessHash}`
|
| 969 |
-
}
|
| 970 |
-
|
| 971 |
-
await prisma.files.update({
|
| 972 |
-
data: {
|
| 973 |
-
message_id: message.id?.toString(),
|
| 974 |
-
uploaded_at: message.date ? new Date(message.date * 1000) : null,
|
| 975 |
-
upload_progress: null,
|
| 976 |
-
...forwardInfo ? { forward_info: forwardInfo } : {}
|
| 977 |
-
},
|
| 978 |
-
where: { id: model.id }
|
| 979 |
-
})
|
| 980 |
-
return res.status(202).send({ accepted: true, file: { id: model.id, file_id: model.file_id, name: model.name, size: model.size, type: model.type } })
|
| 981 |
-
}
|
| 982 |
-
|
| 983 |
-
@Endpoint.GET('/breadcrumbs/:id', { middlewares: [AuthMaybe] })
|
| 984 |
-
public async breadcrumbs(req: Request, res: Response): Promise<any> {
|
| 985 |
-
const { id } = req.params
|
| 986 |
-
let folder = await prisma.files.findUnique({ where: { id } })
|
| 987 |
-
if (!folder) {
|
| 988 |
-
throw { status: 404, body: { error: 'File not found' } }
|
| 989 |
-
}
|
| 990 |
-
if (req.user?.id !== folder.user_id) {
|
| 991 |
-
if (!folder.sharing_options?.includes('*') && !folder.sharing_options?.includes(req.user?.username)) {
|
| 992 |
-
throw { status: 404, body: { error: 'File not found' } }
|
| 993 |
-
}
|
| 994 |
-
}
|
| 995 |
-
|
| 996 |
-
const breadcrumbs = [folder]
|
| 997 |
-
while (folder.parent_id) {
|
| 998 |
-
folder = await prisma.files.findUnique({ where: { id: folder.parent_id } })
|
| 999 |
-
if (!req.user && folder.sharing_options?.includes('*') || folder.sharing_options?.includes(req.user?.username) || folder.user_id === req.user?.id) {
|
| 1000 |
-
breadcrumbs.push(folder)
|
| 1001 |
-
}
|
| 1002 |
-
}
|
| 1003 |
-
|
| 1004 |
-
return res.send({ breadcrumbs: breadcrumbs.reverse() })
|
| 1005 |
-
}
|
| 1006 |
-
|
| 1007 |
-
@Endpoint.POST('/sync', { middlewares: [Auth] })
|
| 1008 |
-
public async sync(req: Request, res: Response): Promise<any> {
|
| 1009 |
-
const { parent_id: parentId, limit } = req.query
|
| 1010 |
-
|
| 1011 |
-
// if (req.user.plan === 'free' || !req.user.plan) {
|
| 1012 |
-
// throw { status: 402, body: { error: 'Payment required' } }
|
| 1013 |
-
// }
|
| 1014 |
-
|
| 1015 |
-
let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
|
| 1016 |
-
const [peerType, peerId, _, accessHash] = ((req.user.settings as Prisma.JsonObject).saved_location as string)?.split('/') || [null, null, null, null]
|
| 1017 |
-
if ((req.user.settings as Prisma.JsonObject)?.saved_location) {
|
| 1018 |
-
if (peerType === 'channel') {
|
| 1019 |
-
peer = new Api.InputPeerChannel({
|
| 1020 |
-
channelId: bigInt(peerId),
|
| 1021 |
-
accessHash: accessHash ? bigInt(accessHash as string) : null })
|
| 1022 |
-
} else if (peerType === 'user') {
|
| 1023 |
-
peer = new Api.InputPeerUser({
|
| 1024 |
-
userId: bigInt(peerId),
|
| 1025 |
-
accessHash: bigInt(accessHash as string) })
|
| 1026 |
-
} else if (peerType === 'chat') {
|
| 1027 |
-
peer = new Api.InputPeerChat({
|
| 1028 |
-
chatId: bigInt(peerId) })
|
| 1029 |
-
}
|
| 1030 |
-
}
|
| 1031 |
-
|
| 1032 |
-
let files = []
|
| 1033 |
-
let found = true
|
| 1034 |
-
let offsetId: number
|
| 1035 |
-
while (files.length < (Number(limit) || 10) && found) {
|
| 1036 |
-
const messages = await req.tg.invoke(new Api.messages.GetHistory({
|
| 1037 |
-
peer: peer || 'me',
|
| 1038 |
-
limit: Number(limit) || 10,
|
| 1039 |
-
offsetId: offsetId || 0,
|
| 1040 |
-
}))
|
| 1041 |
-
|
| 1042 |
-
if (messages['messages']?.length) {
|
| 1043 |
-
offsetId = messages['messages'][messages['messages'].length - 1].id
|
| 1044 |
-
files = [...files, ...messages['messages'].filter((msg: any) => msg?.media?.photo || msg?.media?.document)]
|
| 1045 |
-
} else {
|
| 1046 |
-
found = false
|
| 1047 |
-
}
|
| 1048 |
-
}
|
| 1049 |
-
|
| 1050 |
-
files = files.slice(0, Number(limit) || 10)
|
| 1051 |
-
|
| 1052 |
-
if (files?.length) {
|
| 1053 |
-
const existFiles = await prisma.files.findMany({
|
| 1054 |
-
where: {
|
| 1055 |
-
AND: [
|
| 1056 |
-
{
|
| 1057 |
-
message_id: {
|
| 1058 |
-
in: files.map(file => file.id.toString())
|
| 1059 |
-
}
|
| 1060 |
-
},
|
| 1061 |
-
{ parent_id: parentId as string || null },
|
| 1062 |
-
{ forward_info: null }
|
| 1063 |
-
]
|
| 1064 |
-
}
|
| 1065 |
-
})
|
| 1066 |
-
const filesWantToSave = files.filter(file => !existFiles.find(e => e.message_id == file.id))
|
| 1067 |
-
if (filesWantToSave?.length) {
|
| 1068 |
-
await prisma.files.createMany({
|
| 1069 |
-
data: filesWantToSave.map(file => {
|
| 1070 |
-
const mimeType = file.media.photo ? 'image/jpeg' : file.media.document.mimeType || 'unknown'
|
| 1071 |
-
const name = file.media.photo ? `${file.media.photo.id}.jpg` : file.media.document.attributes?.find((atr: any) => atr.fileName)?.fileName || `${file.media?.document.id}.${mimeType.split('/').pop()}`
|
| 1072 |
-
|
| 1073 |
-
const getSizes = ({ size, sizes }) => sizes ? sizes.pop() : size
|
| 1074 |
-
const size = file.media.photo ? getSizes(file.media.photo.sizes.pop()) : file.media.document?.size
|
| 1075 |
-
let type = file.media.photo
|
| 1076 |
-
if (file.media.document?.mimeType.match(/^video/gi) || name.match(/\.mp4$/gi) || name.match(/\.mkv$/gi) || name.match(/\.mov$/gi)) {
|
| 1077 |
-
type = 'video'
|
| 1078 |
-
} else if (file.media.document?.mimeType.match(/pdf$/gi) || name.match(/\.doc$/gi) || name.match(/\.docx$/gi) || name.match(/\.xls$/gi) || name.match(/\.xlsx$/gi)) {
|
| 1079 |
-
type = 'document'
|
| 1080 |
-
} else if (file.media.document?.mimeType.match(/audio$/gi) || name.match(/\.mp3$/gi) || name.match(/\.ogg$/gi)) {
|
| 1081 |
-
type = 'audio'
|
| 1082 |
-
} else if (file.media.document?.mimeType.match(/^image/gi) || name.match(/\.jpg$/gi) || name.match(/\.jpeg$/gi) || name.match(/\.png$/gi) || name.match(/\.gif$/gi)) {
|
| 1083 |
-
type = 'image'
|
| 1084 |
-
}
|
| 1085 |
-
return {
|
| 1086 |
-
name,
|
| 1087 |
-
message_id: file.id.toString(),
|
| 1088 |
-
mime_type: mimeType,
|
| 1089 |
-
size: size.value,
|
| 1090 |
-
user_id: req.user.id,
|
| 1091 |
-
uploaded_at: new Date(file.date * 1000),
|
| 1092 |
-
type,
|
| 1093 |
-
parent_id: parentId ? parentId.toString() : null,
|
| 1094 |
-
forward_info: peer ? `${peerType}/${peerId}/${file.id.toString()}/${accessHash}` : null
|
| 1095 |
-
}
|
| 1096 |
-
})
|
| 1097 |
-
})
|
| 1098 |
-
}
|
| 1099 |
-
}
|
| 1100 |
-
return res.send({ files })
|
| 1101 |
-
}
|
| 1102 |
-
|
| 1103 |
-
@Endpoint.POST('/filesSync', { middlewares: [Auth] })
|
| 1104 |
-
public async filesSync(req: Request, res: Response): Promise<any> {
|
| 1105 |
-
const { files } = req.body
|
| 1106 |
-
for (const file of files) {
|
| 1107 |
-
const existFile = await prisma.files.findFirst({
|
| 1108 |
-
where: {
|
| 1109 |
-
AND: [
|
| 1110 |
-
{ name: file.name },
|
| 1111 |
-
{ type: file.type },
|
| 1112 |
-
{ size: Number(file.size) || null },
|
| 1113 |
-
{
|
| 1114 |
-
parent_id: file.parent_id ? { not: null } : null
|
| 1115 |
-
}
|
| 1116 |
-
]
|
| 1117 |
-
}
|
| 1118 |
-
})
|
| 1119 |
-
if (!existFile) {
|
| 1120 |
-
try {
|
| 1121 |
-
await prisma.files.create({
|
| 1122 |
-
data: {
|
| 1123 |
-
...file,
|
| 1124 |
-
size: Number(file.size),
|
| 1125 |
-
user_id: req.user.id,
|
| 1126 |
-
}
|
| 1127 |
-
})
|
| 1128 |
-
} catch (error) {
|
| 1129 |
-
// ignore
|
| 1130 |
-
}
|
| 1131 |
-
}
|
| 1132 |
-
}
|
| 1133 |
-
return res.status(202).send({ accepted: true })
|
| 1134 |
-
}
|
| 1135 |
-
|
| 1136 |
-
public static async download(req: Request, res: Response, files: files[], onlyHeaders?: boolean): Promise<any> {
|
| 1137 |
-
const { raw, dl, thumb, as_array: asArray } = req.query
|
| 1138 |
-
|
| 1139 |
-
let usage = await prisma.usages.findFirst({
|
| 1140 |
-
where: {
|
| 1141 |
-
key: req.user ? `u:${req.user.id}` : `ip:${req.headers['cf-connecting-ip'] as string || req.ip}`
|
| 1142 |
-
}
|
| 1143 |
-
})
|
| 1144 |
-
if (!usage) {
|
| 1145 |
-
usage = await prisma.usages.create({
|
| 1146 |
-
data: {
|
| 1147 |
-
key: req.user ? `u:${req.user.id}` : `ip:${req.headers['cf-connecting-ip'] as string || req.ip}`,
|
| 1148 |
-
usage: 0,
|
| 1149 |
-
expire: moment().add(1, 'day').toDate()
|
| 1150 |
-
}
|
| 1151 |
-
})
|
| 1152 |
-
}
|
| 1153 |
-
|
| 1154 |
-
if (new Date().getTime() - new Date(usage.expire).getTime() > 0) { // is expired
|
| 1155 |
-
usage = await prisma.usages.update({
|
| 1156 |
-
data: {
|
| 1157 |
-
expire: moment().add(1, 'day').toDate(),
|
| 1158 |
-
usage: 0
|
| 1159 |
-
},
|
| 1160 |
-
where: { key: usage.key }
|
| 1161 |
-
})
|
| 1162 |
-
}
|
| 1163 |
-
|
| 1164 |
-
const totalFileSize = files.reduce((res, file) => res.add(file.size || 0), bigInt(0))
|
| 1165 |
-
|
| 1166 |
-
if (!raw || Number(raw) === 0) {
|
| 1167 |
-
const { signed_key: _, ...result } = files[0]
|
| 1168 |
-
return res.send({ file: { ...result, password: result.password ? '[REDACTED]' : null } })
|
| 1169 |
-
}
|
| 1170 |
-
|
| 1171 |
-
usage = await prisma.usages.update({
|
| 1172 |
-
data: {
|
| 1173 |
-
usage: bigInt(totalFileSize).add(bigInt(usage.usage)).toJSNumber()
|
| 1174 |
-
},
|
| 1175 |
-
where: { key: usage.key }
|
| 1176 |
-
})
|
| 1177 |
-
if (asArray === '1') {
|
| 1178 |
-
return res.send({ files })
|
| 1179 |
-
}
|
| 1180 |
-
|
| 1181 |
-
console.log(req.headers.range)
|
| 1182 |
-
|
| 1183 |
-
let cancel = false
|
| 1184 |
-
req.on('close', () => cancel = true)
|
| 1185 |
-
|
| 1186 |
-
const ranges = req.headers.range ? req.headers.range.replace(/bytes\=/gi, '').split('-').map(Number) : null
|
| 1187 |
-
|
| 1188 |
-
if (onlyHeaders) return res.status(200)
|
| 1189 |
-
|
| 1190 |
-
const filename = (prefix: string = '') => `${CACHE_DIR}/${prefix}${totalFileSize.toString()}_${files[0].name}`
|
| 1191 |
-
try {
|
| 1192 |
-
mkdirSync(`${CACHE_DIR}`, { recursive: true })
|
| 1193 |
-
} catch (error) {
|
| 1194 |
-
// ignore
|
| 1195 |
-
}
|
| 1196 |
-
|
| 1197 |
-
const cachedFiles = () => readdirSync(`${CACHE_DIR}`)
|
| 1198 |
-
.filter(filename =>
|
| 1199 |
-
statSync(`${CACHE_DIR}/${filename}`).isFile()
|
| 1200 |
-
).sort((a, b) =>
|
| 1201 |
-
new Date(statSync(`${CACHE_DIR}/${a}`).birthtime).getTime()
|
| 1202 |
-
- new Date(statSync(`${CACHE_DIR}/${b}`).birthtime).getTime()
|
| 1203 |
-
)
|
| 1204 |
-
const getCachedFilesSize = () => cachedFiles().reduce((res, file) => res + statSync(`${CACHE_DIR}/${file}`).size, 0)
|
| 1205 |
-
|
| 1206 |
-
if (existsSync(filename())) {
|
| 1207 |
-
if (ranges) {
|
| 1208 |
-
const start = ranges[0]
|
| 1209 |
-
const end = ranges[1] ? ranges[1] : totalFileSize.toJSNumber() - 1
|
| 1210 |
-
|
| 1211 |
-
const readStream = createReadStream(filename(), { start, end })
|
| 1212 |
-
res.writeHead(200, {
|
| 1213 |
-
'Cache-Control': 'public, max-age=604800',
|
| 1214 |
-
'ETag': Buffer.from(`${files[0].id}:${files[0].message_id}`).toString('base64'),
|
| 1215 |
-
'Content-Range': `bytes ${start}-${end}/${totalFileSize}`,
|
| 1216 |
-
'Content-Disposition': contentDisposition(files[0].name.replace(/\.part\d+$/gi, ''), { type: Number(dl) === 1 ? 'attachment' : 'inline' }),
|
| 1217 |
-
'Content-Type': files[0].mime_type,
|
| 1218 |
-
'Content-Length': end - start + 1,
|
| 1219 |
-
'Accept-Ranges': 'bytes',
|
| 1220 |
-
})
|
| 1221 |
-
readStream.pipe(res)
|
| 1222 |
-
} else {
|
| 1223 |
-
res.writeHead(200, {
|
| 1224 |
-
'Cache-Control': 'public, max-age=604800',
|
| 1225 |
-
'ETag': Buffer.from(`${files[0].id}:${files[0].message_id}`).toString('base64'),
|
| 1226 |
-
'Content-Range': `bytes */${totalFileSize}`,
|
| 1227 |
-
'Content-Disposition': contentDisposition(files[0].name.replace(/\.part\d+$/gi, ''), { type: Number(dl) === 1 ? 'attachment' : 'inline' }),
|
| 1228 |
-
'Content-Type': files[0].mime_type,
|
| 1229 |
-
'Content-Length': totalFileSize.toString(),
|
| 1230 |
-
'Accept-Ranges': 'bytes',
|
| 1231 |
-
})
|
| 1232 |
-
const readStream = createReadStream(filename())
|
| 1233 |
-
readStream
|
| 1234 |
-
.on('open', () => readStream.pipe(res))
|
| 1235 |
-
.on('error', msg => res.end(msg))
|
| 1236 |
-
}
|
| 1237 |
-
return
|
| 1238 |
-
}
|
| 1239 |
-
|
| 1240 |
-
// res.setHeader('Cache-Control', 'public, max-age=604800')
|
| 1241 |
-
// res.setHeader('ETag', Buffer.from(`${files[0].id}:${files[0].message_id}`).toString('base64'))
|
| 1242 |
-
res.setHeader('Content-Range', `bytes */${totalFileSize}`)
|
| 1243 |
-
res.setHeader('Content-Disposition', contentDisposition(files[0].name.replace(/\.part\d+$/gi, ''), { type: Number(dl) === 1 ? 'attachment' : 'inline' }))
|
| 1244 |
-
res.setHeader('Content-Type', files[0].mime_type)
|
| 1245 |
-
res.setHeader('Content-Length', totalFileSize.toString())
|
| 1246 |
-
res.setHeader('Accept-Ranges', 'bytes')
|
| 1247 |
-
|
| 1248 |
-
let downloaded: number = 0
|
| 1249 |
-
|
| 1250 |
-
// Sort the files based on their ".part" number
|
| 1251 |
-
files.sort((a, b) => {
|
| 1252 |
-
const aPart = Number(a.name.match(/\.part(\d+)$/i)?.[1] || 0)
|
| 1253 |
-
const bPart = Number(b.name.match(/\.part(\d+)$/i)?.[1] || 0)
|
| 1254 |
-
return aPart - bPart
|
| 1255 |
-
})
|
| 1256 |
-
try {
|
| 1257 |
-
writeFileSync(filename('process-'), '')
|
| 1258 |
-
} catch (error) {
|
| 1259 |
-
// ignore
|
| 1260 |
-
}
|
| 1261 |
-
|
| 1262 |
-
let countFiles = 1
|
| 1263 |
-
for (const file of files) {
|
| 1264 |
-
let chat
|
| 1265 |
-
if (file.forward_info && file.forward_info.match(/^channel\//gi)) {
|
| 1266 |
-
const [type, peerId, id, accessHash] = file.forward_info.split('/')
|
| 1267 |
-
let peer
|
| 1268 |
-
if (type === 'channel') {
|
| 1269 |
-
peer = new Api.InputPeerChannel({
|
| 1270 |
-
channelId: bigInt(peerId),
|
| 1271 |
-
accessHash: bigInt(accessHash as string)
|
| 1272 |
-
})
|
| 1273 |
-
chat = await req.tg.invoke(new Api.channels.GetMessages({
|
| 1274 |
-
channel: peer,
|
| 1275 |
-
id: [new Api.InputMessageID({ id: Number(id) })]
|
| 1276 |
-
}))
|
| 1277 |
-
}
|
| 1278 |
-
} else {
|
| 1279 |
-
chat = await req.tg.invoke(new Api.messages.GetMessages({
|
| 1280 |
-
id: [new Api.InputMessageID({ id: Number(file.message_id) })]
|
| 1281 |
-
}))
|
| 1282 |
-
}
|
| 1283 |
-
const getData = async () => await req.tg.downloadMedia(chat['messages'][0].media, {
|
| 1284 |
-
...thumb ? { thumb: 0 } : {},
|
| 1285 |
-
outputFile: {
|
| 1286 |
-
write: (buffer: Buffer) => {
|
| 1287 |
-
downloaded += buffer.length
|
| 1288 |
-
if (cancel) {
|
| 1289 |
-
throw { status: 422, body: { error: 'canceled' } }
|
| 1290 |
-
} else {
|
| 1291 |
-
console.log(`${chat['messages'][0].id} ${downloaded}/${chat['messages'][0].media.document.size.value} (${downloaded / Number(totalFileSize) * 100 + '%'})`)
|
| 1292 |
-
try {
|
| 1293 |
-
appendFileSync(filename('process-'), buffer)
|
| 1294 |
-
} catch (error) {
|
| 1295 |
-
// ignore
|
| 1296 |
-
}
|
| 1297 |
-
res.write(buffer)
|
| 1298 |
-
}
|
| 1299 |
-
},
|
| 1300 |
-
close: () => {
|
| 1301 |
-
console.log(`${chat['messages'][0].id} ${downloaded}/${chat['messages'][0].media.document.size.value} (${downloaded / Number(totalFileSize) * 100 + '%'})`, '-end-')
|
| 1302 |
-
if (countFiles++ >= files.length) {
|
| 1303 |
-
try {
|
| 1304 |
-
const { size } = statSync(filename('process-'))
|
| 1305 |
-
if (totalFileSize.gt(bigInt(size))) {
|
| 1306 |
-
rmSync(filename('process-'))
|
| 1307 |
-
} else {
|
| 1308 |
-
renameSync(filename('process-'), filename())
|
| 1309 |
-
}
|
| 1310 |
-
} catch (error) {
|
| 1311 |
-
// ignore
|
| 1312 |
-
}
|
| 1313 |
-
res.end()
|
| 1314 |
-
}
|
| 1315 |
-
}
|
| 1316 |
-
}
|
| 1317 |
-
})
|
| 1318 |
-
try {
|
| 1319 |
-
await getData()
|
| 1320 |
-
} catch (error) {
|
| 1321 |
-
console.log(error)
|
| 1322 |
-
}
|
| 1323 |
-
}
|
| 1324 |
-
usage = await prisma.usages.update({
|
| 1325 |
-
data: {
|
| 1326 |
-
usage: bigInt(totalFileSize).add(bigInt(usage.usage)).toJSNumber()
|
| 1327 |
-
},
|
| 1328 |
-
where: { key: usage.key }
|
| 1329 |
-
})
|
| 1330 |
-
|
| 1331 |
-
while (CACHE_FILES_LIMIT < getCachedFilesSize()) {
|
| 1332 |
-
try {
|
| 1333 |
-
rmSync(`${CACHE_DIR}/${cachedFiles()[0]}`)
|
| 1334 |
-
} catch {
|
| 1335 |
-
// ignore
|
| 1336 |
-
}
|
| 1337 |
-
}
|
| 1338 |
-
|
| 1339 |
-
// res.end()
|
| 1340 |
-
}
|
| 1341 |
-
|
| 1342 |
-
public static async initiateSessionTG(req: Request, files?: files[]): Promise<any[]> {
|
| 1343 |
-
if (!files?.length) {
|
| 1344 |
-
throw { status: 404, body: { error: 'File not found' } }
|
| 1345 |
-
}
|
| 1346 |
-
|
| 1347 |
-
let data: { file: { id: string }, session: string }
|
| 1348 |
-
try {
|
| 1349 |
-
data = JSON.parse(AES.decrypt(files[0].signed_key, FILES_JWT_SECRET).toString(enc.Utf8))
|
| 1350 |
-
} catch (error) {
|
| 1351 |
-
throw { status: 401, body: { error: 'Invalid token' } }
|
| 1352 |
-
}
|
| 1353 |
-
|
| 1354 |
-
try {
|
| 1355 |
-
const session = new StringSession(data.session)
|
| 1356 |
-
req.tg = new TelegramClient(session, TG_CREDS.apiId, TG_CREDS.apiHash, {
|
| 1357 |
-
connectionRetries: CONNECTION_RETRIES,
|
| 1358 |
-
useWSS: false,
|
| 1359 |
-
...process.env.ENV === 'production' ? { baseLogger: new Logger(LogLevel.NONE) } : {}
|
| 1360 |
-
})
|
| 1361 |
-
} catch (error) {
|
| 1362 |
-
throw { status: 401, body: { error: 'Invalid key' } }
|
| 1363 |
-
}
|
| 1364 |
-
return files
|
| 1365 |
-
}
|
| 1366 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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service/Cache'
|
| 5 |
-
import { Endpoint } from '../base/Endpoint'
|
| 6 |
-
import { Auth } from '../middlewares/Auth'
|
| 7 |
-
|
| 8 |
-
@Endpoint.API()
|
| 9 |
-
export class Messages {
|
| 10 |
-
|
| 11 |
-
@Endpoint.GET('/history/:type/:id', { middlewares: [Auth] })
|
| 12 |
-
public async history(req: Request, res: Response): Promise<any> {
|
| 13 |
-
const { type, id } = req.params
|
| 14 |
-
const { offset, limit, accessHash } = req.query
|
| 15 |
-
|
| 16 |
-
let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
|
| 17 |
-
if (type === 'channel') {
|
| 18 |
-
peer = new Api.InputPeerChannel({
|
| 19 |
-
channelId: bigInt(id),
|
| 20 |
-
accessHash: bigInt(accessHash as string) })
|
| 21 |
-
} else if (type === 'chat') {
|
| 22 |
-
peer = new Api.InputPeerChat({
|
| 23 |
-
chatId: bigInt(id)
|
| 24 |
-
})
|
| 25 |
-
} else if (type === 'user') {
|
| 26 |
-
peer = new Api.InputPeerUser({
|
| 27 |
-
userId: bigInt(id),
|
| 28 |
-
accessHash: bigInt(accessHash as string) })
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
const result = await Redis.connect().getFromCacheFirst(`history:${req.user.id}:${JSON.stringify(req.params)}:${JSON.stringify(req.query)}`, async () => {
|
| 32 |
-
const messages = await req.tg.invoke(new Api.messages.GetHistory({
|
| 33 |
-
peer: peer,
|
| 34 |
-
limit: Number(limit) || 0,
|
| 35 |
-
offsetId: Number(offset) || 0,
|
| 36 |
-
}))
|
| 37 |
-
const result = JSON.parse(JSON.stringify(messages))
|
| 38 |
-
result.messages = result.messages?.map((msg, i) => ({ ...msg, action: { ...msg.action, className: messages['messages'][i]?.action?.className } }))
|
| 39 |
-
return result
|
| 40 |
-
}, 2)
|
| 41 |
-
return res.send({ messages: result })
|
| 42 |
-
}
|
| 43 |
-
|
| 44 |
-
@Endpoint.GET('/sponsoredMessages/:type/:id', { middlewares: [Auth] })
|
| 45 |
-
public async sponsoredMessages(req: Request, res: Response): Promise<any> {
|
| 46 |
-
const { type, id } = req.params
|
| 47 |
-
const { accessHash } = req.query
|
| 48 |
-
|
| 49 |
-
let peer: Api.InputPeerChannel
|
| 50 |
-
if (type === 'channel') {
|
| 51 |
-
peer = new Api.InputPeerChannel({
|
| 52 |
-
channelId: bigInt(id),
|
| 53 |
-
accessHash: bigInt(accessHash as string) })
|
| 54 |
-
} else {
|
| 55 |
-
return res.send({ messages: {
|
| 56 |
-
messages: [],
|
| 57 |
-
chats: [],
|
| 58 |
-
users: []
|
| 59 |
-
} })
|
| 60 |
-
}
|
| 61 |
-
const messages = await req.tg.invoke(new Api.channels.GetSponsoredMessages({ channel: peer }))
|
| 62 |
-
return res.send({ messages })
|
| 63 |
-
}
|
| 64 |
-
|
| 65 |
-
@Endpoint.POST('/readSponsoredMessages/:type/:id', { middlewares: [Auth] })
|
| 66 |
-
public async readSponsoredMessages(req: Request, res: Response): Promise<any> {
|
| 67 |
-
const { type, id } = req.params
|
| 68 |
-
const { accessHash } = req.query
|
| 69 |
-
const { random_id: randomId } = req.body
|
| 70 |
-
|
| 71 |
-
let peer: Api.InputPeerChannel
|
| 72 |
-
if (type === 'channel') {
|
| 73 |
-
peer = new Api.InputPeerChannel({
|
| 74 |
-
channelId: bigInt(id),
|
| 75 |
-
accessHash: bigInt(accessHash as string) })
|
| 76 |
-
} else {
|
| 77 |
-
return res.status(202).send({ accepted: true })
|
| 78 |
-
}
|
| 79 |
-
const accepted = await req.tg.invoke(new Api.channels.ViewSponsoredMessage({
|
| 80 |
-
channel: peer, randomId: Buffer.from(randomId)
|
| 81 |
-
}))
|
| 82 |
-
return res.status(202).send({ accepted })
|
| 83 |
-
}
|
| 84 |
-
|
| 85 |
-
@Endpoint.POST('/read/:type/:id', { middlewares: [Auth] })
|
| 86 |
-
public async read(req: Request, res: Response): Promise<any> {
|
| 87 |
-
const { type, id } = req.params
|
| 88 |
-
const { accessHash } = req.query
|
| 89 |
-
|
| 90 |
-
let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
|
| 91 |
-
if (type === 'channel') {
|
| 92 |
-
peer = new Api.InputPeerChannel({
|
| 93 |
-
channelId: bigInt(id),
|
| 94 |
-
accessHash: bigInt(accessHash as string) })
|
| 95 |
-
} else if (type === 'chat') {
|
| 96 |
-
peer = new Api.InputPeerChat({
|
| 97 |
-
chatId: bigInt(id)
|
| 98 |
-
})
|
| 99 |
-
} else if (type === 'user') {
|
| 100 |
-
peer = new Api.InputPeerUser({
|
| 101 |
-
userId: bigInt(id),
|
| 102 |
-
accessHash: bigInt(accessHash as string) })
|
| 103 |
-
}
|
| 104 |
-
|
| 105 |
-
try {
|
| 106 |
-
await req.tg.invoke(new Api.messages.ReadHistory({ peer }))
|
| 107 |
-
} catch (error) {
|
| 108 |
-
await req.tg.invoke(new Api.channels.ReadHistory({ channel: peer }))
|
| 109 |
-
}
|
| 110 |
-
return res.status(202).send({ accepted: true })
|
| 111 |
-
}
|
| 112 |
-
|
| 113 |
-
@Endpoint.POST('/send/:type/:id', { middlewares: [Auth] })
|
| 114 |
-
public async send(req: Request, res: Response): Promise<any> {
|
| 115 |
-
const { type, id } = req.params
|
| 116 |
-
const { accessHash } = req.query
|
| 117 |
-
const { message, replyToMsgId } = req.body
|
| 118 |
-
|
| 119 |
-
let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
|
| 120 |
-
if (type === 'channel') {
|
| 121 |
-
peer = new Api.InputPeerChannel({
|
| 122 |
-
channelId: bigInt(id),
|
| 123 |
-
accessHash: bigInt(accessHash as string) })
|
| 124 |
-
} else if (type === 'chat') {
|
| 125 |
-
peer = new Api.InputPeerChat({
|
| 126 |
-
chatId: bigInt(id)
|
| 127 |
-
})
|
| 128 |
-
} else if (type === 'user') {
|
| 129 |
-
peer = new Api.InputPeerUser({
|
| 130 |
-
userId: bigInt(id),
|
| 131 |
-
accessHash: bigInt(accessHash as string) })
|
| 132 |
-
}
|
| 133 |
-
|
| 134 |
-
const result = await req.tg.invoke(new Api.messages.SendMessage({
|
| 135 |
-
peer,
|
| 136 |
-
message,
|
| 137 |
-
// ...replyToMsgId ? { replyToMsgId: new Api.InputMessageReplyTo({ id: bigInt(replyToMsgId) }) } : {}
|
| 138 |
-
...replyToMsgId ? { replyToMsgId: replyToMsgId } : {}
|
| 139 |
-
}))
|
| 140 |
-
return res.send({ message: result })
|
| 141 |
-
}
|
| 142 |
-
|
| 143 |
-
@Endpoint.PATCH('/:type/:id/:msgId', { middlewares: [Auth] })
|
| 144 |
-
public async update(req: Request, res: Response): Promise<any> {
|
| 145 |
-
const { type, id, msgId } = req.params
|
| 146 |
-
const { accessHash } = req.query
|
| 147 |
-
const { message } = req.body
|
| 148 |
-
|
| 149 |
-
let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
|
| 150 |
-
if (type === 'channel') {
|
| 151 |
-
peer = new Api.InputPeerChannel({
|
| 152 |
-
channelId: bigInt(id),
|
| 153 |
-
accessHash: bigInt(accessHash as string) })
|
| 154 |
-
} else if (type === 'chat') {
|
| 155 |
-
peer = new Api.InputPeerChat({
|
| 156 |
-
chatId: bigInt(id)
|
| 157 |
-
})
|
| 158 |
-
} else if (type === 'user') {
|
| 159 |
-
peer = new Api.InputPeerUser({
|
| 160 |
-
userId: bigInt(id),
|
| 161 |
-
accessHash: bigInt(accessHash as string) })
|
| 162 |
-
}
|
| 163 |
-
|
| 164 |
-
const result = await req.tg.invoke(new Api.messages.EditMessage({
|
| 165 |
-
id: Number(msgId),
|
| 166 |
-
peer,
|
| 167 |
-
message
|
| 168 |
-
}))
|
| 169 |
-
return res.send({ message: result })
|
| 170 |
-
}
|
| 171 |
-
|
| 172 |
-
@Endpoint.DELETE('/:type/:id/:msgId', { middlewares: [Auth] })
|
| 173 |
-
public async delete(req: Request, res: Response): Promise<any> {
|
| 174 |
-
const { type, id, msgId } = req.params
|
| 175 |
-
const { accessHash } = req.query
|
| 176 |
-
|
| 177 |
-
let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
|
| 178 |
-
if (type === 'channel') {
|
| 179 |
-
peer = new Api.InputPeerChannel({
|
| 180 |
-
channelId: bigInt(id),
|
| 181 |
-
accessHash: bigInt(accessHash as string) })
|
| 182 |
-
} else if (type === 'chat') {
|
| 183 |
-
peer = new Api.InputPeerChat({
|
| 184 |
-
chatId: bigInt(id)
|
| 185 |
-
})
|
| 186 |
-
} else if (type === 'user') {
|
| 187 |
-
peer = new Api.InputPeerUser({
|
| 188 |
-
userId: bigInt(id),
|
| 189 |
-
accessHash: bigInt(accessHash as string) })
|
| 190 |
-
}
|
| 191 |
-
|
| 192 |
-
try {
|
| 193 |
-
await req.tg.invoke(new Api.messages.DeleteMessages({ id: [Number(msgId)], revoke: true }))
|
| 194 |
-
} catch (error) {
|
| 195 |
-
await req.tg.invoke(new Api.channels.DeleteMessages({ id: [Number(msgId)], channel: peer }))
|
| 196 |
-
}
|
| 197 |
-
return res.status(202).send({ accepted: true })
|
| 198 |
-
}
|
| 199 |
-
|
| 200 |
-
@Endpoint.POST('/forward/:msgId', { middlewares: [Auth] })
|
| 201 |
-
public async forward(req: Request, res: Response): Promise<any> {
|
| 202 |
-
const { msgId, silent=false, dropAuthor=false, cloneFile=false } = req.params
|
| 203 |
-
const { from, to } = req.body as { from?: {
|
| 204 |
-
type: string,
|
| 205 |
-
id: number,
|
| 206 |
-
accessHash?: string
|
| 207 |
-
}, to: {
|
| 208 |
-
type: string,
|
| 209 |
-
id: number,
|
| 210 |
-
accessHash?: string
|
| 211 |
-
} | string }
|
| 212 |
-
|
| 213 |
-
let fromPeer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat | 'me'
|
| 214 |
-
let toPeer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat | string
|
| 215 |
-
if (!from) {
|
| 216 |
-
fromPeer = 'me'
|
| 217 |
-
} else if (from.type === 'channel') {
|
| 218 |
-
fromPeer = new Api.InputPeerChannel({
|
| 219 |
-
channelId: bigInt(from.id),
|
| 220 |
-
accessHash: bigInt(from.accessHash as string) })
|
| 221 |
-
} else if (from.type === 'chat') {
|
| 222 |
-
fromPeer = new Api.InputPeerChat({
|
| 223 |
-
chatId: bigInt(from.id)
|
| 224 |
-
})
|
| 225 |
-
} else if (from.type === 'user') {
|
| 226 |
-
fromPeer = new Api.InputPeerUser({
|
| 227 |
-
userId: bigInt(from.id),
|
| 228 |
-
accessHash: bigInt(from.accessHash as string) })
|
| 229 |
-
}
|
| 230 |
-
|
| 231 |
-
if (typeof to === 'string') {
|
| 232 |
-
toPeer = to
|
| 233 |
-
} else if (to.type === 'channel') {
|
| 234 |
-
toPeer = new Api.InputPeerChannel({
|
| 235 |
-
channelId: bigInt(to.id),
|
| 236 |
-
accessHash: bigInt(to.accessHash as string) })
|
| 237 |
-
} else if (to.type === 'chat') {
|
| 238 |
-
toPeer = new Api.InputPeerChat({
|
| 239 |
-
chatId: bigInt(to.id)
|
| 240 |
-
})
|
| 241 |
-
} else if (to.type === 'user') {
|
| 242 |
-
toPeer = new Api.InputPeerUser({
|
| 243 |
-
userId: bigInt(to.id),
|
| 244 |
-
accessHash: bigInt(to.accessHash as string) })
|
| 245 |
-
}
|
| 246 |
-
|
| 247 |
-
const result = await req.tg.invoke(new Api.messages.ForwardMessages({
|
| 248 |
-
id: [Number(msgId)],
|
| 249 |
-
fromPeer,
|
| 250 |
-
toPeer,
|
| 251 |
-
randomId: [bigInt.randBetween('-1e100', '1e100')],
|
| 252 |
-
silent: Boolean(silent),
|
| 253 |
-
dropAuthor: Boolean(dropAuthor)
|
| 254 |
-
}))
|
| 255 |
-
return cloneFile ? result : res.send({ message: result })
|
| 256 |
-
}
|
| 257 |
-
|
| 258 |
-
@Endpoint.GET('/search', { middlewares: [Auth] })
|
| 259 |
-
public async search(req: Request, res: Response): Promise<any> {
|
| 260 |
-
const { q, offset, limit } = req.query
|
| 261 |
-
if (!q) {
|
| 262 |
-
throw { status: 400, body: { error: 'q is required' } }
|
| 263 |
-
}
|
| 264 |
-
const messages = await req.tg.invoke(new Api.messages.Search({
|
| 265 |
-
q: q as string,
|
| 266 |
-
filter: new Api.InputMessagesFilterEmpty(),
|
| 267 |
-
peer: new Api.InputPeerEmpty(),
|
| 268 |
-
limit: Number(limit) || 0,
|
| 269 |
-
minDate: 0,
|
| 270 |
-
maxDate: 0,
|
| 271 |
-
offsetId: 0,
|
| 272 |
-
addOffset: Number(offset) || 0,
|
| 273 |
-
maxId: 0,
|
| 274 |
-
minId: 0,
|
| 275 |
-
hash: bigInt(0),
|
| 276 |
-
}))
|
| 277 |
-
return res.send({ messages })
|
| 278 |
-
}
|
| 279 |
-
|
| 280 |
-
@Endpoint.GET('/globalSearch', { middlewares: [Auth] })
|
| 281 |
-
public async globalSearch(req: Request, res: Response): Promise<any> {
|
| 282 |
-
const { q, limit } = req.query
|
| 283 |
-
if (!q) {
|
| 284 |
-
throw { status: 400, body: { error: 'q is required' } }
|
| 285 |
-
}
|
| 286 |
-
const messages = await req.tg.invoke(new Api.messages.SearchGlobal({
|
| 287 |
-
q: q as string,
|
| 288 |
-
filter: new Api.InputMessagesFilterEmpty(),
|
| 289 |
-
offsetPeer: new Api.InputPeerEmpty(),
|
| 290 |
-
limit: Number(limit) || 0
|
| 291 |
-
}))
|
| 292 |
-
return res.send({ messages })
|
| 293 |
-
}
|
| 294 |
-
|
| 295 |
-
@Endpoint.GET('/:type/:id/avatar.jpg', { middlewares: [Auth] })
|
| 296 |
-
public async avatar(req: Request, res: Response): Promise<any> {
|
| 297 |
-
const { type, id } = req.params
|
| 298 |
-
let peer: Api.InputPeerChannel | Api.InputPeerUser | Api.InputPeerChat
|
| 299 |
-
if (type === 'channel') {
|
| 300 |
-
peer = new Api.InputPeerChannel({
|
| 301 |
-
channelId: bigInt(id),
|
| 302 |
-
accessHash: bigInt(req.query.accessHash as string) })
|
| 303 |
-
} else if (type === 'chat') {
|
| 304 |
-
peer = new Api.InputPeerChat({
|
| 305 |
-
chatId: bigInt(id)
|
| 306 |
-
})
|
| 307 |
-
} else if (type === 'user') {
|
| 308 |
-
peer = new Api.InputPeerUser({
|
| 309 |
-
userId: bigInt(id),
|
| 310 |
-
accessHash: bigInt(req.query.accessHash as string) })
|
| 311 |
-
}
|
| 312 |
-
try {
|
| 313 |
-
const file = await req.tg.downloadProfilePhoto(peer)
|
| 314 |
-
if (!file?.length) {
|
| 315 |
-
return res.redirect('https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png')
|
| 316 |
-
}
|
| 317 |
-
res.setHeader('Content-Disposition', `inline; filename=avatar-${id}.jpg`)
|
| 318 |
-
res.setHeader('Content-Type', 'image/jpeg')
|
| 319 |
-
res.setHeader('Content-Length', file.length)
|
| 320 |
-
res.write(file)
|
| 321 |
-
return res.end()
|
| 322 |
-
} catch (error) {
|
| 323 |
-
return res.redirect('https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png')
|
| 324 |
-
}
|
| 325 |
-
}
|
| 326 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/api/v1/Users.ts
DELETED
|
@@ -1,184 +0,0 @@
|
|
| 1 |
-
import { Prisma } from '@prisma/client'
|
| 2 |
-
import axios from 'axios'
|
| 3 |
-
import { Request, Response } from 'express'
|
| 4 |
-
import moment from 'moment'
|
| 5 |
-
import { Api } from 'telegram'
|
| 6 |
-
import { prisma } from '../../model'
|
| 7 |
-
import { Redis } from '../../service/Cache'
|
| 8 |
-
import { buildSort } from '../../utils/FilterQuery'
|
| 9 |
-
import { markdownSafe } from '../../utils/StringParser'
|
| 10 |
-
import { Endpoint } from '../base/Endpoint'
|
| 11 |
-
import { Auth, AuthMaybe } from '../middlewares/Auth'
|
| 12 |
-
|
| 13 |
-
@Endpoint.API()
|
| 14 |
-
export class Users {
|
| 15 |
-
|
| 16 |
-
@Endpoint.GET({ middlewares: [Auth] })
|
| 17 |
-
public async search(req: Request, res: Response): Promise<any> {
|
| 18 |
-
const { username, limit } = req.query
|
| 19 |
-
if (!username) {
|
| 20 |
-
throw { status: 400, body: { error: 'Username is required' } }
|
| 21 |
-
}
|
| 22 |
-
const data = await req.tg.invoke(new Api.contacts.Search({
|
| 23 |
-
q: username as string,
|
| 24 |
-
limit: Number(limit) || 10
|
| 25 |
-
}))
|
| 26 |
-
return res.send({ users: data.users })
|
| 27 |
-
}
|
| 28 |
-
|
| 29 |
-
@Endpoint.GET('/me/usage', { middlewares: [AuthMaybe] })
|
| 30 |
-
public async usage(req: Request, res: Response): Promise<any> {
|
| 31 |
-
let usage = await prisma.usages.findUnique({ where: { key: req.user ? `u:${req.user.id}` : `ip:${req.headers['cf-connecting-ip'] as string || req.ip}` } })
|
| 32 |
-
if (!usage) {
|
| 33 |
-
usage = await prisma.usages.create({
|
| 34 |
-
data: {
|
| 35 |
-
key: req.user ? `u:${req.user.id}` : `ip:${req.headers['cf-connecting-ip'] as string || req.ip}`,
|
| 36 |
-
usage: 0,
|
| 37 |
-
expire: moment().add(1, 'day').toDate()
|
| 38 |
-
}
|
| 39 |
-
})
|
| 40 |
-
}
|
| 41 |
-
|
| 42 |
-
if (new Date().getTime() - new Date(usage.expire).getTime() > 0) { // is expired
|
| 43 |
-
await prisma.usages.update({
|
| 44 |
-
where: { key: usage.key },
|
| 45 |
-
data: {
|
| 46 |
-
expire: moment().add(1, 'day').toDate(),
|
| 47 |
-
usage: 0,
|
| 48 |
-
}
|
| 49 |
-
})
|
| 50 |
-
}
|
| 51 |
-
|
| 52 |
-
return res.send({ usage })
|
| 53 |
-
}
|
| 54 |
-
|
| 55 |
-
@Endpoint.GET('/', { middlewares: [Auth] })
|
| 56 |
-
public async find(req: Request, res: Response): Promise<any> {
|
| 57 |
-
const { sort, offset, limit, search, ...filters } = req.query
|
| 58 |
-
const where = {
|
| 59 |
-
...search ? {
|
| 60 |
-
OR: [
|
| 61 |
-
{ username: { contains: search } },
|
| 62 |
-
{ name: { contains: search } },
|
| 63 |
-
]
|
| 64 |
-
} : filters
|
| 65 |
-
}
|
| 66 |
-
return res.send({ users: await prisma.users.findMany({
|
| 67 |
-
where,
|
| 68 |
-
select: req.user.role === 'admin' ? {
|
| 69 |
-
id: true,
|
| 70 |
-
username: true,
|
| 71 |
-
name: true,
|
| 72 |
-
role: true,
|
| 73 |
-
created_at: true,
|
| 74 |
-
} : { username: true },
|
| 75 |
-
skip: Number(offset) || undefined,
|
| 76 |
-
take: Number(limit) || undefined,
|
| 77 |
-
orderBy: buildSort(sort as string)
|
| 78 |
-
}), length: await prisma.users.count({ where }) })
|
| 79 |
-
}
|
| 80 |
-
|
| 81 |
-
@Endpoint.PATCH('/me/settings', { middlewares: [Auth] })
|
| 82 |
-
public async settings(req: Request, res: Response): Promise<any> {
|
| 83 |
-
const { settings } = req.body
|
| 84 |
-
// if (settings.theme === 'dark' && (!req.user.plan || req.user.plan === 'free') && moment().format('l') !== '2/2/2022') {
|
| 85 |
-
// throw { status: 402, body: { error: 'You need to upgrade your plan to use dark theme' } }
|
| 86 |
-
// }
|
| 87 |
-
// if (settings.saved_location && (!req.user.plan || req.user.plan === 'free') && moment().format('l') !== '2/2/2022') {
|
| 88 |
-
// throw { status: 402, body: { error: 'You need to upgrade your plan to use this feature' } }
|
| 89 |
-
// }
|
| 90 |
-
req.user.settings = {
|
| 91 |
-
...req.user.settings as Prisma.JsonObject || {},
|
| 92 |
-
...settings
|
| 93 |
-
}
|
| 94 |
-
await prisma.users.update({
|
| 95 |
-
where: { id: req.user.id },
|
| 96 |
-
data: req.user
|
| 97 |
-
})
|
| 98 |
-
await Redis.connect().del(`auth:${req.authKey}`)
|
| 99 |
-
return res.send({ settings: req.user?.settings })
|
| 100 |
-
}
|
| 101 |
-
|
| 102 |
-
@Endpoint.POST('/me/delete', { middlewares: [Auth] })
|
| 103 |
-
public async remove(req: Request, res: Response): Promise<any> {
|
| 104 |
-
const { reason, agreement } = req.body
|
| 105 |
-
if (agreement !== 'permanently removed') {
|
| 106 |
-
throw { status: 400, body: { error: 'Invalid agreement' } }
|
| 107 |
-
}
|
| 108 |
-
if (reason && process.env.TG_BOT_TOKEN && process.env.TG_BOT_OWNER_ID) {
|
| 109 |
-
await axios.post(`https://api.telegram.org/bot${process.env.TG_BOT_TOKEN}/sendMessage`, {
|
| 110 |
-
chat_id: process.env.TG_BOT_OWNER_ID,
|
| 111 |
-
parse_mode: 'Markdown',
|
| 112 |
-
text: `😭 ${markdownSafe(req.user.name)} (@${markdownSafe(req.user.username)}) removed their account.\n\nReason: ${markdownSafe(reason)}\n\nfrom: \`${markdownSafe(req.headers['cf-connecting-ip'] as string || req.ip)}\`\ndomain: \`${req.headers['authority'] || req.headers.origin}\`${req.user ? `\nplan: ${req.user.plan}` : ''}`
|
| 113 |
-
})
|
| 114 |
-
}
|
| 115 |
-
await prisma.files.deleteMany({
|
| 116 |
-
where: { user_id: req.user.id }
|
| 117 |
-
})
|
| 118 |
-
await prisma.users.delete({ where: { id: req.user.id } })
|
| 119 |
-
const success = await req.tg.invoke(new Api.auth.LogOut())
|
| 120 |
-
return res.clearCookie('authorization').clearCookie('refreshToken').send({ success })
|
| 121 |
-
}
|
| 122 |
-
|
| 123 |
-
@Endpoint.GET('/:username/:param?', { middlewares: [Auth] })
|
| 124 |
-
public async retrieve(req: Request, res: Response): Promise<any> {
|
| 125 |
-
const { username, param } = req.params
|
| 126 |
-
if (param === 'photo') {
|
| 127 |
-
const file = await req.tg.downloadProfilePhoto(username, { isBig: false })
|
| 128 |
-
if (!file?.length) {
|
| 129 |
-
return res.redirect('https://upload.wikimedia.org/wikipedia/commons/7/7c/Profile_avatar_placeholder_large.png')
|
| 130 |
-
}
|
| 131 |
-
res.setHeader('Cache-Control', 'public, max-age=604800')
|
| 132 |
-
res.setHeader('ETag', Buffer.from(file).toString('base64').slice(10, 50))
|
| 133 |
-
res.setHeader('Content-Disposition', `inline; filename=${username === 'me' ? req.user.username : username}.jpg`)
|
| 134 |
-
res.setHeader('Content-Type', 'image/jpeg')
|
| 135 |
-
res.setHeader('Content-Length', file.length)
|
| 136 |
-
res.write(file)
|
| 137 |
-
return res.end()
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
const user = username === 'me' || username === req.user.username ? req.user : await prisma.users.findFirst({
|
| 141 |
-
where: {
|
| 142 |
-
OR: [
|
| 143 |
-
{ username },
|
| 144 |
-
{ id: username }
|
| 145 |
-
]
|
| 146 |
-
}
|
| 147 |
-
})
|
| 148 |
-
if (!user) {
|
| 149 |
-
throw { status: 404, body: { error: 'User not found' } }
|
| 150 |
-
}
|
| 151 |
-
|
| 152 |
-
return res.send({ user })
|
| 153 |
-
}
|
| 154 |
-
|
| 155 |
-
@Endpoint.DELETE('/:id', { middlewares: [Auth] })
|
| 156 |
-
public async delete(req: Request, res: Response): Promise<any> {
|
| 157 |
-
if (req.user.role !== 'admin') {
|
| 158 |
-
throw { status: 403, body: { error: 'You are not allowed to do this' } }
|
| 159 |
-
}
|
| 160 |
-
const { id } = req.params
|
| 161 |
-
await prisma.files.deleteMany({
|
| 162 |
-
where: { user_id: id }
|
| 163 |
-
})
|
| 164 |
-
await prisma.users.delete({ where: { id } })
|
| 165 |
-
return res.send({})
|
| 166 |
-
}
|
| 167 |
-
|
| 168 |
-
@Endpoint.PATCH('/:id', { middlewares: [Auth] })
|
| 169 |
-
public async update(req: Request, res: Response): Promise<any> {
|
| 170 |
-
if (req.user.role !== 'admin') {
|
| 171 |
-
throw { status: 403, body: { error: 'You are not allowed to do this' } }
|
| 172 |
-
}
|
| 173 |
-
const { id } = req.params
|
| 174 |
-
const { user } = req.body
|
| 175 |
-
if (!user) {
|
| 176 |
-
throw { status: 400, body: { error: 'User is required' } }
|
| 177 |
-
}
|
| 178 |
-
await prisma.users.update({
|
| 179 |
-
where: { id },
|
| 180 |
-
data: { role: user?.role }
|
| 181 |
-
})
|
| 182 |
-
return res.send({})
|
| 183 |
-
}
|
| 184 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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readFileSync } from 'fs'
|
| 3 |
-
import { lookup } from 'geoip-lite'
|
| 4 |
-
import { Endpoint } from '../base/Endpoint'
|
| 5 |
-
|
| 6 |
-
@Endpoint.API()
|
| 7 |
-
export class Utils {
|
| 8 |
-
|
| 9 |
-
@Endpoint.GET()
|
| 10 |
-
public async maintenance(_: Request, res: Response): Promise<any> {
|
| 11 |
-
return res.send({ maintenance: ['1', 'true', 'yes'].includes(process.env.IS_MAINTENANCE) })
|
| 12 |
-
}
|
| 13 |
-
|
| 14 |
-
@Endpoint.GET()
|
| 15 |
-
public async ipinfo(req: Request, res: Response): Promise<any> {
|
| 16 |
-
return res.send({ ipinfo: { ip: req.headers['cf-connecting-ip'] as string || req.ip, ...lookup(req.headers['cf-connecting-ip'] as string || req.ip) } })
|
| 17 |
-
}
|
| 18 |
-
|
| 19 |
-
@Endpoint.GET()
|
| 20 |
-
public async version(_: Request, res: Response): Promise<any> {
|
| 21 |
-
return res.send({ version: JSON.parse(readFileSync(`${__dirname}/../../../package.json`, 'utf8')).version })
|
| 22 |
-
}
|
| 23 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/api/v1/index.ts
DELETED
|
@@ -1,22 +0,0 @@
|
|
| 1 |
-
import { Router } from 'express'
|
| 2 |
-
import { Endpoint } from '../base/Endpoint'
|
| 3 |
-
import { Auth } from './Auth'
|
| 4 |
-
import { Config } from './Config'
|
| 5 |
-
import { Dialogs } from './Dialogs'
|
| 6 |
-
import { Files } from './Files'
|
| 7 |
-
import { Messages } from './Messages'
|
| 8 |
-
import { Users } from './Users'
|
| 9 |
-
import { Utils } from './Utils'
|
| 10 |
-
|
| 11 |
-
export const V1 = Router()
|
| 12 |
-
.use(
|
| 13 |
-
Endpoint.register(
|
| 14 |
-
Auth,
|
| 15 |
-
Users,
|
| 16 |
-
Files,
|
| 17 |
-
Dialogs,
|
| 18 |
-
Messages,
|
| 19 |
-
Utils,
|
| 20 |
-
Config
|
| 21 |
-
)
|
| 22 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/index.ts
DELETED
|
@@ -1,105 +0,0 @@
|
|
| 1 |
-
import 'source-map-support/register'
|
| 2 |
-
require('dotenv').config({ path: '.env' })
|
| 3 |
-
|
| 4 |
-
import axios from 'axios'
|
| 5 |
-
import cookieParser from 'cookie-parser'
|
| 6 |
-
import cors from 'cors'
|
| 7 |
-
// import compression from 'compression'
|
| 8 |
-
import { cURL } from 'curly-express'
|
| 9 |
-
import express, {
|
| 10 |
-
json,
|
| 11 |
-
NextFunction,
|
| 12 |
-
raw,
|
| 13 |
-
Request,
|
| 14 |
-
Response,
|
| 15 |
-
static as serveStatic,
|
| 16 |
-
urlencoded
|
| 17 |
-
} from 'express'
|
| 18 |
-
import listEndpoints from 'express-list-endpoints'
|
| 19 |
-
import morgan from 'morgan'
|
| 20 |
-
import path from 'path'
|
| 21 |
-
import { serializeError } from 'serialize-error'
|
| 22 |
-
import serverless from 'serverless-http'
|
| 23 |
-
import { API } from './api'
|
| 24 |
-
import { Redis } from './service/Cache'
|
| 25 |
-
import { markdownSafe } from './utils/StringParser'
|
| 26 |
-
|
| 27 |
-
(BigInt.prototype as any).toJSON = function () {
|
| 28 |
-
return this.toString()
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
Redis.connect()
|
| 33 |
-
|
| 34 |
-
const curl = cURL({ attach: true })
|
| 35 |
-
|
| 36 |
-
const app = express()
|
| 37 |
-
|
| 38 |
-
app.set('trust proxy', 1)
|
| 39 |
-
|
| 40 |
-
app.use(cors({
|
| 41 |
-
credentials: true,
|
| 42 |
-
origin: [
|
| 43 |
-
/.*/
|
| 44 |
-
]
|
| 45 |
-
}))
|
| 46 |
-
// app.use(compression())
|
| 47 |
-
app.use(json({ limit: '100mb' }))
|
| 48 |
-
app.use(urlencoded({ extended: true, limit: '100mb' }))
|
| 49 |
-
app.use(raw({ limit: '100mb' }))
|
| 50 |
-
app.use(cookieParser())
|
| 51 |
-
if (process.env.ENV !== 'production') {
|
| 52 |
-
app.use(morgan('tiny'))
|
| 53 |
-
}
|
| 54 |
-
app.use(curl)
|
| 55 |
-
|
| 56 |
-
app.get('/ping', (_, res) => res.send({ pong: true }))
|
| 57 |
-
app.get('/security.txt', (_, res) => {
|
| 58 |
-
res.setHeader('Content-Type', 'text/plain')
|
| 59 |
-
res.send('Contact: security@teledriveapp.com\nPreferred-Languages: en, id')
|
| 60 |
-
})
|
| 61 |
-
app.use('/api', API)
|
| 62 |
-
|
| 63 |
-
// error handler
|
| 64 |
-
app.use(async (err: { status?: number, body?: Record<string, any> }, req: Request, res: Response, __: NextFunction) => {
|
| 65 |
-
if (process.env.ENV !== 'production') {
|
| 66 |
-
console.error(err)
|
| 67 |
-
}
|
| 68 |
-
if ((err.status || 500) >= 500) {
|
| 69 |
-
if (process.env.TG_BOT_TOKEN && (process.env.TG_BOT_ERROR_REPORT_ID || process.env.TG_BOT_OWNER_ID)) {
|
| 70 |
-
try {
|
| 71 |
-
await axios.post(`https://api.telegram.org/bot${process.env.TG_BOT_TOKEN}/sendMessage`, {
|
| 72 |
-
chat_id: process.env.TG_BOT_ERROR_REPORT_ID || process.env.TG_BOT_OWNER_ID,
|
| 73 |
-
parse_mode: 'Markdown',
|
| 74 |
-
text: `🔥 *${markdownSafe(err.body.error || (err as any).message || 'Unknown error')}*\n\n\`[${err.status || 500}] ${markdownSafe(req.protocol + '://' + req.get('host') + req.originalUrl)}\`\n\n\`\`\`\n${JSON.stringify(serializeError(err), null, 2)}\n\`\`\`\n\n\`\`\`\n${req['_curl']}\n\`\`\``
|
| 75 |
-
})
|
| 76 |
-
} catch (error) {
|
| 77 |
-
if (process.env.ENV !== 'production') {
|
| 78 |
-
console.error(error)
|
| 79 |
-
}
|
| 80 |
-
// ignore
|
| 81 |
-
}
|
| 82 |
-
}
|
| 83 |
-
}
|
| 84 |
-
return res.status(err.status || 500).send(err.body || { error: 'Something error', details: serializeError(err) })
|
| 85 |
-
})
|
| 86 |
-
|
| 87 |
-
// serve web
|
| 88 |
-
app.use(serveStatic(path.join(__dirname, '..', '..', 'web', 'build')))
|
| 89 |
-
app.use((req: Request, res: Response) => {
|
| 90 |
-
try {
|
| 91 |
-
if (req.headers['accept'] !== 'application/json') {
|
| 92 |
-
return res.sendFile(path.join(__dirname, '..', '..','web', 'build', 'index.html'))
|
| 93 |
-
}
|
| 94 |
-
return res.status(404).send({ error: 'Not found' })
|
| 95 |
-
} catch (error) {
|
| 96 |
-
return res.send({ empty: true })
|
| 97 |
-
}
|
| 98 |
-
})
|
| 99 |
-
|
| 100 |
-
app.listen(process.env.PORT || 4000, () => console.log(`Running at :${process.env.PORT || 4000}...`))
|
| 101 |
-
|
| 102 |
-
console.log(listEndpoints(app))
|
| 103 |
-
|
| 104 |
-
module.exports = app
|
| 105 |
-
module.exports.handler = serverless(app)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/model/index.ts
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
import { PrismaClient } from '@prisma/client'
|
| 2 |
-
|
| 3 |
-
export const prisma = new PrismaClient()
|
|
|
|
|
|
|
|
|
|
|
|
api/src/model/migrations/dump.20220406.sql
DELETED
|
@@ -1,11 +0,0 @@
|
|
| 1 |
-
CREATE TABLE public.config (
|
| 2 |
-
created_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 3 |
-
updated_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 4 |
-
id uuid DEFAULT public.uuid_generate_v4() NOT NULL,
|
| 5 |
-
invitation_code character varying,
|
| 6 |
-
disable_signup boolean DEFAULT false NOT NULL
|
| 7 |
-
);
|
| 8 |
-
|
| 9 |
-
ALTER TABLE public.users ADD role character varying DEFAULT NULL;
|
| 10 |
-
|
| 11 |
-
ALTER TABLE public.config ADD allow_server_storage_use boolean DEFAULT false NOT NULL;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/model/migrations/dump.sql
DELETED
|
@@ -1,244 +0,0 @@
|
|
| 1 |
-
--
|
| 2 |
-
-- PostgreSQL database dump
|
| 3 |
-
--
|
| 4 |
-
|
| 5 |
-
-- Dumped from database version 12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)
|
| 6 |
-
-- Dumped by pg_dump version 12.9 (Ubuntu 12.9-0ubuntu0.20.04.1)
|
| 7 |
-
|
| 8 |
-
SET statement_timeout = 0;
|
| 9 |
-
SET lock_timeout = 0;
|
| 10 |
-
SET idle_in_transaction_session_timeout = 0;
|
| 11 |
-
SET client_encoding = 'UTF8';
|
| 12 |
-
SET standard_conforming_strings = on;
|
| 13 |
-
SELECT pg_catalog.set_config('search_path', '', false);
|
| 14 |
-
SET check_function_bodies = false;
|
| 15 |
-
SET xmloption = content;
|
| 16 |
-
SET client_min_messages = warning;
|
| 17 |
-
SET row_security = off;
|
| 18 |
-
|
| 19 |
-
--
|
| 20 |
-
-- Name: pg_stat_statements; Type: EXTENSION; Schema: -; Owner: -
|
| 21 |
-
--
|
| 22 |
-
|
| 23 |
-
CREATE EXTENSION IF NOT EXISTS pg_stat_statements WITH SCHEMA public;
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
--
|
| 27 |
-
-- Name: EXTENSION pg_stat_statements; Type: COMMENT; Schema: -; Owner:
|
| 28 |
-
--
|
| 29 |
-
|
| 30 |
-
-- COMMENT ON EXTENSION pg_stat_statements IS 'track execution statistics of all SQL statements executed';
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
--
|
| 34 |
-
-- Name: uuid-ossp; Type: EXTENSION; Schema: -; Owner: -
|
| 35 |
-
--
|
| 36 |
-
|
| 37 |
-
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
--
|
| 41 |
-
-- Name: EXTENSION "uuid-ossp"; Type: COMMENT; Schema: -; Owner:
|
| 42 |
-
--
|
| 43 |
-
|
| 44 |
-
-- COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
SET default_tablespace = '';
|
| 48 |
-
|
| 49 |
-
SET default_table_access_method = heap;
|
| 50 |
-
|
| 51 |
-
--
|
| 52 |
-
-- Name: files; Type: TABLE; Schema: public; Owner: postgres
|
| 53 |
-
--
|
| 54 |
-
|
| 55 |
-
CREATE TABLE public.files (
|
| 56 |
-
created_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 57 |
-
updated_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 58 |
-
id uuid DEFAULT public.uuid_generate_v4() NOT NULL,
|
| 59 |
-
name character varying NOT NULL,
|
| 60 |
-
type character varying,
|
| 61 |
-
message_id character varying,
|
| 62 |
-
mime_type character varying,
|
| 63 |
-
size bigint,
|
| 64 |
-
uploaded_at timestamp with time zone,
|
| 65 |
-
upload_progress double precision,
|
| 66 |
-
user_id uuid NOT NULL,
|
| 67 |
-
parent_id uuid,
|
| 68 |
-
deleted_at timestamp with time zone,
|
| 69 |
-
sharing_options character varying[],
|
| 70 |
-
signed_key character varying,
|
| 71 |
-
file_id character varying,
|
| 72 |
-
link_id uuid,
|
| 73 |
-
forward_info character varying
|
| 74 |
-
);
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
-- ALTER TABLE public.files OWNER TO postgres;
|
| 78 |
-
|
| 79 |
-
--
|
| 80 |
-
-- Name: rate_limits; Type: TABLE; Schema: public; Owner: postgres
|
| 81 |
-
--
|
| 82 |
-
|
| 83 |
-
CREATE TABLE public.rate_limits (
|
| 84 |
-
key character varying(255) NOT NULL,
|
| 85 |
-
points integer DEFAULT 0 NOT NULL,
|
| 86 |
-
expire bigint
|
| 87 |
-
);
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
-- ALTER TABLE public.rate_limits OWNER TO postgres;
|
| 91 |
-
|
| 92 |
-
--
|
| 93 |
-
-- Name: usages; Type: TABLE; Schema: public; Owner: postgres
|
| 94 |
-
--
|
| 95 |
-
|
| 96 |
-
CREATE TABLE public.usages (
|
| 97 |
-
created_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 98 |
-
updated_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 99 |
-
key character varying NOT NULL,
|
| 100 |
-
usage bigint NOT NULL,
|
| 101 |
-
expire timestamp with time zone NOT NULL
|
| 102 |
-
);
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
-- ALTER TABLE public.usages OWNER TO postgres;
|
| 106 |
-
|
| 107 |
-
--
|
| 108 |
-
-- Name: users; Type: TABLE; Schema: public; Owner: postgres
|
| 109 |
-
--
|
| 110 |
-
|
| 111 |
-
CREATE TABLE public.users (
|
| 112 |
-
created_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 113 |
-
updated_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 114 |
-
id uuid DEFAULT public.uuid_generate_v4() NOT NULL,
|
| 115 |
-
username character varying NOT NULL,
|
| 116 |
-
name character varying,
|
| 117 |
-
email character varying,
|
| 118 |
-
tg_id character varying,
|
| 119 |
-
plan character varying,
|
| 120 |
-
subscription_id character varying,
|
| 121 |
-
midtrans_id character varying,
|
| 122 |
-
plan_expired_at timestamp without time zone,
|
| 123 |
-
settings jsonb
|
| 124 |
-
);
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
-- ALTER TABLE public.users OWNER TO postgres;
|
| 128 |
-
|
| 129 |
-
--
|
| 130 |
-
-- Name: waitings; Type: TABLE; Schema: public; Owner: postgres
|
| 131 |
-
--
|
| 132 |
-
|
| 133 |
-
CREATE TABLE public.waitings (
|
| 134 |
-
created_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 135 |
-
updated_at timestamp with time zone DEFAULT now() NOT NULL,
|
| 136 |
-
id uuid DEFAULT public.uuid_generate_v4() NOT NULL,
|
| 137 |
-
email character varying NOT NULL
|
| 138 |
-
);
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
-- ALTER TABLE public.waitings OWNER TO postgres;
|
| 142 |
-
|
| 143 |
-
--
|
| 144 |
-
-- Name: files PK_6c16b9093a142e0e7613b04a3d9; Type: CONSTRAINT; Schema: public; Owner: postgres
|
| 145 |
-
--
|
| 146 |
-
|
| 147 |
-
ALTER TABLE ONLY public.files
|
| 148 |
-
ADD CONSTRAINT "PK_6c16b9093a142e0e7613b04a3d9" PRIMARY KEY (id);
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
--
|
| 152 |
-
-- Name: usages PK_7d8e95b6dd4c0e87cad4972da13; Type: CONSTRAINT; Schema: public; Owner: postgres
|
| 153 |
-
--
|
| 154 |
-
|
| 155 |
-
ALTER TABLE ONLY public.usages
|
| 156 |
-
ADD CONSTRAINT "PK_7d8e95b6dd4c0e87cad4972da13" PRIMARY KEY (key);
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
--
|
| 160 |
-
-- Name: users PK_a3ffb1c0c8416b9fc6f907b7433; Type: CONSTRAINT; Schema: public; Owner: postgres
|
| 161 |
-
--
|
| 162 |
-
|
| 163 |
-
ALTER TABLE ONLY public.users
|
| 164 |
-
ADD CONSTRAINT "PK_a3ffb1c0c8416b9fc6f907b7433" PRIMARY KEY (id);
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
--
|
| 168 |
-
-- Name: waitings PK_f0cfe98441cf0fb92db66ae71c4; Type: CONSTRAINT; Schema: public; Owner: postgres
|
| 169 |
-
--
|
| 170 |
-
|
| 171 |
-
ALTER TABLE ONLY public.waitings
|
| 172 |
-
ADD CONSTRAINT "PK_f0cfe98441cf0fb92db66ae71c4" PRIMARY KEY (id);
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
--
|
| 176 |
-
-- Name: rate_limits rate_limits_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
|
| 177 |
-
--
|
| 178 |
-
|
| 179 |
-
ALTER TABLE ONLY public.rate_limits
|
| 180 |
-
ADD CONSTRAINT rate_limits_pkey PRIMARY KEY (key);
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
--
|
| 184 |
-
-- Name: files_message_id_idx; Type: INDEX; Schema: public; Owner: postgres
|
| 185 |
-
--
|
| 186 |
-
|
| 187 |
-
CREATE INDEX files_message_id_idx ON public.files USING btree (message_id);
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
--
|
| 191 |
-
-- Name: files_parent_id_idx; Type: INDEX; Schema: public; Owner: postgres
|
| 192 |
-
--
|
| 193 |
-
|
| 194 |
-
CREATE INDEX files_parent_id_idx ON public.files USING btree (parent_id);
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
--
|
| 198 |
-
-- Name: files_link_id_idx; Type: INDEX; Schema: public; Owner: postgres
|
| 199 |
-
--
|
| 200 |
-
|
| 201 |
-
CREATE INDEX files_link_id_idx ON public.files USING btree (link_id);
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
--
|
| 205 |
-
-- Name: files_user_id_idx; Type: INDEX; Schema: public; Owner: postgres
|
| 206 |
-
--
|
| 207 |
-
|
| 208 |
-
CREATE INDEX files_user_id_idx ON public.files USING btree (user_id);
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
--
|
| 212 |
-
-- Name: tg_id; Type: INDEX; Schema: public; Owner: postgres
|
| 213 |
-
--
|
| 214 |
-
|
| 215 |
-
CREATE INDEX tg_id ON public.users USING btree (tg_id);
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
--
|
| 219 |
-
-- Name: files files_files_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
|
| 220 |
-
--
|
| 221 |
-
|
| 222 |
-
ALTER TABLE ONLY public.files
|
| 223 |
-
ADD CONSTRAINT files_files_fkey FOREIGN KEY (parent_id) REFERENCES public.files(id) ON UPDATE CASCADE ON DELETE CASCADE;
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
--
|
| 227 |
-
-- Name: files files_links_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
|
| 228 |
-
--
|
| 229 |
-
|
| 230 |
-
ALTER TABLE ONLY public.files
|
| 231 |
-
ADD CONSTRAINT files_links_fkey FOREIGN KEY (link_id) REFERENCES public.files(id) ON UPDATE CASCADE ON DELETE CASCADE;
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
--
|
| 235 |
-
-- Name: files files_users_fkey; Type: FK CONSTRAINT; Schema: public; Owner: postgres
|
| 236 |
-
--
|
| 237 |
-
|
| 238 |
-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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/service/Cache.ts
DELETED
|
@@ -1,63 +0,0 @@
|
|
| 1 |
-
import IORedis, { Redis as IOredis } from 'ioredis'
|
| 2 |
-
|
| 3 |
-
export class Redis {
|
| 4 |
-
private static client: Redis
|
| 5 |
-
private redis: IOredis
|
| 6 |
-
|
| 7 |
-
private constructor() {
|
| 8 |
-
this.redis = process.env.REDIS_URI ? new IORedis(process.env.REDIS_URI) : null
|
| 9 |
-
}
|
| 10 |
-
|
| 11 |
-
public static connect(): Redis {
|
| 12 |
-
if (!this.client) {
|
| 13 |
-
this.client = new Redis()
|
| 14 |
-
}
|
| 15 |
-
this.client.redis?.on('connect', () => console.log('redis: connected'))
|
| 16 |
-
this.client.redis?.on('ready', () => console.log('redis: ready'))
|
| 17 |
-
this.client.redis?.on('error', console.error)
|
| 18 |
-
return this.client
|
| 19 |
-
}
|
| 20 |
-
|
| 21 |
-
public async get(key: string): Promise<any> {
|
| 22 |
-
const result = await this.redis?.get(key)
|
| 23 |
-
if (!result) return null
|
| 24 |
-
try {
|
| 25 |
-
return JSON.parse(result)
|
| 26 |
-
} catch (error) {
|
| 27 |
-
return result
|
| 28 |
-
}
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
public async set(key: string, data: unknown, ex?: number): Promise<boolean> {
|
| 32 |
-
try {
|
| 33 |
-
if (ex) {
|
| 34 |
-
return await this.redis?.set(key, JSON.stringify(data), 'EX', ex) === 'OK'
|
| 35 |
-
} else {
|
| 36 |
-
return await this.redis?.set(key, JSON.stringify(data)) === 'OK'
|
| 37 |
-
}
|
| 38 |
-
} catch (error) {
|
| 39 |
-
if (ex) {
|
| 40 |
-
return await this.redis?.set(key, data as any, 'EX', ex) === 'OK'
|
| 41 |
-
} else {
|
| 42 |
-
return await this.redis?.set(key, data as any) === 'OK'
|
| 43 |
-
}
|
| 44 |
-
}
|
| 45 |
-
}
|
| 46 |
-
|
| 47 |
-
public async del(key: string): Promise<boolean> {
|
| 48 |
-
return await this.redis?.del(key) === 1
|
| 49 |
-
}
|
| 50 |
-
|
| 51 |
-
public async getFromCacheFirst<T>(key: string, fn: () => T | Promise<T>, ex?: number): Promise<T> {
|
| 52 |
-
try {
|
| 53 |
-
const result = await this.get(key)
|
| 54 |
-
if (result) return result
|
| 55 |
-
|
| 56 |
-
const data = await fn()
|
| 57 |
-
await this.set(key, data, ex)
|
| 58 |
-
return data
|
| 59 |
-
} catch (error) {
|
| 60 |
-
return await fn()
|
| 61 |
-
}
|
| 62 |
-
}
|
| 63 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/utils/Constant.ts
DELETED
|
@@ -1,36 +0,0 @@
|
|
| 1 |
-
import { randomBytes } from 'crypto'
|
| 2 |
-
import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'fs'
|
| 3 |
-
import { parse } from 'human-format'
|
| 4 |
-
|
| 5 |
-
export const TG_CREDS = {
|
| 6 |
-
apiId: Number(process.env.TG_API_ID),
|
| 7 |
-
apiHash: process.env.TG_API_HASH
|
| 8 |
-
}
|
| 9 |
-
|
| 10 |
-
// export const COOKIE_AGE = 3.154e+12
|
| 11 |
-
export const COOKIE_AGE = 54e6
|
| 12 |
-
|
| 13 |
-
export const CONNECTION_RETRIES = 10
|
| 14 |
-
|
| 15 |
-
export const PROCESS_RETRY = 50
|
| 16 |
-
|
| 17 |
-
export const CACHE_FILES_LIMIT = parse(process.env.CACHE_FILES_LIMIT || '20GB')
|
| 18 |
-
|
| 19 |
-
// generate random secret keys
|
| 20 |
-
const keys = existsSync(`${__dirname}/../../keys`) ? readFileSync(`${__dirname}/../../keys`, 'utf-8') : null
|
| 21 |
-
const [apiSecret, filesSecret] = keys?.toString()?.split('\n') || [
|
| 22 |
-
randomBytes(48).toString('base64'),
|
| 23 |
-
randomBytes(48).toString('base64')
|
| 24 |
-
]
|
| 25 |
-
|
| 26 |
-
if (!process.env.API_JWT_SECRET) {
|
| 27 |
-
process.env.API_JWT_SECRET = apiSecret
|
| 28 |
-
writeFileSync(`${__dirname}/../../keys`, process.env.API_JWT_SECRET)
|
| 29 |
-
}
|
| 30 |
-
if (!process.env.FILES_JWT_SECRET) {
|
| 31 |
-
process.env.FILES_JWT_SECRET = filesSecret
|
| 32 |
-
appendFileSync(`${__dirname}/../../keys`, `\n${process.env.FILES_JWT_SECRET}`)
|
| 33 |
-
}
|
| 34 |
-
|
| 35 |
-
export const API_JWT_SECRET = process.env.API_JWT_SECRET
|
| 36 |
-
export const FILES_JWT_SECRET = process.env.FILES_JWT_SECRET
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/utils/FilterQuery.ts
DELETED
|
@@ -1,74 +0,0 @@
|
|
| 1 |
-
import { unescape } from 'querystring'
|
| 2 |
-
|
| 3 |
-
export async function filterQuery<T = any>(base: Record<string, any>, query: Record<string, any>): Promise<T> {
|
| 4 |
-
const { page, size, ...filters } = query
|
| 5 |
-
|
| 6 |
-
for (const param of Object.keys(filters)) {
|
| 7 |
-
const [column, op] = param.split(/(.+)\./).slice(1)
|
| 8 |
-
if (param.match(/^sort\./gi)) {
|
| 9 |
-
const col = param.replace(/^sort\./gi, '')
|
| 10 |
-
base = base.order(col as keyof T, {
|
| 11 |
-
ascending: filters[param].toLowerCase() === 'asc' || filters[param].toLowerCase() === 'ascending' })
|
| 12 |
-
} else {
|
| 13 |
-
base = base.filter(column as keyof T, op || 'eq' as any, filters[param])
|
| 14 |
-
}
|
| 15 |
-
}
|
| 16 |
-
|
| 17 |
-
if (page && size) {
|
| 18 |
-
base = base.range(Number(size) * Number(page),
|
| 19 |
-
Number(size) * Number(page) + Number(size) - 1)
|
| 20 |
-
}
|
| 21 |
-
|
| 22 |
-
const result = await base
|
| 23 |
-
if (result.error) {
|
| 24 |
-
throw { status: result.status, body: { error: result.error.message, details: result } }
|
| 25 |
-
}
|
| 26 |
-
return result.data
|
| 27 |
-
}
|
| 28 |
-
|
| 29 |
-
export function buildWhereQuery(data: Record<string, any>, prefix: string = '', join: 'and' | 'or' = 'and'): string {
|
| 30 |
-
const res = Object.keys(data).reduce((res, key) => {
|
| 31 |
-
let item = ''
|
| 32 |
-
|
| 33 |
-
const [column, op] = key.split(/(.+)\./).filter(Boolean)
|
| 34 |
-
let value = data[key]
|
| 35 |
-
try {
|
| 36 |
-
value = value ? unescape(value) : value
|
| 37 |
-
} catch (error) {
|
| 38 |
-
// ignore
|
| 39 |
-
}
|
| 40 |
-
if (!op) {
|
| 41 |
-
item = `${prefix}${column} = '${value.trim()}'`
|
| 42 |
-
} else if (op === 'lt') {
|
| 43 |
-
item = `${prefix}${column} < '${value.trim()}'`
|
| 44 |
-
} else if (op === 'lte') {
|
| 45 |
-
item = `${prefix}${column} <= '${value.trim()}'`
|
| 46 |
-
} else if (op === 'gt') {
|
| 47 |
-
item = `${prefix}${column} > '${value.trim()}'`
|
| 48 |
-
} else if (op === 'gte') {
|
| 49 |
-
item = `${prefix}${column} >= '${value.trim()}'`
|
| 50 |
-
} else if (op === 'between') {
|
| 51 |
-
const [from, to] = value.trim().split('_')
|
| 52 |
-
item = `${prefix}${column} between '${from.trim()}' and '${to.trim()}'`
|
| 53 |
-
} else if (op === 'match') {
|
| 54 |
-
item = `${prefix}${column} ~ '${value.trim()}'`
|
| 55 |
-
} else if (op === 'notmatch') {
|
| 56 |
-
item = `${prefix}${column} !~ '${value.trim()}'`
|
| 57 |
-
} else if (op === 'like') {
|
| 58 |
-
item = `${prefix}${column} like '${value.trim()}'`
|
| 59 |
-
} else if (op === 'ilike') {
|
| 60 |
-
item = `${prefix}${column} ilike '${value.trim()}'`
|
| 61 |
-
} else {
|
| 62 |
-
item = `${prefix}${column} ${op} ${value.trim()}`
|
| 63 |
-
}
|
| 64 |
-
return [...res, item]
|
| 65 |
-
}, []).join(` ${join} `)
|
| 66 |
-
return res
|
| 67 |
-
}
|
| 68 |
-
|
| 69 |
-
export function buildSort(sort?: string, prefix: string = ''): Record<string, any> {
|
| 70 |
-
return sort?.split(',').reduce((res, data) => {
|
| 71 |
-
const [column, order] = data.split(':')
|
| 72 |
-
return { ...res, [`${prefix}${column}`]: order?.toLowerCase() || 'asc' }
|
| 73 |
-
}, {}) || {}
|
| 74 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/utils/ObjectParser.ts
DELETED
|
@@ -1,5 +0,0 @@
|
|
| 1 |
-
import { serializeError } from 'serialize-error'
|
| 2 |
-
|
| 3 |
-
export function objectParser(obj: unknown): string {
|
| 4 |
-
return JSON.parse(JSON.stringify(serializeError(obj), (key, value) => key.match(/^_/gi) ? undefined : value))
|
| 5 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/src/utils/StringParser.ts
DELETED
|
@@ -1,5 +0,0 @@
|
|
| 1 |
-
export const markdownSafe = (str: string): string => str
|
| 2 |
-
.replaceAll('_', '\\_')
|
| 3 |
-
.replaceAll('*', '\\*')
|
| 4 |
-
.replaceAll('[', '\\[')
|
| 5 |
-
.replaceAll('`', '\\`')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/tsconfig.json
DELETED
|
@@ -1,24 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"compilerOptions": {
|
| 3 |
-
"module": "commonjs",
|
| 4 |
-
"target": "es6",
|
| 5 |
-
"lib": ["es5", "es6", "es2017", "dom"],
|
| 6 |
-
"types": ["reflect-metadata", "node"],
|
| 7 |
-
"noImplicitAny": false,
|
| 8 |
-
"moduleResolution": "node",
|
| 9 |
-
"esModuleInterop": true,
|
| 10 |
-
"removeComments": true,
|
| 11 |
-
"experimentalDecorators": true,
|
| 12 |
-
"emitDecoratorMetadata": true,
|
| 13 |
-
"sourceMap": true,
|
| 14 |
-
"baseUrl": ".",
|
| 15 |
-
"outDir": "dist",
|
| 16 |
-
"resolveJsonModule": true,
|
| 17 |
-
"skipLibCheck": true
|
| 18 |
-
},
|
| 19 |
-
"exclude": [
|
| 20 |
-
"tests",
|
| 21 |
-
"node_modules",
|
| 22 |
-
"dist"
|
| 23 |
-
]
|
| 24 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
api/vercel.json
DELETED
|
@@ -1,21 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"version": 2,
|
| 3 |
-
"env": {},
|
| 4 |
-
"builds": [
|
| 5 |
-
{
|
| 6 |
-
"src": "dist/index.js",
|
| 7 |
-
"use": "@vercel/node",
|
| 8 |
-
"config": {
|
| 9 |
-
"excludeFiles": [
|
| 10 |
-
"src/**"
|
| 11 |
-
]
|
| 12 |
-
}
|
| 13 |
-
}
|
| 14 |
-
],
|
| 15 |
-
"routes": [
|
| 16 |
-
{
|
| 17 |
-
"src": "/(.*)",
|
| 18 |
-
"dest": "dist/index.js"
|
| 19 |
-
}
|
| 20 |
-
]
|
| 21 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|