szq2 / Nyaa add manga links to Baka-updates

// ==UserScript==
// @name        Nyaa add manga links to Baka-updates
// @namespace   Violentmonkey Scripts
// @match       https://nyaa.si/*
// @grant       GM.xmlHttpRequest
// @connect     www.mangaupdates.com
// @version     1.0
// @author      szq2
// @description Adds mangaupdates.com links and rating to nyaa.si tracker
// @license     0BSD
// @updateURL   https://openuserjs.org/meta/szq2/Nyaa_add_manga_links_to_Baka-updates.meta.js
// @downloadURL https://openuserjs.org/install/szq2/Nyaa_add_manga_links_to_Baka-updates.user.js
// ==/UserScript==

const fetchRating = true; // enable to fetch first series rating and link from search page
const fetchRatingDelay = 2000; //ms
const target = "_blank"; // where to open mangaupdates page, _blank for new tab

const re = /^(?:\[.*\])?\s*([^(\[]+?) *((v(olume)?)?[\d\- ]+)?( +[\(\[].*)?$/i; // regex to select book name from torrent name

const fetchHTML = (url) => new Promise((resolve, reject) => {
  GM.xmlHttpRequest({
    method: "GET",
    url: url,
    responseType: 'document',
    anonymous: true,
    onload: response => resolve(response.response),
    onerror: err => reject(err),
  });
});
const delay = (time) => new Promise(res => setTimeout(res, time));

(function () {
  'use strict';

  // books
  let book = 0;
  for (let a of document.querySelectorAll("tr.default > td:nth-child(1) > a[href*='c=3_']")) {
    a = a.parentElement.nextElementSibling.lastElementChild;
    const title = a.innerText.match(re);
    if (!title) continue;
    const url = `https://www.mangaupdates.com/series.html?search=${encodeURI(title[1])}`;
    let mangalink = document.createElement("span");
    mangalink.innerHTML = `<a href="${url}" title="${title[1]}" target="${target}">[m]</a> `;
    a.insertAdjacentElement("beforebegin", mangalink);

    if (fetchRating) {
      delay((book + Math.random()) * fetchRatingDelay)
        .then(() => fetchHTML(url))
        .then(doc => {
          let slink = doc.querySelector('.text > a[alt="Series Info"]');
          if (!slink)
            return console.error(url, "Unable to select", doc);
          mangalink.innerHTML = `<a href="${slink.href}" title="${slink.innerText}" target="${target}" title="${title[1]}">[${slink.parentElement.parentElement.querySelector('.text:last-child').innerText}]</a> `;
        }).catch(error => {
          // Handle any errors that occurred during the download
          console.error('Error:', error);
        });
    }
    book++;
  }

})();