Unify chat timestamps format (#4806) * Unify chat timestamps format * Handle ISO timestamps in stats.js * Refactor timestamp parsing on server * Switch to ISO timestamps for character/messages creation dates * Fix type error * Early exist in saveGroupChat if group not found * Remove redundant fields from temp.chat export header * Auto-fix char creation date format on edit * Add name to fallback chat file names * Rename parseTimestamp server side function
Signed| @@ -1028,9 +1028,6 @@ function verifyCharactersSearchSortRule() { | ||
| 1028 | 1028 | } |
| 1029 | 1029 | } |
| 1030 | 1030 | |
| 1031 | -/** @typedef {object} Character - A character */ | |
| 1032 | -/** @typedef {object} Group - A group */ | |
| 1033 | - | |
| 1034 | 1031 | /** |
| 1035 | 1032 | * @typedef {object} Entity - Object representing a display entity |
| 1036 | 1033 | * @property {Character|Group|import('./scripts/tags.js').Tag|*} item - The item |
| @@ -8248,7 +8245,7 @@ export function select_selected_character(chid, { switchMenu = true } = {}) { | ||
| 8248 | 8245 | $('#talkativeness_slider').val(characters[chid].talkativeness || talkativeness_default); |
| 8249 | 8246 | $('#mes_example_textarea').val(characters[chid].mes_example); |
| 8250 | 8247 | $('#selected_chat_pole').val(characters[chid].chat); |
| 8251 | 8248 | $('#create_date_pole').val(timestampToMoment(characters[chid].create_date).toISOString()); |
| 8252 | 8249 | $('#avatar_url_pole').val(characters[chid].avatar); |
| 8253 | 8250 | $('#chat_import_avatar_url').val(characters[chid].avatar); |
| 8254 | 8251 | $('#chat_import_character_name').val(characters[chid].name); |
| @@ -162,43 +162,37 @@ export function shouldSendOnEnter() { | ||
| 162 | 162 | } |
| 163 | 163 | } |
| 164 | 164 | |
| 165 | -//RossAscends: Added function to format dates used in files and chat timestamps to a humanized format. | |
| 165 | +/** | |
| 166 | -//Mostly I wanted this to be for file names, but couldn't figure out exactly where the filename save code was as everything seemed to be connected. | |
| 166 | + * Gets a humanized date time string from a given timestamp. | |
| 167 | -//Does not break old characters/chats, as the code just uses whatever timestamp exists in the chat. | |
| 167 | + * @param {number} timestamp Timestamp in milliseconds | |
| 168 | -//New chats made with characters will use this new formatting. | |
| 168 | + * @returns {string} Humanized date time string in the format `YYYY-MM-DD@HHhMMmSSsMSms` | |
| 169 | -export function humanizedDateTime() { | |
| 169 | + */ | |
| 170 | 170 | constexport nowfunction =humanizedDateTime(timestamp new= Date(Date.now()); { |
| 171 | + const date = new Date(timestamp); | |
| 171 | 172 | const dt = { |
| 172 | - year: now.getFullYear(), month: now.getMonth() + 1, day: now.getDate(), | |
| 173 | + year: date.getFullYear(), | |
| 173 | - hour: now.getHours(), minute: now.getMinutes(), second: now.getSeconds(), | |
| 174 | + month: date.getMonth() + 1, | |
| 175 | + day: date.getDate(), | |
| 176 | + hour: date.getHours(), | |
| 177 | + minute: date.getMinutes(), | |
| 178 | + second: date.getSeconds(), | |
| 179 | + millisecond: date.getMilliseconds(), | |
| 174 | 180 | }; |
| 175 | 181 | for (const key in dt) { |
| 176 | - dt[key] = dt[key].toString().padStart(2, '0'); | |
| 182 | + const padLength = key === 'millisecond' ? 3 : 2; | |
| 183 | + dt[key] = dt[key].toString().padStart(padLength, '0'); | |
| 177 | 184 | } |
| 178 | 185 | return `${dt.year}-${dt.month}-${dt.day}@${dt.hour}h${dt.minute}m${dt.second}s${dt.millisecond}ms`; |
| 179 | 186 | } |
| 180 | 187 | |
| 181 | -//this is a common format version to display a timestamp on each chat message | |
| 188 | +/** | |
| 182 | -//returns something like: June 19, 2023 2:20pm | |
| 189 | + * Gets a timestamp for messages in ISO 8601 format. | |
| 183 | -export function getMessageTimeStamp() { | |
| 190 | + * @param {number} timestamp - optional timestamp in milliseconds | |
| 184 | - const date = Date.now(); | |
| 191 | + * @returns {string} ISO 8601 formatted timestamp | |
| 185 | - const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; | |
| 192 | + */ | |
| 186 | - const d = new Date(date); | |
| 193 | +export function getMessageTimeStamp(timestamp = Date.now()) { | |
| 187 | 194 | const monthdate = months[d.getMonthnew Date(timestamp)]; |
| 188 | 195 | const day =return ddate.getDatetoISOString(); |
| 189 | - const year = d.getFullYear(); | |
| 190 | - let hours = d.getHours(); | |
| 191 | - const minutes = ('0' + d.getMinutes()).slice(-2); | |
| 192 | - let meridiem = 'am'; | |
| 193 | - if (hours >= 12) { | |
| 194 | - meridiem = 'pm'; | |
| 195 | - hours -= 12; | |
| 196 | - } | |
| 197 | - if (hours === 0) { | |
| 198 | - hours = 12; | |
| 199 | - } | |
| 200 | - const formattedDate = month + ' ' + day + ', ' + year + ' ' + hours + ':' + minutes + meridiem; | |
| 201 | - return formattedDate; | |
| 202 | 196 | } |
| 203 | 197 | |
| 204 | 198 | |
| @@ -10,7 +10,6 @@ import { | ||
| 10 | 10 | event_types, |
| 11 | 11 | getCurrentChatId, |
| 12 | 12 | getRequestHeaders, |
| 13 | - name1, | |
| 14 | 13 | name2, |
| 15 | 14 | reloadCurrentChat, |
| 16 | 15 | saveSettingsDebounced, |
| @@ -2140,13 +2139,9 @@ export function initChatUtilities() { | ||
| 2140 | 2139 | await viewMessageFile(messageId, fileIndex); |
| 2141 | 2140 | }); |
| 2142 | 2141 | |
| 2143 | 2142 | $(document).on('click', '.assistant_note_export', async function (_e) { |
| 2144 | 2143 | const chatToSave = [ |
| 2145 | - { | |
| 2144 | + { chat_metadata: chat_metadata }, | |
| 2146 | - user_name: name1, | |
| 2147 | - character_name: name2, | |
| 2148 | - chat_metadata: chat_metadata, | |
| 2149 | - }, | |
| 2150 | 2145 | ...chat.filter(x => x?.extra?.type !== system_message_types.ASSISTANT_NOTE), |
| 2151 | 2146 | ]; |
| 2152 | 2147 | |
| @@ -2865,7 +2865,7 @@ function getCharacterAvatarUrl() { | ||
| 2865 | 2865 | if (context.groupId) { |
| 2866 | 2866 | const groupMembers = context.groups.find(x => x.id === context.groupId)?.members; |
| 2867 | 2867 | const lastMessageAvatar = context.chat?.filter(x => !x.is_system && !x.is_user)?.slice(-1)[0]?.original_avatar; |
| 2868 | 2868 | const randomMemberAvatar = Array.isArray(groupMembers) ? groupMembers[Math.floor(Math.random() * groupMembers.length)]?.avatar : null; |
| 2869 | 2869 | const avatarToUse = lastMessageAvatar || randomMemberAvatar; |
| 2870 | 2870 | return formatCharacterAvatar(avatarToUse); |
| 2871 | 2871 | } else { |
| @@ -324,7 +324,7 @@ export async function getGroupChat(groupId, reload = false) { | ||
| 324 | 324 | * Retrieves the members of a group |
| 325 | 325 | * |
| 326 | 326 | * @param {string} [groupId=selected_group] - The ID of the group to retrieve members from. Defaults to the currently selected group. |
| 327 | 327 | * @returns {import('../script.js').Character[]} An array of character objects representing the members of the group. If the group is not found, an empty array is returned. |
| 328 | 328 | */ |
| 329 | 329 | export function getGroupMembers(groupId = selected_group) { |
| 330 | 330 | const group = groups.find((x) => x.id === groupId); |
| @@ -617,7 +617,11 @@ function resetSelectedGroup() { | ||
| 617 | 617 | */ |
| 618 | 618 | async function saveGroupChat(groupId, shouldSaveGroup, force = false) { |
| 619 | 619 | const group = groups.find(x => x.id == groupId); |
| 620 | - const chat_id = group.chat_id; | |
| 620 | + if (!group) { | |
| 621 | + console.warn('Group not found', groupId); | |
| 622 | + return; | |
| 623 | + } | |
| 624 | + const chatId = group.chat_id; | |
| 621 | 625 | group['date_last_chat'] = Date.now(); |
| 622 | 626 | /** @type {ChatHeader} */ |
| 623 | 627 | const chatHeader = { |
| @@ -626,7 +630,7 @@ async function saveGroupChat(groupId, shouldSaveGroup, force = false) { | ||
| 626 | 630 | const response = await fetch('/api/chats/group/save', { |
| 627 | 631 | method: 'POST', |
| 628 | 632 | headers: getRequestHeaders(), |
| 629 | 633 | body: JSON.stringify({ id: chat_idchatId, chat: [chatHeader, ...chat], force: force }), |
| 630 | 634 | }); |
| 631 | 635 | |
| 632 | 636 | if (!response.ok) { |
| @@ -1105,6 +1105,8 @@ function parseTimestamp(timestamp) { | ||
| 1105 | 1105 | ms = typeof ms !== 'undefined' ? `.${ms.padStart(3, '0')}` : ''; |
| 1106 | 1106 | return `${year.padStart(4, '0')}-${month.padStart(2, '0')}-${day.padStart(2, '0')}T${hour.padStart(2, '0')}:${min.padStart(2, '0')}:${sec.padStart(2, '0')}${ms}Z`; |
| 1107 | 1107 | }; |
| 1108 | + // 2024-07-12@01h31m37s123ms | |
| 1109 | + dtFmt.push({ callback: convertFromHumanized, pattern: /(\d{4})-(\d{1,2})-(\d{1,2})@(\d{1,2})h(\d{1,2})m(\d{1,2})s(\d{1,3})ms/ }); | |
| 1108 | 1110 | // 2024-7-12@01h31m37s |
| 1109 | 1111 | dtFmt.push({ callback: convertFromHumanized, pattern: /(\d{4})-(\d{1,2})-(\d{1,2})@(\d{1,2})h(\d{1,2})m(\d{1,2})s/ }); |
| 1110 | 1112 | // 2024-6-5 @14h 56m 50s 682ms |
| @@ -2,7 +2,7 @@ import { promises as fsPromises } from 'node:fs'; | ||
| 2 | 2 | import path from 'node:path'; |
| 3 | 3 | import urlJoin from 'url-join'; |
| 4 | 4 | import { DEFAULT_AVATAR_PATH } from './constants.js'; |
| 5 | 5 | import { extractFileFromZipBuffer, humanizedISO8601DateTime } from './util.js'; |
| 6 | 6 | |
| 7 | 7 | /** |
| 8 | 8 | * A parser for BYAF (Backyard Archive Format) files. |
| @@ -267,7 +267,7 @@ export class ByafParser { | ||
| 267 | 267 | extensions: { ...(character?.displayName && { 'display_name': character?.displayName }) }, // Preserve display name unmodified using extensions. "display_name" is not used by SillyTavern currently. |
| 268 | 268 | }, |
| 269 | 269 | // @ts-ignore Non-standard spec extension |
| 270 | 270 | create_date: humanizedISO8601DateTimenew Date().toISOString(), |
| 271 | 271 | }; |
| 272 | 272 | } |
| 273 | 273 | /** |
| @@ -330,13 +330,10 @@ export class ByafParser { | ||
| 330 | 330 | * @returns {string} Chat data |
| 331 | 331 | */ |
| 332 | 332 | static getChatFromScenario(scenario, userName, characterName, chatBackgrounds) { |
| 333 | 333 | const chatStartDate = scenario?.messages?.length == 0 ? humanizedISO8601DateTimenew Date().toISOString() : scenario?.messages?.filter(m => 'createdAt' in m)[0].createdAt; |
| 334 | 334 | const chatBackground = chatBackgrounds.find(bg => bg.paths.includes(scenario?.backgroundImage || ''))?.name || ''; |
| 335 | 335 | /** @type {object[]} */ |
| 336 | 336 | const chat = [{ |
| 337 | - user_name: userName, | |
| 338 | - character_name: characterName, | |
| 339 | - create_date: chatStartDate, | |
| 340 | 337 | chat_metadata: { |
| 341 | 338 | scenario: scenario?.narrative ?? '', |
| 342 | 339 | mes_example: ByafParser.formatExampleMessages(scenario?.exampleMessages), |
| @@ -14,7 +14,7 @@ import storage from 'node-persist'; | ||
| 14 | 14 | |
| 15 | 15 | import { AVATAR_WIDTH, AVATAR_HEIGHT, DEFAULT_AVATAR_PATH } from '../constants.js'; |
| 16 | 16 | import { default as validateAvatarUrlMiddleware, getFileNameValidationFunction } from '../middleware/validateFileName.js'; |
| 17 | 17 | import { deepMerge, humanizedISO8601DateTimehumanizedDateTime, tryParse, extractFileFromZipBuffer, MemoryLimitedMap, getConfigValue, mutateJsonString, clientRelativePath, getUniqueName, sanitizeSafeCharacterReplacements } from '../util.js'; |
| 18 | 18 | import { TavernCardValidator } from '../validator/TavernCardValidator.js'; |
| 19 | 19 | import { parse, read, write } from '../character-card-parser.js'; |
| 20 | 20 | import { readWorldInfoFile } from './worldinfo.js'; |
| @@ -414,7 +414,7 @@ const processCharacter = async (item, directories, { shallow }) => { | ||
| 414 | 414 | character['json_data'] = imgData; |
| 415 | 415 | const charStat = fs.statSync(path.join(directories.characters, item)); |
| 416 | 416 | character['date_added'] = charStat.ctimeMs; |
| 417 | 417 | character['create_date'] = jsonObject['create_date'] || humanizedISO8601DateTimenew Date(Math.round(charStat.ctimeMs)).toISOString(); |
| 418 | 418 | const chatsDirectory = path.join(directories.chats, item.replace('.png', '')); |
| 419 | 419 | |
| 420 | 420 | const { chatSize, dateLastChat } = calculateChatSize(chatsDirectory); |
| @@ -452,7 +452,7 @@ function getCharaCardV2(jsonObject, directories, hoistDate = true) { | ||
| 452 | 452 | jsonObject = convertToV2(jsonObject, directories); |
| 453 | 453 | |
| 454 | 454 | if (hoistDate && !jsonObject.create_date) { |
| 455 | 455 | jsonObject.create_date = humanizedISO8601DateTimenew Date().toISOString(); |
| 456 | 456 | } |
| 457 | 457 | } else { |
| 458 | 458 | jsonObject = readFromV2(jsonObject); |
| @@ -486,7 +486,7 @@ function convertToV2(char, directories) { | ||
| 486 | 486 | depth_prompt_role: char.depth_prompt_role, |
| 487 | 487 | }, directories); |
| 488 | 488 | |
| 489 | 489 | result.chat = char.chat ?? humanizedISO8601DateTime`${char.name} - ${humanizedDateTime()}`; |
| 490 | 490 | result.create_date = char.create_date; |
| 491 | 491 | |
| 492 | 492 | return result; |
| @@ -551,7 +551,7 @@ function readFromV2(char) { | ||
| 551 | 551 | char[charField] = v2Value; |
| 552 | 552 | }); |
| 553 | 553 | |
| 554 | 554 | char['chat'] = char['chat'] ?? humanizedISO8601DateTime`${char.name} - ${humanizedDateTime()}`; |
| 555 | 555 | |
| 556 | 556 | return char; |
| 557 | 557 | } |
| @@ -587,7 +587,7 @@ function charaFormatData(data, directories) { | ||
| 587 | 587 | // Old ST extension fields (for backward compatibility, will be deprecated) |
| 588 | 588 | _.set(char, 'creatorcomment', data.creator_notes || ''); |
| 589 | 589 | _.set(char, 'avatar', 'none'); |
| 590 | 590 | _.set(char, 'chat', data.ch_name + ' - ' + humanizedISO8601DateTimehumanizedDateTime()); |
| 591 | 591 | _.set(char, 'talkativeness', data.talkativeness || 0.5); |
| 592 | 592 | _.set(char, 'fav', data.fav == 'true'); |
| 593 | 593 | _.set(char, 'tags', typeof data.tags == 'string' ? (data.tags.split(',').map(x => x.trim()).filter(x => x)) : data.tags || []); |
| @@ -624,9 +624,6 @@ function charaFormatData(data, directories) { | ||
| 624 | 624 | _.set(char, 'data.extensions.depth_prompt.prompt', data.depth_prompt_prompt ?? ''); |
| 625 | 625 | _.set(char, 'data.extensions.depth_prompt.depth', depth_value); |
| 626 | 626 | _.set(char, 'data.extensions.depth_prompt.role', role_value); |
| 627 | - //_.set(char, 'data.extensions.create_date', humanizedISO8601DateTime()); | |
| 628 | - //_.set(char, 'data.extensions.avatar', 'none'); | |
| 629 | - //_.set(char, 'data.extensions.chat', data.ch_name + ' - ' + humanizedISO8601DateTime()); | |
| 630 | 627 | |
| 631 | 628 | // V3 fields |
| 632 | 629 | _.set(char, 'data.group_only_greetings', data.group_only_greetings ?? []); |
| @@ -746,8 +743,8 @@ async function importFromYaml(uploadPath, context, preservedFileName) { | ||
| 746 | 743 | 'name': yamlData.name, |
| 747 | 744 | 'description': yamlData.context ?? '', |
| 748 | 745 | 'first_mes': yamlData.greeting ?? '', |
| 749 | 746 | 'create_date': humanizedISO8601DateTimenew Date().toISOString(), |
| 750 | 747 | 'chat': `${yamlData.name} - ${humanizedISO8601DateTimehumanizedDateTime()}`, |
| 751 | 748 | 'personality': '', |
| 752 | 749 | 'creatorcomment': '', |
| 753 | 750 | 'avatar': 'none', |
| @@ -800,7 +797,7 @@ async function importFromCharX(uploadPath, { request }, preservedFileName) { | ||
| 800 | 797 | } |
| 801 | 798 | |
| 802 | 799 | unsetPrivateFields(card); |
| 803 | 800 | card['create_date'] = humanizedISO8601DateTimenew Date().toISOString(); |
| 804 | 801 | card.name = sanitize(card.name); |
| 805 | 802 | const fileName = preservedFileName || getPngName(card.name, request.user.directories); |
| 806 | 803 | const result = await writeCharacterData(avatar, JSON.stringify(card), fileName, request); |
| @@ -822,7 +819,7 @@ async function importFromByaf(uploadPath, { request }, preservedFileName) { | ||
| 822 | 819 | * @param {Partial<ByafScenario>} scenario |
| 823 | 820 | */ |
| 824 | 821 | const createChatAsCurrentPersona = (scenario) => { |
| 825 | 822 | const chatName = sanitize(`${scenario.title || card.name} - ${humanizedISO8601DateTimehumanizedDateTime()} imported.jsonl`, { replacement: sanitizeSafeCharacterReplacements }); |
| 826 | 823 | const filePath = path.join(request.user.directories.chats, path.basename(fileName), chatName); |
| 827 | 824 | const dir = path.dirname(filePath); |
| 828 | 825 | if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); |
| @@ -898,7 +895,7 @@ async function importFromJson(uploadPath, { request }, preservedFileName) { | ||
| 898 | 895 | importRisuSprites(request.user.directories, jsonData); |
| 899 | 896 | unsetPrivateFields(jsonData); |
| 900 | 897 | jsonData = readFromV2(jsonData); |
| 901 | 898 | jsonData['create_date'] = humanizedISO8601DateTimenew Date().toISOString(); |
| 902 | 899 | const pngName = preservedFileName || getPngName(jsonData.data?.name || jsonData.name, request.user.directories); |
| 903 | 900 | const char = JSON.stringify(jsonData); |
| 904 | 901 | const result = await writeCharacterData(DEFAULT_AVATAR_PATH, char, pngName, request); |
| @@ -917,10 +914,10 @@ async function importFromJson(uploadPath, { request }, preservedFileName) { | ||
| 917 | 914 | 'personality': jsonData.personality ?? '', |
| 918 | 915 | 'first_mes': jsonData.first_mes ?? '', |
| 919 | 916 | 'avatar': 'none', |
| 920 | 917 | 'chat': jsonData.name + ' - ' + humanizedISO8601DateTimehumanizedDateTime(), |
| 921 | 918 | 'mes_example': jsonData.mes_example ?? '', |
| 922 | 919 | 'scenario': jsonData.scenario ?? '', |
| 923 | 920 | 'create_date': humanizedISO8601DateTimenew Date().toISOString(), |
| 924 | 921 | 'talkativeness': jsonData.talkativeness ?? 0.5, |
| 925 | 922 | 'creator': jsonData.creator ?? '', |
| 926 | 923 | 'tags': jsonData.tags ?? '', |
| @@ -943,10 +940,10 @@ async function importFromJson(uploadPath, { request }, preservedFileName) { | ||
| 943 | 940 | 'personality': '', |
| 944 | 941 | 'first_mes': jsonData.char_greeting ?? '', |
| 945 | 942 | 'avatar': 'none', |
| 946 | 943 | 'chat': jsonData.name + ' - ' + humanizedISO8601DateTimehumanizedDateTime(), |
| 947 | 944 | 'mes_example': jsonData.example_dialogue ?? '', |
| 948 | 945 | 'scenario': jsonData.world_scenario ?? '', |
| 949 | 946 | 'create_date': humanizedISO8601DateTimenew Date().toISOString(), |
| 950 | 947 | 'talkativeness': jsonData.talkativeness ?? 0.5, |
| 951 | 948 | 'creator': jsonData.creator ?? '', |
| 952 | 949 | 'tags': jsonData.tags ?? '', |
| @@ -981,7 +978,7 @@ async function importFromPng(uploadPath, { request }, preservedFileName) { | ||
| 981 | 978 | importRisuSprites(request.user.directories, jsonData); |
| 982 | 979 | unsetPrivateFields(jsonData); |
| 983 | 980 | jsonData = readFromV2(jsonData); |
| 984 | 981 | jsonData['create_date'] = humanizedISO8601DateTimenew Date().toISOString(); |
| 985 | 982 | const char = JSON.stringify(jsonData); |
| 986 | 983 | const result = await writeCharacterData(uploadPath, char, pngName, request); |
| 987 | 984 | fs.unlinkSync(uploadPath); |
| @@ -1000,10 +997,10 @@ async function importFromPng(uploadPath, { request }, preservedFileName) { | ||
| 1000 | 997 | 'personality': jsonData.personality ?? '', |
| 1001 | 998 | 'first_mes': jsonData.first_mes ?? '', |
| 1002 | 999 | 'avatar': 'none', |
| 1003 | 1000 | 'chat': jsonData.name + ' - ' + humanizedISO8601DateTimehumanizedDateTime(), |
| 1004 | 1001 | 'mes_example': jsonData.mes_example ?? '', |
| 1005 | 1002 | 'scenario': jsonData.scenario ?? '', |
| 1006 | 1003 | 'create_date': humanizedISO8601DateTimenew Date().toISOString(), |
| 1007 | 1004 | 'talkativeness': jsonData.talkativeness ?? 0.5, |
| 1008 | 1005 | 'creator': jsonData.creator ?? '', |
| 1009 | 1006 | 'tags': jsonData.tags ?? '', |
| @@ -11,7 +11,7 @@ import _ from 'lodash'; | ||
| 11 | 11 | import validateAvatarUrlMiddleware from '../middleware/validateFileName.js'; |
| 12 | 12 | import { |
| 13 | 13 | getConfigValue, |
| 14 | 14 | humanizedISO8601DateTimehumanizedDateTime, |
| 15 | 15 | tryParse, |
| 16 | 16 | generateTimestamp, |
| 17 | 17 | removeOldBackups, |
| @@ -106,9 +106,7 @@ process.on('exit', () => { | ||
| 106 | 106 | function importOobaChat(userName, characterName, jsonData) { |
| 107 | 107 | /** @type {object[]} */ |
| 108 | 108 | const chat = [{ |
| 109 | 109 | user_namechat_metadata: userName{}, |
| 110 | - character_name: characterName, | |
| 111 | - create_date: humanizedISO8601DateTime(), | |
| 112 | 110 | }]; |
| 113 | 111 | |
| 114 | 112 | for (const arr of jsonData.data_visible) { |
| @@ -116,8 +114,9 @@ function importOobaChat(userName, characterName, jsonData) { | ||
| 116 | 114 | const userMessage = { |
| 117 | 115 | name: userName, |
| 118 | 116 | is_user: true, |
| 119 | 117 | send_date: humanizedISO8601DateTimenew Date().toISOString(), |
| 120 | 118 | mes: arr[0], |
| 119 | + extra: {}, | |
| 121 | 120 | }; |
| 122 | 121 | chat.push(userMessage); |
| 123 | 122 | } |
| @@ -125,8 +124,9 @@ function importOobaChat(userName, characterName, jsonData) { | ||
| 125 | 124 | const charMessage = { |
| 126 | 125 | name: characterName, |
| 127 | 126 | is_user: false, |
| 128 | 127 | send_date: humanizedISO8601DateTimenew Date().toISOString(), |
| 129 | 128 | mes: arr[1], |
| 129 | + extra: {}, | |
| 130 | 130 | }; |
| 131 | 131 | chat.push(charMessage); |
| 132 | 132 | } |
| @@ -145,9 +145,7 @@ function importOobaChat(userName, characterName, jsonData) { | ||
| 145 | 145 | function importAgnaiChat(userName, characterName, jsonData) { |
| 146 | 146 | /** @type {object[]} */ |
| 147 | 147 | const chat = [{ |
| 148 | 148 | user_namechat_metadata: userName{}, |
| 149 | - character_name: characterName, | |
| 150 | - create_date: humanizedISO8601DateTime(), | |
| 151 | 149 | }]; |
| 152 | 150 | |
| 153 | 151 | for (const message of jsonData.messages) { |
| @@ -155,8 +153,9 @@ function importAgnaiChat(userName, characterName, jsonData) { | ||
| 155 | 153 | chat.push({ |
| 156 | 154 | name: isUser ? userName : characterName, |
| 157 | 155 | is_user: isUser, |
| 158 | 156 | send_date: humanizedISO8601DateTimenew Date().toISOString(), |
| 159 | 157 | mes: message.msg, |
| 158 | + extra: {}, | |
| 160 | 159 | }); |
| 161 | 160 | } |
| 162 | 161 | |
| @@ -178,16 +177,15 @@ function importCAIChat(userName, characterName, jsonData) { | ||
| 178 | 177 | */ |
| 179 | 178 | function convert(history) { |
| 180 | 179 | const starter = { |
| 181 | 180 | user_namechat_metadata: userName{}, |
| 182 | - character_name: characterName, | |
| 183 | - create_date: humanizedISO8601DateTime(), | |
| 184 | 181 | }; |
| 185 | 182 | |
| 186 | 183 | const historyData = history.msgs.map((msg) => ({ |
| 187 | 184 | name: msg.src.is_human ? userName : characterName, |
| 188 | 185 | is_user: msg.src.is_human, |
| 189 | 186 | send_date: humanizedISO8601DateTimenew Date().toISOString(), |
| 190 | 187 | mes: msg.text, |
| 188 | + extra: {}, | |
| 191 | 189 | })); |
| 192 | 190 | |
| 193 | 191 | return [starter, ...historyData]; |
| @@ -215,7 +213,8 @@ function importKoboldLiteChat(_userName, _characterName, data) { | ||
| 215 | 213 | name: isUser ? header.user_name : header.character_name, |
| 216 | 214 | is_user: isUser, |
| 217 | 215 | mes: msg.replaceAll(inputToken, '').replaceAll(outputToken, '').trim(), |
| 218 | 216 | send_date: new Date().nowtoISOString(), |
| 217 | + extra: {}, | |
| 219 | 218 | }; |
| 220 | 219 | } |
| 221 | 220 | |
| @@ -276,9 +275,7 @@ function flattenChubChat(userName, characterName, lines) { | ||
| 276 | 275 | function importRisuChat(userName, characterName, jsonData) { |
| 277 | 276 | /** @type {object[]} */ |
| 278 | 277 | const chat = [{ |
| 279 | 278 | user_namechat_metadata: userName{}, |
| 280 | - character_name: characterName, | |
| 281 | - create_date: humanizedISO8601DateTime(), | |
| 282 | 279 | }]; |
| 283 | 280 | |
| 284 | 281 | for (const message of jsonData.data.message) { |
| @@ -286,8 +283,9 @@ function importRisuChat(userName, characterName, jsonData) { | ||
| 286 | 283 | chat.push({ |
| 287 | 284 | name: message.name ?? (isUser ? userName : characterName), |
| 288 | 285 | is_user: isUser, |
| 289 | 286 | send_date: new Date(Number(message.time ?? Date.now())).toISOString(), |
| 290 | 287 | mes: message.data ?? '', |
| 288 | + extra: {}, | |
| 291 | 289 | }); |
| 292 | 290 | } |
| 293 | 291 | |
| @@ -417,7 +415,7 @@ export async function getChatInfo(pathToFile, additionalData = {}, withMetadata | ||
| 417 | 415 | if (jsonData && (jsonData.name || jsonData.character_name || jsonData.chat_metadata)) { |
| 418 | 416 | chatData.chat_items = (itemCounter - 1); |
| 419 | 417 | chatData.mes = jsonData['mes'] || '[The message is empty]'; |
| 420 | 418 | chatData.last_mes = jsonData['send_date'] || new Date(Math.round(stats.mtimeMs)).toISOString(); |
| 421 | 419 | |
| 422 | 420 | res(chatData); |
| 423 | 421 | } else { |
| @@ -623,7 +621,7 @@ router.post('/group/import', function (request, response) { | ||
| 623 | 621 | return response.sendStatus(400); |
| 624 | 622 | } |
| 625 | 623 | |
| 626 | 624 | const chatname = humanizedISO8601DateTimehumanizedDateTime(); |
| 627 | 625 | const pathToUpload = path.join(filedata.destination, filedata.filename); |
| 628 | 626 | const pathToNewFile = path.join(request.user.directories.groupChats, `${chatname}.jsonl`); |
| 629 | 627 | fs.copyFileSync(pathToUpload, pathToNewFile); |
| @@ -675,7 +673,7 @@ router.post('/import', validateAvatarUrlMiddleware, function (request, response) | ||
| 675 | 673 | } |
| 676 | 674 | |
| 677 | 675 | const handleChat = (chat) => { |
| 678 | 676 | const fileName = `${characterName} - ${humanizedISO8601DateTimehumanizedDateTime()} imported.jsonl`; |
| 679 | 677 | const filePath = path.join(request.user.directories.chats, avatarUrl, fileName); |
| 680 | 678 | fileNames.push(fileName); |
| 681 | 679 | writeFileAtomicSync(filePath, chat, 'utf8'); |
| @@ -714,7 +712,7 @@ router.post('/import', validateAvatarUrlMiddleware, function (request, response) | ||
| 714 | 712 | console.warn('Failed to flatten Chub Chat data: ', error); |
| 715 | 713 | } |
| 716 | 714 | |
| 717 | 715 | const fileName = `${characterName} - ${humanizedISO8601DateTimehumanizedDateTime()} imported.jsonl`; |
| 718 | 716 | const filePath = path.join(request.user.directories.chats, avatarUrl, fileName); |
| 719 | 717 | fileNames.push(fileName); |
| 720 | 718 | if (flattenedChat !== data) { |
| @@ -879,7 +877,7 @@ router.post('/search', validateAvatarUrlMiddleware, function (request, response) | ||
| 879 | 877 | } |
| 880 | 878 | |
| 881 | 879 | const lastMessage = messages[messages.length - 1]; |
| 882 | 880 | const lastMesDate = lastMessage?.send_date || Math.roundnew Date(fs.statSync(chatFile.path).mtimeMs).toISOString(); |
| 883 | 881 | |
| 884 | 882 | // If no search query, just return metadata |
| 885 | 883 | if (!query) { |
| @@ -6,7 +6,7 @@ import express from 'express'; | ||
| 6 | 6 | import sanitize from 'sanitize-filename'; |
| 7 | 7 | import { sync as writeFileAtomicSync, default as writeFileAtomic } from 'write-file-atomic'; |
| 8 | 8 | |
| 9 | 9 | import { color, humanizedISO8601DateTime, tryParse } from '../util.js'; |
| 10 | 10 | import { getFileNameValidationFunction } from '../middleware/validateFileName.js'; |
| 11 | 11 | |
| 12 | 12 | export const router = express.Router(); |
| @@ -127,7 +127,7 @@ router.post('/all', (request, response) => { | ||
| 127 | 127 | const group = JSON.parse(fileContents); |
| 128 | 128 | const groupStat = fs.statSync(filePath); |
| 129 | 129 | group['date_added'] = groupStat.birthtimeMs; |
| 130 | 130 | group['create_date'] = humanizedISO8601DateTimenew Date(groupStat.birthtimeMs).toISOString(); |
| 131 | 131 | |
| 132 | 132 | let chat_size = 0; |
| 133 | 133 | let date_last_chat = 0; |
| @@ -12,6 +12,21 @@ import { getAllUserHandles, getUserDirectories } from '../users.js'; | ||
| 12 | 12 | |
| 13 | 13 | const STATS_FILE = 'stats.json'; |
| 14 | 14 | |
| 15 | +const monthNames = [ | |
| 16 | + 'January', | |
| 17 | + 'February', | |
| 18 | + 'March', | |
| 19 | + 'April', | |
| 20 | + 'May', | |
| 21 | + 'June', | |
| 22 | + 'July', | |
| 23 | + 'August', | |
| 24 | + 'September', | |
| 25 | + 'October', | |
| 26 | + 'November', | |
| 27 | + 'December', | |
| 28 | +]; | |
| 29 | + | |
| 15 | 30 | /** |
| 16 | 31 | * @type {Map<string, Object>} The stats object for each user. |
| 17 | 32 | */ |
| @@ -23,92 +38,79 @@ const TIMESTAMPS = new Map(); | ||
| 23 | 38 | |
| 24 | 39 | /** |
| 25 | 40 | * Convert a timestamp to an integer timestamp. |
| 26 | - * (sorry, it's momentless for now, didn't want to add a package just for this) | |
| 27 | 41 | * This function can handle several different timestamp formats: |
| 28 | 42 | * 1. UnixDate.now timestamps (the number of secondsmilliseconds since the Unix Epoch) |
| 29 | 43 | * 2. ST "humanized" timestamps, formatted like "`YYYY-MM-DD @HHh MMm SSs ms"HHhMMmSSsMSms` |
| 30 | 44 | * 3. Date strings in the format "`Month DD, YYYY H:MMam/pm"` |
| 45 | + * 4. ISO 8601 formatted strings | |
| 46 | + * 5. Date objects | |
| 31 | 47 | * |
| 32 | 48 | * The function returns the timestamp as the number of milliseconds since |
| 33 | 49 | * the Unix Epoch, which can be converted to a JavaScript Date object with new Date(). |
| 34 | 50 | * |
| 35 | 51 | * @param {string|number|Date} timestamp - The timestamp to convert. |
| 36 | 52 | * @returns {number} The timestamp in milliseconds since the Unix Epoch, or 0 if the input cannot be parsed. |
| 37 | 53 | * |
| 38 | 54 | * @example |
| 39 | 55 | * // Unix timestamp |
| 40 | 56 | * timestampToMomentparseTimestamp(1609459200); |
| 41 | 57 | * // ST humanized timestamp |
| 42 | 58 | * timestampToMomentparseTimestamp("2021-01-01 \@00h 00m 00s 000ms"); |
| 43 | 59 | * // Date string |
| 44 | 60 | * timestampToMomentparseTimestamp("January 1, 2021 12:00am"); |
| 45 | 61 | */ |
| 46 | 62 | function timestampToMomentparseTimestamp(timestamp) { |
| 47 | 63 | if (!timestamp) { |
| 48 | 64 | return 0; |
| 49 | 65 | } |
| 50 | 66 | |
| 51 | - if (typeof timestamp === 'number') { | |
| 67 | + // Date object | |
| 52 | - return timestamp; | |
| 68 | + if (timestamp instanceof Date) { | |
| 69 | + return timestamp.getTime(); | |
| 53 | 70 | } |
| 54 | 71 | |
| 55 | - const pattern1 = | |
| 72 | + // Unix time | |
| 56 | - /(\d{4})-(\d{1,2})-(\d{1,2}) @(\d{1,2})h (\d{1,2})m (\d{1,2})s (\d{1,3})ms/; | |
| 73 | + if (typeof timestamp === 'number' || /^\d+$/.test(timestamp)) { | |
| 57 | 74 | const replacement1unixTime = Number(timestamp); |
| 58 | - match, | |
| 75 | + const isValid = Number.isFinite(unixTime) && !Number.isNaN(unixTime) && unixTime >= 0; | |
| 59 | - year, | |
| 76 | + if (!isValid) return 0; | |
| 60 | - month, | |
| 77 | + return new Date(unixTime).getTime(); | |
| 61 | - day, | |
| 78 | + } | |
| 62 | - hour, | |
| 79 | + | |
| 63 | - minute, | |
| 80 | + // ISO 8601 format | |
| 64 | - second, | |
| 81 | + const isoPattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/; | |
| 65 | - millisecond, | |
| 82 | + if (isoPattern.test(timestamp)) { | |
| 66 | - ) => { | |
| 83 | + return new Date(timestamp).getTime(); | |
| 67 | - return `${year}-${month.padStart(2, '0')}-${day.padStart( | |
| 68 | - 2, | |
| 69 | - '0', | |
| 70 | - )}T${hour.padStart(2, '0')}:${minute.padStart( | |
| 71 | - 2, | |
| 72 | - '0', | |
| 73 | - )}:${second.padStart(2, '0')}.${millisecond.padStart(3, '0')}Z`; | |
| 74 | - }; | |
| 75 | - const isoTimestamp1 = timestamp.replace(pattern1, replacement1); | |
| 76 | - if (!isNaN(Number(new Date(isoTimestamp1)))) { | |
| 77 | - return new Date(isoTimestamp1).getTime(); | |
| 78 | 84 | } |
| 79 | 85 | |
| 80 | - const pattern2 = /(\w+)\s(\d{1,2}),\s(\d{4})\s(\d{1,2}):(\d{1,2})(am|pm)/i; | |
| 86 | + let dateFormats = []; | |
| 81 | - const replacement2 = (match, month, day, year, hour, minute, meridiem) => { | |
| 87 | + | |
| 82 | - const monthNames = [ | |
| 88 | + // meridiem-based format | |
| 83 | - 'January', | |
| 89 | + const convertFromMeridiemBased = (_, month, day, year, hour, minute, meridiem) => { | |
| 84 | - 'February', | |
| 85 | - 'March', | |
| 86 | - 'April', | |
| 87 | - 'May', | |
| 88 | - 'June', | |
| 89 | - 'July', | |
| 90 | - 'August', | |
| 91 | - 'September', | |
| 92 | - 'October', | |
| 93 | - 'November', | |
| 94 | - 'December', | |
| 95 | - ]; | |
| 96 | 90 | const monthNum = monthNames.indexOf(month) + 1; |
| 97 | - const hour24 = | |
| 91 | + const hour24 = meridiem.toLowerCase() === 'pm' ? (parseInt(hour, 10) % 12) + 12 : parseInt(hour, 10) % 12; | |
| 98 | - meridiem.toLowerCase() === 'pm' | |
| 92 | + return `${year}-${monthNum}-${day.padStart(2, '0')}T${hour24.toString().padStart(2, '0')}:${minute.padStart(2, '0')}:00`; | |
| 99 | - ? (parseInt(hour, 10) % 12) + 12 | |
| 93 | + }; | |
| 100 | - : parseInt(hour, 10) % 12; | |
| 94 | + // June 19, 2023 2:20pm | |
| 101 | - return `${year}-${monthNum.toString().padStart(2, '0')}-${day.padStart( | |
| 95 | + dateFormats.push({ callback: convertFromMeridiemBased, pattern: /(\w+)\s(\d{1,2}),\s(\d{4})\s(\d{1,2}):(\d{1,2})(am|pm)/i }); | |
| 102 | - 2, | |
| 96 | + | |
| 103 | - '0', | |
| 97 | + // ST "humanized" format patterns | |
| 104 | - )}T${hour24.toString().padStart(2, '0')}:${minute.padStart( | |
| 98 | + const convertFromHumanized = (_, year, month, day, hour, min, sec, ms) => { | |
| 105 | - 2, | |
| 99 | + ms = typeof ms !== 'undefined' ? `.${ms.padStart(3, '0')}` : ''; | |
| 106 | - '0', | |
| 100 | + return `${year.padStart(4, '0')}-${month.padStart(2, '0')}-${day.padStart(2, '0')}T${hour.padStart(2, '0')}:${min.padStart(2, '0')}:${sec.padStart(2, '0')}${ms}Z`; | |
| 107 | - )}:00Z`; | |
| 108 | 101 | }; |
| 109 | - const isoTimestamp2 = timestamp.replace(pattern2, replacement2); | |
| 102 | + // 2024-07-12@01h31m37s123ms | |
| 110 | - if (!isNaN(Number(new Date(isoTimestamp2)))) { | |
| 103 | + dateFormats.push({ callback: convertFromHumanized, pattern: /(\d{4})-(\d{1,2})-(\d{1,2})@(\d{1,2})h(\d{1,2})m(\d{1,2})s(\d{1,3})ms/ }); | |
| 111 | - return new Date(isoTimestamp2).getTime(); | |
| 104 | + // 2024-7-12@01h31m37s | |
| 105 | + dateFormats.push({ callback: convertFromHumanized, pattern: /(\d{4})-(\d{1,2})-(\d{1,2})@(\d{1,2})h(\d{1,2})m(\d{1,2})s/ }); | |
| 106 | + // 2024-6-5 @14h 56m 50s 682ms | |
| 107 | + dateFormats.push({ callback: convertFromHumanized, pattern: /(\d{4})-(\d{1,2})-(\d{1,2}) @(\d{1,2})h (\d{1,2})m (\d{1,2})s (\d{1,3})ms/ }); | |
| 108 | + | |
| 109 | + for (const x of dateFormats) { | |
| 110 | + const rgxMatch = timestamp.match(x.pattern); | |
| 111 | + if (!rgxMatch) continue; | |
| 112 | + const isoTimestamp = x.callback(...rgxMatch); | |
| 113 | + return new Date(isoTimestamp).getTime(); | |
| 112 | 114 | } |
| 113 | 115 | |
| 114 | 116 | return 0; |
| @@ -416,7 +418,7 @@ function calculateTotalGenTimeAndWordCount( | ||
| 416 | 418 | // If this is the first user message, set the first chat time |
| 417 | 419 | if (json.is_user) { |
| 418 | 420 | //get min between firstChatTime and timestampToMoment(json.send_date) |
| 419 | 421 | firstChatTime = Math.min(timestampToMomentparseTimestamp(json.send_date), firstChatTime); |
| 420 | 422 | } |
| 421 | 423 | } catch (error) { |
| 422 | 424 | console.error(`Error parsing line ${line}: ${error}`); |
| @@ -389,17 +389,27 @@ export function uuidv4() { | ||
| 389 | 389 | }); |
| 390 | 390 | } |
| 391 | 391 | |
| 392 | -export function humanizedISO8601DateTime(date) { | |
| 392 | +/** | |
| 393 | - let baseDate = typeof date === 'number' ? new Date(date) : new Date(); | |
| 393 | + * Gets a humanized date time string from a given timestamp. | |
| 394 | - let humanYear = baseDate.getFullYear(); | |
| 394 | + * @param {number} timestamp Timestamp in milliseconds | |
| 395 | - let humanMonth = (baseDate.getMonth() + 1); | |
| 395 | + * @returns {string} Humanized date time string in the format `YYYY-MM-DD@HHhMMmSSsMSms` | |
| 396 | - let humanDate = baseDate.getDate(); | |
| 396 | + */ | |
| 397 | - let humanHour = (baseDate.getHours() < 10 ? '0' : '') + baseDate.getHours(); | |
| 397 | +export function humanizedDateTime(timestamp = Date.now()) { | |
| 398 | - let humanMinute = (baseDate.getMinutes() < 10 ? '0' : '') + baseDate.getMinutes(); | |
| 398 | + const date = new Date(timestamp); | |
| 399 | - let humanSecond = (baseDate.getSeconds() < 10 ? '0' : '') + baseDate.getSeconds(); | |
| 399 | + const dt = { | |
| 400 | - let humanMillisecond = (baseDate.getMilliseconds() < 10 ? '0' : '') + baseDate.getMilliseconds(); | |
| 400 | + year: date.getFullYear(), | |
| 401 | - let HumanizedDateTime = (humanYear + '-' + humanMonth + '-' + humanDate + ' @' + humanHour + 'h ' + humanMinute + 'm ' + humanSecond + 's ' + humanMillisecond + 'ms'); | |
| 401 | + month: date.getMonth() + 1, | |
| 402 | - return HumanizedDateTime; | |
| 402 | + day: date.getDate(), | |
| 403 | + hour: date.getHours(), | |
| 404 | + minute: date.getMinutes(), | |
| 405 | + second: date.getSeconds(), | |
| 406 | + millisecond: date.getMilliseconds(), | |
| 407 | + }; | |
| 408 | + for (const key in dt) { | |
| 409 | + const padLength = key === 'millisecond' ? 3 : 2; | |
| 410 | + dt[key] = dt[key].toString().padStart(padLength, '0'); | |
| 411 | + } | |
| 412 | + return `${dt.year}-${dt.month}-${dt.day}@${dt.hour}h${dt.minute}m${dt.second}s${dt.millisecond}ms`; | |
| 403 | 413 | } |
| 404 | 414 | |
| 405 | 415 | export function tryParse(str) { |