Sharkey/packages/backend/src/core/UtilityService.ts

50 lines
1.3 KiB
TypeScript
Raw Normal View History

2022-09-17 21:27:08 +03:00
import { URL } from 'node:url';
import { toASCII } from 'punycode';
import { Inject, Injectable } from '@nestjs/common';
import { DI } from '@/di-symbols.js';
2022-09-20 23:33:11 +03:00
import type { Config } from '@/config.js';
import { bindThis } from '@/decorators.js';
2022-09-17 21:27:08 +03:00
@Injectable()
export class UtilityService {
constructor(
@Inject(DI.config)
private config: Config,
) {
}
@bindThis
2022-09-17 21:27:08 +03:00
public getFullApAccount(username: string, host: string | null): string {
return host ? `${username}@${this.toPuny(host)}` : `${username}@${this.toPuny(this.config.host)}`;
}
@bindThis
2022-09-17 21:27:08 +03:00
public isSelfHost(host: string | null): boolean {
if (host == null) return true;
return this.toPuny(this.config.host) === this.toPuny(host);
}
@bindThis
public isBlockedHost(blockedHosts: string[], host: string | null): boolean {
if (host == null) return false;
return blockedHosts.some(x => `.${host.toLowerCase()}`.endsWith(`.${x}`));
}
@bindThis
2022-09-17 21:27:08 +03:00
public extractDbHost(uri: string): string {
const url = new URL(uri);
return this.toPuny(url.hostname);
}
@bindThis
2022-09-17 21:27:08 +03:00
public toPuny(host: string): string {
return toASCII(host.toLowerCase());
}
@bindThis
2022-09-17 21:27:08 +03:00
public toPunyNullable(host: string | null | undefined): string | null {
if (host == null) return null;
return toASCII(host.toLowerCase());
}
}