From d57421ee728a5fa05d774ca719306ca5996a1be0 Mon Sep 17 00:00:00 2001 From: snapetech Date: Tue, 13 Oct 2026 13:56:11 -0600 Subject: [PATCH 1/3] feat(users): add opt-in Jellyfin and Emby import sync --- README.md | 2 + cypress/e2e/user/user-list.cy.ts | 85 ++++ docs/maintainers/ui-fix-it.md | 7 +- docs/maintainers/ui-style-standard.md | 1 + docs/using-seerr/users/adding-users.mdx | 4 + .../jellyfin-emby-user-import-sync.md | 9 + seerr-api.yml | 31 +- server/routes/settings/index.ts | 29 +- server/routes/settingsIndex.test.ts | 71 +++ server/routes/user.test.ts | 271 +++++++++++ server/routes/user/index.ts | 151 ++++-- src/components/Common/CachedImage/index.tsx | 4 +- .../UserList/JellyfinImportModal.tsx | 439 +++++++++--------- src/components/UserList/index.tsx | 18 +- .../UserList/userSelectionMessages.ts | 8 + src/i18n/locale/en.json | 12 +- src/styles/globals.css | 4 + 17 files changed, 871 insertions(+), 275 deletions(-) create mode 100644 release-notes/jellyfin-emby-user-import-sync.md create mode 100644 src/components/UserList/userSelectionMessages.ts diff --git a/README.md b/README.md index 64a356d53..90924b26b 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ SeerrNG is maintained by snapetech as a separate fork so we can move quickly on - [Configure comics](./docs/using-seerr/comics-backend.md) - [Configure magazines](./docs/using-seerr/magazines-backend.md) - [Companion services and SeerrNG NG forks](./docs/using-seerr/companion-services.md) + - [Add and import users](./docs/using-seerr/users/adding-users.mdx) - [Why SeerrNG is a fork and what could retire it](./docs/fork-rationale.md) - [Cross-platform setup assistant](./docs/using-seerr/setup-assistant.md) - [Indexer searches by media category](./docs/using-seerr/indexer-searches.md) @@ -59,6 +60,7 @@ SeerrNG is maintained by snapetech as a separate fork so we can move quickly on - Requests and approvals for movies, shows, music, ebooks, audiobooks, comics, magazines, emulation ROMs, and PC games. - Media-server integration with Plex, Jellyfin, and Emby, including watch-state-aware My Library views scoped to each linked account. +- Optional Jellyfin and Emby profile sync during user imports, refreshing linked provider names and avatars while preserving SeerrNG email addresses, local passwords, and permissions. - Automation service integration with Radarr, Sonarr, Lidarr, and Bookshelf/Readarr-compatible APIs. - Admin-configured Prowlarr connection, per-indexer diagnostics, category coverage, and format-aware manual search across movies, TV, music, books, comics, magazines, ROMs, and PC games, with title-prefilled search links from media details; approved requests still go through their configured acquisition providers. - Music discovery and metadata through MusicBrainz, ListenBrainz, Cover Art Archive, TheAudioDB, and archive-backed artwork sources. diff --git a/cypress/e2e/user/user-list.cy.ts b/cypress/e2e/user/user-list.cy.ts index 7beed4a47..4673f1abb 100644 --- a/cypress/e2e/user/user-list.cy.ts +++ b/cypress/e2e/user/user-list.cy.ts @@ -110,4 +110,89 @@ describe('User List', () => { expect(settings.sortDirection).to.equal('asc'); }); }); + + it('refreshes selected linked media-server users only after opting in', () => { + const importedUserId = '88888888888888888888888888888888'; + const newUserId = '99999999999999999999999999999999'; + + cy.intercept('GET', '/api/v1/settings/public', (request) => { + request.continue((response) => { + // MediaServerType.JELLYFIN; keep this browser test isolated from the configured provider. + response.body.mediaServerType = 2; + }); + }); + cy.intercept('GET', '/api/v1/settings/jellyfin/users', { + statusCode: 200, + body: [ + { + id: importedUserId, + username: 'Linked Jellyfin User', + thumb: '/user-icon-192x192.png', + email: 'linked@example.com', + isImported: true, + }, + { + id: newUserId, + username: 'New Jellyfin User', + thumb: '/user-icon-192x192.png', + email: 'new@example.com', + isImported: false, + }, + ], + }).as('jellyfinUsers'); + cy.intercept('POST', '/api/v1/user/import-from-jellyfin', { + statusCode: 201, + body: { createdUsers: [], refreshedUsers: 1 }, + }).as('jellyfinImport'); + + cy.visit('/users'); + cy.contains('button', /Import (Jellyfin|Emby) Users/).click(); + cy.wait('@jellyfinUsers'); + + cy.get('[data-testid=jellyfin-sync-existing]').should('not.be.checked'); + cy.get(`[data-testid=jellyfin-import-user-${importedUserId}]`).should( + 'not.exist' + ); + cy.get(`[data-testid=jellyfin-import-user-${newUserId}]`).should('exist'); + cy.get( + `[data-testid=jellyfin-import-user-${newUserId}] svg.cached-image-avatar-fallback` + ) + .should('have.attr', 'width', '20') + .and('have.attr', 'height', '20'); + cy.get( + `[data-testid=jellyfin-import-user-${newUserId}] svg.cached-image-avatar-fallback` + ).should(($icon) => { + expect(($icon[0] as SVGSVGElement).getBoundingClientRect()).to.include({ + width: 20, + height: 20, + }); + }); + + cy.get('[data-testid=jellyfin-sync-existing]').check(); + cy.get( + `[data-testid=jellyfin-user-import-status-${importedUserId}]` + ).should('contain', 'Already Imported'); + cy.get( + `[data-testid=jellyfin-import-user-${importedUserId}] svg.cached-image-avatar-fallback` + ) + .should('have.attr', 'width', '20') + .and('have.attr', 'height', '20'); + cy.get( + `[data-testid=jellyfin-import-user-${importedUserId}] svg.cached-image-avatar-fallback` + ).should(($icon) => { + expect(($icon[0] as SVGSVGElement).getBoundingClientRect()).to.include({ + width: 20, + height: 20, + }); + }); + cy.get(`[data-testid=jellyfin-select-user-${importedUserId}]`).click(); + cy.get('[data-testid=modal-ok-button]').click(); + + cy.wait('@jellyfinImport').then(({ request }) => { + expect(request.body).to.deep.equal({ + jellyfinUserIds: [importedUserId], + syncExisting: true, + }); + }); + }); }); diff --git a/docs/maintainers/ui-fix-it.md b/docs/maintainers/ui-fix-it.md index 6b463fc93..211571568 100644 --- a/docs/maintainers/ui-fix-it.md +++ b/docs/maintainers/ui-fix-it.md @@ -19,9 +19,10 @@ Use [UI Style Standard](ui-style-standard.md) as the target contract. This file 3. Trace headings and titles through their typography roles and active translations/generated helpers. Detect Title Case and punctuation drift by role. Do not create checks keyed to exact example titles, badges, message strings or media names. 4. Search Tailwind use in JSX and styles, including `@apply`, utility aliases, generated `--tw-*` machinery and nested state/media rules. A zero literal-utility count in one component is not a completed dependency audit or native-CSS conversion. 5. Map each observed presentation property to its existing shared owner. Include typography, dimensions, padding/gap/margins, alignment, ratio/crop, border/surface, icon geometry, state effects, transitions, scrollbars and breakpoints. -6. Distinguish external/native classes and meaningful data geometry from presentation utilities. Country flags, provider branding, portrait/mosaic arrangements, runtime pointer bounds and native identifiers are not automatically removable because their names look unfamiliar. -7. Follow source/generated reference relationships and active palette/mode variants. Preserve opt-in reference pages; do not audit a generated preview as if it were the only source or silently adopt its experimental style. -8. Include loading placeholders in the asset inventory. Trace both whole-section loading and per-item lazy/partial metadata branches to the card family they replace. Compare them with established loaded examples at the family's breakpoints; do not assume a shared placeholder component selects the correct variant in every caller. +6. For avatar consumers, inspect both loaded and fallback states at the requested size. Compare the rendered fallback box with its caller-owned dimensions; SVG width/height attributes alone do not prove that padding or other CSS kept the glyph contained. +7. Distinguish external/native classes and meaningful data geometry from presentation utilities. Country flags, provider branding, portrait/mosaic arrangements, runtime pointer bounds and native identifiers are not automatically removable because their names look unfamiliar. +8. Follow source/generated reference relationships and active palette/mode variants. Preserve opt-in reference pages; do not audit a generated preview as if it were the only source or silently adopt its experimental style. +9. Include loading placeholders in the asset inventory. Trace both whole-section loading and per-item lazy/partial metadata branches to the card family they replace. Compare them with established loaded examples at the family's breakpoints; do not assume a shared placeholder component selects the correct variant in every caller. ## 3. Find ownership and layout regressions diff --git a/docs/maintainers/ui-style-standard.md b/docs/maintainers/ui-style-standard.md index 1426b7b7a..2ab67862f 100644 --- a/docs/maintainers/ui-style-standard.md +++ b/docs/maintainers/ui-style-standard.md @@ -28,6 +28,7 @@ The rules describe asset roles, not particular pages, title strings, example med 8. Primary navigation: `sidebar-navigation`, `sidebar-navigation-section`, `sidebar-navigation-heading`, `sidebar-navigation-items`, and `main-menu-link`. Desktop, the mobile drawer, and the mobile bottom menu consume one ordered route model; route availability and permission checks stay attached to each link. Section headings and nested items express grouping without changing a route's access rules. 9. Messages and recovery: `page-error-message` and the shared Retry action. Selection: `selection-circle`; hierarchical selection: `selection-tree` together with table/card roles. 10. Software catalog ownership uses the catalog library badge with the shared compact badge geometry. Play-time estimates use the dedicated readable text role within the existing card-table layout. +11. Cached avatar fallbacks use the caller's avatar dimensions and the shared `cached-image-avatar-fallback` icon color role. Keep their glyph inside that box; percentage padding resolves against the surrounding layout and can expand the avatar beyond its requested size. This map identifies owners, not a whitelist of every valid class. Follow the existing family for the asset and verify its cascade before proposing another family. diff --git a/docs/using-seerr/users/adding-users.mdx b/docs/using-seerr/users/adding-users.mdx index 95d660fe3..c4aba0e57 100644 --- a/docs/using-seerr/users/adding-users.mdx +++ b/docs/using-seerr/users/adding-users.mdx @@ -17,6 +17,8 @@ import TabItem from '@theme/TabItem'; Clicking the **Import Jellyfin Users** button on the **User List** page will fetch the list of users with access to the Jellyfin server and add them to Seerr automatically. + To refresh an account that is already linked, turn on **Sync Existing Users** before selecting users to import. This option is off by default. It refreshes the Jellyfin username and profile photo while preserving the SeerrNG email address, local username and password, and permissions. New and linked users can be selected in the same import. + Importing Jellyfin users is not required, however. Any user with access to the Jellyfin server can log in to Seerr even if they have not been imported, and will be assigned the configured [default permissions](/using-seerr/settings/users#default-permissions) upon their first login. :::tip @@ -27,6 +29,8 @@ To disable new Jellyfin sign-ins, navigate to **Settings → Users** and unch Clicking the **Import Emby Users** button on the **User List** page will fetch the list of users with access to the Emby server and add them to Seerr automatically. + To refresh an account that is already linked, turn on **Sync Existing Users** before selecting users to import. This option is off by default. It refreshes the Emby username and profile photo while preserving the SeerrNG email address, local username and password, and permissions. New and linked users can be selected in the same import. + Importing Emby users is not required, however. Any user with access to the Emby server can log in to Seerr even if they have not been imported, and will be assigned the configured [default permissions](/using-seerr/settings/users#default-permissions) upon their first login. :::tip diff --git a/release-notes/jellyfin-emby-user-import-sync.md b/release-notes/jellyfin-emby-user-import-sync.md new file mode 100644 index 000000000..f2d5a60ca --- /dev/null +++ b/release-notes/jellyfin-emby-user-import-sync.md @@ -0,0 +1,9 @@ +--- +category: changed +audience: users, operators +area: user-management +action: none +breaking: false +--- + +Administrators can refresh linked Jellyfin and Emby usernames and profile photos while importing users. SeerrNG email addresses, local credentials, and permissions remain unchanged. Fallback profile icons keep the requested avatar size so missing photos do not push user names out of alignment. diff --git a/seerr-api.yml b/seerr-api.yml index 4830a29db..3aa4f75e0 100644 --- a/seerr-api.yml +++ b/seerr-api.yml @@ -7598,6 +7598,9 @@ paths: type: string email: type: string + isImported: + type: boolean + description: Whether this media server account is already linked to a SeerrNG user. /settings/jellyfin/sync: get: summary: Get status of full Jellyfin library sync @@ -11879,7 +11882,9 @@ paths: post: summary: Import all users from Jellyfin description: | - Fetches and imports users from the Jellyfin server. + Fetches selected users from the configured Jellyfin or Emby server and imports any accounts not already linked. + + When `syncExisting` is true, linked users are also refreshed. Only the provider username and avatar are updated; SeerrNG email, local credentials, and permissions are preserved. This opt-in mode returns created and refreshed counts. Requests that omit `syncExisting` keep the legacy array response. Requires the `MANAGE_USERS` permission. tags: @@ -11895,15 +11900,31 @@ paths: type: array items: type: string + syncExisting: + type: boolean + description: Refresh provider usernames and avatars for selected users already linked to SeerrNG. responses: '201': - description: A list of the newly created users + description: Newly created users, or created users and a refreshed count when syncExisting is true. content: application/json: schema: - type: array - items: - $ref: '#/components/schemas/User' + oneOf: + - type: array + items: + $ref: '#/components/schemas/User' + - type: object + required: + - createdUsers + - refreshedUsers + properties: + createdUsers: + type: array + items: + $ref: '#/components/schemas/User' + refreshedUsers: + type: integer + minimum: 0 /user/registerPushSubscription: post: summary: Register a web push /user/registerPushSubscription diff --git a/server/routes/settings/index.ts b/server/routes/settings/index.ts index 8d768bf4b..2fb9c4f45 100644 --- a/server/routes/settings/index.ts +++ b/server/routes/settings/index.ts @@ -83,6 +83,7 @@ import { mapWithConcurrency } from '@server/utils/concurrency'; import { dnsCache } from '@server/utils/dnsCache'; import { getHostname } from '@server/utils/getHostname'; import { parseListenPort } from '@server/utils/httpServer'; +import { normalizeJellyfinGuid } from '@server/utils/jellyfin'; import { parsePageParams } from '@server/utils/pagination'; import { parsePositiveRouteId } from '@server/utils/routeId'; import { @@ -2099,12 +2100,28 @@ settingsRoutes.get('/jellyfin/users', async (req, res) => jellyfinClient.setUserId(admin.jellyfinUserId ?? ''); const resp = await jellyfinClient.getUsers(); - const jellyfinUsers = resp.users.map((user) => ({ - username: user.Name, - id: user.Id, - thumb: `/avatarproxy/${user.Id}`, - email: user.Name, - })); + const importedUserRows = await userRepository.find({ + select: { jellyfinUserId: true }, + }); + const importedUserIds = new Set( + importedUserRows + .map((user) => normalizeJellyfinGuid(user.jellyfinUserId)) + .filter((userId): userId is string => Boolean(userId)) + ); + const jellyfinUsers = resp.users.flatMap((user) => { + const id = normalizeJellyfinGuid(user.Id); + if (!id) return []; + + return [ + { + username: user.Name, + id, + thumb: `/avatarproxy/${id}`, + email: user.Name, + isImported: importedUserIds.has(id), + }, + ]; + }); return res.status(200).json(jellyfinUsers); }) diff --git a/server/routes/settingsIndex.test.ts b/server/routes/settingsIndex.test.ts index ac4eaf5c0..1197b62d4 100644 --- a/server/routes/settingsIndex.test.ts +++ b/server/routes/settingsIndex.test.ts @@ -8,6 +8,7 @@ import PlexAPI from '@server/api/plexapi'; import PlexTvAPI, { MAX_PLEX_SHARED_USERS } from '@server/api/plextv'; import TautulliAPI from '@server/api/tautulli'; import { MediaServerType } from '@server/constants/server'; +import { UserType } from '@server/constants/user'; import { getRepository } from '@server/datasource'; import { ScheduledJobLease } from '@server/entity/ScheduledJobLease'; import { User } from '@server/entity/User'; @@ -262,6 +263,76 @@ describe('Settings route input validation', () => { assert.strictEqual(res.body.message, 'Jellyfin is not configured.'); }); + it('returns canonical Jellyfin IDs and server-side import status', async () => { + const settings = getSettings(); + const previousJellyfin = settings.jellyfin; + const providerId = '66666666-6666-6666-6666-666666666666'; + const canonicalId = providerId.replaceAll('-', ''); + const userRepository = getRepository(User); + const linkedUser = await userRepository.save( + new User({ + email: 'linked-jellyfin-import@example.com', + jellyfinUserId: providerId, + jellyfinUsername: 'Linked Jellyfin User', + permissions: Permission.REQUEST, + userType: UserType.LOCAL, + avatar: `/avatarproxy/${canonicalId}`, + }) + ); + settings.jellyfin = { + ...settings.jellyfin, + ip: 'jellyfin.local', + apiKey: 'stored-key', + }; + const getUsersMock = mock.method( + JellyfinAPI.prototype, + 'getUsers', + async () => + ({ + users: [ + { + Name: 'Linked Jellyfin User', + Id: providerId, + }, + { + Name: 'New Jellyfin User', + Id: '77777777-7777-7777-7777-777777777777', + }, + { + Name: 'Invalid ID', + Id: 'not-a-guid', + }, + ], + }) as never + ); + + try { + const response = await request(app).get('/settings/jellyfin/users'); + + assert.strictEqual(response.status, 200); + assert.deepStrictEqual(response.body, [ + { + username: 'Linked Jellyfin User', + id: canonicalId, + thumb: `/avatarproxy/${canonicalId}`, + email: 'Linked Jellyfin User', + isImported: true, + }, + { + username: 'New Jellyfin User', + id: '77777777777777777777777777777777', + thumb: '/avatarproxy/77777777777777777777777777777777', + email: 'New Jellyfin User', + isImported: false, + }, + ]); + } finally { + settings.jellyfin = previousJellyfin; + await userRepository.delete(linkedUser.id); + getUsersMock.mock.restore(); + } + }); + it('does not use Jellyfin credentials removed before admission', async () => { const settings = getSettings(); settings.jellyfin = { diff --git a/server/routes/user.test.ts b/server/routes/user.test.ts index 7a01a2a75..fae5ee991 100644 --- a/server/routes/user.test.ts +++ b/server/routes/user.test.ts @@ -14,6 +14,7 @@ import { User } from '@server/entity/User'; import { UserPushSubscription } from '@server/entity/UserPushSubscription'; import { UserSettings } from '@server/entity/UserSettings'; import PreparedEmail from '@server/lib/email'; +import ImageProxy from '@server/lib/imageproxy'; import { MAX_PERMISSION_VALUE, Permission } from '@server/lib/permissions'; import requestAdmissionCoordinator from '@server/lib/requestAdmission'; import { getSettings } from '@server/lib/settings'; @@ -2410,6 +2411,30 @@ describe('User route input validation', () => { } }); + it('rejects Jellyfin import when another media server is configured', async () => { + const settings = getSettings(); + const previousMediaServerType = settings.main.mediaServerType; + settings.main.mediaServerType = MediaServerType.PLEX; + const getUsersMock = mock.method( + JellyfinAPI.prototype, + 'getUsers', + async () => ({ users: [] }) as never + ); + + try { + const agent = await loginAs('admin@seerr.dev', 'test1234'); + const response = await agent + .post('/user/import-from-jellyfin') + .send({ jellyfinUserIds: [] }); + + assert.strictEqual(response.status, 409); + assert.strictEqual(getUsersMock.mock.callCount(), 0); + } finally { + settings.main.mediaServerType = previousMediaServerType; + getUsersMock.mock.restore(); + } + }); + it('rejects malformed Jellyfin user IDs before provider calls', async () => { const agent = await loginAs('admin@seerr.dev', 'test1234'); const res = await agent @@ -2420,7 +2445,248 @@ describe('User route input validation', () => { assert.match(res.body.message, /jellyfinUserIds is invalid/i); }); + it('rejects a malformed Jellyfin sync option before provider calls', async () => { + const getUsersMock = mock.method( + JellyfinAPI.prototype, + 'getUsers', + async () => ({ users: [] }) as never + ); + try { + const agent = await loginAs('admin@seerr.dev', 'test1234'); + const response = await agent + .post('/user/import-from-jellyfin') + .send({ jellyfinUserIds: [], syncExisting: 'true' }); + + assert.strictEqual(response.status, 400); + assert.match(response.body.message, /syncExisting must be a boolean/i); + assert.strictEqual(getUsersMock.mock.callCount(), 0); + } finally { + getUsersMock.mock.restore(); + } + }); + + it('keeps refreshing linked Jellyfin users opt-in and preserves the legacy response', async () => { + const settings = getSettings(); + const previousMediaServerType = settings.main.mediaServerType; + const previousJellyfin = settings.jellyfin; + const providerId = '44444444-4444-4444-4444-444444444444'; + const canonicalId = providerId.replaceAll('-', ''); + const userRepository = getRepository(User); + const target = await userRepository.findOneByOrFail({ + email: 'friend@seerr.dev', + }); + const previousTarget = { + jellyfinUserId: target.jellyfinUserId, + jellyfinUsername: target.jellyfinUsername, + }; + settings.main.mediaServerType = MediaServerType.JELLYFIN; + settings.jellyfin = { + ...settings.jellyfin, + ip: 'jellyfin.local', + apiKey: 'stored-import-key', + }; + target.jellyfinUserId = canonicalId; + target.jellyfinUsername = 'Existing Provider Name'; + await userRepository.save(target); + + const getUsersMock = mock.method( + JellyfinAPI.prototype, + 'getUsers', + async () => + ({ + users: [ + { + Name: 'Updated Provider Name', + ServerId: 'server', + ServerName: 'Jellyfin', + Id: providerId, + Configuration: { GroupedFolders: [] }, + Policy: { IsAdministrator: false }, + }, + ], + }) as never + ); + const getImageMock = mock.method( + ImageProxy.prototype, + 'getImage', + async () => ({ imageBuffer: Buffer.from('profile photo') }) as never + ); + const clearCachedImageMock = mock.method( + ImageProxy.prototype, + 'clearCachedImage', + async () => undefined + ); + + try { + const agent = await loginAs('admin@seerr.dev', 'test1234'); + const response = await agent + .post('/user/import-from-jellyfin') + .send({ jellyfinUserIds: [providerId] }); + + assert.strictEqual(response.status, 201); + assert.deepStrictEqual(response.body, []); + assert.strictEqual(getUsersMock.mock.callCount(), 1); + assert.strictEqual(getImageMock.mock.callCount(), 0); + assert.strictEqual(clearCachedImageMock.mock.callCount(), 0); + const persisted = await userRepository.findOneByOrFail({ + id: target.id, + }); + assert.strictEqual(persisted.jellyfinUsername, 'Existing Provider Name'); + } finally { + settings.main.mediaServerType = previousMediaServerType; + settings.jellyfin = previousJellyfin; + await userRepository.update(target.id, previousTarget); + getUsersMock.mock.restore(); + getImageMock.mock.restore(); + clearCachedImageMock.mock.restore(); + } + }); + + it('refreshes only the provider name and avatar for an already-linked user', async () => { + const settings = getSettings(); + const previousMediaServerType = settings.main.mediaServerType; + const previousJellyfin = settings.jellyfin; + const providerId = '55555555-5555-5555-5555-555555555555'; + const canonicalId = providerId.replaceAll('-', ''); + const userRepository = getRepository(User); + const target = await userRepository.findOneByOrFail({ + email: 'friend@seerr.dev', + }); + const previousTarget = { + jellyfinUserId: target.jellyfinUserId, + jellyfinUsername: target.jellyfinUsername, + username: target.username, + avatar: target.avatar, + avatarETag: target.avatarETag, + avatarVersion: target.avatarVersion, + permissions: target.permissions, + userType: target.userType, + }; + const previousCredentials = await userRepository.findOneOrFail({ + where: { id: target.id }, + select: { + id: true, + password: true, + jellyfinAuthToken: true, + jellyfinDeviceId: true, + }, + }); + settings.main.mediaServerType = MediaServerType.EMBY; + settings.jellyfin = { + ...settings.jellyfin, + ip: 'jellyfin.local', + apiKey: 'stored-import-key', + }; + target.jellyfinUserId = canonicalId; + target.jellyfinUsername = 'Old Provider Name'; + target.username = 'Local Display Name'; + target.avatar = 'https://example.com/local-profile.png'; + target.avatarETag = 'old-avatar-etag'; + target.avatarVersion = 'old-avatar-version'; + target.jellyfinAuthToken = 'preserved-auth-token'; + target.jellyfinDeviceId = 'preserved-device-id'; + target.permissions = Permission.REQUEST_MUSIC; + target.userType = UserType.LOCAL; + await userRepository.save(target); + + const getUsersMock = mock.method( + JellyfinAPI.prototype, + 'getUsers', + async () => + ({ + users: [ + { + Name: 'Fresh Provider Name', + ServerId: 'server', + ServerName: 'Jellyfin', + Id: providerId, + Configuration: { GroupedFolders: [] }, + Policy: { IsAdministrator: false }, + }, + ], + }) as never + ); + const getImageMock = mock.method( + ImageProxy.prototype, + 'getImage', + async () => ({ imageBuffer: Buffer.from('fresh profile photo') }) as never + ); + const clearCachedImageMock = mock.method( + ImageProxy.prototype, + 'clearCachedImage', + async () => undefined + ); + + try { + const agent = await loginAs('admin@seerr.dev', 'test1234'); + const response = await agent + .post('/user/import-from-jellyfin') + .send({ jellyfinUserIds: [providerId], syncExisting: true }); + + assert.strictEqual(response.status, 201); + assert.deepStrictEqual(response.body, { + createdUsers: [], + refreshedUsers: 1, + }); + assert.strictEqual(getUsersMock.mock.callCount(), 1); + assert.strictEqual(getImageMock.mock.callCount(), 1); + assert.strictEqual(clearCachedImageMock.mock.callCount(), 1); + assert.match( + String(getImageMock.mock.calls[0].arguments[0]), + new RegExp(`/Users/${canonicalId}/Images/Primary\\?quality=90$`) + ); + + const refreshed = await userRepository.findOneByOrFail({ id: target.id }); + assert.strictEqual(refreshed.jellyfinUserId, canonicalId); + assert.strictEqual(refreshed.jellyfinUsername, 'Fresh Provider Name'); + assert.strictEqual(refreshed.username, 'Local Display Name'); + assert.strictEqual(refreshed.email, 'friend@seerr.dev'); + assert.strictEqual(refreshed.permissions, Permission.REQUEST_MUSIC); + assert.strictEqual(refreshed.userType, UserType.LOCAL); + const refreshedCredentials = await userRepository.findOneOrFail({ + where: { id: target.id }, + select: { + id: true, + password: true, + jellyfinAuthToken: true, + jellyfinDeviceId: true, + }, + }); + assert.strictEqual( + refreshedCredentials.password, + previousCredentials.password + ); + assert.strictEqual( + refreshedCredentials.jellyfinAuthToken, + 'preserved-auth-token' + ); + assert.strictEqual( + refreshedCredentials.jellyfinDeviceId, + 'preserved-device-id' + ); + assert.match( + refreshed.avatar ?? '', + new RegExp(`^/avatarproxy/${canonicalId}\\?v=[a-f0-9]{64}$`) + ); + } finally { + settings.main.mediaServerType = previousMediaServerType; + settings.jellyfin = previousJellyfin; + await userRepository.update(target.id, { + ...previousTarget, + password: previousCredentials.password, + jellyfinAuthToken: previousCredentials.jellyfinAuthToken, + jellyfinDeviceId: previousCredentials.jellyfinDeviceId, + }); + getUsersMock.mock.restore(); + getImageMock.mock.restore(); + clearCachedImageMock.mock.restore(); + } + }); + it('does not create a Jellyfin user missing from the provider response', async () => { + const settings = getSettings(); + const previousMediaServerType = settings.main.mediaServerType; + settings.main.mediaServerType = MediaServerType.JELLYFIN; const requestedId = '11111111111111111111111111111111'; const providerId = '22222222222222222222222222222222'; const getUsersMock = mock.method( @@ -2457,11 +2723,15 @@ describe('User route input validation', () => { 0 ); } finally { + settings.main.mediaServerType = previousMediaServerType; getUsersMock.mock.restore(); } }); it('stores imported Jellyfin IDs in canonical form', async () => { + const settings = getSettings(); + const previousMediaServerType = settings.main.mediaServerType; + settings.main.mediaServerType = MediaServerType.JELLYFIN; const providerId = '33333333-3333-3333-3333-333333333333'; const canonicalId = providerId.replaceAll('-', ''); const getUsersMock = mock.method( @@ -2497,6 +2767,7 @@ describe('User route input validation', () => { 1 ); } finally { + settings.main.mediaServerType = previousMediaServerType; getUsersMock.mock.restore(); } }); diff --git a/server/routes/user/index.ts b/server/routes/user/index.ts index 3be8f0647..10f1e0922 100644 --- a/server/routes/user/index.ts +++ b/server/routes/user/index.ts @@ -64,6 +64,7 @@ import { getCombinedWatchlist } from '@server/lib/watchlist'; import logger from '@server/logger'; import { isAuthenticated } from '@server/middleware/auth'; import { authorizedRouteAccess } from '@server/middleware/authorizedMutation'; +import { checkAvatarChanged } from '@server/routes/avatarproxy'; import AsyncLock from '@server/utils/asyncLock'; import { isUniqueConstraintError } from '@server/utils/databaseError'; import { filterEntityResponse } from '@server/utils/entityResponse'; @@ -104,6 +105,15 @@ const router = Router(); const MAX_USER_SEARCH_QUERY_LENGTH = 200; const MAX_USER_SORT_LENGTH = 40; +class UnsupportedMediaServerUserImportError extends Error { + constructor() { + super( + 'Jellyfin user import is unavailable for the configured media server.' + ); + this.name = 'UnsupportedMediaServerUserImportError'; + } +} + const parseOptionalUserQueryString = ( value: unknown, fieldName: string, @@ -2103,6 +2113,15 @@ router.post( return next({ status: 400, message: parsedJellyfinUserIds.error }); } + const parsedSyncExisting = parseOptionalBodyBoolean( + parsedBody.value.syncExisting, + 'syncExisting' + ); + if ('error' in parsedSyncExisting) { + return next({ status: 400, message: parsedSyncExisting.error }); + } + const syncExisting = parsedSyncExisting.value === true; + const jellyfinUserIds = new Set(); for (const rawJellyfinUserId of parsedJellyfinUserIds.value) { const jellyfinUserId = normalizeJellyfinGuid(rawJellyfinUserId); @@ -2115,6 +2134,7 @@ router.post( try { const userRepository = getRepository(User); const createdUsers: User[] = []; + let refreshedUsers = 0; const importAuthority = await runAuthorizedUserSecurityMutation( req.user!.id, [req.user!.id, 1], @@ -2127,6 +2147,12 @@ router.post( ) { throw new UserMutationActorUnauthorizedError(); } + if ( + settings.main.mediaServerType !== MediaServerType.JELLYFIN && + settings.main.mediaServerType !== MediaServerType.EMBY + ) { + throw new UnsupportedMediaServerUserImportError(); + } const admin = await userRepository.findOneOrFail({ where: { id: 1 }, @@ -2161,11 +2187,12 @@ router.post( jellyfinClient.setUserId(importAuthority.owner.jellyfinUserId ?? ''); const jellyfinUsers = await jellyfinClient.getUsers(); const runWithImportAuthority = ( + targetUserIds: number[], callback: (actor: User) => Promise ): Promise => runAuthorizedUserSecurityMutation( req.user!.id, - [1], + [...targetUserIds, 1], Permission.MANAGE_USERS, (actor) => runWithConfigurationSnapshot( @@ -2214,47 +2241,102 @@ router.post( getAuthAccountAdmissionResource('jellyfin', jellyfinUserId), ], async () => { - const user = await userRepository.findOne({ + const linkedUser = await userRepository.findOne({ select: { id: true, jellyfinUserId: true }, - where: [ - { jellyfinUserId }, - { email: jellyfinUser.Name.toLowerCase() }, - ], + where: { jellyfinUserId }, }); - if (!user) { - await runWithImportAuthority(async (actor) => { - const settings = getSettings(); - if ( - !canMakePermissionsChange( - settings.main.defaultPermissions, - actor - ) - ) { - throw new UserMutationActorUnauthorizedError(); - } - const newUser = new User({ - jellyfinUsername: jellyfinUser.Name, - jellyfinUserId: jellyfinUser.Id, - jellyfinDeviceId: Buffer.from( - `BOT_seerr_${jellyfinUser.Name}` - ).toString('base64'), - email: jellyfinUser.Name, - permissions: settings.main.defaultPermissions, - avatar: `/avatarproxy/${jellyfinUser.Id}`, - userType: - settings.main.mediaServerType === MediaServerType.JELLYFIN - ? UserType.JELLYFIN - : UserType.EMBY, - }); + if (linkedUser) { + if (syncExisting) { + await runWithImportAuthority([linkedUser.id], async (actor) => { + const activeUser = await userRepository.findOneBy({ + id: linkedUser.id, + }); + if ( + !activeUser || + normalizeJellyfinGuid(activeUser.jellyfinUserId) !== + jellyfinUserId + ) { + return; + } + + const isOtherProtectedAdministrator = + activeUser.hasPermission(Permission.ADMIN) && + actor.id !== 1 && + actor.id !== activeUser.id; + const mayModifyExistingUser = + actor.id === 1 || + actor.id === activeUser.id || + canMakePermissionsChange(activeUser.permissions, actor); + if (isOtherProtectedAdministrator || !mayModifyExistingUser) { + return; + } - await userRepository.save(newUser); - createdUsers.push(newUser); + await checkAvatarChanged(activeUser); + const avatar = activeUser.avatarVersion + ? `/avatarproxy/${jellyfinUserId}?v=${encodeURIComponent(activeUser.avatarVersion)}` + : `/avatarproxy/${jellyfinUserId}`; + const updates: Partial< + Pick + > = {}; + if (activeUser.jellyfinUsername !== jellyfinUser.Name) { + updates.jellyfinUsername = jellyfinUser.Name; + } + if (activeUser.avatar !== avatar) { + updates.avatar = avatar; + } + if (Object.keys(updates).length > 0) { + await userRepository.update(activeUser.id, updates); + } + refreshedUsers += 1; + }); + } + } else { + const existingEmailUser = await userRepository.findOne({ + select: { id: true }, + where: { email: jellyfinUser.Name.toLowerCase() }, }); + + if (!existingEmailUser) { + await runWithImportAuthority([], async (actor) => { + const settings = getSettings(); + if ( + !canMakePermissionsChange( + settings.main.defaultPermissions, + actor + ) + ) { + throw new UserMutationActorUnauthorizedError(); + } + const newUser = new User({ + jellyfinUsername: jellyfinUser.Name, + jellyfinUserId: jellyfinUser.Id, + jellyfinDeviceId: Buffer.from( + `BOT_seerr_${jellyfinUser.Name}` + ).toString('base64'), + email: jellyfinUser.Name, + permissions: settings.main.defaultPermissions, + avatar: `/avatarproxy/${jellyfinUserId}`, + userType: + settings.main.mediaServerType === MediaServerType.JELLYFIN + ? UserType.JELLYFIN + : UserType.EMBY, + }); + + await userRepository.save(newUser); + createdUsers.push(newUser); + }); + } } } ); } + if (syncExisting) { + return res.status(201).json({ + createdUsers: User.filterMany(createdUsers), + refreshedUsers, + }); + } return res.status(201).json(User.filterMany(createdUsers)); } catch (e) { if (e instanceof UserMutationActorUnauthorizedError) { @@ -2263,6 +2345,9 @@ router.post( message: 'You do not have permission to import users', }); } + if (e instanceof UnsupportedMediaServerUserImportError) { + return next({ status: 409, message: e.message }); + } if ( e instanceof ConfigurationAuthorityChangedError || e instanceof MediaServerUserAuthorityChangedError diff --git a/src/components/Common/CachedImage/index.tsx b/src/components/Common/CachedImage/index.tsx index 8842c505f..d95480462 100644 --- a/src/components/Common/CachedImage/index.tsx +++ b/src/components/Common/CachedImage/index.tsx @@ -153,7 +153,9 @@ const CachedImage = memo( return ( ); diff --git a/src/components/UserList/JellyfinImportModal.tsx b/src/components/UserList/JellyfinImportModal.tsx index a9bec2c76..ede471fbc 100644 --- a/src/components/UserList/JellyfinImportModal.tsx +++ b/src/components/UserList/JellyfinImportModal.tsx @@ -1,21 +1,33 @@ import Alert from '@app/components/Common/Alert'; import CachedImage from '@app/components/Common/CachedImage'; import Modal from '@app/components/Common/Modal'; +import SelectionCircle from '@app/components/Common/SelectionCircle'; import useSettings from '@app/hooks/useSettings'; import useToasts from '@app/hooks/useToasts'; import globalMessages from '@app/i18n/globalMessages'; import defineMessages from '@app/utils/defineMessages'; import { MediaServerType } from '@server/constants/server'; -import type { UserResultsResponse } from '@server/interfaces/api/userInterfaces'; import axios from 'axios'; -import { useState } from 'react'; +import { useMemo, useState } from 'react'; import { useIntl } from 'react-intl'; import useSWR from 'swr'; +import userSelectionMessages from './userSelectionMessages'; + +interface JellyfinImportUser { + id: string; + username: string; + thumb: string; + isImported: boolean; +} + +interface JellyfinImportResponse { + createdUsers: unknown[]; + refreshedUsers: number; +} interface JellyfinImportProps { onCancel?: () => void; onComplete?: () => void; - children?: React.ReactNode; } const messages = defineMessages('components.UserList', { @@ -24,121 +36,148 @@ const messages = defineMessages('components.UserList', { 'Something went wrong while importing {mediaServerName} users.', importedfromJellyfin: '{userCount} {mediaServerName} {userCount, plural, one {user} other {users}} imported successfully!', + importedAndRefreshed: + '{createdCount, plural, =0 {No new users imported} one {# new user imported} other {# new users imported}}. {refreshedCount, plural, =0 {No existing users refreshed} one {# existing user refreshed} other {# existing users refreshed}}.', importedUsersNoPassword: 'Imported users do not have a {applicationTitle} password set. If you disable {mediaServerName} sign-in, they will need to set a password from their profile or via a password reset link.', user: 'User', - noJellyfinuserstoimport: 'There are no {mediaServerName} users to import.', - newJellyfinsigninenabled: + noJellyfinUsersToImport: 'There are no {mediaServerName} users to import.', + noJellyfinUsersToSync: + 'There are no linked {mediaServerName} users to refresh.', + allJellyfinUsersImported: + 'All {mediaServerName} users are already imported. Turn on Sync Existing Users to refresh linked accounts.', + newJellyfinSignInEnabled: 'The Enable New {mediaServerName} Sign-In setting is currently enabled. {mediaServerName} users with library access do not need to be imported in order to sign in.', + syncExistingUsers: 'Sync Existing Users', + syncExistingUsersHelp: + 'Refresh the provider display name and profile photo for linked users. SeerrNG email, passwords, and permissions stay unchanged.', + alreadyImported: 'Already Imported', + noUsersChanged: 'No selected users were imported or refreshed.', + failedToLoadUsers: 'Unable to load {mediaServerName} users.', }); const JellyfinImportModal: React.FC = ({ onCancel, onComplete, - children, }) => { const intl = useIntl(); const settings = useSettings(); const { addToast } = useToasts(); const [isImporting, setImporting] = useState(false); + const [syncExisting, setSyncExisting] = useState(false); const [selectedUsers, setSelectedUsers] = useState([]); - const { data, error } = useSWR< - { - id: string; - title: string; - username: string; - email: string; - thumb: string; - }[] - >(`/api/v1/settings/jellyfin/users`, { - revalidateOnMount: true, - }); + const mediaServerName = + settings.currentSettings.mediaServerType === MediaServerType.EMBY + ? 'Emby' + : 'Jellyfin'; + const { data, error } = useSWR( + '/api/v1/settings/jellyfin/users', + { revalidateOnMount: true } + ); - const { data: existingUsers } = useSWR( - `/api/v1/user?take=${children}` + const availableUsers = useMemo( + () => data?.filter((user) => syncExisting || !user.isImported) ?? [], + [data, syncExisting] + ); + const allAvailableUsersSelected = + availableUsers.length > 0 && + availableUsers.every((user) => selectedUsers.includes(user.id)); + const someAvailableUsersSelected = availableUsers.some((user) => + selectedUsers.includes(user.id) ); const importUsers = async () => { setImporting(true); try { - const { data: createdUsers } = await axios.post( - '/api/v1/user/import-from-jellyfin', - { jellyfinUserIds: selectedUsers } - ); - - if (!createdUsers.length) { - throw new Error('No users were imported from Jellyfin.'); - } + const { data: response } = await axios.post< + JellyfinImportResponse | unknown[] + >('/api/v1/user/import-from-jellyfin', { + jellyfinUserIds: selectedUsers, + ...(syncExisting ? { syncExisting: true } : {}), + }); + const createdUsers = Array.isArray(response) + ? response + : response.createdUsers; + const refreshedUsers = Array.isArray(response) + ? 0 + : response.refreshedUsers; - addToast( - intl.formatMessage(messages.importedfromJellyfin, { - userCount: createdUsers.length, - strong: (msg: React.ReactNode) => {msg}, - mediaServerName: - settings.currentSettings.mediaServerType === MediaServerType.EMBY - ? 'Emby' - : 'Jellyfin', - }), - { + if (!createdUsers.length && !refreshedUsers) { + addToast(intl.formatMessage(messages.noUsersChanged), { autoDismiss: true, - appearance: 'success', - } - ); + appearance: 'info', + }); + return; + } addToast( - intl.formatMessage(messages.importedUsersNoPassword, { - applicationTitle: settings.currentSettings.applicationTitle, - mediaServerName: - settings.currentSettings.mediaServerType === MediaServerType.EMBY - ? 'Emby' - : 'Jellyfin', - }), - { - autoDismiss: false, - appearance: 'warning', - } + intl.formatMessage( + syncExisting + ? messages.importedAndRefreshed + : messages.importedfromJellyfin, + { + createdCount: createdUsers.length, + refreshedCount: refreshedUsers, + userCount: createdUsers.length, + mediaServerName, + strong: (msg: React.ReactNode) => {msg}, + } + ), + { autoDismiss: true, appearance: 'success' } ); - if (onComplete) { - onComplete(); + if (createdUsers.length > 0) { + addToast( + intl.formatMessage(messages.importedUsersNoPassword, { + applicationTitle: settings.currentSettings.applicationTitle, + mediaServerName, + }), + { autoDismiss: false, appearance: 'warning' } + ); } + + onComplete?.(); } catch { addToast( intl.formatMessage(messages.importfromJellyfinerror, { - mediaServerName: - settings.currentSettings.mediaServerType === MediaServerType.EMBY - ? 'Emby' - : 'Jellyfin', + mediaServerName, }), - { - autoDismiss: true, - appearance: 'error', - } + { autoDismiss: true, appearance: 'error' } ); } finally { setImporting(false); } }; - const isSelectedUser = (JellyfinId: string): boolean => - selectedUsers.includes(JellyfinId); + const toggleUser = (userId: string): void => { + setSelectedUsers((users) => + users.includes(userId) + ? users.filter((selectedUserId) => selectedUserId !== userId) + : [...users, userId] + ); + }; - const isAllUsers = (): boolean => selectedUsers.length === data?.length; + const toggleAllUsers = (): void => { + setSelectedUsers((users) => { + if (allAvailableUsersSelected) { + const availableIds = new Set(availableUsers.map((user) => user.id)); + return users.filter((userId) => !availableIds.has(userId)); + } - const toggleUser = (JellyfinId: string): void => { - if (selectedUsers.includes(JellyfinId)) { - setSelectedUsers((users) => users.filter((user) => user !== JellyfinId)); - } else { - setSelectedUsers((users) => [...users, JellyfinId]); - } + return [...new Set([...users, ...availableUsers.map((user) => user.id)])]; + }); }; - const toggleAllUsers = (): void => { - if (data && selectedUsers.length >= 0 && !isAllUsers()) { - setSelectedUsers(data.map((user) => user.id)); - } else { - setSelectedUsers([]); + const toggleSyncExisting = (checked: boolean): void => { + setSyncExisting(checked); + if (!checked) { + const newUserIds = new Set( + data?.filter((user) => !user.isImported).map((user) => user.id) ?? [] + ); + setSelectedUsers((users) => + users.filter((userId) => newUserIds.has(userId)) + ); } }; @@ -146,157 +185,125 @@ const JellyfinImportModal: React.FC = ({ { - importUsers(); - }} - okDisabled={isImporting || !selectedUsers.length} + onOk={importUsers} + okDisabled={isImporting || selectedUsers.length === 0} okText={intl.formatMessage( isImporting ? globalMessages.importing : globalMessages.import )} onCancel={onCancel} > - {data?.length ? ( - <> - {settings.currentSettings.newPlexLogin && ( - ( - {msg} - ), - })} - type="info" + {settings.currentSettings.newPlexLogin && ( + {msg}, + })} + type="info" + /> + )} + +
+ +

+ {intl.formatMessage(messages.syncExistingUsersHelp)} +

+
+ + {error ? ( + + ) : availableUsers.length > 0 ? ( +
+
+ - )} -
-
-
-
- - - - - - - - - {data - ?.filter( - (user) => - !existingUsers?.results.some( - (u) => u.jellyfinUserId === user.id - ) - ) - .map((user) => ( - - - - - ))} - -
- toggleAllUsers()} - onKeyDown={(e) => { - if (e.key === 'Enter' || e.key === 'Space') { - toggleAllUsers(); - } - }} - className="relative inline-flex h-5 w-10 flex-shrink-0 cursor-pointer items-center justify-center pt-2 focus:outline-none" - > - - {intl.formatMessage(messages.user)} -
- toggleUser(user.id)} - onKeyDown={(e) => { - if (e.key === 'Enter' || e.key === 'Space') { - toggleUser(user.id); - } - }} - className="relative inline-flex h-5 w-10 flex-shrink-0 cursor-pointer items-center justify-center pt-2 focus:outline-none" - > - -
- -
-
- {user.username} -
- {/* {user.username && - user.username.toLowerCase() !== - user.email && ( -
- {user.email} -
- )} */} -
-
-
-
-
-
+ + {intl.formatMessage(messages.user)} + +
+
+
    + {availableUsers.map((user) => ( +
  • +
    + toggleUser(user.id)} + /> + + {user.username} +
    + {syncExisting && user.isImported && ( +

    + {intl.formatMessage(messages.alreadyImported)} +

    + )} +
  • + ))} +
- +
+ ) : syncExisting ? ( + + ) : data?.some((user) => user.isImported) ? ( + ) : ( diff --git a/src/components/UserList/index.tsx b/src/components/UserList/index.tsx index 3486597d4..9e0df2351 100644 --- a/src/components/UserList/index.tsx +++ b/src/components/UserList/index.tsx @@ -49,6 +49,7 @@ import useSWR from 'swr'; import validator from 'validator'; import * as Yup from 'yup'; import JellyfinImportModal from './JellyfinImportModal'; +import userSelectionMessages from './userSelectionMessages'; const messages = defineMessages('components.UserList', { users: 'Users', @@ -67,8 +68,6 @@ const messages = defineMessages('components.UserList', { allTypes: 'All Types', allRoles: 'All Roles', userName: 'User Name', - selectAllUsers: 'Select all users', - selectUser: 'Select {user}', noUsers: 'No users match the selected filters.', bulkedit: 'Bulk Edit', owner: 'Owner', @@ -615,9 +614,7 @@ const UserList = () => { setShowImportModal(false); revalidate(); }} - > - {data.pageInfo.results} - + /> )} @@ -693,7 +690,9 @@ const UserList = () => { )} @@ -733,9 +732,10 @@ const UserList = () => { {isUserPermsEditable(user.id) && ( toggleUser(user.id)} /> )} diff --git a/src/components/UserList/userSelectionMessages.ts b/src/components/UserList/userSelectionMessages.ts new file mode 100644 index 000000000..33e9770e9 --- /dev/null +++ b/src/components/UserList/userSelectionMessages.ts @@ -0,0 +1,8 @@ +import defineMessages from '@app/utils/defineMessages'; + +const userSelectionMessages = defineMessages('components.UserList', { + selectAllUsers: 'Select all users', + selectUser: 'Select {user}', +}); + +export default userSelectionMessages; diff --git a/src/i18n/locale/en.json b/src/i18n/locale/en.json index 7c5d259e9..31ebafb16 100644 --- a/src/i18n/locale/en.json +++ b/src/i18n/locale/en.json @@ -4652,8 +4652,10 @@ "components.TvDetails.watchtrailer": "Watch Trailer", "components.UserList.accounttype": "Type", "components.UserList.admin": "Admin", + "components.UserList.allJellyfinUsersImported": "All {mediaServerName} users are already imported. Turn on Sync Existing Users to refresh linked accounts.", "components.UserList.allRoles": "All Roles", "components.UserList.allTypes": "All Types", + "components.UserList.alreadyImported": "Already Imported", "components.UserList.any": "Any", "components.UserList.ascending": "ascending", "components.UserList.autoRequestBooks": "Books", @@ -4676,7 +4678,9 @@ "components.UserList.edituser": "Bulk Edit Users", "components.UserList.email": "Email Address", "components.UserList.enabled": "Enabled", + "components.UserList.failedToLoadUsers": "Unable to load {mediaServerName} users.", "components.UserList.filters": "Filters", + "components.UserList.importedAndRefreshed": "{createdCount, plural, =0 {No new users imported} one {# new user imported} other {# new users imported}}. {refreshedCount, plural, =0 {No existing users refreshed} one {# existing user refreshed} other {# existing users refreshed}}.", "components.UserList.importedPlexUsersNoPassword": "Imported users do not have a {applicationTitle} password set. If you disable Plex sign-in, they will need to set a password from their profile or via a password reset link.", "components.UserList.importedUsersNoPassword": "Imported users do not have a {applicationTitle} password set. If you disable {mediaServerName} sign-in, they will need to set a password from their profile or via a password reset link.", "components.UserList.importedfromJellyfin": "{userCount} {mediaServerName} {userCount, plural, one {user} other {users}} imported successfully!", @@ -4692,11 +4696,13 @@ "components.UserList.localLoginDisabled": "The Enable Local Sign-In setting is currently disabled.", "components.UserList.localuser": "Local User", "components.UserList.mediaServerUser": "{mediaServerName} User", - "components.UserList.newJellyfinsigninenabled": "The Enable New {mediaServerName} Sign-In setting is currently enabled. {mediaServerName} users with library access do not need to be imported in order to sign in.", + "components.UserList.newJellyfinSignInEnabled": "The Enable New {mediaServerName} Sign-In setting is currently enabled. {mediaServerName} users with library access do not need to be imported in order to sign in.", "components.UserList.newplexsigninenabled": "The Enable New Plex Sign-In setting is currently enabled. Plex users with library access do not need to be imported in order to sign in.", "components.UserList.noChange": "No Change", - "components.UserList.noJellyfinuserstoimport": "There are no {mediaServerName} users to import.", + "components.UserList.noJellyfinUsersToImport": "There are no {mediaServerName} users to import.", + "components.UserList.noJellyfinUsersToSync": "There are no linked {mediaServerName} users to refresh.", "components.UserList.noUsers": "No users match the selected filters.", + "components.UserList.noUsersChanged": "No selected users were imported or refreshed.", "components.UserList.nouserstoimport": "There are no Plex users to import.", "components.UserList.owner": "Owner", "components.UserList.password": "Password", @@ -4715,6 +4721,8 @@ "components.UserList.sortByRole": "Sort by user role", "components.UserList.sortByType": "Sort by account type", "components.UserList.sortByUser": "Sort by username", + "components.UserList.syncExistingUsers": "Sync Existing Users", + "components.UserList.syncExistingUsersHelp": "Refresh the provider display name and profile photo for linked users. SeerrNG email, passwords, and permissions stay unchanged.", "components.UserList.syncnotice": "You can still click Sync to refresh existing Plex users, such as updated email or username details.", "components.UserList.toggleSortDirection": "Click again to sort {direction}", "components.UserList.toggleSortDirectionAria": "Toggle sort direction", diff --git a/src/styles/globals.css b/src/styles/globals.css index 37686030b..ab76afbd8 100644 --- a/src/styles/globals.css +++ b/src/styles/globals.css @@ -4985,6 +4985,10 @@ @apply mr-1 h-5 w-5 scale-100 transform-gpu rounded-full transition duration-300 group-hover:scale-105; } + .cached-image-avatar-fallback { + color: rgb(var(--color-indigo-500)); + } + .card-field { @apply flex items-center truncate py-0.5 text-sm sm:py-1; } From ede8144ef2bd3bdd1b986f2af92177094be3393e Mon Sep 17 00:00:00 2001 From: snapetech Date: Tue, 13 Oct 2026 14:41:16 -0600 Subject: [PATCH 2/3] fix(users): revalidate import permission at route boundary --- server/routes/user/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/server/routes/user/index.ts b/server/routes/user/index.ts index 10f1e0922..06a483694 100644 --- a/server/routes/user/index.ts +++ b/server/routes/user/index.ts @@ -2094,6 +2094,7 @@ router.post( router.post( '/import-from-jellyfin', isAuthenticated(Permission.MANAGE_USERS), + authorizedRouteAccess(Permission.MANAGE_USERS), async (req, res, next) => { const parsedBody = parseOptionalUserBodyObject(req.body); if ('error' in parsedBody) { From faba4f2e58b3e0bb81c7dfcdbb7db88dbf7c7a39 Mon Sep 17 00:00:00 2001 From: snapetech Date: Thu, 15 Oct 2026 07:38:05 -0600 Subject: [PATCH 3/3] refactor(users): evaluate import authority before the sync option Co-Authored-By: Claude Sonnet 5.5 --- server/routes/user/index.ts | 85 +++++++++++++++++++------------------ 1 file changed, 43 insertions(+), 42 deletions(-) diff --git a/server/routes/user/index.ts b/server/routes/user/index.ts index 08f753dee..9b7851294 100644 --- a/server/routes/user/index.ts +++ b/server/routes/user/index.ts @@ -2247,50 +2247,51 @@ router.post( }); if (linkedUser) { - if (syncExisting) { - await runWithImportAuthority([linkedUser.id], async (actor) => { - const activeUser = await userRepository.findOneBy({ - id: linkedUser.id, - }); - if ( - !activeUser || - normalizeJellyfinGuid(activeUser.jellyfinUserId) !== - jellyfinUserId - ) { - return; - } + await runWithImportAuthority([linkedUser.id], async (actor) => { + if (!syncExisting) { + return; + } + const activeUser = await userRepository.findOneBy({ + id: linkedUser.id, + }); + if ( + !activeUser || + normalizeJellyfinGuid(activeUser.jellyfinUserId) !== + jellyfinUserId + ) { + return; + } - const isOtherProtectedAdministrator = - activeUser.hasPermission(Permission.ADMIN) && - actor.id !== 1 && - actor.id !== activeUser.id; - const mayModifyExistingUser = - actor.id === 1 || - actor.id === activeUser.id || - canMakePermissionsChange(activeUser.permissions, actor); - if (isOtherProtectedAdministrator || !mayModifyExistingUser) { - return; - } + const isOtherProtectedAdministrator = + activeUser.hasPermission(Permission.ADMIN) && + actor.id !== 1 && + actor.id !== activeUser.id; + const mayModifyExistingUser = + actor.id === 1 || + actor.id === activeUser.id || + canMakePermissionsChange(activeUser.permissions, actor); + if (isOtherProtectedAdministrator || !mayModifyExistingUser) { + return; + } - await checkAvatarChanged(activeUser); - const avatar = activeUser.avatarVersion - ? `/avatarproxy/${jellyfinUserId}?v=${encodeURIComponent(activeUser.avatarVersion)}` - : `/avatarproxy/${jellyfinUserId}`; - const updates: Partial< - Pick - > = {}; - if (activeUser.jellyfinUsername !== jellyfinUser.Name) { - updates.jellyfinUsername = jellyfinUser.Name; - } - if (activeUser.avatar !== avatar) { - updates.avatar = avatar; - } - if (Object.keys(updates).length > 0) { - await userRepository.update(activeUser.id, updates); - } - refreshedUsers += 1; - }); - } + await checkAvatarChanged(activeUser); + const avatar = activeUser.avatarVersion + ? `/avatarproxy/${jellyfinUserId}?v=${encodeURIComponent(activeUser.avatarVersion)}` + : `/avatarproxy/${jellyfinUserId}`; + const updates: Partial< + Pick + > = {}; + if (activeUser.jellyfinUsername !== jellyfinUser.Name) { + updates.jellyfinUsername = jellyfinUser.Name; + } + if (activeUser.avatar !== avatar) { + updates.avatar = avatar; + } + if (Object.keys(updates).length > 0) { + await userRepository.update(activeUser.id, updates); + } + refreshedUsers += 1; + }); } else { const existingEmailUser = await userRepository.findOne({ select: { id: true },