Compare commits

...

10 Commits

Author SHA1 Message Date
Aleksi Lassila
982be33c67 2.0.0-alpha.6 2024-06-18 22:04:04 +03:00
Aleksi Lassila
7845cfcde4 fix: Debug mode showing in production 2024-06-18 21:40:15 +03:00
Aleksi Lassila
7c31ee4ce9 style: Improved onboarding page styling and ux 2024-06-18 19:24:51 +03:00
Aleksi Lassila
d687b33249 refactor: TmdbIntegration 2024-06-18 01:08:50 +03:00
Aleksi Lassila
355c93e9e8 fix: And refactor onboarding integration components 2024-06-18 00:58:03 +03:00
Aleksi Lassila
1c2fbf74eb fix: Update account information after changes in manage page 2024-06-17 20:45:56 +03:00
Aleksi Lassila
421f0982d7 fix: migration commmands to run on dist/ 2024-06-17 01:31:57 +03:00
Aleksi Lassila
0bde0db218 build: Run migrations before starting 2024-06-17 00:59:22 +03:00
Aleksi Lassila
663d842ae5 build: Fix issue with production build not working 2024-06-17 00:50:19 +03:00
Aleksi Lassila
0107b4f7c3 feat: Editing, creating and deleting server accounts, user.controller improvements 2024-06-16 22:15:47 +03:00
42 changed files with 1017 additions and 948 deletions

View File

@@ -88,7 +88,7 @@ services:
`npm install --prefix backend`\
`npm run build`
4. Start the app:\
`node backend/dist/main`
`node backend/dist/src/main`
#### Reiverr will be accessible via port 9494 by default.

View File

