☰

Ferry Studio: JAV subtitles button

On FANZA, MGStage, JavLibrary, JavDB and r18.dev video pages, reads the video code and adds a small button that opens its subtitle page on ferrystudio.app (Chinese, English, Korean and more), plus a "copy code" button.

Dovrai installare un'estensione come Tampermonkey, Greasemonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Userscripts per installare questo script.

Dovrai installare un'estensione come ad esempio Tampermonkey per installare questo script.

Dovrai installare un gestore di script utente per installare questo script.

(Ho già un gestore di script utente, lasciamelo installare!)

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

(Ho già un gestore di stile utente, lasciamelo installare!)

// ==UserScript==
// @name         Ferry Studio: JAV subtitles button
// @name:zh-CN   Ferry Studio:番号中文字幕按钮
// @name:zh-TW   Ferry Studio:番號中文字幕按鈕
// @name:ja      Ferry Studio:品番の字幕ボタン
// @name:ko      Ferry Studio: 품번 자막 버튼
// @namespace    https://ferrystudio.app/
// @version      1.0.0
// @description  On FANZA, MGStage, JavLibrary, JavDB and r18.dev video pages, reads the video code and adds a small button that opens its subtitle page on ferrystudio.app (Chinese, English, Korean and more), plus a "copy code" button.
// @description:zh-CN 在 FANZA、MGStage、JavLibrary、JavDB、r18.dev 的影片页识别番号,右下角加一个按钮:一键打开 ferrystudio.app 上该番号的字幕页(中文、英文、韩文等),并可一键复制番号。
// @description:zh-TW 在 FANZA、MGStage、JavLibrary、JavDB、r18.dev 的影片頁辨識番號,右下角加一個按鈕:一鍵開啟 ferrystudio.app 上該番號的字幕頁(中文、英文、韓文等),並可一鍵複製番號。
// @description:ja FANZA・MGStage・JavLibrary・JavDB・r18.dev の作品ページで品番を読み取り、右下に ferrystudio.app の字幕ページ(中国語・英語・韓国語など)を開くボタンと品番コピーボタンを追加します。
// @description:ko FANZA, MGStage, JavLibrary, JavDB, r18.dev 작품 페이지에서 품번을 읽어 오른쪽 아래에 ferrystudio.app 자막 페이지(한국어·중국어·영어 등)를 여는 버튼과 품번 복사 버튼을 추가합니다.
// @author       Ferry Studio
// @homepageURL  https://ferrystudio.app/
// @supportURL   https://ferrystudio.app/
// @license      MIT
// @match        https://www.dmm.co.jp/digital/videoa/-/detail/*
// @match        https://www.dmm.co.jp/mono/dvd/-/detail/*
// @match        https://video.dmm.co.jp/av/content/*
// @match        https://www.mgstage.com/product/product_detail/*
// @match        https://www.javlibrary.com/*
// @match        https://javdb.com/v/*
// @match        https://r18.dev/videos/vod/movies/detail/*
// @grant        none
// @run-at       document-idle
// @noframes
// ==/UserScript==

/*
 * What it does, and nothing else: finds the video code on the page you are viewing (from the address or the page's own
 * "code" field), and shows a button that opens https://ferrystudio.app/<your language>/v/<code> in a new tab.
 * No data is collected or sent anywhere; the script makes no network requests of its own.
 */
