2019-05-25 21:25:34 +03:00
|
|
|
import { BaseGuildRepository } from "./BaseGuildRepository";
|
2020-06-02 00:26:06 +03:00
|
|
|
import { getRepository, In, Repository } from "typeorm";
|
2019-05-03 23:31:38 +03:00
|
|
|
import { NicknameHistoryEntry } from "./entities/NicknameHistoryEntry";
|
2020-07-22 22:56:21 +03:00
|
|
|
import { MINUTES, SECONDS } from "../utils";
|
2020-06-02 00:26:06 +03:00
|
|
|
import { isAPI } from "../globals";
|
|
|
|
import { cleanupNicknames } from "./cleanup/nicknames";
|
|
|
|
|
|
|
|
if (!isAPI()) {
|
|
|
|
const CLEANUP_INTERVAL = 5 * MINUTES;
|
|
|
|
|
|
|
|
async function cleanup() {
|
|
|
|
await cleanupNicknames();
|
|
|
|
setTimeout(cleanup, CLEANUP_INTERVAL);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start first cleanup 30 seconds after startup
|
|
|
|
setTimeout(cleanup, 30 * SECONDS);
|
|
|
|
}
|
2019-05-03 23:31:38 +03:00
|
|
|
|
|
|
|
export const MAX_NICKNAME_ENTRIES_PER_USER = 10;
|
|
|
|
|
2019-05-25 21:25:34 +03:00
|
|
|
export class GuildNicknameHistory extends BaseGuildRepository {
|
2019-05-03 23:31:38 +03:00
|
|
|
private nicknameHistory: Repository<NicknameHistoryEntry>;
|
|
|
|
|
|
|
|
constructor(guildId) {
|
|
|
|
super(guildId);
|
|
|
|
this.nicknameHistory = getRepository(NicknameHistoryEntry);
|
|
|
|
}
|
|
|
|
|
|
|
|
async getByUserId(userId): Promise<NicknameHistoryEntry[]> {
|
|
|
|
return this.nicknameHistory.find({
|
|
|
|
where: {
|
|
|
|
guild_id: this.guildId,
|
|
|
|
user_id: userId,
|
|
|
|
},
|
|
|
|
order: {
|
|
|
|
id: "DESC",
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
getLastEntry(userId): Promise<NicknameHistoryEntry> {
|
|
|
|
return this.nicknameHistory.findOne({
|
|
|
|
where: {
|
|
|
|
guild_id: this.guildId,
|
|
|
|
user_id: userId,
|
|
|
|
},
|
|
|
|
order: {
|
|
|
|
id: "DESC",
|
|
|
|
},
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async addEntry(userId, nickname) {
|
|
|
|
await this.nicknameHistory.insert({
|
|
|
|
guild_id: this.guildId,
|
|
|
|
user_id: userId,
|
|
|
|
nickname,
|
|
|
|
});
|
|
|
|
|
2020-06-02 00:26:06 +03:00
|
|
|
// Cleanup (leave only the last MAX_USERNAME_ENTRIES_PER_USER entries)
|
|
|
|
const toDelete = await this.nicknameHistory
|
|
|
|
.createQueryBuilder()
|
|
|
|
.where("guild_id = :guildId", { guildId: this.guildId })
|
|
|
|
.andWhere("user_id = :userId", { userId })
|
|
|
|
.orderBy("id", "DESC")
|
2020-07-29 01:58:28 +02:00
|
|
|
.skip(MAX_NICKNAME_ENTRIES_PER_USER)
|
2020-06-02 00:26:06 +03:00
|
|
|
.take(99_999)
|
|
|
|
.getMany();
|
2019-05-03 23:31:38 +03:00
|
|
|
|
2020-06-02 00:26:06 +03:00
|
|
|
if (toDelete.length > 0) {
|
|
|
|
await this.nicknameHistory.delete({
|
|
|
|
id: In(toDelete.map(v => v.id)),
|
|
|
|
});
|
2019-05-03 23:31:38 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|