-
Notifications
You must be signed in to change notification settings - Fork 0
/
vndb-official-stats.user.js
891 lines (831 loc) · 25.3 KB
/
vndb-official-stats.user.js
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
// ==UserScript==
// @name VNDB Official Links and Release Dates
// @namespace Marv
// @homepageURL https://github.com/MarvNC/vn-userscripts
// @match https://vndb.org/v*
// @grant GM_addElement
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// @require https://openuserjs.org/src/libs/sizzle/GM_config.js
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @connect *
// @version 1.5.0
// @author Marv
// @description Adds links and dates to the VNDB infobox.
// ==/UserScript==
const pathRegex = /^\/v(\d+)$/;
const vnIdRegex = /^\/(v\d+)/;
const 税込みRegex = /[\((]税込([^\)]+)[\))]/;
const unreleasedEmoji = '<span title="Unreleased">🚧</span>';
const outOfStockEmoji = '<span title="Out of stock">❌</span>';
const freeEmoji = '<span title="Free">🎁</span>';
(async function () {
GM_addStyle(/* css */ `
.otherlink a {
display: flex;
}
.scriptLinks a span.price {
color: ${getComputedStyle(document.body).color};
margin-left: 10px;
}
.otherlink div {
display: flex !important;
flex-grow: 1;
flex-basis: 400px;
align-items: center;
}
.scriptLinks div, .otherlink div {
margin: 3px 0px;
}
.scriptLinks .grayedout {
margin-left: 10px;
}
.scriptLinks abbr {
flex-shrink: 0;
}
td#officialLinks div {
display: flex;
align-items: center;
}
.scriptLinks img.favicon{
height: 16px;
width: 16px;
margin-right: 5px;
margin-left: 5px;
}
.platforms .lang {
margin-right: 5px;
}
.platforms abbr.unofficial {
-webkit-filter: grayscale(100%);
}
`);
const configID = 'vndb-info-adder-config';
GM_config.init({
id: configID,
title: 'VNDB Official Links and Release Dates',
fields: {
showPlatforms: {
label: 'Show platforms',
type: 'checkbox',
default: true,
},
showReleaseDates: {
label: 'Show release dates',
type: 'checkbox',
default: true,
},
showOfficialLinks: {
label: 'Show official links',
type: 'checkbox',
default: true,
},
officialLinksBeforeCollapse: {
label: 'Amount of official links to display by default before collapsing:',
type: 'int',
title: 'Enter a number between 1 and 999999',
min: 1,
max: 999999,
default: 999999,
},
showOtherLinks: {
label: 'Show other links',
type: 'checkbox',
default: true,
},
otherLinksBeforeCollapse: {
label: 'Amount of other links to display by default before collapsing:',
type: 'int',
title: 'Enter a number between 1 and 999999',
min: 1,
max: 999999,
default: 4,
},
},
css: `
#${configID} {
color: ${getComputedStyle(document.body).color};
background: ${getComputedStyle(document.querySelector('main')).backgroundColor};
}
#${configID}_wrapper {
max-width: 1000px;
margin: 0 auto;
}
#${configID} .config_header {
color: ${getComputedStyle(document.querySelector('main h1')).color};
}
#${configID} input[type=text] {
color: ${getComputedStyle(document.querySelector('input.text')).color};
background: ${getComputedStyle(document.querySelector('input.text')).backgroundColor};
border: ${getComputedStyle(document.querySelector('input.text')).border};
}
#${configID} .saveclose_buttons {
display: none;
}
`,
events: {
save: function () {
console.log('saved');
// GM_config.close();
},
open: function (doc, window, frame) {
// add autosave to all checkboxes and inputs
const inputs = doc.querySelectorAll('input');
inputs.forEach((input) => {
input.addEventListener('input', () => {
GM_config.save();
});
});
},
reset: function () {
GM_config.save();
},
},
});
GM_registerMenuCommand('Configure script', () => {
GM_config.open();
});
// close config when clicking outside of it
document.body.addEventListener('click', (e) => {
if (GM_config.isOpen) {
GM_config.save();
GM_config.close();
}
});
const currentURL = new URL(document.URL);
let allReleases;
let existingShops;
// get titles
const titles = getTitles();
// if on main tab, get info with existing doc, otherwise fetch main page
if (currentURL.pathname.match(pathRegex)) {
existingShops = getShopLinks(document);
({ officialLinks, otherLinks, allReleases, langInfo } = getLangInfo(
document,
existingShops,
titles
));
} else {
const vnID = currentURL.pathname.match(vnIdRegex)[1];
const vnURL = `https://vndb.org/${vnID}`;
console.log(`Fetching ${vnURL}`);
let fetchPage = await fetch(vnURL);
let fetchText = await fetchPage.text();
let fetchDoc = await new DOMParser().parseFromString(fetchText, 'text/html');
existingShops = getShopLinks(fetchDoc);
({ officialLinks, otherLinks, allReleases, langInfo } = getLangInfo(
fetchDoc,
existingShops,
titles
));
}
const tbody = document.querySelector('main .vndetails tbody');
const firstHeader = tbody.querySelector('tr.nostripe');
if (GM_config.get('showPlatforms')) {
const platformsElem = makePlatformTable(langInfo);
tbody.insertBefore(platformsElem, firstHeader);
}
if (GM_config.get('showReleaseDates')) {
const releasesElem = makeHTMLTable(allReleases, 'Release Dates');
tbody.insertBefore(releasesElem, firstHeader);
}
if (GM_config.get('showOfficialLinks')) {
const officialLinksElem = makeHTMLTable(officialLinks, 'Official Links', {
collapsible: true,
linksBeforeCollapse: GM_config.get('officialLinksBeforeCollapse'),
});
tbody.insertBefore(officialLinksElem, firstHeader);
}
if (GM_config.get('showOtherLinks')) {
const otherLinksElem = makeHTMLTable(otherLinks, 'Other Links', {
collapsible: true,
linksBeforeCollapse: GM_config.get('otherLinksBeforeCollapse'),
});
tbody.insertBefore(otherLinksElem, firstHeader);
fetchPrices(otherLinksElem);
}
})();
/**
* Gets all the titles on the page
* @returns {Set} titles
*/
function getTitles() {
const titles = new Set();
const allTds = [...document.querySelectorAll('main .vndetails tbody tr.title td')];
for (const td of allTds) {
const nodes = [...td.childNodes];
for (const node of nodes) {
let add = false;
if (node.nodeType == Node.TEXT_NODE) {
add = true;
} else if (node.nodeType == Node.ELEMENT_NODE && node.tagName == 'SPAN') {
add = true;
}
if (add) {
titles.add(node.textContent.trim());
}
}
}
console.log(titles);
return titles;
}
/**
* Gets the shop links from the given document and returns them as a set.
* @param {DOM} document
* @returns {Set} shopLinks
*/
function getShopLinks(document) {
const buynow = document.getElementById('buynow');
if (buynow) {
return new Set([...buynow.querySelectorAll('a')].map((a) => a.href));
} else {
return new Set();
}
}
/**
* Gets the official links and release dates for the given document.
* @param {DOM} document
* @param {Set} existingShops - set of shop links to exclude
* @returns {object} allLinks, allReleases
*/
function getLangInfo(document, existingShops, titles) {
const langInfo = extractLangInfo(document);
const { officialLinks, otherLinks } = processLinks(langInfo, existingShops, titles);
const allReleases = processReleases(langInfo);
return { officialLinks, otherLinks, allReleases, langInfo };
}
/**
* Extracts language information from the given document.
* @param {DOM} document
* @returns {Array} langInfo
*/
function extractLangInfo(document) {
const langInfo = [];
[...document.querySelectorAll('article.vnreleases > details')].forEach((detail) => {
// Exclude collapsed languages
if (detail.open == false) {
return;
}
const releases = detail.querySelectorAll('tr');
const lang = detail.querySelector('summary > abbr[class*=icon-lang]').outerHTML;
const info = { lang, links: {}, platforms: {} };
for (const release of releases) {
const releaseTitle = release.querySelector('.tc4 a').innerText;
// ignore unofficial/mtl/patches
const grayedout = release.querySelector('small')?.textContent ?? '';
const unofficial = !!grayedout.match(/unofficial/);
const patch = !!grayedout.match(/patch/);
const mtl =
grayedout.match(/machine translation/) ||
release.querySelector('tr')?.classList?.contains('mtl') ||
release?.classList?.contains('mtl');
const complete = !!release.querySelector(`abbr[title="complete"]`);
if (!unofficial && !mtl) {
// get official link first for the case where there is only one link
const officialLinkIcon = release.querySelector('abbr.external[title="Official website"]');
if (officialLinkIcon) {
info.links[officialLinkIcon.parentElement.href] = {
type: patch ? 'Patch' : 'Official website',
title: releaseTitle,
};
}
// get rest of links in dropdown
const otherLinks = [...release.querySelectorAll('.elm_dd_relextlink li > a')];
if (otherLinks.length > 0) {
otherLinks.forEach((linkAnchor) => {
if (!info.links[linkAnchor.href]) {
info.links[linkAnchor.href] = { type: linkAnchor.innerHTML, title: releaseTitle };
const priceSpan = linkAnchor.querySelector('span');
if (priceSpan) {
const price = priceSpan.textContent;
info.links[linkAnchor.href].price = price;
info.links[linkAnchor.href].type = linkAnchor.childNodes[1].textContent;
}
// set type to patch if it's a patch
if (patch) {
info.links[linkAnchor.href].type = 'Patch';
}
}
});
}
// get release date
if (!info.release && complete && !patch) {
info.release = release.querySelector('.tc1').innerHTML;
}
}
// check if release date is set so that there's an official release, add platform if so
if (info.release && complete && !mtl) {
const platform = release.querySelector('abbr[class*=icon-plat]').outerHTML;
const released = !release.querySelector('.future');
// add platform, set officiality
if (!info.platforms[platform]) {
info.platforms[platform] = { official: !unofficial, released };
}
// set to official if not already set
if (!info.platforms[platform].official && !unofficial) {
info.platforms[platform].official = true;
}
// set to released if not already set
if (!info.platforms[platform].released && released) {
info.platforms[platform].released = true;
}
}
}
langInfo.push(info);
});
return langInfo;
}
/**
* Given a map of links to platforms and their release status, returns an HTML string of platform images and labels.
* @param {array} platforms
* @param {boolean} isUnreleased
*/
function createPlatformHtmlString(platforms, isUnreleased = false) {
let htmlString = '';
const label = isUnreleased ? `${unreleasedEmoji}:` : '';
for (const [platformHTML, info] of platforms) {
const platformImg = createElementFromHTML(platformHTML);
if (!info.official) {
platformImg.title += ' (unofficial)';
platformImg.classList.add('unofficial');
}
if (isUnreleased) {
platformImg.title += ' (unreleased)';
platformImg.classList.add('unreleased');
}
htmlString += platformImg.outerHTML;
platformImg.remove();
}
return `${label} ${htmlString}`;
}
/**
* Given a map of links to languages, returns a table element about platform support.
* @param {object[]} langInfo
*/
function makePlatformTable(langInfo) {
let htmlString = '';
for (const lang of langInfo) {
const platforms = Object.entries(lang.platforms);
// skip languages without any official platform releases
if (platforms.length === 0) {
continue;
}
const released = platforms.filter(([, info]) => info.released);
const unreleased = platforms.filter(([, info]) => !info.released);
const flag = lang.lang;
htmlString += `<div>${flag}`;
if (released.length > 0) {
htmlString += createPlatformHtmlString(released);
}
if (unreleased.length > 0) {
if (released.length > 0) {
htmlString += ' ';
}
htmlString += createPlatformHtmlString(unreleased, true);
}
}
const platformsElem = document.createElement('tr');
platformsElem.className = 'platforms';
platformsElem.innerHTML = `
<td>Platforms</td>
<td>
${htmlString}
</td>
`;
return platformsElem;
}
/**
* Processes language information to extract official and other links.
* @param {Array} langInfo
* @param {Set} existingShops - set of shop links to exclude
* @returns {object} officialLinks, otherLinks - maps of linkHTML to languages
*/
function processLinks(langInfo, existingShops, titles) {
const officialLinks = new Map();
const otherLinks = new Map();
const existingLinks = new Set();
for (const lang of langInfo) {
for (const link of Object.keys(lang.links)) {
if (existingShops.has(link)) {
console.log(`Skipping shop link: ${link}`);
continue;
}
if (existingLinks.has(link)) {
console.log(`Skipping duplicate link: ${link}`);
continue;
}
existingLinks.add(link);
const linkType = lang.links[link].type;
let linkTitle = lang.links[link].title;
// trim edition title by removing main title
let titleReplaced = false;
let i = 0;
while (!titleReplaced && i < titles.size) {
const title = [...titles][i];
if (linkTitle.includes(title)) {
linkTitle = linkTitle.replace(title, '');
titleReplaced = true;
}
i++;
}
linkTitle = linkTitle.trim();
const linkPrice = lang.links[link].price;
try {
const url = new URL(link);
let displayLink;
let faviconURL = 'https://www.google.com/s2/favicons?sz=16&domain=' + url;
if (linkType === 'Official website') {
displayLink = url.hostname + url.pathname + url.search + url.hash;
displayLink = decodeURIComponent(displayLink);
displayLink = displayLink.replace(/\/$/, '');
displayLink = displayLink.replace(/^www./, '');
if (displayLink.length > 53) {
displayLink = displayLink.slice(0, 50) + '...';
}
} else {
displayLink = linkType;
}
// merge language flags on each link, create html
let linkHTML = `
<img src="${faviconURL}" alt="favicon" class="favicon">
<a href="${link}" title="${displayLink}">
${displayLink}
${linkPrice ? `<span>${linkPrice}</span>` : ''}
</a>`;
if (linkType === 'Official website') {
if (officialLinks.has(linkHTML)) {
officialLinks.get(linkHTML).push(lang.lang);
} else {
officialLinks.set(linkHTML, [lang.lang]);
}
} else {
// add title to other links
linkHTML += `<span class="grayedout" title="${linkTitle}">${linkTitle}</span>`;
if (otherLinks.has(linkHTML)) {
otherLinks.get(linkHTML).push(lang.lang);
} else {
otherLinks.set(linkHTML, [lang.lang]);
}
}
} catch (error) {
console.log(link, error);
}
}
}
return { officialLinks, otherLinks };
}
/**
* Processes language information to extract all release dates.
* @param {Array} langInfo
* @returns {Map} allReleases
*/
function processReleases(langInfo) {
const allReleases = new Map();
for (const lang of langInfo) {
if (lang.release) {
if (allReleases.has(lang.release)) {
allReleases.get(lang.release).push(lang.lang);
} else {
allReleases.set(lang.release, [lang.lang]);
}
}
}
return allReleases;
}
/**
* Creates an HTML table from the given data. If collapsible is true, the table will be collapsed by default but include linksBeforeCollapse links in the summary.
* @param {object} dataToLangFlags Map of links or data as the key mapped to values of arrays of languages
*/
function makeHTMLTable(dataToLangFlags, title, options = { collapsible: false }) {
const collapsible = options.collapsible;
const linksBeforeCollapse = options.linksBeforeCollapse;
if (!collapsible || dataToLangFlags.size <= linksBeforeCollapse) {
let tableHTML = createTableHTML(dataToLangFlags);
const tableElem = document.createElement('tr');
if (dataToLangFlags.size > 0) {
tableElem.innerHTML = `<td>${title}</td><td id="officialLinks" class="scriptLinks">${tableHTML}</td>`;
}
return tableElem;
} else {
const summaryRows = [...dataToLangFlags].slice(0, linksBeforeCollapse);
let summaryHTML = createTableHTML(summaryRows);
const remainingRows = [...dataToLangFlags].slice(linksBeforeCollapse);
let remainingHTML = createTableHTML(remainingRows);
const tableHTML = `
<td class="titles scriptLinks" colspan="2">
<details>
<summary>
<div>${title}</div>
<table>
<tbody>
<tr class="title nostripe otherlink">
<td>${summaryHTML}
</tr>
</tbody>
</table>
</summary>
<table>
<tbody>
<tr class="title nostripe otherlink">
<td>${remainingHTML}</td>
</tr>
</tbody>
</table>
</details>
</td>
`;
const tableElem = document.createElement('tr');
tableElem.innerHTML = tableHTML;
return tableElem;
}
}
function createTableHTML(dataToLangFlags) {
let tableHTML = '';
for (const [data, lang] of dataToLangFlags) {
tableHTML += '<div>' + lang.join('') + data + '</div>';
}
return tableHTML;
}
function createElementFromHTML(htmlString) {
const div = document.createElement('div');
div.innerHTML = htmlString.trim();
return div.firstChild;
}
/**
* Fetches prices for the given links and adds them to the table.
* @param {DOM} otherLinksElem
*/
async function fetchPrices(otherLinksElem) {
const links = [...otherLinksElem.querySelectorAll('a')];
for (const linkAnchor of links) {
const link = linkAnchor.href;
const type = linkAnchor.title;
getPrice(link, type).then((price) => {
if (price) {
const priceSpan = document.createElement('span');
priceSpan.className = 'price';
priceSpan.innerHTML = price;
linkAnchor.appendChild(priceSpan);
} else {
console.log(`No price found for ${link}`);
}
});
}
}
/**
* Gets the price for the given link.
* @param {string} link
* @param {string} type
* @returns {string} price
*/
async function getPrice(link, type) {
switch (type) {
case 'Steam':
return await getSteamPrice(link);
case 'DMM':
return await getDMMPrice(link);
case 'Getchu':
return await getGetchuPrice(link);
case 'Toranoana':
return await getToranoanaPrice(link);
case 'Melonbooks.co.jp':
return await getMelonbooksPrice(link);
case 'Denpasoft':
return await getDenpasoftPrice(link);
case 'Nutaku':
return await getNutakuPrice(link);
case 'Fakku':
return await getFakkuPrice(link);
default:
console.log(`${type} not supported yet`);
return null;
}
}
/**
* Gets the price for the given Steam link. Adds the price in USD if the user is not in the US.
* @param {string} link
* @returns {string} price
*/
async function getSteamPrice(link, usa = false) {
const steamId = link.match(/\/app\/(\d+)/)[1];
const steamURL = `https://store.steampowered.com/api/appdetails?appids=${steamId}${
usa ? '&cc=us&anonymous=true' : ''
}`;
try {
const response = await getJSONFromURL(steamURL);
const data = response[steamId];
if (data.success) {
if (data.data.is_free) {
return freeEmoji;
}
if (data.data.price_overview.currency === 'USD') {
usa = true;
}
if (usa) {
return data.data.price_overview.final_formatted;
} else {
return data.data.price_overview.final_formatted + ' (' + getSteamPrice(link, true) + ')';
}
}
} catch (error) {
console.log(error);
return null;
}
return null;
}
/**
* Gets the price for the given DMM link.
* @param {string} link
* @returns {string} price
*/
async function getDMMPrice(link) {
const doc = await getDocumentFromURL(link);
const urlInfo = new URL(link);
// DL edition site
if (urlInfo.hostname.startsWith('dlsoft')) {
const normalPrice = doc.querySelector('td.normal-price.red');
const couponPrice = doc.querySelector('div.coupon-price');
if (couponPrice) {
return couponPrice.textContent;
}
if (normalPrice) {
return normalPrice.textContent;
}
} else {
// physical purchase
// region blocked
if (!doc.querySelector('.bg-bskt')) {
return;
}
const priceElem = doc.querySelector('.txt-price-discount');
if (priceElem) {
return priceElem.textContent;
} else {
return outOfStockEmoji;
}
}
return null;
}
/**
* Gets the price for the given Getchu link.
* @param {string} link
* @returns {string} price
*/
async function getGetchuPrice(link) {
const adultLink = link + '&gc=gc';
const doc = await getDocumentFromURL(adultLink);
const taxIn = doc.querySelector('.taxin');
if (taxIn) {
return getTaxPrice(taxIn.textContent);
}
// out of stock, get 定価 price
const softTable = doc.getElementById('soft_table');
const priceLabel = [...softTable.querySelectorAll('td')].find(
(td) => td.textContent === '定価:'
);
if (priceLabel) {
return outOfStockEmoji + getTaxPrice(priceLabel.nextElementSibling.textContent);
}
return null;
}
/**
* Gets the price for the given Toranoana link.
* @param {string} link
* @returns {string} price
*/
async function getToranoanaPrice(link) {
const doc = await getDocumentFromURL(link);
let stock = false;
let price = '';
const addToCart = doc.querySelector('div.product-detail-cart-block a.product-detail-cart-btn');
if (addToCart) {
stock = addToCart.innerText.includes('お取り寄せ');
}
const priceElem = doc.querySelector('ul.pricearea li');
if (priceElem) {
price = priceElem.dataset.price;
}
return (stock ? '' : outOfStockEmoji) + price;
}
/**
* Gets the price for the given Melonbooks link.
* @param {string} link
* @returns {string} price
*/
async function getMelonbooksPrice(link) {
const adultURL = link + '&adult_view=1';
const doc = await getDocumentFromURL(adultURL);
let stock = false;
let price = '';
const cartInput = doc.querySelector('div.btn-cart');
if (cartInput) {
stock = cartInput.innerText.includes('カートに入れる');
}
const priceElem = doc.querySelector('p.price span.yen');
if (priceElem) {
const delElem = priceElem.querySelector('del');
if (delElem) {
delElem.remove();
}
price = priceElem.innerText.trim();
}
return (stock ? '' : outOfStockEmoji) + price;
}
/**
* Gets the price for the given Denpasoft link.
* @param {string} link
* @returns {string} price
*/
async function getDenpasoftPrice(link) {
const doc = await getDocumentFromURL(link);
const priceElem = doc.querySelector('p.price span.woocommerce-Price-amount.amount');
if (priceElem) {
return priceElem.innerText;
}
return null;
}
/**
* Gets the price for the given Nutaku link.
* @param {string} link
* @returns {string} price
*/
async function getNutakuPrice(link) {
const doc = await getDocumentFromURL(link);
const priceElem = doc.querySelector('div.premium-purchase div.price-line');
if (priceElem) {
return priceElem.childNodes[0].textContent;
}
return null;
}
/**
* Gets the price for the given Fakku link.
* @param {string} link
* @returns {string} price
*/
async function getFakkuPrice(link) {
const doc = await getDocumentFromURL(link);
const priceElem = doc.querySelector(
'.w-full.table div[data-tippy-content="Add to Cart"].js-purchase-product'
);
if (priceElem) {
return priceElem.innerText;
}
}
/**
* Gets the tax-included price from a string.
* @param {string} priceString
* @returns {string} price
*/
function getTaxPrice(priceString) {
try {
const price = priceString.match(税込みRegex)[1];
return price;
} catch (error) {
console.log(`Error parsing price: ${priceString}`);
return priceString;
}
}
/**
* Gets the document from a URL using GM_xmlhttpRequest to access other domains
* @param {string} url
* @returns {Promise<Document>}
*/
async function getDocumentFromURL(url) {
console.log(`Fetching ${url}...`);
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url: url,
onload: function (response) {
const parser = new DOMParser();
const doc = parser.parseFromString(response.responseText, 'text/html');
resolve(doc);
},
onerror: function (error) {
reject(error);
},
});
});
}
/**
* Gets the JSON from a URL using GM_xmlhttpRequest to access other domains
* @param {string} url
* @returns {Promise<Object>}
*/
async function getJSONFromURL(url) {
console.log(`Fetching ${url}...`);
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url: url,
onload: function (response) {
resolve(JSON.parse(response.responseText));
},
onerror: function (error) {
reject(error);
},
});
});
}