(function () {
  "use strict";

  // ---------- code detection (pure functions, also used by the tests)

  /** "snos00461" -> "SNOS-461", "1start00664" -> "START-664", "h_1234abc00012" -> "ABC-012". null if not a code. */
  function codeFromCid(cid) {
    const m = String(cid || "").toLowerCase().match(/^(?:h_\d+)?\d*([a-z]{2,8})(\d{2,6})[a-z]?$/);
    if (!m) return null;
    const digits = String(parseInt(m[2], 10)).padStart(3, "0");
    return `${m[1].toUpperCase()}-${digits}`;
  }

  /** "snos-461", "SNOS461", "SNOS 461" -> "SNOS-461"; MGS style "300MIUM-123" is kept. null if no code. */
  function normalizeCode(text) {
    const m = String(text || "").toUpperCase().match(/(\d{0,4}[A-Z]{2,8})[-_ ]?(\d{2,6})/);
    if (!m) return null;
    const digits = m[2].length < 3 ? m[2].padStart(3, "0") : m[2];
    return `${m[1]}-${digits}`;
  }

  /** The code of the page, or null. `loc` and `doc` are window.location and document (passed in for testing). */
  function findCode(loc, doc) {
    const host = loc.hostname;
    const path = decodeURIComponent(loc.pathname);
    const q = (sel) => doc.querySelector(sel);
    if (host === "www.dmm.co.jp") {
      const m = path.match(/\/cid=([a-z0-9_]+)/i);
      return m ? codeFromCid(m[1]) : null;
    }
    if (host === "video.dmm.co.jp") {
      const id = new URLSearchParams(loc.search).get("id");
      return id ? codeFromCid(id) : null;
    }
    if (host === "www.mgstage.com") {
      const m = path.match(/product_detail\/([A-Z0-9]+-\d+)/i);
      return m ? m[1].toUpperCase() : null;
    }
    if (host === "www.javlibrary.com") {
      const el = q("#video_id .text");
      return el ? normalizeCode(el.textContent) : null;
    }
    if (host === "javdb.com") {
      const copy = q("[data-clipboard-text]");
      if (copy) return normalizeCode(copy.getAttribute("data-clipboard-text"));
      const title = q("h2.title strong, .video-detail strong");
      return title ? normalizeCode(title.textContent) : null;
    }
    if (host === "r18.dev") {
      // The page lists "DVD ID: SNOS-461"; the address only has the content id (snos00461).
      const label = Array.prototype.find.call(doc.querySelectorAll("dt, th, span, div"), (e) => /^\s*DVD ID\s*:?\s*$/i.test(e.textContent));
      const value = label && label.nextElementSibling && normalizeCode(label.nextElementSibling.textContent);
      if (value) return value;
      const m = path.match(/id=([a-z0-9_]+)/i);
      return m ? codeFromCid(m[1]) : null;
    }
    return null;
  }

  // ---------- language of the visitor

  const LANGS = {
    zh: { open: "中文字幕", copy: "复制番号", copied: "已复制", close: "关闭" },
    tw: { open: "中文字幕", copy: "複製番號", copied: "已複製", close: "關閉" },
    ja: { open: "字幕", copy: "品番をコピー", copied: "コピーしました", close: "閉じる" },
    ko: { open: "한글자막", copy: "품번 복사", copied: "복사됨", close: "닫기" },
    en: { open: "Subtitles", copy: "Copy code", copied: "Copied", close: "Close" },
  };
  function siteLang(navLangs) {
    for (const l of navLangs || []) {
      const s = String(l).toLowerCase();
      if (/^zh-(tw|hk|mo|hant)/.test(s)) return "tw";
      if (s.startsWith("zh")) return "zh";
      if (s.startsWith("ja")) return "ja";
      if (s.startsWith("ko")) return "ko";
      if (s.startsWith("en")) return "en";
    }
    return "en";
  }
  const subtitleUrl = (lang, code) => `https://ferrystudio.app/${lang}/v/${encodeURIComponent(code.toLowerCase())}`;

  // ---------- the button (in a shadow root, so the page's CSS can't break it and ours can't break the page)

  function mount(code, lang) {
    const t = LANGS[lang];
    let host = document.getElementById("ferry-subtitles-button");
    if (!host) {
      host = document.createElement("div");
      host.id = "ferry-subtitles-button";
      host.style.cssText = "position:fixed;right:16px;bottom:16px;z-index:2147483646;";
      host.attachShadow({ mode: "open" });
      document.documentElement.appendChild(host);
    }
    host.shadowRoot.innerHTML = `
      <style>
        .bar { display:flex; align-items:center; gap:2px; padding:4px; border-radius:999px; background:#4f46e5;
               box-shadow:0 6px 24px rgba(0,0,0,.28); font:600 14px/1 system-ui,-apple-system,"Segoe UI",sans-serif; }
        a, button { all:unset; cursor:pointer; color:#fff; border-radius:999px; }
        a { padding:9px 14px; white-space:nowrap; }
        a:hover, button:hover { background:rgba(255,255,255,.16); }
        button { width:30px; height:30px; display:grid; place-items:center; font-size:15px; }
        .code { opacity:.8; font-weight:500; }
      </style>
      <div class="bar">
        <a target="_blank" rel="noopener" title="ferrystudio.app">${t.open} · <span class="code"></span></a>
        <button class="copy" title="${t.copy}" aria-label="${t.copy}">⧉</button>
        <button class="close" title="${t.close}" aria-label="${t.close}">×</button>
      </div>`;
    const root = host.shadowRoot;
    root.querySelector(".code").textContent = code;
    root.querySelector("a").href = subtitleUrl(lang, code);
    const copyBtn = root.querySelector(".copy");
    copyBtn.addEventListener("click", () => {
      navigator.clipboard.writeText(code).then(() => {
        copyBtn.textContent = "✓";
        copyBtn.title = t.copied;
        setTimeout(() => { copyBtn.textContent = "⧉"; copyBtn.title = t.copy; }, 1500);
      });
    });
    root.querySelector(".close").addEventListener("click", () => {
      host.remove();
      dismissed = location.href; // hidden on this page only
    });
  }

  let shownFor = null;
  let dismissed = null;
  function update() {
    if (location.href === dismissed) return;
    const code = findCode(location, document);
    if (!code) {
      const old = document.getElementById("ferry-subtitles-button");
      if (old) old.remove();
      shownFor = null;
      return;
    }
    if (code === shownFor && document.getElementById("ferry-subtitles-button")) return;
    shownFor = code;
    mount(code, siteLang(navigator.languages || [navigator.language]));
  }

  if (typeof module === "object" && module.exports) {
    module.exports = { codeFromCid, normalizeCode, findCode, siteLang, subtitleUrl }; // node tests only
    return;
  }
  update();
  // Pages that change without reloading (video.dmm.co.jp) or fill in the code late: check once a second.
  let lastHref = location.href;
  setInterval(() => {
    if (location.href !== lastHref || !shownFor) {
      lastHref = location.href;
      update();
    }
  }, 1000);
})();