tweak aid-converter

This commit is contained in:
kakkokari-gtyih 2024-01-21 12:12:51 +09:00
parent 5f5848a5c9
commit 351e12702a
3 changed files with 17 additions and 15 deletions

View File

@ -5,9 +5,6 @@
// AID
// 長さ8の[2000年1月1日からの経過ミリ秒をbase36でエンコードしたもの] + 長さ2の[ノイズ文字列]
import * as crypto from 'crypto';
export const aidRegExp = /^[0-9a-z]{10}$/;
const TIME2000 = 946684800000;
@ -17,6 +14,7 @@ if (process.client) {
const arr = window.crypto.getRandomValues(new Uint16Array(2));
counter = parseInt(arr[0].toString());
} else {
const crypto = require('crypto');
counter = crypto.randomBytes(2).readUInt16LE(0);
}
@ -27,14 +25,16 @@ function getTime(time: number): string {
return time.toString(36).padStart(8, '0');
}
function getNoise(): string {
return counter.toString(36).padStart(2, '0').slice(-2);
function getNoise(ctr: number): string {
return ctr.toString(36).padStart(2, '0').slice(-2);
}
export function genAid(t: number): string {
export function genAid(t: number, ctr: number | null = null): string {
if (isNaN(t)) throw new Error('Failed to create AID: Invalid Date');
counter++;
return getTime(t) + getNoise();
if (!ctr) {
counter++;
}
return getTime(t) + getNoise(ctr ?? counter);
}
export function parseAid(id: string): { date: Date; } {

View File

@ -27,14 +27,16 @@ function getTime(time: number): string {
return time.toString(36).padStart(TIME_LENGTH, '0').slice(-TIME_LENGTH);
}
function getNoise(): string {
function getNoise(ctr: number): string {
return counter.toString(36).padStart(NOISE_LENGTH, '0').slice(-NOISE_LENGTH);
}
export function genAidx(t: number): string {
export function genAidx(t: number, ctr: number | null = null): string {
if (isNaN(t)) throw new Error('Failed to create AIDX: Invalid Date');
counter++;
return getTime(t) + nodeId + getNoise();
if (!ctr) {
counter++;
}
return getTime(t) + nodeId + getNoise(ctr ?? counter);
}
export function parseAidx(id: string): { date: Date; } {

View File

@ -51,7 +51,7 @@ const aidToDateResult = ref<string>('');
function doAidToDate() {
const time = parseInt(aidToDateAid.value.slice(0, 8), 36) + TIME2000;
const d = new Date(time);
aidToDateResult.value = d.toLocaleString();
aidToDateResult.value = `${d.getFullYear().toString().padStart(4, '0')}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}.${d.getMilliseconds().toString().padStart(3, '0')}`;
}
const dateToAidDate = ref<string>('');
@ -60,9 +60,9 @@ const dateToAidResult = ref<string>('');
function doDateToAid() {
const d = new Date(dateToAidDate.value);
if (dateToAidMode.value === 'aid') {
dateToAidResult.value = genAid(d.getTime());
dateToAidResult.value = genAid(d.getTime(), 0);
} else if (dateToAidMode.value === 'aidx') {
dateToAidResult.value = genAidx(d.getTime());
dateToAidResult.value = genAidx(d.getTime(), 0);
}
}