99 Commits
1.0.3 ... 1.3.1

Author SHA1 Message Date
William Oldham
f4b3d43b8f Merge pull request #39 from movie-web/dev
Backend update v1.3.1
2024-01-25 21:34:41 +00:00
mrjvs
2fe48d24d7 Merge branch 'master' into dev 2024-01-25 22:33:24 +01:00
William Oldham
b0f5b28084 Merge pull request #38 from movie-web/scrapetools
Add tool metrics
2024-01-25 21:29:24 +00:00
mrjvs
b5ee9f1f7a Merge branch 'dev' into scrapetools 2024-01-25 22:28:33 +01:00
mrjvs
eb0f47ba53 Bump version 2024-01-25 22:28:08 +01:00
mrjvs
26b46876c5 fix linting 2024-01-25 22:27:54 +01:00
mrjvs
f58c2c86e5 Merge pull request #37 from gsi-kevincarrera/fix/backend-always-return-true
Fix: Implement function to correctly handle boolean strings with zod
2024-01-25 22:27:15 +01:00
mrjvs
4af2d32b72 Add tool metrics 2024-01-25 22:24:58 +01:00
Kevin Carrera Calzado
a911e52ddb Add default false value to boolean schema 2024-01-24 12:54:24 -05:00
Kevin Carrera Calzado
7b26b029de Fix:Implement function to handle boolean strings 2024-01-24 12:34:01 -05:00
William Oldham
06ad2249d6 Merge pull request #35 from movie-web/remove-arm
Remove ARM 32-bit from Docker Build
2024-01-09 21:36:01 +00:00
William Oldham
14601b9010 Remove ARM 32-bit from Docker Build 2024-01-09 21:01:52 +00:00
William Oldham
b1eeb21ba4 Merge pull request #34 from weeryan17/feature/arm-build
Update workflows to support arm
2024-01-07 17:58:15 +00:00
weeryan17
5855943a56 Update .github/workflows/linting_testing.yml
Co-authored-by: William Oldham <github@binaryoverload.co.uk>
2024-01-07 12:55:30 -05:00
weeryan17
9073010f4c Update .github/workflows/linting_testing.yml
Co-authored-by: William Oldham <github@binaryoverload.co.uk>
2024-01-07 12:55:24 -05:00
weeryan17
78e6b6443f Update CODEOWNERS file 2024-01-07 12:51:09 -05:00
weeryan17
e7c5d93cc3 Update workflows to support arm 2024-01-07 12:42:45 -05:00
mrjvs
9fe8cb4877 Merge pull request #31 from Caio-Nogueira/fix-backend-captcha
update deprecated composer syntax; change body format in API request
2024-01-05 21:04:32 +01:00
mrjvs
66840d7894 Merge branch 'dev' into fix-backend-captcha 2024-01-05 20:19:26 +01:00
William Oldham
befa173445 Merge pull request #32 from movie-web/dev
Version 1.3.0 backend
2024-01-02 21:45:53 +00:00
mrjvs
1c1d70fa05 Merge branch 'master' into dev 2024-01-02 22:41:31 +01:00
mrjvs
6b83fcd158 Merge branch 'dev' of https://github.com/movie-web/backend into dev 2024-01-02 22:40:32 +01:00
mrjvs
f8870b5929 Bump version 2024-01-02 22:40:15 +01:00
mrjvs
727a9cdd43 Merge pull request #28 from qtchaos/proxy-syncing
Add proxyUrls column to UserSettings model
2024-01-01 19:04:34 +01:00
mrjvs
206844e758 Merge branch 'dev' into proxy-syncing 2024-01-01 19:03:43 +01:00
qtchaos
b2e0841d0b Swap to using ArrayType 2024-01-01 19:46:46 +02:00
mrjvs
886df2ffb4 Merge pull request #29 from qtchaos/ssl
Add config support for SSL postgres connections.
2024-01-01 18:09:39 +01:00
mrjvs
6ea07ea685 Merge branch 'dev' into ssl 2024-01-01 18:06:13 +01:00
mrjvs
1010eaf71e Merge branch 'dev' into proxy-syncing 2024-01-01 18:04:59 +01:00
mrjvs
1632f138b0 Merge branch 'dev' into fix-backend-captcha 2023-12-31 14:10:18 +01:00
caio_nogueira_27
0c3de831fb update deprecated composer syntax; change body format in API request 2023-12-31 13:03:32 +00:00
mrjvs
ebe00ecbd6 Merge pull request #30 from qtchaos/pnpm
Swap to using `pnpm exec` instead of `npx` in scripts
2023-12-31 12:59:16 +01:00
qtchaos
3bb427401f Update package.json scripts to use pnpm 2023-12-30 14:07:38 +02:00
qtchaos
b2598e3d82 Add SSL support for PostgreSQL connection 2023-12-30 01:09:04 +02:00
qtchaos
bf55be2978 Add proxyUrls column to UserSettings model 2023-12-29 23:56:25 +02:00
William Oldham
8f52dad296 Merge pull request #27 from movie-web/dev
Register Captcha Solves Metric
2023-12-21 21:06:09 +00:00
William Oldham
9a27b0b0b4 Merge branch 'master' into dev 2023-12-21 21:04:00 +00:00
William Oldham
46baac466d Register Captcha Solves Metric 2023-12-21 21:03:18 +00:00
William Oldham
26316c7755 Merge pull request #26 from movie-web/dev
Backend v1.2.0
2023-12-21 20:21:44 +00:00
mrjvs
d5851b522a Merge branch 'master' into dev 2023-12-21 21:19:26 +01:00
mrjvs
7145d6c246 Bump version 2023-12-21 21:17:32 +01:00
William Oldham
961ac7eeca Merge pull request #25 from movie-web/fix-stuff
Ratelimit fix & optimize metrics
2023-12-21 20:11:10 +00:00
mrjvs
59ab9b48bd Implement trusted cloudflare ips
Co-authored-by: William Oldham <github@binaryoverload.co.uk>
2023-12-21 20:38:51 +01:00
mrjvs
07ecd445f9 Add captcha solves metric 2023-12-21 20:11:17 +01:00
mrjvs
5ebecd1476 Remove provider metric table and replace prometheus metrics with something more efficient
Co-authored-by: William Oldham <github@binaryoverload.co.uk>
2023-12-21 20:01:27 +01:00
William Oldham
f4e9a96666 Merge pull request #24 from movie-web/dev
Update bugfix
2023-12-14 20:48:14 +00:00
William Oldham
60dda8ac57 Merge branch 'master' into dev 2023-12-14 20:48:04 +00:00
William Oldham
d84cdc4239 Merge pull request #23 from movie-web/fix-show-delete
Fix show deletion
2023-12-14 20:47:40 +00:00
mrjvs
c2cba27e68 remove unused import 2023-12-14 21:10:48 +01:00
mrjvs
c3259156ac bump version 2023-12-14 21:07:38 +01:00
mrjvs
9ef12d1c0f Delete all entries of a show 2023-12-14 21:07:24 +01:00
William Oldham
e173003f55 Merge pull request #22 from movie-web/dev
v1.1.5 - Progress importing now uses the user's date
2023-12-06 20:03:22 +00:00
William Oldham
9f90ba7da2 Merge pull request #21 from movie-web/progress-date
Add UpdatedAt from User date for Progress
2023-12-06 20:01:35 +00:00
William Oldham
05bf651939 Revert "Use date to compare progress items"
This reverts commit cf0125755c.
2023-12-06 19:59:50 +00:00
William Oldham
cf0125755c Use date to compare progress items 2023-12-06 19:55:09 +00:00
William Oldham
4129b80828 Use movie-web birthday 2023-12-06 19:49:30 +00:00
William Oldham
e5c3cde51b Only use user date on bulk import 2023-12-06 19:46:22 +00:00
William Oldham
4bf0285d06 Bump version 2023-12-06 19:43:57 +00:00
William Oldham
53d5ca1461 Add updatedAt saving into progress imports 2023-12-06 19:43:37 +00:00
mrjvs
3211f74387 Merge pull request #20 from movie-web/dev
V1.1.4
2023-11-25 17:21:20 +01:00
mrjvs
8cffd0e7e8 Merge branch 'master' into dev 2023-11-25 17:11:46 +01:00
mrjvs
c531329931 Merge pull request #19 from movie-web/device-name-fix
Remove duplicate session router
2023-11-25 17:09:20 +01:00
mrjvs
690357ba5a bump version 2023-11-25 16:09:55 +01:00
mrjvs
10e9e06c27 only have one session router 2023-11-25 16:09:29 +01:00
mrjvs
783d89492d Merge pull request #18 from movie-web/dev
Version 1.1.3: Add endpoint to edit device name
2023-11-24 20:07:57 +01:00
mrjvs
4663b2c1f7 Merge branch 'master' into dev 2023-11-24 20:06:42 +01:00
William Oldham
ceea274e70 Merge pull request #17 from movie-web/device-name-update
Device name update + fixing settings endpoint
2023-11-24 18:56:08 +00:00
William Oldham
6d2dcd04e9 Apply suggestions from code review 2023-11-24 18:55:20 +00:00
mrjvs
8a3c0d6edb add settings nullable + undefined difference 2023-11-24 18:40:54 +01:00
mrjvs
72657e73c8 add update session endpoint 2023-11-24 18:00:06 +01:00
William Oldham
1bb344ec2f Merge pull request #16 from movie-web/dev
v1.1.2: Fix Settings
2023-11-22 23:23:00 +00:00
William Oldham
b30623c483 Merge pull request #15 from movie-web/fix-user-settings
Fix user settings
2023-11-22 23:21:26 +00:00
William Oldham
233cb11ac6 Bump version 2023-11-22 23:17:29 +00:00
William Oldham
d3aa4847f8 Update UserSettings primary key to text, to match user 2023-11-22 23:17:29 +00:00
William Oldham
4bf2e658f7 Fix ESLint Ignore for migrations 2023-11-22 23:17:29 +00:00
William Oldham
c18ff489c3 Merge pull request #14 from movie-web/dev
Fix @me endpoint
2023-11-19 20:00:54 +00:00
William Oldham
fcc3dc60d9 Merge branch 'master' into dev 2023-11-19 20:00:06 +00:00
William Oldham
c7a706cdf0 Fix @me endpoint 2023-11-19 19:59:02 +00:00
mrjvs
36c0548c63 Merge pull request #13 from movie-web/dev
Version 1.1: Progress and Bookmark Bulk Importing
2023-11-19 20:48:41 +01:00
mrjvs
60a285316d Merge branch 'master' into dev 2023-11-19 20:47:54 +01:00
William Oldham
fa0e5d0309 Merge pull request #12 from movie-web/import-endpoints
Add Import endpoints
2023-11-19 19:46:57 +00:00
William Oldham
e2b8f123b3 Round duration and watched for progress endpoints 2023-11-19 19:41:59 +00:00
William Oldham
fd9b61061c Return session for @me endpoint 2023-11-19 19:41:47 +00:00
William Oldham
449fd7b153 Bump version 2023-11-18 20:03:52 +00:00
William Oldham
f54b4f6553 Add bookmark import endpoint 2023-11-18 19:57:03 +00:00
William Oldham
787c8a96d6 Update progress import endpoint to be more efficient on memory 2023-11-18 19:48:07 +00:00
William Oldham
3643eea655 Update progress import endpoint 2023-11-18 19:25:33 +00:00
William Oldham
a73baf555b Add progress importing endpoint 2023-11-18 19:21:52 +00:00
William Oldham
6d200e8568 Return ID in progress item response 2023-11-18 19:21:24 +00:00
William Oldham
8e10eb7d59 Add option to enable MikroORM database debug logging 2023-11-18 19:21:02 +00:00
William Oldham
b8016023a4 Merge pull request #11 from movie-web/dev
Pull backend version from package.json
2023-11-12 16:21:20 +00:00
mrjvs
6f48b62275 Merge branch 'master' into dev 2023-11-12 17:20:13 +01:00
William Oldham
709d871a51 Bump version 2023-11-12 16:18:18 +00:00
William Oldham
b2400775fb Pull backend version from package.json 2023-11-12 16:16:45 +00:00
mrjvs
c6720d390a Merge pull request #10 from movie-web/dev
Version 1.0.4 - Store hostname and fix error message storing
2023-11-11 17:46:11 +01:00
mrjvs
d55e0897a9 Merge branch 'master' into dev 2023-11-11 17:45:58 +01:00
mrjvs
4937f148c6 Merge pull request #9 from movie-web/provider-tweaks
Set error fields to have type `text` and add hostname field
2023-11-11 17:10:04 +01:00
William Oldham
f54a45256b Format migrations to be pretty 2023-11-11 16:05:06 +00:00
William Oldham
f1f7660ea2 Set error fields to have type text and add hostname field 2023-11-11 16:02:37 +00:00
36 changed files with 498 additions and 381 deletions

