From 71fc84e22431e88a7bc881f05d0365730b63d731 Mon Sep 17 00:00:00 2001 From: mei23 Date: Mon, 22 Apr 2019 06:19:19 +0900 Subject: [PATCH] Use meid7 for Note --- src/misc/gen-id.ts | 12 ++++++++++++ src/misc/id/meid7.ts | 28 ++++++++++++++++++++++++++++ src/services/note/create.ts | 2 ++ 3 files changed, 42 insertions(+) create mode 100644 src/misc/gen-id.ts create mode 100644 src/misc/id/meid7.ts diff --git a/src/misc/gen-id.ts b/src/misc/gen-id.ts new file mode 100644 index 000000000..63e190471 --- /dev/null +++ b/src/misc/gen-id.ts @@ -0,0 +1,12 @@ +import { genMeid7 } from './id/meid7'; + +const method = 'meid7'; + +export function genId(date?: Date): string { + if (!date || (date > new Date())) date = new Date(); + + switch (method) { + case 'meid7': return genMeid7(date); + default: throw new Error('unknown id generation method'); + } +} diff --git a/src/misc/id/meid7.ts b/src/misc/id/meid7.ts new file mode 100644 index 000000000..5b67fceb0 --- /dev/null +++ b/src/misc/id/meid7.ts @@ -0,0 +1,28 @@ +const CHARS = '0123456789abcdef'; + +// 4bit Fixed hex value '7' +// 44bit UNIX Time ms in Hex +// 48bit Random value in Hex + +function getTime(time: number) { + if (time < 0) time = 0; + if (time === 0) { + return CHARS[0]; + } + + return time.toString(16).padStart(11, CHARS[0]); +} + +function getRandom() { + let str = ''; + + for (let i = 0; i < 12; i++) { + str += CHARS[Math.floor(Math.random() * CHARS.length)]; + } + + return str; +} + +export function genMeid7(date: Date): string { + return '7' + getTime(date.getTime()) + getRandom(); +} diff --git a/src/services/note/create.ts b/src/services/note/create.ts index 85201086d..ebedb9dbe 100644 --- a/src/services/note/create.ts +++ b/src/services/note/create.ts @@ -34,6 +34,7 @@ import Instance from '../../models/instance'; import extractMentions from '../../misc/extract-mentions'; import extractEmojis from '../../misc/extract-emojis'; import extractHashtags from '../../misc/extract-hashtags'; +import { genId } from '../../misc/gen-id'; type NotificationType = 'reply' | 'renote' | 'quote' | 'mention'; @@ -434,6 +435,7 @@ async function publish(user: IUser, note: INote, noteObj: any, reply: INote, ren async function insertNote(user: IUser, data: Option, tags: string[], emojis: string[], mentionedUsers: IUser[]) { const insert: any = { + _id: genId(data.createdAt), createdAt: data.createdAt, fileIds: data.files ? data.files.map(file => file._id) : [], replyId: data.reply ? data.reply._id : null,