Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Advanced settings for backup load #310

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions src/clear.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* Delete all roles of the guild
*/
export async function clearRoles(guild: Guild) {
guild.roles.cache
.filter((role) => !role.managed && role.editable && role.id !== guild.id)
.forEach((role) => {
role.delete().catch(() => {});
});
return;
}
/**
* Delete all channels of the guild
*/
export async function clearChannels(guild: Guild) {
guild.channels.cache.forEach((channel) => {
channel.delete().catch(() => {});
});
return;
}
/**
* Delete all emojis of the guild
*/
export async function clearEmojis(guild: Guild) {
guild.emojis.cache.forEach((emoji) => {
emoji.delete().catch(() => {});
});
return;
}
/**
* Delete all webhooks of the guild
*/
export async function clearWebhooks(guild: Guild) {
const webhooks = await guild.fetchWebhooks();
webhooks.forEach((webhook) => {
webhook.delete().catch(() => {});
});
return;
}
/**
* Delete all bans of the guild
*/
export async function clearBans(guild: Guild) {
const bans = await guild.bans.fetch();
bans.forEach((ban) => {
guild.members.unban(ban.user).catch(() => {});
});
return;
}
/**
* Delete all configuration of a guild
*/
export async function clearConfig(guild: Guild) {
guild.setAFKChannel(null);
guild.setAFKTimeout(60 * 5);
guild.setIcon(null);
guild.setBanner(null).catch(() => {});
guild.setSplash(null).catch(() => {});
guild.setDefaultMessageNotifications('ONLY_MENTIONS');
guild.setWidgetSettings({
enabled: false,
channel: null
});
if (!guild.features.includes('COMMUNITY')) {
guild.setExplicitContentFilter('DISABLED');
guild.setVerificationLevel('NONE');
}
guild.setSystemChannel(null);
guild.setSystemChannelFlags(['SUPPRESS_GUILD_REMINDER_NOTIFICATIONS', 'SUPPRESS_JOIN_NOTIFICATIONS', 'SUPPRESS_PREMIUM_SUBSCRIPTIONS']);
return;
}
79 changes: 55 additions & 24 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { writeFile, readdir } from 'fs/promises';

import * as createMaster from './create';
import * as loadMaster from './load';
import * as clearMaster from './clear';
import * as utilMaster from './util';

