Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 1 | import {openDB} from 'idb'; |
| 2 | |
| 3 | const dbName = 'TWPTAvatarsDB'; |
Adrià Vilanova Martínez | 351860d | 2021-08-16 11:33:24 +0200 | [diff] [blame] | 4 | const threadListRequestEvent = 'TWPT_ViewForumRequest'; |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 5 | const threadListLoadEvent = 'TWPT_ViewForumResponse'; |
avm99963 | afda237 | 2021-08-08 20:54:05 +0200 | [diff] [blame] | 6 | const createMessageLoadEvent = 'TWPT_CreateMessageRequest'; |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 7 | // Time after the last use when a cache entry should be deleted (in s): |
Adrià Vilanova Martínez | c41edf4 | 2021-07-18 02:06:55 +0200 | [diff] [blame] | 8 | const cacheExpirationTime = 4 * 24 * 60 * 60; // 4 days |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 9 | // Probability of running the piece of code to remove unused cache entries after |
| 10 | // loading the thread list. |
| 11 | const probRemoveUnusedCacheEntries = 0.10; // 10% |
| 12 | |
Adrià Vilanova Martínez | c41edf4 | 2021-07-18 02:06:55 +0200 | [diff] [blame] | 13 | // Time after which an unauthorized forum entry expires (in s). |
| 14 | const unauthorizedForumExpirationTime = 1 * 24 * 60 * 60; // 1 day |
| 15 | |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 16 | export default class AvatarsDB { |
| 17 | constructor() { |
| 18 | this.dbPromise = undefined; |
| 19 | this.openDB(); |
avm99963 | afda237 | 2021-08-08 20:54:05 +0200 | [diff] [blame] | 20 | this.setUpInvalidationsHandlers(); |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 21 | } |
| 22 | |
| 23 | openDB() { |
| 24 | if (this.dbPromise === undefined) |
| 25 | this.dbPromise = openDB(dbName, 1, { |
| 26 | upgrade: (udb, oldVersion, newVersion, transaction) => { |
| 27 | switch (oldVersion) { |
| 28 | case 0: |
| 29 | var cache = udb.createObjectStore('avatarsCache', { |
| 30 | keyPath: 'threadId', |
| 31 | }); |
| 32 | cache.createIndex( |
| 33 | 'lastUsedTimestamp', 'lastUsedTimestamp', {unique: false}); |
| 34 | |
| 35 | var unauthedForums = udb.createObjectStore('unauthorizedForums', { |
| 36 | keyPath: 'forumId', |
| 37 | }); |
| 38 | unauthedForums.createIndex( |
| 39 | 'expirationTimestamp', 'expirationTimestamp', |
| 40 | {unique: false}); |
| 41 | } |
| 42 | }, |
| 43 | }); |
| 44 | } |
| 45 | |
Adrià Vilanova Martínez | c41edf4 | 2021-07-18 02:06:55 +0200 | [diff] [blame] | 46 | // avatarsCache methods: |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 47 | getCacheEntry(threadId) { |
| 48 | return this.dbPromise.then(db => db.get('avatarsCache', threadId)); |
| 49 | } |
| 50 | |
| 51 | putCacheEntry(entry) { |
| 52 | return this.dbPromise.then(db => db.put('avatarsCache', entry)); |
| 53 | } |
| 54 | |
| 55 | invalidateCacheEntryIfExists(threadId) { |
| 56 | return this.dbPromise.then(db => db.delete('avatarsCache', threadId)); |
| 57 | } |
| 58 | |
| 59 | removeUnusedCacheEntries() { |
| 60 | console.debug('[threadListAvatars] Removing unused cache entries...'); |
| 61 | return this.dbPromise |
| 62 | .then(db => { |
| 63 | var upperBoundTimestamp = |
Adrià Vilanova Martínez | c41edf4 | 2021-07-18 02:06:55 +0200 | [diff] [blame] | 64 | Math.floor(Date.now() / 1000) - cacheExpirationTime; |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 65 | var range = IDBKeyRange.upperBound(upperBoundTimestamp); |
| 66 | |
| 67 | var tx = db.transaction('avatarsCache', 'readwrite'); |
| 68 | var index = tx.store.index('lastUsedTimestamp'); |
| 69 | return index.openCursor(range); |
| 70 | }) |
| 71 | .then(function iterateCursor(cursor) { |
| 72 | if (!cursor) return; |
| 73 | cursor.delete(); |
| 74 | return cursor.continue().then(iterateCursor); |
| 75 | }); |
| 76 | } |
| 77 | |
avm99963 | afda237 | 2021-08-08 20:54:05 +0200 | [diff] [blame] | 78 | setUpInvalidationsHandlers() { |
Adrià Vilanova Martínez | 351860d | 2021-08-16 11:33:24 +0200 | [diff] [blame] | 79 | let ignoredRequests = []; |
| 80 | |
| 81 | window.addEventListener(threadListRequestEvent, e => { |
Adrià Vilanova Martínez | 31a6616 | 2021-08-16 10:31:23 +0200 | [diff] [blame] | 82 | // Ignore ViewForum requests made by the chat feature and the "Mark as |
| 83 | // duplicate" dialog. |
| 84 | // |
| 85 | // All those requests have |maxNum| set to 10 and 20 respectively, while |
| 86 | // the requests that we want to handle are the ones to initially load the |
| 87 | // thread list (which currently requests 100 threads) and the ones to load |
| 88 | // more threads (which request 50 threads). |
| 89 | var maxNum = e.detail.body?.['2']?.['1']?.['2']; |
Adrià Vilanova Martínez | 351860d | 2021-08-16 11:33:24 +0200 | [diff] [blame] | 90 | if (maxNum == 10 || maxNum == 20) ignoredRequests.push(e.$TWPTID); |
| 91 | }); |
| 92 | window.addEventListener(threadListLoadEvent, e => { |
| 93 | if (ignoredRequests.includes(e.$TWPTID)) { |
| 94 | ignoredRequests = ignoredRequests.filter(item => item != e.$TWPTID); |
| 95 | return; |
| 96 | } |
Adrià Vilanova Martínez | 31a6616 | 2021-08-16 10:31:23 +0200 | [diff] [blame] | 97 | |
| 98 | this.handleInvalidationsByListLoad(e); |
| 99 | }); |
avm99963 | afda237 | 2021-08-08 20:54:05 +0200 | [diff] [blame] | 100 | window.addEventListener( |
| 101 | createMessageLoadEvent, e => this.handleInvalidationByNewMessage(e)); |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 102 | } |
| 103 | |
avm99963 | afda237 | 2021-08-08 20:54:05 +0200 | [diff] [blame] | 104 | handleInvalidationsByListLoad(e) { |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 105 | var response = e?.detail?.body; |
| 106 | var threads = response?.['1']?.['2']; |
| 107 | if (threads === undefined) { |
| 108 | console.warn( |
| 109 | '[threadListAvatars] The thread list doesn\'t contain any threads.'); |
| 110 | return; |
| 111 | } |
| 112 | |
| 113 | var promises = []; |
| 114 | threads.forEach(t => { |
| 115 | var id = t?.['2']?.['1']?.['1']; |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 116 | var currentLastMessageId = t?.['2']?.['10']; |
| 117 | |
Adrià Vilanova Martínez | d561503 | 2021-07-22 22:19:37 +0200 | [diff] [blame] | 118 | if (id === undefined) return; |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 119 | |
| 120 | promises.push(this.getCacheEntry(id).then(entry => { |
| 121 | if (entry === undefined) return; |
| 122 | |
| 123 | // If the cache entry is still valid. |
Adrià Vilanova Martínez | d561503 | 2021-07-22 22:19:37 +0200 | [diff] [blame] | 124 | if (currentLastMessageId !== undefined && |
| 125 | currentLastMessageId == entry.lastMessageId) { |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 126 | entry.lastUsedTimestamp = Math.floor(Date.now() / 1000); |
| 127 | return this.putCacheEntry(entry).catch(err => { |
| 128 | console.error( |
| 129 | '[threadListAvatars] Error while updating lastUsedTimestamp from thread in cache:', |
| 130 | err); |
| 131 | }); |
| 132 | } |
| 133 | |
| 134 | console.debug( |
| 135 | '[threadListAvatars] Invalidating thread', entry.threadId); |
| 136 | return this.invalidateCacheEntryIfExists(entry.threadId).catch(err => { |
| 137 | console.error( |
| 138 | '[threadListAvatars] Error while invalidating thread from cache:', |
| 139 | err); |
| 140 | }); |
| 141 | })); |
| 142 | }); |
| 143 | |
| 144 | Promise.allSettled(promises).then(() => { |
| 145 | if (Math.random() < probRemoveUnusedCacheEntries) |
| 146 | this.removeUnusedCacheEntries().catch(err => { |
| 147 | console.error( |
| 148 | '[threadListAvatars] Error while removing unused cache entries:', |
| 149 | err); |
| 150 | }); |
| 151 | }); |
| 152 | } |
Adrià Vilanova Martínez | c41edf4 | 2021-07-18 02:06:55 +0200 | [diff] [blame] | 153 | |
avm99963 | afda237 | 2021-08-08 20:54:05 +0200 | [diff] [blame] | 154 | handleInvalidationByNewMessage(e) { |
| 155 | var request = e?.detail?.body; |
| 156 | var threadId = request?.['2']; |
| 157 | if (threadId === undefined) { |
| 158 | console.warn( |
| 159 | '[threadListAvatars] Thread ID couldn\'t be parsed from the CreateMessage request.'); |
| 160 | return; |
| 161 | } |
| 162 | |
| 163 | console.debug( |
| 164 | '[threadListAvatars] Invalidating thread', threadId, |
| 165 | 'due to intercepting a CreateMessage request for that thread.'); |
| 166 | return this.invalidateCacheEntryIfExists(threadId); |
| 167 | } |
| 168 | |
Adrià Vilanova Martínez | c41edf4 | 2021-07-18 02:06:55 +0200 | [diff] [blame] | 169 | // unauthorizedForums methods: |
| 170 | isForumUnauthorized(forumId) { |
| 171 | return this.dbPromise.then(db => db.get('unauthorizedForums', forumId)) |
| 172 | .then(entry => { |
| 173 | if (entry === undefined) return false; |
| 174 | |
| 175 | var now = Math.floor(Date.now() / 1000); |
| 176 | if (entry.expirationTimestamp > now) return true; |
| 177 | |
| 178 | this.invalidateUnauthorizedForum(forumId); |
| 179 | return false; |
| 180 | }); |
| 181 | } |
| 182 | |
| 183 | putUnauthorizedForum(forumId) { |
| 184 | return this.dbPromise.then(db => db.put('unauthorizedForums', { |
| 185 | forumId, |
| 186 | expirationTimestamp: |
| 187 | Math.floor(Date.now() / 1000) + unauthorizedForumExpirationTime, |
| 188 | })); |
| 189 | } |
| 190 | |
| 191 | invalidateUnauthorizedForum(forumId) { |
| 192 | return this.dbPromise.then(db => db.delete('unauthorizedForums', forumId)); |
| 193 | } |
Adrià Vilanova Martínez | 27c6996 | 2021-07-17 23:32:51 +0200 | [diff] [blame] | 194 | }; |