firefish/packages/backend/src/misc/id/aid.ts

26 lines
651 B
TypeScript
Raw Normal View History

2019-04-13 18:08:26 +02:00
// AID
// 長さ8の[2000年1月1日からの経過ミリ秒をbase36でエンコードしたもの] + 長さ2の[ノイズ文字列]
2023-01-13 05:40:33 +01:00
import * as crypto from "node:crypto";
2019-04-13 18:08:26 +02:00
const TIME2000 = 946684800000;
2020-01-26 21:37:53 +01:00
let counter = crypto.randomBytes(2).readUInt16LE(0);
2019-04-13 18:08:26 +02:00
function getTime(time: number) {
time = time - TIME2000;
if (time < 0) time = 0;
2023-01-13 05:40:33 +01:00
return time.toString(36).padStart(8, "0");
2019-04-13 18:08:26 +02:00
}
2019-04-13 19:36:00 +02:00
function getNoise() {
2023-01-13 05:40:33 +01:00
return counter.toString(36).padStart(2, "0").slice(-2);
2019-04-13 18:08:26 +02:00
}
export function genAid(date: Date): string {
2020-04-26 04:54:51 +02:00
const t = date.getTime();
2023-01-13 05:40:33 +01:00
if (isNaN(t)) throw "Failed to create AID: Invalid Date";
2019-04-13 18:08:26 +02:00
counter++;
2020-04-26 04:54:51 +02:00
return getTime(t) + getNoise();
2019-04-13 18:08:26 +02:00
}