summary refs log tree commit diff
path: root/src/api/util/utility/RandomInviteID.ts
blob: fa484bd52dbda60990e9668d7f89ef64c6547076 (plain) (blame)
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
import { Snowflake } from "@fosscord/util";
import crypto from "crypto";

// TODO: 'random'? seriously? who named this?
// And why is this even here? Just use cryto.randomBytes?

export function random(length = 6) {
	// Declare all characters
	let chars =
		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

	// Pick characers randomly
	let str = "";
	for (let i = 0; i < length; i++) {
		str += chars.charAt(Math.floor(crypto.randomInt(chars.length)));
	}

	return str;
}

export function snowflakeBasedInvite() {
	// Declare all characters
	let chars =
		"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	let base = BigInt(chars.length);
	let snowflake = Snowflake.generateWorkerProcess();

	// snowflakes hold ~10.75 characters worth of entropy;
	// safe to generate a 8-char invite out of them
	let str = "";
	for (let i = 0; i < 10; i++) {
		str.concat(chars.charAt(Number(snowflake % base)));
		snowflake = snowflake / base;
	}

	return str.substr(3, 8).split("").reverse().join("");
}