format more files
All checks were successful
Compile the repository / compile (pull_request) Successful in 1m12s

This commit is contained in:
2023-06-24 21:09:56 +02:00
parent d82a7cffd2
commit 66f843b399
25 changed files with 1418 additions and 1418 deletions

View File

@ -9,275 +9,275 @@ import { Configuration, ConfigurationParameters } from "./runtime";
export class JellyfinHandler {
private userApi: UserApi
private systemApi: SystemApi
private moviesApi: ItemsApi
private token: string
private authHeader: { headers: { 'X-Emby-Authorization': string } }
private config: JellyfinConfig
private serverName = "";
private userApi: UserApi
private systemApi: SystemApi
private moviesApi: ItemsApi
private token: string
private authHeader: { headers: { 'X-Emby-Authorization': string } }
private config: JellyfinConfig
private serverName = "";
constructor(_config: JellyfinConfig, _userApi?: UserApi, _systemApi?: SystemApi, _itemsApi?: ItemsApi) {
this.config = _config
this.token = this.config.jellyfinToken
this.authHeader = {
headers: {
"X-Emby-Authorization": this.config.jellyfinToken
}
}
const userApiConfigurationParams: ConfigurationParameters = {
basePath: this.config.jellyfinUrl,
headers: this.authHeader.headers
}
const systemApiConfigurationParams: ConfigurationParameters = {
basePath: this.config.jellyfinUrl,
headers: this.authHeader.headers
}
const libraryApiConfigurationParams: ConfigurationParameters = {
basePath: this.config.jellyfinUrl,
headers: this.authHeader.headers
}
constructor(_config: JellyfinConfig, _userApi?: UserApi, _systemApi?: SystemApi, _itemsApi?: ItemsApi) {
this.config = _config
this.token = this.config.jellyfinToken
this.authHeader = {
headers: {
"X-Emby-Authorization": this.config.jellyfinToken
}
}
const userApiConfigurationParams: ConfigurationParameters = {
basePath: this.config.jellyfinUrl,
headers: this.authHeader.headers
}
const systemApiConfigurationParams: ConfigurationParameters = {
basePath: this.config.jellyfinUrl,
headers: this.authHeader.headers
}
const libraryApiConfigurationParams: ConfigurationParameters = {
basePath: this.config.jellyfinUrl,
headers: this.authHeader.headers
}
this.userApi = _userApi ?? new UserApi(new Configuration(userApiConfigurationParams))
this.systemApi = _systemApi ?? new SystemApi(new Configuration(systemApiConfigurationParams))
this.moviesApi = _itemsApi ?? new ItemsApi(new Configuration(libraryApiConfigurationParams))
logger.info(`Initialized Jellyfin handler`, { requestId: 'Init' })
}
this.userApi = _userApi ?? new UserApi(new Configuration(userApiConfigurationParams))
this.systemApi = _systemApi ?? new SystemApi(new Configuration(systemApiConfigurationParams))
this.moviesApi = _itemsApi ?? new ItemsApi(new Configuration(libraryApiConfigurationParams))
logger.info(`Initialized Jellyfin handler`, { requestId: 'Init' })
}
private generateJFUserName(discordUser: GuildMember, level: PermissionLevel): string {
return `${discordUser.displayName}${level == "TEMPORARY" ? "_tmp" : ""}`
}
private generateJFUserName(discordUser: GuildMember, level: PermissionLevel): string {
return `${discordUser.displayName}${level == "TEMPORARY" ? "_tmp" : ""}`
}
private generatePasswordForUser(): string {
return (Math.random() * 10000 + 10000).toFixed(0)
}
private generatePasswordForUser(): string {
return (Math.random() * 10000 + 10000).toFixed(0)
}
public async createUserAccountForDiscordUser(discordUser: GuildMember, level: PermissionLevel, requestId: string, guildId?: string): Promise<UserDto> {
const newUserName = this.generateJFUserName(discordUser, level)
logger.info(`New Username for ${discordUser.displayName}: ${newUserName}`, { guildId, requestId })
const req: CreateUserByNameOperationRequest = {
createUserByNameRequest: {
name: newUserName,
password: this.generatePasswordForUser()
}
}
logger.debug(JSON.stringify(req), { requestId, guildId })
const createResult = await this.userApi.createUserByName(req)
if (createResult) {
if (createResult.policy) {
this.setUserPermissions(createResult, requestId, guildId)
}
(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 createUserAccountForDiscordUser(discordUser: GuildMember, level: PermissionLevel, requestId: string, guildId?: string): Promise<UserDto> {
const newUserName = this.generateJFUserName(discordUser, level)
logger.info(`New Username for ${discordUser.displayName}: ${newUserName}`, { guildId, requestId })
const req: CreateUserByNameOperationRequest = {
createUserByNameRequest: {
name: newUserName,
password: this.generatePasswordForUser()
}
}
logger.debug(JSON.stringify(req), { requestId, guildId })
const createResult = await this.userApi.createUserByName(req)
if (createResult) {
if (createResult.policy) {
this.setUserPermissions(createResult, requestId, guildId)
}
(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 setUserPermissions(user: UserDto, requestId: string, guildId?: string) {
if (!user.policy || !user.id) {
logger.error(`Cannot update user policy. User ${user.name} has no policy to modify`, { guildId, requestId })
return
}
user.policy.enableVideoPlaybackTranscoding = false
public async setUserPermissions(user: UserDto, requestId: string, guildId?: string) {
if (!user.policy || !user.id) {
logger.error(`Cannot update user policy. User ${user.name} has no policy to modify`, { guildId, requestId })
return
}
user.policy.enableVideoPlaybackTranscoding = false
const operation: UpdateUserPolicyRequest = {
...user.policy,
enableVideoPlaybackTranscoding: false
}
const operation: UpdateUserPolicyRequest = {
...user.policy,
enableVideoPlaybackTranscoding: false
}
const request: UpdateUserPolicyOperationRequest = {
userId: user.id,
updateUserPolicyRequest: operation
}
this.userApi.updateUserPolicy(request)
}
const request: UpdateUserPolicyOperationRequest = {
userId: user.id,
updateUserPolicyRequest: operation
}
this.userApi.updateUserPolicy(request)
}
public async isUserAlreadyPresent(discordUser: GuildMember, requestId?: string): Promise<boolean> {
const jfuser = await this.getUser(discordUser, requestId)
logger.debug(`Presence for DiscordUser ${discordUser.id}:${jfuser !== undefined}`, { guildId: discordUser.guild.id, requestId })
return jfuser !== undefined
}
public async isUserAlreadyPresent(discordUser: GuildMember, requestId?: string): Promise<boolean> {
const jfuser = await this.getUser(discordUser, requestId)
logger.debug(`Presence for DiscordUser ${discordUser.id}:${jfuser !== undefined}`, { guildId: discordUser.guild.id, requestId })
return jfuser !== undefined
}
public async getCurrentUsers(guildId: string, requestId?: string): Promise<UserDto[]> {
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 getCurrentUsers(guildId: string, requestId?: string): Promise<UserDto[]> {
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<Maybe<UserDto>> {
logger.info(`Getting user for discord member ${discordUser.displayName}`, { requestId, guildId: discordUser.guild.id })
const jfUsers = await this.getCurrentUsers(discordUser.guild.id, requestId)
const foundUser = jfUsers.find(x => x.name?.includes(discordUser.displayName))
return foundUser
}
public async getUser(discordUser: GuildMember, requestId?: string): Promise<Maybe<UserDto>> {
logger.info(`Getting user for discord member ${discordUser.displayName}`, { requestId, guildId: discordUser.guild.id })
const jfUsers = await this.getCurrentUsers(discordUser.guild.id, requestId)
const foundUser = jfUsers.find(x => x.name?.includes(discordUser.displayName))
return foundUser
}
public async removeUser(newMember: GuildMember, level: PermissionLevel, requestId?: string) {
logger.info(`${level == "TEMPORARY" ? "Deleting" : "Disabling"} user ${newMember.displayName}, but method is not implemented`, { requestId, guildId: newMember.guild.id })
const jfuser = await this.getUser(newMember, requestId)
if (jfuser && jfuser.id) {
if (level === "TEMPORARY") {
const r: DeleteUserRequest = {
userId: jfuser.id
}
this.userApi.deleteUser(r)
}
else
await this.disableUser(jfuser, newMember.guild.id, requestId)
}
}
public async removeUser(newMember: GuildMember, level: PermissionLevel, requestId?: string) {
logger.info(`${level == "TEMPORARY" ? "Deleting" : "Disabling"} user ${newMember.displayName}, but method is not implemented`, { requestId, guildId: newMember.guild.id })
const jfuser = await this.getUser(newMember, requestId)
if (jfuser && jfuser.id) {
if (level === "TEMPORARY") {
const r: DeleteUserRequest = {
userId: jfuser.id
}
this.userApi.deleteUser(r)
}
else
await this.disableUser(jfuser, newMember.guild.id, requestId)
}
}
public async purge(guildId: string, requestId?: string) {
logger.info("Deleting tmp users", { requestId, guildId })
const users = (await this.userApi.getUsers()).filter(user => user.name?.endsWith("_tmp"))
public async purge(guildId: string, requestId?: string) {
logger.info("Deleting tmp users", { requestId, guildId })
const users = (await this.userApi.getUsers()).filter(user => user.name?.endsWith("_tmp"))
users.forEach(user => {
if (user.id) {
const r: DeleteUserRequest = {
userId: user.id
}
this.userApi.deleteUser(r)
}
})
}
users.forEach(user => {
if (user.id) {
const r: DeleteUserRequest = {
userId: user.id
}
this.userApi.deleteUser(r)
}
})
}
public async resetUserPasswort(member: GuildMember, requestId?: string) {
logger.info(`Resetting password for user ${member.displayName}`, { requestId, guildId: member.guild.id })
const jfUser = await this.getUser(member, requestId)
if (jfUser && jfUser.id) {
public async resetUserPasswort(member: GuildMember, requestId?: string) {
logger.info(`Resetting password for user ${member.displayName}`, { requestId, guildId: member.guild.id })
const jfUser = await this.getUser(member, requestId)
if (jfUser && jfUser.id) {
// const reset: UpdateUserPasswordRequest = {
// resetPassword: true
// }
// const reset: UpdateUserPasswordRequest = {
// resetPassword: true
// }
// const shit: UpdateUserPasswordOperationRequest = {
// updateUserPasswordRequest: reset,
// userId: jfUser.id
// }
// const shit: UpdateUserPasswordOperationRequest = {
// updateUserPasswordRequest: reset,
// userId: jfUser.id
// }
// logger.info(JSON.stringify(jfUser.policy, null, 2))
// logger.info(JSON.stringify(jfUser.policy, null, 2))
// logger.info("Resetting password", {requestId})
// await this.userApi.updateUserPassword(shit);
// logger.info("Resetting password", {requestId})
// await this.userApi.updateUserPassword(shit);
const password = this.generatePasswordForUser()
const passwordRequest: UpdateUserPasswordRequest = {
// resetPassword: true,
currentPw: "",
newPw: password
}
const password = this.generatePasswordForUser()
const passwordRequest: UpdateUserPasswordRequest = {
// resetPassword: true,
currentPw: "",
newPw: password
}
const passwordOperationRequest: UpdateUserPasswordOperationRequest = {
updateUserPasswordRequest: passwordRequest,
userId: jfUser.id
}
const passwordOperationRequest: UpdateUserPasswordOperationRequest = {
updateUserPasswordRequest: passwordRequest,
userId: jfUser.id
}
logger.info("Setting new password", { requestId, guildId: member.guild.id })
await this.userApi.updateUserPassword(passwordOperationRequest);
logger.info("Setting new password", { requestId, guildId: member.guild.id })
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!")
}
(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<void> {
if (user.id) {
const jfUser = await this.getUser(<GuildMember>{ displayName: user.name, guild: { id: guildId } }, requestId)
logger.info(`Trying to disable user: ${user.name}|${user.id}|${JSON.stringify(jfUser, null, 2)}`, { guildId, requestId })
const r: UpdateUserPolicyOperationRequest = {
userId: user.id ?? "",
updateUserPolicyRequest: {
...jfUser?.policy,
isDisabled: true,
}
}
await this.userApi.updateUserPolicy(r)
logger.info(`Succeeded with disabling user: ${user.name}`, { guildId, requestId })
}
else {
logger.error(`Can not disable user ${JSON.stringify(user)}, has no id?!`, { requestId, guildId })
}
}
public async disableUser(user: UserDto, guildId?: string, requestId?: string): Promise<void> {
if (user.id) {
const jfUser = await this.getUser(<GuildMember>{ displayName: user.name, guild: { id: guildId } }, requestId)
logger.info(`Trying to disable user: ${user.name}|${user.id}|${JSON.stringify(jfUser, null, 2)}`, { guildId, requestId })
const r: UpdateUserPolicyOperationRequest = {
userId: user.id ?? "",
updateUserPolicyRequest: {
...jfUser?.policy,
isDisabled: true,
}
}
await this.userApi.updateUserPolicy(r)
logger.info(`Succeeded with disabling user: ${user.name}`, { guildId, requestId })
}
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<void> {
if (user.id) {
const jfUser = await this.getUser(<GuildMember>{ displayName: user.name, guild: { id: guildId } }, requestId)
logger.info(`Trying to enable user: ${user.name}|${user.id}|${JSON.stringify(jfUser, null, 2)}`, { guildId, requestId })
const r: UpdateUserPolicyOperationRequest = {
userId: user.id ?? "",
updateUserPolicyRequest: {
...jfUser?.policy,
isDisabled: false,
}
}
await this.userApi.updateUserPolicy(r)
logger.info(`Succeeded with enabling user: ${user.name}`, { guildId, requestId })
}
else {
logger.error(`Can not enable user ${JSON.stringify(user)}, has no id?!`, { requestId, guildId })
}
}
public async enableUser(user: UserDto, guildId: string, requestId?: string): Promise<void> {
if (user.id) {
const jfUser = await this.getUser(<GuildMember>{ displayName: user.name, guild: { id: guildId } }, requestId)
logger.info(`Trying to enable user: ${user.name}|${user.id}|${JSON.stringify(jfUser, null, 2)}`, { guildId, requestId })
const r: UpdateUserPolicyOperationRequest = {
userId: user.id ?? "",
updateUserPolicyRequest: {
...jfUser?.policy,
isDisabled: false,
}
}
await this.userApi.updateUserPolicy(r)
logger.info(`Succeeded with enabling user: ${user.name}`, { guildId, requestId })
}
else {
logger.error(`Can not enable user ${JSON.stringify(user)}, has no id?!`, { requestId, guildId })
}
}
public async upsertUser(newMember: GuildMember, level: PermissionLevel, requestId?: string): Promise<UserUpsertResult> {
logger.info(`Trying to upsert user ${newMember.displayName}, with permissionLevel ${level}`, { guildId: newMember.guild.id, requestId })
const jfuser = await this.getUser(newMember, requestId)
if (jfuser && !jfuser.policy?.isDisabled) {
logger.info(`User with name ${newMember.displayName} is already present`, { guildId: newMember.guild.id, requestId })
await this.enableUser(jfuser, newMember.guild.id, requestId)
return UserUpsertResult.enabled
} else {
this.createUserAccountForDiscordUser(newMember, level, newMember.guild.id, requestId)
return UserUpsertResult.created
}
}
public async upsertUser(newMember: GuildMember, level: PermissionLevel, requestId?: string): Promise<UserUpsertResult> {
logger.info(`Trying to upsert user ${newMember.displayName}, with permissionLevel ${level}`, { guildId: newMember.guild.id, requestId })
const jfuser = await this.getUser(newMember, requestId)
if (jfuser && !jfuser.policy?.isDisabled) {
logger.info(`User with name ${newMember.displayName} is already present`, { guildId: newMember.guild.id, requestId })
await this.enableUser(jfuser, newMember.guild.id, requestId)
return UserUpsertResult.enabled
} else {
this.createUserAccountForDiscordUser(newMember, level, newMember.guild.id, requestId)
return UserUpsertResult.created
}
}
public async getAllMovies(guildId: string, requestId: string): Promise<BaseItemDto[]> {
logger.info("requesting all movies from jellyfin", { guildId, requestId })
public async getAllMovies(guildId: string, requestId: string): Promise<BaseItemDto[]> {
logger.info("requesting all movies from jellyfin", { guildId, requestId })
const searchParams: GetItemsRequest = {
userId: this.config.collectionUser,
parentId: this.config.movieCollectionId // collection ID for all movies
}
const movies = (await (this.moviesApi.getItems(searchParams))).items?.filter(item => !item.isFolder)
// logger.debug(JSON.stringify(movies, null, 2), { guildId: guildId, requestId })
logger.info(`Found ${movies?.length} movies in total`, { guildId, requestId })
return movies ?? []
}
const searchParams: GetItemsRequest = {
userId: this.config.collectionUser,
parentId: this.config.movieCollectionId // collection ID for all movies
}
const movies = (await (this.moviesApi.getItems(searchParams))).items?.filter(item => !item.isFolder)
// logger.debug(JSON.stringify(movies, null, 2), { guildId: guildId, requestId })
logger.info(`Found ${movies?.length} movies in total`, { guildId, requestId })
return movies ?? []
}
public async getRandomMovies(count: number, guildId: string, requestId: string): Promise<BaseItemDto[]> {
logger.info(`${count} random movies requested.`, { guildId, requestId })
const allMovies = await this.getAllMovies(guildId, requestId)
if (count >= allMovies.length) {
logger.info(`${count} random movies requested but found only ${allMovies.length}. Returning all Movies.`, { guildId, requestId })
return allMovies
}
const movies: BaseItemDto[] = []
for (let i = 0; i < count; i++) {
const index = Math.floor(Math.random() * allMovies.length)
movies.push(...allMovies.splice(index, 1)) // maybe out of bounds? ?
}
return movies
}
public async getRandomMovies(count: number, guildId: string, requestId: string): Promise<BaseItemDto[]> {
logger.info(`${count} random movies requested.`, { guildId, requestId })
const allMovies = await this.getAllMovies(guildId, requestId)
if (count >= allMovies.length) {
logger.info(`${count} random movies requested but found only ${allMovies.length}. Returning all Movies.`, { guildId, requestId })
return allMovies
}
const movies: BaseItemDto[] = []
for (let i = 0; i < count; i++) {
const index = Math.floor(Math.random() * allMovies.length)
movies.push(...allMovies.splice(index, 1)) // maybe out of bounds? ?
}
return movies
}
public async getRandomMovieNames(count: number, guildId: string, requestId: string): Promise<string[]> {
logger.info(`${count} random movie names requested`, { guildId, requestId })
public async getRandomMovieNames(count: number, guildId: string, requestId: string): Promise<string[]> {
logger.info(`${count} random movie names requested`, { guildId, requestId })
let movieCount = 0
let movieNames: string[]
do {
movieNames = (await this.getRandomMovies(count, guildId, requestId)).filter(movie => movie.name && movie.name.length > 0).map(movie => <string>movie.name)
movieCount = movieNames.length
} while (movieCount < count)
return movieNames
}
let movieCount = 0
let movieNames: string[]
do {
movieNames = (await this.getRandomMovies(count, guildId, requestId)).filter(movie => movie.name && movie.name.length > 0).map(movie => <string>movie.name)
movieCount = movieNames.length
} while (movieCount < count)
return movieNames
}
}

View File

@ -16,72 +16,72 @@
export const BASE_PATH = "http://localhost".replace(/\/+$/, "");
export interface ConfigurationParameters {
basePath?: string; // override base path
fetchApi?: FetchAPI; // override for fetch implementation
middleware?: Middleware[]; // middleware to apply before/after fetch requests
queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings
username?: string; // parameter for basic security
password?: string; // parameter for basic security
apiKey?: string | ((name: string) => string); // parameter for apiKey security
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string | Promise<string>); // parameter for oauth2 security
headers?: HTTPHeaders; //header params we want to use on every request
credentials?: RequestCredentials; //value for the credentials param we want to use on each request
basePath?: string; // override base path
fetchApi?: FetchAPI; // override for fetch implementation
middleware?: Middleware[]; // middleware to apply before/after fetch requests
queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings
username?: string; // parameter for basic security
password?: string; // parameter for basic security
apiKey?: string | ((name: string) => string); // parameter for apiKey security
accessToken?: string | Promise<string> | ((name?: string, scopes?: string[]) => string | Promise<string>); // parameter for oauth2 security
headers?: HTTPHeaders; //header params we want to use on every request
credentials?: RequestCredentials; //value for the credentials param we want to use on each request
}
export class Configuration {
constructor(private configuration: ConfigurationParameters = {}) { }
constructor(private configuration: ConfigurationParameters = {}) { }
set config(configuration: Configuration) {
this.configuration = configuration;
}
set config(configuration: Configuration) {
this.configuration = configuration;
}
get basePath(): string {
return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
}
get basePath(): string {
return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
}
get fetchApi(): FetchAPI | undefined {
return this.configuration.fetchApi;
}
get fetchApi(): FetchAPI | undefined {
return this.configuration.fetchApi;
}
get middleware(): Middleware[] {
return this.configuration.middleware || [];
}
get middleware(): Middleware[] {
return this.configuration.middleware || [];
}
get queryParamsStringify(): (params: HTTPQuery) => string {
return this.configuration.queryParamsStringify || querystring;
}
get queryParamsStringify(): (params: HTTPQuery) => string {
return this.configuration.queryParamsStringify || querystring;
}
get username(): string | undefined {
return this.configuration.username;
}
get username(): string | undefined {
return this.configuration.username;
}
get password(): string | undefined {
return this.configuration.password;
}
get password(): string | undefined {
return this.configuration.password;
}
get apiKey(): ((name: string) => string) | undefined {
const apiKey = this.configuration.apiKey;
if (apiKey) {
return typeof apiKey === 'function' ? apiKey : () => apiKey;
}
return undefined;
}
get apiKey(): ((name: string) => string) | undefined {
const apiKey = this.configuration.apiKey;
if (apiKey) {
return typeof apiKey === 'function' ? apiKey : () => apiKey;
}
return undefined;
}
get accessToken(): ((name?: string, scopes?: string[]) => string | Promise<string>) | undefined {
const accessToken = this.configuration.accessToken;
if (accessToken) {
return typeof accessToken === 'function' ? accessToken : async () => accessToken;
}
return undefined;
}
get accessToken(): ((name?: string, scopes?: string[]) => string | Promise<string>) | undefined {
const accessToken = this.configuration.accessToken;
if (accessToken) {
return typeof accessToken === 'function' ? accessToken : async () => accessToken;
}
return undefined;
}
get headers(): HTTPHeaders | undefined {
return this.configuration.headers;
}
get headers(): HTTPHeaders | undefined {
return this.configuration.headers;
}
get credentials(): RequestCredentials | undefined {
return this.configuration.credentials;
}
get credentials(): RequestCredentials | undefined {
return this.configuration.credentials;
}
}
export const DefaultConfig = new Configuration();
@ -91,192 +91,192 @@ export const DefaultConfig = new Configuration();
*/
export class BaseAPI {
private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i');
private middleware: Middleware[];
private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i');
private middleware: Middleware[];
constructor(protected configuration = DefaultConfig) {
this.middleware = configuration.middleware;
}
constructor(protected configuration = DefaultConfig) {
this.middleware = configuration.middleware;
}
withMiddleware<T extends BaseAPI>(this: T, ...middlewares: Middleware[]) {
const next = this.clone<T>();
next.middleware = next.middleware.concat(...middlewares);
return next;
}
withMiddleware<T extends BaseAPI>(this: T, ...middlewares: Middleware[]) {
const next = this.clone<T>();
next.middleware = next.middleware.concat(...middlewares);
return next;
}
withPreMiddleware<T extends BaseAPI>(this: T, ...preMiddlewares: Array<Middleware['pre']>) {
const middlewares = preMiddlewares.map((pre) => ({ pre }));
return this.withMiddleware<T>(...middlewares);
}
withPreMiddleware<T extends BaseAPI>(this: T, ...preMiddlewares: Array<Middleware['pre']>) {
const middlewares = preMiddlewares.map((pre) => ({ pre }));
return this.withMiddleware<T>(...middlewares);
}
withPostMiddleware<T extends BaseAPI>(this: T, ...postMiddlewares: Array<Middleware['post']>) {
const middlewares = postMiddlewares.map((post) => ({ post }));
return this.withMiddleware<T>(...middlewares);
}
withPostMiddleware<T extends BaseAPI>(this: T, ...postMiddlewares: Array<Middleware['post']>) {
const middlewares = postMiddlewares.map((post) => ({ post }));
return this.withMiddleware<T>(...middlewares);
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
protected isJsonMime(mime: string | null | undefined): boolean {
if (!mime) {
return false;
}
return BaseAPI.jsonRegex.test(mime);
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
protected isJsonMime(mime: string | null | undefined): boolean {
if (!mime) {
return false;
}
return BaseAPI.jsonRegex.test(mime);
}
protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise<Response> {
const { url, init } = await this.createFetchParams(context, initOverrides);
const response = await this.fetchApi(url, init);
if (response && (response.status >= 200 && response.status < 300)) {
return response;
}
throw new ResponseError(response, 'Response returned an error code');
}
protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise<Response> {
const { url, init } = await this.createFetchParams(context, initOverrides);
const response = await this.fetchApi(url, init);
if (response && (response.status >= 200 && response.status < 300)) {
return response;
}
throw new ResponseError(response, 'Response returned an error code');
}
private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) {
let url = this.configuration.basePath + context.path;
if (context.query !== undefined && Object.keys(context.query).length !== 0) {
// only add the querystring to the URL if there are query parameters.
// this is done to avoid urls ending with a "?" character which buggy webservers
// do not handle correctly sometimes.
url += '?' + this.configuration.queryParamsStringify(context.query);
}
private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) {
let url = this.configuration.basePath + context.path;
if (context.query !== undefined && Object.keys(context.query).length !== 0) {
// only add the querystring to the URL if there are query parameters.
// this is done to avoid urls ending with a "?" character which buggy webservers
// do not handle correctly sometimes.
url += '?' + this.configuration.queryParamsStringify(context.query);
}
const headers = Object.assign({}, this.configuration.headers, context.headers);
Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {});
const headers = Object.assign({}, this.configuration.headers, context.headers);
Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {});
const initOverrideFn =
typeof initOverrides === "function"
? initOverrides
: async () => initOverrides;
const initOverrideFn =
typeof initOverrides === "function"
? initOverrides
: async () => initOverrides;
const initParams = {
method: context.method,
headers,
body: context.body,
credentials: this.configuration.credentials,
};
const initParams = {
method: context.method,
headers,
body: context.body,
credentials: this.configuration.credentials,
};
const overriddenInit: RequestInit = {
...initParams,
...(await initOverrideFn({
init: initParams,
context,
}))
};
const overriddenInit: RequestInit = {
...initParams,
...(await initOverrideFn({
init: initParams,
context,
}))
};
const init: RequestInit = {
...overriddenInit,
body:
isFormData(overriddenInit.body) ||
overriddenInit.body instanceof URLSearchParams ||
isBlob(overriddenInit.body)
? overriddenInit.body
: JSON.stringify(overriddenInit.body),
};
const init: RequestInit = {
...overriddenInit,
body:
isFormData(overriddenInit.body) ||
overriddenInit.body instanceof URLSearchParams ||
isBlob(overriddenInit.body)
? overriddenInit.body
: JSON.stringify(overriddenInit.body),
};
return { url, init };
}
return { url, init };
}
private fetchApi = async (url: string, init: RequestInit) => {
let fetchParams = { url, init };
for (const middleware of this.middleware) {
if (middleware.pre) {
fetchParams = await middleware.pre({
fetch: this.fetchApi,
...fetchParams,
}) || fetchParams;
}
}
let response: Response | undefined = undefined;
try {
response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init);
} catch (e) {
for (const middleware of this.middleware) {
if (middleware.onError) {
response = await middleware.onError({
fetch: this.fetchApi,
url: fetchParams.url,
init: fetchParams.init,
error: e,
response: response ? response.clone() : undefined,
}) || response;
}
}
if (response === undefined) {
if (e instanceof Error) {
throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response');
} else {
throw e;
}
}
}
for (const middleware of this.middleware) {
if (middleware.post) {
response = await middleware.post({
fetch: this.fetchApi,
url: fetchParams.url,
init: fetchParams.init,
response: response.clone(),
}) || response;
}
}
return response;
}
private fetchApi = async (url: string, init: RequestInit) => {
let fetchParams = { url, init };
for (const middleware of this.middleware) {
if (middleware.pre) {
fetchParams = await middleware.pre({
fetch: this.fetchApi,
...fetchParams,
}) || fetchParams;
}
}
let response: Response | undefined = undefined;
try {
response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init);
} catch (e) {
for (const middleware of this.middleware) {
if (middleware.onError) {
response = await middleware.onError({
fetch: this.fetchApi,
url: fetchParams.url,
init: fetchParams.init,
error: e,
response: response ? response.clone() : undefined,
}) || response;
}
}
if (response === undefined) {
if (e instanceof Error) {
throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response');
} else {
throw e;
}
}
}
for (const middleware of this.middleware) {
if (middleware.post) {
response = await middleware.post({
fetch: this.fetchApi,
url: fetchParams.url,
init: fetchParams.init,
response: response.clone(),
}) || response;
}
}
return response;
}
/**
* Create a shallow clone of `this` by constructing a new instance
* and then shallow cloning data members.
*/
private clone<T extends BaseAPI>(this: T): T {
const constructor = this.constructor as any;
const next = new constructor(this.configuration);
next.middleware = this.middleware.slice();
return next;
}
/**
* Create a shallow clone of `this` by constructing a new instance
* and then shallow cloning data members.
*/
private clone<T extends BaseAPI>(this: T): T {
const constructor = this.constructor as any;
const next = new constructor(this.configuration);
next.middleware = this.middleware.slice();
return next;
}
};
function isBlob(value: any): value is Blob {
return typeof Blob !== 'undefined' && value instanceof Blob;
return typeof Blob !== 'undefined' && value instanceof Blob;
}
function isFormData(value: any): value is FormData {
return typeof FormData !== "undefined" && value instanceof FormData;
return typeof FormData !== "undefined" && value instanceof FormData;
}
export class ResponseError extends Error {
override name: "ResponseError" = "ResponseError";
constructor(public response: Response, msg?: string) {
super(msg);
}
override name: "ResponseError" = "ResponseError";
constructor(public response: Response, msg?: string) {
super(msg);
}
}
export class FetchError extends Error {
override name: "FetchError" = "FetchError";
constructor(public cause: Error, msg?: string) {
super(msg);
}
override name: "FetchError" = "FetchError";
constructor(public cause: Error, msg?: string) {
super(msg);
}
}
export class RequiredError extends Error {
override name: "RequiredError" = "RequiredError";
constructor(public field: string, msg?: string) {
super(msg);
}
override name: "RequiredError" = "RequiredError";
constructor(public field: string, msg?: string) {
super(msg);
}
}
export const COLLECTION_FORMATS = {
csv: ",",
ssv: " ",
tsv: "\t",
pipes: "|",
csv: ",",
ssv: " ",
tsv: "\t",
pipes: "|",
};
export type FetchAPI = WindowOrWorkerGlobalScope['fetch'];
@ -292,134 +292,134 @@ export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'o
export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise<RequestInit>
export interface FetchParams {
url: string;
init: RequestInit;
url: string;
init: RequestInit;
}
export interface RequestOpts {
path: string;
method: HTTPMethod;
headers: HTTPHeaders;
query?: HTTPQuery;
body?: HTTPBody;
path: string;
method: HTTPMethod;
headers: HTTPHeaders;
query?: HTTPQuery;
body?: HTTPBody;
}
export function exists(json: any, key: string) {
const value = json[key];
return value !== null && value !== undefined;
const value = json[key];
return value !== null && value !== undefined;
}
export function querystring(params: HTTPQuery, prefix: string = ''): string {
return Object.keys(params)
.map(key => querystringSingleKey(key, params[key], prefix))
.filter(part => part.length > 0)
.join('&');
return Object.keys(params)
.map(key => querystringSingleKey(key, params[key], prefix))
.filter(part => part.length > 0)
.join('&');
}
function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery, keyPrefix: string = ''): string {
const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
if (value instanceof Array) {
const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue)))
.join(`&${encodeURIComponent(fullKey)}=`);
return `${encodeURIComponent(fullKey)}=${multiValue}`;
}
if (value instanceof Set) {
const valueAsArray = Array.from(value);
return querystringSingleKey(key, valueAsArray, keyPrefix);
}
if (value instanceof Date) {
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
}
if (value instanceof Object) {
return querystring(value as HTTPQuery, fullKey);
}
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
if (value instanceof Array) {
const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue)))
.join(`&${encodeURIComponent(fullKey)}=`);
return `${encodeURIComponent(fullKey)}=${multiValue}`;
}
if (value instanceof Set) {
const valueAsArray = Array.from(value);
return querystringSingleKey(key, valueAsArray, keyPrefix);
}
if (value instanceof Date) {
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
}
if (value instanceof Object) {
return querystring(value as HTTPQuery, fullKey);
}
return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
}
export function mapValues(data: any, fn: (item: any) => any) {
return Object.keys(data).reduce(
(acc, key) => ({ ...acc, [key]: fn(data[key]) }),
{}
);
return Object.keys(data).reduce(
(acc, key) => ({ ...acc, [key]: fn(data[key]) }),
{}
);
}
export function canConsumeForm(consumes: Consume[]): boolean {
for (const consume of consumes) {
if ('multipart/form-data' === consume.contentType) {
return true;
}
}
return false;
for (const consume of consumes) {
if ('multipart/form-data' === consume.contentType) {
return true;
}
}
return false;
}
export interface Consume {
contentType: string;
contentType: string;
}
export interface RequestContext {
fetch: FetchAPI;
url: string;
init: RequestInit;
fetch: FetchAPI;
url: string;
init: RequestInit;
}
export interface ResponseContext {
fetch: FetchAPI;
url: string;
init: RequestInit;
response: Response;
fetch: FetchAPI;
url: string;
init: RequestInit;
response: Response;
}
export interface ErrorContext {
fetch: FetchAPI;
url: string;
init: RequestInit;
error: unknown;
response?: Response;
fetch: FetchAPI;
url: string;
init: RequestInit;
error: unknown;
response?: Response;
}
export interface Middleware {
pre?(context: RequestContext): Promise<FetchParams | void>;
post?(context: ResponseContext): Promise<Response | void>;
onError?(context: ErrorContext): Promise<Response | void>;
pre?(context: RequestContext): Promise<FetchParams | void>;
post?(context: ResponseContext): Promise<Response | void>;
onError?(context: ErrorContext): Promise<Response | void>;
}
export interface ApiResponse<T> {
raw: Response;
value(): Promise<T>;
raw: Response;
value(): Promise<T>;
}
export interface ResponseTransformer<T> {
(json: any): T;
(json: any): T;
}
export class JSONApiResponse<T> {
constructor(public raw: Response, private transformer: ResponseTransformer<T> = (jsonValue: any) => jsonValue) { }
constructor(public raw: Response, private transformer: ResponseTransformer<T> = (jsonValue: any) => jsonValue) { }
async value(): Promise<T> {
return this.transformer(await this.raw.json());
}
async value(): Promise<T> {
return this.transformer(await this.raw.json());
}
}
export class VoidApiResponse {
constructor(public raw: Response) { }
constructor(public raw: Response) { }
async value(): Promise<void> {
return undefined;
}
async value(): Promise<void> {
return undefined;
}
}
export class BlobApiResponse {
constructor(public raw: Response) { }
constructor(public raw: Response) { }
async value(): Promise<Blob> {
return await this.raw.blob();
};
async value(): Promise<Blob> {
return await this.raw.blob();
};
}
export class TextApiResponse {
constructor(public raw: Response) { }
constructor(public raw: Response) { }
async value(): Promise<string> {
return await this.raw.text();
};
async value(): Promise<string> {
return await this.raw.text();
};
}