-
-
Notifications
You must be signed in to change notification settings - Fork 94
/
util.ts
209 lines (192 loc) · 6.69 KB
/
util.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import { URL } from "url";
import { DisTubeError, DisTubeVoice, Queue } from ".";
import { Constants, GatewayIntentBits, IntentsBitField, SnowflakeUtil } from "discord.js";
import type { GuildIdResolvable } from ".";
import type {
Client,
ClientOptions,
Guild,
GuildMember,
GuildTextBasedChannel,
Message,
Snowflake,
VoiceBasedChannel,
VoiceState,
} from "discord.js";
const formatInt = (int: number) => (int < 10 ? `0${int}` : int);
/**
* Format duration to string
*
* @param sec - Duration in seconds
*/
export function formatDuration(sec: number): string {
if (!sec || !Number(sec)) return "00:00";
const seconds = Math.floor(sec % 60);
const minutes = Math.floor((sec % 3600) / 60);
const hours = Math.floor(sec / 3600);
if (hours > 0) return `${formatInt(hours)}:${formatInt(minutes)}:${formatInt(seconds)}`;
if (minutes > 0) return `${formatInt(minutes)}:${formatInt(seconds)}`;
return `00:${formatInt(seconds)}`;
}
/**
* Convert formatted duration to seconds
*
* @param input - Formatted duration string
*/
export function toSecond(input: any): number {
if (!input) return 0;
if (typeof input !== "string") return Number(input) || 0;
if (input.includes(":")) {
const time = input.split(":").reverse();
let seconds = 0;
for (let i = 0; i < 3; i++) if (time[i]) seconds += Number(time[i].replace(/[^\d.]+/g, "")) * Math.pow(60, i);
if (time.length > 3) seconds += Number(time[3].replace(/[^\d.]+/g, "")) * 24 * 60 * 60;
return seconds;
} else {
return Number(input.replace(/[^\d.]+/g, "")) || 0;
}
}
/**
* Parse number from input
*
* @param input - Any
*/
export function parseNumber(input: any): number {
if (typeof input === "string") return Number(input.replace(/[^\d.]+/g, "")) || 0;
return Number(input) || 0;
}
const SUPPORTED_PROTOCOL = ["https:", "http:", "file:"] as const;
/**
* Check if the string is an URL
*
* @param input - input
*/
export function isURL(input: any): input is `${(typeof SUPPORTED_PROTOCOL)[number]}//${string}` {
if (typeof input !== "string" || input.includes(" ")) return false;
try {
const url = new URL(input);
if (!SUPPORTED_PROTOCOL.some(p => p === url.protocol)) return false;
} catch {
return false;
}
return true;
}
/**
* Check if the Client has enough intents to using DisTube
*
* @param options - options
*/
export function checkIntents(options: ClientOptions): void {
const intents = new IntentsBitField(options.intents);
if (!intents.has(GatewayIntentBits.GuildVoiceStates)) throw new DisTubeError("MISSING_INTENTS", "GuildVoiceStates");
}
/**
* Check if the voice channel is empty
*
* @param voiceState - voiceState
*/
export function isVoiceChannelEmpty(voiceState: VoiceState): boolean {
const guild = voiceState.guild;
const clientId = voiceState.client.user?.id;
if (!guild || !clientId) return false;
const voiceChannel = guild.members.me?.voice?.channel;
if (!voiceChannel) return false;
const members = voiceChannel.members.filter(m => !m.user.bot);
return !members.size;
}
export function isSnowflake(id: any): id is Snowflake {
try {
return SnowflakeUtil.deconstruct(id).timestamp > SnowflakeUtil.epoch;
} catch {
return false;
}
}
export function isMemberInstance(member: any): member is GuildMember {
return (
Boolean(member) &&
isSnowflake(member.id) &&
isSnowflake(member.guild?.id) &&
isSnowflake(member.user?.id) &&
member.id === member.user.id
);
}
export function isTextChannelInstance(channel: any): channel is GuildTextBasedChannel {
return (
Boolean(channel) &&
isSnowflake(channel.id) &&
isSnowflake(channel.guildId || channel.guild?.id) &&
Constants.TextBasedChannelTypes.includes(channel.type) &&
typeof channel.send === "function" &&
(typeof channel.nsfw === "boolean" || typeof channel.parent?.nsfw === "boolean")
);
}
export function isMessageInstance(message: any): message is Message<true> {
// Simple check for using distube normally
return (
Boolean(message) &&
isSnowflake(message.id) &&
isSnowflake(message.guildId || message.guild?.id) &&
isMemberInstance(message.member) &&
isTextChannelInstance(message.channel) &&
Constants.NonSystemMessageTypes.includes(message.type) &&
message.member.id === message.author?.id
);
}
export function isSupportedVoiceChannel(channel: any): channel is VoiceBasedChannel {
return (
Boolean(channel) &&
isSnowflake(channel.id) &&
isSnowflake(channel.guildId || channel.guild?.id) &&
Constants.VoiceBasedChannelTypes.includes(channel.type)
);
}
export function isGuildInstance(guild: any): guild is Guild {
return Boolean(guild) && isSnowflake(guild.id) && isSnowflake(guild.ownerId) && typeof guild.name === "string";
}
export function resolveGuildId(resolvable: GuildIdResolvable): Snowflake {
let guildId: string | undefined;
if (typeof resolvable === "string") {
guildId = resolvable;
} else if (isObject(resolvable)) {
if ("guildId" in resolvable && resolvable.guildId) {
guildId = resolvable.guildId;
} else if (resolvable instanceof Queue || resolvable instanceof DisTubeVoice || isGuildInstance(resolvable)) {
guildId = resolvable.id;
} else if ("guild" in resolvable && isGuildInstance(resolvable.guild)) {
guildId = resolvable.guild.id;
}
}
if (!isSnowflake(guildId)) throw new DisTubeError("INVALID_TYPE", "GuildIdResolvable", resolvable);
return guildId;
}
export function isClientInstance(client: any): client is Client {
return Boolean(client) && typeof client.login === "function";
}
export function checkInvalidKey(
target: Record<string, any>,
source: Record<string, any> | string[],
sourceName: string,
) {
if (!isObject(target)) throw new DisTubeError("INVALID_TYPE", "object", target, sourceName);
const sourceKeys = Array.isArray(source) ? source : objectKeys(source);
const invalidKey = objectKeys(target).find(key => !sourceKeys.includes(key));
if (invalidKey) throw new DisTubeError("INVALID_KEY", sourceName, invalidKey);
}
export function isObject(obj: any): obj is object {
return typeof obj === "object" && obj !== null && !Array.isArray(obj);
}
export function isRecord<T = unknown>(obj: any): obj is Record<string, T> {
return isObject(obj);
}
type KeyOf<T> = T extends object ? (keyof T)[] : [];
export function objectKeys<T>(obj: T): KeyOf<T> {
if (!isObject(obj)) return [] as KeyOf<T>;
return Object.keys(obj) as KeyOf<T>;
}
export function isNsfwChannel(channel?: GuildTextBasedChannel): boolean {
if (!isTextChannelInstance(channel)) return false;
if (channel.isThread()) return channel.parent?.nsfw ?? false;
return channel.nsfw;
}
type Falsy = undefined | null | false | 0 | "";
export const isTruthy = <T>(x: T | Falsy): x is T => Boolean(x);