Compare commits

...

42 Commits

Author SHA1 Message Date
Rowan Murphy
7f39794116 docs: change comma-separated lists to space-separated
Changed documentation for scopes and required claims lists to correctly reflect source code showing space-separated instead of comma-separated.
2025-09-08 14:08:15 -04:00
Michael Thomas
be5ee1e980 fix(userlinkedaccountssettings): use correct button style for dropdown 2025-09-08 14:08:15 -04:00
Puranjay Savar Mattas
ab3c8e4e7e refactor(oidc): remove explanatory comments
Removes unnecessary tutorial-style comments from the OIDC components. The code is now
self-documenting, and these comments added noise without providing additional value. This change
cleans up the code and aligns it with the project's established style.

Addresses https://github.com/michaelhthomas/jellyseerr/pull/4#pullrequestreview-3079128668
2025-09-08 14:08:14 -04:00
Puranjay Savar Mattas
05b0a1fa99 style(oidc): standardize form error display in OIDC modal
Refactors the form in EditOidcModal to display validation errors manually using a `div` instead of
Formik's `<ErrorMessage>` component. This change brings the component's style in line with the
established pattern used in other forms throughout the application, improving code consistency.

Addresses https://github.com/fallenbagel/jellyseerr/pull/1505#discussion_r2195088361
2025-09-08 14:08:14 -04:00
Puranjay Savar Mattas
cfbf7edf7e chore(login): remove unused ErrorCallout component
Deletes the ErrorCallout.tsx file as it is not used anywhere in the codebase. This cleans up dead
code from the project.

Addresses https://github.com/fallenbagel/jellyseerr/pull/1505#discussion_r2195045066
2025-09-08 14:08:14 -04:00
Puranjay Savar Mattas
8f8a4153b6 fix(auth): prevent duplicate user creation on OIDC login
Adds a check to ensure a user with the same email address does not already exist before creating a
new user during an OIDC callback. If a duplicate email is found, the process is aborted with a 409
Conflict error.

Addresses https://github.com/fallenbagel/jellyseerr/pull/1505#discussion_r2195036663
2025-09-08 14:08:14 -04:00
Puranjay Savar Mattas
f4988aba15 refactor(oidc): inline OIDC utility function
Moves the processCallback function from src/utils/oidc.ts directly into the OidcLoginButton.tsx
component where it is used. The now-empty oidc.ts utility file has been removed. This improves code
co-location as the function is only used in a single place.

Addresses https://github.com/fallenbagel/jellyseerr/pull/1505#discussion_r2194982515
2025-09-08 14:08:14 -04:00
Puranjay Savar Mattas
4a3f38fa10 docs(settings): clarify non-OIDC login methods
Updates the user settings documentation to be more generic. Instead of stating users can only sign
in with their email address, the text now correctly states that they can use their username or email
address. This accounts for both local and media server users.

Addresses https://github.com/fallenbagel/jellyseerr/pull/1505#discussion_r2194953503
2025-09-08 14:08:14 -04:00
Puranjay Savar Mattas
67bbc73564 feat(api): refactor fetch calls to axios
Replaces the native fetch() API with axios for all OIDC-related frontend API calls. This improves
consistency with other parts of the codebase and simplifies error handling.

