mirror of
https://github.com/movie-web/backend.git
synced 2025-09-13 14:53:25 +00:00
Compare commits
59 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
f4b3d43b8f | ||
|
2fe48d24d7 | ||
|
b0f5b28084 | ||
|
b5ee9f1f7a | ||
|
eb0f47ba53 | ||
|
26b46876c5 | ||
|
f58c2c86e5 | ||
|
4af2d32b72 | ||
|
a911e52ddb | ||
|
7b26b029de | ||
|
06ad2249d6 | ||
|
14601b9010 | ||
|
b1eeb21ba4 | ||
|
5855943a56 | ||
|
9073010f4c | ||
|
78e6b6443f | ||
|
e7c5d93cc3 | ||
|
9fe8cb4877 | ||
|
66840d7894 | ||
|
befa173445 | ||
|
1c1d70fa05 | ||
|
6b83fcd158 | ||
|
f8870b5929 | ||
|
727a9cdd43 | ||
|
206844e758 | ||
|
b2e0841d0b | ||
|
886df2ffb4 | ||
|
6ea07ea685 | ||
|
1010eaf71e | ||
|
1632f138b0 | ||
|
0c3de831fb | ||
|
ebe00ecbd6 | ||
|
3bb427401f | ||
|
b2598e3d82 | ||
|
bf55be2978 | ||
|
8f52dad296 | ||
|
9a27b0b0b4 | ||
|
46baac466d | ||
|
26316c7755 | ||
|
d5851b522a | ||
|
7145d6c246 | ||
|
961ac7eeca | ||
|
59ab9b48bd | ||
|
07ecd445f9 | ||
|
5ebecd1476 | ||
|
f4e9a96666 | ||
|
60dda8ac57 | ||
|
d84cdc4239 | ||
|
c2cba27e68 | ||
|
c3259156ac | ||
|
9ef12d1c0f | ||
|
e173003f55 | ||
|
9f90ba7da2 | ||
|
05bf651939 | ||
|
cf0125755c | ||
|
4129b80828 | ||
|
e5c3cde51b | ||
|
4bf0285d06 | ||
|
53d5ca1461 |
@@ -12,6 +12,8 @@ services:
|
|||||||
POSTGRES_PASSWORD: postgres
|
POSTGRES_PASSWORD: postgres
|
||||||
volumes:
|
volumes:
|
||||||
- 'postgres_data:/var/lib/postgresql/data'
|
- 'postgres_data:/var/lib/postgresql/data'
|
||||||
|
redis:
|
||||||
|
image: redis
|
||||||
|
|
||||||
# custom services
|
# custom services
|
||||||
backend:
|
backend:
|
||||||
@@ -39,7 +41,7 @@ services:
|
|||||||
links:
|
links:
|
||||||
- postgres:postgres
|
- postgres:postgres
|
||||||
environment:
|
environment:
|
||||||
- DATABASE_URL=postgres://postgres:postgres@postgres:5432/postgres?sslmode=disable
|
- PGWEB_DATABASE_URL=postgres://postgres:postgres@postgres:5432/postgres?sslmode=disable
|
||||||
depends_on:
|
depends_on:
|
||||||
- postgres
|
- postgres
|
||||||
|
|
||||||
|
4
.github/CODEOWNERS
vendored
4
.github/CODEOWNERS
vendored
@@ -1,3 +1 @@
|
|||||||
* @movie-web/core
|
* @movie-web/project-leads
|
||||||
|
|
||||||
.github @binaryoverload
|
|
||||||
|
18
.github/workflows/linting_testing.yml
vendored
18
.github/workflows/linting_testing.yml
vendored
@@ -14,16 +14,16 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v2
|
- uses: pnpm/action-setup@v2
|
||||||
with:
|
with:
|
||||||
version: 8
|
version: 8
|
||||||
|
|
||||||
- name: Install Node.js
|
- name: Install Node.js
|
||||||
uses: actions/setup-node@v3
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 18
|
node-version: 20
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- name: Install packages
|
- name: Install packages
|
||||||
@@ -38,16 +38,16 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- uses: pnpm/action-setup@v2
|
- uses: pnpm/action-setup@v2
|
||||||
with:
|
with:
|
||||||
version: 8
|
version: 8
|
||||||
|
|
||||||
- name: Install Node.js
|
- name: Install Node.js
|
||||||
uses: actions/setup-node@v3
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 18
|
node-version: 20
|
||||||
cache: 'pnpm'
|
cache: 'pnpm'
|
||||||
|
|
||||||
- name: Install packages
|
- name: Install packages
|
||||||
@@ -62,10 +62,10 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v2
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
uses: docker/build-push-action@v4
|
uses: docker/build-push-action@v5
|
||||||
|
11
.github/workflows/release.yml
vendored
11
.github/workflows/release.yml
vendored
@@ -12,7 +12,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Get version
|
- name: Get version
|
||||||
id: package-version
|
id: package-version
|
||||||
@@ -42,10 +42,10 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Setup Docker buildx
|
- name: Setup Docker buildx
|
||||||
uses: docker/setup-buildx-action@v2
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
- name: Get version
|
- name: Get version
|
||||||
id: package-version
|
id: package-version
|
||||||
@@ -70,9 +70,12 @@ jobs:
|
|||||||
|
|
||||||
- name: Build and push Docker image
|
- name: Build and push Docker image
|
||||||
id: build-and-push
|
id: build-and-push
|
||||||
uses: docker/build-push-action@v4
|
uses: docker/build-push-action@v5
|
||||||
with:
|
with:
|
||||||
push: true
|
push: true
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
context: .
|
context: .
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
|
10
package.json
10
package.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "backend",
|
"name": "backend",
|
||||||
"version": "1.1.4",
|
"version": "1.3.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"homepage": "https://github.com/movie-web/backend",
|
"homepage": "https://github.com/movie-web/backend",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -8,16 +8,16 @@
|
|||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "nodemon -r tsconfig-paths/register src/main.ts",
|
"dev": "nodemon -r tsconfig-paths/register src/main.ts",
|
||||||
"build": "npm run build:pre && npm run build:compile",
|
"build": "pnpm run build:pre && pnpm run build:compile",
|
||||||
"start": "node dist/main.js",
|
"start": "node dist/main.js",
|
||||||
"lint": "eslint --ext .ts,.js,.json,.tsx src/",
|
"lint": "eslint --ext .ts,.js,.json,.tsx src/",
|
||||||
"lint:fix": "eslint --fix --ext .ts,.js,.json,.tsx src/",
|
"lint:fix": "eslint --fix --ext .ts,.js,.json,.tsx src/",
|
||||||
"build:pre": "rimraf dist/",
|
"build:pre": "rimraf dist/",
|
||||||
"build:compile": "tsc && tsc-alias",
|
"build:compile": "tsc && tsc-alias",
|
||||||
"preinstall": "npx -y only-allow pnpm",
|
"preinstall": "npx -y only-allow pnpm",
|
||||||
"migration:create": "npx -y mikro-orm migration:create",
|
"migration:create": "pnpm exec mikro-orm migration:create",
|
||||||
"migration:up": "npx -y mikro-orm migration:up",
|
"migration:up": "pnpm exec mikro-orm migration:up",
|
||||||
"migration:down": "npx -y mikro-orm migration:down"
|
"migration:down": "pnpm exec mikro-orm migration:down"
|
||||||
},
|
},
|
||||||
"mikro-orm": {
|
"mikro-orm": {
|
||||||
"useTsNode": true,
|
"useTsNode": true,
|
||||||
|
@@ -4,4 +4,8 @@ export const dockerFragment: FragmentSchema = {
|
|||||||
postgres: {
|
postgres: {
|
||||||
connection: 'postgres://postgres:postgres@postgres:5432/postgres',
|
connection: 'postgres://postgres:postgres@postgres:5432/postgres',
|
||||||
},
|
},
|
||||||
|
ratelimits: {
|
||||||
|
enabled: true,
|
||||||
|
redisUrl: 'redis://redis:6379',
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
@@ -1,10 +1,20 @@
|
|||||||
|
import { devFragment } from '@/config/fragments/dev';
|
||||||
|
import { dockerFragment } from '@/config/fragments/docker';
|
||||||
import { createConfigLoader } from 'neat-config';
|
import { createConfigLoader } from 'neat-config';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
import { booleanSchema } from './schema';
|
||||||
|
|
||||||
|
const fragments = {
|
||||||
|
dev: devFragment,
|
||||||
|
dockerdev: dockerFragment,
|
||||||
|
};
|
||||||
|
|
||||||
export const ormConfigSchema = z.object({
|
export const ormConfigSchema = z.object({
|
||||||
postgres: z.object({
|
postgres: z.object({
|
||||||
// connection URL for postgres database
|
// connection URL for postgres database
|
||||||
connection: z.string(),
|
connection: z.string(),
|
||||||
|
// whether to use SSL for the connection
|
||||||
|
ssl: booleanSchema.default(false),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -15,6 +25,8 @@ export const ormConf = createConfigLoader()
|
|||||||
prefix: 'MWB_',
|
prefix: 'MWB_',
|
||||||
})
|
})
|
||||||
.addFromFile('config.json')
|
.addFromFile('config.json')
|
||||||
|
.setFragmentKey('usePresets')
|
||||||
|
.addConfigFragments(fragments)
|
||||||
.addZodSchema(ormConfigSchema)
|
.addZodSchema(ormConfigSchema)
|
||||||
.freeze()
|
.freeze()
|
||||||
.load();
|
.load();
|
||||||
|
@@ -1,5 +1,7 @@
|
|||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export const booleanSchema = z.preprocess((val) => val === 'true', z.boolean());
|
||||||
|
|
||||||
export const configSchema = z.object({
|
export const configSchema = z.object({
|
||||||
server: z
|
server: z
|
||||||
.object({
|
.object({
|
||||||
@@ -11,10 +13,13 @@ export const configSchema = z.object({
|
|||||||
|
|
||||||
// disable cross origin restrictions, allow any site.
|
// disable cross origin restrictions, allow any site.
|
||||||
// overwrites the cors option above
|
// overwrites the cors option above
|
||||||
allowAnySite: z.coerce.boolean().default(false),
|
allowAnySite: booleanSchema.default(false),
|
||||||
|
|
||||||
// should it trust reverse proxy headers? (for ip gathering)
|
// should it trust reverse proxy headers? (for ip gathering)
|
||||||
trustProxy: z.coerce.boolean().default(false),
|
trustProxy: booleanSchema.default(false),
|
||||||
|
|
||||||
|
// should it trust cloudflare headers? (for ip gathering, cloudflare has priority)
|
||||||
|
trustCloudflare: booleanSchema.default(false),
|
||||||
|
|
||||||
// prefix for where the instance is run on. for example set it to /backend if you're hosting it on example.com/backend
|
// prefix for where the instance is run on. for example set it to /backend if you're hosting it on example.com/backend
|
||||||
// if this is set, do not apply url rewriting before proxing
|
// if this is set, do not apply url rewriting before proxing
|
||||||
@@ -27,7 +32,7 @@ export const configSchema = z.object({
|
|||||||
format: z.enum(['json', 'pretty']).default('pretty'),
|
format: z.enum(['json', 'pretty']).default('pretty'),
|
||||||
|
|
||||||
// show debug logs?
|
// show debug logs?
|
||||||
debug: z.coerce.boolean().default(false),
|
debug: booleanSchema.default(false),
|
||||||
})
|
})
|
||||||
.default({}),
|
.default({}),
|
||||||
postgres: z.object({
|
postgres: z.object({
|
||||||
@@ -35,16 +40,19 @@ export const configSchema = z.object({
|
|||||||
connection: z.string(),
|
connection: z.string(),
|
||||||
|
|
||||||
// run all migrations on boot of the application
|
// run all migrations on boot of the application
|
||||||
migrateOnBoot: z.coerce.boolean().default(false),
|
migrateOnBoot: booleanSchema.default(false),
|
||||||
|
|
||||||
// try to sync the schema on boot, useful for development
|
// try to sync the schema on boot, useful for development
|
||||||
// will always keep the database schema in sync with the connected database
|
// will always keep the database schema in sync with the connected database
|
||||||
// it is extremely destructive, do not use it EVER in production
|
// it is extremely destructive, do not use it EVER in production
|
||||||
syncSchema: z.coerce.boolean().default(false),
|
syncSchema: booleanSchema.default(false),
|
||||||
|
|
||||||
// Enable debug logging for MikroORM - Outputs queries and entity management logs
|
// Enable debug logging for MikroORM - Outputs queries and entity management logs
|
||||||
// Do NOT use in production, leaks all sensitive data
|
// Do NOT use in production, leaks all sensitive data
|
||||||
debugLogging: z.coerce.boolean().default(false),
|
debugLogging: booleanSchema.default(false),
|
||||||
|
|
||||||
|
// Enable SSL for the postgres connection
|
||||||
|
ssl: booleanSchema.default(false),
|
||||||
}),
|
}),
|
||||||
crypto: z.object({
|
crypto: z.object({
|
||||||
// session secret. used for signing session tokens
|
// session secret. used for signing session tokens
|
||||||
@@ -59,7 +67,7 @@ export const configSchema = z.object({
|
|||||||
captcha: z
|
captcha: z
|
||||||
.object({
|
.object({
|
||||||
// enabled captchas on register
|
// enabled captchas on register
|
||||||
enabled: z.coerce.boolean().default(false),
|
enabled: booleanSchema.default(false),
|
||||||
|
|
||||||
// captcha secret
|
// captcha secret
|
||||||
secret: z.string().min(1).optional(),
|
secret: z.string().min(1).optional(),
|
||||||
@@ -70,7 +78,7 @@ export const configSchema = z.object({
|
|||||||
ratelimits: z
|
ratelimits: z
|
||||||
.object({
|
.object({
|
||||||
// enabled captchas on register
|
// enabled captchas on register
|
||||||
enabled: z.coerce.boolean().default(false),
|
enabled: booleanSchema.default(false),
|
||||||
redisUrl: z.string().optional(),
|
redisUrl: z.string().optional(),
|
||||||
})
|
})
|
||||||
.default({}),
|
.default({}),
|
||||||
|
@@ -268,143 +268,6 @@
|
|||||||
"checks": [],
|
"checks": [],
|
||||||
"foreignKeys": {}
|
"foreignKeys": {}
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"columns": {
|
|
||||||
"id": {
|
|
||||||
"name": "id",
|
|
||||||
"type": "uuid",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": false,
|
|
||||||
"mappedType": "uuid"
|
|
||||||
},
|
|
||||||
"tmdb_id": {
|
|
||||||
"name": "tmdb_id",
|
|
||||||
"type": "varchar(255)",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": false,
|
|
||||||
"mappedType": "string"
|
|
||||||
},
|
|
||||||
"type": {
|
|
||||||
"name": "type",
|
|
||||||
"type": "varchar(255)",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": false,
|
|
||||||
"mappedType": "string"
|
|
||||||
},
|
|
||||||
"title": {
|
|
||||||
"name": "title",
|
|
||||||
"type": "varchar(255)",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": false,
|
|
||||||
"mappedType": "string"
|
|
||||||
},
|
|
||||||
"season_id": {
|
|
||||||
"name": "season_id",
|
|
||||||
"type": "varchar(255)",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": true,
|
|
||||||
"mappedType": "string"
|
|
||||||
},
|
|
||||||
"episode_id": {
|
|
||||||
"name": "episode_id",
|
|
||||||
"type": "varchar(255)",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": true,
|
|
||||||
"mappedType": "string"
|
|
||||||
},
|
|
||||||
"created_at": {
|
|
||||||
"name": "created_at",
|
|
||||||
"type": "timestamptz(0)",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": false,
|
|
||||||
"length": 0,
|
|
||||||
"mappedType": "datetime"
|
|
||||||
},
|
|
||||||
"status": {
|
|
||||||
"name": "status",
|
|
||||||
"type": "varchar(255)",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": false,
|
|
||||||
"mappedType": "string"
|
|
||||||
},
|
|
||||||
"provider_id": {
|
|
||||||
"name": "provider_id",
|
|
||||||
"type": "varchar(255)",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": false,
|
|
||||||
"mappedType": "string"
|
|
||||||
},
|
|
||||||
"embed_id": {
|
|
||||||
"name": "embed_id",
|
|
||||||
"type": "varchar(255)",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": true,
|
|
||||||
"mappedType": "string"
|
|
||||||
},
|
|
||||||
"error_message": {
|
|
||||||
"name": "error_message",
|
|
||||||
"type": "text",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": true,
|
|
||||||
"mappedType": "text"
|
|
||||||
},
|
|
||||||
"full_error": {
|
|
||||||
"name": "full_error",
|
|
||||||
"type": "text",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": true,
|
|
||||||
"mappedType": "text"
|
|
||||||
},
|
|
||||||
"hostname": {
|
|
||||||
"name": "hostname",
|
|
||||||
"type": "varchar(255)",
|
|
||||||
"unsigned": false,
|
|
||||||
"autoincrement": false,
|
|
||||||
"primary": false,
|
|
||||||
"nullable": false,
|
|
||||||
"mappedType": "string"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"name": "provider_metrics",
|
|
||||||
"schema": "public",
|
|
||||||
"indexes": [
|
|
||||||
{
|
|
||||||
"keyName": "provider_metrics_pkey",
|
|
||||||
"columnNames": [
|
|
||||||
"id"
|
|
||||||
],
|
|
||||||
"composite": false,
|
|
||||||
"primary": true,
|
|
||||||
"unique": true
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"checks": [],
|
|
||||||
"foreignKeys": {}
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
"columns": {
|
"columns": {
|
||||||
"id": {
|
"id": {
|
||||||
@@ -620,6 +483,15 @@
|
|||||||
"primary": false,
|
"primary": false,
|
||||||
"nullable": true,
|
"nullable": true,
|
||||||
"mappedType": "string"
|
"mappedType": "string"
|
||||||
|
},
|
||||||
|
"proxy_urls": {
|
||||||
|
"name": "proxy_urls",
|
||||||
|
"type": "text[]",
|
||||||
|
"unsigned": false,
|
||||||
|
"autoincrement": false,
|
||||||
|
"primary": false,
|
||||||
|
"nullable": true,
|
||||||
|
"mappedType": "array"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"name": "user_settings",
|
"name": "user_settings",
|
13
src/db/migrations/Migration20231221185725.ts
Normal file
13
src/db/migrations/Migration20231221185725.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { Migration } from '@mikro-orm/migrations';
|
||||||
|
|
||||||
|
export class Migration20231221185725 extends Migration {
|
||||||
|
|
||||||
|
async up(): Promise<void> {
|
||||||
|
this.addSql('drop table if exists "provider_metrics" cascade;');
|
||||||
|
}
|
||||||
|
|
||||||
|
async down(): Promise<void> {
|
||||||
|
this.addSql('create table "provider_metrics" ("id" uuid not null default null, "tmdb_id" varchar not null default null, "type" varchar not null default null, "title" varchar not null default null, "season_id" varchar null default null, "episode_id" varchar null default null, "created_at" timestamptz not null default null, "status" varchar not null default null, "provider_id" varchar not null default null, "embed_id" varchar null default null, "error_message" text null default null, "full_error" text null default null, "hostname" varchar not null default null, constraint "provider_metrics_pkey" primary key ("id"));');
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
13
src/db/migrations/Migration20231229214215.ts
Normal file
13
src/db/migrations/Migration20231229214215.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { Migration } from '@mikro-orm/migrations';
|
||||||
|
|
||||||
|
export class Migration20231229214215 extends Migration {
|
||||||
|
|
||||||
|
async up(): Promise<void> {
|
||||||
|
this.addSql('alter table "user_settings" add column "proxy_urls" text[] null;');
|
||||||
|
}
|
||||||
|
|
||||||
|
async down(): Promise<void> {
|
||||||
|
this.addSql('alter table "user_settings" drop column "proxy_urls";');
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@@ -1,51 +0,0 @@
|
|||||||
import { Entity, PrimaryKey, Property } from '@mikro-orm/core';
|
|
||||||
import { randomUUID } from 'crypto';
|
|
||||||
|
|
||||||
export const status = {
|
|
||||||
failed: 'failed',
|
|
||||||
notfound: 'notfound',
|
|
||||||
success: 'success',
|
|
||||||
} as const;
|
|
||||||
type Status = keyof typeof status;
|
|
||||||
|
|
||||||
@Entity({ tableName: 'provider_metrics' })
|
|
||||||
export class ProviderMetric {
|
|
||||||
@PrimaryKey({ name: 'id', type: 'uuid' })
|
|
||||||
id: string = randomUUID();
|
|
||||||
|
|
||||||
@Property({ name: 'tmdb_id' })
|
|
||||||
tmdbId!: string;
|
|
||||||
|
|
||||||
@Property({ name: 'type' })
|
|
||||||
type!: string;
|
|
||||||
|
|
||||||
@Property({ name: 'title' })
|
|
||||||
title!: string;
|
|
||||||
|
|
||||||
@Property({ name: 'season_id', nullable: true })
|
|
||||||
seasonId?: string;
|
|
||||||
|
|
||||||
@Property({ name: 'episode_id', nullable: true })
|
|
||||||
episodeId?: string;
|
|
||||||
|
|
||||||
@Property({ name: 'created_at', type: 'date' })
|
|
||||||
createdAt = new Date();
|
|
||||||
|
|
||||||
@Property({ name: 'status' })
|
|
||||||
status!: Status;
|
|
||||||
|
|
||||||
@Property({ name: 'provider_id' })
|
|
||||||
providerId!: string;
|
|
||||||
|
|
||||||
@Property({ name: 'embed_id', nullable: true })
|
|
||||||
embedId?: string;
|
|
||||||
|
|
||||||
@Property({ name: 'error_message', nullable: true, type: 'text' })
|
|
||||||
errorMessage?: string;
|
|
||||||
|
|
||||||
@Property({ name: 'full_error', nullable: true, type: 'text' })
|
|
||||||
fullError?: string;
|
|
||||||
|
|
||||||
@Property({ name: 'hostname' })
|
|
||||||
hostname!: string;
|
|
||||||
}
|
|
@@ -1,4 +1,4 @@
|
|||||||
import { Entity, PrimaryKey, Property } from '@mikro-orm/core';
|
import { ArrayType, Entity, PrimaryKey, Property } from '@mikro-orm/core';
|
||||||
|
|
||||||
@Entity({ tableName: 'user_settings' })
|
@Entity({ tableName: 'user_settings' })
|
||||||
export class UserSettings {
|
export class UserSettings {
|
||||||
@@ -13,6 +13,9 @@ export class UserSettings {
|
|||||||
|
|
||||||
@Property({ name: 'default_subtitle_language', nullable: true })
|
@Property({ name: 'default_subtitle_language', nullable: true })
|
||||||
defaultSubtitleLanguage?: string | null;
|
defaultSubtitleLanguage?: string | null;
|
||||||
|
|
||||||
|
@Property({ name: 'proxy_urls', type: ArrayType, nullable: true })
|
||||||
|
proxyUrls?: string[] | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserSettingsDTO {
|
export interface UserSettingsDTO {
|
||||||
@@ -20,6 +23,7 @@ export interface UserSettingsDTO {
|
|||||||
applicationTheme?: string | null;
|
applicationTheme?: string | null;
|
||||||
applicationLanguage?: string | null;
|
applicationLanguage?: string | null;
|
||||||
defaultSubtitleLanguage?: string | null;
|
defaultSubtitleLanguage?: string | null;
|
||||||
|
proxyUrls?: string[] | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatUserSettings(
|
export function formatUserSettings(
|
||||||
@@ -30,5 +34,6 @@ export function formatUserSettings(
|
|||||||
applicationTheme: userSettings.applicationTheme,
|
applicationTheme: userSettings.applicationTheme,
|
||||||
applicationLanguage: userSettings.applicationLanguage,
|
applicationLanguage: userSettings.applicationLanguage,
|
||||||
defaultSubtitleLanguage: userSettings.defaultSubtitleLanguage,
|
defaultSubtitleLanguage: userSettings.defaultSubtitleLanguage,
|
||||||
|
proxyUrls: userSettings.proxyUrls,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
import { ormConf } from '@/config/orm';
|
import { ormConf } from '@/config/orm';
|
||||||
import { makeOrmConfig } from '@/modules/mikro/orm';
|
import { makeOrmConfig } from '@/modules/mikro/orm';
|
||||||
|
|
||||||
export default makeOrmConfig(ormConf.postgres.connection);
|
export default makeOrmConfig(ormConf.postgres.connection, ormConf.postgres.ssl);
|
||||||
|
@@ -1,11 +1,9 @@
|
|||||||
import { challengeCodeJob } from '@/modules/jobs/list/challengeCode';
|
import { challengeCodeJob } from '@/modules/jobs/list/challengeCode';
|
||||||
import { sessionExpiryJob } from '@/modules/jobs/list/sessionExpiry';
|
import { sessionExpiryJob } from '@/modules/jobs/list/sessionExpiry';
|
||||||
import { userDeletionJob } from '@/modules/jobs/list/userDeletion';
|
import { userDeletionJob } from '@/modules/jobs/list/userDeletion';
|
||||||
import { providerMetricCleanupJob } from '@/modules/jobs/list/providerMetricCleanup';
|
|
||||||
|
|
||||||
export async function setupJobs() {
|
export async function setupJobs() {
|
||||||
challengeCodeJob.start();
|
challengeCodeJob.start();
|
||||||
sessionExpiryJob.start();
|
sessionExpiryJob.start();
|
||||||
userDeletionJob.start();
|
userDeletionJob.start();
|
||||||
providerMetricCleanupJob.start();
|
|
||||||
}
|
}
|
||||||
|
@@ -1,27 +0,0 @@
|
|||||||
import { ProviderMetric } from '@/db/models/ProviderMetrics';
|
|
||||||
import { job } from '@/modules/jobs/job';
|
|
||||||
import ms from 'ms';
|
|
||||||
|
|
||||||
// every day at 12:00:00
|
|
||||||
export const providerMetricCleanupJob = job(
|
|
||||||
'provider-metric-cleanup',
|
|
||||||
'0 12 * * *',
|
|
||||||
async ({ em, log }) => {
|
|
||||||
const now = new Date();
|
|
||||||
const thirtyDaysAgo = new Date(now.getTime() - ms('30d'));
|
|
||||||
|
|
||||||
const deletedMetrics = await em
|
|
||||||
.createQueryBuilder(ProviderMetric)
|
|
||||||
.delete()
|
|
||||||
.where({
|
|
||||||
createdAt: {
|
|
||||||
$lt: thirtyDaysAgo,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
.execute<{ affectedRows: number }>('run');
|
|
||||||
|
|
||||||
log.info(
|
|
||||||
`Removed ${deletedMetrics.affectedRows} metrics that were older than 30 days`,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
@@ -9,17 +9,11 @@ const log = scopedLogger('metrics');
|
|||||||
|
|
||||||
export type Metrics = {
|
export type Metrics = {
|
||||||
user: Counter<'namespace'>;
|
user: Counter<'namespace'>;
|
||||||
providerMetrics: Counter<
|
captchaSolves: Counter<'success'>;
|
||||||
| 'title'
|
providerHostnames: Counter<'hostname'>;
|
||||||
| 'tmdb_id'
|
providerStatuses: Counter<'provider_id' | 'status'>;
|
||||||
| 'season_id'
|
watchMetrics: Counter<'title' | 'tmdb_full_id' | 'provider_id' | 'success'>;
|
||||||
| 'episode_id'
|
toolMetrics: Counter<'tool'>;
|
||||||
| 'status'
|
|
||||||
| 'type'
|
|
||||||
| 'provider_id'
|
|
||||||
| 'embed_id'
|
|
||||||
| 'hostname'
|
|
||||||
>;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let metrics: null | Metrics = null;
|
let metrics: null | Metrics = null;
|
||||||
@@ -42,31 +36,45 @@ export async function setupMetrics(app: FastifyInstance) {
|
|||||||
|
|
||||||
metrics = {
|
metrics = {
|
||||||
user: new Counter({
|
user: new Counter({
|
||||||
name: 'user_count',
|
name: 'mw_user_count',
|
||||||
help: 'user_help',
|
help: 'mw_user_help',
|
||||||
labelNames: ['namespace'],
|
labelNames: ['namespace'],
|
||||||
}),
|
}),
|
||||||
providerMetrics: new Counter({
|
captchaSolves: new Counter({
|
||||||
name: 'provider_metrics',
|
name: 'mw_captcha_solves',
|
||||||
help: 'provider_metrics',
|
help: 'mw_captcha_solves',
|
||||||
labelNames: [
|
labelNames: ['success'],
|
||||||
'episode_id',
|
}),
|
||||||
'provider_id',
|
providerHostnames: new Counter({
|
||||||
'season_id',
|
name: 'mw_provider_hostname_count',
|
||||||
'status',
|
help: 'mw_provider_hostname_count',
|
||||||
'title',
|
labelNames: ['hostname'],
|
||||||
'tmdb_id',
|
}),
|
||||||
'type',
|
providerStatuses: new Counter({
|
||||||
'embed_id',
|
name: 'mw_provider_status_count',
|
||||||
'hostname',
|
help: 'mw_provider_status_count',
|
||||||
],
|
labelNames: ['provider_id', 'status'],
|
||||||
|
}),
|
||||||
|
watchMetrics: new Counter({
|
||||||
|
name: 'mw_media_watch_count',
|
||||||
|
help: 'mw_media_watch_count',
|
||||||
|
labelNames: ['title', 'tmdb_full_id', 'provider_id', 'success'],
|
||||||
|
}),
|
||||||
|
toolMetrics: new Counter({
|
||||||
|
name: 'mw_provider_tool_count',
|
||||||
|
help: 'mw_provider_tool_count',
|
||||||
|
labelNames: ['tool'],
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
|
|
||||||
const promClient = app.metrics.client;
|
const promClient = app.metrics.client;
|
||||||
|
|
||||||
promClient.register.registerMetric(metrics.user);
|
promClient.register.registerMetric(metrics.user);
|
||||||
promClient.register.registerMetric(metrics.providerMetrics);
|
promClient.register.registerMetric(metrics.providerHostnames);
|
||||||
|
promClient.register.registerMetric(metrics.providerStatuses);
|
||||||
|
promClient.register.registerMetric(metrics.watchMetrics);
|
||||||
|
promClient.register.registerMetric(metrics.captchaSolves);
|
||||||
|
promClient.register.registerMetric(metrics.toolMetrics);
|
||||||
|
|
||||||
const orm = getORM();
|
const orm = getORM();
|
||||||
const em = orm.em.fork();
|
const em = orm.em.fork();
|
||||||
|
@@ -18,6 +18,7 @@ export async function setupMikroORM() {
|
|||||||
conf.postgres.connection,
|
conf.postgres.connection,
|
||||||
conf.postgres.debugLogging,
|
conf.postgres.debugLogging,
|
||||||
(msg) => log.info(msg),
|
(msg) => log.info(msg),
|
||||||
|
conf.postgres.ssl,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (conf.postgres.syncSchema) {
|
if (conf.postgres.syncSchema) {
|
||||||
|
@@ -2,7 +2,10 @@ import { Options } from '@mikro-orm/core';
|
|||||||
import { MikroORM, PostgreSqlDriver } from '@mikro-orm/postgresql';
|
import { MikroORM, PostgreSqlDriver } from '@mikro-orm/postgresql';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
|
||||||
export function makeOrmConfig(url: string): Options<PostgreSqlDriver> {
|
export function makeOrmConfig(
|
||||||
|
url: string,
|
||||||
|
ssl: boolean,
|
||||||
|
): Options<PostgreSqlDriver> {
|
||||||
return {
|
return {
|
||||||
type: 'postgresql',
|
type: 'postgresql',
|
||||||
clientUrl: url,
|
clientUrl: url,
|
||||||
@@ -13,6 +16,11 @@ export function makeOrmConfig(url: string): Options<PostgreSqlDriver> {
|
|||||||
pathTs: './migrations',
|
pathTs: './migrations',
|
||||||
path: './migrations',
|
path: './migrations',
|
||||||
},
|
},
|
||||||
|
driverOptions: {
|
||||||
|
connection: {
|
||||||
|
ssl,
|
||||||
|
},
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -20,9 +28,10 @@ export async function createORM(
|
|||||||
url: string,
|
url: string,
|
||||||
debug: boolean,
|
debug: boolean,
|
||||||
log: (msg: string) => void,
|
log: (msg: string) => void,
|
||||||
|
ssl: boolean,
|
||||||
) {
|
) {
|
||||||
return await MikroORM.init<PostgreSqlDriver>({
|
return await MikroORM.init<PostgreSqlDriver>({
|
||||||
...makeOrmConfig(url),
|
...makeOrmConfig(url, ssl),
|
||||||
logger: log,
|
logger: log,
|
||||||
debug,
|
debug,
|
||||||
});
|
});
|
||||||
|
@@ -2,6 +2,7 @@ import Redis from 'ioredis';
|
|||||||
import RateLimiter from 'async-ratelimiter';
|
import RateLimiter from 'async-ratelimiter';
|
||||||
import ms from 'ms';
|
import ms from 'ms';
|
||||||
import { StatusError } from '@/services/error';
|
import { StatusError } from '@/services/error';
|
||||||
|
import { IpReq, getIp } from '@/services/ip';
|
||||||
|
|
||||||
export interface LimiterOptions {
|
export interface LimiterOptions {
|
||||||
redis: Redis;
|
redis: Redis;
|
||||||
@@ -26,8 +27,8 @@ export class Limiter {
|
|||||||
this.redis = ops.redis;
|
this.redis = ops.redis;
|
||||||
}
|
}
|
||||||
|
|
||||||
async bump(req: { ip: string }, ops: BucketOptions) {
|
async bump(req: IpReq, ops: BucketOptions) {
|
||||||
const ip = req.ip;
|
const ip = getIp(req);
|
||||||
if (!this.buckets[ops.id]) {
|
if (!this.buckets[ops.id]) {
|
||||||
this.buckets[ops.id] = {
|
this.buckets[ops.id] = {
|
||||||
limiter: new RateLimiter({
|
limiter: new RateLimiter({
|
||||||
@@ -54,7 +55,7 @@ export class Limiter {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async assertAndBump(req: { ip: string }, ops: BucketOptions) {
|
async assertAndBump(req: IpReq, ops: BucketOptions) {
|
||||||
const { hasBeenLimited } = await this.bump(req, ops);
|
const { hasBeenLimited } = await this.bump(req, ops);
|
||||||
if (hasBeenLimited) {
|
if (hasBeenLimited) {
|
||||||
throw new StatusError('Ratelimited', 429);
|
throw new StatusError('Ratelimited', 429);
|
||||||
|
@@ -1,8 +1,8 @@
|
|||||||
import { handle } from '@/services/handler';
|
import { handle } from '@/services/handler';
|
||||||
import { makeRouter } from '@/services/router';
|
import { makeRouter } from '@/services/router';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { ProviderMetric, status } from '@/db/models/ProviderMetrics';
|
|
||||||
import { getMetrics } from '@/modules/metrics';
|
import { getMetrics } from '@/modules/metrics';
|
||||||
|
import { status } from '@/routes/statuses';
|
||||||
|
|
||||||
const metricsProviderSchema = z.object({
|
const metricsProviderSchema = z.object({
|
||||||
tmdbId: z.string(),
|
tmdbId: z.string(),
|
||||||
@@ -19,6 +19,7 @@ const metricsProviderSchema = z.object({
|
|||||||
|
|
||||||
const metricsProviderInputSchema = z.object({
|
const metricsProviderInputSchema = z.object({
|
||||||
items: z.array(metricsProviderSchema).max(10).min(1),
|
items: z.array(metricsProviderSchema).max(10).min(1),
|
||||||
|
tool: z.string().optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const metricsRouter = makeRouter((app) => {
|
export const metricsRouter = makeRouter((app) => {
|
||||||
@@ -29,7 +30,7 @@ export const metricsRouter = makeRouter((app) => {
|
|||||||
body: metricsProviderInputSchema,
|
body: metricsProviderInputSchema,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
handle(async ({ em, body, req, limiter }) => {
|
handle(async ({ body, req, limiter }) => {
|
||||||
await limiter?.assertAndBump(req, {
|
await limiter?.assertAndBump(req, {
|
||||||
id: 'provider_metrics',
|
id: 'provider_metrics',
|
||||||
max: 300,
|
max: 300,
|
||||||
@@ -37,43 +38,65 @@ export const metricsRouter = makeRouter((app) => {
|
|||||||
window: '30m',
|
window: '30m',
|
||||||
});
|
});
|
||||||
|
|
||||||
const hostname = req.headers.origin?.slice(0, 255) ?? 'unknown origin';
|
const hostname = req.headers.origin?.slice(0, 255) ?? '<UNKNOWN>';
|
||||||
|
getMetrics().providerHostnames.inc({
|
||||||
const entities = body.items.map((v) => {
|
|
||||||
const errorMessage = v.errorMessage?.slice(0, 200);
|
|
||||||
const truncatedFullError = v.fullError?.slice(0, 2000);
|
|
||||||
|
|
||||||
const metric = new ProviderMetric();
|
|
||||||
em.assign(metric, {
|
|
||||||
providerId: v.providerId,
|
|
||||||
embedId: v.embedId,
|
|
||||||
fullError: truncatedFullError,
|
|
||||||
errorMessage: errorMessage,
|
|
||||||
episodeId: v.episodeId,
|
|
||||||
seasonId: v.seasonId,
|
|
||||||
status: v.status,
|
|
||||||
title: v.title,
|
|
||||||
tmdbId: v.tmdbId,
|
|
||||||
type: v.type,
|
|
||||||
hostname,
|
hostname,
|
||||||
});
|
});
|
||||||
return metric;
|
|
||||||
});
|
|
||||||
|
|
||||||
entities.forEach((entity) => {
|
body.items.forEach((item) => {
|
||||||
getMetrics().providerMetrics.inc({
|
getMetrics().providerStatuses.inc({
|
||||||
episode_id: entity.episodeId,
|
provider_id: item.embedId ?? item.providerId,
|
||||||
provider_id: entity.providerId,
|
status: item.status,
|
||||||
season_id: entity.seasonId,
|
|
||||||
status: entity.status,
|
|
||||||
title: entity.title,
|
|
||||||
tmdb_id: entity.tmdbId,
|
|
||||||
type: entity.type,
|
|
||||||
hostname,
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
await em.persistAndFlush(entities);
|
const itemList = [...body.items];
|
||||||
|
itemList.reverse();
|
||||||
|
const lastSuccessfulItem = body.items.find(
|
||||||
|
(v) => v.status === status.success,
|
||||||
|
);
|
||||||
|
const lastItem = itemList[0];
|
||||||
|
|
||||||
|
if (lastItem) {
|
||||||
|
getMetrics().watchMetrics.inc({
|
||||||
|
tmdb_full_id: lastItem.type + '-' + lastItem.tmdbId,
|
||||||
|
provider_id: lastSuccessfulItem?.providerId ?? lastItem.providerId,
|
||||||
|
title: lastItem.title,
|
||||||
|
success: (!!lastSuccessfulItem).toString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (body.tool) {
|
||||||
|
getMetrics().toolMetrics.inc({
|
||||||
|
tool: body.tool,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
app.post(
|
||||||
|
'/metrics/captcha',
|
||||||
|
{
|
||||||
|
schema: {
|
||||||
|
body: z.object({
|
||||||
|
success: z.boolean(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
handle(async ({ body, req, limiter }) => {
|
||||||
|
await limiter?.assertAndBump(req, {
|
||||||
|
id: 'captcha_solves',
|
||||||
|
max: 300,
|
||||||
|
inc: 1,
|
||||||
|
window: '30m',
|
||||||
|
});
|
||||||
|
|
||||||
|
getMetrics().captchaSolves.inc({
|
||||||
|
success: body.success.toString(),
|
||||||
|
});
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
6
src/routes/statuses.ts
Normal file
6
src/routes/statuses.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export const status = {
|
||||||
|
failed: 'failed',
|
||||||
|
notfound: 'notfound',
|
||||||
|
success: 'success',
|
||||||
|
} as const;
|
||||||
|
export type Status = keyof typeof status;
|
@@ -6,7 +6,6 @@ import {
|
|||||||
import { StatusError } from '@/services/error';
|
import { StatusError } from '@/services/error';
|
||||||
import { handle } from '@/services/handler';
|
import { handle } from '@/services/handler';
|
||||||
import { makeRouter } from '@/services/router';
|
import { makeRouter } from '@/services/router';
|
||||||
import { randomUUID } from 'crypto';
|
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
const bookmarkDataSchema = z.object({
|
const bookmarkDataSchema = z.object({
|
||||||
|
@@ -6,6 +6,7 @@ import {
|
|||||||
import { StatusError } from '@/services/error';
|
import { StatusError } from '@/services/error';
|
||||||
import { handle } from '@/services/handler';
|
import { handle } from '@/services/handler';
|
||||||
import { makeRouter } from '@/services/router';
|
import { makeRouter } from '@/services/router';
|
||||||
|
import { FilterQuery } from '@mikro-orm/core';
|
||||||
import { randomUUID } from 'crypto';
|
import { randomUUID } from 'crypto';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
@@ -18,6 +19,7 @@ const progressItemSchema = z.object({
|
|||||||
episodeId: z.string().optional(),
|
episodeId: z.string().optional(),
|
||||||
seasonNumber: z.number().optional(),
|
seasonNumber: z.number().optional(),
|
||||||
episodeNumber: z.number().optional(),
|
episodeNumber: z.number().optional(),
|
||||||
|
updatedAt: z.string().datetime({ offset: true }).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const userProgressRouter = makeRouter((app) => {
|
export const userProgressRouter = makeRouter((app) => {
|
||||||
@@ -100,7 +102,9 @@ export const userProgressRouter = makeRouter((app) => {
|
|||||||
if (newItemIndex > -1) {
|
if (newItemIndex > -1) {
|
||||||
const newItem = newItems[newItemIndex];
|
const newItem = newItems[newItemIndex];
|
||||||
if (existingItem.watched < newItem.watched) {
|
if (existingItem.watched < newItem.watched) {
|
||||||
existingItem.updatedAt = new Date();
|
existingItem.updatedAt = defaultAndCoerceDateTime(
|
||||||
|
newItem.updatedAt,
|
||||||
|
);
|
||||||
existingItem.watched = newItem.watched;
|
existingItem.watched = newItem.watched;
|
||||||
}
|
}
|
||||||
itemsUpserted.push(existingItem);
|
itemsUpserted.push(existingItem);
|
||||||
@@ -123,7 +127,7 @@ export const userProgressRouter = makeRouter((app) => {
|
|||||||
tmdbId: newItem.tmdbId,
|
tmdbId: newItem.tmdbId,
|
||||||
userId: params.uid,
|
userId: params.uid,
|
||||||
watched: newItem.watched,
|
watched: newItem.watched,
|
||||||
updatedAt: new Date(),
|
updatedAt: defaultAndCoerceDateTime(newItem.updatedAt),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,22 +165,28 @@ export const userProgressRouter = makeRouter((app) => {
|
|||||||
if (auth.user.id !== params.uid)
|
if (auth.user.id !== params.uid)
|
||||||
throw new StatusError('Cannot modify user other than yourself', 403);
|
throw new StatusError('Cannot modify user other than yourself', 403);
|
||||||
|
|
||||||
const progressItem = await em.findOne(ProgressItem, {
|
const query: FilterQuery<ProgressItem> = {
|
||||||
userId: params.uid,
|
userId: params.uid,
|
||||||
tmdbId: params.tmdbid,
|
tmdbId: params.tmdbid,
|
||||||
episodeId: body.episodeId,
|
};
|
||||||
seasonId: body.seasonId,
|
if (body.seasonId) query.seasonId = body.seasonId;
|
||||||
});
|
if (body.episodeId) query.episodeId = body.episodeId;
|
||||||
if (!progressItem) {
|
const progressItems = await em.find(ProgressItem, query);
|
||||||
|
|
||||||
|
if (progressItems.length === 0) {
|
||||||
return {
|
return {
|
||||||
|
count: 0,
|
||||||
tmdbId: params.tmdbid,
|
tmdbId: params.tmdbid,
|
||||||
episodeId: body.episodeId,
|
episodeId: body.episodeId,
|
||||||
seasonId: body.seasonId,
|
seasonId: body.seasonId,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
await em.removeAndFlush(progressItem);
|
progressItems.forEach((v) => em.remove(v));
|
||||||
|
await em.flush();
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
count: progressItems.length,
|
||||||
tmdbId: params.tmdbid,
|
tmdbId: params.tmdbid,
|
||||||
episodeId: body.episodeId,
|
episodeId: body.episodeId,
|
||||||
seasonId: body.seasonId,
|
seasonId: body.seasonId,
|
||||||
@@ -207,3 +217,14 @@ export const userProgressRouter = makeRouter((app) => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 13th July 2021 - movie-web epoch
|
||||||
|
const minEpoch = 1626134400000;
|
||||||
|
|
||||||
|
function defaultAndCoerceDateTime(dateTime: string | undefined) {
|
||||||
|
const epoch = dateTime ? new Date(dateTime).getTime() : Date.now();
|
||||||
|
|
||||||
|
const clampedEpoch = Math.max(minEpoch, Math.min(epoch, Date.now()));
|
||||||
|
|
||||||
|
return new Date(clampedEpoch);
|
||||||
|
}
|
||||||
|
@@ -41,6 +41,7 @@ export const userSettingsRouter = makeRouter((app) => {
|
|||||||
applicationLanguage: z.string().nullable().optional(),
|
applicationLanguage: z.string().nullable().optional(),
|
||||||
applicationTheme: z.string().nullable().optional(),
|
applicationTheme: z.string().nullable().optional(),
|
||||||
defaultSubtitleLanguage: z.string().nullable().optional(),
|
defaultSubtitleLanguage: z.string().nullable().optional(),
|
||||||
|
proxyUrls: z.string().array().nullable().optional(),
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -64,6 +65,7 @@ export const userSettingsRouter = makeRouter((app) => {
|
|||||||
settings.defaultSubtitleLanguage = body.defaultSubtitleLanguage;
|
settings.defaultSubtitleLanguage = body.defaultSubtitleLanguage;
|
||||||
if (body.applicationTheme !== undefined)
|
if (body.applicationTheme !== undefined)
|
||||||
settings.applicationTheme = body.applicationTheme;
|
settings.applicationTheme = body.applicationTheme;
|
||||||
|
if (body.proxyUrls !== undefined) settings.proxyUrls = body.proxyUrls;
|
||||||
|
|
||||||
await em.persistAndFlush(settings);
|
await em.persistAndFlush(settings);
|
||||||
return formatUserSettings(settings);
|
return formatUserSettings(settings);
|
||||||
|
@@ -4,16 +4,14 @@ import { StatusError } from '@/services/error';
|
|||||||
export async function isValidCaptcha(token: string): Promise<boolean> {
|
export async function isValidCaptcha(token: string): Promise<boolean> {
|
||||||
if (!conf.captcha.secret)
|
if (!conf.captcha.secret)
|
||||||
throw new Error('isValidCaptcha() is called but no secret set');
|
throw new Error('isValidCaptcha() is called but no secret set');
|
||||||
|
const formData = new URLSearchParams();
|
||||||
|
formData.append('secret', conf.captcha.secret);
|
||||||
|
formData.append('response', token);
|
||||||
const res = await fetch('https://www.google.com/recaptcha/api/siteverify', {
|
const res = await fetch('https://www.google.com/recaptcha/api/siteverify', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify({
|
body: formData,
|
||||||
secret: conf.captcha.secret,
|
|
||||||
response: token,
|
|
||||||
}),
|
|
||||||
headers: {
|
|
||||||
'content-type': 'application/json',
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const json = await res.json();
|
const json = await res.json();
|
||||||
return !!json.success;
|
return !!json.success;
|
||||||
}
|
}
|
||||||
|
27
src/services/ip.ts
Normal file
27
src/services/ip.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { conf } from '@/config';
|
||||||
|
import { IncomingHttpHeaders } from 'http';
|
||||||
|
|
||||||
|
export type IpReq = {
|
||||||
|
ip: string;
|
||||||
|
headers: IncomingHttpHeaders;
|
||||||
|
};
|
||||||
|
|
||||||
|
const trustCloudflare = conf.server.trustCloudflare;
|
||||||
|
|
||||||
|
function getSingleHeader(
|
||||||
|
headers: IncomingHttpHeaders,
|
||||||
|
key: string,
|
||||||
|
): string | undefined {
|
||||||
|
const header = headers[key];
|
||||||
|
if (Array.isArray(header)) return header[0];
|
||||||
|
return header;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getIp(req: IpReq) {
|
||||||
|
const cfIp = getSingleHeader(req.headers, 'cf-connecting-ip');
|
||||||
|
if (trustCloudflare && cfIp) {
|
||||||
|
return cfIp;
|
||||||
|
}
|
||||||
|
|
||||||
|
return req.ip;
|
||||||
|
}
|
Reference in New Issue
Block a user