Repository navigation
Expand file tree
/
Copy pathupdate.js
More file actions
270 lines (247 loc) · 8.51 KB
/
Copy pathupdate.js
File metadata and controls
270 lines (247 loc) · 8.51 KB
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
// =============================================================================
// Chat Archive — Update page
// =============================================================================
// Writes the latest GitHub main archive into the unpacked extension folder
// the user loaded, then reloads the extension. Chrome does not auto-update
// unpacked extensions, and a popup cannot keep a folder picker open.
const statusEl = document.getElementById('status');
const currentEl = document.getElementById('currentVersion');
const latestEl = document.getElementById('latestVersion');
const folderEl = document.getElementById('folderStatus');
const updateBtn = document.getElementById('updateBtn');
const chooseBtn = document.getElementById('chooseBtn');
const checkBtn = document.getElementById('checkBtn');
let latestVersion = null;
let busy = false;
function showStatus(type, text) {
statusEl.className = `status ${type}`;
statusEl.textContent = text;
}
function setBusy(on) {
busy = on;
updateBtn.disabled = on || !canUpdate();
chooseBtn.disabled = on;
checkBtn.disabled = on;
}
function canUpdate() {
const current = readInstalledVersion();
return !!(latestVersion && current && isNewer(latestVersion, current));
}
function renderVersions() {
const current = readInstalledVersion();
currentEl.textContent = current || 'Unknown';
latestEl.textContent = latestVersion || 'Unknown';
if (!current) {
showStatus('error', 'This page has to be opened from the Chat Archive extension.');
updateBtn.disabled = true;
return;
}
if (!latestVersion) return;
if (isNewer(latestVersion, current)) {
showStatus('warning', `Version ${latestVersion} is ready to install.`);
updateBtn.disabled = busy;
updateBtn.textContent = `Update to ${latestVersion}`;
} else if (compareVersions(latestVersion, current) === 0) {
showStatus('success', `You're on the latest version (${current}).`);
updateBtn.disabled = true;
updateBtn.textContent = 'Up to date';
} else {
showStatus('info', `This copy (${current}) is newer than GitHub (${latestVersion}).`);
updateBtn.disabled = true;
updateBtn.textContent = 'Up to date';
}
}
function openHandleDb() {
return new Promise((resolve, reject) => {
const req = indexedDB.open(UPDATE_DIR_DB, 1);
req.onupgradeneeded = () => {
req.result.createObjectStore(UPDATE_DIR_STORE);
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async function readStoredDir() {
const db = await openHandleDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(UPDATE_DIR_STORE, 'readonly');
const req = tx.objectStore(UPDATE_DIR_STORE).get(UPDATE_DIR_KEY);
req.onsuccess = () => resolve(req.result || null);
req.onerror = () => reject(req.error);
});
}
async function storeDir(handle) {
const db = await openHandleDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(UPDATE_DIR_STORE, 'readwrite');
tx.objectStore(UPDATE_DIR_STORE).put(handle, UPDATE_DIR_KEY);
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
});
}
async function assertChatArchiveDir(dirHandle) {
let manifestHandle;
try {
manifestHandle = await dirHandle.getFileHandle('manifest.json');
} catch (err) {
if (err && err.name === 'NotFoundError') {
throw new Error('That folder is not the Chat Archive extension.');
}
throw err;
}
const manifest = JSON.parse(await (await manifestHandle.getFile()).text());
if (manifest.name !== 'Chat Archive') {
throw new Error('That folder is not the Chat Archive extension.');
}
return manifest;
}
async function refreshFolderStatus() {
if (!window.showDirectoryPicker) {
folderEl.textContent = 'This browser cannot write the extension folder. Download the zip from GitHub instead.';
return;
}
try {
const handle = await readStoredDir();
if (!handle) {
folderEl.textContent = 'No folder chosen yet. Update will ask for the folder you loaded in chrome://extensions.';
return;
}
const perm = await handle.queryPermission({ mode: 'readwrite' });
if (perm === 'granted') {
folderEl.textContent = `Folder ready: ${handle.name}`;
} else {
folderEl.textContent = `Folder remembered: ${handle.name}. Update will ask to use it again.`;
}
} catch {
folderEl.textContent = 'No folder chosen yet.';
}
}
async function chooseFolder() {
const handle = await showDirectoryPicker({
id: 'chat-archive-root',
mode: 'readwrite',
});
await assertChatArchiveDir(handle);
await storeDir(handle);
folderEl.textContent = `Folder ready: ${handle.name}`;
return handle;
}
async function ensureExtensionDir() {
let handle = await readStoredDir();
if (handle) {
let perm = await handle.queryPermission({ mode: 'readwrite' });
if (perm !== 'granted') {
perm = await handle.requestPermission({ mode: 'readwrite' });
}
if (perm !== 'granted') handle = null;
}
if (!handle) handle = await chooseFolder();
await assertChatArchiveDir(handle);
return handle;
}
async function writeRelativeFile(dirHandle, relativePath, bytes) {
const parts = relativePath.split('/');
let dir = dirHandle;
for (let i = 0; i < parts.length - 1; i++) {
dir = await dir.getDirectoryHandle(parts[i], { create: true });
}
const fileHandle = await dir.getFileHandle(parts[parts.length - 1], { create: true });
const writable = await fileHandle.createWritable();
await writable.write(bytes);
await writable.close();
}
async function applyArchive(dirHandle, arrayBuffer) {
if (typeof JSZip === 'undefined') {
throw new Error('Could not read the update archive.');
}
const zip = await JSZip.loadAsync(arrayBuffer);
const entries = [];
zip.forEach((relativePath, entry) => {
const stripped = stripArchiveRoot(relativePath);
if (!entry.dir && isSafeRelativePath(stripped)) {
entries.push({ path: stripped, entry });
}
});
if (!entries.some((item) => item.path === 'manifest.json')) {
throw new Error('Download did not contain the Chat Archive extension.');
}
let written = 0;
for (const item of entries) {
const bytes = await item.entry.async('uint8array');
await writeRelativeFile(dirHandle, item.path, bytes);
written += 1;
if (written % 10 === 0 || written === entries.length) {
showStatus('info', `Writing files… ${written} of ${entries.length}`);
}
}
return written;
}
async function runUpdate() {
if (busy || !canUpdate()) return;
if (!window.showDirectoryPicker) {
showStatus('error', 'Folder updates need Chrome or another Chromium browser.');
return;
}
setBusy(true);
try {
showStatus('info', 'Choose the Chat Archive folder if asked, then wait.');
const dir = await ensureExtensionDir();
showStatus('info', 'Downloading the update…');
const res = await fetch(UPDATE_ARCHIVE_URL, {
cache: 'no-store',
signal: AbortSignal.timeout(60_000),
});
if (!res.ok) throw new Error(`Download failed (${res.status}).`);
const written = await applyArchive(dir, await res.arrayBuffer());
showStatus('success', `Updated ${written} files. Reloading the extension…`);
chrome.runtime.reload();
} catch (err) {
setBusy(false);
if (err && err.name === 'AbortError') {
showStatus('info', 'Folder choice cancelled.');
} else {
showStatus('error', err.message || 'Update failed.');
}
}
}
async function checkNow() {
if (busy) return;
setBusy(true);
showStatus('info', 'Checking GitHub…');
try {
latestVersion = await getLatestVersion({ force: true });
busy = false;
chooseBtn.disabled = false;
checkBtn.disabled = false;
renderVersions();
} catch (err) {
busy = false;
chooseBtn.disabled = false;
checkBtn.disabled = false;
latestEl.textContent = 'Unavailable';
updateBtn.disabled = true;
showStatus('error', err.message || 'Update check failed.');
}
}
checkBtn.addEventListener('click', checkNow);
chooseBtn.addEventListener('click', async () => {
if (busy) return;
setBusy(true);
try {
await chooseFolder();
setBusy(false);
renderVersions();
} catch (err) {
setBusy(false);
if (err && err.name === 'AbortError') {
showStatus('info', 'Folder choice cancelled.');
} else {
showStatus('error', err.message || 'Could not use that folder.');
}
}
});
updateBtn.addEventListener('click', runUpdate);
currentEl.textContent = readInstalledVersion() || 'Unknown';
latestEl.textContent = 'Checking…';
refreshFolderStatus();
checkNow();