View File

@@ -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

View File

@@ -13,7 +13,7 @@ module.exports = {
sourceType: 'module', sourceType: 'module',
}, },
plugins: ['@typescript-eslint'], plugins: ['@typescript-eslint'],
ignorePatterns: ['./src/db/migrations/**/*'], ignorePatterns: ['src/db/migrations/**/*'],
rules: { rules: {
'@typescript-eslint/interface-name-prefix': 'off', '@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/explicit-function-return-type': 'off',

4
.github/CODEOWNERS vendored
View File

@@ -1,3 +1 @@
* @movie-web/core * @movie-web/project-leads
.github @binaryoverload

View File

@@ -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

View File

@@ -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

View File

@@ -1,6 +1,6 @@
{ {
"name": "backend", "name": "backend",
"version": "1.0.3", "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,

View File

@@ -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',
},
}; };

View File

@@ -8,7 +8,7 @@ const fragments = {
dockerdev: dockerFragment, dockerdev: dockerFragment,
}; };
export const version = '1.0.3'; export const version = process.env.npm_package_version ?? 'unknown';
export const conf = createConfigLoader() export const conf = createConfigLoader()
.addFromEnvironment('MWB_') .addFromEnvironment('MWB_')

View File

@@ -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();

View File

@@ -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,12 +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
// Do NOT use in production, leaks all sensitive data
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
@@ -55,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(),
@@ -66,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({}),

