-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstashify.js
More file actions
316 lines (287 loc) · 11 KB
/
Copy pathstashify.js
File metadata and controls
316 lines (287 loc) · 11 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
// Stashify — Stash UI widget.
// Adds an on-scene-page panel: a button to decensor the current scene via the
// worker container, a live progress bar, then a review player with
// "Replace original" / "Discard". Self-contained (no csLib/PluginApi coupling)
// so it survives Stash version changes: it reads the scene id from the URL and
// renders a fixed panel rather than patching internal components.
(function () {
"use strict";
var PLUGIN_ID = "stashify";
var POLL_MS = 1500;
var cfgCache = null;
var current = { sceneId: null, jobId: null, timer: null };
var MIXED_MSG = "Mixed content: Stash is loaded over HTTPS but the Worker URL is HTTP. " +
"Browsers block that. Open Stash over http:// on your LAN, or serve the worker over HTTPS.";
function mixedContent(url) {
return location.protocol === "https:" && /^http:\/\//i.test(url || "");
}
// ---- helpers ----------------------------------------------------------- //
function sceneIdFromUrl() {
var m = location.pathname.match(/\/scenes\/(\d+)/);
return m ? m[1] : null;
}
async function stashGQL(query, variables) {
var r = await fetch("/graphql", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "same-origin",
body: JSON.stringify({ query: query, variables: variables || {} }),
});
var j = await r.json();
if (j.errors && j.errors.length) throw new Error(j.errors[0].message);
return j.data;
}
async function loadConfig(force) {
if (!force && cfgCache && cfgCache.url) return cfgCache;
var data = await stashGQL("query { configuration { plugins } }");
var p = ((data.configuration || {}).plugins || {})[PLUGIN_ID] || {};
cfgCache = {
url: (p.workerUrl || "").replace(/\/+$/, ""),
token: p.workerToken || "",
};
return cfgCache;
}
// Low-level GET used by the connection test (returns status in the error so
// we can tell a rejected token from an unreachable worker).
async function rawWorker(cfg, path, token) {
var headers = {};
if (token) headers["X-Decensor-Token"] = token;
var r = await fetch(cfg.url + path, { headers: headers });
var text = await r.text();
var b;
try { b = text ? JSON.parse(text) : {}; }
catch (e) {
// A reverse proxy in front of the worker may return HTML/plain text for 5xx.
if (!r.ok) throw new Error(String(r.status)); // keep status leading for the 401 check
throw new Error("worker returned non-JSON (HTTP " + r.status + ")");
}
if (!r.ok) throw new Error(r.status + (b.error ? " " + b.error : ""));
return b;
}
async function testConnection(out) {
out.className = "decensor-test-result";
out.textContent = "Testing…";
var cfg;
try {
cfg = await loadConfig(true); // re-read settings in case they just changed
} catch (e) {
out.className = "decensor-test-result decensor-err";
out.textContent = "Config error: " + (e.message || e);
return;
}
if (!cfg.url) {
out.className = "decensor-test-result decensor-err";
out.textContent = "Set the Worker URL in the plugin settings first.";
return;
}
if (mixedContent(cfg.url)) {
out.className = "decensor-test-result decensor-err";
out.textContent = "✗ " + MIXED_MSG;
return;
}
// 1) reachability + CORS (health needs no token)
var health;
try {
health = await rawWorker(cfg, "/api/health");
} catch (e) {
out.className = "decensor-test-result decensor-err";
out.textContent = "✗ Can't reach worker at " + cfg.url + "\n" + (e.message || e) +
"\nCheck the URL, that the container is running, and CORS/CSP.";
return;
}
// 2) token check via an authed endpoint
var tokenMsg;
try {
await rawWorker(cfg, "/api/jobs", cfg.token);
tokenMsg = cfg.token ? "token OK" : "no token set";
} catch (e) {
if (/^401/.test(String(e.message))) {
out.className = "decensor-test-result decensor-err";
out.textContent = "✗ Reached the worker, but the token was rejected.\n" +
"Match Worker Token to the container's WORKER_TOKEN.";
return;
}
tokenMsg = "jobs check failed: " + (e.message || e);
}
out.className = "decensor-test-result decensor-ok";
out.textContent = "✓ Connected — backend " + health.backend + ", GPU " + health.gpu +
", upscale " + (health.postUpscale ? "on" : "off") + " · " + tokenMsg;
}
async function workerFetch(path, opts) {
var cfg = await loadConfig();
if (!cfg.url) throw new Error("Set the Worker URL in Settings > Plugins > Stashify.");
if (mixedContent(cfg.url)) throw new Error(MIXED_MSG);
opts = opts || {};
var headers = Object.assign({ "Content-Type": "application/json" }, opts.headers || {});
if (cfg.token) headers["X-Decensor-Token"] = cfg.token;
var r = await fetch(cfg.url + path, Object.assign({}, opts, { headers: headers }));
var text = await r.text();
var body;
try { body = text ? JSON.parse(text) : {}; }
catch (e) { throw new Error("worker HTTP " + r.status + (r.ok ? " (non-JSON response)" : "")); }
if (!r.ok) throw new Error(body.error || ("worker HTTP " + r.status));
return body;
}
// ---- panel ------------------------------------------------------------- //
function el(tag, cls, html) {
var e = document.createElement(tag);
if (cls) e.className = cls;
if (html != null) e.innerHTML = html;
return e;
}
function ensurePanel() {
var panel = document.getElementById("decensor-panel");
if (panel) return panel;
panel = el("div", "decensor-panel");
panel.id = "decensor-panel";
panel.innerHTML =
'<div class="decensor-head">' +
'<span class="decensor-title">🩹 Stashify</span>' +
'<button class="decensor-x" title="hide">×</button>' +
"</div>" +
'<div class="decensor-body"></div>';
document.body.appendChild(panel);
panel.querySelector(".decensor-x").onclick = function () {
panel.classList.add("decensor-hidden");
};
return panel;
}
function body() {
return ensurePanel().querySelector(".decensor-body");
}
function showIdle() {
ensurePanel().classList.remove("decensor-hidden");
var b = body();
b.innerHTML = "";
var btn = el("button", "decensor-btn decensor-primary", "Decensor this scene");
btn.onclick = startJob;
b.appendChild(btn);
var test = el("button", "decensor-btn decensor-test", "Test connection");
var result = el("div", "decensor-test-result");
test.onclick = function () { testConnection(result); };
b.appendChild(test);
b.appendChild(result);
b.appendChild(el("div", "decensor-note", "Runs DeepMosaics" +
" → Real-ESRGAN on the worker, then lets you review before replacing."));
}
function showProgress(job) {
var b = body();
b.innerHTML = "";
var pct = Math.round((job.progress || 0) * 100);
b.appendChild(el("div", "decensor-msg", job.message || job.state));
var bar = el("div", "decensor-bar");
bar.appendChild(el("div", "decensor-fill")).style.width = pct + "%";
b.appendChild(bar);
b.appendChild(el("div", "decensor-note", pct + "%"));
}
function showReview(job) {
var b = body();
b.innerHTML = "";
b.appendChild(el("div", "decensor-msg", "Preview ready — review it:"));
if (job.review_scene_id) {
var v = el("video", "decensor-video");
v.controls = true;
v.preload = "metadata";
v.src = "/scene/" + job.review_scene_id + "/stream";
b.appendChild(v);
}
var row = el("div", "decensor-row");
var replace = el("button", "decensor-btn decensor-danger", "Replace original");
var discard = el("button", "decensor-btn", "Discard");
// Disable both immediately so a fast double-click can't fire two requests.
replace.onclick = function () { replace.disabled = true; discard.disabled = true; action("replace"); };
discard.onclick = function () { replace.disabled = true; discard.disabled = true; action("discard"); };
row.appendChild(replace);
row.appendChild(discard);
b.appendChild(row);
b.appendChild(el("div", "decensor-note",
"Replace overwrites the original file in place (no backup); tags & history are kept."));
}
function showDone(msg, reload) {
var b = body();
b.innerHTML = "";
b.appendChild(el("div", "decensor-msg decensor-ok", msg));
if (reload) setTimeout(function () { location.reload(); }, 1200);
else setTimeout(showIdle, 1400);
}
function showError(msg) {
var b = body();
b.innerHTML = "";
b.appendChild(el("div", "decensor-msg decensor-err", msg));
var retry = el("button", "decensor-btn", "Back");
retry.onclick = showIdle;
b.appendChild(retry);
}
// ---- job lifecycle ----------------------------------------------------- //
function stopPolling() {
if (current.timer) { clearInterval(current.timer); current.timer = null; }
}
function poll() {
stopPolling();
current.timer = setInterval(async function () {
try {
var job = await workerFetch("/api/jobs/" + current.jobId);
if (job.state === "running" || job.state === "queued" ||
job.state === "replacing" || job.state === "discarding") {
showProgress(job);
} else if (job.state === "review_ready") {
stopPolling();
showReview(job);
} else if (job.state === "replaced") {
stopPolling();
showDone("Original replaced ✓", true);
} else if (job.state === "discarded") {
stopPolling();
showDone("Preview discarded", false);
} else if (job.state === "error") {
stopPolling();
showError(job.error || job.message || "Failed");
}
} catch (e) {
stopPolling();
showError(String(e.message || e));
}
}, POLL_MS);
}
async function startJob() {
try {
showProgress({ progress: 0, message: "Submitting…" });
var job = await workerFetch("/api/decensor", {
method: "POST",
body: JSON.stringify({ scene_id: current.sceneId }),
});
current.jobId = job.id;
poll();
} catch (e) {
showError(String(e.message || e));
}
}
async function action(kind) {
try {
showProgress({ progress: 0, message: kind === "replace" ? "Replacing…" : "Discarding…" });
await workerFetch("/api/jobs/" + current.jobId + "/" + kind, { method: "POST" });
poll();
} catch (e) {
showError(String(e.message || e));
}
}
// ---- route watching ---------------------------------------------------- //
function tick() {
var sceneId = sceneIdFromUrl();
var panel = document.getElementById("decensor-panel");
if (!sceneId) {
if (panel) panel.remove();
stopPolling();
current = { sceneId: null, jobId: null, timer: null };
return;
}
if (sceneId !== current.sceneId) {
// navigated to a different scene: reset
stopPolling();
current = { sceneId: sceneId, jobId: null, timer: null };
showIdle();
}
}
setInterval(tick, 700);
tick();
})();