Addresses https://github.com/fallenbagel/jellyseerr/pull/1505#pullrequestreview-3001436908
2025-09-08 14:08:14 -04:00
Michael Thomas
205aa5da92 docs: add OpenID connect documentation 2025-09-08 14:08:14 -04:00
Michael Thomas
27292c02ea fix(LinkedAccounts): update linked accounts to account for new redirect flow 2025-09-08 14:08:14 -04:00
Michael Thomas
80217c70ea fix(login): hide login form when only OIDC login is enabled 2025-09-08 14:08:14 -04:00
Michael Thomas
7d426f0c7e fix(UpdateOidcModal): do not update slug when changing name of existing provider 2025-09-08 14:08:14 -04:00
Michael Thomas
55870fed20 fix: improve error handling, process callback on login page 2025-09-08 14:08:14 -04:00
Michael Thomas
7bd26eebb5 fix: add database migrations 2025-09-08 14:08:13 -04:00
Michael Thomas
d36dcbed7e fix: tweak login buttons to ensure labels fit 2025-09-08 14:08:13 -04:00
Michael Thomas
03d869ca59 feat: add openid connect settings interface 2025-09-08 14:08:13 -04:00
Michael Thomas
51849cd9de feat: add OpenID Connect options to login screen 2025-09-08 14:08:13 -04:00
Michael Thomas
fa7efa31bc feat: basic OpenID Connect support 2025-09-08 14:08:13 -04:00
THOMAS B
4878722030 fix(tvdb): respect display language when fetching metadata (#1889)
* fix(tvdb): respect display language when fetching metadata

* refactor(tvdb): use seasons translation

* refactor(tvdb): limit while loop

* fix(tvdb): fix translation with '-'

* refactor(tvdb): remove logs

* style(tvdb): remove useless logs

* refactor(tvdb): simplify wanted translation condition

* refactor(languages): move AvailableLocale  from context to types
2025-09-08 20:20:21 +08:00
Ishan Jain
479be0daeb feat(notifications): make embedded posters optional (#1364)
* feat(notifications): make images optional

* fix(notifications): added en i18n config

* fix: prettify

* fix(notifications): added embedImage support for ntfy

* fix(frontend): update embedImage on form state change and submission

* fix(locale): updated locale for embedImage

* fix: renamed embedImage to embedPoster
2025-09-08 14:11:31 +02:00
THOMAS B
6245dae3b3 fix(tvdb): return specials seasons (#1894) 2025-09-08 10:49:26 +02:00
Gauthier
d82c6f6222 fix(settings): correct port saving of proxy settings (#1890)
The port of the proxy settings was saved as a string instead of a number, causing the API to throw
an error and making it impossible to save the network settings.
2025-09-04 14:45:42 +02:00
0xsysr3ll
13fe4c890b feat(issue): add issue description preview (#1881)
* feat(issue): add issue description preview

This PR adds a description preview to the issues list page, allowing users to quickly view issue details without navigating to individual issue pages.

Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me>

* fix(issue): remove unnecessary user join

Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me>

---------

Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me>
2025-09-04 10:24:08 +02:00
THOMAS B
22b2824441 feat: add tvdb indexer (#899)
* feat(tvdb): get tv seasons/episodes with tvdb

* fix: fix rate limiter index tvdb indexer

* fix(usersettings): remove unused column tvdbtoken

* refactor(tvdb): replace tvdb api by skyhook

* fix: error during get episodes

* fix: error if tmdb poster is null

* refactor: clean tvdb indexer code

* fix: wrong language with tmdb indexer

* style: replace avalaible to available

* style: tvdb.login to tvdb.test

* fix(test): fix  discover test

* fix(test): wrong url tv-details

* test(tvdb): add tvdb tests

* style(tvdb): rename pokemon to correct tv show

* refactor(indexer): remove unused getSeasonIdentifier method

* refactor(settings): replace tvdb object to boolean type

* refactor(tmdb): reduce still path condition

* test(tvdb): change 'use' to 'tvdb' condition check

* fix(tmdb): fix build

fix build after rebase

* fix(build): revert package.json

* fix(tvdb): ensure that seasons contain data

* refactor(swagger): fix /tvdb/test response

* fix(scanner): add tvdb indexer for scanner

* refactor(tvdb): remove skyhook api

* refactor(tvdb): use tvdb api

* fix(tvdb): rename tvdb to medatada

* refactor(medata): add tvdb settings

* refactor(metadata): rewrite metadata settings

* refactor(metadata): refactor metadata routes

* refactor(metadata): remove french comments

* refactor(metadata): refactor tvdb api calls

* style(prettier): run prettier

* fix(scanner): fix jellyfin scanner with tvdb provider

* fix(scanner): fix plex scanner tvdb provider

* style(provider): change provider name in info section

* style(provider): full provider name in select

* style(provider): remove french comment

* fix(tests): fix all cypress tests

* refactor(tvdb): fix apikey

* refactor(tmdb): apply prettier

* refactor(tvdb): remove logger info

* feat(metadata): replace fetch with axios for API calls

* feat(provider): replace indexer by provider

* fix(tests): fix cypress test

* chore: add project-wide apikey for tvdb

* chore: add correct application-wide key

* fix(test): fix test with default provider tmdb anime

* style(cypress): fix anime name variable

* chore(i18n): remove french translation + apply i18n:extract

* style(wording): standardize naming to "Metadata Provider" in UI text

* docs(comments): translate from French to English

* refactor(tvdb): remove unnecessary try/catch block

* feat(i18n): add missing translations

* fix(scanner): correct metadata provider ID from Tmdb to Tvdb

* style(settings): clarify navigation label from "Metadata" to "Metadata Providers"

* style(logs): update error log label from "Metadata" to "MetadataProvider"

* refactor(tvdb): replace indexer by metadata providers

* refactor(settings): remove metadata providers logo

* fix(config): restore missing config/db/.gitkeep file

---------

Co-authored-by: TOomaAh <ubuntu@PC>
Co-authored-by: fallenbagel <98979876+Fallenbagel@users.noreply.github.com>
2025-09-02 22:40:47 +02:00
Gauthier
368ecf8771 fix(dnscaching): display stats for DNS caching (#1858)
* fix(dnscaching): display stats for DNS caching

* fix: add missing translation
2025-08-20 17:32:59 +08:00
Georgy
d3fd5028dc feat: add IMDb rating votes count in tooltip (#1696)
* feat: add IMDb rating votes count in tooltip

* feat: add IMDb rating votes count in tooltip

* feat: add IMDb rating votes count in tooltip
2025-08-19 22:26:42 +02:00
Gauvain
c0fd81a5f0 fix: remove console warning (#1836)
* fix: remove a console warning

* fix: Adds id attribute to select element for accessibility

Fixes label association by adding missing id attribute to the select dropdown, ensuring proper accessibility compliance and screen reader functionality.
2025-08-19 21:49:06 +02:00
0xsysr3ll
af7ceaf7a2 feat(requests): add user's avatar next to Requested/Last Modified by icon (#1750)
* feat(requests): add user's avatar in front of Requested/Last Modified by

* refactor(requests): wrap both the avatar and the username in Link

* fix(requests): remove unnecessary margin between avatar and username
2025-08-20 03:43:51 +08:00
fallenbagel
b4adfd2ffa feat: dns caching manager (#1294)
* feat(dns): implement dns caching

* feat: simple implementation of dnscaching

* feat: dynamic ttl which is revalidated while using stale dns cache

This is done as tmdb ttl is very less like 40 seconds so to make sure
any issues wont be caused due to cached dns (previously we were caching
for 5 minutes no matter what ttl)

* feat(dns): improve DNS cache with multi-strategy fallback system

- multiple DNS resolution strategie
- graceful fallbacks between IPv6 and IPv4 addresses
- network error reporting in fetch fix
- compatibility with cypress testing (I HOPE)

* fix: typos

* feat: dns cache stats in jobs & cache page (and cleanup)

* feat(networksettings): cache dns off by default

* feat: make dnsCache optional and enable-able through network settings

* chore(i18n): extract translation keys

* test(cypress): fix cypress testing

* feat(dnscache): dns cache entries are now flushable

* style(cypress): run prettier

* chore(cypresssettings): git ignore cypress json settings

* chore: ignore cypress/config/settings.json

* fix(dnscache): use entry specific hits and misses not global

* refactor: clean up console logs

* fix(dnscache): fix miss counter

* feat(dnscache): global stats

* chore(i18n): extract translation keys

* refactor: use date-fns for formatting age and remove useless code

* refactor: remove cypress testing options in dnsCacheManager

* refactor: remove console logs

* refactor: removed useless condition when its always truthy

* fix: remove FetchAPI-related code

* fix: remove old ipv4first setting

* refactor: use our own dns-caching package instead

* fix: correct dns-caching module configuration

* fix: correct dns-caching module configuration

* fix: remove useless lru-cache dependency

* fix: update dns-caching to v0.2.0

* fix: add env variable for min/max ttl & update dns-caching

* fix: update dns-caching package

* fix: add force min/max TTL in network settings

* docs: add docs for dns caching

---------

Co-authored-by: Gauthier <mail@gauthierth.fr>
2025-08-20 03:02:21 +08:00
0xsysr3ll
5c1583cf56 fix(UserProfile): handle optional chaining for recentlyWatched data (#1852)
This PR fixes a client-side TypeError in the "Recently Watched" section of user profiles. The issue occurred when recentlyWatched was undefined. The fix adds optional chaining (?.) to prevent the app from crashing.

Signed-off-by: 0xsysr3ll <0xsysr3ll@pm.me>
2025-08-19 19:00:09 +02:00
Gauthier
66d4cd63bb docs(notifications): add more documentation for notifications (#1856)
This PR adds more documentation methods for notifications. Most of it is taken from the Overseerr
documentation.
2025-08-20 00:46:04 +08:00
Ludovic Ortega
e8ec3473da chore(helm): bump jellyseerr to 2.7.3 (#1848)
Signed-off-by: Ludovic Ortega <ludovic.ortega@adminafk.fr>
2025-08-14 23:24:09 +02:00
0xsysr3ll
17d4f13afe fix(api): update Plex Watchlist URL (#1847) 2025-08-15 03:57:30 +08:00
0xsysr3ll
3292f11308 fix(MediaRequestSubscriber): use event manager to get fresh media state for MEDIA_AVAILABLE notifications (#1825)
* fix(MediaRequestSubscriber): use event manager to get fresh media state for MEDIA_AVAILABLE notifications

* refactor(MediaRequestSubscriber): streamline media availability notifications
2025-08-10 21:33:06 +02:00
0xsysr3ll
c86ee0ddb1 fix(api): make username field nullable in UserSettings API schema (#1835) 2025-08-06 06:22:21 +08:00
0xsysr3ll
e02ee24f70 fix(media): update delete media file logic to include is4k parameter (#1832)
* fix(media): update delete media file logic to include is4k parameter

* fix(media): revert to MANAGE_REQUESTS permission
2025-08-05 11:42:11 +02:00
0xsysr3ll
ca1686425b fix(blacklist): handle invalid keywords gracefully (#1815)
* fix(blacklist): handle invalid keywords gracefully

* fix(blacklist): only remove keywords on 404 errors

* fix(blacklist): remove non-null assertion and add proper type annotation

* refactor(blacklist): return null instead of 404 for missing keywords

* fix(blacklist): add type annotation for validKeywords

* fix(selector): update type annotation for validKeywords
2025-08-01 11:03:22 +02:00
0xsysr3ll
e52c63164f fix(api): add missing user settings' api docs (#1820)
This PR adds new fields to the UserSettings schema, including username, email, discordId, and various quota limits for movies and TV shows.

It also updates API paths to reference the new UserSettings schema.
2025-07-30 23:44:49 +02:00
Gauthier
e98f31e66c fix(proxy): initialize image proxies after the proxy is set up (#1794)
The ImageProxy for TMDB and TheTVDB were initialized before the proxy settings were set up, so they
were ignoring the proxy settings.

fix #1787
2025-07-24 10:33:53 +02:00
Gauthier
75a7279ea2 fix(proxy): modify the registration of the axios interceptors (#1791)
The previous way of adding Axios interceptors added a new interceptor each time, causing lags after
a while because of all the duplicate interceptors added.

fix #1787
2025-07-20 11:33:16 +02:00
Ludovic Ortega
d53ffca5db chore(helm): bump jellyseerr to 2.7.1 (#1785)
Signed-off-by: Ludovic Ortega <ludovic.ortega@adminafk.fr>
2025-07-15 22:06:29 +02:00
120 changed files with 5800 additions and 476 deletions

View File

@@ -4,6 +4,7 @@ dist/
config/
CHANGELOG.md
pnpm-lock.yaml
cypress/config/settings.cypress.json
# assets
src/assets/

View File

@@ -21,5 +21,11 @@ module.exports = {
rangeEnd: 0, // default: Infinity
},
},
{
files: 'cypress/config/settings.cypress.json',
options: {
rangeEnd: 0,
},
},
],
};

View File

@@ -3,8 +3,8 @@ kubeVersion: ">=1.23.0-0"
name: jellyseerr-chart
description: Jellyseerr helm chart for Kubernetes
type: application
version: 2.6.0
appVersion: "2.7.0"
version: 2.6.2
appVersion: "2.7.3"
maintainers:
- name: Jellyseerr
url: https://github.com/Fallenbagel/jellyseerr

View File

@@ -1,6 +1,6 @@
# jellyseerr-chart
![Version: 2.6.0](https://img.shields.io/badge/Version-2.6.0-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 2.7.0](https://img.shields.io/badge/AppVersion-2.7.0-informational?style=flat-square)
![Version: 2.6.2](https://img.shields.io/badge/Version-2.6.2-informational?style=flat-square) ![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square) ![AppVersion: 2.7.3](https://img.shields.io/badge/AppVersion-2.7.3-informational?style=flat-square)
Jellyseerr helm chart for Kubernetes

View File

@@ -6,7 +6,6 @@
"apiKey": "testkey",
"applicationTitle": "Jellyseerr",
"applicationUrl": "",
"csrfProtection": false,
"cacheImages": false,
"defaultPermissions": 32,
"defaultQuotas": {
@@ -180,5 +179,26 @@
"image-cache-cleanup": {
"schedule": "0 0 5 * * *"
}
},
"network": {
"csrfProtection": false,
"trustProxy": false,
"forceIpv4First": false,
"dnsServers": "",
"proxy": {
"enabled": false,
"hostname": "",
"port": 8080,
"useSsl": false,
"user": "",
"password": "",
"bypassFilter": "",
"bypassLocalAddresses": true
},
"dnsCache": {
"enabled": false,
"forceMinTtl": 0,
"forceMaxTtl": -1
}
}
}

View File

@@ -0,0 +1,148 @@
describe('TVDB Integration', () => {
// Constants for routes and selectors
const ROUTES = {
home: '/',
metadataSettings: '/settings/metadata',
tomorrowIsOursTvShow: '/tv/72879',
monsterTvShow: '/tv/225634',
dragonnBallZKaiAnime: '/tv/61709',
};
const SELECTORS = {
sidebarToggle: '[data-testid=sidebar-toggle]',
sidebarSettingsMobile: '[data-testid=sidebar-menu-settings-mobile]',
settingsNavDesktop: 'nav[data-testid="settings-nav-desktop"]',
metadataTestButton: 'button[type="button"]:contains("Test")',
metadataSaveButton: '[data-testid="metadata-save-button"]',
tmdbStatus: '[data-testid="tmdb-status"]',
tvdbStatus: '[data-testid="tvdb-status"]',
tvMetadataProviderSelector: '[data-testid="tv-metadata-provider-selector"]',
animeMetadataProviderSelector:
'[data-testid="anime-metadata-provider-selector"]',
seasonSelector: '[data-testid="season-selector"]',
season1: 'Season 1',
season2: 'Season 2',
season3: 'Season 3',
episodeList: '[data-testid="episode-list"]',
episode9: '9 - Hang Men',
};
// Reusable commands
const navigateToMetadataSettings = () => {
cy.visit(ROUTES.home);
cy.get(SELECTORS.sidebarToggle).click();
cy.get(SELECTORS.sidebarSettingsMobile).click();
cy.get(
`${SELECTORS.settingsNavDesktop} a[href="${ROUTES.metadataSettings}"]`
).click();
};
const testAndVerifyMetadataConnection = () => {
cy.intercept('POST', '/api/v1/settings/metadatas/test').as(
'testConnection'
);
cy.get(SELECTORS.metadataTestButton).click();
return cy.wait('@testConnection');
};
const saveMetadataSettings = (customBody = null) => {
if (customBody) {
cy.intercept('PUT', '/api/v1/settings/metadatas', (req) => {
req.body = customBody;
}).as('saveMetadata');
} else {
// Else just intercept without modifying body
cy.intercept('PUT', '/api/v1/settings/metadatas').as('saveMetadata');
}
cy.get(SELECTORS.metadataSaveButton).click();
return cy.wait('@saveMetadata');
};
beforeEach(() => {
// Perform login
cy.login(Cypress.env('ADMIN_EMAIL'), Cypress.env('ADMIN_PASSWORD'));
// Navigate to Metadata settings
navigateToMetadataSettings();
// Verify we're on the correct settings page
cy.contains('h3', 'Metadata Providers').should('be.visible');
// Configure TVDB as TV provider and test connection
cy.get(SELECTORS.tvMetadataProviderSelector).click();
// get id react-select-4-option-1
cy.get('[class*="react-select__option"]').contains('TheTVDB').click();
// Test the connection
testAndVerifyMetadataConnection().then(({ response }) => {
expect(response.statusCode).to.equal(200);
// Check TVDB connection status
cy.get(SELECTORS.tvdbStatus).should('contain', 'Operational');
});
// Save settings
saveMetadataSettings({
anime: 'tvdb',
tv: 'tvdb',
}).then(({ response }) => {
expect(response.statusCode).to.equal(200);
expect(response.body.tv).to.equal('tvdb');
});
});
it('should display "Tomorrow is Ours" show information with multiple seasons from TVDB', () => {
// Navigate to the TV show
cy.visit(ROUTES.tomorrowIsOursTvShow);
// Verify that multiple seasons are displayed (TMDB has only 1 season, TVDB has multiple)
// cy.get(SELECTORS.seasonSelector).should('exist');
cy.intercept('/api/v1/tv/225634/season/1').as('season1');
// Select Season 2 and verify it loads
cy.contains(SELECTORS.season2)
.should('be.visible')
.scrollIntoView()
.click();
// Verify that episodes are displayed for Season 2
cy.contains('260 - Episode 506').should('be.visible');
});
it('Should display "Monster" show information correctly when not existing on TVDB', () => {
// Navigate to the TV show
cy.visit(ROUTES.monsterTvShow);
// Intercept season 1 request
cy.intercept('/api/v1/tv/225634/season/1').as('season1');
// Select Season 1
cy.contains(SELECTORS.season1)
.should('be.visible')
.scrollIntoView()
.click();
// Wait for the season data to load
cy.wait('@season1');
// Verify specific episode exists
cy.contains(SELECTORS.episode9).should('be.visible');
});
it('should display "Dragon Ball Z Kai" show information with multiple only 2 seasons from TVDB', () => {
// Navigate to the TV show
cy.visit(ROUTES.dragonnBallZKaiAnime);
// Intercept season 1 request
cy.intercept('/api/v1/tv/61709/season/1').as('season1');
// Select Season 2 and verify it visible
cy.contains(SELECTORS.season2)
.should('be.visible')
.scrollIntoView()
.click();
// select season 3 and verify it not visible
cy.contains(SELECTORS.season3).should('not.exist');
});
});

View File

@@ -0,0 +1,21 @@
---
title: Gotify
description: Configure Gotify notifications.
sidebar_position: 5
---
# Gotify
## Configuration
### Server URL
Set this to the URL of your Gotify server.
### Application Token
Add an application to your Gotify server, and set this field to the generated application token.
:::info
Please refer to the [Gotify API documentation](https://gotify.net/docs) for more details on configuring these notifications.
:::

View File

@@ -0,0 +1,29 @@
---
title: ntfy.sh
description: Configure ntfy.sh notifications.
sidebar_position: 6
---
# ntfy.sh
## Configuration
### Server Root URL
Set this to the URL of your ntfy.sh server.
### Topic
Set this to the topic you want to send notifications to.
### Username + Password authentication (optional)
Set this to the username and password for your ntfy.sh server.
### Token authentication (optional)
Set this to the token for your ntfy.sh server.
:::info
Please refer to the [ntfy.sh API documentation](https://docs.ntfy.sh/) for more details on configuring these notifications.
:::

View File

@@ -0,0 +1,23 @@
---
title: Pushbullet
description: Configure Pushbullet notifications.
sidebar_position: 7
---
# Pushbullet
:::info
Users can optionally configure personal notifications in their user settings.
User notifications are separate from system notifications, and the available notification types are dependent on user permissions.
:::
## Configuration
### Access Token
[Create an access token](https://www.pushbullet.com/#settings) and set it here to grant Jellyseerr access to the Pushbullet API.
### Channel Tag (optional)
Optionally, [create a channel](https://www.pushbullet.com/my-channel) to allow other users to follow the notification feed using the specified channel tag.

View File

@@ -0,0 +1,27 @@
---
title: Pushover
description: Configure Pushover notifications.
sidebar_position: 8
---
# Pushover
:::info
Users can optionally configure personal notifications in their user settings.
User notifications are separate from system notifications, and the available notification types are dependent on user permissions.
:::
## Configuration
### Application/API Token
[Register an application](https://pushover.net/apps/build) and enter the API token in this field. (You can use one of the [official icons in our GitHub repository](https://github.com/fallenbagel/jellyseerr/tree/develop/public) when configuring the application.)
For more details on registering applications or the API token, please see the [Pushover API documentation](https://pushover.net/api#registration).
### User Key
Set this to the user key for your Pushover account. Alternatively, you can set this to a group key to deliver notifications to multiple users.
For more details, please see the [Pushover API documentation](https://pushover.net/api#identifiers).

View File

@@ -0,0 +1,17 @@
---
title: Slack
description: Configure Slack notifications.
sidebar_position: 9
---
# Slack
## Configuration
### Webhook URL
Simply [create a webhook](https://my.slack.com/services/new/incoming-webhook/) and enter the URL in this field.
:::info
Please refer to the [Slack API documentation](https://api.slack.com/messaging/webhooks) for more details on configuring these notifications.
:::

View File

@@ -0,0 +1,39 @@
---
title: Telegram
description: Configure Telegram notifications.
sidebar_position: 10
---
# Telegram
:::info
Users can optionally configure personal notifications in their user settings.
User notifications are separate from system notifications, and the available notification types are dependent on user permissions.
:::
## Configuration
:::info
In order to configure Telegram notifications, you first need to [create a bot](https://telegram.me/BotFather).
Bots **cannot** initiate conversations with users, so users must have your bot added to a conversation in order to receive notifications.
:::
### Bot Username (optional)
If this value is configured, users will be able to click a link to start a chat with your bot and configure their own personal notifications.
The bot username should end with `_bot`, and the `@` prefix should be omitted.
### Bot Authentication Token
At the end of the bot creation process, [@BotFather](https://telegram.me/botfather) will provide an authentication token.
### Chat ID
To obtain your chat ID, simply create a new group chat, add [@get_id_bot](https://telegram.me/get_id_bot), and issue the `/my_id` command.
### Send Silently (optional)
Optionally, notifications can be sent silently. Silent notifications send messages without notification sounds.

View File

@@ -0,0 +1,138 @@
---
title: Webhook
description: Configure webhook notifications.
sidebar_position: 4
---
# Webhook
The webhook notification agent enables you to send a custom JSON payload to any endpoint for specific notification events.
## Configuration
### Webhook URL
The URL you would like to post notifications to. Your JSON will be sent as the body of the request.
### Authorization Header (optional)
:::info
This is typically not needed. Please refer to your webhook provider's documentation for details.
:::
This value will be sent as an `Authorization` HTTP header.
### JSON Payload
Customize the JSON payload to suit your needs. Jellyseerr provides several [template variables](#template-variables) for use in the payload, which will be replaced with the relevant data when the notifications are triggered.
## Template Variables
### General
| Variable | Value |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `{{notification_type}}` | The type of notification (e.g. `MEDIA_PENDING` or `ISSUE_COMMENT`) |
| `{{event}}` | A friendly description of the notification event |
| `{{subject}}` | The notification subject (typically the media title) |
| `{{message}}` | The notification message body (the media overview/synopsis for request notifications; the issue description for issue notificatons) |
| `{{image}}` | The notification image (typically the media poster) |
### Notify User
These variables are for the target recipient of the notification.
| Variable | Value |
| ---------------------------------------- | ------------------------------------------------------------- |
| `{{notifyuser_username}}` | The target notification recipient's username |
| `{{notifyuser_email}}` | The target notification recipient's email address |
| `{{notifyuser_avatar}}` | The target notification recipient's avatar URL |
| `{{notifyuser_settings_discordId}}` | The target notification recipient's Discord ID (if set) |
| `{{notifyuser_settings_telegramChatId}}` | The target notification recipient's Telegram Chat ID (if set) |
:::info
The `notifyuser` variables are not defined for the following request notification types, as they are intended for application administrators rather than end users:
- Request Pending Approval
- Request Automatically Approved
- Request Processing Failed
On the other hand, the `notifyuser` variables _will_ be replaced with the requesting user's information for the below notification types:
- Request Approved
- Request Declined
- Request Available
If you would like to use the requesting user's information in your webhook, please instead include the relevant variables from the [Request](#request) section below.
:::
### Special
The following variables must be used as a key in the JSON payload (e.g., `"{{extra}}": []`).
| Variable | Value |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `{{media}}` | The relevant media object |
| `{{request}}` | The relevant request object |
| `{{issue}}` | The relevant issue object |
| `{{comment}}` | The relevant issue comment object |
| `{{extra}}` | The "extra" array of additional data for certain notifications (e.g., season/episode numbers for series-related notifications) |
#### Media
The `{{media}}` will be `null` if there is no relevant media object for the notification.
These following special variables are only included in media-related notifications, such as requests.
| Variable | Value |
| -------------------- | -------------------------------------------------------------------------------------------------------------- |
| `{{media_type}}` | The media type (`movie` or `tv`) |
| `{{media_tmdbid}}` | The media's TMDB ID |
| `{{media_tvdbid}}` | The media's TheTVDB ID |
| `{{media_status}}` | The media's availability status (`UNKNOWN`, `PENDING`, `PROCESSING`, `PARTIALLY_AVAILABLE`, or `AVAILABLE`) |
| `{{media_status4k}}` | The media's 4K availability status (`UNKNOWN`, `PENDING`, `PROCESSING`, `PARTIALLY_AVAILABLE`, or `AVAILABLE`) |
#### Request
The `{{request}}` will be `null` if there is no relevant media object for the notification.
The following special variables are only included in request-related notifications.
| Variable | Value |
| ----------------------------------------- | ----------------------------------------------- |
| `{{request_id}}` | The request ID |
| `{{requestedBy_username}}` | The requesting user's username |
| `{{requestedBy_email}}` | The requesting user's email address |
| `{{requestedBy_avatar}}` | The requesting user's avatar URL |
| `{{requestedBy_settings_discordId}}` | The requesting user's Discord ID (if set) |
| `{{requestedBy_settings_telegramChatId}}` | The requesting user's Telegram Chat ID (if set) |
#### Issue
The `{{issue}}` will be `null` if there is no relevant media object for the notification.
The following special variables are only included in issue-related notifications.
| Variable | Value |
| ---------------------------------------- | ----------------------------------------------- |
| `{{issue_id}}` | The issue ID |
| `{{reportedBy_username}}` | The requesting user's username |
| `{{reportedBy_email}}` | The requesting user's email address |
| `{{reportedBy_avatar}}` | The requesting user's avatar URL |
| `{{reportedBy_settings_discordId}}` | The requesting user's Discord ID (if set) |
| `{{reportedBy_settings_telegramChatId}}` | The requesting user's Telegram Chat ID (if set) |
#### Comment
The `{{comment}}` will be `null` if there is no relevant media object for the notification.
The following special variables are only included in issue comment-related notifications.
| Variable | Value |
| ----------------------------------------- | ----------------------------------------------- |
| `{{comment_message}}` | The comment message |
| `{{commentedBy_username}}` | The commenting user's username |
| `{{commentedBy_email}}` | The commenting user's email address |
| `{{commentedBy_avatar}}` | The commenting user's avatar URL |
| `{{commentedBy_settings_discordId}}` | The commenting user's Discord ID (if set) |
| `{{commentedBy_settings_telegramChatId}}` | The commenting user's Telegram Chat ID (if set) |

View File

@@ -0,0 +1,16 @@
---
title: DNS Caching
description: Configure DNS caching settings.
sidebar_position: 7
---
# DNS Caching
Jellyseerr uses DNS caching to improve performance and reduce the number of DNS lookups required for external API calls. This can help speed up response times and reduce load on DNS servers, when something like a Pi-hole is used as a DNS resolver.
## Configuration
You can enable the DNS caching settings in the Network tab of the Jellyseerr settings. The default values follow the standard DNS caching behavior.
- **Force Minimum TTL**: Set a minimum time-to-live (TTL) in seconds for DNS cache entries. This ensures that frequently accessed DNS records are cached for a longer period, reducing the need for repeated lookups. Default is 0.
- **Force Maximum TTL**: Set a maximum time-to-live (TTL) in seconds for DNS cache entries. This prevents infrequently accessed DNS records from being cached indefinitely, allowing for more up-to-date information to be retrieved. Default is -1 (unlimited).

View File

@@ -1,6 +1,7 @@
---
title: Jobs & Cache
description: Configure jobs and cache settings.
sidebar_position: 6
---
# Jobs & Cache

Binary file not shown.

After

Width:  |  Height:  |  Size: 375 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 296 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 306 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 306 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 285 KiB

View File

@@ -22,6 +22,14 @@ When disabled, users will only be able to sign in using their email address. Use
This setting is **enabled** by default.
## Enable OpenID Connect Sign-In
When enabled, users will be able to sign in to Jellyseerr using their OpenID Connect credentials, provided they have linked their OpenID Connect accounts. Once enabled, the [OpenID Connect settings](./oidc.md) can be accessed using the settings cog to the right of this option, and OpenID Connect providers can be configured.
When disabled, users will only be able to sign in using their Jellyseerr username or email address. Users without a password set will not be able to sign in to Jellyseerr.
This setting is **disabled** by default.
## Enable New Jellyfin/Emby/Plex Sign-In
When enabled, users with access to your media server will be able to sign in to Jellyseerr even if they have not yet been imported. Users will be automatically assigned the permissions configured in the [Default Permissions](#default-permissions) setting upon first sign-in.

View File

@@ -0,0 +1,82 @@
---
title: OpenID Connect
description: Configure OpenID Connect settings.
sidebar_position: 2.5
---
# OpenID Connect
Jellyseerr supports OpenID Connect (OIDC) for authentication and authorization. To begin setting up OpenID Connect, follow these steps:
1. First, enable OpenID Connect [on the User settings page](./index.md#enable-openid-connect-sign-in).
2. Once enabled, access OpenID Connect settings using the cog icon to the right.
3. Add a new provider by clicking the "Add Provider" button.
4. Configure the provider with the options described below.
5. Link your OpenID Connect account to your Jellyseerr account using the "Link Account" button on the Linked Accounts page in your user's settings.
6. Finally, you should be able to log in using your OpenID Connect account.
## Configuration Options
### Provider Name
Name of the provider which appears on the login screen.
Configuring this setting will automatically determine the [provider slug](#provider-slug), unless it is manually specified.
### Logo
The logo to display for the provider. Should be a URL or base64 encoded image.
:::tip
The search icon at the right of the logo field opens the [selfh.st/icons](https://selfh.st/icons) database. These icons include popular self-hosted OpenID Connect providers.
:::
### Issuer URL
The base URL of the identity provider's OpenID Connect endpoint
### Client ID
The Client ID assigned to Jellyseerr
### Client Secret
The Client Secret assigned to Jellyseerr
### Provider Slug
Unique identifier for the provider
### Scopes
Space-separated list of scopes to request from the provider
### Required Claims
Space-separated list of boolean claims that are required to log in
### Allow New Users
Create accounts for new users logging in with this provider
## Provider Guides
### Keycloak
To set up Keycloak, follow these steps:
1. First, create a new client in Keycloak.
![Keycloak Step 1](./assets/oidc_keycloak_1.png)
1. Set the client ID to `jellyseerr`, and set the name to "Jellyseerr" (or whatever you prefer).
![Keycloak Step 2](./assets/oidc_keycloak_2.png)
1. Next, be sure to enable "Client authentication" in the capabilities section. The remaining defaults should be fine.
![Keycloak Step 3](./assets/oidc_keycloak_3.png)
1. Finally, set the root url to your Jellyseerr instance's URL, and add the login page as a valid redirect URL.
![Keycloak Step 4](./assets/oidc_keycloak_4.png)
1. With all that set up, you should be able to configure Jellyseerr to use Keycloak for authentication. Be sure to copy the client secret from the credentials page, as shown above. The issuer URL can be obtained from the "Realm Settings" page, by copying the link titled "OpenID Endpoint Configuration".
![Keycloak Step 5](./assets/oidc_keycloak_5.png)

View File

@@ -141,14 +141,83 @@ components:
UserSettings:
type: object
properties:
username:
type: string
nullable: true
example: 'Mr User'
email:
type: string
example: 'user@example.com'
discordId:
type: string
nullable: true
example: '123456789'
locale:
type: string
nullable: true
example: 'en'
discoverRegion:
type: string
originalLanguage:
type: string
nullable: true
example: 'US'
streamingRegion:
type: string
nullable: true
example: 'US'
originalLanguage:
type: string
nullable: true
example: 'en'
movieQuotaLimit:
type: number
nullable: true
description: 'Maximum number of movie requests allowed'
example: 10
movieQuotaDays:
type: number
nullable: true
description: 'Time period in days for movie quota'
example: 30
tvQuotaLimit:
type: number
nullable: true
description: 'Maximum number of TV requests allowed'
example: 5
tvQuotaDays:
type: number
nullable: true
description: 'Time period in days for TV quota'
example: 14
globalMovieQuotaDays:
type: number
nullable: true
description: 'Global movie quota days setting'
example: 30
globalMovieQuotaLimit:
type: number
nullable: true
description: 'Global movie quota limit setting'
example: 10
globalTvQuotaLimit:
type: number
nullable: true
description: 'Global TV quota limit setting'
example: 5
globalTvQuotaDays:
type: number
nullable: true
description: 'Global TV quota days setting'
example: 14
watchlistSyncMovies:
type: boolean
nullable: true
description: 'Enable watchlist sync for movies'
example: true
watchlistSyncTv:
type: boolean
nullable: true
description: 'Enable watchlist sync for TV'
example: false
MainSettings:
type: object
properties:
@@ -185,15 +254,92 @@ components:
enableSpecialEpisodes:
type: boolean
example: false
OidcProvider:
type: object
properties:
slug:
type: string
readOnly: true
name:
type: string
issuerUrl:
type: string
clientId:
type: string
clientSecret:
type: string
logo:
type: string
requiredClaims:
type: string
scopes:
type: string
newUserLogin:
type: boolean
required:
- slug
- name
- issuerUrl
- clientId
- clientSecret
OidcSettings:
type: object
properties:
providers:
type: array
items:
$ref: '#/components/schemas/OidcProvider'
NetworkSettings:
type: object
properties:
csrfProtection:
type: boolean
example: false
forceIpv4First:
type: boolean
example: false
trustProxy:
type: boolean
example: true
example: false
proxy:
type: object
properties:
enabled:
type: boolean
example: false
hostname:
type: string
example: ''
port:
type: number
example: 8080
useSsl:
type: boolean
example: false
user:
type: string
example: ''
password:
type: string
example: ''
bypassFilter:
type: string
example: ''
bypassLocalAddresses:
type: boolean
example: true
dnsCache:
type: object
properties:
enabled:
type: boolean
example: false
forceMinTtl:
type: number
example: 0
forceMaxTtl:
type: number
example: -1
PlexLibrary:
type: object
properties:
@@ -408,6 +554,20 @@ components:
serverID:
type: string
readOnly: true
MetadataSettings:
type: object
properties:
settings:
type: object
properties:
tv:
type: string
enum: [tvdb, tmdb]
example: 'tvdb'
anime:
type: string
enum: [tvdb, tmdb]
example: 'tvdb'
TautulliSettings:
type: object
properties:
@@ -2087,6 +2247,64 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/MainSettings'
/settings/oidc:
get:
summary: Get OpenID Connect settings
description: Retrieves all OpenID Connect settings in a JSON object.
tags:
- settings
responses:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/OidcSettings'
/settings/oidc/{provider}:
put:
summary: Update OpenID Connect provider
description: Updates an existing OpenID Connect provider with the provided values.
tags:
- settings
parameters:
- in: path
name: provider
required: true
schema:
type: string
description: Provider slug
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/OidcProvider'
responses:
'200':
description: 'Radarr instance updated'
content:
application/json:
schema:
$ref: '#/components/schemas/RadarrSettings'
delete:
summary: Delete OpenID Connect provider
description: Deletes an existing OpenID Connect provider based on the provider slug parameter.
tags:
- settings
parameters:
- in: path
name: provider
required: true
schema:
type: string
description: Provider slug
responses:
'200':
description: 'OpenID Connect provider deleted'
content:
application/json:
schema:
$ref: '#/components/schemas/OidcSettings'
/settings/network:
get:
summary: Get network settings
@@ -2457,6 +2675,67 @@ paths:
type: string
thumb:
type: string
/settings/metadatas:
get:
summary: Get Metadata settings
description: Retrieves current Metadata settings.
tags:
- settings
responses:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/MetadataSettings'
put:
summary: Update Metadata settings
description: Updates Metadata settings with the provided values.
tags:
- settings
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/MetadataSettings'
responses:
'200':
description: 'Values were successfully updated'
content:
application/json:
schema:
$ref: '#/components/schemas/MetadataSettings'
/settings/metadatas/test:
post:
summary: Test Provider configuration
description: Tests if the TVDB configuration is valid. Returns a list of available languages on success.
tags:
- settings
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
tmdb:
type: boolean
example: true
tvdb:
type: boolean
example: true
responses:
'200':
description: Succesfully connected to TVDB
content:
application/json:
schema:
type: object
properties:
message:
type: string
example: 'Successfully connected to TVDB'
/settings/tautulli:
get:
summary: Get Tautulli settings
@@ -2898,6 +3177,68 @@ paths:
imageCount:
type: number
example: 123
dnsCache:
type: object
properties:
stats:
type: object
properties:
size:
type: number
example: 1
maxSize:
type: number
example: 500
hits:
type: number
example: 19
misses:
type: number
example: 1
failures:
type: number
example: 0
ipv4Fallbacks:
type: number
example: 0
hitRate:
type: number
example: 0.95
entries:
type: array
additionalProperties:
type: object
properties:
addresses:
type: object
properties:
ipv4:
type: number
example: 1
ipv6:
type: number
example: 1
activeAddress:
type: string
example: 127.0.0.1
family:
type: number
example: 4
age:
type: number
example: 10
ttl:
type: number
example: 10
networkErrors:
type: number
example: 0
hits:
type: number
example: 1
misses:
type: number
example: 1
apiCaches:
type: array
items:
@@ -2937,6 +3278,21 @@ paths:
responses:
'204':
description: 'Flushed cache'
/settings/cache/dns/{dnsEntry}/flush:
post:
summary: Flush a specific DNS cache entry
description: Flushes a specific DNS cache entry
tags:
- settings
parameters:
- in: path
name: dnsEntry
required: true
schema:
type: string
responses:
'204':
description: 'Flushed dns cache'
/settings/logs:
get:
summary: Returns logs
@@ -3742,6 +4098,81 @@ paths:
required:
- email
- password
/auth/oidc/login/{slug}:
get:
security: []
summary: Redirect to the OpenID Connect provider
description: Constructs the redirect URL to the OpenID Connect provider, and redirects the user to it.
tags:
- auth
parameters:
- in: path
name: slug
required: true
schema:
type: string
example: 'authentik'
responses:
'200':
description: Authentication redirect url for the OpenID Connect provider
headers:
Set-Cookie:
schema:
type: string
example: 'oidc-state=123456789; HttpOnly; max-age=60000; Secure'
content:
application/json:
schema:
type: object
properties:
redirectUrl:
type: string
example: https://example.com/auth/oidc/callback?response_type=code&client_id=client_id&redirect_uri=https%3A%2F%2Fexample.com%2Fauth%2Foidc%2Fcallback&scope=openid%20email&state=state
/auth/oidc/callback/{slug}:
get:
security: []
summary: The callback endpoint for the OpenID Connect provider redirect
description: Takes the `code` and `state` parameters from the OpenID Connect provider, and exchanges them for a token.
x-allow-unknown-query-parameters: true
tags:
- auth
parameters:
- in: path
name: slug
required: true
schema:
type: string
example: 'authentik'
- in: query
name: code
required: true
schema:
type: string
example: '123456789'
- in: query
name: state
required: true
schema:
type: string
example: '123456789'
- in: cookie
name: oidc-state
required: true
schema:
type: string
example: '123456789'
responses:
'302':
description: A redirect to the home page if successful or back to the login page if not
headers:
Location:
schema:
type: string
example: /
Set-Cookie:
schema:
type: string
example: 'oidc-state=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT'
/auth/logout:
post:
summary: Sign out and clear session cookie
@@ -4469,11 +4900,7 @@ paths:
content:
application/json:
schema:
type: object
properties:
username:
type: string
example: 'Mr User'
$ref: '#/components/schemas/UserSettings'
post:
summary: Update general settings for a user
description: Updates and returns general settings for a specific user. Requires `MANAGE_USERS` permission if editing other users.
@@ -4490,22 +4917,14 @@ paths:
content:
application/json:
schema:
type: object
properties:
username:
type: string
nullable: true
$ref: '#/components/schemas/UserSettings'
responses:
'200':
description: Updated user general settings returned
content:
application/json:
schema:
type: object
properties:
username:
type: string
example: 'Mr User'
$ref: '#/components/schemas/UserSettings'
/user/{userId}/settings/password:
get:
summary: Get password page informatiom
@@ -4557,6 +4976,23 @@ paths:
responses:
'204':
description: User password updated
/user/{userId}/settings/linked-accounts:
get:
summary: Lists the user's linked OpenID Connect accounts
description: Lists the user's linked OpenID Connect accounts
tags:
- users
parameters:
- in: path
name: userId
required: true
schema:
type: number
responses:
'200':
description: List of linked accounts
'403':
description: Invalid credentials
/user/{userId}/settings/linked-accounts/plex:
post:
summary: Link the provided Plex account to the current user
@@ -4655,6 +5091,28 @@ paths:
description: Unlink request invalid
'404':
description: User does not exist
/user/{userId}/settings/linked-accounts/{acctId}:
delete:
summary: Remove a linked account for a user
description: Removes the linked account with the given ID for a specific user. Requires `MANAGE_USERS` permission if editing other users.
tags:
- users
parameters:
- in: path
name: userId
required: true
schema:
type: number
- in: path
name: acctId
required: true
schema:
type: number
responses:
'204':
description: Unlinking account succeeded
'404':
description: User or linked account does not exist
/user/{userId}/settings/notifications:
get:
summary: Get notification settings for a user
@@ -6296,7 +6754,7 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/TvDetails'
/tv/{tvId}/season/{seasonId}:
/tv/{tvId}/season/{seasonNumber}:
get:
summary: Get season details and episode list
description: Returns season details with a list of episodes in a JSON object.
@@ -6310,11 +6768,11 @@ paths:
type: number
example: 76479
- in: path
name: seasonId
name: seasonNumber
required: true
schema:
type: number
example: 1
example: 123456
- in: query
name: language
schema:
@@ -6599,9 +7057,16 @@ paths:
example: '1'
schema:
type: string
- in: query
name: is4k
description: Whether to remove from 4K service instance (true) or regular service instance (false)
required: false
example: false
schema:
type: boolean
responses:
'204':
description: Succesfully removed media item
description: Successfully removed media item
/media/{mediaId}/{status}:
post:
summary: Update media status
@@ -7268,11 +7733,22 @@ paths:
example: 1
responses:
'200':
description: Keyword returned
description: Keyword returned (null if not found)
content:
application/json:
schema:
nullable: true
$ref: '#/components/schemas/Keyword'
'500':
description: Internal server error
content:
application/json:
schema:
type: object
properties:
message:
type: string
example: 'Unable to retrieve keyword data.'
/watchproviders/regions:
get:
summary: Get watch provider regions

View File

@@ -57,6 +57,7 @@
"cronstrue": "2.23.0",
"date-fns": "2.29.3",
"dayjs": "1.11.7",
"dns-caching": "^0.2.5",
"email-templates": "12.0.1",
"email-validator": "2.0.4",
"express": "4.21.2",
@@ -67,6 +68,7 @@
"gravatar-url": "3.1.0",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.6",
"jwt-decode": "^4.0.0",
"lodash": "4.17.21",
"mime": "3",
"next": "^14.2.25",

223
pnpm-lock.yaml generated
View File

@@ -83,6 +83,9 @@ importers:
dayjs:
specifier: 1.11.7
version: 1.11.7
dns-caching:
specifier: ^0.2.5
version: 0.2.5
email-templates:
specifier: 12.0.1
version: 12.0.1(@babel/core@7.24.7)(encoding@0.1.13)(handlebars@4.7.8)(mustache@4.2.0)(pug@3.0.3)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(underscore@1.13.7)
@@ -113,6 +116,9 @@ importers:
https-proxy-agent:
specifier: ^7.0.6
version: 7.0.6
jwt-decode:
specifier: ^4.0.0
version: 4.0.0
lodash:
specifier: 4.17.21
version: 4.17.21
@@ -688,8 +694,8 @@ packages:
resolution: {integrity: sha512-NlmJJtvcw72yRJRcnCmGvSi+3jDEg8qFu3z0AFoymmzLx5ERVWyzd9kVXr7Th9/8yIJi2Zc6av4Tqz3wFs8QWg==}
engines: {node: '>=6.9.0'}
'@babel/helpers@7.27.6':
resolution: {integrity: sha512-muE8Tt8M22638HU31A3CgfSUciwz1fhATfoVai05aPXGor//CdWDCbnlY1yvBPo07njuVOCNGCSp/GTt12lIug==}
'@babel/helpers@7.28.2':
resolution: {integrity: sha512-/V9771t+EgXz62aCcyofnQhGM8DQACbRhvzKFsXKC9QM+5MadF8ZmIm0crDMaz3+o0h0zXfJnd4EhbYbxsrcFw==}
engines: {node: '>=6.9.0'}
'@babel/highlight@7.24.7':
@@ -1455,8 +1461,8 @@ packages:
resolution: {integrity: sha512-FDSOghenHTiToteC/QRlv2q3DhPZ/oOXTBoirfWNx1Cx3TMVcGWQtMMmQcSvb/JjpNeGzx8Pq/b4fKEJuWm1sw==}
engines: {node: '>=6.9.0'}
'@babel/runtime@7.27.6':
resolution: {integrity: sha512-vbavdySgbTTrmFE+EsiqUTzlOr5bzlnJtUv9PynGCAKvfQqjIXbvFdumPM/GxMDfyuGMJaJAU6TO4zc1Jf1i8Q==}
'@babel/runtime@7.28.2':
resolution: {integrity: sha512-KHp2IflsnGywDjBWDkR9iEqiWSpc8GIi0lgTT3mOElT0PP1tG26P4tmFI2YvAdzgq9RGyoHZQEIEdZy6Ec5xCA==}
engines: {node: '>=6.9.0'}
'@babel/template@7.24.7':
@@ -1483,8 +1489,8 @@ packages:
resolution: {integrity: sha512-Y3IR1cRnOxOCDvMmNiym7XpXQ93iGDDPHx+Zj+NM+rg0fBaShfQLkg+hKPaZCEvg5N/LeCo4+Rj/i3FuJsIQaw==}
engines: {node: '>=6.9.0'}
'@babel/types@7.28.1':
resolution: {integrity: sha512-x0LvFTekgSX+83TI28Y9wYPUfzrnl2aT5+5QLnO6v7mSJYtEEevuDRN0F0uSHRk1G1IWZC43o00Y0xDDrpBGPQ==}
'@babel/types@7.28.2':
resolution: {integrity: sha512-ruv7Ae4J5dUYULmeXw1gmb7rYRz57OWCPM57pHojnLq/3Z1CK2lNSLTCVjxVk1F/TZHwOZZrOWi0ur95BbLxNQ==}
engines: {node: '>=6.9.0'}
'@codedependant/semantic-release-docker@5.1.0':
@@ -1975,8 +1981,8 @@ packages:
resolution: {integrity: sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==}
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
'@jridgewell/gen-mapping@0.3.12':
resolution: {integrity: sha512-OuLGC46TjB5BbN1dH8JULVVZY4WTdkF7tV9Ys6wLL1rubZnCMstOhNHueU5bLCrnRuDhKPDM4g6sw4Bel5Gzqg==}
'@jridgewell/gen-mapping@0.3.13':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
'@jridgewell/gen-mapping@0.3.5':
resolution: {integrity: sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==}
@@ -1990,20 +1996,20 @@ packages:
resolution: {integrity: sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==}
engines: {node: '>=6.0.0'}
'@jridgewell/source-map@0.3.10':
resolution: {integrity: sha512-0pPkgz9dY+bijgistcTTJ5mR+ocqRXLuhXHYdzoMmmoJ2C9S46RCm2GMUbatPEUK9Yjy26IrAy8D/M00lLkv+Q==}
'@jridgewell/source-map@0.3.11':
resolution: {integrity: sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==}
'@jridgewell/sourcemap-codec@1.4.15':
resolution: {integrity: sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==}
'@jridgewell/sourcemap-codec@1.5.4':
resolution: {integrity: sha512-VT2+G1VQs/9oz078bLrYbecdZKs912zQlkelYpuf+SXF+QvZDYJlbx/LSx+meSAwdDFnF8FVXW92AVjjkVmgFw==}
'@jridgewell/sourcemap-codec@1.5.5':
resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}
'@jridgewell/trace-mapping@0.3.25':
resolution: {integrity: sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==}
'@jridgewell/trace-mapping@0.3.29':
resolution: {integrity: sha512-uw6guiW/gcAGPDhLmd77/6lW8QLeiV5RUTsAX46Db6oLhGaVj4lhnPwb184s1bkc8kdVg/+h988dro8GRDpmYQ==}
'@jridgewell/trace-mapping@0.3.30':
resolution: {integrity: sha512-GQ7Nw5G2lTu/BtHTKfXhKHok2WGetd4XYcVKGx00SjAk8GMwgJM3zr6zORiPGuOE+/vkc90KtTosSSvaCjKb2Q==}
'@jridgewell/trace-mapping@0.3.9':
resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==}
@@ -3229,8 +3235,8 @@ packages:
'@swc/helpers@0.5.5':
resolution: {integrity: sha512-KGYxvIOXcceOAbEk4bi/dVLEK9z8sZ0uBB3Il5b1rhfClSpcX0yfRO0KmTkqR2cnQDymwLB+25ZyMzICg/cm/A==}
'@swc/types@0.1.23':
resolution: {integrity: sha512-u1iIVZV9Q0jxY+yM2vw/hZGDNudsN85bBpTqzAQ9rzkxW9D+e3aEM4Han+ow518gSewkXgjmEK0BD79ZcNVgPw==}
'@swc/types@0.1.24':
resolution: {integrity: sha512-tjTMh3V4vAORHtdTprLlfoMptu1WfTZG9Rsca6yOKyNYsRr+MUXutKmliB17orgSZk5DpnDxs8GUdd/qwYxOng==}
'@tailwindcss/aspect-ratio@0.4.2':
resolution: {integrity: sha512-8QPrypskfBa7QIMuKHg2TA7BqES6vhBrDLOv8Unb6FcFyd3TjKbc6lcmb9UPQHxfl24sXoJ41ux/H7qQQvfaSQ==}
@@ -3391,8 +3397,8 @@ packages:
'@types/node@17.0.45':
resolution: {integrity: sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw==}
'@types/node@18.19.118':
resolution: {integrity: sha512-hIPK0hSrrcaoAu/gJMzN3QClXE4QdCdFvaenJ0JsjIbExP1JFFVH+RHcBt25c9n8bx5dkIfqKE+uw6BmBns7ug==}
'@types/node@18.19.122':
resolution: {integrity: sha512-yzegtT82dwTNEe/9y+CM8cgb42WrUfMMCg2QqSddzO1J6uPmBD7qKCZ7dOHZP2Yrpm/kb0eqdNMn2MUyEiqBmA==}
'@types/node@20.5.1':
resolution: {integrity: sha512-4tT2UrL5LBqDwoed9wZ6N3umC4Yhz3W3FloMmiiG4JwmUJWpie0c7lcnUNd4gtMKuDEO4wRVS8B6Xa0uMRsMKg==}
@@ -4087,11 +4093,6 @@ packages:
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
hasBin: true
browserslist@4.24.3:
resolution: {integrity: sha512-1CPmv8iobE2fyRMV97dAcMVegvvWKxmq94hkLiAkUGwKVTyDLw33K+ZxiFrREKmmps4rIw6grcCFCnTMSZ/YiA==}
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
hasBin: true
browserslist@4.25.1:
resolution: {integrity: sha512-KGj0KoOMXLpSNkkEI6Z6mShmQy0bc1I+T7K9N81k4WWMrfz+6fQ6es80B/YLAeRoKvjYE1YSHHOW1qe9xIVzHw==}
engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}
@@ -4196,8 +4197,8 @@ packages:
caniuse-lite@1.0.30001700:
resolution: {integrity: sha512-2S6XIXwaE7K7erT8dY+kLQcpa5ms63XlRkMkReXjle+kf6c5g38vyMl+Z5y8dSxOFDhcFe+nxnn261PLxBSQsQ==}
caniuse-lite@1.0.30001727:
resolution: {integrity: sha512-pB68nIHmbN6L/4C6MH1DokyR3bYqFwjaSs/sWDHGj4CTcFtQUQMuJftVwWkXq7mNWOybD3KhUv3oWHoGxgP14Q==}
caniuse-lite@1.0.30001734:
resolution: {integrity: sha512-uhE1Ye5vgqju6OI71HTQqcBCZrvHugk0MjLak7Q+HfoBgoq5Bi+5YnwjP4fjDgrtYr/l8MVRBvzz9dPD4KyK0A==}
caseless@0.12.0:
resolution: {integrity: sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==}
@@ -4426,8 +4427,8 @@ packages:
resolution: {integrity: sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==}
engines: {node: '>= 0.6'}
compression@1.8.0:
resolution: {integrity: sha512-k6WLKfunuqCYD3t6AsuPGvQWaKwuLLh2/xHNcX4qE+vIfDNXpSqnrhwA7O53R7WVQUnt8dVAIW+YHr7xTgOgGA==}
compression@1.8.1:
resolution: {integrity: sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==}
engines: {node: '>= 0.8.0'}
computed-style@0.1.4:
@@ -4547,8 +4548,8 @@ packages:
core-js-compat@3.37.1:
resolution: {integrity: sha512-9TNiImhKvQqSUkOvk/mMRZzOANTiEVC7WaBNhHcKM7x+/5E1l5NvsysR19zuDQScE8k+kfQXWRN3AtS/eOSHpg==}
core-js-compat@3.44.0:
resolution: {integrity: sha512-JepmAj2zfl6ogy34qfWtcE7nHKAJnKsQFRn++scjVS2bZFllwptzw61BZcZFYBPpUznLfAvh0LGhxKppk04ClA==}
core-js-compat@3.45.0:
resolution: {integrity: sha512-gRoVMBawZg0OnxaVv3zpqLLxaHmsubEGyTnqdpI/CEBvX4JadI1dMSHxagThprYRtSVbuQxvi6iUatdPxohHpA==}
core-util-is@1.0.2:
resolution: {integrity: sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==}
@@ -4866,6 +4867,9 @@ packages:
dlv@1.1.3:
resolution: {integrity: sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==}
dns-caching@0.2.5:
resolution: {integrity: sha512-1cnB6i/OG4zfYbRnDjWZDT+FGLvOBuJlFIxVZvHBiaa62SCfaGoP4Si50O14HyoHmx1gadeGWigYXdX5LQAFvg==}
doctrine@2.1.0:
resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}
engines: {node: '>=0.10.0'}
@@ -4937,8 +4941,8 @@ packages:
electron-to-chromium@1.4.810:
resolution: {integrity: sha512-Kaxhu4T7SJGpRQx99tq216gCq2nMxJo+uuT6uzz9l8TVN2stL7M06MIIXAtr9jsrLs2Glflgf2vMQRepxawOdQ==}
electron-to-chromium@1.5.182:
resolution: {integrity: sha512-Lv65Btwv9W4J9pyODI6EWpdnhfvrve/us5h1WspW8B2Fb0366REPtY3hX7ounk1CkV/TBjWCEvCBBbYbmV0qCA==}
electron-to-chromium@1.5.200:
resolution: {integrity: sha512-rFCxROw7aOe4uPTfIAx+rXv9cEcGx+buAF4npnhtTqCJk5KDFRnh3+KYj7rdVh6lsFt5/aPs+Irj9rZ33WMA7w==}
email-templates@12.0.1:
resolution: {integrity: sha512-849pjBFVUAWWTa3HqhDjxlXHaSWmxf4CZOlZ9iVkrSAbQ8YCYi+7KiKqt35L6F20WhSViWX7lmMjno6zBv2rNQ==}
@@ -5506,8 +5510,8 @@ packages:
flow-enums-runtime@0.0.6:
resolution: {integrity: sha512-3PYnM29RFXwvAN6Pc/scUfkI7RwhQ/xqyLUyPNlXUp9S40zI8nup9tUSrTLSVnWGBN38FNiGWbwZOB6uR4OGdw==}
flow-parser@0.275.0:
resolution: {integrity: sha512-fHNwawoA2LM7FsxhU/1lTRGq9n6/Q8k861eHgN7GKtamYt9Qrxpg/ZSrev8o1WX7fQ2D3Gg3+uvYN15PmsG7Yw==}
flow-parser@0.278.0:
resolution: {integrity: sha512-9oUcYDHf9n+E/t0FXndgBqGbaUsGEcmWqIr1ldqCzTzctsJV5E/bHusOj4ThB72Ss2mqWpLFNz0+o2c1O8J6+A==}
engines: {node: '>=0.4.0'}
fn.name@1.1.0:
@@ -6519,6 +6523,10 @@ packages:
jws@4.0.0:
resolution: {integrity: sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==}
jwt-decode@4.0.0:
resolution: {integrity: sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==}
engines: {node: '>=18'}
keyv@4.5.4:
resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==}
@@ -6744,6 +6752,10 @@ packages:
resolution: {integrity: sha512-9hp3Vp2/hFQUiIwKo8XCeFVnrg8Pk3TYNPIR7tJADKi5YfcF7vEaK7avFHTlSy3kOKYaJQaalfEo6YuXdceBOQ==}
engines: {node: 14 || >=16.14}
lru-cache@11.1.0:
resolution: {integrity: sha512-QIXZUBJUx+2zHUdQujWejBkcD9+cs94tLn0+YL8UrCh+D5sCXZ4c7LaEH48pNwRY3MLDgqUFyhlCyjJPf1WP0A==}
engines: {node: 20 || >=22}
lru-cache@5.1.1:
resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}
@@ -7534,6 +7546,10 @@ packages:
resolution: {integrity: sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==}
engines: {node: '>= 0.8'}
on-headers@1.1.0:
resolution: {integrity: sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==}
engines: {node: '>= 0.8'}
once@1.4.0:
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
@@ -8838,9 +8854,9 @@ packages:
resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==}
engines: {node: '>=0.10.0'}
source-map@0.7.4:
resolution: {integrity: sha512-l3BikUxvPOcn5E74dZiq5BGsTb5yEwhaTSzccU6t4sDOH8NWJCstKO5QT2CvtFoK6F0saL7p9xHAqHOlCPJygA==}
engines: {node: '>= 8'}
source-map@0.7.6:
resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==}
engines: {node: '>= 12'}
space-separated-tokens@2.0.2:
resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==}
@@ -9893,8 +9909,8 @@ packages:
engines: {node: '>= 14'}
hasBin: true
yaml@2.8.0:
resolution: {integrity: sha512-4lLa/EcQCB0cJkyts+FpIRx5G/llPxfP6VQU5KByHEhLxY3IJCH0f0Hy1MHI8sClTvsIb8qwRJ6R/ZdlDJ/leQ==}
yaml@2.8.1:
resolution: {integrity: sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==}
engines: {node: '>= 14.6'}
hasBin: true
@@ -10038,11 +10054,11 @@ snapshots:
'@babel/generator': 7.28.0
'@babel/helper-compilation-targets': 7.27.2
'@babel/helper-module-transforms': 7.27.3(@babel/core@7.28.0)
'@babel/helpers': 7.27.6
'@babel/helpers': 7.28.2
'@babel/parser': 7.28.0
'@babel/template': 7.27.2
'@babel/traverse': 7.28.0
'@babel/types': 7.28.1
'@babel/types': 7.28.2
convert-source-map: 2.0.0
debug: 4.4.1
gensync: 1.0.0-beta.2
@@ -10061,9 +10077,9 @@ snapshots:
'@babel/generator@7.28.0':
dependencies:
'@babel/parser': 7.28.0
'@babel/types': 7.28.1
'@jridgewell/gen-mapping': 0.3.12
'@jridgewell/trace-mapping': 0.3.29
'@babel/types': 7.28.2
'@jridgewell/gen-mapping': 0.3.13
'@jridgewell/trace-mapping': 0.3.30
jsesc: 3.1.0
'@babel/helper-annotate-as-pure@7.24.7':
@@ -10072,7 +10088,7 @@ snapshots:
'@babel/helper-annotate-as-pure@7.27.3':
dependencies:
'@babel/types': 7.28.1
'@babel/types': 7.28.2
'@babel/helper-builder-binary-assignment-operator-visitor@7.24.7':
dependencies:
@@ -10093,7 +10109,7 @@ snapshots:
dependencies:
'@babel/compat-data': 7.28.0
'@babel/helper-validator-option': 7.27.1
browserslist: 4.24.3
browserslist: 4.25.1
lru-cache: 5.1.1
semver: 6.3.1
@@ -10199,7 +10215,7 @@ snapshots:
'@babel/helper-member-expression-to-functions@7.27.1':
dependencies:
'@babel/traverse': 7.28.0
'@babel/types': 7.28.1
'@babel/types': 7.28.2
transitivePeerDependencies:
- supports-color
@@ -10213,7 +10229,7 @@ snapshots:
'@babel/helper-module-imports@7.27.1':
dependencies:
'@babel/traverse': 7.28.0
'@babel/types': 7.28.1
'@babel/types': 7.28.2
transitivePeerDependencies:
- supports-color
@@ -10252,7 +10268,7 @@ snapshots:
'@babel/helper-optimise-call-expression@7.27.1':
dependencies:
'@babel/types': 7.28.1
'@babel/types': 7.28.2
'@babel/helper-plugin-utils@7.24.7': {}
@@ -10320,7 +10336,7 @@ snapshots:
'@babel/helper-skip-transparent-expression-wrappers@7.27.1':
dependencies:
'@babel/traverse': 7.28.0
'@babel/types': 7.28.1
'@babel/types': 7.28.2
transitivePeerDependencies:
- supports-color
@@ -10357,7 +10373,7 @@ snapshots:
dependencies:
'@babel/template': 7.27.2
'@babel/traverse': 7.28.0
'@babel/types': 7.28.1
'@babel/types': 7.28.2
transitivePeerDependencies:
- supports-color
@@ -10366,10 +10382,10 @@ snapshots:
'@babel/template': 7.24.7
'@babel/types': 7.24.7
'@babel/helpers@7.27.6':
'@babel/helpers@7.28.2':
dependencies:
'@babel/template': 7.27.2
'@babel/types': 7.28.1
'@babel/types': 7.28.2
'@babel/highlight@7.24.7':
dependencies:
@@ -10388,7 +10404,7 @@ snapshots:
'@babel/parser@7.28.0':
dependencies:
'@babel/types': 7.28.1
'@babel/types': 7.28.2
'@babel/plugin-bugfix-firefox-class-in-computed-class-key@7.24.7(@babel/core@7.24.7)':
dependencies:
@@ -11080,7 +11096,7 @@ snapshots:
'@babel/helper-module-imports': 7.27.1
'@babel/helper-plugin-utils': 7.27.1
'@babel/plugin-syntax-jsx': 7.27.1(@babel/core@7.24.7)
'@babel/types': 7.28.1
'@babel/types': 7.28.2
transitivePeerDependencies:
- supports-color
@@ -11374,7 +11390,7 @@ snapshots:
dependencies:
regenerator-runtime: 0.14.1
'@babel/runtime@7.27.6': {}
'@babel/runtime@7.28.2': {}
'@babel/template@7.24.7':
dependencies:
@@ -11386,7 +11402,7 @@ snapshots:
dependencies:
'@babel/code-frame': 7.27.1
'@babel/parser': 7.28.0
'@babel/types': 7.28.1
'@babel/types': 7.28.2
'@babel/traverse@7.24.7':
dependencies:
@@ -11410,7 +11426,7 @@ snapshots:
'@babel/helper-globals': 7.28.0
'@babel/parser': 7.28.0
'@babel/template': 7.27.2
'@babel/types': 7.28.1
'@babel/types': 7.28.2
debug: 4.4.1
transitivePeerDependencies:
- supports-color
@@ -11426,7 +11442,7 @@ snapshots:
'@babel/helper-string-parser': 7.25.9
'@babel/helper-validator-identifier': 7.25.9
'@babel/types@7.28.1':
'@babel/types@7.28.2':
dependencies:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.27.1
@@ -12091,10 +12107,10 @@ snapshots:
'@types/yargs': 17.0.33
chalk: 4.1.2
'@jridgewell/gen-mapping@0.3.12':
'@jridgewell/gen-mapping@0.3.13':
dependencies:
'@jridgewell/sourcemap-codec': 1.5.4
'@jridgewell/trace-mapping': 0.3.29
'@jridgewell/sourcemap-codec': 1.5.5
'@jridgewell/trace-mapping': 0.3.30
'@jridgewell/gen-mapping@0.3.5':
dependencies:
@@ -12106,24 +12122,24 @@ snapshots:
'@jridgewell/set-array@1.2.1': {}
'@jridgewell/source-map@0.3.10':
'@jridgewell/source-map@0.3.11':
dependencies:
'@jridgewell/gen-mapping': 0.3.12
'@jridgewell/trace-mapping': 0.3.29
'@jridgewell/gen-mapping': 0.3.13
'@jridgewell/trace-mapping': 0.3.30
'@jridgewell/sourcemap-codec@1.4.15': {}
'@jridgewell/sourcemap-codec@1.5.4': {}
'@jridgewell/sourcemap-codec@1.5.5': {}
'@jridgewell/trace-mapping@0.3.25':
dependencies:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.4.15
'@jridgewell/trace-mapping@0.3.29':
'@jridgewell/trace-mapping@0.3.30':
dependencies:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.4
'@jridgewell/sourcemap-codec': 1.5.5
'@jridgewell/trace-mapping@0.3.9':
dependencies:
@@ -12871,7 +12887,7 @@ snapshots:
semver: 7.7.1
strip-ansi: 5.2.0
wcwidth: 1.0.1
yaml: 2.8.0
yaml: 2.8.1
transitivePeerDependencies:
- encoding
@@ -12916,7 +12932,7 @@ snapshots:
dependencies:
'@react-native-community/cli-debugger-ui': 13.6.8
'@react-native-community/cli-tools': 13.6.8(encoding@0.1.13)
compression: 1.8.0
compression: 1.8.1
connect: 3.7.0
errorhandler: 1.5.1
nocache: 3.0.4
@@ -13392,7 +13408,7 @@ snapshots:
'@react-three/fiber@8.16.8(@types/react@18.3.3)(react-dom@18.3.1(react@18.3.1))(react-native@0.74.2(@babel/core@7.24.7)(@babel/preset-env@7.24.7(@babel/core@7.24.7))(@types/react@18.3.3)(encoding@0.1.13)(react@18.3.1))(react@18.3.1)(three@0.165.0)':
dependencies:
'@babel/runtime': 7.27.6
'@babel/runtime': 7.28.2
'@types/react-reconciler': 0.26.7
'@types/webxr': 0.5.22
base64-js: 1.5.1
@@ -13547,7 +13563,7 @@ snapshots:
'@rnx-kit/chromium-edge-launcher@1.0.0':
dependencies:
'@types/node': 18.19.118
'@types/node': 18.19.122
escape-string-regexp: 4.0.0
is-wsl: 2.2.0
lighthouse-logger: 1.4.2
@@ -13810,7 +13826,7 @@ snapshots:
'@swc/core@1.6.5(@swc/helpers@0.5.11)':
dependencies:
'@swc/counter': 0.1.3
'@swc/types': 0.1.23
'@swc/types': 0.1.24
optionalDependencies:
'@swc/core-darwin-arm64': 1.6.5
'@swc/core-darwin-x64': 1.6.5
@@ -13835,7 +13851,7 @@ snapshots:
'@swc/counter': 0.1.3
tslib: 2.8.1
'@swc/types@0.1.23':
'@swc/types@0.1.24':
dependencies:
'@swc/counter': 0.1.3
@@ -14013,7 +14029,7 @@ snapshots:
'@types/node@17.0.45': {}
'@types/node@18.19.118':
'@types/node@18.19.122':
dependencies:
undici-types: 5.26.5
@@ -14689,7 +14705,7 @@ snapshots:
dependencies:
'@babel/core': 7.24.7
'@babel/helper-define-polyfill-provider': 0.6.5(@babel/core@7.24.7)
core-js-compat: 3.44.0
core-js-compat: 3.45.0
transitivePeerDependencies:
- supports-color
@@ -14804,17 +14820,10 @@ snapshots:
node-releases: 2.0.14
update-browserslist-db: 1.0.16(browserslist@4.23.1)
browserslist@4.24.3:
dependencies:
caniuse-lite: 1.0.30001727
electron-to-chromium: 1.5.182
node-releases: 2.0.19
update-browserslist-db: 1.1.3(browserslist@4.24.3)
browserslist@4.25.1:
dependencies:
caniuse-lite: 1.0.30001727
electron-to-chromium: 1.5.182
caniuse-lite: 1.0.30001734
electron-to-chromium: 1.5.200
node-releases: 2.0.19
update-browserslist-db: 1.1.3(browserslist@4.25.1)
@@ -14945,7 +14954,7 @@ snapshots:
caniuse-lite@1.0.30001700: {}
caniuse-lite@1.0.30001727: {}
caniuse-lite@1.0.30001734: {}
caseless@0.12.0: {}
@@ -15195,13 +15204,13 @@ snapshots:
dependencies:
mime-db: 1.54.0
compression@1.8.0:
compression@1.8.1:
dependencies:
bytes: 3.1.2
compressible: 2.0.18
debug: 2.6.9
negotiator: 0.6.4
on-headers: 1.0.2
on-headers: 1.1.0
safe-buffer: 5.2.1
vary: 1.1.2
transitivePeerDependencies:
@@ -15332,7 +15341,7 @@ snapshots:
dependencies:
browserslist: 4.23.1
core-js-compat@3.44.0:
core-js-compat@3.45.0:
dependencies:
browserslist: 4.25.1
@@ -15698,6 +15707,10 @@ snapshots:
dlv@1.1.3: {}
dns-caching@0.2.5:
dependencies:
lru-cache: 11.1.0
doctrine@2.1.0:
dependencies:
esutils: 2.0.3
@@ -15782,7 +15795,7 @@ snapshots:
electron-to-chromium@1.4.810: {}
electron-to-chromium@1.5.182: {}
electron-to-chromium@1.5.200: {}
email-templates@12.0.1(@babel/core@7.24.7)(encoding@0.1.13)(handlebars@4.7.8)(mustache@4.2.0)(pug@3.0.3)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(underscore@1.13.7):
dependencies:
@@ -16702,7 +16715,7 @@ snapshots:
flow-enums-runtime@0.0.6: {}
flow-parser@0.275.0: {}
flow-parser@0.278.0: {}
fn.name@1.1.0: {}
@@ -17092,7 +17105,7 @@ snapshots:
hermes-profile-transformer@0.0.6:
dependencies:
source-map: 0.7.4
source-map: 0.7.6
highlight.js@10.7.3: {}
@@ -17685,7 +17698,7 @@ snapshots:
'@babel/register': 7.27.1(@babel/core@7.28.0)
babel-core: 7.0.0-bridge.0(@babel/core@7.28.0)
chalk: 4.1.2
flow-parser: 0.275.0
flow-parser: 0.278.0
graceful-fs: 4.2.11
micromatch: 4.0.8
neo-async: 2.6.2
@@ -17808,6 +17821,8 @@ snapshots:
jwa: 2.0.0
safe-buffer: 5.2.1
jwt-decode@4.0.0: {}
keyv@4.5.4:
dependencies:
json-buffer: 3.0.1
@@ -18036,6 +18051,8 @@ snapshots:
lru-cache@10.2.2: {}
lru-cache@11.1.0: {}
lru-cache@5.1.1:
dependencies:
yallist: 3.1.1
@@ -18307,13 +18324,13 @@ snapshots:
metro-runtime@0.80.12:
dependencies:
'@babel/runtime': 7.27.6
'@babel/runtime': 7.28.2
flow-enums-runtime: 0.0.6
metro-source-map@0.80.12:
dependencies:
'@babel/traverse': 7.28.0
'@babel/types': 7.28.1
'@babel/types': 7.28.2
flow-enums-runtime: 0.0.6
invariant: 2.2.4
metro-symbolicate: 0.80.12
@@ -18352,7 +18369,7 @@ snapshots:
'@babel/core': 7.28.0
'@babel/generator': 7.28.0
'@babel/parser': 7.28.0
'@babel/types': 7.28.1
'@babel/types': 7.28.2
flow-enums-runtime: 0.0.6
metro: 0.80.12
metro-babel-transformer: 0.80.12
@@ -18375,7 +18392,7 @@ snapshots:
'@babel/parser': 7.28.0
'@babel/template': 7.27.2
'@babel/traverse': 7.28.0
'@babel/types': 7.28.1
'@babel/types': 7.28.2
accepts: 1.3.8
chalk: 4.1.2
ci-info: 2.0.0
@@ -19002,6 +19019,8 @@ snapshots:
on-headers@1.0.2: {}
on-headers@1.1.0: {}
once@1.4.0:
dependencies:
wrappy: 1.0.2
@@ -20534,7 +20553,7 @@ snapshots:
source-map@0.6.1: {}
source-map@0.7.4: {}
source-map@0.7.6: {}
space-separated-tokens@2.0.2: {}
@@ -20871,7 +20890,7 @@ snapshots:
terser@5.43.1:
dependencies:
'@jridgewell/source-map': 0.3.10
'@jridgewell/source-map': 0.3.11
acorn: 8.15.0
commander: 2.20.3
source-map-support: 0.5.21
@@ -21298,12 +21317,6 @@ snapshots:
escalade: 3.1.2
picocolors: 1.0.1
update-browserslist-db@1.1.3(browserslist@4.24.3):
dependencies:
browserslist: 4.24.3
escalade: 3.2.0
picocolors: 1.1.1
update-browserslist-db@1.1.3(browserslist@4.25.1):
dependencies:
browserslist: 4.25.1
@@ -21594,7 +21607,7 @@ snapshots:
yaml@2.4.5: {}
yaml@2.8.0: {}
yaml@2.8.1: {}
yamljs@0.3.0:
dependencies:

57
public/images/openid.svg Normal file
View File

@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
version="1.0"
width="120"
height="120"
id="svg2593"
xml:space="preserve"
sodipodi:docname="OpenID_logo_2.svg"
inkscape:version="1.3.2 (091e20e, 2023-11-25)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"><sodipodi:namedview
id="namedview1"
pagecolor="#505050"
bordercolor="#eeeeee"
borderopacity="1"
inkscape:showpageshadow="0"
inkscape:pageopacity="0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#505050"
showgrid="false"
inkscape:zoom="5.3731101"
inkscape:cx="69.60587"
inkscape:cy="65.883631"
inkscape:window-width="1512"
inkscape:window-height="945"
inkscape:window-x="0"
inkscape:window-y="37"
inkscape:window-maximized="0"
inkscape:current-layer="svg2593" /><defs
id="defs2596"><clipPath
id="clipPath2616"><path
d="M 0,14400 H 14400 V 0 H 0 Z"
id="path2618" /></clipPath></defs><g
transform="matrix(1.25,0,0,-1.25,-8601.6804,9121.1624)"
id="g2602"><g
transform="matrix(0.375,0,0,0.375,4301.4506,4557.5812)"
id="g2734"><g
id="g2726"><g
transform="translate(6998.0969,7259.1135)"
id="g2604"><path
d="M 0,0 V -159.939 -180 l 32,15.061 V 15.633 Z"
id="path2606"
style="fill:#f8931e;fill-opacity:1;fill-rule:nonzero;stroke:none" /></g><g
transform="translate(7108.9192,7206.3137)"
id="g2608"><path
d="M 0,0 4.417,-45.864 -57.466,-32.4"
id="path2610"
style="fill:#b3b3b3;fill-opacity:1;fill-rule:nonzero;stroke:none" /></g><g
transform="translate(6934.0969,7147.6213)"
id="g2620"><path
d="M 0,0 C 0,22.674 24.707,41.769 58.383,47.598 V 67.923 C 6.873,61.697 -32,33.656 -32,0 -32,-34.869 9.725,-63.709 64,-68.508 v 20.061 C 27.484,-43.869 0,-23.919 0,0 M 101.617,67.915 V 47.598 c 13.399,-2.319 25.385,-6.727 34.951,-12.64 l 22.627,13.984 c -15.42,9.531 -35.322,16.283 -57.578,18.973"
id="path2622"
style="fill:#b3b3b3;fill-opacity:1;fill-rule:nonzero;stroke:none" /></g></g></g></g></svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

@@ -1,3 +1,4 @@
import { requestInterceptorFunction } from '@server/utils/customProxyAgent';
import type { AxiosInstance, AxiosRequestConfig } from 'axios';
import axios from 'axios';
import rateLimit from 'axios-rate-limit';
@@ -9,7 +10,7 @@ const DEFAULT_TTL = 300;
// 10 seconds default rolling buffer (in ms)
const DEFAULT_ROLLING_BUFFER = 10000;
interface ExternalAPIOptions {
export interface ExternalAPIOptions {
nodeCache?: NodeCache;
headers?: Record<string, unknown>;
rateLimit?: {
@@ -37,8 +38,7 @@ class ExternalAPI {
...options.headers,
},
});
this.axios.interceptors.request = axios.interceptors.request;
this.axios.interceptors.response = axios.interceptors.response;
this.axios.interceptors.request.use(requestInterceptorFunction);
if (options.rateLimit) {
this.axios = rateLimit(this.axios, {

39
server/api/metadata.ts Normal file
View File

@@ -0,0 +1,39 @@
import type { TvShowProvider } from '@server/api/provider';
import TheMovieDb from '@server/api/themoviedb';
import Tvdb from '@server/api/tvdb';
import { getSettings, MetadataProviderType } from '@server/lib/settings';
import logger from '@server/logger';
export const getMetadataProvider = async (
mediaType: 'movie' | 'tv' | 'anime'
): Promise<TvShowProvider> => {
try {
const settings = await getSettings();
if (mediaType == 'movie') {
return new TheMovieDb();
}
if (
mediaType == 'tv' &&
settings.metadataSettings.tv == MetadataProviderType.TVDB
) {
return await Tvdb.getInstance();
}
if (
mediaType == 'anime' &&
settings.metadataSettings.anime == MetadataProviderType.TVDB
) {
return await Tvdb.getInstance();
}
return new TheMovieDb();
} catch (e) {
logger.error('Failed to get metadata provider', {
label: 'Metadata',
message: e.message,
});
return new TheMovieDb();
}
};

View File

@@ -291,7 +291,7 @@ class PlexTvAPI extends ExternalAPI {
headers: {
'If-None-Match': cachedWatchlist?.etag,
},
baseURL: 'https://metadata.provider.plex.tv',
baseURL: 'https://discover.provider.plex.tv',
validateStatus: (status) => status < 400, // Allow HTTP 304 to return without error
}
);
@@ -315,7 +315,7 @@ class PlexTvAPI extends ExternalAPI {
const detailedResponse = await this.getRolling<MetadataResponse>(
`/library/metadata/${watchlistItem.ratingKey}`,
{
baseURL: 'https://metadata.provider.plex.tv',
baseURL: 'https://discover.provider.plex.tv',
}
);

30
server/api/provider.ts Normal file
View File

@@ -0,0 +1,30 @@
import type {
TmdbSeasonWithEpisodes,
TmdbTvDetails,
} from '@server/api/themoviedb/interfaces';
export interface TvShowProvider {
getTvShow({
tvId,
language,
}: {
tvId: number;
language?: string;
}): Promise<TmdbTvDetails>;
getTvSeason({
tvId,
seasonNumber,
language,
}: {
tvId: number;
seasonNumber: number;
language?: string;
}): Promise<TmdbSeasonWithEpisodes>;
getShowByTvdbId({
tvdbId,
language,
}: {
tvdbId: number;
language?: string;
}): Promise<TmdbTvDetails>;
}

View File

@@ -145,6 +145,7 @@ export interface IMDBRating {
title: string;
url: string;
criticsScore: number;
criticsScoreCount: number;
}
/**
@@ -187,6 +188,7 @@ class IMDBRadarrProxy extends ExternalAPI {
title: data[0].Title,
url: `https://www.imdb.com/title/${data[0].ImdbId}`,
criticsScore: data[0].MovieRatings.Imdb.Value,
criticsScoreCount: data[0].MovieRatings.Imdb.Count,
};
} catch (e) {
throw new Error(

View File

@@ -1,6 +1,7 @@
import type { User } from '@server/entity/User';
import type { TautulliSettings } from '@server/lib/settings';
import logger from '@server/logger';
import { requestInterceptorFunction } from '@server/utils/customProxyAgent';
import type { AxiosInstance } from 'axios';
import axios from 'axios';
import { uniqWith } from 'lodash';
@@ -123,8 +124,7 @@ class TautulliAPI {
}${settings.urlBase ?? ''}`,
params: { apikey: settings.apiKey },
});
this.axios.interceptors.request = axios.interceptors.request;
this.axios.interceptors.response = axios.interceptors.response;
this.axios.interceptors.request.use(requestInterceptorFunction);
}
public async getInfo(): Promise<TautulliInfo> {

View File

@@ -1,4 +1,5 @@
import ExternalAPI from '@server/api/externalapi';
import type { TvShowProvider } from '@server/api/provider';
import cacheManager from '@server/lib/cache';
import { getSettings } from '@server/lib/settings';
import { sortBy } from 'lodash';
@@ -120,7 +121,7 @@ interface DiscoverTvOptions {
certificationCountry?: string;
}
class TheMovieDb extends ExternalAPI {
class TheMovieDb extends ExternalAPI implements TvShowProvider {
private locale: string;
private discoverRegion?: string;
private originalLanguage?: string;
@@ -341,6 +342,13 @@ class TheMovieDb extends ExternalAPI {
}
);
data.episodes = data.episodes.map((episode) => {
if (episode.still_path) {
episode.still_path = `https://image.tmdb.org/t/p/original/${episode.still_path}`;
}
return episode;
});
return data;
} catch (e) {
throw new Error(`[TMDB] Failed to fetch TV show details: ${e.message}`);
@@ -1054,7 +1062,7 @@ class TheMovieDb extends ExternalAPI {
keywordId,
}: {
keywordId: number;
}): Promise<TmdbKeyword> {
}): Promise<TmdbKeyword | null> {
try {
const data = await this.get<TmdbKeyword>(
`/keyword/${keywordId}`,
@@ -1064,6 +1072,9 @@ class TheMovieDb extends ExternalAPI {
return data;
} catch (e) {
if (e.response?.status === 404) {
return null;
}
throw new Error(`[TMDB] Failed to fetch keyword: ${e.message}`);
}
}

View File

@@ -220,7 +220,7 @@ export interface TmdbTvEpisodeResult {
show_id: number;
still_path: string;
vote_average: number;
vote_cuont: number;
vote_count: number;
}
export interface TmdbTvSeasonResult {

563
server/api/tvdb/index.ts Normal file
View File

@@ -0,0 +1,563 @@
import ExternalAPI from '@server/api/externalapi';
import type { TvShowProvider } from '@server/api/provider';
import TheMovieDb from '@server/api/themoviedb';
import type {
TmdbSeasonWithEpisodes,
TmdbTvDetails,
TmdbTvEpisodeResult,
TmdbTvSeasonResult,
} from '@server/api/themoviedb/interfaces';
import {
convertTmdbLanguageToTvdbWithFallback,
type TvdbBaseResponse,
type TvdbEpisode,
type TvdbLoginResponse,
type TvdbSeasonDetails,
type TvdbTvDetails,
} from '@server/api/tvdb/interfaces';
import cacheManager, { type AvailableCacheIds } from '@server/lib/cache';
import logger from '@server/logger';
interface TvdbConfig {
baseUrl: string;
maxRequestsPerSecond: number;
maxRequests: number;
cachePrefix: AvailableCacheIds;
}
const DEFAULT_CONFIG: TvdbConfig = {
baseUrl: 'https://api4.thetvdb.com/v4',
maxRequestsPerSecond: 50,
maxRequests: 20,
cachePrefix: 'tvdb' as const,
};
const enum TvdbIdStatus {
INVALID = -1,
}
type TvdbId = number;
type ValidTvdbId = Exclude<TvdbId, TvdbIdStatus.INVALID>;
class Tvdb extends ExternalAPI implements TvShowProvider {
static instance: Tvdb;
private readonly tmdb: TheMovieDb;
private static readonly DEFAULT_CACHE_TTL = 43200;
private static readonly DEFAULT_LANGUAGE = 'eng';
private token: string;
private pin?: string;
constructor(pin?: string) {
const finalConfig = { ...DEFAULT_CONFIG };
super(
finalConfig.baseUrl,
{},
{
nodeCache: cacheManager.getCache(finalConfig.cachePrefix).data,
rateLimit: {
maxRequests: finalConfig.maxRequests,
maxRPS: finalConfig.maxRequestsPerSecond,
},
}
);
this.pin = pin;
this.tmdb = new TheMovieDb();
}
public static async getInstance(): Promise<Tvdb> {
if (!this.instance) {
this.instance = new Tvdb();
await this.instance.login();
}
return this.instance;
}
private async refreshToken(): Promise<void> {
try {
if (!this.token) {
await this.login();
return;
}
const base64Url = this.token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const payload = JSON.parse(Buffer.from(base64, 'base64').toString());
if (!payload.exp) {
await this.login();
}
const now = Math.floor(Date.now() / 1000);
const diff = payload.exp - now;
// refresh token 1 week before expiration
if (diff < 604800) {
await this.login();
}
} catch (error) {
this.handleError('Failed to refresh token', error);
}
}
public async test(): Promise<void> {
try {
await this.login();
} catch (error) {
this.handleError('Login failed', error);
throw error;
}
}
async login(): Promise<TvdbLoginResponse> {
let body: { apiKey: string; pin?: string } = {
apiKey: 'd00d9ecb-a9d0-4860-958a-74b14a041405',
};
if (this.pin) {
body = {
...body,
pin: this.pin,
};
}
const response = await this.post<TvdbBaseResponse<TvdbLoginResponse>>(
'/login',
{
...body,
}
);
this.token = response.data.token;
return response.data;
}
public async getShowByTvdbId({
tvdbId,
language,
}: {
tvdbId: number;
language?: string;
}): Promise<TmdbTvDetails> {
try {
const tmdbTvShow = await this.tmdb.getShowByTvdbId({
tvdbId: tvdbId,
language,
});
try {
await this.refreshToken();
const validTvdbId = this.getTvdbIdFromTmdb(tmdbTvShow);
if (this.isValidTvdbId(validTvdbId)) {
return this.enrichTmdbShowWithTvdbData(tmdbTvShow, validTvdbId);
}
return tmdbTvShow;
} catch (error) {
return tmdbTvShow;
}
} catch (error) {
this.handleError('Failed to fetch TV show details', error);
throw error;
}
}
public async getTvShow({
tvId,
language,
}: {
tvId: number;
language?: string;
}): Promise<TmdbTvDetails> {
try {
const tmdbTvShow = await this.tmdb.getTvShow({ tvId, language });
try {
await this.refreshToken();
const tvdbId = this.getTvdbIdFromTmdb(tmdbTvShow);
if (this.isValidTvdbId(tvdbId)) {
return await this.enrichTmdbShowWithTvdbData(tmdbTvShow, tvdbId);
}
return tmdbTvShow;
} catch (error) {
this.handleError('Failed to fetch TV show details', error);
return tmdbTvShow;
}
} catch (error) {
this.handleError('Failed to fetch TV show details', error);
return this.tmdb.getTvShow({ tvId, language });
}
}
public async getTvSeason({
tvId,
seasonNumber,
language = Tvdb.DEFAULT_LANGUAGE,
}: {
tvId: number;
seasonNumber: number;
language?: string;
}): Promise<TmdbSeasonWithEpisodes> {
try {
const tmdbTvShow = await this.tmdb.getTvShow({ tvId, language });
try {
await this.refreshToken();
const tvdbId = this.getTvdbIdFromTmdb(tmdbTvShow);
if (!this.isValidTvdbId(tvdbId)) {
return await this.tmdb.getTvSeason({ tvId, seasonNumber, language });
}
return await this.getTvdbSeasonData(
tvdbId,
seasonNumber,
tvId,
language
);
} catch (error) {
this.handleError('Failed to fetch TV season details', error);
return await this.tmdb.getTvSeason({ tvId, seasonNumber, language });
}
} catch (error) {
logger.error(
`[TVDB] Failed to fetch TV season details: ${error.message}`
);
throw error;
}
}
private async enrichTmdbShowWithTvdbData(
tmdbTvShow: TmdbTvDetails,
tvdbId: ValidTvdbId
): Promise<TmdbTvDetails> {
try {
await this.refreshToken();
const tvdbData = await this.fetchTvdbShowData(tvdbId);
const seasons = this.processSeasons(tvdbData);
if (!seasons.length) {
return tmdbTvShow;
}
return { ...tmdbTvShow, seasons };
} catch (error) {
logger.error(
`Failed to enrich TMDB show with TVDB data: ${error.message} token: ${this.token}`
);
return tmdbTvShow;
}
}
private async fetchTvdbShowData(tvdbId: number): Promise<TvdbTvDetails> {
const resp = await this.get<TvdbBaseResponse<TvdbTvDetails>>(
`/series/${tvdbId}/extended?meta=episodes&short=true`,
{
headers: {
Authorization: `Bearer ${this.token}`,
},
},
Tvdb.DEFAULT_CACHE_TTL
);
return resp.data;
}
private processSeasons(tvdbData: TvdbTvDetails): TmdbTvSeasonResult[] {
if (!tvdbData || !tvdbData.seasons || !tvdbData.episodes) {
return [];
}
const seasons = tvdbData.seasons
.filter((season) => season.type && season.type.type === 'official')
.sort((a, b) => a.number - b.number)
.map((season) => this.createSeasonData(season, tvdbData))
.filter(
(season) => season && season.season_number >= 0
) as TmdbTvSeasonResult[];
return seasons;
}
private createSeasonData(
season: TvdbSeasonDetails,
tvdbData: TvdbTvDetails
): TmdbTvSeasonResult {
const seasonNumber = season.number ?? -1;
if (seasonNumber < 0) {
return {
id: 0,
episode_count: 0,
name: '',
overview: '',
season_number: -1,
poster_path: '',
air_date: '',
};
}
const episodeCount = tvdbData.episodes.filter(
(episode) => episode.seasonNumber === season.number
).length;
return {
id: tvdbData.id,
episode_count: episodeCount,
name: `${season.number}`,
overview: '',
season_number: season.number,
poster_path: '',
air_date: '',
};
}
private async getTvdbSeasonData(
tvdbId: number,
seasonNumber: number,
tvId: number,
language: string = Tvdb.DEFAULT_LANGUAGE
): Promise<TmdbSeasonWithEpisodes> {
const tvdbData = await this.fetchTvdbShowData(tvdbId);
if (!tvdbData) {
logger.error(`Failed to fetch TVDB data for ID: ${tvdbId}`);
return this.createEmptySeasonResponse(tvId);
}
// get season id
const season = tvdbData.seasons.find(
(season) =>
season.number === seasonNumber &&
season.type.type &&
season.type.type === 'official'
);
if (!season) {
logger.error(
`Failed to find season ${seasonNumber} for TVDB ID: ${tvdbId}`
);
return this.createEmptySeasonResponse(tvId);
}
const wantedTranslation = convertTmdbLanguageToTvdbWithFallback(
language,
Tvdb.DEFAULT_LANGUAGE
);
// check if translation is available for the season
const availableTranslation = season.nameTranslations.filter(
(translation) =>
translation === wantedTranslation ||
translation === Tvdb.DEFAULT_LANGUAGE
);
if (!availableTranslation) {
return this.getSeasonWithOriginalLanguage(
tvdbId,
tvId,
seasonNumber,
season
);
}
return this.getSeasonWithTranslation(
tvdbId,
tvId,
seasonNumber,
season,
wantedTranslation
);
}
private async getSeasonWithTranslation(
tvdbId: number,
tvId: number,
seasonNumber: number,
season: TvdbSeasonDetails,
language: string
): Promise<TmdbSeasonWithEpisodes> {
if (!season) {
logger.error(
`Failed to find season ${seasonNumber} for TVDB ID: ${tvdbId}`
);
return this.createEmptySeasonResponse(tvId);
}
const allEpisodes = [] as TvdbEpisode[];
let page = 0;
// Limit to max 50 pages to avoid infinite loops.
// 50 pages with 500 items per page = 25_000 episodes in a series which should be more than enough
const maxPages = 50;
while (page < maxPages) {
const resp = await this.get<TvdbBaseResponse<TvdbSeasonDetails>>(
`/series/${tvdbId}/episodes/default/${language}`,
{
headers: {
Authorization: `Bearer ${this.token}`,
},
params: {
page: page,
},
}
);
if (!resp?.data?.episodes) {
logger.warn(
`No episodes found for TVDB ID: ${tvdbId} on page ${page} for season ${seasonNumber}`
);
break;
}
const { episodes } = resp.data;
if (!episodes) {
logger.debug(
`No more episodes found for TVDB ID: ${tvdbId} on page ${page} for season ${seasonNumber}`
);
break;
}
allEpisodes.push(...episodes);
const hasNextPage = resp.links?.next && episodes.length > 0;
if (!hasNextPage) {
break;
}
page++;
}
if (page >= maxPages) {
logger.warn(
`Reached max pages (${maxPages}) for TVDB ID: ${tvdbId} on season ${seasonNumber} with language ${language}. There might be more episodes available.`
);
}
const episodes = this.processEpisodes(
{ ...season, episodes: allEpisodes },
seasonNumber,
tvId
);
return {
episodes,
external_ids: { tvdb_id: tvdbId },
name: '',
overview: '',
id: season.id,
air_date: season.firstAired,
season_number: episodes.length,
};
}
private async getSeasonWithOriginalLanguage(
tvdbId: number,
tvId: number,
seasonNumber: number,
season: TvdbSeasonDetails
): Promise<TmdbSeasonWithEpisodes> {
if (!season) {
logger.error(
`Failed to find season ${seasonNumber} for TVDB ID: ${tvdbId}`
);
return this.createEmptySeasonResponse(tvId);
}
const resp = await this.get<TvdbBaseResponse<TvdbSeasonDetails>>(
`/seasons/${season.id}/extended`,
{
headers: {
Authorization: `Bearer ${this.token}`,
},
}
);
const seasons = resp.data;
const episodes = this.processEpisodes(seasons, seasonNumber, tvId);
return {
episodes,
external_ids: { tvdb_id: tvdbId },
name: '',
overview: '',
id: seasons.id,
air_date: seasons.firstAired,
season_number: episodes.length,
};
}
private processEpisodes(
tvdbSeason: TvdbSeasonDetails,
seasonNumber: number,
tvId: number
): TmdbTvEpisodeResult[] {
if (!tvdbSeason || !tvdbSeason.episodes) {
logger.error('No episodes found in TVDB season data');
return [];
}
return tvdbSeason.episodes
.filter((episode) => episode.seasonNumber === seasonNumber)
.map((episode, index) => this.createEpisodeData(episode, index, tvId));
}
private createEpisodeData(
episode: TvdbEpisode,
index: number,
tvId: number
): TmdbTvEpisodeResult {
return {
id: episode.id,
air_date: episode.aired,
episode_number: episode.number,
name: episode.name || `Episode ${index + 1}`,
overview: episode.overview || '',
season_number: episode.seasonNumber,
production_code: '',
show_id: tvId,
still_path:
episode.image && !episode.image.startsWith('https://')
? 'https://artworks.thetvdb.com' + episode.image
: '',
vote_average: 1,
vote_count: 1,
};
}
private createEmptySeasonResponse(tvId: number): TmdbSeasonWithEpisodes {
return {
episodes: [],
external_ids: { tvdb_id: tvId },
name: '',
overview: '',
id: 0,
air_date: '',
season_number: 0,
};
}
private getTvdbIdFromTmdb(tmdbTvShow: TmdbTvDetails): TvdbId {
return tmdbTvShow?.external_ids?.tvdb_id ?? TvdbIdStatus.INVALID;
}
private isValidTvdbId(tvdbId: TvdbId): tvdbId is ValidTvdbId {
return tvdbId !== TvdbIdStatus.INVALID;
}
private handleError(context: string, error: Error): void {
throw new Error(`[TVDB] ${context}: ${error.message}`);
}
}
export default Tvdb;

View File

@@ -0,0 +1,216 @@
import { type AvailableLocale } from '@server/types/languages';
export interface TvdbBaseResponse<T> {
data: T;
errors: string;
links?: TvdbPagination;
}
export interface TvdbPagination {
prev?: string;
self: string;
next?: string;
totalItems: number;
pageSize: number;
}
export interface TvdbLoginResponse {
token: string;
}
interface TvDetailsAliases {
language: string;
name: string;
}
interface TvDetailsStatus {
id: number;
name: string;
recordType: string;
keepUpdated: boolean;
}
export interface TvdbTvDetails {
id: number;
name: string;
slug: string;
image: string;
nameTranslations: string[];
overwiewTranslations: string[];
aliases: TvDetailsAliases[];
firstAired: Date;
lastAired: Date;
nextAired: Date | string;
score: number;
status: TvDetailsStatus;
originalCountry: string;
originalLanguage: string;
defaultSeasonType: string;
isOrderRandomized: boolean;
lastUpdated: Date;
averageRuntime: number;
seasons: TvdbSeasonDetails[];
episodes: TvdbEpisode[];
}
interface TvdbCompanyType {
companyTypeId: number;
companyTypeName: string;
}
interface TvdbParentCompany {
id?: number;
name?: string;
relation?: {
id?: number;
typeName?: string;
};
}
interface TvdbCompany {
id: number;
name: string;
slug: string;
nameTranslations?: string[];
overviewTranslations?: string[];
aliases?: string[];
country: string;
primaryCompanyType: number;
activeDate: string;
inactiveDate?: string;
companyType: TvdbCompanyType;
parentCompany: TvdbParentCompany;
tagOptions?: string[];
}
interface TvdbType {
id: number;
name: string;
type: string;
alternateName?: string;
}
interface TvdbArtwork {
id: number;
image: string;
thumbnail: string;
language: string;
type: number;
score: number;
width: number;
height: number;
includesText: boolean;
}
export interface TvdbEpisode {
id: number;
seriesId: number;
name: string;
aired: string;
runtime: number;
nameTranslations: string[];
overview?: string;
overviewTranslations: string[];
image: string;
imageType: number;
isMovie: number;
seasons?: string[];
number: number;
absoluteNumber: number;
seasonNumber: number;
lastUpdated: string;
finaleType?: string;
year: string;
}
export interface TvdbSeasonDetails {
id: number;
seriesId: number;
type: TvdbType;
number: number;
nameTranslations: string[];
overviewTranslations: string[];
image: string;
imageType: number;
companies: {
studio: TvdbCompany[];
network: TvdbCompany[];
production: TvdbCompany[];
distributor: TvdbCompany[];
special_effects: TvdbCompany[];
};
lastUpdated: string;
year: string;
episodes: TvdbEpisode[];
trailers: string[];
artwork: TvdbArtwork[];
tagOptions?: string[];
firstAired: string;
}
export interface TvdbEpisodeTranslation {
name: string;
overview: string;
language: string;
}
const TMDB_TO_TVDB_MAPPING: Record<string, string> & {
[key in AvailableLocale]: string;
} = {
ar: 'ara', // Arabic
bg: 'bul', // Bulgarian
ca: 'cat', // Catalan
cs: 'ces', // Czech
da: 'dan', // Danish
de: 'deu', // German
el: 'ell', // Greek
en: 'eng', // English
es: 'spa', // Spanish
fi: 'fin', // Finnish
fr: 'fra', // French
he: 'heb', // Hebrew
hi: 'hin', // Hindi
hr: 'hrv', // Croatian
hu: 'hun', // Hungarian
it: 'ita', // Italian
ja: 'jpn', // Japanese
ko: 'kor', // Korean
lt: 'lit', // Lithuanian
nl: 'nld', // Dutch
pl: 'pol', // Polish
ro: 'ron', // Romanian
ru: 'rus', // Russian
sq: 'sqi', // Albanian
sr: 'srp', // Serbian
sv: 'swe', // Swedish
tr: 'tur', // Turkish
uk: 'ukr', // Ukrainian
'es-MX': 'spa', // Spanish (Latin America) -> Spanish
'nb-NO': 'nor', // Norwegian Bokmål -> Norwegian
'pt-BR': 'pt', // Portuguese (Brazil) -> Portuguese - Brazil (from TVDB data)
'pt-PT': 'por', // Portuguese (Portugal) -> Portuguese - Portugal (from TVDB data)
'zh-CN': 'zho', // Chinese (Simplified) -> Chinese - China
'zh-TW': 'zhtw', // Chinese (Traditional) -> Chinese - Taiwan
};
export function convertTMDBToTVDB(tmdbCode: string): string | null {
const normalizedCode = tmdbCode.toLowerCase();
return (
TMDB_TO_TVDB_MAPPING[tmdbCode] ||
TMDB_TO_TVDB_MAPPING[normalizedCode] ||
null
);
}
export function convertTmdbLanguageToTvdbWithFallback(
tmdbCode: string,
fallback: string
): string {
// First try exact match
const tvdbCode = convertTMDBToTVDB(tmdbCode);
if (tvdbCode) return tvdbCode;
return tvdbCode || fallback || 'eng'; // Default to English if no match found
}

View File

@@ -0,0 +1,27 @@
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
import { User } from './User';
@Entity('linked_accounts')
export class LinkedAccount {
constructor(options: Omit<LinkedAccount, 'id'>) {
Object.assign(this, options);
}
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(() => User, (user) => user.linkedAccounts, { onDelete: 'CASCADE' })
user: User;
/** Slug of the OIDC provider. */
@Column({ type: 'varchar', length: 255 })
provider: string;
/** Unique ID from the OAuth provider */
@Column({ type: 'varchar', length: 255 })
sub: string;
/** Account username from the OAuth provider */
@Column()
username: string;
}

View File

@@ -1,6 +1,7 @@
import { MediaRequestStatus, MediaType } from '@server/constants/media';
import { UserType } from '@server/constants/user';
import { getRepository } from '@server/datasource';
import { LinkedAccount } from '@server/entity/LinkedAccount';
import { Watchlist } from '@server/entity/Watchlist';
import type { QuotaResponse } from '@server/interfaces/api/userInterfaces';
import PreparedEmail from '@server/lib/email';
@@ -91,6 +92,9 @@ export class User {
@Column({ type: 'varchar', nullable: true, select: false })
public plexToken?: string | null;
@OneToMany(() => LinkedAccount, (link) => link.user)
public linkedAccounts: LinkedAccount[];
@Column({ type: 'integer', default: 0 })
public permissions = 0;

View File

@@ -25,6 +25,7 @@ import imageproxy from '@server/routes/imageproxy';
import { appDataPermissions } from '@server/utils/appDataVolume';
import { getAppVersion } from '@server/utils/appVersion';
import createCustomProxyAgent from '@server/utils/customProxyAgent';
import { initializeDnsCache } from '@server/utils/dnsCache';
import restartFlag from '@server/utils/restartFlag';
import { getClientIp } from '@supercharge/request-ip';
import axios from 'axios';
@@ -80,6 +81,14 @@ app
axios.defaults.httpsAgent = new https.Agent({ family: 4 });
}
// Add DNS caching
if (settings.network.dnsCache) {
initializeDnsCache({
forceMinTtl: settings.network.dnsCache.forceMinTtl,
forceMaxTtl: settings.network.dnsCache.forceMaxTtl,
});
}
// Register HTTP proxy
if (settings.network.proxy.enabled) {
await createCustomProxyAgent(settings.network.proxy);

View File

@@ -0,0 +1,239 @@
/**
* @internal
*/
type Mandatory<T, K extends keyof T> = Required<Pick<T, K>> & Omit<T, K>;
/**
* Standard OpenID Connect discovery document.
*
* @public
* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
*/
export interface OidcProviderMetadata {
issuer: string; // REQUIRED
authorization_endpoint: string; // REQUIRED
token_endpoint: string; // REQUIRED
token_endpoint_auth_methods_supported?: string[]; // OPTIONAL
token_endpoint_auth_signing_alg_values_supported?: string[]; // OPTIONAL
userinfo_endpoint: string; // RECOMMENDED
check_session_iframe: string; // REQUIRED
end_session_endpoint: string; // REQUIRED
jwks_uri: string; // REQUIRED
registration_endpoint: string; // RECOMMENDED
scopes_supported: string[]; // RECOMMENDED
response_types_supported: string[]; // REQUIRED
acr_values_supported?: string[]; // OPTIONAL
subject_types_supported: string[]; // REQUIRED
request_object_signing_alg_values_supported?: string[]; // OPTIONAL
display_values_supported?: string[]; // OPTIONAL
claim_types_supported?: string[]; // OPTIONAL
claims_supported: string[]; // RECOMMENDED
claims_parameter_supported?: boolean; // OPTIONAL
service_documentation?: string; // OPTIONAL
ui_locales_supported?: string[]; // OPTIONAL
revocation_endpoint: string; // REQUIRED
introspection_endpoint: string; // REQUIRED
frontchannel_logout_supported?: boolean; // OPTIONAL
frontchannel_logout_session_supported?: boolean; // OPTIONAL
backchannel_logout_supported?: boolean; // OPTIONAL
backchannel_logout_session_supported?: boolean; // OPTIONAL
grant_types_supported?: string[]; // OPTIONAL
response_modes_supported?: string[]; // OPTIONAL
code_challenge_methods_supported?: string[]; // OPTIONAL
}
/**
* Standard OpenID Connect address claim.
* The Address Claim represents a physical mailing address.
*
* @public
* @see https://openid.net/specs/openid-connect-core-1_0.html#AddressClaim
*/
export interface OidcAddressClaim {
/** Full mailing address, formatted for display or use on a mailing label. This field MAY contain multiple lines, separated by newlines. Newlines can be represented either as a carriage return/line feed pair ("\\r\\n") or as a single line feed character ("\\n"). */
formatted?: string;
/** Full street address component, which MAY include house number, street name, Post Office Box, and multi-line extended street address information. This field MAY contain multiple lines, separated by newlines. Newlines can be represented either as a carriage return/line feed pair ("\\r\\n") or as a single line feed character ("\\n"). */
street_address?: string;
/** City or locality component. */
locality?: string;
/** State, province, prefecture, or region component. */
region?: string;
/** Zip code or postal code component. */
postal_code?: string;
/** Country name component. */
country?: string;
}
/**
* Standard OpenID Connect claims.
* They can be requested to be returned either in the UserInfo Response or in the ID Token.
*
* @public
* @see https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
*/
export interface OidcStandardClaims {
/** Subject - Identifier for the End-User at the Issuer. */
sub?: string;
/** End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences. */
name?: string;
/** Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters. */
given_name?: string;
/** Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters. */
family_name?: string;
/** Middle name(s) of the End-User. Note that in some cultures, people can have multiple middle names; all can be present, with the names being separated by space characters. Also note that in some cultures, middle names are not used. */
middle_name?: string;
/** Casual name of the End-User that may or may not be the same as the given_name. For instance, a nickname value of Mike might be returned alongside a given_name value of Michael. */
nickname?: string;
/** Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as \@, /, or whitespace. */
preferred_username?: string;
/** URL of the End-User's profile page. The contents of this Web page SHOULD be about the End-User. */
profile?: string;
/** URL of the End-User's profile picture. This URL MUST refer to an image file (for example, a PNG, JPEG, or GIF image file), rather than to a Web page containing an image. Note that this URL SHOULD specifically reference a profile photo of the End-User suitable for displaying when describing the End-User, rather than an arbitrary photo taken by the End-User. */
picture?: string;
/** URL of the End-User's Web page or blog. This Web page SHOULD contain information published by the End-User or an organization that the End-User is affiliated with. */
website?: string;
/** End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 addr-spec syntax. */
email?: string;
/** True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. */
email_verified?: boolean;
/** End-User's gender. Values defined by this specification are female and male. Other values MAY be used when neither of the defined values are applicable. */
gender?: string;
/** End-User's birthday, represented as an ISO 8601:2004 [ISO86012004] YYYY-MM-DD format. The year MAY be 0000, indicating that it is omitted. To represent only the year, YYYY format is allowed. Note that depending on the underlying platform's date related function, providing just year can result in varying month and day, so the implementers need to take this factor into account to correctly process the dates. */
birthdate?: string;
/** String from zoneinfo [zoneinfo] time zone database representing the End-User's time zone. For example, Europe/Paris or America/Los_Angeles. */
zoneinfo?: string;
/** End-User's locale, represented as a BCP47 [RFC5646] language tag. This is typically an ISO 639-1 Alpha-2 [ISO6391] language code in lowercase and an ISO 3166-1 Alpha-2 [ISO31661] country code in uppercase, separated by a dash. For example, en-US or fr-CA. As a compatibility note, some implementations have used an underscore as the separator rather than a dash, for example, en_US; */
locale?: string;
/** End-User's preferred telephone number. E.164 [E.164] is RECOMMENDED as the format of this Claim, for example, +1 (425) 555-1212 or +56 (2) 687 2400. If the phone number contains an extension, it is RECOMMENDED that the extension be represented using the RFC 3966 [RFC3966] extension syntax, for example, +1 (604) 555-1234;ext=5678. */
phone_number?: string;
/** True if the End-User's phone number has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this phone number was controlled by the End-User at the time the verification was performed. The means by which a phone number is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating. When true, the phone_number Claim MUST be in E.164 format and any extensions MUST be represented in RFC 3966 format. */
phone_number_verified?: boolean;
/** End-User's preferred postal address. The value of the address member is a JSON [RFC4627] structure containing some or all of the members defined in Section 5.1.1. */
address?: OidcAddressClaim;
/** Time the End-User's information was last updated. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. */
updated_at?: number;
}
/**
* Standard JWT claims.
*
* @public
* @see https://datatracker.ietf.org/doc/html/rfc7519#section-4.1
*/
export interface JwtClaims {
[claim: string]: unknown;
/** The "iss" (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The "iss" value is a case-sensitive string containing a StringOrURI value. */
iss?: string;
/** The "sub" (subject) claim identifies the principal that is the subject of the JWT. The claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The "sub" value is a case-sensitive string containing a StringOrURI value. */
sub?: string;
/** The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected. In the general case, the "aud" value is an array of case-sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the "aud" value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. */
aud?: string | string[];
/** The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the "exp" claim requires that the current date/time MUST be before the expiration date/time listed in the "exp" claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. */
exp?: number;
/** The "nbf" (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the "nbf" claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the "nbf" claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. */
nbf?: number;
/** The "iat" (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a NumericDate value. */
iat?: number;
/** The "jti" (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The "jti" claim can be used to prevent the JWT from being replayed. The "jti" value is a case-sensitive string. */
jti?: string;
}
/**
* Standard ID Token claims.
*
* @public
* @see https://openid.net/specs/openid-connect-core-1_0.html#IDToken
*/
export interface IdTokenClaims
extends Mandatory<OidcStandardClaims, 'sub'>,
Mandatory<JwtClaims, 'iss' | 'sub' | 'aud' | 'exp' | 'iat'> {
[claim: string]: unknown;
/** Time when the End-User authentication occurred. Its value is a JSON number representing the number of seconds from 1970-01-01T0:0:0Z as measured in UTC until the date/time. When a max_age request is made or when auth_time is requested as an Essential Claim, then this Claim is REQUIRED; otherwise, its inclusion is OPTIONAL. (The auth_time Claim semantically corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] auth_time response parameter.) */
auth_time?: number;
/** String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed through unmodified from the Authentication Request to the ID Token. If present in the ID Token, Clients MUST verify that the nonce Claim Value is equal to the value of the nonce parameter sent in the Authentication Request. If present in the Authentication Request, Authorization Servers MUST include a nonce Claim in the ID Token with the Claim Value being the nonce value sent in the Authentication Request. Authorization Servers SHOULD perform no other processing on nonce values used. The nonce value is a case sensitive string. */
nonce?: string;
/** Authentication Context Class Reference. String specifying an Authentication Context Class Reference value that identifies the Authentication Context Class that the authentication performed satisfied. The value "0" indicates the End-User authentication did not meet the requirements of ISO/IEC 29115 [ISO29115] level 1. Authentication using a long-lived browser cookie, for instance, is one example where the use of "level 0" is appropriate. Authentications with level 0 SHOULD NOT be used to authorize access to any resource of any monetary value. (This corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] nist_auth_level 0.) An absolute URI or an RFC 6711 [RFC6711] registered name SHOULD be used as the acr value; registered names MUST NOT be used with a different meaning than that which is registered. Parties using this claim will need to agree upon the meanings of the values used, which may be context-specific. The acr value is a case sensitive string. */
acr?: string;
/** Authentication Methods References. JSON array of strings that are identifiers for authentication methods used in the authentication. For instance, values might indicate that both password and OTP authentication methods were used. The definition of particular values to be used in the amr Claim is beyond the scope of this specification. Parties using this claim will need to agree upon the meanings of the values used, which may be context-specific. The amr value is an array of case sensitive strings. */
amr?: unknown;
/** Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value. */
azp?: string;
/**
* Session ID - String identifier for a Session. This represents a Session of a User Agent or device for a logged-in End-User at an RP. Different sid values are used to identify distinct sessions at an OP. The sid value need only be unique in the context of a particular issuer. Its contents are opaque to the RP. Its syntax is the same as an OAuth 2.0 Client Identifier.
* @see https://openid.net/specs/openid-connect-frontchannel-1_0.html#OPLogout
* */
sid?: string;
}
type OidcTokenSuccessResponse = {
/**
* REQUIRED. ID Token value associated with the authenticated session.
*
* @see https://openid.net/specs/openid-connect-core-1_0.html#IDToken
*/
id_token: string;
/**
* REQUIRED. The access token issued by the authorization server.
*/
access_token: string;
/**
* REQUIRED. The type of the token issued as described in
* Section 7.1. Value is case insensitive.
*
* @see https://datatracker.ietf.org/doc/html/rfc6749#section-7.1
*/
token_type: string;
/**
* RECOMMENDED. The lifetime in seconds of the access token. For
* example, the value "3600" denotes that the access token will
* expire in one hour from the time the response was generated.
* If omitted, the authorization server SHOULD provide the
* expiration time via other means or document the default value.
*/
expires_in?: number;
};
type OidcTokenErrorResponse = {
error: string;
};
/**
* Standard response from the OpenID Connect token request endpoint.
*
* @public
* @see https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse
*/
export type OidcTokenResponse =
| OidcTokenSuccessResponse
| OidcTokenErrorResponse;

View File

@@ -1,3 +1,5 @@
import type { PublicOidcProvider } from '@server/lib/settings';
import type { DnsEntries, DnsStats } from 'dns-caching';
import type { PaginatedResponse } from './common';
export type LogMessage = {
@@ -47,6 +49,7 @@ export interface PublicSettingsResponse {
emailEnabled: boolean;
newPlexLogin: boolean;
youtubeUrl: string;
openIdProviders: PublicOidcProvider[];
}
export interface CacheItem {
@@ -64,6 +67,10 @@ export interface CacheItem {
export interface CacheResponse {
apiCaches: CacheItem[];
imageCache: Record<'tmdb' | 'avatar', { size: number; imageCount: number }>;
dnsCache: {
stats: DnsStats | undefined;
entries: DnsEntries | undefined;
};
}
export interface StatusResponse {

View File

@@ -1,4 +1,7 @@
import type { NotificationAgentKey } from '@server/lib/settings';
import type {
NotificationAgentKey,
PublicOidcProvider,
} from '@server/lib/settings';
export interface UserSettingsGeneralResponse {
username?: string;
@@ -39,3 +42,11 @@ export interface UserSettingsNotificationsResponse {
webPushEnabled?: boolean;
notificationTypes: Partial<NotificationAgentTypes>;
}
export type UserSettingsLinkedAccount = {
id: number;
username: string;
provider: PublicOidcProvider;
};
export type UserSettingsLinkedAccountResponse = UserSettingsLinkedAccount[];

View File

@@ -72,6 +72,7 @@ class BlacklistedTagProcessor implements RunnableScanner<StatusBase> {
const blacklistedTagsArr = blacklistedTags.split(',');
const pageLimit = settings.main.blacklistedTagsLimit;
const invalidKeywords = new Set<string>();
if (blacklistedTags.length === 0) {
return;
@@ -87,6 +88,19 @@ class BlacklistedTagProcessor implements RunnableScanner<StatusBase> {
// Iterate for each tag
for (const tag of blacklistedTagsArr) {
const keywordDetails = await tmdb.getKeywordDetails({
keywordId: Number(tag),
});
if (keywordDetails === null) {
logger.warn('Skipping invalid keyword in blacklisted tags', {
label: 'Blacklisted Tags Processor',
keywordId: tag,
});
invalidKeywords.add(tag);
continue;
}
let queryMax = pageLimit * SortOptionsIterable.length;
let fixedSortMode = false; // Set to true when the page limit allows for getting every page of tag
@@ -102,24 +116,51 @@ class BlacklistedTagProcessor implements RunnableScanner<StatusBase> {
throw new AbortTransaction();
}
const response = await getDiscover({
page,
sortBy,
keywords: tag,
});
await this.processResults(response, tag, type, em);
await new Promise((res) => setTimeout(res, TMDB_API_DELAY_MS));
try {
const response = await getDiscover({
page,
sortBy,
keywords: tag,
});
this.progress++;
if (page === 1 && response.total_pages <= queryMax) {
// We will finish the tag with less queries than expected, move progress accordingly
this.progress += queryMax - response.total_pages;
fixedSortMode = true;
queryMax = response.total_pages;
await this.processResults(response, tag, type, em);
await new Promise((res) => setTimeout(res, TMDB_API_DELAY_MS));
this.progress++;
if (page === 1 && response.total_pages <= queryMax) {
// We will finish the tag with less queries than expected, move progress accordingly
this.progress += queryMax - response.total_pages;
fixedSortMode = true;
queryMax = response.total_pages;
}
} catch (error) {
logger.error('Error processing keyword in blacklisted tags', {
label: 'Blacklisted Tags Processor',
keywordId: tag,
errorMessage: error.message,
});
}
}
}
}
if (invalidKeywords.size > 0) {
const currentTags = blacklistedTagsArr.filter(
(tag) => !invalidKeywords.has(tag)
);
const cleanedTags = currentTags.join(',');
if (cleanedTags !== blacklistedTags) {
settings.main.blacklistedTags = cleanedTags;
await settings.save();
logger.info('Cleaned up invalid keywords from settings', {
label: 'Blacklisted Tags Processor',
removedKeywords: Array.from(invalidKeywords),
newBlacklistedTags: cleanedTags,
});
}
}
}
private async processResults(

View File

@@ -9,7 +9,8 @@ export type AvailableCacheIds =
| 'github'
| 'plexguid'
| 'plextv'
| 'plexwatchlist';
| 'plexwatchlist'
| 'tvdb';
const DEFAULT_TTL = 300;
const DEFAULT_CHECK_PERIOD = 120;
@@ -70,6 +71,10 @@ class CacheManager {
checkPeriod: 60,
}),
plexwatchlist: new Cache('plexwatchlist', 'Plex Watchlist'),
tvdb: new Cache('tvdb', 'The TVDB API', {
stdTtl: 21600,
checkPeriod: 60 * 30,
}),
};
public getCache(id: AvailableCacheIds): Cache {

View File

@@ -1,4 +1,5 @@
import logger from '@server/logger';
import { requestInterceptorFunction } from '@server/utils/customProxyAgent';
import axios from 'axios';
import rateLimit, { type rateLimitOptions } from 'axios-rate-limit';
import { createHash } from 'crypto';
@@ -150,8 +151,7 @@ class ImageProxy {
baseURL: baseUrl,
headers: options.headers,
});
this.axios.interceptors.request = axios.interceptors.request;
this.axios.interceptors.response = axios.interceptors.response;
this.axios.interceptors.request.use(requestInterceptorFunction);
if (options.rateLimitOptions) {
this.axios = rateLimit(this.axios, options.rateLimitOptions);

View File

@@ -109,7 +109,9 @@ class DiscordAgent
type: Notification,
payload: NotificationPayload
): DiscordRichEmbed {
const { applicationUrl } = getSettings().main;
const settings = getSettings();
const { applicationUrl } = settings.main;
const { embedPoster } = settings.notifications.agents.discord;
const appUrl =
applicationUrl || `http://localhost:${process.env.port || 5055}`;
@@ -223,9 +225,11 @@ class DiscordAgent
}
: undefined,
fields,
thumbnail: {
url: payload.image,
},
thumbnail: embedPoster
? {
url: payload.image,
}
: undefined,
};
}

View File

@@ -48,7 +48,9 @@ class EmailAgent
recipientEmail: string,
recipientName?: string
): EmailOptions | undefined {
const { applicationUrl, applicationTitle } = getSettings().main;
const settings = getSettings();
const { applicationUrl, applicationTitle } = settings.main;
const { embedPoster } = settings.notifications.agents.email;
if (type === Notification.TEST_NOTIFICATION) {
return {
@@ -129,7 +131,7 @@ class EmailAgent
body,
mediaName: payload.subject,
mediaExtra: payload.extra ?? [],
imageUrl: payload.image,
imageUrl: embedPoster ? payload.image : undefined,
timestamp: new Date().toTimeString(),
requestedBy: payload.request.requestedBy.displayName,
actionUrl: applicationUrl
@@ -176,7 +178,7 @@ class EmailAgent
issueComment: payload.comment?.message,
mediaName: payload.subject,
extra: payload.extra ?? [],
imageUrl: payload.image,
imageUrl: embedPoster ? payload.image : undefined,
timestamp: new Date().toTimeString(),
actionUrl: applicationUrl
? `${applicationUrl}/issues/${payload.issue.id}`

View File

@@ -22,7 +22,9 @@ class NtfyAgent
}
private buildPayload(type: Notification, payload: NotificationPayload) {
const { applicationUrl } = getSettings().main;
const settings = getSettings();
const { applicationUrl } = settings.main;
const { embedPoster } = settings.notifications.agents.ntfy;
const topic = this.getSettings().options.topic;
const priority = 3;
@@ -72,7 +74,7 @@ class NtfyAgent
message += `\n\n**${extra.name}**\n${extra.value}`;
}
const attach = payload.image;
const attach = embedPoster ? payload.image : undefined;
let click;
if (applicationUrl && payload.media) {

View File

@@ -78,7 +78,9 @@ class PushoverAgent
type: Notification,
payload: NotificationPayload
): Promise<Partial<PushoverPayload>> {
const { applicationUrl, applicationTitle } = getSettings().main;
const settings = getSettings();
const { applicationUrl, applicationTitle } = settings.main;
const { embedPoster } = settings.notifications.agents.pushover;
const title = payload.event ?? payload.subject;
let message = payload.event ? `<b>${payload.subject}</b>` : '';
@@ -155,7 +157,7 @@ class PushoverAgent
let attachment_base64;
let attachment_type;
if (payload.image) {
if (embedPoster && payload.image) {
const imagePayload = await this.getImagePayload(payload.image);
if (imagePayload.attachment_base64 && imagePayload.attachment_type) {
attachment_base64 = imagePayload.attachment_base64;

View File

@@ -63,7 +63,9 @@ class SlackAgent
type: Notification,
payload: NotificationPayload
): SlackBlockEmbed {
const { applicationUrl, applicationTitle } = getSettings().main;
const settings = getSettings();
const { applicationUrl, applicationTitle } = settings.main;
const { embedPoster } = settings.notifications.agents.slack;
const fields: EmbedField[] = [];
@@ -159,13 +161,14 @@ class SlackAgent
type: 'mrkdwn',
text: payload.message,
},
accessory: payload.image
? {
type: 'image',
image_url: payload.image,
alt_text: payload.subject,
}
: undefined,
accessory:
embedPoster && payload.image
? {
type: 'image',
image_url: payload.image,
alt_text: payload.subject,
}
: undefined,
});
}

View File

@@ -65,7 +65,9 @@ class TelegramAgent
type: Notification,
payload: NotificationPayload
): Partial<TelegramMessagePayload | TelegramPhotoPayload> {
const { applicationUrl, applicationTitle } = getSettings().main;
const settings = getSettings();
const { applicationUrl, applicationTitle } = settings.main;
const { embedPoster } = settings.notifications.agents.telegram;
/* eslint-disable no-useless-escape */
let message = `\*${this.escapeText(
@@ -142,7 +144,7 @@ class TelegramAgent
}
/* eslint-enable */
return payload.image
return embedPoster && payload.image
? {
photo: payload.image,
caption: message,
@@ -160,7 +162,7 @@ class TelegramAgent
): Promise<boolean> {
const settings = this.getSettings();
const endpoint = `${this.baseUrl}bot${settings.options.botAPI}/${
payload.image ? 'sendPhoto' : 'sendMessage'
settings.embedPoster && payload.image ? 'sendPhoto' : 'sendMessage'
}`;
const notificationPayload = this.getNotificationPayload(type, payload);

View File

@@ -42,6 +42,8 @@ class WebPushAgent
type: Notification,
payload: NotificationPayload
): PushNotificationPayload {
const { embedPoster } = getSettings().notifications.agents.webpush;
const mediaType = payload.media
? payload.media.mediaType === MediaType.MOVIE
? 'movie'
@@ -128,7 +130,7 @@ class WebPushAgent
notificationType: Notification[type],
subject: payload.subject,
message,
image: payload.image,
image: embedPoster ? payload.image : undefined,
requestId: payload.request?.id,
actionUrl,
actionUrlTitle,

View File

@@ -1,7 +1,12 @@
import type { JellyfinLibraryItem } from '@server/api/jellyfin';
import JellyfinAPI from '@server/api/jellyfin';
import { getMetadataProvider } from '@server/api/metadata';
import TheMovieDb from '@server/api/themoviedb';
import type { TmdbTvDetails } from '@server/api/themoviedb/interfaces';
import { ANIME_KEYWORD_ID } from '@server/api/themoviedb/constants';
import type {
TmdbKeyword,
TmdbTvDetails,
} from '@server/api/themoviedb/interfaces';
import { MediaStatus, MediaType } from '@server/constants/media';
import { MediaServerType } from '@server/constants/server';
import { getRepository } from '@server/datasource';
@@ -43,6 +48,7 @@ class JellyfinScanner {
constructor({ isRecentOnly }: { isRecentOnly?: boolean } = {}) {
this.tmdb = new TheMovieDb();
this.isRecentOnly = isRecentOnly ?? false;
}
@@ -192,6 +198,42 @@ class JellyfinScanner {
}
}
private async getTvShow({
tmdbId,
tvdbId,
}: {
tmdbId?: number;
tvdbId?: number;
}): Promise<TmdbTvDetails> {
let tvShow;
if (tmdbId) {
tvShow = await this.tmdb.getTvShow({
tvId: Number(tmdbId),
});
} else if (tvdbId) {
tvShow = await this.tmdb.getShowByTvdbId({
tvdbId: Number(tvdbId),
});
} else {
throw new Error('No ID provided');
}
const metadataProvider = tvShow.keywords.results.some(
(keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID
)
? await getMetadataProvider('anime')
: await getMetadataProvider('tv');
if (!(metadataProvider instanceof TheMovieDb)) {
tvShow = await metadataProvider.getTvShow({
tvId: Number(tmdbId),
});
}
return tvShow;
}
private async processShow(jellyfinitem: JellyfinLibraryItem) {
const mediaRepository = getRepository(Media);
@@ -212,8 +254,8 @@ class JellyfinScanner {
if (metadata.ProviderIds.Tmdb) {
try {
tvShow = await this.tmdb.getTvShow({
tvId: Number(metadata.ProviderIds.Tmdb),
tvShow = await this.getTvShow({
tmdbId: Number(metadata.ProviderIds.Tmdb),
});
} catch {
this.log('Unable to find TMDb ID for this title.', 'debug', {
@@ -223,7 +265,7 @@ class JellyfinScanner {
}
if (!tvShow && metadata.ProviderIds.Tvdb) {
try {
tvShow = await this.tmdb.getShowByTvdbId({
tvShow = await this.getTvShow({
tvdbId: Number(metadata.ProviderIds.Tvdb),
});
} catch {

View File

@@ -1,7 +1,13 @@
import animeList from '@server/api/animelist';
import { getMetadataProvider } from '@server/api/metadata';
import type { PlexLibraryItem, PlexMetadata } from '@server/api/plexapi';
import PlexAPI from '@server/api/plexapi';
import type { TmdbTvDetails } from '@server/api/themoviedb/interfaces';
import TheMovieDb from '@server/api/themoviedb';
import { ANIME_KEYWORD_ID } from '@server/api/themoviedb/constants';
import type {
TmdbKeyword,
TmdbTvDetails,
} from '@server/api/themoviedb/interfaces';
import { getRepository } from '@server/datasource';
import { User } from '@server/entity/User';
import cacheManager from '@server/lib/cache';
@@ -249,6 +255,42 @@ class PlexScanner
});
}
private async getTvShow({
tmdbId,
tvdbId,
}: {
tmdbId?: number;
tvdbId?: number;
}): Promise<TmdbTvDetails> {
let tvShow;
if (tmdbId) {
tvShow = await this.tmdb.getTvShow({
tvId: Number(tmdbId),
});
} else if (tvdbId) {
tvShow = await this.tmdb.getShowByTvdbId({
tvdbId: Number(tvdbId),
});
} else {
throw new Error('No ID provided');
}
const metadataProvider = tvShow.keywords.results.some(
(keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID
)
? await getMetadataProvider('anime')
: await getMetadataProvider('tv');
if (!(metadataProvider instanceof TheMovieDb)) {
tvShow = await metadataProvider.getTvShow({
tvId: Number(tmdbId),
});
}
return tvShow;
}
private async processPlexShow(plexitem: PlexLibraryItem) {
const ratingKey =
plexitem.grandparentRatingKey ??
@@ -273,7 +315,9 @@ class PlexScanner
await this.processHamaSpecials(metadata, mediaIds.tvdbId);
}
const tvShow = await this.tmdb.getTvShow({ tvId: mediaIds.tmdbId });
const tvShow = await this.getTvShow({
tmdbId: mediaIds.tmdbId,
});
const seasons = tvShow.seasons;
const processableSeasons: ProcessableSeason[] = [];

View File

@@ -49,6 +49,25 @@ export interface JellyfinSettings {
serverId: string;
apiKey: string;
}
export type OidcProvider = {
slug: string;
name: string;
issuerUrl: string;
clientId: string;
clientSecret: string;
logo?: string;
requiredClaims?: string;
scopes?: string;
newUserLogin?: boolean;
};
export type PublicOidcProvider = Pick<OidcProvider, 'slug' | 'name' | 'logo'>;
export interface OidcSettings {
providers: OidcProvider[];
}
export interface TautulliSettings {
hostname?: string;
port?: number;
@@ -100,6 +119,16 @@ interface Quota {
quotaDays?: number;
}
export enum MetadataProviderType {
TMDB = 'tmdb',
TVDB = 'tvdb',
}
export interface MetadataSettings {
tv: MetadataProviderType;
anime: MetadataProviderType;
}
export interface ProxySettings {
enabled: boolean;
hostname: string;
@@ -125,6 +154,7 @@ export interface MainSettings {
hideBlacklisted: boolean;
localLogin: boolean;
mediaServerLogin: boolean;
oidcLogin: boolean;
newPlexLogin: boolean;
discoverRegion: string;
streamingRegion: string;
@@ -138,11 +168,29 @@ export interface MainSettings {
youtubeUrl: string;
}
export interface ProxySettings {
enabled: boolean;
hostname: string;
port: number;
useSsl: boolean;
user: string;
password: string;
bypassFilter: string;
bypassLocalAddresses: boolean;
}
export interface DnsCacheSettings {
enabled: boolean;
forceMinTtl?: number;
forceMaxTtl?: number;
}
export interface NetworkSettings {
csrfProtection: boolean;
forceIpv4First: boolean;
trustProxy: boolean;
proxy: ProxySettings;
dnsCache: DnsCacheSettings;
}
interface PublicSettings {
@@ -175,10 +223,12 @@ interface FullPublicSettings extends PublicSettings {
userEmailRequired: boolean;
newPlexLogin: boolean;
youtubeUrl: string;
openIdProviders: PublicOidcProvider[];
}
export interface NotificationAgentConfig {
enabled: boolean;
embedPoster: boolean;
types?: number;
options: Record<string, unknown>;
}
@@ -325,6 +375,7 @@ export interface AllSettings {
main: MainSettings;
plex: PlexSettings;
jellyfin: JellyfinSettings;
oidc: OidcSettings;
tautulli: TautulliSettings;
radarr: RadarrSettings[];
sonarr: SonarrSettings[];
@@ -332,6 +383,7 @@ export interface AllSettings {
notifications: NotificationSettings;
jobs: Record<JobId, JobSettings>;
network: NetworkSettings;
metadataSettings: MetadataSettings;
}
const SETTINGS_PATH = process.env.CONFIG_DIRECTORY
@@ -360,6 +412,7 @@ class Settings {
hideBlacklisted: false,
localLogin: true,
mediaServerLogin: true,
oidcLogin: false,
newPlexLogin: true,
discoverRegion: '',
streamingRegion: '',
@@ -391,7 +444,14 @@ class Settings {
serverId: '',
apiKey: '',
},
oidc: {
providers: [],
},
tautulli: {},
metadataSettings: {
tv: MetadataProviderType.TMDB,
anime: MetadataProviderType.TMDB,
},
radarr: [],
sonarr: [],
public: {
@@ -401,6 +461,7 @@ class Settings {
agents: {
email: {
enabled: false,
embedPoster: true,
options: {
userEmailRequired: false,
emailFrom: '',
@@ -415,6 +476,7 @@ class Settings {
},
discord: {
enabled: false,
embedPoster: true,
types: 0,
options: {
webhookUrl: '',
@@ -424,6 +486,7 @@ class Settings {
},
slack: {
enabled: false,
embedPoster: true,
types: 0,
options: {
webhookUrl: '',
@@ -431,6 +494,7 @@ class Settings {
},
telegram: {
enabled: false,
embedPoster: true,
types: 0,
options: {
botAPI: '',
@@ -441,6 +505,7 @@ class Settings {
},
pushbullet: {
enabled: false,
embedPoster: false,
types: 0,
options: {
accessToken: '',
@@ -448,6 +513,7 @@ class Settings {
},
pushover: {
enabled: false,
embedPoster: true,
types: 0,
options: {
accessToken: '',
@@ -457,6 +523,7 @@ class Settings {
},
webhook: {
enabled: false,
embedPoster: true,
types: 0,
options: {
webhookUrl: '',
@@ -466,10 +533,12 @@ class Settings {
},
webpush: {
enabled: false,
embedPoster: true,
options: {},
},
gotify: {
enabled: false,
embedPoster: false,
types: 0,
options: {
url: '',
@@ -479,6 +548,7 @@ class Settings {
},
ntfy: {
enabled: false,
embedPoster: true,
types: 0,
options: {
url: '',
@@ -542,6 +612,11 @@ class Settings {
bypassFilter: '',
bypassLocalAddresses: true,
},
dnsCache: {
enabled: false,
forceMinTtl: 0,
forceMaxTtl: -1,
},
},
};
if (initialSettings) {
@@ -573,6 +648,14 @@ class Settings {
this.data.jellyfin = data;
}
get oidc(): OidcSettings {
return this.data.oidc;
}
set oidc(data: OidcSettings) {
this.data.oidc = data;
}
get tautulli(): TautulliSettings {
return this.data.tautulli;
}
@@ -581,6 +664,14 @@ class Settings {
this.data.tautulli = data;
}
get metadataSettings(): MetadataSettings {
return this.data.metadataSettings;
}
set metadataSettings(data: MetadataSettings) {
this.data.metadataSettings = data;
}
get radarr(): RadarrSettings[] {
return this.data.radarr;
}
@@ -637,6 +728,13 @@ class Settings {
this.data.notifications.agents.email.options.userEmailRequired,
newPlexLogin: this.data.main.newPlexLogin,
youtubeUrl: this.data.main.youtubeUrl,
openIdProviders: this.data.main.oidcLogin
? this.data.oidc.providers.map((p) => ({
slug: p.slug,
name: p.name,
logo: p.logo,
}))
: [],
};
}

View File

@@ -0,0 +1,21 @@
import type { MigrationInterface, QueryRunner } from 'typeorm';
export class AddLinkedAccount1742858617989 implements MigrationInterface {
name = 'AddLinkedAccount1742858617989';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "linked_accounts" ("id" SERIAL NOT NULL, "provider" character varying(255) NOT NULL, "sub" character varying(255) NOT NULL, "username" character varying NOT NULL, "userId" integer, CONSTRAINT "PK_445bf7a50aeeb7f0084052935a6" PRIMARY KEY ("id"))`
);
await queryRunner.query(
`ALTER TABLE "linked_accounts" ADD CONSTRAINT "FK_2c77d2a0c06eeab6e62dc35af64" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE NO ACTION`
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "linked_accounts" DROP CONSTRAINT "FK_2c77d2a0c06eeab6e62dc35af64"`
);
await queryRunner.query(`DROP TABLE "linked_accounts"`);
}
}

View File

@@ -0,0 +1,15 @@
import type { MigrationInterface, QueryRunner } from 'typeorm';
export class AddLinkedAccounts1742858484395 implements MigrationInterface {
name = 'AddLinkedAccounts1742858484395';
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "linked_accounts" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "provider" varchar(255) NOT NULL, "sub" varchar(255) NOT NULL, "username" varchar NOT NULL, "userId" integer, CONSTRAINT "FK_2c77d2a0c06eeab6e62dc35af64" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "linked_accounts"`);
}
}

View File

@@ -124,7 +124,7 @@ const mapEpisodeResult = (episode: TmdbTvEpisodeResult): Episode => ({
seasonNumber: episode.season_number,
showId: episode.show_id,
voteAverage: episode.vote_average,
voteCount: episode.vote_cuont,
voteCount: episode.vote_count,
stillPath: episode.still_path,
});

View File

@@ -4,7 +4,9 @@ import { ApiErrorCode } from '@server/constants/error';
import { MediaServerType, ServerType } from '@server/constants/server';
import { UserType } from '@server/constants/user';
import { getRepository } from '@server/datasource';
import { LinkedAccount } from '@server/entity/LinkedAccount';
import { User } from '@server/entity/User';
import type { IdTokenClaims } from '@server/interfaces/api/oidcInterfaces';
import { startJobs } from '@server/job/schedule';
import { Permission } from '@server/lib/permissions';
import { getSettings } from '@server/lib/settings';
@@ -14,9 +16,21 @@ import { checkAvatarChanged } from '@server/routes/avatarproxy';
import { ApiError } from '@server/types/error';
import { getAppVersion } from '@server/utils/appVersion';
import { getHostname } from '@server/utils/getHostname';
import {
createIdTokenSchema,
fetchOpenIdTokenData,
getOpenIdConfiguration,
getOpenIdRedirectUrl,
getOpenIdUserInfo,
validateUserClaims,
type FullUserInfo,
} from '@server/utils/oidc';
import axios from 'axios';
import { randomBytes } from 'crypto';
import * as EmailValidator from 'email-validator';
import { Router } from 'express';
import gravatarUrl from 'gravatar-url';
import { jwtDecode } from 'jwt-decode';
import net from 'net';
const authRoutes = Router();
@@ -721,6 +735,287 @@ authRoutes.post('/local', async (req, res, next) => {
}
});
authRoutes.get('/oidc/login/:slug', async (req, res, next) => {
const settings = getSettings();
const provider = settings.oidc.providers.find(
(p) => p.slug === req.params.slug
);
if (!settings.main.oidcLogin || !provider) {
return next({
status: 403,
message: 'OpenID Connect sign-in is disabled.',
});
}
const state = randomBytes(32).toString('hex');
let redirectUrl;
try {
redirectUrl = await getOpenIdRedirectUrl(req, provider, state);
} catch (err) {
logger.info('Failed OpenID Connect login attempt', {
cause: 'Failed to fetch OpenID Connect redirect url',
ip: req.ip,
errorMessage: err.message,
});
return next({
status: 500,
message: 'Configuration error.',
});
}
res.cookie('oidc-state', state, {
maxAge: 60000,
httpOnly: true,
secure: req.protocol === 'https',
});
return res.status(200).json({
redirectUrl,
});
});
authRoutes.get('/oidc/callback/:slug', async (req, res, next) => {
const settings = getSettings();
const provider = settings.oidc.providers.find(
(p) => p.slug === req.params.slug
);
if (!settings.main.oidcLogin || !provider) {
return next({
status: 403,
message: 'OpenID Connect sign-in is disabled',
});
}
const requiredClaims = (provider.requiredClaims ?? '')
.split(' ')
.filter((s) => !!s);
const cookieState = req.cookies['oidc-state'];
const url = new URL(req.url, `${req.protocol}://${req.hostname}`);
const state = url.searchParams.get('state');
try {
// Check that the request belongs to the correct state
if (state && cookieState === state) {
res.clearCookie('oidc-state');
} else {
logger.info('Failed OpenID Connect login attempt', {
cause: 'Invalid state',
ip: req.ip,
state: state,
cookieState: cookieState,
});
return next({
status: 400,
message: 'Authorization failed',
});
}
// Check that a code has been issued
const code = url.searchParams.get('code');
if (!code) {
logger.info('Failed OpenID Connect login attempt', {
cause: 'Invalid code',
ip: req.ip,
code: code,
});
return next({
status: 400,
message: 'Authorization failed',
});
}
const wellKnownInfo = await getOpenIdConfiguration(provider.issuerUrl);
// Fetch the token data
const body = await fetchOpenIdTokenData(req, provider, wellKnownInfo, code);
// Validate that the token response is valid and not manipulated
if ('error' in body) {
logger.info('Failed OIDC login attempt', {
cause: 'Invalid token response',
ip: req.ip,
body: body,
});
return next({
status: 400,
message: 'Authorization failed',
});
}
// Extract the ID token and access token
const { id_token: idToken, access_token: accessToken } = body;
// Attempt to decode ID token jwt
let decoded: IdTokenClaims;
try {
decoded = jwtDecode(idToken);
} catch (err) {
logger.info('Failed OIDC login attempt', {
cause: 'Invalid jwt',
ip: req.ip,
idToken: idToken,
err,
});
return next({
status: 400,
message: 'Authorization failed',
});
}
// Merge claims from JWT with data from userinfo endpoint
const userInfo = await getOpenIdUserInfo(wellKnownInfo, accessToken);
const fullUserInfo: FullUserInfo = { ...decoded, ...userInfo };
// Validate ID token jwt and user info
try {
const idTokenSchema = createIdTokenSchema({
oidcClientId: provider.clientId,
oidcDomain: provider.issuerUrl,
requiredClaims,
});
await idTokenSchema.validate(fullUserInfo);
} catch (err) {
logger.info('Failed OIDC login attempt', {
cause: 'Invalid jwt or missing claims',
ip: req.ip,
idToken: idToken,
errorMessage: err.message,
});
return next({
status: 403,
message: 'Authorization failed',
});
}
// Validate that user meets required claims
try {
validateUserClaims(fullUserInfo, requiredClaims);
} catch (error) {
logger.info('Failed OIDC login attempt', {
cause: 'Failed to validate required claims',
error,
ip: req.ip,
requiredClaims: provider.requiredClaims,
});
return next({
status: 403,
message: 'Insufficient permissions',
});
}
// Map identifier to linked account
const userRepository = getRepository(User);
const linkedAccountsRepository = getRepository(LinkedAccount);
const linkedAccount = await linkedAccountsRepository.findOne({
relations: {
user: true,
},
where: {
provider: provider.slug,
sub: fullUserInfo.sub,
},
});
let user = linkedAccount?.user;
// If there is already a user logged in, and no linked account, link the account.
if (req.user != null && linkedAccount == null) {
const linkedAccount = new LinkedAccount({
user: req.user,
provider: provider.slug,
sub: fullUserInfo.sub,
username: fullUserInfo.preferred_username ?? req.user.displayName,
});
await linkedAccountsRepository.save(linkedAccount);
return res
.status(200)
.json({ status: 'ok', to: '/profile/settings/linked-accounts' });
}
// Create user if one doesn't already exist
if (!user && fullUserInfo.email != null && provider.newUserLogin) {
// Check if a user with this email already exists
const existingUser = await userRepository.findOne({
where: { email: fullUserInfo.email },
});
if (existingUser) {
// If a user with the email exists, throw a 409 Conflict error
return next({
status: 409,
message: 'A user with this email address already exists.',
});
}
logger.info(`Creating user for ${fullUserInfo.email}`, {
ip: req.ip,
email: fullUserInfo.email,
});
const avatar =
fullUserInfo.picture ??
gravatarUrl(fullUserInfo.email, { default: 'mm', size: 200 });
user = new User({
avatar: avatar,
username: fullUserInfo.preferred_username,
email: fullUserInfo.email,
permissions: settings.main.defaultPermissions,
plexToken: '',
userType: UserType.LOCAL,
});
await userRepository.save(user);
const linkedAccount = new LinkedAccount({
user,
provider: provider.slug,
sub: fullUserInfo.sub,
username: fullUserInfo.preferred_username ?? fullUserInfo.email,
});
await linkedAccountsRepository.save(linkedAccount);
user.linkedAccounts = [linkedAccount];
await userRepository.save(user);
}
if (!user) {
logger.debug('Failed OIDC sign-up attempt', {
cause: provider.newUserLogin
? 'User did not have an account, and was missing an associated email address.'
: 'User did not have an account, and new user login was disabled.',
});
return next({
status: 400,
message: provider.newUserLogin
? 'Unable to create new user account (missing email address)'
: 'Unable to create new user account (new user login is disabled)',
});
}
// Set logged in session and return
if (req.session) {
req.session.userId = user.id;
}
// Success!
return res.status(200).json({ status: 'ok', to: '/' });
} catch (error) {
logger.error('Failed OIDC login attempt', {
cause: 'Unknown error',
ip: req.ip,
error,
});
return next({
status: 500,
message: 'An unknown error occurred',
});
}
});
authRoutes.post('/logout', async (req, res, next) => {
try {
const userId = req.session?.userId;

View File

@@ -128,11 +128,15 @@ discoverRoutes.get('/movies', async (req, res, next) => {
if (keywords) {
const splitKeywords = keywords.split(',');
keywordData = await Promise.all(
const keywordResults = await Promise.all(
splitKeywords.map(async (keywordId) => {
return await tmdb.getKeywordDetails({ keywordId: Number(keywordId) });
})
);
keywordData = keywordResults.filter(
(keyword): keyword is TmdbKeyword => keyword !== null
);
}
return res.status(200).json({
@@ -415,11 +419,15 @@ discoverRoutes.get('/tv', async (req, res, next) => {
if (keywords) {
const splitKeywords = keywords.split(',');
keywordData = await Promise.all(
const keywordResults = await Promise.all(
splitKeywords.map(async (keywordId) => {
return await tmdb.getKeywordDetails({ keywordId: Number(keywordId) });
})
);
keywordData = keywordResults.filter(
(keyword): keyword is TmdbKeyword => keyword !== null
);
}
return res.status(200).json({

View File

@@ -4,27 +4,40 @@ import { Router } from 'express';
const router = Router();
const tmdbImageProxy = new ImageProxy('tmdb', 'https://image.tmdb.org', {
rateLimitOptions: {
maxRequests: 20,
maxRPS: 50,
},
});
const tvdbImageProxy = new ImageProxy('tvdb', 'https://artworks.thetvdb.com', {
rateLimitOptions: {
maxRequests: 20,
maxRPS: 50,
},
});
// Delay the initialization of ImageProxy instances until the proxy (if any) is properly configured
let _tmdbImageProxy: ImageProxy;
function initTmdbImageProxy() {
if (!_tmdbImageProxy) {
_tmdbImageProxy = new ImageProxy('tmdb', 'https://image.tmdb.org', {
rateLimitOptions: {
maxRequests: 20,
maxRPS: 50,
},
});
}
return _tmdbImageProxy;
}
let _tvdbImageProxy: ImageProxy;
function initTvdbImageProxy() {
if (!_tvdbImageProxy) {
_tvdbImageProxy = new ImageProxy('tvdb', 'https://artworks.thetvdb.com', {
rateLimitOptions: {
maxRequests: 20,
maxRPS: 50,
},
});
}
return _tvdbImageProxy;
}
router.get('/:type/*', async (req, res) => {
const imagePath = req.path.replace(/^\/\w+/, '');
try {
let imageData;
if (req.params.type === 'tmdb') {
imageData = await tmdbImageProxy.getImage(imagePath);
imageData = await initTmdbImageProxy().getImage(imagePath);
} else if (req.params.type === 'tvdb') {
imageData = await tvdbImageProxy.getImage(imagePath);
imageData = await initTvdbImageProxy().getImage(imagePath);
} else {
logger.error('Unsupported image type', {
imagePath,

View File

@@ -54,6 +54,7 @@ issueRoutes.get<Record<string, string>, IssueResultsResponse>(
.leftJoinAndSelect('issue.createdBy', 'createdBy')
.leftJoinAndSelect('issue.media', 'media')
.leftJoinAndSelect('issue.modifiedBy', 'modifiedBy')
.leftJoinAndSelect('issue.comments', 'comments')
.where('issue.status IN (:...issueStatus)', {
issueStatus: statusFilter,
});

View File

@@ -197,8 +197,10 @@ mediaRoutes.delete(
const media = await mediaRepository.findOneOrFail({
where: { id: Number(req.params.id) },
});
const is4k = media.serviceUrl4k !== undefined;
const is4k = req.query.is4k === 'true';
const isMovie = media.mediaType === MediaType.MOVIE;
let serviceSettings;
if (isMovie) {
serviceSettings = settings.radarr.find(
@@ -225,6 +227,7 @@ mediaRoutes.delete(
);
}
}
if (!serviceSettings) {
logger.warn(
`There is no default ${
@@ -239,6 +242,7 @@ mediaRoutes.delete(
);
return;
}
let service;
if (isMovie) {
service = new RadarrAPI({

View File

@@ -28,7 +28,9 @@ import discoverSettingRoutes from '@server/routes/settings/discover';
import { ApiError } from '@server/types/error';
import { appDataPath } from '@server/utils/appDataVolume';
import { getAppVersion } from '@server/utils/appVersion';
import { dnsCache } from '@server/utils/dnsCache';
import { getHostname } from '@server/utils/getHostname';
import type { DnsEntries, DnsStats } from 'dns-caching';
import { Router } from 'express';
import rateLimit from 'express-rate-limit';
import fs from 'fs';
@@ -37,6 +39,7 @@ import { rescheduleJob } from 'node-schedule';
import path from 'path';
import semver from 'semver';
import { URL } from 'url';
import metadataRoutes from './metadata';
import notificationRoutes from './notifications';
import radarrRoutes from './radarr';
import sonarrRoutes from './sonarr';
@@ -47,6 +50,7 @@ settingsRoutes.use('/notifications', notificationRoutes);
settingsRoutes.use('/radarr', radarrRoutes);
settingsRoutes.use('/sonarr', sonarrRoutes);
settingsRoutes.use('/discover', discoverSettingRoutes);
settingsRoutes.use('/metadatas', metadataRoutes);
const filteredMainSettings = (
user: User,
@@ -105,6 +109,45 @@ settingsRoutes.post('/main/regenerate', async (req, res, next) => {
return res.status(200).json(filteredMainSettings(req.user, main));
});
settingsRoutes.get('/oidc', async (req, res) => {
const settings = getSettings();
return res.status(200).json(settings.oidc);
});
settingsRoutes.put('/oidc/:slug', async (req, res) => {
const settings = getSettings();
let provider = settings.oidc.providers.findIndex(
(p) => p.slug === req.params.slug
);
if (provider !== -1) {
Object.assign(settings.oidc.providers[provider], req.body);
} else {
settings.oidc.providers.push({ slug: req.params.slug, ...req.body });
provider = settings.oidc.providers.length - 1;
}
await settings.save();
return res.status(200).json(settings.oidc.providers[provider]);
});
settingsRoutes.delete('/oidc/:slug', async (req, res) => {
const settings = getSettings();
const provider = settings.oidc.providers.findIndex(
(p) => p.slug === req.params.slug
);
if (provider === -1)
return res.status(404).json({ message: 'Provider not found' });
settings.oidc.providers.splice(provider, 1);
await settings.save();
return res.status(200).json(settings.oidc);
});
settingsRoutes.get('/plex', (_req, res) => {
const settings = getSettings();
@@ -755,12 +798,19 @@ settingsRoutes.get('/cache', async (_req, res) => {
const tmdbImageCache = await ImageProxy.getImageStats('tmdb');
const avatarImageCache = await ImageProxy.getImageStats('avatar');
const stats: DnsStats | undefined = dnsCache?.getStats();
const entries: DnsEntries | undefined = dnsCache?.getCacheEntries();
return res.status(200).json({
apiCaches,
imageCache: {
tmdb: tmdbImageCache,
avatar: avatarImageCache,
},
dnsCache: {
stats,
entries,
},
});
});
@@ -778,6 +828,20 @@ settingsRoutes.post<{ cacheId: AvailableCacheIds }>(
}
);
settingsRoutes.post<{ dnsEntry: string }>(
'/cache/dns/:dnsEntry/flush',
(req, res, next) => {
const dnsEntry = req.params.dnsEntry;
if (dnsCache) {
dnsCache.clear(dnsEntry);
return res.status(204).send();
}
next({ status: 404, message: 'Cache not found.' });
}
);
settingsRoutes.post(
'/initialize',
isAuthenticated(Permission.ADMIN),

View File

@@ -0,0 +1,153 @@
import TheMovieDb from '@server/api/themoviedb';
import Tvdb from '@server/api/tvdb';
import {
getSettings,
MetadataProviderType,
type MetadataSettings,
} from '@server/lib/settings';
import logger from '@server/logger';
import { Router } from 'express';
function getTestResultString(testValue: number): string {
if (testValue === -1) return 'not tested';
if (testValue === 0) return 'failed';
return 'ok';
}
const metadataRoutes = Router();
metadataRoutes.get('/', (_req, res) => {
const settings = getSettings();
res.status(200).json({
tv: settings.metadataSettings.tv,
anime: settings.metadataSettings.anime,
});
});
metadataRoutes.put('/', async (req, res) => {
const settings = getSettings();
const body = req.body as MetadataSettings;
let tvdbTest = -1;
let tmdbTest = -1;
try {
if (
body.tv === MetadataProviderType.TVDB ||
body.anime === MetadataProviderType.TVDB
) {
tvdbTest = 0;
const tvdb = await Tvdb.getInstance();
await tvdb.test();
tvdbTest = 1;
}
} catch (e) {
logger.error('Failed to test metadata provider', {
label: 'Metadata',
message: e.message,
});
}
try {
if (
body.tv === MetadataProviderType.TMDB ||
body.anime === MetadataProviderType.TMDB
) {
tmdbTest = 0;
const tmdb = new TheMovieDb();
await tmdb.getTvShow({ tvId: 1054 });
tmdbTest = 1;
}
} catch (e) {
logger.error('Failed to test metadata provider', {
label: 'MetadataProvider',
message: e.message,
});
}
// If a test failed, return the test results
if (tvdbTest === 0 || tmdbTest === 0) {
return res.status(500).json({
success: false,
tests: {
tvdb: getTestResultString(tvdbTest),
tmdb: getTestResultString(tmdbTest),
},
});
}
settings.metadataSettings = {
tv: body.tv,
anime: body.anime,
};
await settings.save();
res.status(200).json({
success: true,
tv: body.tv,
anime: body.anime,
tests: {
tvdb: getTestResultString(tvdbTest),
tmdb: getTestResultString(tmdbTest),
},
});
});
metadataRoutes.post('/test', async (req, res) => {
let tvdbTest = -1;
let tmdbTest = -1;
try {
const body = req.body as { tmdb: boolean; tvdb: boolean };
try {
if (body.tmdb) {
tmdbTest = 0;
const tmdb = new TheMovieDb();
await tmdb.getTvShow({ tvId: 1054 });
tmdbTest = 1;
}
} catch (e) {
logger.error('Failed to test metadata provider', {
label: 'MetadataProvider',
message: e.message,
});
}
try {
if (body.tvdb) {
tvdbTest = 0;
const tvdb = await Tvdb.getInstance();
await tvdb.test();
tvdbTest = 1;
}
} catch (e) {
logger.error('Failed to test metadata provider', {
label: 'MetadataProvider',
message: e.message,
});
}
const success = !(tvdbTest === 0 || tmdbTest === 0);
const statusCode = success ? 200 : 500;
return res.status(statusCode).json({
success: success,
tests: {
tmdb: getTestResultString(tmdbTest),
tvdb: getTestResultString(tvdbTest),
},
});
} catch (e) {
return res.status(500).json({
success: false,
tests: {
tmdb: getTestResultString(tmdbTest),
tvdb: getTestResultString(tvdbTest),
},
error: e.message,
});
}
});
export default metadataRoutes;

View File

@@ -270,6 +270,7 @@ notificationRoutes.get('/webhook', (_req, res) => {
const response: typeof webhookSettings = {
enabled: webhookSettings.enabled,
embedPoster: webhookSettings.embedPoster,
types: webhookSettings.types,
options: {
...webhookSettings.options,
@@ -291,6 +292,7 @@ notificationRoutes.post('/webhook', async (req, res, next) => {
settings.notifications.agents.webhook = {
enabled: req.body.enabled,
embedPoster: req.body.embedPoster,
types: req.body.types,
options: {
jsonPayload: Buffer.from(req.body.options.jsonPayload).toString(
@@ -321,6 +323,7 @@ notificationRoutes.post('/webhook/test', async (req, res, next) => {
const testBody = {
enabled: req.body.enabled,
embedPoster: req.body.embedPoster,
types: req.body.types,
options: {
jsonPayload: Buffer.from(req.body.options.jsonPayload).toString(

View File

@@ -1,5 +1,8 @@
import { getMetadataProvider } from '@server/api/metadata';
import RottenTomatoes from '@server/api/rating/rottentomatoes';
import TheMovieDb from '@server/api/themoviedb';
import { ANIME_KEYWORD_ID } from '@server/api/themoviedb/constants';
import type { TmdbKeyword } from '@server/api/themoviedb/interfaces';
import { MediaType } from '@server/constants/media';
import { getRepository } from '@server/datasource';
import Media from '@server/entity/Media';
@@ -13,12 +16,20 @@ const tvRoutes = Router();
tvRoutes.get('/:id', async (req, res, next) => {
const tmdb = new TheMovieDb();
try {
const tv = await tmdb.getTvShow({
const tmdbTv = await tmdb.getTvShow({
tvId: Number(req.params.id),
});
const metadataProvider = tmdbTv.keywords.results.some(
(keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID
)
? await getMetadataProvider('anime')
: await getMetadataProvider('tv');
const tv = await metadataProvider.getTvShow({
tvId: Number(req.params.id),
language: (req.query.language as string) ?? req.locale,
});
const media = await Media.getMedia(tv.id, MediaType.TV);
const onUserWatchlist = await getRepository(Watchlist).exist({
@@ -34,7 +45,9 @@ tvRoutes.get('/:id', async (req, res, next) => {
// TMDB issue where it doesnt fallback to English when no overview is available in requested locale.
if (!data.overview) {
const tvEnglish = await tmdb.getTvShow({ tvId: Number(req.params.id) });
const tvEnglish = await metadataProvider.getTvShow({
tvId: Number(req.params.id),
});
data.overview = tvEnglish.overview;
}
@@ -53,10 +66,18 @@ tvRoutes.get('/:id', async (req, res, next) => {
});
tvRoutes.get('/:id/season/:seasonNumber', async (req, res, next) => {
const tmdb = new TheMovieDb();
try {
const season = await tmdb.getTvSeason({
const tmdb = new TheMovieDb();
const tmdbTv = await tmdb.getTvShow({
tvId: Number(req.params.id),
});
const metadataProvider = tmdbTv.keywords.results.some(
(keyword: TmdbKeyword) => keyword.id === ANIME_KEYWORD_ID
)
? await getMetadataProvider('anime')
: await getMetadataProvider('tv');
const season = await metadataProvider.getTvSeason({
tvId: Number(req.params.id),
seasonNumber: Number(req.params.seasonNumber),
language: (req.query.language as string) ?? req.locale,

View File

@@ -4,10 +4,13 @@ import { ApiErrorCode } from '@server/constants/error';
import { MediaServerType } from '@server/constants/server';
import { UserType } from '@server/constants/user';
import { getRepository } from '@server/datasource';
import { LinkedAccount } from '@server/entity/LinkedAccount';
import { User } from '@server/entity/User';
import { UserSettings } from '@server/entity/UserSettings';
import type {
UserSettingsGeneralResponse,
UserSettingsLinkedAccount,
UserSettingsLinkedAccountResponse,
UserSettingsNotificationsResponse,
} from '@server/interfaces/api/userSettingsInterfaces';
import { Permission } from '@server/lib/permissions';
@@ -18,7 +21,7 @@ import { ApiError } from '@server/types/error';
import { getHostname } from '@server/utils/getHostname';
import { Router } from 'express';
import net from 'net';
import { Not } from 'typeorm';
import { In, Not, type FindOptionsWhere } from 'typeorm';
import { canMakePermissionsChange } from '.';
const isOwnProfile = (): Middleware => {
@@ -546,6 +549,73 @@ userSettingsRoutes.delete<{ id: string }>(
}
);
userSettingsRoutes.get<{ id: string }, UserSettingsLinkedAccountResponse>(
'/linked-accounts',
isOwnProfileOrAdmin(),
async (req, res) => {
const settings = getSettings();
if (!settings.main.oidcLogin) {
// don't show any linked accounts if OIDC login is disabled
return res.status(200).json([]);
}
const activeProviders = settings.oidc.providers.map((p) => p.slug);
const linkedAccountsRepository = getRepository(LinkedAccount);
const linkedAccounts = await linkedAccountsRepository.find({
relations: {
user: true,
},
where: {
provider: In(activeProviders),
user: {
id: Number(req.params.id),
},
},
});
const linkedAccountInfo = linkedAccounts.map((acc) => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const provider = settings.oidc.providers.find(
(p) => p.slug === acc.provider
)!;
return {
id: acc.id,
username: acc.username,
provider: {
slug: provider.slug,
name: provider.name,
logo: provider.logo,
},
} satisfies UserSettingsLinkedAccount;
});
return res.status(200).json(linkedAccountInfo);
}
);
userSettingsRoutes.delete<{ id: string; acctId: string }>(
'/linked-accounts/:acctId',
isOwnProfileOrAdmin(),
async (req, res) => {
const linkedAccountsRepository = getRepository(LinkedAccount);
const condition: FindOptionsWhere<LinkedAccount> = {
id: Number(req.params.acctId),
user: {
id: Number(req.params.id),
},
};
if (await linkedAccountsRepository.exist({ where: condition })) {
await linkedAccountsRepository.delete(condition);
return res.status(204).send();
} else {
return res.status(404).send();
}
}
);
userSettingsRoutes.get<{ id: string }, UserSettingsNotificationsResponse>(
'/notifications',
isOwnProfileOrAdmin(),

View File

@@ -33,52 +33,93 @@ import { EventSubscriber } from 'typeorm';
export class MediaRequestSubscriber
implements EntitySubscriberInterface<MediaRequest>
{
private async notifyAvailableMovie(entity: MediaRequest) {
private async notifyAvailableMovie(
entity: MediaRequest,
event?: UpdateEvent<MediaRequest>
) {
// Get fresh media state using event manager
let latestMedia: Media | null = null;
if (event?.manager) {
latestMedia = await event.manager.findOne(Media, {
where: { id: entity.media.id },
});
}
if (!latestMedia) {
const mediaRepository = getRepository(Media);
latestMedia = await mediaRepository.findOne({
where: { id: entity.media.id },
});
}
// Check availability using fresh media state
if (
entity.media[entity.is4k ? 'status4k' : 'status'] ===
MediaStatus.AVAILABLE
!latestMedia ||
latestMedia[entity.is4k ? 'status4k' : 'status'] !== MediaStatus.AVAILABLE
) {
const tmdb = new TheMovieDb();
return;
}
try {
const movie = await tmdb.getMovie({
movieId: entity.media.tmdbId,
});
const tmdb = new TheMovieDb();
notificationManager.sendNotification(Notification.MEDIA_AVAILABLE, {
event: `${entity.is4k ? '4K ' : ''}Movie Request Now Available`,
notifyAdmin: false,
notifySystem: true,
notifyUser: entity.requestedBy,
subject: `${movie.title}${
movie.release_date ? ` (${movie.release_date.slice(0, 4)})` : ''
}`,
message: truncate(movie.overview, {
length: 500,
separator: /\s/,
omission: '…',
}),
media: entity.media,
image: `https://image.tmdb.org/t/p/w600_and_h900_bestv2${movie.poster_path}`,
request: entity,
});
} catch (e) {
logger.error('Something went wrong sending media notification(s)', {
label: 'Notifications',
errorMessage: e.message,
mediaId: entity.id,
});
}
try {
const movie = await tmdb.getMovie({
movieId: entity.media.tmdbId,
});
notificationManager.sendNotification(Notification.MEDIA_AVAILABLE, {
event: `${entity.is4k ? '4K ' : ''}Movie Request Now Available`,
notifyAdmin: false,
notifySystem: true,
notifyUser: entity.requestedBy,
subject: `${movie.title}${
movie.release_date ? ` (${movie.release_date.slice(0, 4)})` : ''
}`,
message: truncate(movie.overview, {
length: 500,
separator: /\s/,
omission: '…',
}),
media: latestMedia,
image: `https://image.tmdb.org/t/p/w600_and_h900_bestv2${movie.poster_path}`,
request: entity,
});
} catch (e) {
logger.error('Something went wrong sending media notification(s)', {
label: 'Notifications',
errorMessage: e.message,
mediaId: entity.id,
});
}
}
private async notifyAvailableSeries(entity: MediaRequest) {
// Find all seasons in the related media entity
// and see if they are available, then we can check
// if the request contains the same seasons
private async notifyAvailableSeries(
entity: MediaRequest,
event?: UpdateEvent<MediaRequest>
) {
// Get fresh media state with seasons using event manager
let latestMedia: Media | null = null;
if (event?.manager) {
latestMedia = await event.manager.findOne(Media, {
where: { id: entity.media.id },
relations: { seasons: true },
});
}
if (!latestMedia) {
const mediaRepository = getRepository(Media);
latestMedia = await mediaRepository.findOne({
where: { id: entity.media.id },
relations: { seasons: true },
});
}
if (!latestMedia) {
return;
}
// Check availability using fresh media state
const requestedSeasons =
entity.seasons?.map((entitySeason) => entitySeason.seasonNumber) ?? [];
const availableSeasons = entity.media.seasons.filter(
const availableSeasons = latestMedia.seasons.filter(
(season) =>
season[entity.is4k ? 'status4k' : 'status'] === MediaStatus.AVAILABLE &&
requestedSeasons.includes(season.seasonNumber)
@@ -87,44 +128,46 @@ export class MediaRequestSubscriber
availableSeasons.length > 0 &&
availableSeasons.length === requestedSeasons.length;
if (isMediaAvailable) {
const tmdb = new TheMovieDb();
if (!isMediaAvailable) {
return;
}
try {
const tv = await tmdb.getTvShow({ tvId: entity.media.tmdbId });
const tmdb = new TheMovieDb();
notificationManager.sendNotification(Notification.MEDIA_AVAILABLE, {
event: `${entity.is4k ? '4K ' : ''}Series Request Now Available`,
subject: `${tv.name}${
tv.first_air_date ? ` (${tv.first_air_date.slice(0, 4)})` : ''
}`,
message: truncate(tv.overview, {
length: 500,
separator: /\s/,
omission: '…',
}),
notifyAdmin: false,
notifySystem: true,
notifyUser: entity.requestedBy,
image: `https://image.tmdb.org/t/p/w600_and_h900_bestv2${tv.poster_path}`,
media: entity.media,
extra: [
{
name: 'Requested Seasons',
value: entity.seasons
.map((season) => season.seasonNumber)
.join(', '),
},
],
request: entity,
});
} catch (e) {
logger.error('Something went wrong sending media notification(s)', {
label: 'Notifications',
errorMessage: e.message,
mediaId: entity.id,
});
}
try {
const tv = await tmdb.getTvShow({ tvId: entity.media.tmdbId });
notificationManager.sendNotification(Notification.MEDIA_AVAILABLE, {
event: `${entity.is4k ? '4K ' : ''}Series Request Now Available`,
subject: `${tv.name}${
tv.first_air_date ? ` (${tv.first_air_date.slice(0, 4)})` : ''
}`,
message: truncate(tv.overview, {
length: 500,
separator: /\s/,
omission: '…',
}),
notifyAdmin: false,
notifySystem: true,
notifyUser: entity.requestedBy,
image: `https://image.tmdb.org/t/p/w600_and_h900_bestv2${tv.poster_path}`,
media: latestMedia,
extra: [
{
name: 'Requested Seasons',
value: entity.seasons
.map((season) => season.seasonNumber)
.join(', '),
},
],
request: entity,
});
} catch (e) {
logger.error('Something went wrong sending media notification(s)', {
label: 'Notifications',
errorMessage: e.message,
mediaId: entity.id,
});
}
}
@@ -782,10 +825,10 @@ export class MediaRequestSubscriber
if (event.entity.status === MediaRequestStatus.COMPLETED) {
if (event.entity.media.mediaType === MediaType.MOVIE) {
this.notifyAvailableMovie(event.entity as MediaRequest);
this.notifyAvailableMovie(event.entity as MediaRequest, event);
}
if (event.entity.media.mediaType === MediaType.TV) {
this.notifyAvailableSeries(event.entity as MediaRequest);
this.notifyAvailableSeries(event.entity as MediaRequest, event);
}
}
}

View File

@@ -53,10 +53,11 @@ div(style='display: block; background-color: #111827; padding: 2.5rem 0;')
b(style='color: #9ca3af; font-weight: 700;')
| #{extra.name}&nbsp;
| #{extra.value}
td(rowspan='2' style='width: 7rem;')
a(style='display: block; width: 7rem; overflow: hidden; border-radius: .375rem;' href=actionUrl)
div(style='overflow: hidden; box-sizing: border-box; margin: 0px;')
img(alt='' src=imageUrl style='box-sizing: border-box; padding: 0px; border: none; margin: auto; display: block; min-width: 100%; max-width: 100%; min-height: 100%; max-height: 100%;')
if imageUrl
td(rowspan='2' style='width: 7rem;')
a(style='display: block; width: 7rem; overflow: hidden; border-radius: .375rem;' href=actionUrl)
div(style='overflow: hidden; box-sizing: border-box; margin: 0px;')
img(alt='' src=imageUrl style='box-sizing: border-box; padding: 0px; border: none; margin: auto; display: block; min-width: 100%; max-width: 100%; min-height: 100%; max-height: 100%;')
tr
td(style='font-size: .85em; color: #9ca3af; line-height: 1em; vertical-align: bottom; margin-right: 1rem')
span

35
server/types/languages.d.ts vendored Normal file
View File

@@ -0,0 +1,35 @@
export type AvailableLocale =
| 'ar'
| 'bg'
| 'ca'
| 'cs'
| 'da'
| 'de'
| 'en'
| 'el'
| 'es'
| 'es-MX'
| 'fi'
| 'fr'
| 'hr'
| 'he'
| 'hi'
| 'hu'
| 'it'
| 'ja'
| 'ko'
| 'lt'
| 'nb-NO'
| 'nl'
| 'pl'
| 'pt-BR'
| 'pt-PT'
| 'ro'
| 'ru'
| 'sq'
| 'sr'
| 'sv'
| 'tr'
| 'uk'
| 'zh-CN'
| 'zh-TW';

View File

@@ -1,11 +1,15 @@
import type { ProxySettings } from '@server/lib/settings';
import logger from '@server/logger';
import axios from 'axios';
import axios, { type InternalAxiosRequestConfig } from 'axios';
import { HttpProxyAgent } from 'http-proxy-agent';
import { HttpsProxyAgent } from 'https-proxy-agent';
import type { Dispatcher } from 'undici';
import { Agent, ProxyAgent, setGlobalDispatcher } from 'undici';
export let requestInterceptorFunction: (
config: InternalAxiosRequestConfig
) => InternalAxiosRequestConfig;
export default async function createCustomProxyAgent(
proxySettings: ProxySettings
) {
@@ -73,7 +77,8 @@ export default async function createCustomProxyAgent(
axios.defaults.httpsAgent = new HttpsProxyAgent(proxyUrl, {
headers: token ? { 'proxy-authorization': token } : undefined,
});
axios.interceptors.request.use((config) => {
requestInterceptorFunction = (config) => {
const url = config.baseURL
? new URL(config.baseURL + (config.url || ''))
: config.url;
@@ -82,7 +87,8 @@ export default async function createCustomProxyAgent(
config.httpsAgent = false;
}
return config;
});
};
axios.interceptors.request.use(requestInterceptorFunction);
} catch (e) {
logger.error('Failed to connect to the proxy: ' + e.message, {
label: 'Proxy',

26
server/utils/dnsCache.ts Normal file
View File

@@ -0,0 +1,26 @@
import logger from '@server/logger';
import { DnsCacheManager } from 'dns-caching';
export let dnsCache: DnsCacheManager | undefined;
export function initializeDnsCache({
forceMinTtl,
forceMaxTtl,
}: {
forceMinTtl?: number;
forceMaxTtl?: number;
}) {
if (dnsCache) {
logger.warn('DNS Cache is already initialized', { label: 'DNS Cache' });
return;
}
logger.info('Initializing DNS Cache', { label: 'DNS Cache' });
dnsCache = new DnsCacheManager({
logger,
forceMinTtl: typeof forceMinTtl === 'number' ? forceMinTtl * 1000 : 0,
forceMaxTtl: typeof forceMaxTtl === 'number' ? forceMaxTtl * 1000 : -1,
});
dnsCache.initialize();
}

203
server/utils/oidc.ts Normal file
View File

@@ -0,0 +1,203 @@
import type {
IdTokenClaims,
OidcProviderMetadata,
OidcStandardClaims,
OidcTokenResponse,
} from '@server/interfaces/api/oidcInterfaces';
import type { OidcProvider } from '@server/lib/settings';
import type { Request } from 'express';
import * as yup from 'yup';
/** Fetch the issuer configuration from the OpenID Connect Discovery endpoint */
export async function getOpenIdConfiguration(domain: string) {
// remove trailing slash from url if it exists and add /.well-known/openid-configuration path
const wellKnownUrl = new URL(
domain.replace(/\/$/, '') + '/.well-known/openid-configuration'
).toString();
const wellKnownInfo: OidcProviderMetadata = await fetch(wellKnownUrl, {
headers: {
'Content-Type': 'application/json',
},
}).then((r) => r.json());
return wellKnownInfo;
}
function getOpenIdCallbackUrl(req: Request, provider: OidcProvider) {
const callbackUrl = new URL(
`/login`,
`${req.protocol}://${req.headers.host}`
);
callbackUrl.searchParams.set('provider', provider.slug);
callbackUrl.searchParams.set('callback', 'true');
return callbackUrl.toString();
}
/** Generate authentication request url */
export async function getOpenIdRedirectUrl(
req: Request,
provider: OidcProvider,
state: string
) {
const wellKnownInfo = await getOpenIdConfiguration(provider.issuerUrl);
const url = new URL(wellKnownInfo.authorization_endpoint);
url.searchParams.set('response_type', 'code');
url.searchParams.set('client_id', provider.clientId);
url.searchParams.set('redirect_uri', getOpenIdCallbackUrl(req, provider));
url.searchParams.set('scope', provider.scopes ?? 'openid profile email');
url.searchParams.set('state', state);
return url.toString();
}
/** Exchange authorization code for token data */
export async function fetchOpenIdTokenData(
req: Request,
provider: OidcProvider,
wellKnownInfo: OidcProviderMetadata,
code: string
): Promise<OidcTokenResponse> {
const formData = new URLSearchParams();
formData.append('client_secret', provider.clientSecret);
formData.append('grant_type', 'authorization_code');
formData.append('redirect_uri', getOpenIdCallbackUrl(req, provider));
formData.append('client_id', provider.clientId);
formData.append('code', code);
return await fetch(wellKnownInfo.token_endpoint, {
method: 'POST',
body: formData,
}).then((r) => r.json());
}
export async function getOpenIdUserInfo(
wellKnownInfo: OidcProviderMetadata,
authToken: string
) {
return fetch(wellKnownInfo.userinfo_endpoint, {
headers: {
Authorization: `Bearer ${authToken}`,
Accept: 'application/json',
},
}).then((r) => r.json());
}
class OidcAuthorizationError extends Error {}
class OidcMissingKeyError extends OidcAuthorizationError {
constructor(public userInfo: FullUserInfo, public key: string) {
super(`Key ${key} was missing on OIDC userinfo but was expected.`);
}
}
type PrimitiveString = 'string' | 'boolean';
type TypeFromName<T extends PrimitiveString> = T extends 'string'
? string
: T extends 'boolean'
? boolean
: unknown;
export function tryGetUserInfoKey<T extends PrimitiveString>(
userInfo: FullUserInfo,
key: string,
expectedType: T
): TypeFromName<T> {
if (!Object.hasOwn(userInfo, key) || typeof userInfo[key] !== expectedType) {
throw new OidcMissingKeyError(userInfo, key);
}
return userInfo[key] as TypeFromName<T>;
}
export function validateUserClaims(
userInfo: FullUserInfo,
requiredClaims: string[]
) {
requiredClaims.some((claim) => {
const value = tryGetUserInfoKey(userInfo, claim, 'boolean');
if (!value)
throw new OidcAuthorizationError('User was missing a required claim.');
});
}
/** Generates a schema to validate ID token JWT and userinfo claims */
export const createIdTokenSchema = ({
oidcDomain,
oidcClientId,
requiredClaims,
}: {
oidcDomain: string;
oidcClientId: string;
requiredClaims: string[];
}) => {
return yup.object().shape({
iss: yup
.string()
.oneOf(
[oidcDomain, `${oidcDomain}/`],
`The token iss value doesn't match the oidc_DOMAIN (${oidcDomain})`
)
.required("The token didn't come with an iss value."),
aud: yup.lazy((val) => {
// single audience
if (typeof val === 'string')
return yup
.string()
.oneOf(
[oidcClientId],
`The token aud value doesn't match the oidc_CLIENT_ID (${oidcClientId})`
)
.required("The token didn't come with an aud value.");
// several audiences
if (typeof val === 'object' && Array.isArray(val))
return yup
.array()
.of(yup.string())
.test(
'contains-client-id',
`The token aud value doesn't contain the oidc_CLIENT_ID (${oidcClientId})`,
(value) => !!(value && value.includes(oidcClientId))
);
// invalid type
return yup
.mixed()
.typeError('The token aud value is not a string or array.');
}),
exp: yup
.number()
.required()
.test(
'is_before_date',
'Token exp value is before current time.',
(value) => {
if (!value) return false;
if (value < Math.ceil(Date.now() / 1000)) return false;
return true;
}
),
iat: yup
.number()
.required()
.test(
'is_before_one_day',
'Token was issued before one day ago and is now invalid.',
(value) => {
if (!value) return false;
const date = new Date();
date.setDate(date.getDate() - 1);
if (value < Math.ceil(Number(date) / 1000)) return false;
return true;
}
),
// TODO: only require this for new user login
email: yup.string().required(),
// ensure all required claims are present and are booleans
...requiredClaims.reduce(
(a, v) => ({ ...a, [v]: yup.boolean().required() }),
{}
),
});
};
export type FullUserInfo = IdTokenClaims & OidcStandardClaims;

View File

@@ -29,14 +29,10 @@ const BlacklistedTagsBadge = ({ data }: BlacklistedTagsBadgeProps) => {
const keywordIds = data.blacklistedTags.slice(1, -1).split(',');
Promise.all(
keywordIds.map(async (keywordId) => {
try {
const { data } = await axios.get<Keyword>(
`/api/v1/keyword/${keywordId}`
);
return data.name;
} catch (err) {
return '';
}
const { data } = await axios.get<Keyword | null>(
`/api/v1/keyword/${keywordId}`
);
return data?.name || `[Invalid: ${keywordId}]`;
})
).then((keywords) => {
setTagNamesBlacklistedFor(keywords.join(', '));

View File

@@ -5,7 +5,10 @@ import { encodeURIExtraParams } from '@app/hooks/useDiscover';
import defineMessages from '@app/utils/defineMessages';
import { Transition } from '@headlessui/react';
import { ArrowDownIcon } from '@heroicons/react/24/solid';
import type { TmdbKeywordSearchResponse } from '@server/api/themoviedb/interfaces';
import type {
TmdbKeyword,
TmdbKeywordSearchResponse,
} from '@server/api/themoviedb/interfaces';
import type { Keyword } from '@server/models/common';
import axios from 'axios';
import { useFormikContext } from 'formik';
@@ -124,15 +127,19 @@ const ControlledKeywordSelector = ({
const keywords = await Promise.all(
defaultValue.split(',').map(async (keywordId) => {
const { data } = await axios.get<Keyword>(
const { data } = await axios.get<Keyword | null>(
`/api/v1/keyword/${keywordId}`
);
return data;
})
);
const validKeywords: TmdbKeyword[] = keywords.filter(
(keyword): keyword is TmdbKeyword => keyword !== null
);
onChange(
keywords.map((keyword) => ({
validKeywords.map((keyword) => ({
label: keyword.name,
value: keyword.id,
}))

View File

@@ -31,7 +31,7 @@ type BaseProps<P> = {
) => void;
};
type ButtonProps<P extends React.ElementType> = {
export type ButtonProps<P extends React.ElementType> = {
as?: P;
} & MergeElementProps<P, BaseProps<P>>;

View File

@@ -1,31 +1,34 @@
import { Field } from 'formik';
import { useId } from 'react';
import { twMerge } from 'tailwind-merge';
interface LabeledCheckboxProps {
id: string;
name: string;
className?: string;
label: string;
description: string;
onChange: () => void;
onChange?: () => void;
children?: React.ReactNode;
}
const LabeledCheckbox: React.FC<LabeledCheckboxProps> = ({
id,
name,
className,
label,
description,
onChange,
children,
}) => {
const id = useId();
return (
<>
<div className={twMerge('relative flex items-start', className)}>
<div className="flex h-6 items-center">
<Field type="checkbox" id={id} name={id} onChange={onChange} />
<Field type="checkbox" id={id} name={name} onChange={onChange} />
</div>
<div className="ml-3 text-sm leading-6">
<label htmlFor="localLogin" className="block">
<label htmlFor={id} className="block">
<div className="flex flex-col">
<span className="font-medium text-white">{label}</span>
<span className="font-normal text-gray-400">{description}</span>

View File

@@ -84,6 +84,7 @@ const SettingsTabs = ({
Select a Tab
</label>
<select
id="tabs"
onChange={(e) => {
router.push(e.target.value);
}}

View File

@@ -77,16 +77,19 @@ const CreateSlider = ({ onCreate, slider }: CreateSliderProps) => {
const keywords = await Promise.all(
slider.data.split(',').map(async (keywordId) => {
const keyword = await axios.get<Keyword>(
const keyword = await axios.get<Keyword | null>(
`/api/v1/keyword/${keywordId}`
);
return keyword.data;
})
);
const validKeywords: Keyword[] = keywords.filter(
(keyword): keyword is Keyword => keyword !== null
);
setDefaultDataValue(
keywords.map((keyword) => ({
validKeywords.map((keyword) => ({
label: keyword.name,
value: keyword.id,
}))

View File

@@ -1,6 +1,7 @@
import Badge from '@app/components/Common/Badge';
import Button from '@app/components/Common/Button';
import CachedImage from '@app/components/Common/CachedImage';
import Tooltip from '@app/components/Common/Tooltip';
import { issueOptions } from '@app/components/IssueModal/constants';
import { Permission, useUser } from '@app/hooks/useUser';
import globalMessages from '@app/i18n/globalMessages';
@@ -26,6 +27,7 @@ const messages = defineMessages('components.IssueList.IssueItem', {
opened: 'Opened',
viewissue: 'View Issue',
unknownissuetype: 'Unknown',
descriptionpreview: 'Issue Description',
});
const isMovie = (movie: MovieDetails | TvDetails): movie is MovieDetails => {
@@ -107,8 +109,15 @@ const IssueItem = ({ issue }: IssueItemProps) => {
}
}
const description = issue.comments?.[0]?.message || '';
const maxDescriptionLength = 120;
const shouldTruncate = description.length > maxDescriptionLength;
const truncatedDescription = shouldTruncate
? description.substring(0, maxDescriptionLength) + '...'
: description;
return (
<div className="relative flex w-full flex-col justify-between overflow-hidden rounded-xl bg-gray-800 py-4 text-gray-400 shadow-md ring-1 ring-gray-700 xl:h-28 xl:flex-row">
<div className="relative flex w-full flex-col justify-between overflow-hidden rounded-xl bg-gray-800 py-4 text-gray-400 shadow-md ring-1 ring-gray-700 xl:flex-row">
{title.backdropPath && (
<div className="absolute inset-0 z-0 w-full bg-cover bg-center xl:w-2/3">
<CachedImage
@@ -168,8 +177,38 @@ const IssueItem = ({ issue }: IssueItemProps) => {
>
{isMovie(title) ? title.title : title.name}
</Link>
{description && (
<div className="mt-1 max-w-full">
<div className="overflow-hidden text-sm text-gray-300">
{shouldTruncate ? (
<Tooltip
content={
<div className="max-w-sm p-3">
<div className="mb-1 text-sm font-medium text-gray-200">
Issue Description
</div>
<div className="whitespace-pre-wrap text-sm leading-relaxed text-gray-300">
{description}
</div>
</div>
}
tooltipConfig={{
placement: 'top',
offset: [0, 8],
}}
>
<span className="block cursor-help truncate transition-colors hover:text-gray-200">
{truncatedDescription}
</span>
</Tooltip>
) : (
<span className="block break-words">{description}</span>
)}
</div>
</div>
)}
{problemSeasonEpisodeLine.length > 0 && (
<div className="card-field">
<div className="card-field mt-1">
{problemSeasonEpisodeLine.map((t, k) => (
<span key={k}>{t}</span>
))}

View File

@@ -1,10 +1,10 @@
import type { AvailableLocale } from '@app/context/LanguageContext';
import { availableLanguages } from '@app/context/LanguageContext';
import useClickOutside from '@app/hooks/useClickOutside';
import useLocale from '@app/hooks/useLocale';
import defineMessages from '@app/utils/defineMessages';
import { Transition } from '@headlessui/react';
import { LanguageIcon } from '@heroicons/react/24/solid';
import type { AvailableLocale } from '@server/types/languages';
import { useRef, useState } from 'react';
import { useIntl } from 'react-intl';

View File

@@ -3,11 +3,11 @@ import PullToRefresh from '@app/components/Layout/PullToRefresh';
import SearchInput from '@app/components/Layout/SearchInput';
import Sidebar from '@app/components/Layout/Sidebar';
import UserDropdown from '@app/components/Layout/UserDropdown';
import type { AvailableLocale } from '@app/context/LanguageContext';
import useLocale from '@app/hooks/useLocale';
import useSettings from '@app/hooks/useSettings';
import { useUser } from '@app/hooks/useUser';
import { ArrowLeftIcon, Bars3BottomLeftIcon } from '@heroicons/react/24/solid';
import type { AvailableLocale } from '@server/types/languages';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import useSWR from 'swr';

View File

@@ -0,0 +1,35 @@
import Button, { type ButtonProps } from '@app/components/Common/Button';
import { SmallLoadingSpinner } from '@app/components/Common/LoadingSpinner';
import { type PropsWithChildren } from 'react';
import { twMerge } from 'tailwind-merge';
export type LoginButtonProps = ButtonProps<'button'> &
PropsWithChildren<{
loading?: boolean;
}>;
export default function LoginButton({
loading,
className,
children,
...buttonProps
}: LoginButtonProps) {
return (
<Button
className={twMerge(
'relative flex-grow bg-transparent disabled:opacity-50',
className
)}
disabled={loading}
{...buttonProps}
>
{loading && (
<div className="absolute right-0 mr-4 h-4 w-4">
<SmallLoadingSpinner />
</div>
)}
{children}
</Button>
);
}

View File

@@ -0,0 +1,109 @@
import defineMessages from '@app/utils/defineMessages';
import type { PublicOidcProvider } from '@server/lib/settings';
import axios, { isAxiosError } from 'axios';
import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import { useIntl } from 'react-intl';
import LoginButton from './LoginButton';
const messages = defineMessages('components.Login', {
oidcLoginError: 'An error occurred while logging in with {provider}.',
});
async function processCallback(params: URLSearchParams, provider: string) {
const url = new URL(
`/api/v1/auth/oidc/callback/${encodeURIComponent(provider)}`,
window.location.origin
);
url.search = params.toString();
try {
const res = await axios.get(url.toString());
return {
type: 'success',
message: res.data,
};
} catch (e) {
if (isAxiosError(e) && e.response?.data?.message) {
return { type: 'error', message: e.response.data.message };
}
return {
type: 'error',
message: e.message,
};
}
}
type OidcLoginButtonProps = {
provider: PublicOidcProvider;
onError?: (message: string) => void;
};
export default function OidcLoginButton({
provider,
onError,
}: OidcLoginButtonProps) {
const intl = useIntl();
const searchParams = useSearchParams();
const router = useRouter();
const [loading, setLoading] = useState(false);
const redirectToLogin = useCallback(async () => {
try {
const res = await axios.get<{ redirectUrl: string }>(
`/api/v1/auth/oidc/login/${provider.slug}`
);
window.location.href = res.data.redirectUrl;
} catch (e) {
setLoading(false);
onError?.(
intl.formatMessage(messages.oidcLoginError, {
provider: provider.name,
})
);
}
}, [provider, intl, onError]);
const handleCallback = useCallback(async () => {
const result = await processCallback(searchParams, provider.slug);
if (result.type === 'success') {
// redirect to homepage
router.push(result.message?.to ?? '/');
} else {
setLoading(false);
onError?.(
intl.formatMessage(messages.oidcLoginError, {
provider: provider.name,
})
);
}
}, [provider, searchParams, intl, onError, router]);
useEffect(() => {
if (loading) return;
const isCallback = searchParams.get('callback') === 'true';
const providerSlug = searchParams.get('provider');
if (providerSlug === provider.slug) {
setLoading(true);
if (isCallback) handleCallback();
else redirectToLogin();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<LoginButton loading={loading} onClick={() => redirectToLogin()}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={provider.logo || '/images/openid.svg'}
alt={provider.name}
className="mr-2 max-h-5 w-5"
/>
<span>{provider.name}</span>
</LoginButton>
);
}

View File

@@ -1,9 +1,8 @@
import PlexIcon from '@app/assets/services/plex.svg';
import Button from '@app/components/Common/Button';
import { SmallLoadingSpinner } from '@app/components/Common/LoadingSpinner';
import usePlexLogin from '@app/hooks/usePlexLogin';
import defineMessages from '@app/utils/defineMessages';
import { FormattedMessage } from 'react-intl';
import LoginButton from './LoginButton';
const messages = defineMessages('components.Login', {
loginwithapp: 'Login with {appName}',
@@ -25,18 +24,12 @@ const PlexLoginButton = ({
const { loading, login } = usePlexLogin({ onAuthToken, onError });
return (
<Button
className="relative flex-1 border-[#cc7b19] bg-[rgba(204,123,25,0.3)] hover:border-[#cc7b19] hover:bg-[rgba(204,123,25,0.7)] disabled:opacity-50"
<LoginButton
className="border-[#cc7b19] bg-[rgba(204,123,25,0.3)] hover:border-[#cc7b19] hover:bg-[rgba(204,123,25,0.7)]"
onClick={login}
disabled={loading || isProcessing}
loading={loading || isProcessing}
data-testid="plex-login-button"
>
{loading && (
<div className="absolute right-0 mr-4 h-4 w-4">
<SmallLoadingSpinner />
</div>
)}
{large ? (
<FormattedMessage
{...messages.loginwithapp}
@@ -55,7 +48,7 @@ const PlexLoginButton = ({
) : (
<PlexIcon className="w-8" />
)}
</Button>
</LoginButton>
);
};

View File

@@ -1,12 +1,12 @@
import EmbyLogo from '@app/assets/services/emby-icon-only.svg';
import JellyfinLogo from '@app/assets/services/jellyfin-icon.svg';
import PlexLogo from '@app/assets/services/plex.svg';
import Button from '@app/components/Common/Button';
import ImageFader from '@app/components/Common/ImageFader';
import PageTitle from '@app/components/Common/PageTitle';
import LanguagePicker from '@app/components/Layout/LanguagePicker';
import JellyfinLogin from '@app/components/Login/JellyfinLogin';
import LocalLogin from '@app/components/Login/LocalLogin';
import OidcLoginButton from '@app/components/Login/OidcLoginButton';
import PlexLoginButton from '@app/components/Login/PlexLoginButton';
import useSettings from '@app/hooks/useSettings';
import { useUser } from '@app/hooks/useUser';
@@ -21,6 +21,7 @@ import { useEffect, useRef, useState } from 'react';
import { useIntl } from 'react-intl';
import { CSSTransition, SwitchTransition } from 'react-transition-group';
import useSWR from 'swr';
import LoginButton from './LoginButton';
const messages = defineMessages('components.Login', {
signin: 'Sign In',
@@ -121,10 +122,9 @@ const Login = () => {
) : (
settings.currentSettings.localLogin &&
(mediaServerLogin ? (
<Button
<LoginButton
key="jellyseerr"
data-testid="jellyseerr-login-button"
className="flex-1 bg-transparent"
onClick={() => setMediaServerLogin(false)}
>
{/* eslint-disable-next-line @next/next/no-img-element */}
@@ -134,19 +134,25 @@ const Login = () => {
className="mr-2 h-5"
/>
<span>{settings.currentSettings.applicationTitle}</span>
</Button>
</LoginButton>
) : (
<Button
<LoginButton
key="mediaserver"
data-testid="mediaserver-login-button"
className="flex-1 bg-transparent"
onClick={() => setMediaServerLogin(true)}
>
<MediaServerLogo />
<span>{mediaServerName}</span>
</Button>
</LoginButton>
))
)),
...settings.currentSettings.openIdProviders.map((provider) => (
<OidcLoginButton
key={provider.slug}
provider={provider}
onError={setError}
/>
)),
].filter((o): o is JSX.Element => !!o);
return (
@@ -197,46 +203,50 @@ const Login = () => {
</div>
</Transition>
<div className="px-10 py-8">
<SwitchTransition mode="out-in">
<CSSTransition
key={mediaServerLogin ? 'ms' : 'local'}
nodeRef={loginRef}
addEndListener={(done) => {
loginRef.current?.addEventListener(
'transitionend',
done,
false
);
}}
onEntered={() => {
document
.querySelector<HTMLInputElement>('#email, #username')
?.focus();
}}
classNames={{
appear: 'opacity-0',
appearActive: 'transition-opacity duration-500 opacity-100',
enter: 'opacity-0',
enterActive: 'transition-opacity duration-500 opacity-100',
exitActive: 'transition-opacity duration-0 opacity-0',
}}
>
<div ref={loginRef} className="button-container">
{isJellyfin &&
(mediaServerLogin ||
!settings.currentSettings.localLogin) ? (
<JellyfinLogin
serverType={settings.currentSettings.mediaServerType}
revalidate={revalidate}
/>
) : (
settings.currentSettings.localLogin && (
<LocalLogin revalidate={revalidate} />
)
)}
</div>
</CSSTransition>
</SwitchTransition>
{loginFormVisible && (
<SwitchTransition mode="out-in">
<CSSTransition
key={mediaServerLogin ? 'ms' : 'local'}
nodeRef={loginRef}
addEndListener={(done) => {
loginRef.current?.addEventListener(
'transitionend',
done,
false
);
}}
onEntered={() => {
document
.querySelector<HTMLInputElement>('#email, #username')
?.focus();
}}
classNames={{
appear: 'opacity-0',
appearActive:
'transition-opacity duration-500 opacity-100',
enter: 'opacity-0',
enterActive:
'transition-opacity duration-500 opacity-100',
exitActive: 'transition-opacity duration-0 opacity-0',
}}
>
<div ref={loginRef} className="button-container">
{isJellyfin &&
(mediaServerLogin ||
!settings.currentSettings.localLogin) ? (
<JellyfinLogin
serverType={settings.currentSettings.mediaServerType}
revalidate={revalidate}
/>
) : (
settings.currentSettings.localLogin && (
<LocalLogin revalidate={revalidate} />
)
)}
</div>
</CSSTransition>
</SwitchTransition>
)}
{additionalLoginOptions.length > 0 &&
(loginFormVisible ? (

View File

@@ -118,9 +118,11 @@ const ManageSlideOver = ({
}
};
const deleteMediaFile = async () => {
const deleteMediaFile = async (is4k = false) => {
if (data.mediaInfo) {
await axios.delete(`/api/v1/media/${data.mediaInfo.id}/file`);
await axios.delete(
`/api/v1/media/${data.mediaInfo.id}/file?is4k=${is4k}`
);
await axios.delete(`/api/v1/media/${data.mediaInfo.id}`);
revalidate();
onClose();
@@ -414,7 +416,7 @@ const ManageSlideOver = ({
isDefaultService() && (
<div>
<ConfirmButton
onClick={() => deleteMediaFile()}
onClick={() => deleteMediaFile(false)}
confirmText={intl.formatMessage(
globalMessages.areyousure
)}
@@ -573,7 +575,7 @@ const ManageSlideOver = ({
{isDefaultService() && (
<div>
<ConfirmButton
onClick={() => deleteMediaFile()}
onClick={() => deleteMediaFile(true)}
confirmText={intl.formatMessage(
globalMessages.areyousure
)}

View File

@@ -0,0 +1,91 @@
import defineMessages from '@app/utils/defineMessages';
import { useIntl } from 'react-intl';
import Select, { type StylesConfig } from 'react-select';
enum MetadataProviderType {
TMDB = 'tmdb',
TVDB = 'tvdb',
}
type MetadataProviderOptionType = {
testId?: string;
value: MetadataProviderType;
label: string;
};
const messages = defineMessages('components.MetadataSelector', {
tmdbLabel: 'The Movie Database (TMDB)',
tvdbLabel: 'TheTVDB',
selectMetdataProvider: 'Select a metadata provider',
});
interface MetadataSelectorProps {
testId: string;
value: MetadataProviderType;
onChange: (value: MetadataProviderType) => void;
isDisabled?: boolean;
}
const MetadataSelector = ({
testId = 'metadata-provider-selector',
value,
onChange,
isDisabled = false,
}: MetadataSelectorProps) => {
const intl = useIntl();
const metadataProviderOptions: MetadataProviderOptionType[] = [
{
testId: 'tmdb-option',
value: MetadataProviderType.TMDB,
label: intl.formatMessage(messages.tmdbLabel),
},
{
testId: 'tvdb-option',
value: MetadataProviderType.TVDB,
label: intl.formatMessage(messages.tvdbLabel),
},
];
const customStyles: StylesConfig<MetadataProviderOptionType, false> = {
option: (base) => ({
...base,
display: 'flex',
alignItems: 'center',
}),
singleValue: (base) => ({
...base,
display: 'flex',
alignItems: 'center',
}),
};
const formatOptionLabel = (option: MetadataProviderOptionType) => (
<div className="flex items-center">
<span data-testid={option.testId}>{option.label}</span>
</div>
);
return (
<div data-testid={testId}>
<Select
options={metadataProviderOptions}
isDisabled={isDisabled}
className="react-select-container"
classNamePrefix="react-select"
value={metadataProviderOptions.find((option) => option.value === value)}
onChange={(selectedOption) => {
if (selectedOption) {
onChange(selectedOption.value);
}
}}
placeholder={intl.formatMessage(messages.selectMetdataProvider)}
styles={customStyles}
formatOptionLabel={formatOptionLabel}
/>
</div>
);
};
export { MetadataProviderType };
export default MetadataSelector;

View File

@@ -99,7 +99,7 @@ const messages = defineMessages('components.MovieDetails', {
rtcriticsscore: 'Rotten Tomatoes Tomatometer',
rtaudiencescore: 'Rotten Tomatoes Audience Score',
tmdbuserscore: 'TMDB User Score',
imdbuserscore: 'IMDB User Score',
imdbuserscore: 'IMDB User Score votes: {formattedCount}',
watchlistSuccess: '<strong>{title}</strong> added to watchlist successfully!',
watchlistDeleted:
'<strong>{title}</strong> Removed from watchlist successfully!',
@@ -812,7 +812,18 @@ const MovieDetails = ({ movie }: MovieDetailsProps) => {
</Tooltip>
)}
{ratingData?.imdb?.criticsScore && (
<Tooltip content={intl.formatMessage(messages.imdbuserscore)}>
<Tooltip
content={intl.formatMessage(messages.imdbuserscore, {
formattedCount: intl.formatNumber(
ratingData.imdb.criticsScoreCount,
{
notation: 'compact',
compactDisplay: 'short',
maximumFractionDigits: 1,
}
),
})}
>
<a
href={ratingData.imdb.url}
className="media-rating"

View File

@@ -152,7 +152,6 @@ const PWAHeader = ({ applicationTitle = 'Jellyseerr' }: PWAHeaderProps) => {
href="/apple-splash-1136-640.jpg"
media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)"
/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta
name="apple-mobile-web-app-status-bar-style"
content="black-translucent"

View File

@@ -1,5 +1,6 @@
import Badge from '@app/components/Common/Badge';
import Button from '@app/components/Common/Button';
import CachedImage from '@app/components/Common/CachedImage';
import Tooltip from '@app/components/Common/Tooltip';
import RequestModal from '@app/components/RequestModal';
import useRequestOverride from '@app/hooks/useRequestOverride';
@@ -95,36 +96,58 @@ const RequestBlock = ({ request, onUpdate }: RequestBlockProps) => {
<div className="flex items-center justify-between">
<div className="mr-6 min-w-0 flex-1 flex-col items-center text-sm leading-5">
<div className="white mb-1 flex flex-nowrap">
<Tooltip content={intl.formatMessage(messages.requestedby)}>
<UserIcon className="mr-1.5 h-5 w-5 min-w-0 flex-shrink-0" />
</Tooltip>
<span className="w-40 truncate md:w-auto">
<span className="flex w-40 items-center truncate md:w-auto">
<Tooltip content={intl.formatMessage(messages.requestedby)}>
<UserIcon className="mr-1.5 h-5 w-5 min-w-0 flex-shrink-0" />
</Tooltip>
<Link
href={
request.requestedBy.id === user?.id
? '/profile'
: `/users/${request.requestedBy.id}`
}
className="font-semibold text-gray-100 transition duration-300 hover:text-white hover:underline"
className="flex items-center font-semibold text-gray-100 transition duration-300 hover:text-white hover:underline"
>
<span className="avatar-sm">
<CachedImage
type="avatar"
src={request.requestedBy.avatar}
alt=""
className="avatar-sm object-cover"
width={20}
height={20}
/>
</span>
{request.requestedBy.displayName}
</Link>
</span>
</div>
{request.modifiedBy && (
<div className="flex flex-nowrap">
<Tooltip content={intl.formatMessage(messages.lastmodifiedby)}>
<EyeIcon className="mr-1.5 h-5 w-5 flex-shrink-0" />
</Tooltip>
<span className="w-40 truncate md:w-auto">
<span className="flex w-40 items-center truncate md:w-auto">
<Tooltip
content={intl.formatMessage(messages.lastmodifiedby)}
>
<EyeIcon className="mr-1.5 h-5 w-5 flex-shrink-0" />
</Tooltip>
<Link
href={
request.modifiedBy.id === user?.id
? '/profile'
: `/users/${request.modifiedBy.id}`
}
className="font-semibold text-gray-100 transition duration-300 hover:text-white hover:underline"
className="flex items-center font-semibold text-gray-100 transition duration-300 hover:text-white hover:underline"
>
<span className="avatar-sm">
<CachedImage
type="avatar"
src={request.modifiedBy.avatar}
alt=""
className="avatar-sm object-cover"
width={20}
height={20}
/>
</span>
{request.modifiedBy.displayName}
</Link>
</span>

View File

@@ -343,7 +343,9 @@ const RequestItem = ({ request, revalidateList }: RequestItemProps) => {
const deleteMediaFile = async () => {
if (request.media) {
await axios.delete(`/api/v1/media/${request.media.id}/file`);
await axios.delete(
`/api/v1/media/${request.media.id}/file?is4k=${request.is4k}`
);
await axios.delete(`/api/v1/media/${request.media.id}`);
revalidateList();
}

View File

@@ -309,16 +309,19 @@ export const KeywordSelector = ({
const keywords = await Promise.all(
defaultValue.split(',').map(async (keywordId) => {
const keyword = await axios.get<Keyword>(
const keyword = await axios.get<Keyword | null>(
`/api/v1/keyword/${keywordId}`
);
return keyword.data;
})
);
const validKeywords: Keyword[] = keywords.filter(
(keyword): keyword is Keyword => keyword !== null
);
setDefaultDataValue(
keywords.map((keyword) => ({
validKeywords.map((keyword) => ({
label: keyword.name,
value: keyword.id,
}))

View File

@@ -0,0 +1,366 @@
import Accordion from '@app/components/Common/Accordion';
import Modal from '@app/components/Common/Modal';
import SensitiveInput from '@app/components/Common/SensitiveInput';
import globalMessages from '@app/i18n/globalMessages';
import defineMessages from '@app/utils/defineMessages';
import { Transition } from '@headlessui/react';
import { ChevronRightIcon } from '@heroicons/react/20/solid';
import { MagnifyingGlassIcon } from '@heroicons/react/24/solid';
import type { OidcProvider } from '@server/lib/settings';
import axios from 'axios';
import { Field, Formik, useFormikContext, type FieldAttributes } from 'formik';
import { useEffect } from 'react';
import { useIntl } from 'react-intl';
import { useToasts } from 'react-toast-notifications';
import { twMerge } from 'tailwind-merge';
import * as Yup from 'yup';
const messages = defineMessages('settings.settings.SettingsOidc', {
required: '{field} is required',
url: '{field} must be a valid URL',
addoidc: 'Add New OpenID Connect Provider',
editoidc: 'Edit {name}',
oidcDomain: 'Issuer URL',
oidcDomainTip:
"The base URL of the identity provider's OpenID Connect endpoint",
oidcSlug: 'Provider Slug',
oidcSlugTip: 'Unique identifier for the provider',
oidcName: 'Provider Name',
oidcNameTip: 'Name of the provider which appears on the login screen',
oidcClientId: 'Client ID',
oidcClientIdTip: 'The Client ID assigned to Jellyseerr',
oidcClientSecret: 'Client Secret',
oidcClientSecretTip: 'The Client Secret assigned to Jellyseerr',
oidcLogo: 'Logo',
oidcLogoTip:
'The logo to display for the provider. Should be a URL or base64 encoded image',
oidcScopes: 'Scopes',
oidcScopesTip: 'Space-separated list of scopes to request from the provider',
oidcRequiredClaims: 'Required Claims',
oidcRequiredClaimsTip:
'Space-separated list of boolean claims that are required to log in',
oidcNewUserLogin: 'Allow New Users',
oidcNewUserLoginTip:
'Create accounts for new users logging in with this provider',
saveSuccess: 'OpenID Connect provider saved successfully!',
saveError: 'Failed to save OpenID Connect provider configuration',
});
interface EditOidcModalProps {
show: boolean;
provider?: OidcProvider;
onClose: () => void;
onOk: () => void;
}
function SlugField(props: FieldAttributes<unknown> & { readOnly?: boolean }) {
const {
values: { name },
setFieldValue,
} = useFormikContext<Partial<OidcProvider>>();
useEffect(() => {
if (!props.readOnly)
setFieldValue(props.name, name?.toLowerCase().replace(/\s/g, '-'));
}, [props.name, props.readOnly, name, setFieldValue]);
return <Field {...props} />;
}
export default function EditOidcModal(props: EditOidcModalProps) {
const intl = useIntl();
const { addToast } = useToasts();
const errorMessage = (
field: keyof typeof messages,
message: keyof typeof messages = 'required'
) =>
intl.formatMessage(messages[message], {
field: intl.formatMessage(messages[field]),
});
const oidcSettingsSchema = Yup.object().shape({
slug: Yup.string().required(errorMessage('oidcSlug')),
name: Yup.string().required(errorMessage('oidcName')),
issuerUrl: Yup.string()
.url(errorMessage('oidcDomain', 'url'))
.required(errorMessage('oidcDomain')),
clientId: Yup.string().required(errorMessage('oidcClientId')),
clientSecret: Yup.string().required(errorMessage('oidcClientSecret')),
logo: Yup.string(),
requiredClaims: Yup.string(),
scopes: Yup.string(),
newUserLogin: Yup.boolean(),
});
const onSubmit = async ({ slug, ...provider }: OidcProvider) => {
try {
await axios.put(`/api/v1/settings/oidc/${slug}`, provider);
addToast(intl.formatMessage(messages.saveSuccess), {
appearance: 'success',
autoDismiss: true,
});
props.onOk();
} catch (e) {
addToast(intl.formatMessage(messages.saveError), {
appearance: 'error',
autoDismiss: true,
});
}
};
return (
<Transition show={props.show}>
<Formik
initialValues={{
slug: props.provider?.slug ?? '',
name: props.provider?.name ?? '',
issuerUrl: props.provider?.issuerUrl ?? '',
clientId: props.provider?.clientId ?? '',
clientSecret: props.provider?.clientSecret ?? '',
logo: props.provider?.logo,
requiredClaims: props.provider?.requiredClaims,
scopes: props.provider?.scopes,
newUserLogin: props.provider?.newUserLogin,
}}
validationSchema={oidcSettingsSchema}
onSubmit={onSubmit}
enableReinitialize
>
{({ handleSubmit, isValid, errors, touched }) => (
<Modal
onCancel={props.onClose}
cancelButtonProps={{ type: 'button' }}
okButtonType="primary"
okButtonProps={{ type: 'button' }}
okDisabled={!isValid}
onOk={() => handleSubmit()}
okText={intl.formatMessage(globalMessages.save)}
title={
props.provider
? intl.formatMessage(messages.editoidc, {
name: props.provider.name,
})
: intl.formatMessage(messages.addoidc)
}
>
<div className="form-row">
<label htmlFor="oidcName" className="text-label">
{intl.formatMessage(messages.oidcName)}
<span className="label-required">*</span>
<span className="label-tip">
{intl.formatMessage(messages.oidcNameTip)}
</span>
</label>
<div className="form-input-area">
<Field id="oidcName" name="name" type="text" />
{errors.name &&
touched.name &&
typeof errors.name === 'string' && (
<div className="error">{errors.name}</div>
)}
</div>
</div>
<div className="form-row">
<label htmlFor="oidcLogo" className="text-label">
{intl.formatMessage(messages.oidcLogo)}
<span className="label-tip">
{intl.formatMessage(messages.oidcLogoTip)}
</span>
</label>
<div className="form-input-area">
<div className="relative">
<Field
id="oidcLogo"
name="logo"
type="text"
className="pr-10"
/>
<a
className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 transition-colors hover:text-gray-200"
href="https://selfh.st/icons"
target="_blank"
rel="noreferrer noopener"
>
<MagnifyingGlassIcon className="h-4 w-4" />
</a>
</div>
{errors.logo &&
touched.logo &&
typeof errors.logo === 'string' && (
<div className="error">{errors.logo}</div>
)}
</div>
</div>
<div className="form-row">
<label htmlFor="oidcDomain" className="text-label">
{intl.formatMessage(messages.oidcDomain)}
<span className="label-required">*</span>
<span className="label-tip">
{intl.formatMessage(messages.oidcDomainTip)}
</span>
</label>
<div className="form-input-area">
<Field id="oidcDomain" name="issuerUrl" type="text" />
{errors.issuerUrl &&
touched.issuerUrl &&
typeof errors.issuerUrl === 'string' && (
<div className="error">{errors.issuerUrl}</div>
)}
</div>
</div>
<div className="form-row">
<label htmlFor="oidcClientId" className="text-label">
{intl.formatMessage(messages.oidcClientId)}
<span className="label-required">*</span>
<span className="label-tip">
{intl.formatMessage(messages.oidcClientIdTip)}
</span>
</label>
<div className="form-input-area">
<Field id="oidcClientId" name="clientId" type="text" />
{errors.clientId &&
touched.clientId &&
typeof errors.clientId === 'string' && (
<div className="error">{errors.clientId}</div>
)}
</div>
</div>
<div className="form-row">
<label htmlFor="oidcClientSecret" className="text-label">
{intl.formatMessage(messages.oidcClientSecret)}
<span className="label-required">*</span>
<span className="label-tip">
{intl.formatMessage(messages.oidcClientSecretTip)}
</span>
</label>
<div className="form-input-area">
<div className="flex">
<SensitiveInput
id="oidcClientSecret"
name="clientSecret"
as="field"
autoComplete="new-password"
/>
</div>
{errors.clientSecret &&
touched.clientSecret &&
typeof errors.clientSecret === 'string' && (
<div className="error">{errors.clientSecret}</div>
)}
</div>
</div>
{/* Advanced Settings */}
<Accordion>
{({ openIndexes, AccordionContent, handleClick }) => (
<>
<button
type="button"
onClick={() => handleClick(0)}
className="flex w-full items-center gap-0.5 py-4 font-bold text-gray-400"
>
<ChevronRightIcon
width={18}
className={twMerge(
'transition-transform',
openIndexes.includes(0) ? 'rotate-90' : ''
)}
/>
Advanced Settings
</button>
<AccordionContent isOpen={openIndexes.includes(0)}>
<div className="form-row mt-0">
<label htmlFor="oidcSlug" className="text-label">
{intl.formatMessage(messages.oidcSlug)}
<span className="label-required">*</span>
<span className="label-tip">
{intl.formatMessage(messages.oidcSlugTip)}
</span>
</label>
<div className="form-input-area">
<SlugField
id="oidcSlug"
name="slug"
type="text"
readOnly={props.provider != null}
disabled={props.provider != null}
className={props.provider != null ? 'opacity-50' : ''}
/>
{errors.slug &&
touched.slug &&
typeof errors.slug === 'string' && (
<div className="error">{errors.slug}</div>
)}
</div>
</div>
<div className="form-row">
<label htmlFor="oidcScopes" className="text-label">
{intl.formatMessage(messages.oidcScopes)}
<span className="label-tip">
{intl.formatMessage(messages.oidcScopesTip)}
</span>
</label>
<div className="form-input-area">
<Field id="oidcScopes" name="scopes" type="text" />
{errors.scopes &&
touched.scopes &&
typeof errors.scopes === 'string' && (
<div className="error">{errors.scopes}</div>
)}
</div>
</div>
<div className="form-row">
<label
htmlFor="oidcRequiredClaims"
className="text-label"
>
{intl.formatMessage(messages.oidcRequiredClaims)}
<span className="label-tip">
{intl.formatMessage(messages.oidcRequiredClaimsTip)}
</span>
</label>
<div className="form-input-area">
<Field
id="oidcRequiredClaims"
name="requiredClaims"
type="text"
/>
{errors.requiredClaims &&
touched.requiredClaims &&
typeof errors.requiredClaims === 'string' && (
<div className="error">{errors.requiredClaims}</div>
)}
</div>
</div>
<div className="form-row">
<label htmlFor="oidcNewUserLogin" className="text-label">
{intl.formatMessage(messages.oidcNewUserLogin)}
<span className="label-tip">
{intl.formatMessage(messages.oidcNewUserLoginTip)}
</span>
</label>
<div className="form-input-area">
<Field
id="oidcNewUserLogin"
name="newUserLogin"
type="checkbox"
/>
{errors.newUserLogin &&
touched.newUserLogin &&
typeof errors.newUserLogin === 'string' && (
<div className="error">{errors.newUserLogin}</div>
)}
</div>
</div>
</AccordionContent>
</>
)}
</Accordion>
</Modal>
)}
</Formik>
</Transition>
);
}

View File

@@ -15,6 +15,7 @@ import * as Yup from 'yup';
const messages = defineMessages('components.Settings.Notifications', {
agentenabled: 'Enable Agent',
embedPoster: 'Embed Poster',
botUsername: 'Bot Username',
botAvatarUrl: 'Bot Avatar URL',
webhookUrl: 'Webhook URL',
@@ -74,6 +75,7 @@ const NotificationsDiscord = () => {
<Formik
initialValues={{
enabled: data.enabled,
embedPoster: data.embedPoster,
types: data.types,
botUsername: data?.options.botUsername,
botAvatarUrl: data?.options.botAvatarUrl,
@@ -86,6 +88,7 @@ const NotificationsDiscord = () => {
try {
await axios.post('/api/v1/settings/notifications/discord', {
enabled: values.enabled,
embedPoster: values.embedPoster,
types: values.types,
options: {
botUsername: values.botUsername,
@@ -135,6 +138,7 @@ const NotificationsDiscord = () => {
);
await axios.post('/api/v1/settings/notifications/discord/test', {
enabled: true,
embedPoster: values.embedPoster,
types: values.types,
options: {
botUsername: values.botUsername,
@@ -176,6 +180,14 @@ const NotificationsDiscord = () => {
<Field type="checkbox" id="enabled" name="enabled" />
</div>
</div>
<div className="form-row">
<label htmlFor="embedPoster" className="checkbox-label">
{intl.formatMessage(messages.embedPoster)}
</label>
<div className="form-input-area">
<Field type="checkbox" id="embedPoster" name="embedPoster" />
</div>
</div>
<div className="form-row">
<label htmlFor="name" className="text-label">
{intl.formatMessage(messages.webhookUrl)}

View File

@@ -17,6 +17,7 @@ const messages = defineMessages('components.Settings.Notifications', {
validationSmtpHostRequired: 'You must provide a valid hostname or IP address',
validationSmtpPortRequired: 'You must provide a valid port number',
agentenabled: 'Enable Agent',
embedPoster: 'Embed Poster',
userEmailRequired: 'Require user email',
emailsender: 'Sender Address',
smtpHost: 'SMTP Host',
@@ -122,6 +123,7 @@ const NotificationsEmail = () => {
<Formik
initialValues={{
enabled: data.enabled,
embedPoster: data.embedPoster,
userEmailRequired: data.options.userEmailRequired,
emailFrom: data.options.emailFrom,
smtpHost: data.options.smtpHost,
@@ -145,6 +147,7 @@ const NotificationsEmail = () => {
try {
await axios.post('/api/v1/settings/notifications/email', {
enabled: values.enabled,
embedPoster: values.embedPoster,
options: {
userEmailRequired: values.userEmailRequired,
emailFrom: values.emailFrom,
@@ -194,6 +197,7 @@ const NotificationsEmail = () => {
);
await axios.post('/api/v1/settings/notifications/email/test', {
enabled: true,
embedPoster: values.embedPoster,
options: {
emailFrom: values.emailFrom,
smtpHost: values.smtpHost,
@@ -241,6 +245,14 @@ const NotificationsEmail = () => {
<Field type="checkbox" id="enabled" name="enabled" />
</div>
</div>
<div className="form-row">
<label htmlFor="embedPoster" className="checkbox-label">
{intl.formatMessage(messages.embedPoster)}
</label>
<div className="form-input-area">
<Field type="checkbox" id="embedPoster" name="embedPoster" />
</div>
</div>
<div className="form-row">
<label htmlFor="userEmailRequired" className="checkbox-label">
{intl.formatMessage(messages.userEmailRequired)}

View File

@@ -19,6 +19,7 @@ const messages = defineMessages(
'components.Settings.Notifications.NotificationsNtfy',
{
agentenabled: 'Enable Agent',
embedPoster: 'Embed Poster',
url: 'Server root URL',
topic: 'Topic',
usernamePasswordAuth: 'Username + Password authentication',
@@ -80,6 +81,7 @@ const NotificationsNtfy = () => {
<Formik
initialValues={{
enabled: data?.enabled,
embedPoster: data?.embedPoster,
types: data?.types,
url: data?.options.url,
topic: data?.options.topic,
@@ -94,6 +96,7 @@ const NotificationsNtfy = () => {
try {
await axios.post('/api/v1/settings/notifications/ntfy', {
enabled: values.enabled,
embedPoster: values.embedPoster,
types: values.types,
options: {
url: values.url,
@@ -188,6 +191,14 @@ const NotificationsNtfy = () => {
<Field type="checkbox" id="enabled" name="enabled" />
</div>
</div>
<div className="form-row">
<label htmlFor="embedPoster" className="checkbox-label">
{intl.formatMessage(messages.embedPoster)}
</label>
<div className="form-input-area">
<Field type="checkbox" id="embedPoster" name="embedPoster" />
</div>
</div>
<div className="form-row">
<label htmlFor="url" className="text-label">
{intl.formatMessage(messages.url)}

View File

@@ -17,6 +17,7 @@ const messages = defineMessages(
'components.Settings.Notifications.NotificationsPushover',
{
agentenabled: 'Enable Agent',
embedPoster: 'Embed Poster',
accessToken: 'Application API Token',
accessTokenTip:
'<ApplicationRegistrationLink>Register an application</ApplicationRegistrationLink> for use with Jellyseerr',
@@ -86,6 +87,7 @@ const NotificationsPushover = () => {
<Formik
initialValues={{
enabled: data?.enabled,
embedPoster: data?.embedPoster,
types: data?.types,
accessToken: data?.options.accessToken,
userToken: data?.options.userToken,
@@ -96,6 +98,7 @@ const NotificationsPushover = () => {
try {
await axios.post('/api/v1/settings/notifications/pushover', {
enabled: values.enabled,
embedPoster: values.embedPoster,
types: values.types,
options: {
accessToken: values.accessToken,
@@ -142,6 +145,7 @@ const NotificationsPushover = () => {
);
await axios.post('/api/v1/settings/notifications/pushover/test', {
enabled: true,
embedPoster: values.embedPoster,
types: values.types,
options: {
accessToken: values.accessToken,
@@ -181,6 +185,14 @@ const NotificationsPushover = () => {
<Field type="checkbox" id="enabled" name="enabled" />
</div>
</div>
<div className="form-row">
<label htmlFor="embedPoster" className="checkbox-label">
{intl.formatMessage(messages.embedPoster)}
</label>
<div className="form-input-area">
<Field type="checkbox" id="embedPoster" name="embedPoster" />
</div>
</div>
<div className="form-row">
<label htmlFor="accessToken" className="text-label">
{intl.formatMessage(messages.accessToken)}

View File

@@ -16,6 +16,7 @@ const messages = defineMessages(
'components.Settings.Notifications.NotificationsSlack',
{
agentenabled: 'Enable Agent',
embedPoster: 'Embed Poster',
webhookUrl: 'Webhook URL',
webhookUrlTip:
'Create an <WebhookLink>Incoming Webhook</WebhookLink> integration',
@@ -59,6 +60,7 @@ const NotificationsSlack = () => {
<Formik
initialValues={{
enabled: data.enabled,
embedPoster: data.embedPoster,
types: data.types,
webhookUrl: data.options.webhookUrl,
}}
@@ -67,6 +69,7 @@ const NotificationsSlack = () => {
try {
await axios.post('/api/v1/settings/notifications/slack', {
enabled: values.enabled,
embedPoster: values.embedPoster,
types: values.types,
options: {
webhookUrl: values.webhookUrl,
@@ -111,6 +114,7 @@ const NotificationsSlack = () => {
);
await axios.post('/api/v1/settings/notifications/slack/test', {
enabled: true,
embedPoster: values.embedPoster,
types: values.types,
options: {
webhookUrl: values.webhookUrl,
@@ -148,6 +152,14 @@ const NotificationsSlack = () => {
<Field type="checkbox" id="enabled" name="enabled" />
</div>
</div>
<div className="form-row">
<label htmlFor="embedPoster" className="checkbox-label">
{intl.formatMessage(messages.embedPoster)}
</label>
<div className="form-input-area">
<Field type="checkbox" id="embedPoster" name="embedPoster" />
</div>
</div>
<div className="form-row">
<label htmlFor="name" className="text-label">
{intl.formatMessage(messages.webhookUrl)}

Some files were not shown because too many files have changed in this diff Show More