2022-09-17 18:27:08 +00:00
|
|
|
import { Inject, Injectable } from '@nestjs/common';
|
2022-09-20 20:33:11 +00:00
|
|
|
import type { InstancesRepository } from '@/models/index.js';
|
2022-09-17 18:27:08 +00:00
|
|
|
import type { Instance } from '@/models/entities/Instance.js';
|
|
|
|
import { Cache } from '@/misc/cache.js';
|
|
|
|
import { IdService } from '@/core/IdService.js';
|
|
|
|
import { DI } from '@/di-symbols.js';
|
|
|
|
import { UtilityService } from './UtilityService.js';
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class FederatedInstanceService {
|
2022-09-18 18:11:50 +00:00
|
|
|
private cache: Cache<Instance>;
|
2022-09-17 18:27:08 +00:00
|
|
|
|
|
|
|
constructor(
|
|
|
|
@Inject(DI.instancesRepository)
|
|
|
|
private instancesRepository: InstancesRepository,
|
|
|
|
|
|
|
|
private utilityService: UtilityService,
|
|
|
|
private idService: IdService,
|
|
|
|
) {
|
2022-09-18 18:11:50 +00:00
|
|
|
this.cache = new Cache<Instance>(1000 * 60 * 60);
|
2022-09-17 18:27:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public async registerOrFetchInstanceDoc(host: string): Promise<Instance> {
|
|
|
|
host = this.utilityService.toPuny(host);
|
|
|
|
|
2022-09-18 18:11:50 +00:00
|
|
|
const cached = this.cache.get(host);
|
2022-09-17 18:27:08 +00:00
|
|
|
if (cached) return cached;
|
|
|
|
|
|
|
|
const index = await this.instancesRepository.findOneBy({ host });
|
|
|
|
|
|
|
|
if (index == null) {
|
|
|
|
const i = await this.instancesRepository.insert({
|
|
|
|
id: this.idService.genId(),
|
|
|
|
host,
|
|
|
|
caughtAt: new Date(),
|
|
|
|
lastCommunicatedAt: new Date(),
|
|
|
|
}).then(x => this.instancesRepository.findOneByOrFail(x.identifiers[0]));
|
|
|
|
|
2022-09-18 18:11:50 +00:00
|
|
|
this.cache.set(host, i);
|
2022-09-17 18:27:08 +00:00
|
|
|
return i;
|
|
|
|
} else {
|
2022-09-18 18:11:50 +00:00
|
|
|
this.cache.set(host, index);
|
2022-09-17 18:27:08 +00:00
|
|
|
return index;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|