-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglitchwave-csv-tracker.user.js
More file actions
458 lines (403 loc) · 13.5 KB
/
glitchwave-csv-tracker.user.js
File metadata and controls
458 lines (403 loc) · 13.5 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// ==UserScript==
// @name Glitchwave Game CSV Tracker
// @namespace https://github.com/dbeley/rym-userscripts
// @version 1.1.0
// @description Capture game metadata on Glitchwave pages and keep a CSV in sync (auto-save or manual download).
// @author dbeley
// @match https://glitchwave.com/game/*
// @match https://glitchwave.com/charts/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant GM_download
// @run-at document-idle
// ==/UserScript==
(function () {
"use strict";
const STORAGE_KEY = "glitchwave-csv::records";
const DB_NAME = "glitchwave-csv";
const STORE_NAME = "handles";
const FILE_KEY = "csv-output";
GM_registerMenuCommand("Set CSV output file", () => {
pickCsvFile(true).catch(console.error);
});
GM_registerMenuCommand("Download CSV once", () => {
downloadCsv().catch(console.error);
});
main().catch(console.error);
async function main() {
// Check if we're on a chart page
if (window.location.pathname.includes("/charts/")) {
const records = extractChartRecords();
if (records.length > 0) {
for (const record of records) {
await upsertRecord(record);
}
console.info(
`[glitchwave-csv] Recorded ${records.length} games from chart page`
);
await writeCsvToDisk();
}
return;
}
// Otherwise, extract from game page
const record = extractGameRecord();
if (!record) return;
await upsertRecord(record);
console.info(
`[glitchwave-csv] Recorded ${record.name || "unknown"} (${record.slug}) updated at ${record.updatedAt}`
);
await writeCsvToDisk();
}
function extractGameRecord() {
const scriptNodes = Array.from(
document.querySelectorAll('script[type="application/ld+json"]')
);
for (const node of scriptNodes) {
try {
const parsed = JSON.parse(node.textContent);
if (parsed && parsed["@type"] === "VideoGame") {
return buildRecord(parsed);
}
} catch (_) {
/* ignore malformed JSON blocks */
}
}
console.warn("[glitchwave-csv] No VideoGame JSON-LD block found.");
return null;
}
function buildRecord(json) {
const aggregate = json.aggregateRating || {};
const urlFromJson = json.url || location.href;
const urlObj = new URL(urlFromJson, location.href);
const url = urlObj.href;
const slug =
(json["@id"] && json["@id"].split("/").filter(Boolean).pop()) ||
urlObj.pathname.split("/").filter(Boolean).pop();
const now = new Date().toISOString();
return {
slug: slug || "",
name: (json.name || "").trim(),
url,
description: json.description || "",
releaseDate: json.datePublished || "",
genres: toList(json.genre),
platforms: toList(json.gamePlatform),
operatingSystems: toList(json.operatingSystem),
image: json.image || "",
ratingValue: aggregate.ratingValue ?? "",
ratingCount: aggregate.ratingCount ?? "",
reviewCount: aggregate.reviewCount ?? "",
updatedAt: now,
};
}
function extractChartRecords() {
// Look for chart cards in the Glitchwave format
const chartCards = document.querySelectorAll(".chart_card_top");
const records = [];
chartCards.forEach((card) => {
const link = card.querySelector(".chart_title a.game");
if (!link) return;
const url = new URL(link.href, location.href).href;
const slug = new URL(url).pathname.split("/").filter(Boolean).pop();
if (!slug) return;
const name = link.textContent.trim();
// Get the parent container to find metadata
const container = card.parentElement;
if (!container) return;
// Extract release date
const dateNode = card.querySelector(".chart_release_date");
const releaseDate = dateNode ? dateNode.textContent.trim() : "";
// Extract rating info
const ratingNode = container.querySelector(
".chart_card_score .rating_number"
);
const ratingValue = ratingNode ? ratingNode.textContent.trim() : "";
const ratingsText = container.querySelector(".chart_card_ratings b");
const ratingCount = ratingsText ? ratingsText.textContent.trim() : "";
const reviewsText = container.querySelector(".chart_card_reviews b");
const reviewCount = reviewsText ? reviewsText.textContent.trim() : "";
// Extract genres
const genreNodes = card.querySelectorAll(".chart_genres a.genre_");
const genres = Array.from(genreNodes)
.map((node) => node.textContent.trim())
.filter(Boolean)
.join("; ");
// Extract image
const imageDiv = container.querySelector(".chart_card_image");
let image = "";
if (imageDiv) {
const bgUrl =
imageDiv.style.backgroundImage ||
imageDiv.getAttribute("data-delayloadurl2x") ||
imageDiv.getAttribute("data-delayloadurl");
if (bgUrl) {
// Extract URL from url('...') or just use the value
const match = bgUrl.match(/url\(['"]?([^'"]+)['"]?\)/);
image = match ? match[1] : bgUrl;
}
}
const now = new Date().toISOString();
records.push({
slug,
name,
url,
description: "", // Not available on chart items
releaseDate,
genres,
platforms: "", // Not available on chart items
operatingSystems: "", // Not available on chart items
image,
ratingValue,
ratingCount,
reviewCount,
updatedAt: now,
isPartial: true, // Mark as partial data
});
});
return records;
}
async function upsertRecord(record) {
const records = await loadRecords();
const existing = records[record.slug] || {};
// If the new record is partial, only update fields that have values
// and preserve full data if it exists
if (record.isPartial && !existing.isPartial) {
// Merge partial data into full data, keeping full data when available
records[record.slug] = {
...existing,
slug: record.slug, // Ensure slug is always set
// Only update these fields from partial data if they're not empty
...(record.name && { name: record.name }),
...(record.releaseDate && { releaseDate: record.releaseDate }),
...(record.ratingValue && { ratingValue: record.ratingValue }),
...(record.ratingCount && { ratingCount: record.ratingCount }),
...(record.reviewCount && { reviewCount: record.reviewCount }),
...(record.genres && { genres: record.genres }),
...(record.image && { image: record.image }),
// Update URL only if it's different
...(record.url && record.url !== existing.url && { url: record.url }),
updatedAt: record.updatedAt,
firstSeen: existing.firstSeen || record.updatedAt,
};
} else {
// Full data or both partial - do normal merge
const merged = {
...existing,
...record,
firstSeen: existing.firstSeen || record.updatedAt,
};
// If incoming record doesn't have isPartial property, remove the flag
if (record.isPartial === undefined) {
delete merged.isPartial;
}
records[record.slug] = merged;
}
await saveRecords(records);
}
function toList(value) {
if (Array.isArray(value)) return value.join("; ");
if (typeof value === "string") return value;
return "";
}
async function loadRecords() {
try {
const stored = await GM_getValue(STORAGE_KEY, {});
return stored || {};
} catch (_) {
return {};
}
}
async function saveRecords(records) {
try {
await GM_setValue(STORAGE_KEY, records);
} catch (err) {
console.error("[glitchwave-csv] Unable to persist records", err);
}
}
function buildCsv(records) {
const headers = [
"name",
"slug",
"url",
"releaseDate",
"ratingValue",
"ratingCount",
"reviewCount",
"genres",
"platforms",
"operatingSystems",
"image",
"firstSeen",
"updatedAt",
"description",
];
const rows = Object.values(records)
.sort((a, b) => a.name.localeCompare(b.name))
.map((entry) =>
headers.map((key) => escapeCsv(entry[key] ?? "")).join(",")
);
return [headers.join(","), ...rows].join("\n");
}
function escapeCsv(value) {
const str = String(value ?? "");
if (/[",\n]/.test(str)) {
return `"${str.replace(/"/g, '""')}"`;
}
return str;
}
async function writeCsvToDisk() {
const records = await loadRecords();
const csv = buildCsv(records);
const handle = await loadStoredHandle();
if (!handle) {
console.info(
"[glitchwave-csv] Pick an output file via the menu to auto-save the CSV."
);
return;
}
const permission = await ensurePermission(handle);
if (permission !== "granted") {
console.warn(
"[glitchwave-csv] File permission was denied. Re-select the output file."
);
return;
}
const writable = await handle.createWritable();
await writable.write(csv);
await writable.close();
console.debug("[glitchwave-csv] CSV written to disk.");
}
async function ensurePermission(handle) {
if (!handle.queryPermission || !handle.requestPermission) return "denied";
let status = await handle.queryPermission({ mode: "readwrite" });
if (status === "granted") return status;
if (status === "prompt") {
try {
status = await handle.requestPermission({ mode: "readwrite" });
} catch (_) {
status = "denied";
}
}
return status;
}
async function pickCsvFile(writeCurrentCsv = false) {
if (!window.showSaveFilePicker) {
alert(
"Your browser does not support the File System Access API. Use the 'Download CSV once' menu instead."
);
return;
}
const handle = await window.showSaveFilePicker({
suggestedName: "glitchwave-games.csv",
types: [
{
description: "CSV file",
accept: { "text/csv": [".csv"] },
},
],
});
await storeHandle(handle);
if (writeCurrentCsv) {
await writeCsvToDisk();
}
}
async function downloadCsv() {
const records = await loadRecords();
const csv = buildCsv(records);
console.info(
`[glitchwave-csv] Download command triggered (records=${
Object.keys(records).length || 0
})`
);
const filename = "glitchwave-games.csv";
const blob = new Blob([csv], { type: "text/csv" });
const blobUrl = URL.createObjectURL(blob);
const isFirefox =
typeof navigator === "object" && /Firefox/.test(navigator.userAgent);
const attempts = [
async () => {
if (isFirefox) throw new Error("skip GM_download on Firefox");
if (typeof GM_download !== "function")
throw new Error("GM_download missing");
await GM_download({ url: blobUrl, name: filename, saveAs: true });
console.info("[glitchwave-csv] GM_download succeeded.");
},
async () => {
const anchor = document.createElement("a");
anchor.href = blobUrl;
anchor.download = filename;
anchor.style.display = "none";
document.body.append(anchor);
anchor.dispatchEvent(
new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true,
})
);
anchor.click();
anchor.remove();
console.info("[glitchwave-csv] Anchor click fallback attempted.");
},
async () => {
const dataUrl = `data:text/csv;charset=utf-8,${encodeURIComponent(csv)}`;
const win = window.open(dataUrl, "_blank");
if (!win) throw new Error("Popup blocked");
console.info("[glitchwave-csv] Opened data URL in new tab.");
},
];
let success = false;
for (const attempt of attempts) {
try {
await attempt();
success = true;
break;
} catch (err) {
console.warn("[glitchwave-csv] Download path failed:", err);
}
}
if (!success) {
alert(
"CSV download was blocked. Check popup/download permissions for this site and try again."
);
}
setTimeout(() => URL.revokeObjectURL(blobUrl), 1500);
}
async function loadStoredHandle() {
try {
const db = await openDb();
return await readHandle(db);
} catch (err) {
console.error("[glitchwave-csv] Unable to load stored handle", err);
return null;
}
}
async function storeHandle(handle) {
const db = await openDb();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readwrite");
tx.onerror = () => reject(tx.error);
tx.oncomplete = () => resolve();
tx.objectStore(STORE_NAME).put(handle, FILE_KEY);
});
}
function readHandle(db) {
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, "readonly");
const req = tx.objectStore(STORE_NAME).get(FILE_KEY);
req.onsuccess = () => resolve(req.result || null);
req.onerror = () => reject(req.error);
});
}
function openDb() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, 1);
request.onupgradeneeded = () => {
request.result.createObjectStore(STORE_NAME);
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
})();