import { GuildMember } from "discord.js"; import { CreateUserByNameOperationRequest, SystemApi, UpdateUserPasswordOperationRequest, UpdateUserPolicyOperationRequest, UserApi } from "./apis"; import { UserDto } from "./models/UserDto"; import { Configuration, ConfigurationParameters } from "./runtime"; import { CreateUserByNameRequest, UpdateUserEasyPasswordRequest, UpdateUserPasswordRequest, UpdateUserPolicyRequest } from "./models"; import { Config } from "../configuration"; import { logger } from "../logger"; import { Maybe } from "../interfaces"; import { v4 as uuid } from "uuid"; export class JellyfinHandler { private userApi: UserApi private systemApi: SystemApi private token: string private authHeader: { headers: { 'X-Emby-Authorization': string } } private config: Config private serverName = ""; public async ServerName(): Promise { if (this.serverName === "") { const info = await this.systemApi.getSystemInfo(this.authHeader) this.serverName = info.serverName ?? this.config.bot.jellyfin_url } return this.serverName } constructor(_config: Config, _userApi?: UserApi, _systemApi?: SystemApi) { this.config = _config this.token = this.config.bot.jellfin_token this.authHeader = { headers: { "X-Emby-Authorization": this.config.bot.workaround_token } } const userApiConfigurationParams: ConfigurationParameters = { basePath: this.config.bot.jellyfin_url, headers: this.authHeader.headers } const systemApiConfigurationParams: ConfigurationParameters = { basePath: this.config.bot.jellyfin_url, headers: this.authHeader.headers } this.userApi = _userApi ?? new UserApi(new Configuration(userApiConfigurationParams)) this.systemApi = _systemApi ?? new SystemApi(new Configuration(systemApiConfigurationParams)) logger.info(`Initialized Jellyfin handler`, { requestId: 'Init' }) } private generateJFUserName(discordUser: GuildMember): string { return discordUser.displayName } public async addPermissionsToUserAccount(jfUserAccount: UserDto, guildId: string, requestId: string): Promise { throw new Error("Method not implemented."); } private generatePasswordForUser(): string { return (Math.random() * 10000 + 10000).toFixed(0) } public async createUserAccountForDiscordUser(discordUser: GuildMember, guildId?: string, requestId?: string): Promise { const newUserName = this.generateJFUserName(discordUser) logger.info(`New Username for ${discordUser.displayName}: ${newUserName}`, { guildId, requestId }) const req: CreateUserByNameOperationRequest = { createUserByNameRequest: { name: newUserName, password: this.generatePasswordForUser(), } } logger.debug(JSON.stringify(req)) const createResult = await this.userApi.createUserByName(req) if (createResult) { (await discordUser.createDM()).send(`Ich hab dir mal nen Account angelegt :)\nDein Username ist ${createResult.name}, dein Password ist "${req.createUserByNameRequest.password}"!`) return createResult } else throw new Error('Could not create User in Jellyfin') } public async isUserAlreadyPresent(discordUser: GuildMember, requestId?: string): Promise { const jfuser = await this.getUser(discordUser, requestId) logger.debug(`Presence for DiscordUser ${discordUser.id}:${jfuser !== undefined}`) return jfuser !== undefined } public async getCurrentUsers(guildId: string, requestId?: string): Promise { try { logger.info(`Fetching current users from Jellyfin`, { requestId, guildId }) const result = await this.userApi.getUsers(undefined, this.authHeader) return result } catch (error) { logger.error(`Could not fetch current users from jellyfin`, { guildId, requestId }) } return [] } public async getUser(discordUser: GuildMember, requestId?: string): Promise> { logger.info(`Getting user for discord member ${discordUser.displayName}`, {requestId}) const jfUsernameFromDiscordUsername = this.generateJFUserName(discordUser) const jfUsers = await this.getCurrentUsers(discordUser.guild.id, requestId) const foundUser = jfUsers.find(x => x.name === jfUsernameFromDiscordUsername) return foundUser } public async removeUser(newMember: GuildMember, requestId?: string) { logger.error(`Trying to remove user ${newMember.displayName}, but method is not implemented`, {requestId}) const jfuser = await this.getUser(newMember, requestId) if (jfuser) { await this.disableUser(jfuser, newMember.guild.id, requestId) } } public async resetUserPasswort(member: GuildMember, requestId?: string) { logger.info(`Resetting password for user ${member.displayName}`, {requestId}) const jfUser = await this.getUser(member, requestId) if (jfUser && jfUser.id) { // const reset: UpdateUserPasswordRequest = { // resetPassword: true // } // const shit: UpdateUserPasswordOperationRequest = { // updateUserPasswordRequest: reset, // userId: jfUser.id // } // logger.info(JSON.stringify(jfUser.policy, null, 2)) // logger.info("Resetting password", {requestId}) // await this.userApi.updateUserPassword(shit); const password = this.generatePasswordForUser() const passwordRequest: UpdateUserPasswordRequest = { // resetPassword: true, currentPw: "", newPw: password } const passwordOperationRequest: UpdateUserPasswordOperationRequest = { updateUserPasswordRequest: passwordRequest, userId: jfUser.id } logger.info("Setting new password", {requestId}) await this.userApi.updateUserPassword(passwordOperationRequest); (await member.createDM()).send(`Hier ist dein neues Passwort: ${password}`) } else { (await member.createDM()).send("Ich konnte leider keinen User von dir auf Jellyfin finden. Bitte melde dich bei Markus oder Samantha!") } } public async disableUser(user: UserDto, guildId?: string, requestId?: string): Promise { if (user.id) { const jfUser = await this.getUser({ displayName: user.name, guild: { id: guildId } }, requestId) logger.info(`Trying to disable user: ${user.name}|${user.id}|${JSON.stringify(jfUser, null, 2)}`) const r: UpdateUserPolicyOperationRequest = { userId: user.id ?? "", updateUserPolicyRequest: { ...jfUser?.policy, isDisabled: true, } } await this.userApi.updateUserPolicy(r) logger.info(`Succeeded with disabling user: ${user.name}`) } else { logger.error(`Can not disable user ${JSON.stringify(user)}, has no id?!`, { requestId, guildId }) } } public async enableUser(user: UserDto, guildId: string, requestId?: string): Promise { if (user.id) { const jfUser = await this.getUser({ displayName: user.name, guild: { id: guildId } }, requestId) logger.info(`Trying to enable user: ${user.name}|${user.id}|${JSON.stringify(jfUser, null, 2)}`) const r: UpdateUserPolicyOperationRequest = { userId: user.id ?? "", updateUserPolicyRequest: { ...jfUser?.policy, isDisabled: false, } } await this.userApi.updateUserPolicy(r) logger.info(`Succeeded with enabling user: ${user.name}`) } else { logger.error(`Can not enable user ${JSON.stringify(user)}, has no id?!`, { requestId, guildId }) } } public async upsertUser(newMember: GuildMember, level: string, requestId?: string) { logger.error(`Trying to upsert user ${newMember.displayName}, with permissionLevel ${level}`) const jfuser = await this.getUser(newMember, requestId) if (jfuser) { logger.info(`User with name ${newMember.displayName} is already present`) await this.enableUser(jfuser, newMember.guild.id, requestId) } else { this.createUserAccountForDiscordUser(newMember, newMember.guild.id, requestId) } } }