Bobby's Pixiv Utils

7/2/2024, 8:37:14 PM

当前为 2025-02-16 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name        Bobby's Pixiv Utils
// @namespace   https://github.com/BobbyWibowo
// @match       *://www.pixiv.net/*
// @match       *://pixiv.net/*
// @icon        https://www.google.com/s2/favicons?sz=64&domain=pixiv.net
// @grant       GM_addStyle
// @grant       GM_getValue
// @run-at      document-end
// @version     1.0.17
// @author      Bobby Wibowo
// @license     MIT
// @description 7/2/2024, 8:37:14 PM
// @noframes
// ==/UserScript==

(function () {
  'use strict'

  /** CONFIG **/

  const log = (message, ...args) => {
    console.log(`[Bobby's Pixiv Utils]: ${message}`, ...args)
  }

  const logError = (message, ...args) => {
    console.error(`[Bobby's Pixiv Utils]: ${message}`, ...args)
  }

  const ENV = {
    MODE: GM_getValue('MODE', 'PROD'),

    SELECTORS_IMAGE: GM_getValue('SELECTORS_IMAGE'),
    SELECTORS_ILLUST_CONTROLS: GM_getValue('SELECTORS_ILLUST_CONTROLS'),
    SELECTORS_BOTTOM_RIGHT_CONTROLS: GM_getValue('SELECTORS_BOTTOM_RIGHT_CONTROLS'),

    DATE_CONVERSION: GM_getValue('DATE_CONVERSION', true),
    SELECTORS_DATE: GM_getValue('SELECTORS_DATE')
  }

  const SELECTORS_IMAGE = '.jtUPOE > li, .gmoaNn > li, .hjtPnz > li, .boBnlf > div, .hkzusx > div, .ranking-item, .iXWLAI > li, .hdRpMN > li'
    + (ENV.SELECTORS_IMAGE ? `, ${ENV.SELECTORS_IMAGE}` : '');
  const SELECTORS_ILLUST_CONTROLS = '.gMEAWM'
    + (ENV.SELECTORS_ILLUST_CONTROLS ? `, ${ENV.SELECTORS_ILLUST_CONTROLS}` : '');
  const SELECTORS_BOTTOM_RIGHT_CONTROLS = '.iHfghO, .cGfNRT, ._layout-thumbnail, .dVtEKY'
    + (ENV.SELECTORS_BOTTOM_RIGHT_CONTROLS ? `, ${ENV.SELECTORS_BOTTOM_RIGHT_CONTROLS}` : '');

  const DATE_CONVERSION = ENV.DATE_CONVERSION;
  const SELECTORS_DATE = '.dqHJfP'
    + (ENV.SELECTORS_DATE ? `, ${ENV.SELECTORS_DATE}` : '');

  if (ENV.MODE !== 'PROD') {
    log(`ENV: ${ENV.MODE}`);
    log(`SELECTORS_IMAGE: ${SELECTORS_IMAGE}`);
    log(`SELECTORS_ILLUST_CONTROLS: ${SELECTORS_ILLUST_CONTROLS}`);
    log(`SELECTORS_BOTTOM_RIGHT_CONTROLS: ${SELECTORS_BOTTOM_RIGHT_CONTROLS}`);
    log(`DATE_CONVERSION: ${DATE_CONVERSION}`);
    log(`SELECTORS_DATE: ${SELECTORS_DATE}`);
  }

  /** STYLES **/

  const mainStyle = /*css*/`
  .pu_edit_bookmark {
    color: rgb(245, 245, 245);
    background: rgba(0, 0, 0, 0.32);
    display: block;
    box-sizing: border-box;
    padding: 0px 6px;
    margin-top: 7px;
    margin-right: 2px;
    border-radius: 10px;
    font-weight: bold;
    font-size: 10px;
    line-height: 20px;
    height: 20px;
  }

  .gMEAWM .pu_edit_bookmark {
    font-size: 12px;
    height: 24px;
    line-height: 24px;
    margin-top: 5px;
    margin-right: 7px;
  }

  ._layout-thumbnail .pu_edit_bookmark {
    position: absolute;
    right: calc(50% - 71px);
    bottom: 4px;
    z-index: 2;
  }

  .iHfghO, .cGfNRT {
    display: flex;
    justify-content: flex-end;
  }
  `;

  const addPageStyle = /*css*/`
  .bookmark-detail-unit .meta {
    display: block;
    font-size: 16px;
    font-weight: bold;
    color: inherit;
    margin-left: 0;
    margin-top: 10px;
  }
  `;

  /** UTILS **/

  const convertDate = elem => {
    const date = new Date(elem.getAttribute('datetime') || elem.innerText);
    if (!date) {
      return false;
    }

    const timestamp = String(date.getTime());
    if (elem.dataset.oldTimestamp && elem.dataset.oldTimestamp === timestamp) {
      return false;
    }

    elem.dataset.oldTimestamp = timestamp;
    elem.innerText = date.toLocaleString("en-GB", {
      hour12: true,
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
    return true;
  }

  /** INTERCEPT SOME PAGES **/

  const path = location.pathname;

  if (path.startsWith('/bookmark_add.php')) {
    GM_addStyle(addPageStyle);

    if (DATE_CONVERSION) {
      const date = document.querySelector('.bookmark-detail-unit .meta');
      convertDate(date);
    }

    log(`${path}: Applied customization, and disabled mutation observer.`)
    return;
  }

  /** MAIN **/

  GM_addStyle(mainStyle);

  class FunctionQueue {
    constructor() {
      this.queue = [];
      this.running = false;
    }

    async go() {
      if (this.queue.length) {
        this.running = true;
        const _func = this.queue.shift();
        await _func[0](..._func[1]);
        this.go();
      } else {
        this.running = false;
      }
    }

    add (func, ...args) {
      this.queue.push([func, [...args]]);

      if (!this.running) {
        this.go();
      }
    }
  }

  const observerFactory = function (option) {
    let options;
    if (typeof option === 'function') {
      options = {
        callback: option,
        node: document.getElementsByTagName('body')[0],
        option: { childList: true, subtree: true }
      };
    } else {
      options = $.extend({
        callback: () => {},
        node: document.getElementsByTagName('body')[0],
        option: { childList: true, subtree: true }
      }, option);
    }
    const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

    const observer = new MutationObserver((mutations, observer) => {
      options.callback.call(this, mutations, observer);
    });

    observer.observe(options.node, options.option);
    return observer;
  };

  const editBookmarkButton = id => {
    const buttonContainer = document.createElement('div');
    const button = document.createElement('a');
    button.className = 'pu_edit_bookmark';
    button.href = `https://www.pixiv.net/bookmark_add.php?type=illust&illust_id=${id}`;
    button.innerText = 'Edit bookmark';

    buttonContainer.appendChild(button);
    return buttonContainer;
  }

  const isElementValid = element => {
    // Skip if no longer in DOM
    if (!element.isConnected) {
      return false;
    }

    // Skip if hidden (e.g., due to page change transition)
    if (!element.checkVisibility({ contentVisibilityAuto: true, opacityProperty: true, visibilityProperty: true })) {
      return false;
    }

    // Skip if already modified
    if (element.querySelector('.pu_edit_bookmark')) {
      return false;
    }

    return true;
  }

  const doImage = element => {
    if (!isElementValid(element)) {
      return false;
    }

    const link = element.querySelector('a[href*="artworks/"]');
    const bottomRightControls = element.querySelector(SELECTORS_BOTTOM_RIGHT_CONTROLS);
    if (!link || !bottomRightControls) {
      return false;
    }

    const match = link.href.match(/artworks\/(\d+)/);
    if (!match || !match[1]) {
      return false;
    }

    bottomRightControls.insertBefore(editBookmarkButton(match[1]), bottomRightControls.firstChild);
    return true;
  }

  const doIllustControls = element => {
    if (!isElementValid(element)) {
      return false;
    }

    const match = window.location.href.match(/artworks\/(\d+)/);
    if (!match || !match[1]) {
      return false;
    }

    element.appendChild(editBookmarkButton(match[1]));
    return true;
  }

  const triggerQueue = new FunctionQueue();
  const queryQueue = new FunctionQueue();

  observerFactory((...args) => {
    triggerQueue.add((mutations, observer) => {
      for (let i = 0, len = mutations.length; i < len; i++) {
        const mutation = mutations[i];

        // Whether to change nodes
        if (mutation.type !== 'childList') {
          continue;
        }

        // Always attempt to query from its parent, to allow the element itself to match the queries
        const target = mutation.target.parentElement || mutation.target;

        // Images
        queryQueue.add(() => {
          const images = target.querySelectorAll(SELECTORS_IMAGE);

          let i = 0;
          for (const image of images) {
            if (doImage(image)) {
              i++;
            }
          }

          if (i > 0) {
            log(`Processed ${i} image(s).`);
          }
        });

        // Illust controls
        queryQueue.add(() => {
          const illustControls = target.querySelector(SELECTORS_ILLUST_CONTROLS);
          if (illustControls && doIllustControls(illustControls)) {
            log('Processed illust control.');
          }
        });

        // Dates
        if (DATE_CONVERSION) {
          queryQueue.add(() => {
            const dates = target.querySelectorAll(SELECTORS_DATE);

            let i = 0;
            for (const date of dates) {
              if (convertDate(date)) {
                i++;
              }
            }

            if (i > 0) {
              log(`Processed ${i} date element(s).`);
            }
          });
        }
      }
    }, ...args);
  });

})()