-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathdb.js
584 lines (489 loc) · 19.3 KB
/
db.js
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// db.js
const MS_PER_DAY = 24 * 60 * 60 * 1000;
const CACHE_SIZE = 100;
const CACHE_DURATION = 5 * 60 * 1000;
class MessageStoreDB {
constructor(options = {}) {
this.dbName = options.dbName || 'chatMessagesDB_v3';
this.storeName = options.storeName || 'messages';
this.cacheSize = options.cacheSize || 100;
this.cacheDuration = options.cacheDuration || 5 * 60 * 1000;
this.daysToKeep = options.daysToKeep || 30;
this.db = null;
this.cache = {
recent: [],
userMessages: new Map(),
lastUpdate: 0
};
this.initPromise = this.initDatabase();
}
async initDatabase() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.dbName, 3);
request.onupgradeneeded = event => {
const db = event.target.result;
if (!db.objectStoreNames.contains(this.storeName)) {
const store = db.createObjectStore(this.storeName, { keyPath: 'id', autoIncrement: true });
store.createIndex('timestamp', 'timestamp');
store.createIndex('user_timestamp', ['chatname', 'timestamp']);
store.createIndex('user_type_timestamp', ['chatname', 'type', 'timestamp']);
}
};
request.onsuccess = event => {
this.db = event.target.result;
this.scheduleCleanup();
resolve();
};
request.onerror = () => reject(request.error);
});
}
async ensureDB() {
if (!this.db) await this.initPromise;
return this.db;
}
async addMessage(message) {
const db = await this.ensureDB();
const now = Date.now();
delete message.id; // this will conflict with the id in the database if we include it.
const messageData = {
...message,
timestamp: now,
expiresAt: now + (this.daysToKeep * MS_PER_DAY)
};
return new Promise((resolve, reject) => {
const tx = db.transaction(this.storeName, 'readwrite');
const store = tx.objectStore(this.storeName);
const request = store.add(messageData);
request.onsuccess = () => {
this.updateCache(messageData);
resolve(messageData);
};
request.onerror = () => reject(request.error);
});
}
updateCache(message) {
const { recent, userMessages } = this.cache;
recent.unshift(message);
if (recent.length > this.cacheSize) recent.pop();
if (!userMessages.has(message.chatname)) {
userMessages.set(message.chatname, []);
}
const userCache = userMessages.get(message.chatname);
userCache.unshift(message);
if (userCache.length > this.cacheSize) userCache.pop();
this.cache.lastUpdate = Date.now();
}
async getRecentMessages(limit = 10) {
const now = Date.now();
if (this.cache.recent.length >= limit &&
(now - this.cache.lastUpdate) < this.cacheDuration) {
return this.cache.recent.slice(0, limit);
}
const db = await this.ensureDB();
return new Promise((resolve) => {
const tx = db.transaction(this.storeName, 'readonly');
const index = tx.objectStore(this.storeName).index('timestamp');
const messages = [];
index.openCursor(IDBKeyRange.upperBound(now), 'prev').onsuccess = event => {
const cursor = event.target.result;
if (cursor && messages.length < limit) {
const msg = cursor.value;
if (!msg.expiresAt || msg.expiresAt > now) {
messages.push(msg);
}
cursor.continue();
} else {
this.cache.recent = messages;
this.cache.lastUpdate = now;
resolve(messages);
}
};
});
}
async getUserMessages(chatname, type, page = 0, pageSize = 100) {
const db = await this.ensureDB();
const now = Date.now();
if (page === 0 && this.cache.userMessages.has(chatname)) {
const cached = this.cache.userMessages.get(chatname);
if (cached.length >= pageSize && (now - this.cache.lastUpdate) < this.cacheDuration) {
return cached.slice(0, pageSize);
}
}
if (settings?.disableDB) return [];
return new Promise((resolve) => {
const tx = db.transaction(this.storeName, 'readonly');
const index = tx.objectStore(this.storeName).index(
type ? 'user_type_timestamp' : 'user_timestamp'
);
const messages = [];
const skip = page * pageSize;
let count = 0;
const range = type ?
IDBKeyRange.bound([chatname, type, 0], [chatname, type, now]) :
IDBKeyRange.bound([chatname, 0], [chatname, now]);
index.openCursor(range, 'prev').onsuccess = event => {
const cursor = event.target.result;
if (cursor) {
const msg = cursor.value;
if (!msg.expiresAt || msg.expiresAt > now) {
if (count >= skip && messages.length < pageSize) {
messages.push(msg);
}
count++;
}
cursor.continue();
} else {
if (page === 0) {
this.cache.userMessages.set(chatname, messages);
this.cache.lastUpdate = now;
}
resolve(messages);
}
};
});
}
scheduleCleanup() {
const cleanup = async () => {
const db = await this.ensureDB();
const now = Date.now();
const tx = db.transaction(this.storeName, 'readwrite');
const store = tx.objectStore(this.storeName);
const index = store.index('timestamp');
index.openCursor().onsuccess = event => {
const cursor = event.target.result;
if (cursor) {
const message = cursor.value;
if (message.expiresAt && message.expiresAt < now) {
store.delete(cursor.primaryKey);
}
cursor.continue();
}
};
};
cleanup();
setInterval(cleanup, MS_PER_DAY);
}
async clearCache() {
this.cache.recent = [];
this.cache.userMessages.clear();
this.cache.lastUpdate = 0;
}
}
// Compatibility function for getLastMessagesDB
async function getLastMessagesDB(limit = 10) {
return await messageStoreDB.getRecentMessages(limit);
}
// Compatibility function for addMessageDB
async function addMessageDB(message) {
if (settings?.disableDB) return;
await messageStoreDB.addMessage(message);
}
// Compatibility function for getMessagesDB
async function getMessagesDB(chatname, type, page = 0, pageSize = 100, callback) {
if (settings?.disableDB) {
if (callback) callback([]);
return [];
}
const messages = await messageStoreDB.getUserMessages(chatname, type, page, pageSize);
if (callback) {
callback(messages);
}
return messages;
}
// Compatibility function for getRecentMessages
async function getRecentMessages(chatname, limit, timeWindow) {
const messages = await messageStoreDB.getUserMessages(chatname, null, 0, limit);
if (timeWindow) {
const cutoffTime = Date.now() - timeWindow;
return messages.filter(msg => msg.timestamp >= cutoffTime);
}
return messages;
}
// Initialize the store - I might want to use this after I no longer need the migration script
/* const messageStoreDB = new MessageStoreDB({
dbName: 'chatMessagesDB_v3',
storeName: 'messages',
cacheSize: 100, // should be no smaller than the default paging size (100).
cacheDuration: 5 * 60 * 1000, // 5 minutes
daysToKeep: 30
}); */
/// migration addon -- remove this in late 2025
class MessageStoreMigration {
constructor(messageStore, options = {}) {
this.messageStore = messageStore;
this.oldDbName = 'chatMessagesDB';
this.oldStoreName = 'messages';
this.maxMessages = options.maxMessages || 10000;
this.cutoffDate = options.cutoffDate || new Date(Date.now() - (30 * 24 * 60 * 60 * 1000));
this.migrationAttempted = false;
}
async checkAndMigrate() {
if (this.migrationAttempted) return;
try {
const oldVersion = await this.detectDatabaseVersion();
if (!oldVersion) {
console.log('No old database found');
return;
}
const hasValidStore = await this.verifyObjectStore(oldVersion);
if (!hasValidStore) {
console.log('Old database found but store is invalid, cleaning up...');
await this.deleteOldDatabase();
return;
}
console.log(`Found valid old database (version ${oldVersion}), starting migration...`);
const migratedCount = await this.migrateRecentData(oldVersion);
if (migratedCount > 0) {
console.log(`Successfully migrated ${migratedCount} messages`);
await this.deleteOldDatabase();
} else {
console.log('No messages to migrate');
await this.deleteOldDatabase();
}
} catch (error) {
console.error('Migration failed:', error);
await this.cleanupFailedMigration();
} finally {
this.migrationAttempted = true;
}
}
async verifyObjectStore(version) {
return new Promise((resolve) => {
console.log(`Attempting to verify database version ${version}`);
const request = indexedDB.open(this.oldDbName, version);
request.onerror = () => {
console.error('Error during store verification:', request.error);
resolve(false);
};
request.onupgradeneeded = (event) => {
console.log('Database upgrade needed during verification');
event.target.transaction.abort();
resolve(false);
};
request.onsuccess = event => {
const db = event.target.result;
console.log('Successfully opened old database');
if (!db.objectStoreNames.contains(this.oldStoreName)) {
console.log('Store name not found:', this.oldStoreName);
db.close();
resolve(false);
return;
}
try {
const tx = db.transaction(this.oldStoreName, 'readonly');
const store = tx.objectStore(this.oldStoreName);
console.log('Store indexes:', Array.from(store.indexNames));
const countRequest = store.count();
countRequest.onsuccess = () => {
const count = countRequest.result;
console.log('Store record count:', count);
db.close();
resolve(true); // Changed to always resolve true if we can access the store
};
countRequest.onerror = (error) => {
console.error('Error counting records:', error);
db.close();
resolve(false);
};
} catch (e) {
console.error('Error during store transaction:', e);
db.close();
resolve(false);
}
};
});
}
async detectDatabaseVersion() {
return new Promise((resolve) => {
console.log('Detecting database version...');
let wasUpgradeNeeded = false;
const request = indexedDB.open(this.oldDbName);
request.onerror = () => {
// If error is from our intentional abort, treat as "no database"
if (wasUpgradeNeeded) {
resolve(null);
return;
}
console.log('Error detecting version:', request.error);
resolve(null);
};
request.onsuccess = event => {
const db = event.target.result;
const version = db.version;
console.log('Detected database version:', version);
db.close();
resolve(version);
};
request.onupgradeneeded = event => {
console.log('Database upgrade needed during version detection');
wasUpgradeNeeded = true;
const db = event.target.result;
db.close();
resolve(null);
};
});
}
async migrateRecentData(oldVersion) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(this.oldDbName, oldVersion);
request.onerror = () => {
console.error('Error opening old database for migration:', request.error);
reject(request.error);
};
request.onsuccess = async event => {
const oldDb = event.target.result;
let migratedCount = 0;
try {
const messages = await this.getRecentMessages(oldDb, oldVersion);
console.log(`Found ${messages.length} messages to migrate`);
if (messages.length === 0) {
oldDb.close();
resolve(0);
return;
}
const batchSize = 50;
for (let i = 0; i < messages.length; i += batchSize) {
const batch = messages.slice(i, i + batchSize);
const batchResults = await this.migrateBatch(batch);
migratedCount += batchResults.filter(Boolean).length;
}
oldDb.close();
resolve(migratedCount);
} catch (error) {
console.error('Error during migration:', error);
oldDb.close();
reject(error);
}
};
});
}
async migrateBatch(messages) {
return Promise.all(messages.map(async (message) => {
try {
await this.messageStore.addMessage(message);
return true;
} catch (error) {
console.error("Failed to migrate message:", message, error);
return false;
}
}));
}
async getRecentMessages(db, oldVersion) {
return new Promise((resolve, reject) => {
console.log(`Getting messages from version ${oldVersion} database`);
const tx = db.transaction(this.oldStoreName, 'readonly');
const store = tx.objectStore(this.oldStoreName);
const messages = [];
let cursorRequest;
try {
// Try to get cursor from store directly first
cursorRequest = store.openCursor(null, 'prev');
cursorRequest.onsuccess = event => {
const cursor = event.target.result;
if (cursor && messages.length < this.maxMessages) {
console.log('Processing message:', cursor.value);
try {
const message = this.normalizeMessage(cursor.value, oldVersion);
const messageDate = new Date(message.timestamp);
if (messageDate >= this.cutoffDate) {
messages.push(message);
}
cursor.continue();
} catch (e) {
console.error('Error processing message:', e);
cursor.continue();
}
} else {
console.log(`Retrieved ${messages.length} messages`);
resolve(messages);
}
};
cursorRequest.onerror = (error) => {
console.error('Error during cursor operation:', error);
resolve(messages); // Resolve with whatever we got
};
} catch (error) {
console.error('Error setting up cursor:', error);
resolve(messages);
}
tx.onerror = () => {
console.error('Transaction error:', tx.error);
resolve(messages);
};
});
}
async cleanupFailedMigration() {
try {
// Attempt to delete the old database
await this.deleteOldDatabase();
console.log('Cleaned up old database after failed migration');
} catch (error) {
console.error('Failed to cleanup after migration:', error);
}
}
normalizeMessage(oldMessage, oldVersion) {
const now = Date.now();
const thirtyDays = 30 * 24 * 60 * 60 * 1000;
let timestamp;
if (oldMessage.timestamp instanceof Date) {
timestamp = oldMessage.timestamp.getTime();
} else if (typeof oldMessage.timestamp === 'string') {
timestamp = new Date(oldMessage.timestamp).getTime();
} else {
timestamp = now;
}
return {
chatname: oldMessage.chatname || '',
chatmessage: oldMessage.chatmessage || oldMessage.message || '',
chatimg: oldMessage.chatimg || '',
hasDonation: oldMessage.hasDonation || '',
membership: oldMessage.membership || oldMessage.hasMembership || '',
type: oldMessage.type || 'user',
timestamp: timestamp,
expiresAt: now + thirtyDays,
backgroundColor: oldMessage.backgroundColor || '',
chatbadges: oldMessage.chatbadges || '',
event: oldMessage.event || '',
nameColor: oldMessage.nameColor || '',
textColor: oldMessage.textColor || ''
};
}
async deleteOldDatabase() {
return new Promise((resolve, reject) => {
const request = indexedDB.deleteDatabase(this.oldDbName);
request.onsuccess = () => {
console.log('Successfully deleted old database');
resolve();
};
request.onerror = () => reject(request.error);
});
}
}
class MessageStoreWithMigration extends MessageStoreDB {
constructor(options = {}) {
super(options);
this.migration = new MessageStoreMigration(this);
}
async init() {
await this.initPromise;
await this.migration.checkAndMigrate();
return this;
}
}
// Initialize the store
const messageStoreDB = new MessageStoreWithMigration({
dbName: 'chatMessagesDB_v3', // Use a new name to avoid conflicts
storeName: 'messages',
cacheSize: CACHE_SIZE,
cacheDuration: CACHE_DURATION,
daysToKeep: 30
});
async function initializeMessageStore() {
try {
await messageStoreDB.init();
console.log('Message store initialized and migration completed if needed');
} catch (error) {
console.error('Failed to initialize message store:', error);
}
}
initializeMessageStore();