-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbgg-names-to-ids.html
705 lines (638 loc) · 23.7 KB
/
bgg-names-to-ids.html
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Bulk Convert Boardgame Name to BoardGameGeek ID</title>
<style>
@import url(https://fonts.bunny.net/css?family=open-sans:400,400i,700,700i);
:root {
--red: #a40e4c;
--text-on-red: #ffffff;
--green: #73956f;
--text-on-green: #ffffff;
--header-color: #2c2c54;
--text-on-header: #ffffff;
}
html,
body {
height: 100%;
}
body {
margin: 0;
font-family: "Open Sans";
display: grid;
grid-template-columns: 1fr 3fr;
grid-template-rows: auto 1fr;
}
#sidebar {
grid-row: span 2;
background: #f5d6ba;
}
#header {
background-color: var(--header-color);
padding: 15px;
}
#main {
padding: 15px;
}
#input-container {
display: flex;
flex-direction: column;
gap: 20px;
align-items: center;
}
#sidebar-explanation {
padding: 10px 30px;
}
#sidebar-explanation h4 {
margin-bottom: 10px;
}
#sidebar-explanation p {
font-size: 0.9rem;
margin-top: 0;
}
button {
background-color: var(--red);
color: var(--text-on-red);
font-size: 1rem;
border: none;
padding: 5px 16px;
border-radius: 4px;
transition: all 0.3s ease-in-out;
font-family: "Open Sans";
}
a {
color: var(--header-color);
}
#start,
#download {
background-color: var(--green);
color: var(--text-on-green);
}
button:hover {
transform: scale(0.95);
}
button:active {
transform: scale(0.85);
}
h1 {
color: var(--text-on-header);
margin: 0;
font-size: 1.6rem;
}
textarea {
font-family: "Open sans";
width: max(60%, 300px);
height: 50vh;
}
h1,
h2,
h3,
h4 {
text-align: center;
}
#sidebar .skip-to-end {
background-color: var(--red);
color: var(--text-on-red);
position: fixed;
bottom: -5px;
left: 60px;
padding-bottom: 10px;
}
#container-progress-table {
max-height: calc(100vh - 75px);
overflow-y: auto;
}
#progress-table {
border-collapse: collapse;
width: 100%;
}
td,
th {
border-bottom: 1px solid #2c2c54;
padding: 5px;
width: 50%;
min-width: 100px;
max-width: 150px;
width: min-content;
overflow: hidden;
}
td:first-child,
th:first-child {
border-right: 1px solid #2c2c54;
padding-left: 20px;
}
tr:first-child th {
border-right: none;
}
#heading-choose-game {
line-height: 1.8rem;
}
#search-term-in-heading {
background-color: var(--green);
color: var(--text-on-green);
padding: 5px 10px;
border-radius: 3px;
white-space: pre;
}
#tile-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
justify-items: center;
gap: 10px;
align-items: center;
}
#tile-container button {
align-self: baseline;
margin-top: 50px;
}
.tile {
text-align: center;
}
.tile img {
max-width: 150px;
cursor: pointer;
}
.alternate-names {
font-size: 0.9rem;
}
#modal-background {
width: 100vw;
height: 100vh;
position: fixed;
left: 0;
top: 0;
display: flex;
justify-content: center;
background: #00000099;
align-items: center;
}
#modal-too-many-requests {
background: var(--green);
color: var(--text-on-green);
padding: 10px 40px;
border-radius: 5px;
box-shadow: rgb(0 0 0 / 30%) 0px 0px 15px;
}
.hidden {
display: none !important;
}
#id-list {
color: green;
}
#no-matches {
color: red;
}
#skipped {
color: var(--header-color);
}
#results-buttons {
display: flex;
justify-content: center;
gap: 30px;
}
</style>
</head>
<body>
<div id="sidebar">
<div id="sidebar-explanation" class="visible-at-input">
<h4>Purpose of this website</h4>
<p>
This website helps you to identify the
<a href="https://boardgamegeek.com/" target="_blank">BoardGameGeek</a>
(BGG) ID's of your boardgames. With your ID list, you can then bulk
upload your games into your BGG Collection using
<a href="https://github.com/fenglisch/bgg-bulk-upload" target="_blank"
>this program</a
>.
</p>
<h4>How it works</h4>
<p>
This website sends the names you provide as search queries to the BGG
database (via their XML API2). When there is no unique match, the
website will ask you for clarification.
</p>
<p>
To spare the BGG API from too many requests, there is a short break of
0.75 seconds between each new search query. Nevertheless, it can
happen that the BGG servers need some time to breathe in between
(especially if you provide a long list of games). This will only cause
a short delay, so don't worry.
</p>
</div>
<div id="container-progress-table" class="visible-at-processing hidden">
<table id="progress-table">
<thead>
<tr>
<th colspan="2">Progress</th>
</tr>
<tr>
<th scope="col">Name</th>
<th scope="col">Status</th>
</tr>
</thead>
</table>
<button class="skip-to-end">Skip to final results</button>
</div>
<div id="sidebar-explanation" class="visible-at-results hidden">
<h4>Great! And what now?</h4>
<p>
With your ID list, you can now bulk upload your boardgames to your
BoardGameGeek Collection. This feature is missing on BGG itself, but
you can use
<a href="https://github.com/fenglisch/bgg-bulk-upload" target="_blank"
>this program</a
>
to get the job done.
</p>
</div>
</div>
<div id="header">
<h1>Bulk Convert Boardgame Names to BoardGameGeek ID's</h1>
</div>
<div id="main">
<form id="input-container" class="visible-at-input">
<textarea
required
placeholder="Paste a semicolon-separated list with the names of your games."
></textarea>
<div>
<input type="checkbox" id="includeExpansions" />
<label for="includeExpansions"
>Also search for Boardgame Expansions?</label
>
</div>
<button id="start">Start</button>
</form>
<div id="processing-container" class="visible-at-processing hidden">
<div id="modal-background" class="hidden">
<div id="modal-too-many-requests">
<p>
The BoardGameGeek API is getting too many requests. Sit back and
wait a little bit.
</p>
<p>Automatic retry in: <span id="countdown-till-retry"></span></p>
<p>
Or:
<button class="skip-to-end">
Skip to results to store current progress
</button>
</p>
</div>
</div>
<h4 id="heading-processing">Processing your list...</h4>
<div id="heading-choose-game" class="hidden">
<h3>
There has been no clear match for
<span id="search-term-in-heading"></span>.
</h3>
<h3>Please choose the right game by clicking on the thumbnail.</h3>
</div>
<div id="tile-container"></div>
</div>
<div id="results-container" class="visible-at-results hidden">
<h2>Proccessing completed.</h2>
<p id="paragraph-id-list" class="hidden">
Your ID list: <br />
<code id="id-list"></code>
</p>
<p id="paragraph-no-matches" class="hidden">
There have been no matches for the following games (please search for
these games manually or fix spelling mistakes and try again): <br />
<code id="no-matches"></code>
</p>
<p id="paragraph-skipped" class="hidden">
You skipped the following games from your list: <br />
<code id="skipped"></code>
</p>
<div id="results-buttons">
<button id="download">Download Results as CSV</button>
<button onclick="location.reload()" id="restart">Restart</button>
</div>
</div>
</div>
<script>
let arNamesToBeProcessed = [];
const arFoundIds = [];
const arGamesWithNoIdFound = [];
let arSkippedGames = [];
let isIncludeExpansions = false;
const BASE_URL = "https://boardgamegeek.com";
const modalTooManyRequests = document.querySelector("#modal-background");
const countdown = document.querySelector("#countdown-till-retry");
const tileContainer = document.querySelector("#tile-container");
const headingChooseGame = document.querySelector("#heading-choose-game");
let i = 0;
// There are to skip buttons, one above the progress table and one in the "Too many requests" modal
document.querySelectorAll(".skip-to-end").forEach((btn) => {
btn.addEventListener("click", () => {
// i tells us how far we got, everything after it was skipped
arSkippedGames = arNamesToBeProcessed.slice(i);
announceFinalResults();
});
});
function hideOldAndShowNextSection(hideThis, showThis) {
document
.querySelectorAll(`.visible-at-${hideThis}`)
.forEach((element) => {
element.classList.add("hidden");
});
document
.querySelectorAll(`.visible-at-${showThis}`)
.forEach((element) => {
element.classList.remove("hidden");
});
}
async function makeHttpRequest(url) {
modalTooManyRequests.classList.add("hidden");
try {
const response = await fetch(url);
const responseText = await response.text();
const parser = new DOMParser();
return parser.parseFromString(responseText, "text/xml");
} catch (error) {
// This represents a 429 "Too many requests"
if (
error instanceof TypeError &&
error.message === "Failed to fetch"
) {
modalTooManyRequests.classList.remove("hidden");
startTimer(30, countdown);
await new Promise((resolve) => setTimeout(resolve, 30000));
return await makeHttpRequest(url);
}
console.error(`Http request failed. ${error}`);
throw error;
}
}
function startTimer(duration, display) {
const intervalId = setInterval(() => {
let minutes = parseInt(duration / 60, 10);
let seconds = parseInt(duration % 60, 10);
minutes = minutes < 10 ? `0${minutes}` : minutes;
seconds = seconds < 10 ? `0${seconds}` : seconds;
display.textContent = `${minutes}:${seconds}`;
--duration;
if (duration < 0) clearInterval(intervalId);
}, 1000);
}
document.querySelector("form").addEventListener("submit", (e) => {
e.preventDefault();
hideOldAndShowNextSection("input", "processing");
isIncludeExpansions =
document.querySelector("#includeExpansions").checked;
const inputFromTextarea = document.querySelector("textarea").value;
// const uploadedFile = document.querySelector("input[type='file'");
const arAllNamesFromInput = inputFromTextarea
.split(";") // Split at Commas which are not between quotes (see https://stackoverflow.com/a/53774647)
.map(
(name) =>
name
.replace(/^ */g, "") // Remove spaces at the beginning...
.replace(/ *$/g, "") // ... and at the end...
.replace(/"/g, "") // ... as well as quotes...
.replace(/\n/g, "") // ... and line breaks, bevause they would compromise the search and comparision
);
// Remove empty strings and duplicates
arNamesToBeProcessed = [
...new Set(arAllNamesFromInput.filter(Boolean)),
];
// Fill progress table with game names
arNamesToBeProcessed.forEach((name) => {
const NewRowInTable = document.createElement("tr");
NewRowInTable.innerHTML = `<td class="name">${name}</td><td class="status"></td>`;
document.querySelector("#progress-table").appendChild(NewRowInTable);
});
processNextGame();
});
async function processNextGame() {
if (i === arNamesToBeProcessed.length) {
announceFinalResults();
return;
}
const searchTerm = arNamesToBeProcessed[i];
const parameters = {
query: searchTerm,
};
if (isIncludeExpansions)
parameters.type = "boardgame,boardgameexpansion";
// This is not enough to exclude expansions, but filters out some of them
else parameters.type = "boardgame";
const urlParameters = new URLSearchParams(parameters).toString();
const xmlOfSearchByTerm = await makeHttpRequest(
`${BASE_URL}/xmlapi2/search?${urlParameters}`
); // There are 3 possible outcomes of this search
const arItemsOfSearchByTerm =
xmlOfSearchByTerm.querySelectorAll("item");
// 1. There aren't any search results at all (e. g. spelling mistake)
if (arItemsOfSearchByTerm.length === 0) {
processResult(null, searchTerm, "No search results");
return;
}
// 2. There is exactly one search result. Is very likely that this is the right game, so we just take it
if (arItemsOfSearchByTerm.length === 1) {
processResult(arItemsOfSearchByTerm[0].id, searchTerm);
return;
}
// 3. There is more than one search result
// Now, we look for perfect matches (ignoring case), which again has 3 possible outcomes
let arIdsOfMatches = Array.from(arItemsOfSearchByTerm)
.filter(
(item) =>
item.querySelector("name").getAttribute("value").toLowerCase() ===
searchTerm.toLowerCase()
)
.map((item) => item.id);
// Remove duplicates which BGG sometimes shows in the search results for some reason
arIdsOfMatches = [...new Set(arIdsOfMatches)];
// 3.1. There is no perfect match
if (arIdsOfMatches.length === 0) {
let arIdsOfAllSearchResults = Array.from(arItemsOfSearchByTerm).map(
(result) => result.id
);
// Remove duplicates
arIdsOfAllSearchResults = [...new Set(arIdsOfAllSearchResults)];
askForClarification(arIdsOfAllSearchResults, searchTerm);
}
// 3.2. There is exactly 1 perfect match
else if (arIdsOfMatches.length === 1)
processResult(arIdsOfMatches[0], searchTerm);
// 3.3. There are many perfect matches
else askForClarification(arIdsOfMatches, searchTerm);
}
// Get more data about all potential matches and display them so that the user can choose the right match
async function askForClarification(arIds, searchTerm) {
// Don't request very long ID lists to avoid delays and 429 errors (and to spare the BGG servers)
if (arIds.length > 75) {
processResult(null, searchTerm, "Too many search results");
return;
}
const parameters = {
id: arIds.join(","),
};
if (isIncludeExpansions)
parameters.type = "boardgame,boardgameexpansion";
// This is filters out all expansions
else {
parameters.type = "boardgame";
parameters.excludesubtype = "boardgameexpansion";
}
const urlParameters = new URLSearchParams(parameters).toString();
const xmlOfRequestByIdList = await makeHttpRequest(
`${BASE_URL}/xmlapi2/thing?${urlParameters}`
);
const arItemsOfRequestByIdList = Array.from(
xmlOfRequestByIdList.querySelectorAll("item")
);
if (arItemsOfRequestByIdList.length === 0) {
processResult(null, searchTerm, "No search results");
return;
}
// Setup the page to page so that the user can choose the right game
document.querySelector("#search-term-in-heading").textContent =
searchTerm;
headingChooseGame.classList.remove("hidden");
// Alternatively to creating the btnChooseNone every time, it could also be hardcoded into the HTML file
// However, the button could then not be in the same div as the tiles, because the tileContainer.innerHTML is emptied each time
// Also, it would be necessary to remove the old event listener and create a new one each time, so re-creating the whole button seems to be easier
const btnChooseNone = document.createElement("button");
btnChooseNone.innerHTML = "None of these games /<br>I'm not sure";
btnChooseNone.addEventListener("click", () => {
headingChooseGame.classList.add("hidden");
tileContainer.innerHTML = "";
processResult(
null,
searchTerm,
"Search results didn't include the right game"
);
});
tileContainer.appendChild(btnChooseNone);
// Sort games by popularity
// Use number of people who voted for recommended player number as approximation for popularity
// Alternatively, one could set the URL param "stats=1" to get better indicators, but this would increase the size of each request
arItemsOfRequestByIdList.sort(
(a, b) =>
+b
.querySelector("[name='suggested_numplayers']")
.getAttribute("totalvotes") -
+a
.querySelector("[name='suggested_numplayers']")
.getAttribute("totalvotes")
);
// Create a tile for each game for the user to choose from
arItemsOfRequestByIdList.forEach((result) => {
const tile = document.createElement("div");
tile.classList.add("tile");
const thumbnail = result.querySelector("thumbnail")
? result.querySelector("thumbnail").textContent
: "https://upload.wikimedia.org/wikipedia/commons/1/14/No_Image_Available.jpg";
const year = result
.querySelector("yearpublished")
.getAttribute("value");
const linkElement = `<a href="${BASE_URL}/boardgame/${result.id}" target="_blank">BGG ⇗</a>`;
const primaryName = result
.querySelector("name[type='primary']")
.getAttribute("value");
// If the primary name of the game isn't already equal to the search term, get all alternate names that are
let listOfMatchingAlternateNames = "";
if (primaryName.toLowerCase() !== searchTerm.toLowerCase()) {
const arAllAlternateNames = Array.from(
result.querySelectorAll("name[type='alternate']")
).map((nameElement) => nameElement.getAttribute("value"));
let arMatchingAlternateNames = arAllAlternateNames.filter(
(name) => name.toLowerCase() === searchTerm.toLowerCase()
);
// No perfect matches found -> look for general matches
if (arMatchingAlternateNames.length === 0) {
const regexSearchTerm = new RegExp(searchTerm, "i");
arMatchingAlternateNames = arAllAlternateNames.filter((name) =>
name.match(regexSearchTerm)
);
}
// Anything found -> Wrap each name in quotes and the whole list in HTML tags and brackets
if (arMatchingAlternateNames.length > 0) {
listOfMatchingAlternateNames = arMatchingAlternateNames
.map((name) => name.replace(/^|$/g, """))
.join(", ")
.replace(/^/, "<span class='alternate-names'>(")
.replace(/$/, ")<s/span>");
}
}
tile.innerHTML = `<img data-game-id="${result.id}" src="${thumbnail}" />
<p><strong>${primaryName}</strong> (${year}, ${linkElement})<br>${listOfMatchingAlternateNames}</p>`;
tile.querySelector("img").addEventListener("click", (e) => {
headingChooseGame.classList.add("hidden");
tileContainer.innerHTML = "";
processResult(e.target.getAttribute("data-game-id"), searchTerm);
});
tileContainer.appendChild(tile);
});
}
function processResult(id, searchTerm, status = "Success") {
const statusInTable = document.querySelectorAll(
"#progress-table .status"
)[i];
statusInTable.textContent = status;
if (id) {
arFoundIds.push(id);
statusInTable.style.backgroundColor = "var(--green)";
statusInTable.style.color = "var(--text-on-green)";
} else {
arGamesWithNoIdFound.push(searchTerm);
statusInTable.style.backgroundColor = "var(--red)";
statusInTable.style.color = "var(--text-on-red)";
}
++i;
setTimeout(processNextGame, 750);
}
function announceFinalResults() {
let csvResults = "";
if (arFoundIds.length > 0) {
document
.querySelector("#paragraph-id-list")
.classList.remove("hidden");
document.querySelector("#id-list").textContent =
arFoundIds.join("; ");
csvResults += `"Successfully identified ID's";${arFoundIds
.map((id) => id.replace(/^|$/g, '"'))
.join(";")}\n`;
}
if (arGamesWithNoIdFound.length > 0) {
document
.querySelector("#paragraph-no-matches")
.classList.remove("hidden");
document.querySelector("#no-matches").textContent =
arGamesWithNoIdFound.join("; ");
csvResults += `"Games, where no ID could be found";${arGamesWithNoIdFound
.map((name) => name.replace(/^|$/g, '"'))
.join(";")}\n`;
}
if (arSkippedGames.length > 0) {
console.log("hey");
document
.querySelector("#paragraph-skipped")
.classList.remove("hidden");
document.querySelector("#skipped").textContent =
arSkippedGames.join("; ");
csvResults += `"Skipped games";${arSkippedGames
.map((name) => name.replace(/^|$/g, '"'))
.join(";")}`;
}
document.querySelector("#download").addEventListener("click", () => {
const downloadLink = document.createElement("a");
downloadLink.setAttribute(
"href",
`data:text/plain;charset=utf-8,${encodeURIComponent(csvResults)}`
);
downloadLink.setAttribute("download", `bgg-game-to-id.csv`);
document.querySelector("body").appendChild(downloadLink);
downloadLink.click();
document.querySelector("body").removeChild(downloadLink);
});
hideOldAndShowNextSection("processing", "results");
}
</script>
</body>
</html>