ovanasdf / HentaiFoundry Gallery Downloader

// ==UserScript==
// @name         HentaiFoundry Gallery Downloader
// @namespace    blargh
// @version      0.1
// @description  Adds a "Download Gallery" button on every page on Hentai Foundry that has a gallery. Works on both artists pages and categories.
// @author       SomeFuckingWeeb
// @match        https://www.hentai-foundry.com/*
// @connect      self
// @grant        GM_download
// @license      MIT
// ==/UserScript==

(function () {
  'use strict';
  if(!document.querySelector('.galleryView')) return; //bail if we don't have a gallery

  const invokeElem = document.createElement('button');
  invokeElem.style.cssText = "background: #222; color: #aaaaaa; font-size: 2em; border: 1px solid #aaaaaa;"; //vague attempt to make the button fit in
  invokeElem.innerText = 'Download Gallery';
  invokeElem.onclick = DownloadAll;
  document.querySelector('.galleryHeader').append(invokeElem); //gallery header seems like the best place atm for this
  //we're using the channel api for this
  window.addEventListener(
    'message',
    (event) => {
      console.log(event.data);
      event.data.onerror = (e) => console.warn(e);
      GM_download(event.data);
    },
    false
  );
})();

function DownloadAll() {
  const thumbs = document.querySelectorAll('a.thumbLink');
  const imageRefRegex = /\/user\/(.*)\/(\d*)\/(.*)/g;

  thumbs.forEach((thumb) => {
    const matches = imageRefRegex.exec(thumb.href);
    if (!matches) return;
    const username = matches[1];
    const id = matches[2];
    const name = matches[3];
    var imageUrl = "https://pictures.hentai-foundry.com/" + username.substring(0, 1).toLowerCase() + "/" + username + "/" + id + "/" + username + "-" + id + "-" + name + ".jpg";
    var imageName = `${username}-${name}-${id}.jpg`;
    window.postMessage(
      {
        url: imageUrl,
        name: imageName,
        saveAs: false,
      },
      '*'
    );
  });
}