@@ -11,7 +11,7 @@
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"start:prod": "npm run typeorm:run-migrations && node dist/src/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
@@ -20,10 +20,10 @@
"test:e2e": "jest --config ./test/jest-e2e.json",
"openapi:schema": "ts-node src/generate-openapi.ts",
"typeorm": "ts-node ./node_modules/typeorm/cli",
"typeorm:run-migrations": "npm run typeorm migration:run -- -d ./data-source.ts",
"typeorm:generate-migration": "npm run typeorm -- -d ./data-source.ts migration:generate ./migrations/$npm_config_name",
"typeorm:run-migrations": "npm run typeorm migration:run -- -d ./dist/data-source.js",
"typeorm:generate-migration": "npm run typeorm -- -d ./dist/data-source.js migration:generate ./dist/migrations/$npm_config_name",
"typeorm:create-migration": "npm run typeorm -- migration:create ./migrations/$npm_config_name",
"typeorm:revert-migration": "npm run typeorm -- -d ./data-source.ts migration:revert"
"typeorm:revert-migration": "npm run typeorm -- -d ./dist/data-source.js migration:revert"
},
"dependencies": {
"@nanogiants/nestjs-swagger-api-exception-decorator": "^1.6.11",

View File

@@ -2,7 +2,7 @@ import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { DatabaseModule } from './database/database.module';
import { UserModule } from './user/user.module';
import { UsersModule } from './users/users.module';
import { AuthModule } from './auth/auth.module';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';
@@ -10,10 +10,10 @@ import { join } from 'path';
@Module({
imports: [
DatabaseModule,
UserModule,
UsersModule,
AuthModule,
ServeStaticModule.forRoot({
rootPath: join(__dirname, 'dist'),
rootPath: join(__dirname, '../dist'),
}),
],
controllers: [AppController],

View File

@@ -7,7 +7,7 @@ import {
UnauthorizedException,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { SignInDto, UserDto } from '../user/user.dto';
import { SignInDto, UserDto } from '../users/user.dto';
import { ApiOkResponse, ApiProperty } from '@nestjs/swagger';
import { ApiException } from '@nanogiants/nestjs-swagger-api-exception-decorator';

View File

@@ -8,8 +8,8 @@ import {
import { JwtService } from '@nestjs/jwt';
import { JWT_SECRET } from '../consts';
import { AccessTokenPayload } from './auth.service';
import { User } from '../user/user.entity';
import { UserService } from '../user/user.service';
import { User } from '../users/user.entity';
import { UsersService } from '../users/users.service';
export const GetUser = createParamDecorator(
(data: unknown, ctx: ExecutionContext): User => {
@@ -28,7 +28,7 @@ function extractTokenFromHeader(request: Request): string | undefined {
export class AuthGuard implements CanActivate {
constructor(
private jwtService: JwtService,
private userService: UserService,
private userService: UsersService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
@@ -47,6 +47,10 @@ export class AuthGuard implements CanActivate {
if (payload.sub) {
request['user'] = await this.userService.findOne(payload.sub);
}
if (!request['user']) {
throw new UnauthorizedException();
}
} catch {
throw new UnauthorizedException();
}
@@ -58,7 +62,7 @@ export class AuthGuard implements CanActivate {
export class OptionalAuthGuard implements CanActivate {
constructor(
private jwtService: JwtService,
private userService: UserService,
private userService: UsersService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {

View File

@@ -1,13 +1,13 @@
import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { UserModule } from '../user/user.module';
import { UsersModule } from '../users/users.module';
import { JwtModule } from '@nestjs/jwt';
import { JWT_SECRET } from '../consts';
@Module({
imports: [
UserModule,
UsersModule,
JwtModule.register({
global: true,
secret: JWT_SECRET,

View File

@@ -1,7 +1,7 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { UsersService } from '../users/users.service';
import { JwtService } from '@nestjs/jwt';
import { User } from '../user/user.entity';
import { User } from '../users/user.entity';
export interface AccessTokenPayload {
sub: string;
@@ -10,7 +10,7 @@ export interface AccessTokenPayload {
@Injectable()
export class AuthService {
constructor(
private userService: UserService,
private userService: UsersService,
private jwtService: JwtService,
) {}
@@ -23,7 +23,11 @@ export class AuthService {
}> {
let user = await this.userService.findOneByName(name);
if (!user && (await this.userService.noPreviousAdmins()))
user = await this.userService.create(name, password, true);
user = await this.userService.create({
name,
password,
isAdmin: true,
});
if (!(user && user.password === password)) {
throw new UnauthorizedException();

View File

@@ -3,18 +3,22 @@ import { AppModule } from './app.module';
import 'reflect-metadata';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import * as fs from 'fs';
import { UserService } from './user/user.service';
import { UsersService } from './users/users.service';
import { ADMIN_PASSWORD, ADMIN_USERNAME } from './consts';
import { json, urlencoded } from 'express';
// import * as proxy from 'express-http-proxy';
async function createAdminUser(userService: UserService) {
async function createAdminUser(userService: UsersService) {
if (!ADMIN_USERNAME || ADMIN_PASSWORD === undefined) return;
const existingUser = await userService.findOneByName(ADMIN_USERNAME);
if (!existingUser) {
await userService.create(ADMIN_USERNAME, ADMIN_PASSWORD, true);
await userService.create({
name: ADMIN_USERNAME,
password: ADMIN_PASSWORD,
isAdmin: true,
});
}
}
@@ -35,7 +39,7 @@ async function bootstrap() {
SwaggerModule.setup('openapi', app, document);
fs.writeFileSync('./swagger-spec.json', JSON.stringify(document));
await createAdminUser(app.get(UserService));
await createAdminUser(app.get(UsersService));
await app.listen(9494);
}

View File

@@ -1,132 +0,0 @@
import {
BadRequestException,
Body,
Controller,
Get,
HttpCode,
HttpStatus,
NotFoundException,
Param,
Post,
Put,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';
import { UserService } from './user.service';
import { AuthGuard, GetUser, OptionalAuthGuard } from '../auth/auth.guard';
import { ApiOkResponse, ApiTags } from '@nestjs/swagger';
import { CreateUserDto, UpdateUserDto, UserDto } from './user.dto';
import { User } from './user.entity';
import { ApiException } from '@nanogiants/nestjs-swagger-api-exception-decorator';
@ApiTags('user')
@Controller('user')
export class UserController {
constructor(private userService: UserService) {}
@UseGuards(AuthGuard)
@Get()
@ApiOkResponse({ description: 'User found', type: UserDto })
@ApiException(() => NotFoundException, { description: 'User not found' })
async getProfile(@GetUser() user: User): Promise<UserDto> {
console.log(user);
if (!user) {
throw new NotFoundException();
}
return UserDto.fromEntity(user);
}
@UseGuards(AuthGuard)
@Get(':id')
@ApiOkResponse({ description: 'User found', type: UserDto })
@ApiException(() => NotFoundException, { description: 'User not found' })
async findById(
@Param('id') id: string,
@GetUser() callerUser: User,
): Promise<UserDto> {
if (!callerUser.isAdmin && callerUser.id !== id) {
throw new NotFoundException();
}
const user = await this.userService.findOne(id);
if (!user) {
throw new NotFoundException();
}
return UserDto.fromEntity(user);
}
// @Get('isSetupDone')
// @ApiOkResponse({ description: 'Setup done', type: Boolean })
// async isSetupDone() {
// return this.userService.noPreviousAdmins();
// }
@UseGuards(OptionalAuthGuard)
@HttpCode(HttpStatus.OK)
@Post()
async create(
@Body()
userCreateDto: CreateUserDto,
@GetUser() callerUser: User | undefined,
) {
const canCreateUser =
(await this.userService.noPreviousAdmins()) || callerUser?.isAdmin;
if (!canCreateUser) throw new UnauthorizedException();
const user = await this.userService.create(
userCreateDto.name,
userCreateDto.password,
userCreateDto.isAdmin,
);
return UserDto.fromEntity(user);
}
@UseGuards(AuthGuard)
@Put(':id')
@ApiOkResponse({ description: 'User updated', type: UserDto })
@ApiException(() => NotFoundException, { description: 'User not found' })
async updateUser(
@Param('id') id: string,
@Body() updateUserDto: UpdateUserDto,
@GetUser() callerUser: User,
): Promise<UserDto> {
if ((!callerUser.isAdmin && callerUser.id !== id) || !id) {
throw new NotFoundException();
}
const user = await this.userService.findOne(id);
if (updateUserDto.name) user.name = updateUserDto.name;
if (
updateUserDto.oldPassword === user.password &&
updateUserDto.password !== undefined
)
user.password = updateUserDto.password;
else if (
updateUserDto.password &&
updateUserDto.oldPassword !== user.password
)
throw new BadRequestException("Passwords don't match");
if (updateUserDto.settings) user.settings = updateUserDto.settings;
if (updateUserDto.onboardingDone)
user.onboardingDone = updateUserDto.onboardingDone;
if (updateUserDto.profilePicture) {
try {
user.profilePicture = Buffer.from(
updateUserDto.profilePicture.split(';base64,').pop() as string,
'base64',
);
} catch (e) {
console.error(e);
}
}
const updated = await this.userService.update(user);
return UserDto.fromEntity(updated);
}
}

View File

@@ -1,13 +0,0 @@
import { Module } from '@nestjs/common';
import { UserService } from './user.service';
import { userProviders } from './user.providers';
import { UserController } from './user.controller';
import { DatabaseModule } from '../database/database.module';
@Module({
imports: [DatabaseModule],
providers: [...userProviders, UserService],
controllers: [UserController],
exports: [UserService],
})
export class UserModule {}

View File

@@ -1,48 +0,0 @@
import { Inject, Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from './user.entity';
@Injectable()
export class UserService {
constructor(
@Inject('USER_REPOSITORY')
private readonly userRepository: Repository<User>,
) {}
async findAll(): Promise<User[]> {
return this.userRepository.find();
}
async findOne(id: string): Promise<User> {
return this.userRepository.findOne({ where: { id } });
}
async findOneByName(name: string): Promise<User> {
return this.userRepository.findOne({ where: { name } });
}
async create(name: string, password: string, isAdmin = false): Promise<User> {
const user = this.userRepository.create();
user.name = name;
// TODO: Hash password
user.password = password;
user.isAdmin = isAdmin;
return this.userRepository.save(user);
}
async update(user: User): Promise<User> {
return this.userRepository.save(user);
}
async remove(id: number): Promise<void> {
await this.userRepository.delete(id);
}
async noPreviousAdmins(): Promise<boolean> {
const adminCount = await this.userRepository.count({
where: { isAdmin: true },
});
return adminCount === 0;
}
}

View File

@@ -25,10 +25,19 @@ export class CreateUserDto extends PickType(User, [
'name',
'password',
'isAdmin',
] as const) {}
] as const) {
@ApiProperty({ type: 'string', required: false })
profilePicture?: string;
}
export class UpdateUserDto extends PartialType(
PickType(User, ['settings', 'onboardingDone', 'name', 'password'] as const),
PickType(User, [
'settings',
'onboardingDone',
'name',
'password',
'isAdmin',
] as const),
) {
@ApiProperty({ type: 'string', required: false })
profilePicture?: string;

View File

@@ -0,0 +1,149 @@
import {
BadRequestException,
Body,
Controller,
Delete,
Get,
HttpCode,
HttpStatus,
InternalServerErrorException,
NotFoundException,
Param,
Post,
Put,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';
import { UserServiceError, UsersService } from './users.service';
import { AuthGuard, GetUser, OptionalAuthGuard } from '../auth/auth.guard';
import { ApiOkResponse, ApiTags } from '@nestjs/swagger';
import { CreateUserDto, UpdateUserDto, UserDto } from './user.dto';
import { User } from './user.entity';
import { ApiException } from '@nanogiants/nestjs-swagger-api-exception-decorator';
@ApiTags('users')
@Controller('users')
export class UsersController {
constructor(private usersService: UsersService) {}
// @UseGuards(AuthGuard)
// @Get()
// @ApiOkResponse({ description: 'User found', type: UserDto })
// @ApiException(() => NotFoundException, { description: 'User not found' })
// async getProfile(@GetUser() user: User): Promise<UserDto> {
// console.log(user);
//
// if (!user) {
// throw new NotFoundException();
// }
//
// return UserDto.fromEntity(user);
// }
@UseGuards(AuthGuard)
@Get('')
@ApiOkResponse({
description: 'All users found',
type: UserDto,
isArray: true,
})
async findAll(@GetUser() callerUser: User): Promise<UserDto[]> {
if (!callerUser.isAdmin) {
throw new UnauthorizedException();
}
const users = await this.usersService.findAll();
return users.map((user) => UserDto.fromEntity(user));
}
@UseGuards(AuthGuard)
@Get(':id')
@ApiOkResponse({ description: 'User found', type: UserDto })
@ApiException(() => NotFoundException, { description: 'User not found' })
async findById(
@Param('id') id: string,
@GetUser() callerUser: User,
): Promise<UserDto> {
console.log('callerUser', callerUser);
if (!callerUser.isAdmin && callerUser.id !== id) {
throw new NotFoundException();
}
const user = await this.usersService.findOne(id);
if (!user) {
throw new NotFoundException();
}
return UserDto.fromEntity(user);
}
// @Get('isSetupDone')
// @ApiOkResponse({ description: 'Setup done', type: Boolean })
// async isSetupDone() {
// return this.userService.noPreviousAdmins();
// }
@UseGuards(OptionalAuthGuard)
@Post()
@ApiOkResponse({ description: 'User created', type: UserDto })
@ApiException(() => UnauthorizedException, { description: 'Unauthorized' })
@ApiException(() => BadRequestException)
async create(
@Body()
userCreateDto: CreateUserDto,
@GetUser() callerUser: User | undefined,
) {
const canCreateUser =
(await this.usersService.noPreviousAdmins()) || callerUser?.isAdmin;
if (!canCreateUser) throw new UnauthorizedException();
const user = await this.usersService.create(userCreateDto).catch((e) => {
if (e === UserServiceError.UsernameRequired)
throw new BadRequestException('Username is required');
else throw new InternalServerErrorException();
});
return UserDto.fromEntity(user);
}
@UseGuards(AuthGuard)
@Put(':id')
@ApiOkResponse({ description: 'User updated', type: UserDto })
@ApiException(() => NotFoundException, { description: 'User not found' })
async update(
@Param('id') id: string,
@Body() updateUserDto: UpdateUserDto,
@GetUser() callerUser: User,
): Promise<UserDto> {
if ((!callerUser.isAdmin && callerUser.id !== id) || !id) {
throw new NotFoundException();
}
const user = await this.usersService.findOne(id);
const updated = await this.usersService
.update(user, callerUser, updateUserDto)
.catch((e) => {
console.error(e);
if (e === UserServiceError.PasswordMismatch) {
throw new BadRequestException('Password mismatch');
} else throw new InternalServerErrorException();
});
return UserDto.fromEntity(updated);
}
@UseGuards(AuthGuard)
@Delete(':id')
@ApiOkResponse({ description: 'User deleted' })
@ApiException(() => NotFoundException, { description: 'User not found' })
async deleteUser(@Param('id') id: string, @GetUser() callerUser: User) {
if ((!callerUser.isAdmin && callerUser.id !== id) || !id) {
throw new NotFoundException();
}
await this.usersService.remove(id);
}
}

View File

@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { userProviders } from './user.providers';
import { UsersController } from './users.controller';
import { DatabaseModule } from '../database/database.module';
@Module({
imports: [DatabaseModule],
providers: [...userProviders, UsersService],
controllers: [UsersController],
exports: [UsersService],
})
export class UsersModule {}

View File

@@ -0,0 +1,99 @@
import { Inject, Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { CreateUserDto, UpdateUserDto } from './user.dto';
export enum UserServiceError {
PasswordMismatch = 'PasswordMismatch',
Unauthorized = 'Unauthorized',
UsernameRequired = 'UsernameRequired',
}
@Injectable()
export class UsersService {
constructor(
@Inject('USER_REPOSITORY')
private readonly userRepository: Repository<User>,
) {}
async findAll(): Promise<User[]> {
return this.userRepository.find();
}
async findOne(id: string): Promise<User> {
return this.userRepository.findOne({ where: { id } });
}
async findOneByName(name: string): Promise<User> {
return this.userRepository.findOne({ where: { name } });
}
async create(userCreateDto: CreateUserDto): Promise<User> {
if (!userCreateDto.name) throw UserServiceError.UsernameRequired;
const user = this.userRepository.create();
user.name = userCreateDto.name;
// TODO: Hash password
user.password = userCreateDto.password;
user.isAdmin = userCreateDto.isAdmin;
try {
user.profilePicture = Buffer.from(
userCreateDto.profilePicture.split(';base64,').pop() as string,
'base64',
);
} catch (e) {
console.error(e);
}
return this.userRepository.save(user);
}
async update(
user: User,
callerUser: User,
updateUserDto: UpdateUserDto,
): Promise<User> {
if (updateUserDto.name) user.name = updateUserDto.name;
if (updateUserDto.oldPassword !== updateUserDto.password) {
if (
updateUserDto.password !== undefined &&
updateUserDto.oldPassword !== user.password
)
throw UserServiceError.PasswordMismatch;
else if (updateUserDto.password !== undefined)
user.password = updateUserDto.password;
}
if (updateUserDto.settings) user.settings = updateUserDto.settings;
if (updateUserDto.onboardingDone)
user.onboardingDone = updateUserDto.onboardingDone;
if (updateUserDto.profilePicture) {
try {
user.profilePicture = Buffer.from(
updateUserDto.profilePicture.split(';base64,').pop() as string,
'base64',
);
} catch (e) {
console.error(e);
}
}
if (updateUserDto.isAdmin !== undefined && callerUser.isAdmin)
user.isAdmin = updateUserDto.isAdmin;
return this.userRepository.save(user);
}
async remove(id: string): Promise<void> {
await this.userRepository.delete(id);
}
async noPreviousAdmins(): Promise<boolean> {
const adminCount = await this.userRepository.count({
where: { isAdmin: true },
});
return adminCount === 0;
}
}

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "reiverr",
"version": "2.0.0-alpha.5",
"version": "2.0.0-alpha.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "reiverr",
"version": "2.0.0-alpha.5",
"version": "2.0.0-alpha.6",
"dependencies": {
"gsap": "^3.12.5"
},

View File

@@ -1,6 +1,6 @@
{
"name": "reiverr",
"version": "2.0.0-alpha.5",
"version": "2.0.0-alpha.6",
"repository": {
"type": "git",
"url": "https://github.com/aleksilassila/reiverr"
@@ -8,8 +8,8 @@
"type": "module",
"scripts": {
"dev": "vite",
"build": "npm run --prefix backend build && vite build --outDir backend/dist/dist",
"build:tizen": "set VITE_PLATFORM=tv&& vite build --outDir tizen/dist",
"build": "npm run --prefix backend build && vite build --mode production --outDir backend/dist/dist",
"build:tizen": "set VITE_PLATFORM=tv&& vite build --mode production --outDir tizen/dist",
"preview": "vite preview",
"preview:tizen": "set VITE_PLATFORM=tv&& vite build --outDir tizen/dist && vite preview --outDir tizen/dist",
"deploy": "PORT=9494 NODE_ENV=production node build/",

View File

@@ -94,6 +94,7 @@
<NotificationStack />
<NavigationDebugger />
{#if import.meta.env.DEV}
<NavigationDebugger />
{/if}
<svelte:window on:keydown={handleKeyboardNavigation} />

View File

@@ -85,7 +85,7 @@ html[data-useragent*="Tizen"] .selectable-secondary {
}
.header1 {
@apply font-medium text-lg text-secondary-300;
@apply font-semibold text-xl text-secondary-100;
}
.header2 {
@@ -96,13 +96,12 @@ html[data-useragent*="Tizen"] .selectable-secondary {
@apply font-semibold text-3xl text-secondary-100;
}
.header4 {
@apply font-semibold text-4xl text-secondary-100 tracking-wider;
}
.body {
@apply text-base text-secondary-200;
@apply font-medium text-lg text-secondary-300;
}
@media tv {

View File

@@ -506,9 +506,9 @@ export class JellyfinApi implements Api<paths> {
apiKey: string | undefined = undefined
): Promise<JellyfinUser[]> =>
axios
.get((baseUrl || this.getBaseUrl()) + '/Users', {
.get((baseUrl ?? this.getBaseUrl()) + '/Users', {
headers: {
'X-Emby-Token': apiKey || this.getApiKey()
'X-Emby-Token': apiKey ?? this.getApiKey()
}
})
.then((res) => res.data || [])

View File

@@ -249,9 +249,9 @@ export class RadarrApi implements Api<paths> {
apiKey: string | undefined = undefined
) =>
axios
.get((baseUrl || this.getBaseUrl()) + '/api/v3/health', {
.get((baseUrl ?? this.getBaseUrl()) + '/api/v3/health', {
headers: {
'X-Api-Key': apiKey || this.getSettings()?.apiKey
'X-Api-Key': apiKey ?? this.getSettings()?.apiKey
}
})
.catch((e) => e.response);

View File

@@ -5,6 +5,8 @@ import type { Api } from '../api.interface';
import { sessions } from '../../stores/session.store';
export type ReiverrUser = components['schemas']['UserDto'];
export type CreateReiverrUser = components['schemas']['CreateUserDto'];
export type UpdateReiverrUser = components['schemas']['UpdateUserDto'];
export type ReiverrSettings = ReiverrUser['settings'];
export class ReiverrApi implements Api<paths> {
@@ -22,36 +24,40 @@ export class ReiverrApi implements Api<paths> {
});
}
// isSetupDone = async (): Promise<boolean> =>
// this.getClient()
// ?.GET('/user/isSetupDone')
// .then((res) => res.data || false) || false;
async getUser() {
const res = await this.getClient()?.GET('/user', {});
return res.data;
}
authenticate(name: string, password: string) {
return this.getClient().POST('/auth', {
body: {
name,
password
}
});
}
updateUser = (user: ReiverrUser) =>
updateUser = (id: string, user: UpdateReiverrUser) =>
this.getClient()
?.PUT('/user/{id}', {
?.PUT('/users/{id}', {
params: {
path: {
id: user.id
id
}
},
body: user
})
.then((res) => ({ user: res.data, error: res.error?.message }));
getUsers = () =>
this.getClient()
.GET('/users', {})
.then((res) => res.data);
deleteUser = (id?: string) =>
this.getClient()
?.DELETE('/users/{id}', {
params: {
path: {
id: id || get(sessions).activeSession?.id || ''
}
}
})
.then((res) => res.error?.message);
createUser = (user: CreateReiverrUser) =>
this.getClient()
?.POST('/users', {
body: user
})
.then((res) => ({ user: res.data, error: res.error?.message }));
}
export const reiverrApi = new ReiverrApi();

View File

@@ -5,13 +5,14 @@
export interface paths {
"/user": {
get: operations["UserController_getProfile"];
post: operations["UserController_create"];
"/users": {
get: operations["UsersController_findAll"];
post: operations["UsersController_create"];
};
"/user/{id}": {
get: operations["UserController_findById"];
put: operations["UserController_updateUser"];
"/users/{id}": {
get: operations["UsersController_findById"];
put: operations["UsersController_update"];
delete: operations["UsersController_deleteUser"];
};
"/auth": {
post: operations["AuthController_signIn"];
@@ -68,10 +69,12 @@ export interface components {
name: string;
password: string;
isAdmin: boolean;
profilePicture?: string;
};
UpdateUserDto: {
name?: string;
password?: string;
isAdmin?: boolean;
onboardingDone?: boolean;
settings?: components["schemas"]["Settings"];
profilePicture?: string;
@@ -99,41 +102,56 @@ export type external = Record<string, never>;
export interface operations {
UserController_getProfile: {
UsersController_findAll: {
responses: {
/** @description User found */
/** @description All users found */
200: {
content: {
"application/json": components["schemas"]["UserDto"];
};
};
404: {
content: {
"application/json": {
/** @example 404 */
statusCode: number;
/** @example Not Found */
message: string;
/** @example Not Found */
error?: string;
};
"application/json": components["schemas"]["UserDto"][];
};
};
};
};
UserController_create: {
UsersController_create: {
requestBody: {
content: {
"application/json": components["schemas"]["CreateUserDto"];
};
};
responses: {
/** @description User created */
200: {
content: never;
content: {
"application/json": components["schemas"]["UserDto"];
};
};
400: {
content: {
"application/json": {
/** @example 400 */
statusCode: number;
/** @example Bad Request */
message: string;
/** @example Bad Request */
error?: string;
};
};
};
401: {
content: {
"application/json": {
/** @example 401 */
statusCode: number;
/** @example Unauthorized */
message: string;
/** @example Unauthorized */
error?: string;
};
};
};
};
};
UserController_findById: {
UsersController_findById: {
parameters: {
path: {
id: string;
@@ -160,7 +178,7 @@ export interface operations {
};
};
};
UserController_updateUser: {
UsersController_update: {
parameters: {
path: {
id: string;
@@ -192,6 +210,31 @@ export interface operations {
};
};
};
UsersController_deleteUser: {
parameters: {
path: {
id: string;
};
};
responses: {
/** @description User deleted */
200: {
content: never;
};
404: {
content: {
"application/json": {
/** @example 404 */
statusCode: number;
/** @example Not Found */
message: string;
/** @example Not Found */
error?: string;
};
};
};
};
};
AuthController_signIn: {
requestBody: {
content: {

View File

@@ -397,9 +397,9 @@ export class SonarrApi implements ApiAsync<paths> {
apiKey: string | undefined = undefined
) =>
axios
.get((baseUrl || this.getBaseUrl()) + '/api/v3/health', {
.get((baseUrl ?? this.getBaseUrl()) + '/api/v3/health', {
headers: {
'X-Api-Key': apiKey || this.getApiKey()
'X-Api-Key': apiKey ?? this.getApiKey()
}
})
.catch((e) => e.response);

View File

@@ -9,6 +9,7 @@
export let disabled: boolean = false;
export let focusOnMount: boolean = false;
export let focusedChild = false;
export let type: 'primary' | 'secondary' | 'primary-dark' = 'primary';
export let confirmDanger = false;
export let action: (() => Promise<any>) | null = null;
@@ -62,6 +63,7 @@
on:clickOrSelect={handleClickOrSelect}
on:enter
{focusOnMount}
{focusedChild}
>
<div
class={classNames({

View File

@@ -3,23 +3,33 @@
import { reiverrApi, type ReiverrUser } from '../../apis/reiverr/reiverr-api';
import TextField from '../TextField.svelte';
import Button from '../Button.svelte';
import { ArrowUp, EyeClosed, EyeOpen, Upload } from 'radix-icons-svelte';
import { ArrowUp, EyeClosed, EyeOpen, Trash, Upload } from 'radix-icons-svelte';
import Container from '../../../Container.svelte';
import IconToggle from '../IconToggle.svelte';
import Tab from '../Tab/Tab.svelte';
import { useTabs } from '../Tab/Tab';
import SelectField from '../SelectField.svelte';
import ProfileIcon from '../ProfileIcon.svelte';
import { profilePictures } from '../../profile-pictures';
import { modalStack } from '../Modal/modal.store';
import { getRandomProfilePicture, profilePictures } from '../../profile-pictures';
import { createModal, modalStack } from '../Modal/modal.store';
import { user as userStore } from '../../stores/user.store';
import ConfirmDialog from './ConfirmDialog.svelte';
import { sessions } from '../../stores/session.store';
import { navigate } from '../StackRouter/StackRouter';
import Toggle from '../Toggle.svelte';
import { get } from 'svelte/store';
enum Tabs {
EditProfile,
ProfilePictures
}
export let user: ReiverrUser;
export let modalId: symbol;
export let user: ReiverrUser | undefined = undefined;
export let onComplete: () => void = () => {};
export let createNew = false;
export let admin = createNew;
const tab = useTabs(Tabs.EditProfile);
@@ -28,8 +38,9 @@
let oldPasswordVisible = false;
let newPassword = '';
let newPasswordVisible = false;
let isAdmin = user?.isAdmin || false;
let profilePictureFiles: FileList;
let profilePictureBase64: string = user.profilePicture;
let profilePictureBase64: string = user?.profilePicture ?? getRandomProfilePicture() ?? '';
let profilePictureTitle: string;
let profilePictureFilesInput: HTMLInputElement;
$: {
@@ -75,9 +86,11 @@
}
$: stale =
(name !== user.name && name !== '') ||
(name !== user?.name && name !== '') ||
oldPassword !== newPassword ||
profilePictureBase64 !== user.profilePicture;
profilePictureBase64 !== user?.profilePicture ||
isAdmin !== user?.isAdmin;
$: complete = name !== '';
let errorMessage = '';
function setProfilePicture(image: string) {
@@ -86,43 +99,94 @@
}
async function save() {
const error = await userStore.updateUser((u) => ({
...u,
name,
password: newPassword,
oldPassword,
profilePicture: profilePictureBase64
// password: newPassword
}));
const id = user?.id;
if (!id) return;
const error =
id === get(userStore)?.id
? await userStore.updateUser((u) => ({
...u,
name,
password: newPassword,
oldPassword,
profilePicture: profilePictureBase64,
isAdmin
// password: newPassword
}))
: (
await reiverrApi.updateUser(id, {
name,
password: newPassword,
oldPassword,
profilePicture: profilePictureBase64,
isAdmin
})
).error;
if (error) {
errorMessage = error;
} else {
modalStack.closeTopmost();
onComplete();
}
}
async function create() {
const { error } = await reiverrApi.createUser({
name,
password: newPassword,
isAdmin,
profilePicture: profilePictureBase64
});
if (error) {
errorMessage = error;
} else {
modalStack.closeTopmost();
onComplete();
}
}
async function handleDeleteAccount() {
const self = user?.id === get(userStore)?.id;
const error = await reiverrApi.deleteUser(user?.id);
if (error) {
errorMessage = error;
} else {
modalStack.close(modalId);
if (self) {
sessions.removeSession();
navigate('/');
} else onComplete();
}
}
</script>
<Dialog class="grid" size={'dynamic'}>
<Tab {...tab} tab={Tabs.EditProfile} class="space-y-4 max-w-lg">
<h1 class="header2">Edit Profile</h1>
<h1 class="header2">
{createNew ? 'Create Account' : 'Edit Profile'}
</h1>
<TextField bind:value={name}>name</TextField>
<SelectField value={profilePictureTitle} on:clickOrSelect={() => tab.set(Tabs.ProfilePictures)}>
Profile Picture
</SelectField>
<Container direction="horizontal" class="flex space-x-4 items-end">
<TextField
class="flex-1"
bind:value={oldPassword}
type={oldPasswordVisible ? 'text' : 'password'}
>
Old Password
</TextField>
<IconToggle
on:clickOrSelect={() => (oldPasswordVisible = !oldPasswordVisible)}
icon={oldPasswordVisible ? EyeOpen : EyeClosed}
/>
</Container>
{#if !createNew}
<Container direction="horizontal" class="flex space-x-4 items-end">
<TextField
class="flex-1"
bind:value={oldPassword}
type={oldPasswordVisible ? 'text' : 'password'}
>
Old Password
</TextField>
<IconToggle
on:clickOrSelect={() => (oldPasswordVisible = !oldPasswordVisible)}
icon={oldPasswordVisible ? EyeOpen : EyeClosed}
/>
</Container>
{/if}
<Container direction="horizontal" class="flex space-x-4 items-end">
<TextField
class="flex-1"
@@ -136,10 +200,32 @@
icon={newPasswordVisible ? EyeOpen : EyeClosed}
/>
</Container>
{#if isAdmin || admin}
<div class="flex justify-between">
<label>Admin</label>
<Toggle bind:checked={isAdmin}>Admin</Toggle>
</div>
{/if}
{#if errorMessage}
<div class="text-red-500 mb-4">{errorMessage}</div>
{/if}
<Button type="primary-dark" disabled={!stale} action={save} class="mt-8">Save</Button>
<Container direction="horizontal" class="flex space-x-4 pt-4 *:flex-1">
{#if !createNew}
<Button type="primary-dark" disabled={!stale} action={save}>Save</Button>
<Button
type="primary-dark"
icon={Trash}
on:clickOrSelect={() =>
createModal(ConfirmDialog, {
header: 'Delete Account',
body: 'Are you sure you want to delete your account?',
confirm: handleDeleteAccount
})}>Delete Account</Button
>
{:else}
<Button type="primary-dark" disabled={!complete} action={create}>Create</Button>
{/if}
</Container>
</Tab>
<Tab
@@ -204,10 +290,6 @@
accept="image/png, image/jpeg"
class="hidden"
/>
<!-- <Container>-->
<!-- Select File-->
<!-- <input type="file" bind:files={profilePictureFiles} accept="image/png, image/jpeg" />-->
<!-- </Container>-->
</Container>
</Tab>
</Dialog>

View File

@@ -7,55 +7,59 @@
import { derived, get } from 'svelte/store';
const dispatch = createEventDispatcher<{
change: { baseUrl: string; apiKey: string; stale: boolean };
'click-user': { user: JellyfinUser | undefined; users: JellyfinUser[] };
'click-user': {
user: JellyfinUser | undefined;
users: JellyfinUser[];
setJellyfinUser: typeof setJellyfinUser;
};
}>();
export let baseUrl = get(user)?.settings.jellyfin.baseUrl || '';
export let apiKey = get(user)?.settings.jellyfin.apiKey || '';
let baseUrl = get(user)?.settings.jellyfin.baseUrl || '';
let apiKey = get(user)?.settings.jellyfin.apiKey || '';
export let jellyfinUser: JellyfinUser | undefined = undefined;
const originalBaseUrl = derived(user, (user) => user?.settings.jellyfin.baseUrl || '');
const originalApiKey = derived(user, (user) => user?.settings.jellyfin.apiKey || '');
const originalUserId = derived(user, (user) => user?.settings.jellyfin.userId || undefined);
let timeout: ReturnType<typeof setTimeout>;
export let jellyfinUsers: Promise<JellyfinUser[]> | undefined = undefined;
let stale = false;
let error = '';
let jellyfinUsers: Promise<JellyfinUser[]> | undefined = undefined;
export let jellyfinUser: JellyfinUser | undefined;
$: {
if ($originalBaseUrl !== baseUrl && $originalApiKey !== apiKey) handleChange();
else dispatch('change', { baseUrl, apiKey, stale: false });
jellyfinUser;
$originalBaseUrl;
$originalApiKey;
$originalUserId;
stale = getIsStale();
}
$: if (jellyfinUser)
dispatch('change', {
baseUrl,
apiKey,
stale:
baseUrl && apiKey ? jellyfinUser?.Id !== get(user)?.settings.jellyfin.userId : !jellyfinUser
});
handleChange();
function getIsStale() {
return (
(!!jellyfinUser?.Id || (!baseUrl && !apiKey && !jellyfinUser)) &&
($originalBaseUrl !== baseUrl ||
$originalApiKey !== apiKey ||
$originalUserId !== jellyfinUser?.Id)
);
}
function handleChange() {
clearTimeout(timeout);
stale = false;
error = '';
jellyfinUsers = undefined;
jellyfinUser = undefined;
if (baseUrl === '' || apiKey === '') {
stale = getIsStale();
return;
}
const baseUrlCopy = baseUrl;
const apiKeyCopy = apiKey;
dispatch('change', {
baseUrl: '',
apiKey: '',
stale:
baseUrl === '' &&
apiKey === '' &&
jellyfinUser === undefined &&
(baseUrl !== $originalBaseUrl || apiKey !== $originalApiKey)
});
if (baseUrlCopy === '' || apiKeyCopy === '') return;
timeout = setTimeout(async () => {
jellyfinUsers = jellyfinApi.getJellyfinUsers(baseUrl, apiKey);
@@ -64,28 +68,38 @@
if (users.length) {
jellyfinUser = users.find((u) => u.Id === get(user)?.settings.jellyfin.userId);
const stale =
(baseUrlCopy !== $originalBaseUrl || apiKeyCopy !== $originalApiKey) &&
jellyfinUser !== undefined;
dispatch('change', { baseUrl: baseUrlCopy, apiKey: apiKeyCopy, stale });
// stale = !!jellyfinUser?.Id && getIsStale();
} else {
error = 'Could not connect';
stale = false;
}
// if (res.status !== 200) {
// error =
// res.status === 404
// ? 'Server not found'
// : res.status === 401
// ? 'Invalid api key'
// : 'Could not connect';
//
// return; // TODO add notification
// } else {
// dispatch('change', { baseUrl: baseUrlCopy, apiKey: apiKeyCopy, stale });
// }
}, 1000);
}
const setJellyfinUser = (u: JellyfinUser) => (jellyfinUser = u);
async function handleSave() {
if (!stale) return;
return user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
jellyfin: {
...prev.settings.jellyfin,
baseUrl,
apiKey,
userId: jellyfinUser?.Id || ''
}
}
}));
}
$: empty = !baseUrl && !apiKey && !jellyfinUser;
$: unchanged =
$originalBaseUrl === baseUrl &&
$originalApiKey === apiKey &&
$originalUserId === jellyfinUser?.Id;
</script>
<div class="space-y-4 mb-4">
@@ -109,7 +123,9 @@
{#if users?.length}
<SelectField
value={jellyfinUser?.Name || 'Select User'}
on:clickOrSelect={() => dispatch('click-user', { user: jellyfinUser, users })}
on:clickOrSelect={() =>
dispatch('click-user', { user: jellyfinUser, users, setJellyfinUser })}
class="mb-4"
>
User
</SelectField>
@@ -119,3 +135,5 @@
{#if error}
<div class="text-red-500 mb-4">{error}</div>
{/if}
<slot {handleSave} {stale} {empty} {unchanged} />

View File

@@ -5,48 +5,51 @@
import { user } from '../../stores/user.store';
import { derived, get } from 'svelte/store';
const dispatch = createEventDispatcher<{
change: { baseUrl: string; apiKey: string; stale: boolean };
}>();
export let baseUrl = get(user)?.settings.radarr.baseUrl || '';
export let apiKey = get(user)?.settings.radarr.apiKey || '';
let baseUrl = get(user)?.settings.radarr.baseUrl || '';
let apiKey = get(user)?.settings.radarr.apiKey || '';
const originalBaseUrl = derived(user, (user) => user?.settings.radarr.baseUrl || '');
const originalApiKey = derived(user, (user) => user?.settings.radarr.apiKey || '');
let timeout: ReturnType<typeof setTimeout>;
let stale = false;
let error = '';
let timeout: ReturnType<typeof setTimeout>;
let healthCheck: Promise<boolean> | undefined;
$: {
if ($originalBaseUrl !== baseUrl && $originalApiKey !== apiKey) handleChange();
else dispatch('change', { baseUrl, apiKey, stale: false });
$originalBaseUrl;
$originalApiKey;
stale = getIsStale();
}
handleChange();
function getIsStale() {
return (
(!!healthCheck || (!baseUrl && !apiKey)) &&
($originalBaseUrl !== baseUrl || $originalApiKey !== apiKey)
);
}
function handleChange() {
clearTimeout(timeout);
stale = false;
error = '';
healthCheck = undefined;
if (baseUrl === '' || apiKey === '') {
stale = getIsStale();
return;
}
const baseUrlCopy = baseUrl;
const apiKeyCopy = apiKey;
const stale = baseUrlCopy !== $originalBaseUrl || apiKeyCopy !== $originalApiKey;
dispatch('change', {
baseUrl: '',
apiKey: '',
stale: baseUrl === '' && apiKey === '' && stale
});
if (baseUrlCopy === '' || apiKeyCopy === '') return;
timeout = setTimeout(async () => {
const p = radarrApi.getHealth(baseUrlCopy, apiKeyCopy);
healthCheck = p.then((res) => res.status === 200);
const res = await p;
if (baseUrlCopy !== baseUrl || apiKeyCopy !== apiKey) return;
if (res.status !== 200) {
error =
res.status === 404
@@ -55,12 +58,29 @@
? 'Invalid api key'
: 'Could not connect';
return; // TODO add notification
stale = false; // TODO add notification
} else {
dispatch('change', { baseUrl: baseUrlCopy, apiKey: apiKeyCopy, stale });
stale = getIsStale();
}
}, 1000);
}
async function handleSave() {
return user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
radarr: {
...prev.settings.radarr,
baseUrl,
apiKey
}
}
}));
}
$: empty = !baseUrl && !apiKey;
$: unchanged = baseUrl === $originalBaseUrl && apiKey === $originalApiKey;
</script>
<div class="space-y-4 mb-4">
@@ -73,3 +93,5 @@
{#if error}
<div class="text-red-500 mb-4">{error}</div>
{/if}
<slot {handleSave} {stale} {empty} {unchanged} />

View File

@@ -5,50 +5,51 @@
import { user } from '../../stores/user.store';
import { derived, get } from 'svelte/store';
const dispatch = createEventDispatcher<{
change: { baseUrl: string; apiKey: string; stale: boolean };
}>();
export let baseUrl = get(user)?.settings.sonarr.baseUrl || '';
export let apiKey = get(user)?.settings.sonarr.apiKey || '';
let baseUrl = get(user)?.settings.sonarr.baseUrl || '';
let apiKey = get(user)?.settings.sonarr.apiKey || '';
const originalBaseUrl = derived(user, (u) => u?.settings.sonarr.baseUrl || '');
const originalApiKey = derived(user, (u) => u?.settings.sonarr.apiKey || '');
let timeout: ReturnType<typeof setTimeout>;
let stale = false;
let error = '';
let timeout: ReturnType<typeof setTimeout>;
let healthCheck: Promise<boolean> | undefined;
$: {
if ($originalBaseUrl !== baseUrl && $originalApiKey !== apiKey) handleChange();
else dispatch('change', { baseUrl, apiKey, stale: false });
$originalBaseUrl;
$originalApiKey;
stale = getIsStale();
}
handleChange();
function handleChange() {
console.log('handleChange', $originalBaseUrl, baseUrl, $originalApiKey, apiKey);
function getIsStale() {
return (
(!!healthCheck || (!baseUrl && !apiKey)) &&
($originalBaseUrl !== baseUrl || $originalApiKey !== apiKey)
);
}
function handleChange() {
clearTimeout(timeout);
stale = false;
error = '';
healthCheck = undefined;
if (baseUrl === '' || apiKey === '') {
stale = getIsStale();
return;
}
const baseUrlCopy = baseUrl;
const apiKeyCopy = apiKey;
const stale = baseUrlCopy !== $originalBaseUrl || apiKeyCopy !== $originalApiKey;
dispatch('change', {
baseUrl: '',
apiKey: '',
stale: baseUrl === '' && apiKey === '' && stale
});
if (baseUrlCopy === '' || apiKeyCopy === '') return;
timeout = setTimeout(async () => {
const p = sonarrApi.getHealth(baseUrlCopy, apiKeyCopy);
healthCheck = p.then((res) => res.status === 200);
const res = await p;
if (baseUrlCopy !== baseUrl || apiKeyCopy !== apiKey) return;
if (res.status !== 200) {
error =
res.status === 404
@@ -57,12 +58,29 @@
? 'Invalid api key'
: 'Could not connect';
return; // TODO add notification
stale = false; // TODO add notification
} else {
dispatch('change', { baseUrl: baseUrlCopy, apiKey: apiKeyCopy, stale });
stale = getIsStale();
}
}, 1000);
}
async function handleSave() {
return user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
sonarr: {
...prev.settings.sonarr,
baseUrl,
apiKey
}
}
}));
}
$: empty = !baseUrl && !apiKey;
$: unchanged = baseUrl === $originalBaseUrl && apiKey === $originalApiKey;
</script>
<div class="space-y-4 mb-4">
@@ -75,3 +93,5 @@
{#if error}
<div class="text-red-500 mb-4">{error}</div>
{/if}
<slot {handleSave} {stale} {empty} {unchanged} />

View File

@@ -1,76 +1,36 @@
<script lang="ts">
import TextField from '../TextField.svelte';
import { sonarrApi } from '../../apis/sonarr/sonarr-api';
import { createEventDispatcher } from 'svelte';
import { tmdbApi } from '../../apis/tmdb/tmdb-api';
import { user } from '../../stores/user.store';
import SelectField from '../SelectField.svelte';
import { Trash } from 'radix-icons-svelte';
import { derived } from 'svelte/store';
import classNames from 'classnames';
const dispatch = createEventDispatcher<{
change: { baseUrl: string; apiKey: string; stale: boolean };
}>();
const userId = derived(user, (user) => user?.settings.tmdb.userId);
export let baseUrl = '';
export let apiKey = '';
let originalBaseUrl: string | undefined;
let originalApiKey: string | undefined;
let timeout: ReturnType<typeof setTimeout>;
let error = '';
let healthCheck: Promise<boolean> | undefined;
$: connectedTmdbAccount = !!$userId && tmdbApi.getAccountDetails();
user.subscribe((user) => {
baseUrl = baseUrl || user?.settings.sonarr.baseUrl || '';
apiKey = apiKey || user?.settings.sonarr.apiKey || '';
originalBaseUrl = baseUrl;
originalApiKey = apiKey;
handleChange();
});
function handleChange() {
clearTimeout(timeout);
error = '';
healthCheck = undefined;
const baseUrlCopy = baseUrl;
const apiKeyCopy = apiKey;
const stale = baseUrlCopy !== originalBaseUrl || apiKeyCopy !== originalApiKey;
dispatch('change', {
baseUrl: '',
apiKey: '',
stale: baseUrl === '' && apiKey === ''
});
if (baseUrlCopy === '' || apiKeyCopy === '') return;
timeout = setTimeout(async () => {
const p = sonarrApi.getHealth(baseUrlCopy, apiKeyCopy);
healthCheck = p.then((res) => res.status === 200);
const res = await p;
if (baseUrlCopy !== baseUrl || apiKeyCopy !== apiKey) return;
if (res.status !== 200) {
error =
res.status === 404
? 'Server not found'
: res.status === 401
? 'Invalid api key'
: 'Could not connect';
return; // TODO add notification
} else {
dispatch('change', { baseUrl: baseUrlCopy, apiKey: apiKeyCopy, stale });
async function handleDisconnectTmdb() {
return user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
tmdb: {
...prev.settings.tmdb,
userId: '',
sessionId: ''
}
}
}, 1000);
}));
}
</script>
<div class="space-y-4 mb-4">
<TextField bind:value={baseUrl} isValid={healthCheck} on:change={handleChange}>Base Url</TextField
>
<TextField bind:value={apiKey} isValid={healthCheck} on:change={handleChange}>API Key</TextField>
</div>
{#if error}
<div class="text-red-500 mb-4">{error}</div>
{/if}
{#await connectedTmdbAccount then tmdbAccount}
{#if tmdbAccount}
<SelectField value={tmdbAccount.username || ''} action={handleDisconnectTmdb}>
Connected to
<Trash slot="icon" let:size let:iconClass {size} class={classNames(iconClass, '')} />
</SelectField>
{/if}
<slot connected={!!tmdbAccount} />
{/await}

View File

@@ -2,7 +2,7 @@
import Container from '../../../Container.svelte';
import { tmdbApi } from '../../apis/tmdb/tmdb-api';
import Button from '../Button.svelte';
import { createEventDispatcher } from 'svelte';
import { createEventDispatcher, onMount } from 'svelte';
import { ExternalLink } from 'radix-icons-svelte';
import { user } from '../../stores/user.store';
@@ -13,6 +13,8 @@
let tmdbConnectQrCode: string | undefined = undefined;
let tmdbError: string = '';
handleGenerateTMDBLink();
async function handleGenerateTMDBLink() {
return tmdbApi.getConnectAccountLink().then((res) => {
if (res?.status_code !== 1) return; // TODO add notification
@@ -66,9 +68,9 @@
{/if}
<Container direction="horizontal" class="flex space-x-4 *:flex-1">
{#if !tmdbConnectRequestToken}
<Button type="primary-dark" action={handleGenerateTMDBLink}>Generate Link</Button>
{:else if tmdbConnectLink}
<!--{#if !tmdbConnectRequestToken}-->
<!-- <Button type="primary-dark" action={handleGenerateTMDBLink}>Generate Link</Button>-->
{#if tmdbConnectLink}
<Button type="primary-dark" action={completeTMDBConnect}>Complete Connection</Button>
<Button type="primary-dark" on:clickOrSelect={() => window.open(tmdbConnectLink)}>
Open Link

View File

@@ -41,7 +41,7 @@
<Container class="flex flex-col" focusOnMount>
<h1 class="header2 w-full mb-2">Login to Reiverr</h1>
<div class="header1 mb-4">
<div class="body mb-4">
If this is your first time logging in, a new account will be created based on your credentials.
</div>

View File

@@ -27,12 +27,13 @@
<Container
class={classNames(
'flex items-center justify-between bg-primary-900 rounded-xl px-6 py-2.5 mb-4 font-medium',
'flex items-center justify-between bg-primary-900 rounded-xl px-6 py-2.5 font-medium',
'border-2 border-transparent focus:border-primary-500 hover:border-primary-500 group',
{
'cursor-pointer': !_disabled,
'cursor-not-allowed pointer-events-none opacity-40': _disabled
}
},
$$restProps.class
)}
on:clickOrSelect={handleClickOrSelect}
let:hasFocus

View File

@@ -13,15 +13,16 @@
import JellyfinIntegrationUsersDialog from '../components/Integrations/JellyfinIntegrationUsersDialog.svelte';
import { tmdbApi } from '../apis/tmdb/tmdb-api';
import SelectField from '../components/SelectField.svelte';
import { ArrowRight, Exit, Pencil1, Pencil2, Trash } from 'radix-icons-svelte';
import { ArrowRight, Exit, Pencil2, Plus, Trash } from 'radix-icons-svelte';
import TmdbIntegrationConnectDialog from '../components/Integrations/TmdbIntegrationConnectDialog.svelte';
import { createModal } from '../components/Modal/modal.store';
import DetachedPage from '../components/DetachedPage/DetachedPage.svelte';
import { user } from '../stores/user.store';
import { sessions } from '../stores/session.store';
import TextField from '../components/TextField.svelte';
import EditProfileModal from '../components/Dialog/EditProfileModal.svelte';
import EditProfileModal from '../components/Dialog/CreateOrEditProfileModal.svelte';
import { scrollIntoView } from '../selectable';
import { reiverrApi } from '../apis/reiverr/reiverr-api';
import TmdbIntegration from '../components/Integrations/TmdbIntegration.svelte';
enum Tabs {
Interface,
@@ -31,23 +32,19 @@
const tab = useTabs(Tabs.Interface, { size: 'stretch' });
let jellyfinBaseUrl = '';
let jellyfinApiKey = '';
let jellyfinStale = false;
let jellyfinUser: JellyfinUser | undefined = undefined;
let sonarrBaseUrl = '';
let sonarrApiKey = '';
let sonarrStale = false;
let radarrBaseUrl = '';
let radarrApiKey = '';
let radarrStale = false;
let lastKeyCode = 0;
let lastKey = '';
let tizenMediaKey = '';
$: tmdbAccount = $user?.settings.tmdb.userId ? tmdbApi.getAccountDetails() : undefined;
let users = getUsers();
function getUsers() {
return $user?.isAdmin ? reiverrApi.getUsers() : undefined;
}
function handleLogOut() {
sessions.removeSession();
}
// onMount(() => {
// if (isTizen()) {
@@ -63,67 +60,6 @@
// (tizen as any)?.mediakey?.setMediaKeyEventListener?.(myMediaKeyChangeListener);
// }
// });
async function handleDisconnectTmdb() {
return user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
tmdb: {
...prev.settings.tmdb,
userId: '',
sessionId: ''
}
}
}));
}
async function handleSaveJellyfin() {
return user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
jellyfin: {
...prev.settings.jellyfin,
baseUrl: jellyfinBaseUrl,
apiKey: jellyfinApiKey,
userId: jellyfinUser?.Id ?? ''
}
}
}));
}
async function handleSaveSonarr() {
return user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
sonarr: {
...prev.settings.sonarr,
baseUrl: sonarrBaseUrl,
apiKey: sonarrApiKey
}
}
}));
}
async function handleSaveRadarr() {
return user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
radarr: {
...prev.settings.radarr,
baseUrl: radarrBaseUrl,
apiKey: radarrApiKey
}
}
}));
}
function handleLogOut() {
sessions.removeSession();
}
</script>
<svelte:window
@@ -133,10 +69,10 @@
}}
/>
<DetachedPage class="px-32 py-16 h-screen flex flex-col">
<DetachedPage class="pt-16 h-screen flex flex-col">
<Container
direction="horizontal"
class="flex space-x-8 header3 pb-3 border-b-2 border-secondary-700 w-full mb-8"
class="flex space-x-8 header3 pb-3 border-b-2 border-secondary-700 mb-8 mx-32"
>
<Container
on:enter={() => tab.set(Tabs.Interface)}
@@ -165,7 +101,7 @@
'text-primary-500': hasFocus
})}
>
Account
Accounts
</span>
</Container>
<Container
@@ -185,7 +121,7 @@
</Container>
</Container>
<Container class="flex-1 grid w-full overflow-y-auto scrollbar-hide relative">
<Container class="flex-1 grid w-full overflow-y-auto scrollbar-hide relative pb-16 px-32">
<Tab {...tab} tab={Tabs.Interface} class="w-full">
<div class="flex items-center justify-between text-lg font-medium text-secondary-100 py-2">
<label class="mr-2">Animate scrolling</label>
@@ -215,9 +151,10 @@
<Tab {...tab} tab={Tabs.Account} class="space-y-16">
<div>
<h1 class="font-semibold text-2xl text-secondary-100 mb-8">Profile</h1>
<Container class="bg-primary-800 rounded-xl p-8" on:enter={scrollIntoView({ top: 9999 })}>
<h1 class="header1 mb-4">My Profile</h1>
<SelectField
class="mb-4"
value={$user?.name || ''}
on:clickOrSelect={() => {
const u = $user;
@@ -233,6 +170,48 @@
<Container direction="horizontal" class="flex space-x-4">
<Button type="primary-dark" icon={Exit} on:clickOrSelect={handleLogOut}>Log Out</Button>
</Container>
{#await users then usersR}
{#if usersR?.length}
<div class="mt-8">
<h1 class="header1 mb-4">Server Accounts</h1>
<Container class="grid grid-cols-2 gap-4" direction="grid" gridCols={2}>
{#each usersR.filter((u) => u.id !== $user?.id) as user}
<SelectField
value={user?.name || ''}
on:clickOrSelect={() => {
createModal(EditProfileModal, {
user,
admin: true,
onComplete: () => (users = getUsers())
});
}}
>
{user.isAdmin ? 'Admin' : 'User'}
<Pencil2
slot="icon"
let:size
let:iconClass
{size}
class={classNames(iconClass)}
/>
</SelectField>
{/each}
<SelectField
value="New Account"
on:clickOrSelect={() => {
createModal(EditProfileModal, {
createNew: true,
onComplete: () => (users = getUsers())
});
}}
>
Create
<Plus slot="icon" let:size let:iconClass {size} class={classNames(iconClass)} />
</SelectField>
</Container>
</div>
{/if}
{/await}
</Container>
</div>
@@ -244,38 +223,20 @@
class="bg-primary-800 rounded-xl p-8"
on:enter={scrollIntoView({ vertical: 64 })}
>
<h1 class="mb-4 header2">Sonarr</h1>
<SonarrIntegration
on:change={({ detail }) => {
sonarrBaseUrl = detail.baseUrl;
sonarrApiKey = detail.apiKey;
sonarrStale = detail.stale;
}}
/>
<div class="flex">
<Button disabled={!sonarrStale} type="primary-dark" action={handleSaveSonarr}>
Save
</Button>
</div>
<h1 class="mb-4 header1">Sonarr</h1>
<SonarrIntegration let:stale let:handleSave>
<Button disabled={!stale} type="primary-dark" action={handleSave}>Save</Button>
</SonarrIntegration>
</Container>
<Container
class="bg-primary-800 rounded-xl p-8"
on:enter={scrollIntoView({ vertical: 64 })}
>
<h1 class="mb-4 header2">Radarr</h1>
<RadarrIntegration
on:change={({ detail }) => {
radarrBaseUrl = detail.baseUrl;
radarrApiKey = detail.apiKey;
radarrStale = detail.stale;
}}
/>
<div class="flex">
<Button disabled={!radarrStale} type="primary-dark" action={handleSaveRadarr}>
Save
</Button>
</div>
<h1 class="mb-4 header1">Radarr</h1>
<RadarrIntegration let:stale let:handleSave>
<Button disabled={!stale} type="primary-dark" action={handleSave}>Save</Button>
</RadarrIntegration>
</Container>
</Container>
@@ -284,56 +245,67 @@
class="bg-primary-800 rounded-xl p-8"
on:enter={scrollIntoView({ vertical: 64 })}
>
<h1 class="mb-4 header2">Tmdb Account</h1>
{#await tmdbAccount then tmdbAccount}
{#if tmdbAccount}
<SelectField value={tmdbAccount.username || ''} action={handleDisconnectTmdb}>
Connected to
<Trash
slot="icon"
let:size
let:iconClass
{size}
class={classNames(iconClass, '')}
/>
</SelectField>
{:else}
<div class="flex space-x-4">
<h1 class="mb-4 header1">Tmdb Account</h1>
<TmdbIntegration let:connected>
{#if !connected}
<div class="flex space-x-4 mt-4">
<Button
type="primary-dark"
iconAfter={ArrowRight}
on:clickOrSelect={() => createModal(TmdbIntegrationConnectDialog, {})}
>Connect</Button
>
Connect
</Button>
</div>
{/if}
{/await}
</TmdbIntegration>
<!--{#await tmdbAccount then tmdbAccount}-->
<!-- {#if tmdbAccount}-->
<!-- <SelectField-->
<!-- value={tmdbAccount.username || ''}-->
<!-- action={handleDisconnectTmdb}-->
<!-- class="mb-4"-->
<!-- >-->
<!-- Connected to-->
<!-- <Trash-->
<!-- slot="icon"-->
<!-- let:size-->
<!-- let:iconClass-->
<!-- {size}-->
<!-- class={classNames(iconClass, '')}-->
<!-- />-->
<!-- </SelectField>-->
<!-- {:else}-->
<!-- <div class="flex space-x-4">-->
<!-- <Button-->
<!-- type="primary-dark"-->
<!-- iconAfter={ArrowRight}-->
<!-- on:clickOrSelect={() => createModal(TmdbIntegrationConnectDialog, {})}-->
<!-- >Connect</Button-->
<!-- >-->
<!-- </div>-->
<!-- {/if}-->
<!--{/await}-->
</Container>
<Container
class="bg-primary-800 rounded-xl p-8"
on:enter={scrollIntoView({ vertical: 64 })}
>
<h1 class="mb-4 header2">Jellyfin</h1>
<h1 class="mb-4 header1">Jellyfin</h1>
<JellyfinIntegration
bind:jellyfinUser
on:change={({ detail }) => {
jellyfinBaseUrl = detail.baseUrl;
jellyfinApiKey = detail.apiKey;
jellyfinStale = detail.stale;
}}
on:click-user={({ detail }) =>
createModal(JellyfinIntegrationUsersDialog, {
selectedUser: detail.user,
users: detail.users,
handleSelectUser: (u) => (jellyfinUser = u)
handleSelectUser: detail.setJellyfinUser
})}
/>
<div class="flex">
<Button disabled={!jellyfinStale} type="primary-dark" action={handleSaveJellyfin}>
Save
</Button>
</div>
let:handleSave
let:stale
>
<Button disabled={!stale} type="primary-dark" action={handleSave}>Save</Button>
</JellyfinIntegration>
</Container>
</Container>
</Container>
@@ -344,6 +316,12 @@
<div>
Version: {REIVERR_VERSION}
</div>
<div>
Mode: {import.meta.env.MODE}
</div>
<div>
meta.env: {JSON.stringify(import.meta.env)}
</div>
User agent: {window?.navigator?.userAgent}
<div>Last key code: {lastKeyCode}</div>
<div>Last key: {lastKey}</div>

View File

@@ -15,6 +15,11 @@
import { user } from '../stores/user.store';
import { sessions } from '../stores/session.store';
import Panel from '../components/Panel.svelte';
import TmdbIntegrationConnect from '../components/Integrations/TmdbIntegrationConnect.svelte';
import JellyfinIntegration from '../components/Integrations/JellyfinIntegration.svelte';
import SonarrIntegration from '../components/Integrations/SonarrIntegration.svelte';
import RadarrIntegration from '../components/Integrations/RadarrIntegration.svelte';
import TmdbIntegration from '../components/Integrations/TmdbIntegration.svelte';
enum Tabs {
Welcome,
@@ -30,190 +35,10 @@
const tab = useTabs(Tabs.Welcome, { ['class']: 'w-max max-w-lg' });
let tmdbConnectRequestToken: string | undefined = undefined;
let tmdbConnectLink: string | undefined = undefined;
let tmdbConnectQrCode: string | undefined = undefined;
$: connectedTmdbAccount = $user?.settings.tmdb.userId && tmdbApi.getAccountDetails();
let tmdbError: string = '';
let jellyfinBaseUrl: string = '';
let jellyfinApiKey: string = '';
let jellyfinUser: JellyfinUser | undefined = undefined;
let jellyfinUsers: Promise<JellyfinUser[]> = Promise.resolve([]);
let jellyfinConnectionCheckTimeout: ReturnType<typeof setTimeout> | undefined = undefined;
let jellyfinError: string = '';
let sonarrBaseUrl: string = '';
let sonarrApiKey: string = '';
let sonarrError: string = '';
let radarrBaseUrl: string = '';
let radarrApiKey: string = '';
let radarrError: string = '';
user.subscribe((user) => {
jellyfinBaseUrl = jellyfinBaseUrl || user?.settings.jellyfin.baseUrl || '';
jellyfinApiKey = jellyfinApiKey || user?.settings.jellyfin.apiKey || '';
sonarrBaseUrl = sonarrBaseUrl || user?.settings.sonarr.baseUrl || '';
sonarrApiKey = sonarrApiKey || user?.settings.sonarr.apiKey || '';
radarrBaseUrl = radarrBaseUrl || user?.settings.radarr.baseUrl || '';
radarrApiKey = radarrApiKey || user?.settings.radarr.apiKey || '';
// if (
// !jellyfinUser &&
// appState.user?.settings.jellyfin.userId &&
// jellyfinBaseUrl &&
// jellyfinApiKey
// ) {
// jellyfinUsers = jellyfinApi.getJellyfinUsers(jellyfinBaseUrl, jellyfinApiKey);
// jellyfinUsers.then(
// (users) =>
// (jellyfinUser = users.find((u) => u.Id === appState.user?.settings.jellyfin.userId))
// );
// }
});
$: if (jellyfinBaseUrl && jellyfinApiKey) {
clearTimeout(jellyfinConnectionCheckTimeout);
const baseUrlCopy = jellyfinBaseUrl;
const apiKeyCopy = jellyfinApiKey;
jellyfinUser = undefined;
jellyfinConnectionCheckTimeout = setTimeout(async () => {
jellyfinUsers = jellyfinApi
.getJellyfinUsers(jellyfinBaseUrl, jellyfinApiKey)
.then((users) => {
if (baseUrlCopy === jellyfinBaseUrl && apiKeyCopy === jellyfinApiKey) {
jellyfinUser = users.find((u) => u.Id === $user?.settings.jellyfin.userId);
jellyfinError = users.length ? '' : 'Could not connect';
}
// console.log(users, baseUrlCopy, jellyfinBaseUrl, apiKeyCopy, jellyfinApiKey);
// jellyfinUsers = users;
// return !!users?.length;
return users;
});
}, 500);
}
async function handleGenerateTMDBLink() {
return tmdbApi.getConnectAccountLink().then((res) => {
if (res?.status_code !== 1) return; // TODO add notification
const link = `https://www.themoviedb.org/auth/access?request_token=${res?.request_token}`;
const qrCode = `https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${link}`;
tmdbConnectRequestToken = res?.request_token;
tmdbConnectLink = link;
tmdbConnectQrCode = qrCode;
});
}
async function completeTMDBConnect() {
if (!tmdbConnectRequestToken) return;
tmdbApi.getAccountAccessToken(tmdbConnectRequestToken).then((res) => {
const { status_code, access_token, account_id } = res || {};
if (status_code !== 1 || !access_token || !account_id) return; // TODO add notification
user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
tmdb: {
userId: account_id,
sessionId: access_token
}
}
}));
tab.set(Tabs.Jellyfin);
});
}
async function handleConnectJellyfin() {
const userId = jellyfinUser?.Id;
const baseUrl = jellyfinBaseUrl;
const apiKey = jellyfinApiKey;
if (!userId || !baseUrl || !apiKey) return;
await user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
jellyfin: {
...prev.settings.jellyfin,
userId,
baseUrl,
apiKey
}
}
}));
tab.next();
}
async function handleConnectSonarr() {
const baseUrl = sonarrBaseUrl;
const apiKey = sonarrApiKey;
if (!baseUrl || !apiKey) return;
const res = await sonarrApi.getHealth(baseUrl, apiKey);
if (res.status !== 200) {
sonarrError =
res.status === 404
? 'Server not found'
: res.status === 401
? 'Invalid api key'
: 'Could not connect';
return; // TODO add notification
}
await user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
sonarr: {
...prev.settings.sonarr,
baseUrl,
apiKey
}
}
}));
tab.next();
}
async function handleConnectRadarr() {
const baseUrl = radarrBaseUrl;
const apiKey = radarrApiKey;
if (!baseUrl || !apiKey) return;
const res = await radarrApi.getHealth(baseUrl, apiKey);
if (res.status !== 200) {
res.status === 404
? 'Server not found'
: res.status === 401
? 'Invalid api key'
: 'Could not connect';
return; // TODO add notification
}
await user.updateUser((prev) => ({
...prev,
settings: {
...prev.settings,
radarr: {
...prev.settings.radarr,
baseUrl,
apiKey
}
}
}));
await finalizeSetup();
}
async function finalizeSetup() {
await user.updateUser((prev) => ({
@@ -225,9 +50,6 @@
function handleBack() {
tab.previous();
}
const tabContainer =
'col-start-1 col-end-1 row-start-1 row-end-1 flex flex-col bg-primary-800 rounded-2xl p-10 shadow-xl max-w-lg';
</script>
<Container focusOnMount class="h-full w-full flex items-center justify-center" on:back={handleBack}>
@@ -238,18 +60,18 @@
Looks like this is a new account. This setup will get you started with connecting your
services to get most out of Reiverr.
</div>
<Container direction="horizontal" class="flex space-x-4">
<Container direction="horizontal" class="flex space-x-4 *:flex-1">
<Button type="primary-dark" on:clickOrSelect={() => sessions.removeSession()}
>Log Out</Button
>
<div class="flex-1">
<Button type="primary-dark" on:clickOrSelect={() => tab.next()}>
Next
<div class="absolute inset-y-0 right-0 flex items-center justify-center">
<ArrowRight size={24} />
</div>
</Button>
</div>
<Button
focusOnMount
type="primary-dark"
on:clickOrSelect={() => tab.next()}
iconAbsolute={ArrowRight}
>
Next
</Button>
</Container>
</Tab>
@@ -260,39 +82,54 @@
preferences.
</div>
<div class="space-y-4 flex flex-col">
{#await connectedTmdbAccount then account}
{#if account}
<SelectField
value={account.username || ''}
on:clickOrSelect={() => {
tab.set(Tabs.TmdbConnect);
handleGenerateTMDBLink();
}}>Logged in as</SelectField
>
{:else}
<TmdbIntegration handleConnectTmdb={() => tab.set(Tabs.TmdbConnect)} let:connected>
{#if !connected}
{#if !$user?.settings.tmdb.userId}
<Button
type="primary-dark"
on:clickOrSelect={() => {
tab.set(Tabs.TmdbConnect);
handleGenerateTMDBLink();
}}
>
Connect
<ArrowRight size={19} slot="icon-absolute" />
</Button>
{/if}
{/await}
{/if}
<Container direction="horizontal" class="flex space-x-4 *:flex-1 mt-4">
<Button type="primary-dark" on:clickOrSelect={() => tab.previous()}>Back</Button>
<Button focusedChild type="primary-dark" on:clickOrSelect={() => tab.next()}>
{#if connected}
Next
{:else}
Skip
{/if}
</Button>
</Container>
</TmdbIntegration>
<Button type="primary-dark" on:clickOrSelect={() => tab.next()}>
{#if $user?.settings.tmdb.userId}
Next
{:else}
Skip
{/if}
<ArrowRight size={19} slot="icon-absolute" />
</Button>
</div>
<!-- <div class="space-y-4 flex flex-col">-->
<!-- {#await connectedTmdbAccount then account}-->
<!-- {#if account}-->
<!-- <SelectField-->
<!-- class="mb-4"-->
<!-- value={account.username || ''}-->
<!-- on:clickOrSelect={() => {-->
<!-- tab.set(Tabs.TmdbConnect);-->
<!-- }}>Logged in as</SelectField-->
<!-- >-->
<!-- {:else}-->
<!-- <Button-->
<!-- type="primary-dark"-->
<!-- on:clickOrSelect={() => {-->
<!-- tab.set(Tabs.TmdbConnect);-->
<!-- }}-->
<!-- >-->
<!-- Connect-->
<!-- <ArrowRight size={19} slot="icon-absolute" />-->
<!-- </Button>-->
<!-- {/if}-->
<!-- {/await}-->
<!-- </div>-->
</Tab>
<Tab
@@ -303,68 +140,64 @@
detail.stopPropagation();
}}
>
<h1 class="header2 mb-2">Connect a TMDB Account</h1>
<div class="body mb-8">
To connect your TMDB account, log in via the link below and then click "Complete
Connection".
</div>
{#if tmdbConnectQrCode}
<div
class="w-[150px] h-[150px] bg-contain bg-center mb-8 mx-auto"
style={`background-image: url(${tmdbConnectQrCode})`}
/>
{/if}
<Container direction="horizontal" class="flex space-x-4 *:flex-1">
{#if !tmdbConnectRequestToken}
<Button type="primary-dark" action={handleGenerateTMDBLink}>Generate Link</Button>
{:else if tmdbConnectLink}
<Button type="primary-dark" action={completeTMDBConnect}>Complete Connection</Button>
<Button type="primary-dark" on:clickOrSelect={() => window.open(tmdbConnectLink)}>
Open Link
<ExternalLink size={19} slot="icon-after" />
</Button>
{/if}
</Container>
<TmdbIntegrationConnect on:connected={() => tab.set(Tabs.Jellyfin)} />
</Tab>
<Tab {...tab} tab={Tabs.Jellyfin}>
<h1 class="header2 mb-2">Connect to Jellyfin</h1>
<div class="mb-8 body">Connect to Jellyfin to watch movies and tv shows.</div>
<div class="space-y-4 mb-4">
<TextField bind:value={jellyfinBaseUrl} isValid={jellyfinUsers.then((u) => !!u?.length)}>
Base Url
</TextField>
<TextField bind:value={jellyfinApiKey} isValid={jellyfinUsers.then((u) => !!u?.length)}>
API Key
</TextField>
</div>
<JellyfinIntegration
bind:jellyfinUser
bind:jellyfinUsers
on:click-user={() => tab.set(Tabs.SelectUser)}
let:handleSave
let:stale
let:empty
let:unchanged
>
<Container direction="horizontal" class="grid grid-cols-2 gap-4 mt-4">
<Button type="primary-dark" on:clickOrSelect={() => tab.previous()}>Back</Button>
{#if empty || unchanged}
<Button focusedChild type="primary-dark" on:clickOrSelect={() => tab.next()}>
{empty ? 'Skip' : 'Next'}
</Button>
{:else}
<Button
type="primary-dark"
disabled={!stale}
action={() => handleSave().then(tab.next)}
>
Connect
</Button>
{/if}
</Container>
</JellyfinIntegration>
{#await jellyfinUsers then users}
{#if users.length}
<SelectField
value={jellyfinUser?.Name || 'Select User'}
on:clickOrSelect={() => tab.set(Tabs.SelectUser)}
>
User
</SelectField>
{/if}
{/await}
<!-- <div class="space-y-4 mb-4">-->
<!-- <TextField bind:value={jellyfinBaseUrl} isValid={jellyfinUsers.then((u) => !!u?.length)}>-->
<!-- Base Url-->
<!-- </TextField>-->
<!-- <TextField bind:value={jellyfinApiKey} isValid={jellyfinUsers.then((u) => !!u?.length)}>-->
<!-- API Key-->
<!-- </TextField>-->
<!-- </div>-->
{#if jellyfinError}
<div class="text-red-500 mb-4">{jellyfinError}</div>
{/if}
<!-- {#await jellyfinUsers then users}-->
<!-- {#if users.length}-->
<!-- <SelectField-->
<!-- value={jellyfinUser?.Name || 'Select User'}-->
<!-- on:clickOrSelect={() => tab.set(Tabs.SelectUser)}-->
<!-- class="mb-4"-->
<!-- >-->
<!-- User-->
<!-- </SelectField>-->
<!-- {/if}-->
<!-- {/await}-->
<Container direction="horizontal" class="grid grid-cols-2 gap-4 mt-4">
<Button type="primary-dark" on:clickOrSelect={() => tab.previous()}>Back</Button>
{#if jellyfinBaseUrl && jellyfinApiKey && jellyfinUser}
<Button type="primary-dark" action={handleConnectJellyfin}>Connect</Button>
{:else}
<Button type="primary-dark" on:clickOrSelect={() => tab.next()}>Skip</Button>
{/if}
</Container>
<!-- {#if jellyfinError}-->
<!-- <div class="text-red-500 mb-4">{jellyfinError}</div>-->
<!-- {/if}-->
</Tab>
<Tab
{...tab}
@@ -377,7 +210,7 @@
<h1 class="header1 mb-2 w-96">Select User</h1>
<div class="flex flex-col space-y-4" />
{#await jellyfinUsers then users}
{#each users as user}
{#each users || [] as user}
<SelectItem
selected={user?.Id === jellyfinUser?.Id}
on:clickOrSelect={() => {
@@ -395,46 +228,48 @@
<h1 class="header2 mb-2">Connect to Sonarr</h1>
<div class="mb-8">Connect to Sonarr for requesting and managing tv shows.</div>
<div class="space-y-4 mb-4">
<TextField bind:value={sonarrBaseUrl}>Base Url</TextField>
<TextField bind:value={sonarrApiKey}>API Key</TextField>
</div>
{#if sonarrError}
<div class="text-red-500 mb-4">{sonarrError}</div>
{/if}
<Container direction="horizontal" class="grid grid-cols-2 gap-4 mt-4">
<Button type="primary-dark" on:clickOrSelect={() => tab.previous()}>Back</Button>
{#if sonarrBaseUrl && sonarrApiKey}
<Button type="primary-dark" action={handleConnectSonarr}>Connect</Button>
{:else}
<Button type="primary-dark" on:clickOrSelect={() => tab.next()}>Skip</Button>
{/if}
</Container>
<SonarrIntegration let:stale let:handleSave let:empty let:unchanged>
<Container direction="horizontal" class="grid grid-cols-2 gap-4 mt-4">
<Button type="primary-dark" on:clickOrSelect={() => tab.previous()}>Back</Button>
{#if empty || unchanged}
<Button focusedChild type="primary-dark" on:clickOrSelect={() => tab.next()}>
{empty ? 'Skip' : 'Next'}
</Button>
{:else}
<Button
type="primary-dark"
disabled={!stale}
action={() => handleSave().then(tab.next)}
>
Connect
</Button>
{/if}
</Container>
</SonarrIntegration>
</Tab>
<Tab {...tab} tab={Tabs.Radarr}>
<h1 class="header2 mb-2">Connect to Radarr</h1>
<div class="mb-8">Connect to Radarr for requesting and managing movies.</div>
<div class="space-y-4 mb-4">
<TextField bind:value={radarrBaseUrl}>Base Url</TextField>
<TextField bind:value={radarrApiKey}>API Key</TextField>
</div>
{#if radarrError}
<div class="text-red-500 mb-4">{radarrError}</div>
{/if}
<Container direction="horizontal" class="grid grid-cols-2 gap-4 mt-4">
<Button type="primary-dark" on:clickOrSelect={() => tab.previous()}>Back</Button>
{#if radarrBaseUrl && radarrApiKey}
<Button type="primary-dark" action={handleConnectRadarr}>Connect</Button>
{:else}
<Button type="primary-dark" on:clickOrSelect={() => tab.next()}>Skip</Button>
{/if}
</Container>
<RadarrIntegration let:stale let:handleSave let:empty let:unchanged>
<Container direction="horizontal" class="grid grid-cols-2 gap-4 mt-4">
<Button type="primary-dark" on:clickOrSelect={() => tab.previous()}>Back</Button>
{#if empty || unchanged}
<Button focusedChild type="primary-dark" on:clickOrSelect={() => tab.next()}>
{empty ? 'Skip' : 'Next'}
</Button>
{:else}
<Button
type="primary-dark"
disabled={!stale}
action={() => handleSave().then(tab.next)}
>
Connect
</Button>
{/if}
</Container>
</RadarrIntegration>
</Tab>
<Tab {...tab} tab={Tabs.Complete} class={classNames('w-full')}>
@@ -442,16 +277,21 @@
<CheckCircled size={64} />
</div>
<h1 class="header2 text-center w-full">All Set!</h1>
<div class="header1 mb-8 text-center">Reiverr is now ready to use.</div>
<div class="body mb-8 text-center">Reiverr is now ready to use.</div>
<Container direction="horizontal" class="inline-flex space-x-4 w-full">
<Button type="primary-dark" on:clickOrSelect={() => tab.previous()} icon={ArrowLeft}
>Back</Button
>
<Button type="primary-dark" on:clickOrSelect={() => tab.previous()} icon={ArrowLeft}>
Back
</Button>
<div class="flex-1">
<Button type="primary-dark" on:clickOrSelect={finalizeSetup} iconAbsolute={ArrowRight}
>Done</Button
<Button
focusedChild
type="primary-dark"
on:clickOrSelect={finalizeSetup}
iconAbsolute={ArrowRight}
>
Done
</Button>
</div>
</Container>
</Tab>

View File

@@ -4,9 +4,7 @@
import { reiverrApi } from '../apis/reiverr/reiverr-api';
import Container from '../../Container.svelte';
import Button from '../components/Button.svelte';
import { TMDB_PROFILE_LARGE } from '../constants';
import classNames from 'classnames';
import AnimateScale from '../components/AnimateScale.svelte';
import { navigate } from '../components/StackRouter/StackRouter';
import { createModal } from '../components/Modal/modal.store';
import AddUserDialog from '../components/Dialog/AddUserDialog.svelte';
@@ -22,7 +20,7 @@
sessions.map(async (session) =>
reiverrApi
.getClient(session.baseUrl, session.token)
.GET('/user')
.GET('/users/{id}', { params: { path: { id: session.id } } })
.then((r) => ({ session, user: r.data }))
)
).then((us) => us.filter((u) => !!u.user));

File diff suppressed because one or more lines are too long

View File

@@ -580,6 +580,20 @@ export class Selectable {
console.error('No html element found for', this);
return;
}
if (this.makeFocusedChild) {
// eslint-disable-next-line @typescript-eslint/no-this-alias
let el: Selectable = this;
let parent = el.parent;
while (parent && !get(parent.hasFocusWithin)) {
console.log('setting parent focusIndex', parent, parent.children.indexOf(el));
parent.focusIndex.update((prev) => parent?.children?.indexOf(el) || prev);
el = parent;
parent = el.parent;
}
}
}
_unmountContainer() {
@@ -744,18 +758,6 @@ export class Selectable {
this.children.splice(index, 0, child);
child.parent = this;
if (child.makeFocusedChild) {
let el = child;
let parent = el.parent;
while (parent && !get(parent.hasFocusWithin)) {
parent.focusIndex.update((prev) => parent?.children?.indexOf(el) || prev);
el = parent;
parent = el.parent;
}
}
return childToFocus;
}

View File

@@ -54,10 +54,10 @@ function useSessions() {
function removeSession(_session?: Session) {
sessions.update((s) => {
const session = _session || s.activeSession;
const sessions = s.sessions.filter((s) => s !== session);
const sessions = s.sessions.filter((s) => s.id !== session?.id);
return {
sessions,
activeSession: s.activeSession === session ? undefined : s.activeSession
activeSession: s.activeSession?.id === session?.id ? undefined : s.activeSession
};
});
}

View File

@@ -20,8 +20,8 @@ function useUser() {
lastActiveSession = activeSession;
const user = await axios
.get<
operations['UserController_getProfile']['responses']['200']['content']['application/json']
>(activeSession.baseUrl + '/api/user', {
operations['UsersController_findById']['responses']['200']['content']['application/json']
>(activeSession.baseUrl + '/api/users/' + activeSession.id, {
headers: {
Authorization: 'Bearer ' + activeSession.token
}
@@ -38,7 +38,7 @@ function useUser() {
if (!user) return;
const updated = updateFn(user);
const { user: update, error } = await reiverrApi.updateUser(updated);
const { user: update, error } = await reiverrApi.updateUser(updated.id, updated);
if (update) {
userStore.set(update);