forked from lockb0x-llc/lockbox-codex-forge
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
195 lines (193 loc) · 6.29 KB
/
background.js
File metadata and controls
195 lines (193 loc) · 6.29 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
import { checkDriveFileExists } from "./lib/drive-utils.js";
import {
getGoogleAuthToken,
setGoogleAuthToken,
removeGoogleAuthToken,
getValidGoogleAuthToken,
fetchGoogleUserProfile,
} from "./lib/google-auth-utils.js";
import { handleLargeFileUpload } from "./lib/large-file-handler.js";
import { handleSmallFileUpload } from "./lib/small-file-handler.js";
import { processCodexEntryAndArchive } from "./lib/codex-workflow.js";
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type === "GOOGLE_AUTH_REQUEST") {
chrome.identity.getAuthToken({ interactive: true }, async (token) => {
if (chrome.runtime.lastError || !token) {
const errMsg = chrome.runtime.lastError
? chrome.runtime.lastError.message ||
JSON.stringify(chrome.runtime.lastError)
: "No token returned";
console.error("[background] Google Auth error:", errMsg);
sendResponse({ ok: false, error: errMsg });
} else {
await setGoogleAuthToken(token);
sendResponse({ ok: true, token });
}
});
return true;
}
if (msg.type === "VALIDATE_PAYLOAD_EXISTENCE") {
(async function () {
try {
const { fileId } = msg.payload;
const token = await getGoogleAuthToken();
const metadata = await checkDriveFileExists({ fileId, token });
sendResponse({ ok: true, exists: true, metadata });
} catch (err) {
if (err.message && err.message.includes("401")) {
await removeGoogleAuthToken();
sendResponse({
ok: false,
exists: false,
error: "Google token expired. Please sign in again.",
});
} else {
sendResponse({ ok: false, exists: false, error: err.message });
}
}
})();
return true;
}
if (msg.type === "CREATE_CODEX_FROM_FILE") {
if (
![
"GOOGLE_AUTH_REQUEST",
"VALIDATE_PAYLOAD_EXISTENCE",
"CREATE_CODEX_FROM_FILE",
].includes(msg.type)
) {
sendResponse({ ok: false, error: "Unknown message type" });
return false;
}
(async function () {
const result = await handleSmallFileUpload({ ...msg.payload });
if (result.ok) {
// Archive and upload zip after successful small file upload
console.log(
"[background] Invoking processCodexEntryAndArchive for small file upload",
);
const payloadBytes = new Uint8Array(msg.payload.bytes);
const payloadFilename = msg.payload.filename;
const codexEntry = result.entry;
const storageMetadata = {
location: codexEntry.storage?.location,
tx: codexEntry.anchor?.tx,
url: codexEntry.anchor?.url,
};
const driveToken = msg.payload.googleAuthToken;
let zipResult = null;
try {
zipResult = await processCodexEntryAndArchive({
payloadBytes,
payloadFilename,
codexEntry,
storageMetadata,
driveToken,
});
console.log(
"[background] Zip workflow result (small file):",
zipResult,
);
} catch (err) {
zipResult = { error: err.message };
console.error(
"[background] Error in zip workflow (small file):",
err,
);
}
sendResponse({
ok: true,
entry: result.entry,
payloadDriveInfo: result.payloadDriveInfo,
codexDriveInfo: result.codexDriveInfo,
codexSelfRefInfo: result.codexSelfRefInfo,
zipUploadResult: zipResult?.driveResult || null,
zipError: zipResult?.error || null,
});
} else {
sendResponse({
ok: false,
error: result.error,
details: result.details,
});
}
})();
return true;
}
});
chrome.runtime.onConnect.addListener(function (port) {
let chunks = [];
let metadata = {};
port.onMessage.addListener(async function (msg) {
if (msg.type === "START_LARGE_FILE_UPLOAD") {
metadata = {
filename: msg.filename,
anchorType: msg.anchorType,
googleAuthToken: msg.googleAuthToken,
totalChunks: msg.totalChunks,
createdBy: msg.createdBy,
};
chunks = [];
port.postMessage({ status: "started" });
} else if (msg.type === "LARGE_FILE_CHUNK") {
chunks[msg.chunkIndex] = msg.chunk;
port.postMessage({
status: "chunk-received",
chunkIndex: msg.chunkIndex,
});
} else if (msg.type === "END_LARGE_FILE_UPLOAD") {
const result = await handleLargeFileUpload(metadata, chunks);
if (result.ok) {
// Archive and upload zip after successful large file upload
console.log(
"[background] Invoking processCodexEntryAndArchive for large file upload",
);
// Reconstruct payload bytes from chunks
const payloadBytes = new Uint8Array([].concat(...chunks));
const payloadFilename = metadata.filename;
const codexEntry = result.entry;
const storageMetadata = {
location: codexEntry.storage?.location,
tx: codexEntry.anchor?.tx,
url: codexEntry.anchor?.url,
};
const driveToken = metadata.googleAuthToken;
let zipResult = null;
try {
zipResult = await processCodexEntryAndArchive({
payloadBytes,
payloadFilename,
codexEntry,
storageMetadata,
driveToken,
});
console.log(
"[background] Zip workflow result (large file):",
zipResult,
);
} catch (err) {
zipResult = { error: err.message };
console.error(
"[background] Error in zip workflow (large file):",
err,
);
}
port.postMessage({
ok: true,
entry: result.entry,
payloadDriveInfo: result.payloadDriveInfo,
codexDriveInfo: result.codexDriveInfo,
codexSelfRefInfo: result.codexSelfRefInfo,
zipUploadResult: zipResult?.driveResult || null,
zipError: zipResult?.error || null,
});
} else {
port.postMessage({
ok: false,
error: result.error,
details: result.details,
});
}
}
});
});