let backups = `${__dirname}/backups`;
Expand All @@ -20,11 +21,11 @@ if (!existsSync(backups)) {
/**
* Checks if a backup exists and returns its data
*/
const getBackupData = async (backupID: string) => {
const getBackupData = async (backupId: string) => {
return new Promise<BackupData>(async (resolve, reject) => {
const files = await readdir(backups); // Read "backups" directory
// Try to get the json file
const file = files.filter((f) => f.split('.').pop() === 'json').find((f) => f === `${backupID}.json`);
const file = files.filter((f) => f.split('.').pop() === 'json').find((f) => f === `${backupId}.json`);
if (file) {
// If the file exists
const backupData: BackupData = require(`${backups}${sep}${file}`);
Expand All @@ -40,14 +41,14 @@ const getBackupData = async (backupID: string) => {
/**
* Fetches a backyp and returns the information about it
*/
export const fetch = (backupID: string) => {
export const fetch = (backupId: string) => {
return new Promise<BackupInfos>(async (resolve, reject) => {
getBackupData(backupID)
getBackupData(backupId)
.then((backupData) => {
const size = statSync(`${backups}${sep}${backupID}.json`).size; // Gets the size of the file using fs
const size = statSync(`${backups}${sep}${backupId}.json`).size; // Gets the size of the file using fs
const backupInfos: BackupInfos = {
data: backupData,
id: backupID,
id: backupId,
size: Number((size / 1024).toFixed(2))
};
// Returns backup informations
Expand All @@ -65,7 +66,7 @@ export const fetch = (backupID: string) => {
export const create = async (
guild: Guild,
options: CreateOptions = {
backupID: null,
backupId: null,
maxMessagesPerChannel: 10,
jsonSave: true,
jsonBeautify: true,
Expand Down Expand Up @@ -94,8 +95,8 @@ export const create = async (
bans: [],
emojis: [],
createdTimestamp: Date.now(),
guildID: guild.id,
id: options.backupID ?? SnowflakeUtil.generate(Date.now())
guildId: guild.id,
id: options.backupId ?? SnowflakeUtil.generate(Date.now())
};
if (guild.iconURL()) {
if (options && options.saveImages && options.saveImages === 'base64') {
Expand Down Expand Up @@ -160,7 +161,8 @@ export const load = async (
backup: string | BackupData,
guild: Guild,
options: LoadOptions = {
clearGuildBeforeRestore: true,
doNotClear: [],
doNotRestore: [],
maxMessagesPerChannel: 10
}
) => {
Expand All @@ -171,23 +173,52 @@ export const load = async (
try {
const backupData: BackupData = typeof backup === 'string' ? await getBackupData(backup) : backup;
try {
if (options.clearGuildBeforeRestore === undefined || options.clearGuildBeforeRestore) {
// Clear the guild
await utilMaster.clearGuild(guild);
if (!options || !(options.doNotClear || []).includes('roles')) {
// Clear guild roles
await clearMaster.clearRoles(guild);
}
if (!options || !(options.doNotClear || []).includes('channels')) {
// Clear guild channels
await clearMaster.clearChannels(guild);
}
if (!options || !(options.doNotClear || []).includes('emojis')) {
// Clear guild emojis
await clearMaster.clearEmojis(guild);
}
if (!options || !(options.doNotClear || []).includes('bans')) {
// Clear guild bans
await clearMaster.clearBans(guild);
}

await Promise.all([
// Clear guild configuration
clearMaster.clearConfig(guild),
// Clear guild webhooks
clearMaster.clearWebhooks(guild)
]);

if (!options || !(options.doNotRestore || []).includes('roles')) {
// Restore guild roles
await loadMaster.loadRoles(guild, backupData);
}
if (!options || !(options.doNotRestore || []).includes('channels')) {
// Restore guild channels
await loadMaster.loadChannels(guild, backupData);
}
if (!options || !(options.doNotRestore || []).includes('emojis')) {
// Restore guild emojis
await loadMaster.loadEmojis(guild, backupData);
}
if (!options || !(options.doNotRestore || []).includes('bans')) {
// Restore guild bans
await loadMaster.loadBans(guild, backupData);
}

await Promise.all([
// Restore guild configuration
loadMaster.loadConfig(guild, backupData),
// Restore guild roles
loadMaster.loadRoles(guild, backupData),
// Restore guild channels
loadMaster.loadChannels(guild, backupData, options),
// Restore afk channel and timeout
loadMaster.loadAFK(guild, backupData),
// Restore guild emojis
loadMaster.loadEmojis(guild, backupData),
// Restore guild bans
loadMaster.loadBans(guild, backupData),
// Restore embed channel
loadMaster.loadEmbedChannel(guild, backupData)
]);
Expand All @@ -205,11 +236,11 @@ export const load = async (
/**
* Removes a backup
*/
export const remove = async (backupID: string) => {
export const remove = async (backupId: string) => {
return new Promise<void>((resolve, reject) => {
try {
require(`${backups}${sep}${backupID}.json`);
unlinkSync(`${backups}${sep}${backupID}.json`);
require(`${backups}${sep}${backupId}.json`);
unlinkSync(`${backups}${sep}${backupId}.json`);
resolve();
} catch (error) {
reject('Backup not found');
Expand Down
2 changes: 1 addition & 1 deletion src/types/BackupData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ export interface BackupData {
bans: BanData[];
emojis: EmojiData[];
createdTimestamp: number;
guildID: string;
guildId: string;
id: Snowflake;
}
2 changes: 1 addition & 1 deletion src/types/CreateOptions.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export interface CreateOptions {
backupID?: string;
backupId?: string;
maxMessagesPerChannel?: number;
jsonSave?: boolean;
jsonBeautify?: boolean;
Expand Down
42 changes: 0 additions & 42 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,45 +299,3 @@ export async function loadChannel(
});
});
}

/**
* Delete all roles, all channels, all emojis, etc... of a guild
*/
export async function clearGuild(guild: Guild) {
guild.roles.cache
.filter((role) => !role.managed && role.editable && role.id !== guild.id)
.forEach((role) => {
role.delete().catch(() => {});
});
guild.channels.cache.forEach((channel) => {
channel.delete().catch(() => {});
});
guild.emojis.cache.forEach((emoji) => {
emoji.delete().catch(() => {});
});
const webhooks = await guild.fetchWebhooks();
webhooks.forEach((webhook) => {
webhook.delete().catch(() => {});
});
const bans = await guild.bans.fetch();
bans.forEach((ban) => {
guild.members.unban(ban.user).catch(() => {});
});
guild.setAFKChannel(null);
guild.setAFKTimeout(60 * 5);
guild.setIcon(null);
guild.setBanner(null).catch(() => {});
guild.setSplash(null).catch(() => {});
guild.setDefaultMessageNotifications('ONLY_MENTIONS');
guild.setWidgetSettings({
enabled: false,
channel: null
});
if (!guild.features.includes('COMMUNITY')) {
guild.setExplicitContentFilter('DISABLED');
guild.setVerificationLevel('NONE');
}
guild.setSystemChannel(null);
guild.setSystemChannelFlags(['SUPPRESS_GUILD_REMINDER_NOTIFICATIONS', 'SUPPRESS_JOIN_NOTIFICATIONS', 'SUPPRESS_PREMIUM_SUBSCRIPTIONS']);
return;
}