View File

@@ -268,134 +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": "varchar(255)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"mappedType": "string"
},
"full_error": {
"name": "full_error",
"type": "varchar(255)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"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": {
@@ -578,12 +450,12 @@
"columns": { "columns": {
"id": { "id": {
"name": "id", "name": "id",
"type": "uuid", "type": "text",
"unsigned": false, "unsigned": false,
"autoincrement": false, "autoincrement": false,
"primary": false, "primary": false,
"nullable": false, "nullable": false,
"mappedType": "uuid" "mappedType": "text"
}, },
"application_theme": { "application_theme": {
"name": "application_theme", "name": "application_theme",
@@ -611,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",

View File

@@ -0,0 +1,25 @@
import { Migration } from '@mikro-orm/migrations';
export class Migration20231111160045 extends Migration {
async up(): Promise<void> {
this.addSql(
'alter table "provider_metrics" add column "hostname" varchar(255) not null;',
);
this.addSql(
'alter table "provider_metrics" alter column "error_message" type text using ("error_message"::text);',
);
this.addSql(
'alter table "provider_metrics" alter column "full_error" type text using ("full_error"::text);',
);
}
async down(): Promise<void> {
this.addSql(
'alter table "provider_metrics" alter column "error_message" type varchar(255) using ("error_message"::varchar(255));',
);
this.addSql(
'alter table "provider_metrics" alter column "full_error" type varchar(255) using ("full_error"::varchar(255));',
);
this.addSql('alter table "provider_metrics" drop column "hostname";');
}
}

View File

@@ -0,0 +1,14 @@
import { Migration } from '@mikro-orm/migrations';
export class Migration20231122231620 extends Migration {
async up(): Promise<void> {
this.addSql('alter table "user_settings" alter column "id" type text using ("id"::text);');
}
async down(): Promise<void> {
this.addSql('alter table "user_settings" alter column "id" drop default;');
this.addSql('alter table "user_settings" alter column "id" type uuid using ("id"::text::uuid);');
}
}

View 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"));');
}
}

View 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";');
}
}

View File

@@ -53,6 +53,7 @@ export class ProgressItem {
} }
export interface ProgressItemDTO { export interface ProgressItemDTO {
id: string;
tmdbId: string; tmdbId: string;
season: { season: {
id?: string; id?: string;
@@ -77,6 +78,7 @@ export function formatProgressItem(
progressItem: ProgressItem, progressItem: ProgressItem,
): ProgressItemDTO { ): ProgressItemDTO {
return { return {
id: progressItem.id,
tmdbId: progressItem.tmdbId, tmdbId: progressItem.tmdbId,
episode: { episode: {
id: progressItem.episodeId, id: progressItem.episodeId,

View File

@@ -1,48 +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 })
errorMessage?: string;
@Property({ name: 'full_error', nullable: true })
fullError?: string;
}

View File

@@ -1,10 +1,9 @@
import { Entity, PrimaryKey, Property } from '@mikro-orm/core'; import { ArrayType, Entity, PrimaryKey, Property } from '@mikro-orm/core';
import { randomUUID } from 'crypto';
@Entity({ tableName: 'user_settings' }) @Entity({ tableName: 'user_settings' })
export class UserSettings { export class UserSettings {
@PrimaryKey({ name: 'id', type: 'uuid' }) @PrimaryKey({ name: 'id', type: 'text' })
id: string = randomUUID(); id!: string;
@Property({ name: 'application_theme', nullable: true }) @Property({ name: 'application_theme', nullable: true })
applicationTheme?: string | null; applicationTheme?: string | null;
@@ -14,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 {
@@ -21,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(
@@ -31,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,
}; };
} }

View File

@@ -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);

View File

@@ -2,7 +2,7 @@ import { loginAuthRouter } from '@/routes/auth/login';
import { manageAuthRouter } from '@/routes/auth/manage'; import { manageAuthRouter } from '@/routes/auth/manage';
import { metaRouter } from '@/routes/meta'; import { metaRouter } from '@/routes/meta';
import { metricsRouter } from '@/routes/metrics'; import { metricsRouter } from '@/routes/metrics';
import { sessionsRouter } from '@/routes/sessions'; import { sessionsRouter } from '@/routes/sessions/sessions';
import { userBookmarkRouter } from '@/routes/users/bookmark'; import { userBookmarkRouter } from '@/routes/users/bookmark';
import { userDeleteRouter } from '@/routes/users/delete'; import { userDeleteRouter } from '@/routes/users/delete';
import { userEditRouter } from '@/routes/users/edit'; import { userEditRouter } from '@/routes/users/edit';

View File

@@ -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();
} }

View File

@@ -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`,
);
},
);

View File

@@ -9,16 +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'
>;
}; };
let metrics: null | Metrics = null; let metrics: null | Metrics = null;
@@ -41,30 +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',
], 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();

View File

@@ -14,8 +14,11 @@ export function getORM() {
export async function setupMikroORM() { export async function setupMikroORM() {
log.info(`Connecting to postgres`, { evt: 'connecting' }); log.info(`Connecting to postgres`, { evt: 'connecting' });
const mikro = await createORM(conf.postgres.connection, (msg) => const mikro = await createORM(
log.info(msg), conf.postgres.connection,
conf.postgres.debugLogging,
(msg) => log.info(msg),
conf.postgres.ssl,
); );
if (conf.postgres.syncSchema) { if (conf.postgres.syncSchema) {

View File

@@ -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,12 +16,23 @@ export function makeOrmConfig(url: string): Options<PostgreSqlDriver> {
pathTs: './migrations', pathTs: './migrations',
path: './migrations', path: './migrations',
}, },
driverOptions: {
connection: {
ssl,
},
},
}; };
} }
export async function createORM(url: string, log: (msg: string) => void) { export async function createORM(
url: string,
debug: boolean,
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,
}); });
} }

View File

@@ -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);

View File

@@ -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,36 +38,65 @@ export const metricsRouter = makeRouter((app) => {
window: '30m', window: '30m',
}); });
const entities = body.items.map((v) => { const hostname = req.headers.origin?.slice(0, 255) ?? '<UNKNOWN>';
const metric = new ProviderMetric(); getMetrics().providerHostnames.inc({
em.assign(metric, { hostname,
providerId: v.providerId,
embedId: v.embedId,
fullError: v.fullError,
errorMessage: v.errorMessage,
episodeId: v.episodeId,
seasonId: v.seasonId,
status: v.status,
title: v.title,
tmdbId: v.tmdbId,
type: v.type,
});
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,
}); });
}); });
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;
}), }),
); );

View File

@@ -1,35 +0,0 @@
import { Session } from '@/db/models/Session';
import { StatusError } from '@/services/error';
import { handle } from '@/services/handler';
import { makeRouter } from '@/services/router';
import { z } from 'zod';
export const sessionRouter = makeRouter((app) => {
app.delete(
'/sessions/:sid',
{
schema: {
params: z.object({
sid: z.string(),
}),
},
},
handle(async ({ auth, params, em }) => {
await auth.assert();
const targetedSession = await em.findOne(Session, { id: params.sid });
if (!targetedSession)
return {
id: params.sid,
};
if (targetedSession.user !== auth.user.id)
throw new StatusError('Cannot delete sessions you do not own', 401);
await em.removeAndFlush(targetedSession);
return {
id: params.sid,
};
}),
);
});

View File

@@ -13,7 +13,7 @@ export const sessionsRouter = makeRouter((app) => {
sid: z.string(), sid: z.string(),
}), }),
body: z.object({ body: z.object({
name: z.string().max(500).min(1).optional(), deviceName: z.string().max(500).min(1).optional(),
}), }),
}, },
}, },
@@ -25,10 +25,10 @@ export const sessionsRouter = makeRouter((app) => {
if (!targetedSession) if (!targetedSession)
throw new StatusError('Session cannot be found', 404); throw new StatusError('Session cannot be found', 404);
if (targetedSession.user !== auth.user.id) if (targetedSession.id !== params.sid)
throw new StatusError('Cannot modify sessions you do not own', 401); throw new StatusError('Cannot edit sessions other than your own', 401);
if (body.name) targetedSession.device = body.name; if (body.deviceName) targetedSession.device = body.deviceName;
await em.persistAndFlush(targetedSession); await em.persistAndFlush(targetedSession);

6
src/routes/statuses.ts Normal file
View File

@@ -0,0 +1,6 @@
export const status = {
failed: 'failed',
notfound: 'notfound',
success: 'success',
} as const;
export type Status = keyof typeof status;

View File

@@ -8,6 +8,11 @@ import { handle } from '@/services/handler';
import { makeRouter } from '@/services/router'; import { makeRouter } from '@/services/router';
import { z } from 'zod'; import { z } from 'zod';
const bookmarkDataSchema = z.object({
tmdbId: z.string(),
meta: bookmarkMetaSchema,
});
export const userBookmarkRouter = makeRouter((app) => { export const userBookmarkRouter = makeRouter((app) => {
app.get( app.get(
'/users/:uid/bookmarks', '/users/:uid/bookmarks',
@@ -40,9 +45,7 @@ export const userBookmarkRouter = makeRouter((app) => {
uid: z.string(), uid: z.string(),
tmdbid: z.string(), tmdbid: z.string(),
}), }),
body: z.object({ body: bookmarkDataSchema,
meta: bookmarkMetaSchema,
}),
}, },
}, },
handle(async ({ auth, params, body, em }) => { handle(async ({ auth, params, body, em }) => {
@@ -70,6 +73,40 @@ export const userBookmarkRouter = makeRouter((app) => {
}), }),
); );
app.put(
'/users/:uid/bookmarks',
{
schema: {
params: z.object({
uid: z.string(),
}),
body: z.array(bookmarkDataSchema),
},
},
handle(async ({ auth, params, body, em }) => {
await auth.assert();
if (auth.user.id !== params.uid)
throw new StatusError('Cannot modify user other than yourself', 403);
const bookmarks = await em.upsertMany(
Bookmark,
body.map((item) => ({
userId: params.uid,
tmdbId: item.tmdbId,
meta: item.meta,
updatedAt: new Date(),
})),
{
onConflictFields: ['tmdbId', 'userId'],
},
);
await em.flush();
return bookmarks.map(formatBookmark);
}),
);
app.delete( app.delete(
'/users/:uid/bookmarks/:tmdbid', '/users/:uid/bookmarks/:tmdbid',
{ {

View File

@@ -1,3 +1,4 @@
import { formatSession } from '@/db/models/Session';
import { User, formatUser } from '@/db/models/User'; import { User, formatUser } from '@/db/models/User';
import { StatusError } from '@/services/error'; import { StatusError } from '@/services/error';
import { handle } from '@/services/handler'; import { handle } from '@/services/handler';
@@ -5,6 +6,24 @@ import { makeRouter } from '@/services/router';
import { z } from 'zod'; import { z } from 'zod';
export const userGetRouter = makeRouter((app) => { export const userGetRouter = makeRouter((app) => {
app.get(
'/users/@me',
handle(async ({ auth, em }) => {
await auth.assert();
const user = await em.findOne(User, { id: auth.user.id });
if (!user) throw new StatusError('User does not exist', 404);
const session = await auth.getSession();
if (!session) throw new StatusError('Session does not exist', 400);
return {
user: formatUser(user),
session: formatSession(session),
};
}),
);
app.get( app.get(
'/users/:uid', '/users/:uid',
{ {
@@ -16,16 +35,16 @@ export const userGetRouter = makeRouter((app) => {
}, },
handle(async ({ auth, params, em }) => { handle(async ({ auth, params, em }) => {
await auth.assert(); await auth.assert();
let uid = params.uid;
if (uid === '@me') uid = auth.user.id;
if (auth.user.id !== uid) if (auth.user.id !== params.uid)
throw new StatusError('Cannot access users other than yourself', 403); throw new StatusError('Cannot access users other than yourself', 403);
const user = await em.findOne(User, { id: uid }); const user = await em.findOne(User, { id: params.uid });
if (!user) throw new StatusError('User does not exist', 404); if (!user) throw new StatusError('User does not exist', 404);
return formatUser(user); return {
user: formatUser(user),
};
}), }),
); );
}); });

View File

@@ -6,8 +6,22 @@ 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 { z } from 'zod'; import { z } from 'zod';
const progressItemSchema = z.object({
meta: progressMetaSchema,
tmdbId: z.string(),
duration: z.number().transform((n) => Math.round(n)),
watched: z.number().transform((n) => Math.round(n)),
seasonId: z.string().optional(),
episodeId: z.string().optional(),
seasonNumber: z.number().optional(),
episodeNumber: z.number().optional(),
updatedAt: z.string().datetime({ offset: true }).optional(),
});
export const userProgressRouter = makeRouter((app) => { export const userProgressRouter = makeRouter((app) => {
app.put( app.put(
'/users/:uid/progress/:tmdbid', '/users/:uid/progress/:tmdbid',
@@ -17,15 +31,7 @@ export const userProgressRouter = makeRouter((app) => {
uid: z.string(), uid: z.string(),
tmdbid: z.string(), tmdbid: z.string(),
}), }),
body: z.object({ body: progressItemSchema,
meta: progressMetaSchema,
duration: z.number(),
watched: z.number(),
seasonId: z.string().optional(),
episodeId: z.string().optional(),
seasonNumber: z.number().optional(),
episodeNumber: z.number().optional(),
}),
}, },
}, },
handle(async ({ auth, params, body, em }) => { handle(async ({ auth, params, body, em }) => {
@@ -63,6 +69,82 @@ export const userProgressRouter = makeRouter((app) => {
}), }),
); );
app.put(
'/users/:uid/progress/import',
{
schema: {
params: z.object({
uid: z.string(),
}),
body: z.array(progressItemSchema),
},
},
handle(async ({ auth, params, body, em, req, limiter }) => {
await auth.assert();
if (auth.user.id !== params.uid)
throw new StatusError('Cannot modify user other than yourself', 403);
const itemsUpserted: ProgressItem[] = [];
const newItems = [...body];
for (const existingItem of await em.find(ProgressItem, {
userId: params.uid,
})) {
const newItemIndex = newItems.findIndex(
(item) =>
item.tmdbId == existingItem.tmdbId &&
item.seasonId == existingItem.seasonId &&
item.episodeId == existingItem.episodeId,
);
if (newItemIndex > -1) {
const newItem = newItems[newItemIndex];
if (existingItem.watched < newItem.watched) {
existingItem.updatedAt = defaultAndCoerceDateTime(
newItem.updatedAt,
);
existingItem.watched = newItem.watched;
}
itemsUpserted.push(existingItem);
// Remove the item from the array, we have processed it
newItems.splice(newItemIndex, 1);
}
}
// All unprocessed items, aka all items that don't already exist
for (const newItem of newItems) {
itemsUpserted.push({
id: randomUUID(),
duration: newItem.duration,
episodeId: newItem.episodeId,
episodeNumber: newItem.episodeNumber,
meta: newItem.meta,
seasonId: newItem.seasonId,
seasonNumber: newItem.seasonNumber,
tmdbId: newItem.tmdbId,
userId: params.uid,
watched: newItem.watched,
updatedAt: defaultAndCoerceDateTime(newItem.updatedAt),
});
}
const progressItems = await em.upsertMany(ProgressItem, itemsUpserted);
await em.flush();
await limiter?.assertAndBump(req, {
id: 'progress_import',
max: 5,
window: '10m',
});
return progressItems.map(formatProgressItem);
}),
);
app.delete( app.delete(
'/users/:uid/progress/:tmdbid', '/users/:uid/progress/:tmdbid',
{ {
@@ -83,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,
@@ -129,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);
}

View File

@@ -38,9 +38,10 @@ export const userSettingsRouter = makeRouter((app) => {
uid: z.string(), uid: z.string(),
}), }),
body: z.object({ body: z.object({
applicationLanguage: z.string().optional(), applicationLanguage: z.string().nullable().optional(),
applicationTheme: z.string().optional(), applicationTheme: z.string().nullable().optional(),
defaultSubtitleLanguage: z.string().optional(), defaultSubtitleLanguage: z.string().nullable().optional(),
proxyUrls: z.string().array().nullable().optional(),
}), }),
}, },
}, },
@@ -58,12 +59,13 @@ export const userSettingsRouter = makeRouter((app) => {
settings.id = params.uid; settings.id = params.uid;
} }
if (body.applicationLanguage) if (body.applicationLanguage !== undefined)
settings.applicationLanguage = body.applicationLanguage; settings.applicationLanguage = body.applicationLanguage;
if (body.applicationTheme) if (body.defaultSubtitleLanguage !== undefined)
settings.applicationTheme = body.applicationTheme;
if (body.defaultSubtitleLanguage)
settings.defaultSubtitleLanguage = body.defaultSubtitleLanguage; settings.defaultSubtitleLanguage = body.defaultSubtitleLanguage;
if (body.applicationTheme !== undefined)
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);

View File

@@ -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
View 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;
}