-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
316 lines (284 loc) · 10.1 KB
/
Copy pathbackground.js
File metadata and controls
316 lines (284 loc) · 10.1 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
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
// background.js — service worker. Owns the queue and the timer.
//
// Timing model: instead of one repeating chrome.alarms period, we schedule a
// single one-shot alarm after every successful send, with a delay chosen
// randomly between minIntervalSeconds and maxIntervalSeconds. That gives a
// different (randomized) gap each time instead of a fixed cadence. A manual
// "Next" click cancels whatever alarm is pending, fires immediately, and
// then re-schedules the following one from that new point in time.
//
// chrome.alarms only accepts minutes, so seconds are converted on the way in
// (delayInMinutes: seconds / 60). Chrome enforces a hard 1-minute floor for
// alarms in extensions installed from the Web Store, but relaxes that for
// unpacked/developer-mode extensions (which is how this is loaded) — so
// sub-minute delays work here, just don't expect second-level precision.
const ALARM_NAME = "sunoQueueAlarm";
const STORAGE_KEY = "state";
const DEFAULT_URL = "https://suno.com/create";
const MIN_ALLOWED_SECONDS = 5; // floor to keep things sane / avoid hammering Suno
// Make the toolbar icon open the side panel directly instead of a popup.
// (Side panel stays docked and open across tab switches; a popup would close
// the moment focus moves to the Suno tab, which is annoying mid-queue.)
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }).catch(() => {});
function defaultState() {
return {
queue: [],
index: 0,
running: false,
busy: false,
instrumental: true,
minIntervalSeconds: 60,
maxIntervalSeconds: 60,
nextFireAt: null,
targetUrl: DEFAULT_URL,
log: [],
};
}
async function getState() {
const data = await chrome.storage.local.get(STORAGE_KEY);
return { ...defaultState(), ...(data[STORAGE_KEY] || {}) };
}
async function setState(patch) {
const state = await getState();
const next = { ...state, ...patch };
await chrome.storage.local.set({ [STORAGE_KEY]: next });
return next;
}
function withLog(state, message, level = "info") {
const entry = { time: Date.now(), message, level };
return [...(state.log || []), entry].slice(-80);
}
function updateBadge(state) {
if (!state.running) {
chrome.action.setBadgeText({ text: "" });
return;
}
chrome.action.setBadgeText({ text: `${state.index}/${state.queue.length}` });
chrome.action.setBadgeBackgroundColor({ color: "#5b47e0" });
}
function pickDelaySeconds(state) {
const min = Math.max(MIN_ALLOWED_SECONDS, Number(state.minIntervalSeconds) || MIN_ALLOWED_SECONDS);
const max = Math.max(min, Number(state.maxIntervalSeconds) || min);
if (max <= min) return min;
return min + Math.random() * (max - min);
}
async function scheduleNextAlarm() {
const state = await getState();
if (!state.running || state.index >= state.queue.length) {
chrome.alarms.clear(ALARM_NAME);
await setState({ nextFireAt: null });
return;
}
const delaySeconds = pickDelaySeconds(state);
await setState({ nextFireAt: Date.now() + delaySeconds * 1000 });
chrome.alarms.create(ALARM_NAME, { delayInMinutes: delaySeconds / 60 });
}
// ---- messaging ----------------------------------------------------------
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message.type === "START") {
(async () => {
let state = await getState();
state = await setState({
queue: message.queue,
index: 0,
running: true,
instrumental: message.instrumental,
minIntervalSeconds: message.minIntervalSeconds,
maxIntervalSeconds: message.maxIntervalSeconds,
targetUrl: message.targetUrl,
log: withLog(
state,
`Старт черги: ${message.queue.length} промпт(ів), інтервал ${message.minIntervalSeconds}-${message.maxIntervalSeconds} сек, режим: ${message.instrumental ? "Instrumental" : "як на сторінці"}`
),
});
updateBadge(state);
await processOne();
await scheduleNextAlarm();
sendResponse({ ok: true });
})();
return true;
}
if (message.type === "NEXT") {
(async () => {
chrome.alarms.clear(ALARM_NAME);
const before = await getState();
if (before.index >= before.queue.length) {
sendResponse({ ok: false, error: "Черга порожня" });
return;
}
await processOne();
const state = await getState();
if (state.running) await scheduleNextAlarm();
sendResponse({ ok: true });
})();
return true;
}
if (message.type === "STOP") {
(async () => {
chrome.alarms.clear(ALARM_NAME);
const state = await getState();
const next = await setState({ running: false, nextFireAt: null, log: withLog(state, "Зупинено користувачем") });
updateBadge(next);
sendResponse({ ok: true });
})();
return true;
}
if (message.type === "RESET") {
(async () => {
chrome.alarms.clear(ALARM_NAME);
const next = await setState({ queue: [], index: 0, running: false, busy: false, nextFireAt: null, log: [] });
updateBadge(next);
sendResponse({ ok: true });
})();
return true;
}
if (message.type === "GET_STATE") {
(async () => {
sendResponse(await getState());
})();
return true;
}
return undefined;
});
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name !== ALARM_NAME) return;
(async () => {
await processOne();
await scheduleNextAlarm();
})();
});
// ---- tab / content-script plumbing --------------------------------------
function waitForTabComplete(tabId, timeoutMs = 20000) {
return new Promise((resolve) => {
let done = false;
function listener(id, info) {
if (id === tabId && info.status === "complete" && !done) {
done = true;
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
}
chrome.tabs.onUpdated.addListener(listener);
setTimeout(() => {
if (!done) {
done = true;
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
}, timeoutMs);
});
}
async function findOrCreateTab(targetUrl) {
const tabs = await chrome.tabs.query({ url: "https://suno.com/create*" });
let tab = tabs[0];
if (!tab) {
tab = await chrome.tabs.create({ url: targetUrl, active: false });
await waitForTabComplete(tab.id);
} else if (tab.status !== "complete") {
await waitForTabComplete(tab.id);
}
return tab;
}
async function ensureContentScript(tabId) {
// Tabs opened before the extension was installed/reloaded never got the
// declarative content script injected. (Re-)injecting is safe: content.js
// guards itself against registering its listener twice.
try {
await chrome.scripting.executeScript({ target: { tabId }, files: ["content.js"] });
} catch (err) {
// Injection can fail if the tab is a chrome:// page, still loading, etc.
// Fall through and let the retry loop below surface a real error.
}
}
async function sendToContentWithRetry(tabId, message, attempts = 6) {
let lastError;
for (let i = 0; i < attempts; i += 1) {
if (i === 0 || lastError) {
// eslint-disable-next-line no-await-in-loop
await ensureContentScript(tabId);
}
try {
// eslint-disable-next-line no-await-in-loop
const res = await chrome.tabs.sendMessage(tabId, message);
if (res) return res;
} catch (err) {
lastError = err;
}
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => setTimeout(resolve, 1000));
}
throw new Error(
`Немає відповіді від сторінки Suno (${lastError ? lastError.message : "content-script не готовий"}). Онови вкладку suno.com/create і спробуй ще раз.`
);
}
// ---- core: send exactly one prompt ---------------------------------------
let processing = false;
async function processOne() {
if (processing) return { skipped: true };
processing = true;
await setState({ busy: true });
try {
let state = await getState();
if (state.index >= state.queue.length) {
await setState({ busy: false });
return { done: true };
}
const prompt = state.queue[state.index];
let tab;
try {
tab = await findOrCreateTab(state.targetUrl || DEFAULT_URL);
} catch (err) {
chrome.alarms.clear(ALARM_NAME);
state = await setState({
running: false,
busy: false,
nextFireAt: null,
log: withLog(state, `Помилка вкладки: ${err.message}`, "error"),
});
updateBadge(state);
return { error: err.message };
}
let result;
try {
result = await sendToContentWithRetry(tab.id, {
action: "sunoGenerate",
prompt,
instrumental: state.instrumental,
});
} catch (err) {
result = { ok: false, error: err.message };
}
state = await getState();
if (result && result.ok) {
const nextIndex = state.index + 1;
const creditsNote = result.credits != null ? ` (кредитів залишилось ≈${result.credits})` : "";
state = await setState({
index: nextIndex,
busy: false,
log: withLog(state, `[${nextIndex}/${state.queue.length}] Відправлено: ${prompt.slice(0, 70)}${creditsNote}`),
});
updateBadge(state);
if (nextIndex >= state.queue.length) {
chrome.alarms.clear(ALARM_NAME);
state = await setState({
running: false,
nextFireAt: null,
log: withLog(state, `Готово: згенеровано ${state.queue.length}/${state.queue.length}`),
});
updateBadge(state);
}
return { ok: true };
}
chrome.alarms.clear(ALARM_NAME);
state = await setState({
running: false,
busy: false,
nextFireAt: null,
log: withLog(state, `Зупинено через помилку на промпті ${state.index + 1}: ${result ? result.error : "невідома помилка"}`, "error"),
});
updateBadge(state);
return { error: result ? result.error : "unknown" };
} finally {
processing = false;
}
}