☰

Redgifs media controls

Adds reliable keyboard media controls for the current Redgifs player

スクリプトをインストールするには、Tampermonkey, Greasemonkey や Violentmonkey のような拡張機能のインストールが必要です。

スクリプトをインストールするには、 Tampermonkey や Violentmonkey のような拡張機能のインストールが必要です。

スクリプトをインストールするには、Tampermonkey や Violentmonkey のような拡張機能のインストールが必要です。

スクリプトをインストールするには、Tampermonkey や Userscripts のような拡張機能のインストールが必要です。

このスクリプトをインストールするには、Tampermonkeyなどの拡張機能をインストールする必要があります。

このスクリプトをインストールするには、ユーザースクリプト管理ツールの拡張機能をインストールする必要があります。

(ユーザースクリプト管理ツールは設定済みなのでインストール!)

このスタイルをインストールするには、Stylusなどの拡張機能をインストールする必要があります。

このスタイルをインストールするには、Stylus などの拡張機能をインストールする必要があります。

このスタイルをインストールするには、Stylus tなどの拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

このスタイルをインストールするには、ユーザースタイル管理用の拡張機能をインストールする必要があります。

(ユーザースタイル管理ツールは設定済みなのでインストール!)

このスクリプトの質問や評価の投稿はこちら、通報はこちらへお寄せください
// ==UserScript==
// @name         Redgifs media controls
// @namespace    http://tampermonkey.net/
// @version      3.0.0
// @description  Adds reliable keyboard media controls for the current Redgifs player
// @author       You
// @match        https://redgifs.com/*
// @match        https://*.redgifs.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=redgifs.com
// @license      MIT
// @grant        none
// @run-at       document-idle
// ==/UserScript==

/* jshint esversion: 11 */

(function() {
  "use strict";

  const STORAGE = { MUTED: "rgmc-muted" };
  const PLAYER_SELECTORS = [".Player", ".GifPreview", "[class*='Player']", "[class*='GifPreview']"];
  const FULLSCREEN_SELECTORS = [
    ".FSButton", "button[aria-label*='fullscreen' i]", "button[title*='fullscreen' i]",
    "[role='button'][aria-label*='fullscreen' i]", "[class*='FullscreenButton']",
    "[class*='fullscreenButton']"
  ];
  const DOWNLOAD_BUTTON_CLASS = "rgmc-download-button";
  let activeVideo = null;
  let refreshQueued = false;

  function isVisible(element) {
    if (!element?.isConnected) return false;
    const style = window.getComputedStyle(element);
    const rect = element.getBoundingClientRect();
    return style.display !== "none" && style.visibility !== "hidden" && Number(style.opacity) !== 0 &&
      rect.width > 0 && rect.height > 0 && rect.bottom > 0 && rect.right > 0 &&
      rect.top < window.innerHeight && rect.left < window.innerWidth;
  }

  function visibleArea(element) {
    const rect = element.getBoundingClientRect();
    const width = Math.max(0, Math.min(rect.right, innerWidth) - Math.max(rect.left, 0));
    const height = Math.max(0, Math.min(rect.bottom, innerHeight) - Math.max(rect.top, 0));
    return width * height;
  }

  function getActiveVideo() {
    if (document.fullscreenElement) {
      const fullscreenVideo = document.fullscreenElement.matches("video")
        ? document.fullscreenElement : document.fullscreenElement.querySelector("video");
      if (fullscreenVideo) return fullscreenVideo;
    }
    const videos = Array.from(document.querySelectorAll("video")).filter(isVisible);
    if (!videos.length) return activeVideo?.isConnected ? activeVideo : null;

    const playingVideos = videos.filter(video => !video.paused && !video.ended);
    const candidates = playingVideos.length ? playingVideos : videos;
    const siteActiveVideos = candidates.filter(video => video.closest(
      ".GifPreview_isActive, .Player_isActive, .GifPreview.VisibleOnly"
    ));
    const rankedVideos = siteActiveVideos.length ? siteActiveVideos : candidates;

    return rankedVideos.sort((a, b) => visibleArea(b) - visibleArea(a))[0];
  }

  function getPlayer(video = getActiveVideo()) {
    if (!video) return null;
    for (const selector of PLAYER_SELECTORS) {
      const player = video.closest(selector);
      if (player) return player;
    }
    return video.parentElement || video;
  }

  function applySavedMuteState(video) {
    const saved = localStorage.getItem(STORAGE.MUTED);
    if (video && saved !== null) video.muted = saved === "true";
  }

  function refreshActiveVideo() {
    const nextVideo = getActiveVideo();
    if (!nextVideo) return activeVideo;
    if (nextVideo === activeVideo) {
      addDownloadButton(activeVideo);
      return activeVideo;
    }
    activeVideo = nextVideo;
    applySavedMuteState(activeVideo);
    addDownloadButton(activeVideo);
    return activeVideo;
  }

  function queueRefresh() {
    if (refreshQueued) return;
    refreshQueued = true;
    requestAnimationFrame(() => {
      refreshQueued = false;
      refreshActiveVideo();
      addDownloadButtons();
      linkDescriptionTags();
    });
  }

  function requireVideo() { return refreshActiveVideo() || getActiveVideo(); }

  function toggleSound(forceAudible = false) {
    const video = requireVideo();
    if (!video) return;
    video.muted = forceAudible ? false : !video.muted;
    if (!video.muted && video.volume === 0) video.volume = 1;
    localStorage.setItem(STORAGE.MUTED, String(video.muted));
  }

  function getControlRoot(video = requireVideo()) {
    let element = video?.parentElement;
    while (element && element !== document.body) {
      if (FULLSCREEN_SELECTORS.some(selector => element.querySelector(selector))) return element;
      element = element.parentElement;
    }
    return null;
  }

  function toggleFullscreen() {
    const video = requireVideo();
    const controlRoot = getControlRoot(video);
    if (!controlRoot) return;
    for (const selector of FULLSCREEN_SELECTORS) {
      const button = controlRoot.querySelector(selector);
      if (button) {
        button.click();
        return;
      }
    }
    console.info("RGMC: Redgifs fullscreen control was not found");
  }

  function togglePlayState(forcePlay) {
    const video = requireVideo();
    if (!video) return;
    if (forcePlay === false || (forcePlay === undefined && !video.paused)) video.pause();
    else video.play().catch(() => {});
  }

  function seekVideo(value, useTenths = false) {
    const video = requireVideo();
    if (!video) return;
    const destination = useTenths ? (Number(value) * video.duration) / 10 : video.currentTime + Number(value);
    if (Number.isFinite(destination)) video.currentTime = Math.max(0, Math.min(video.duration || destination, destination));
  }

  function getMediaId(video = requireVideo()) {
    const player = getPlayer(video);
    const container = player?.closest("[data-feed-item-id]") || player;
    const feedId = container?.dataset?.feedItemId;
    if (feedId && !feedId.startsWith("feed-module-")) return feedId.toLowerCase();
    const match = location.pathname.match(/\/(?:watch|ifr)\/([^/?#]+)/i);
    return match?.[1]?.toLowerCase() || null;
  }

  async function getDownloadInfo(video = requireVideo()) {
    const mediaId = getMediaId(video);
    if (!mediaId) throw new Error("Could not determine the Redgifs media ID");
    const directSource = video?.currentSrc || video?.src;
    if (directSource && !directSource.startsWith("blob:")) {
      return { mediaId, url: directSource.replace(/-silent(?=\.mp4)/i, "") };
    }
    const response = await fetch(`https://www.redgifs.com/watch/${mediaId}`);
    if (!response.ok) throw new Error(`Redgifs page request failed (${response.status})`);
    const doc = new DOMParser().parseFromString(await response.text(), "text/html");
    const url = doc.querySelector('meta[property="og:video"]')?.content?.replace(/-silent(?=\.mp4)/i, "");
    if (!url) throw new Error("Could not find the HD media URL");
    return { mediaId, url };
  }

  function getDownloadButton(video = requireVideo()) {
    const controlRoot = getControlRoot(video);
    return controlRoot?.querySelector(`.${DOWNLOAD_BUTTON_CLASS}`) || null;
  }

  function setDownloadProgress(button, progress) {
    const circle = button?.querySelector(".rgmc-download-progress");
    if (!circle) return;
    const value = Math.max(0, Math.min(1, Number(progress) || 0));
    circle.style.strokeDashoffset = String(100 * (1 - value));
  }

  async function readDownloadBlob(response, onProgress) {
    const total = Number(response.headers.get("content-length"));
    if (!response.body || !Number.isFinite(total) || total <= 0) {
      const blob = await response.blob();
      onProgress(1);
      return blob;
    }

    const reader = response.body.getReader();
    const chunks = [];
    let received = 0;
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      chunks.push(value);
      received += value.byteLength;
      onProgress(received / total);
    }
    onProgress(1);
    return new Blob(chunks, { type: response.headers.get("content-type") || "video/mp4" });
  }

  async function downloadVideo(button = null, video = null) {
    video = video || requireVideo();
    button = button || getDownloadButton(video);
    if (button?.disabled) return;
    const originalTitle = button?.title;
    if (button) {
      button.disabled = true;
      button.title = "Downloading… 0%";
      setDownloadProgress(button, 0);
    }
    let objectUrl = null;
    let link = null;
    try {
      const { mediaId, url } = await getDownloadInfo(video);
      const response = await fetch(url);
      if (!response.ok) throw new Error(`Media request failed (${response.status})`);
      const blob = await readDownloadBlob(response, progress => {
        setDownloadProgress(button, progress);
        if (button) button.title = `Downloading… ${Math.round(progress * 100)}%`;
      });
      objectUrl = URL.createObjectURL(blob);
      link = document.createElement("a");
      link.href = objectUrl;
      link.download = `${mediaId}.mp4`;
      document.body.appendChild(link);
      link.click();
    } catch (error) {
      console.error("RGMC: download failed", error);
      setDownloadProgress(button, 0);
    } finally {
      link?.remove();
      if (objectUrl) setTimeout(() => URL.revokeObjectURL(objectUrl), 60000);
      if (button) {
        button.disabled = false;
        button.title = originalTitle || "Download HD video (D)";
        if (objectUrl) setTimeout(() => setDownloadProgress(button, 0), 1500);
      }
    }
  }

  function addDownloadButtons(root = document) {
    const previews = root.matches?.(".GifPreview") ? [root] : root.querySelectorAll(".GifPreview");
    previews.forEach(preview => addDownloadButton(preview.querySelector("video"), preview));
  }

  function addDownloadButton(video = null, controlRoot = null) {
    controlRoot = controlRoot || getControlRoot(video || requireVideo());
    if (!controlRoot) return;
    const fullscreenButton = FULLSCREEN_SELECTORS
      .map(selector => controlRoot.querySelector(selector))
      .find(Boolean);
    if (!fullscreenButton) return;

    const fullscreenItem = fullscreenButton.closest("li") || fullscreenButton;
    const controls = fullscreenItem.parentElement;
    if (!controls) return;

    const existing = controlRoot.querySelector(`.${DOWNLOAD_BUTTON_CLASS}`);
    if (existing) {
      const existingItem = existing.closest("li") || existing;
      if (existingItem.parentElement === controls && existingItem.nextElementSibling === fullscreenItem) return;
      existingItem.remove();
    }

    const button = document.createElement("button");
    button.type = "button";
    button.className = DOWNLOAD_BUTTON_CLASS;
    button.title = "Download HD video (D)";
    button.setAttribute("aria-label", "Download HD video");
    button.innerHTML = '<svg class="rgmc-download-icon" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v12m0 0 5-5m-5 5-5-5M5 19h14"/></svg><svg class="rgmc-download-ring" viewBox="0 0 36 36" aria-hidden="true"><circle class="rgmc-download-progress" cx="18" cy="18" r="15.9155" pathLength="100"/></svg>';
    Object.assign(button.style, { width: "36px", height: "36px", padding: "6px", border: "0",
      background: "transparent", color: "inherit", cursor: "pointer", display: "grid", placeItems: "center",
      position: "relative" });
    const icon = button.querySelector(".rgmc-download-icon");
    Object.assign(icon.style, { width: "24px", height: "24px", fill: "none", stroke: "currentColor",
      strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round" });
    const ring = button.querySelector(".rgmc-download-ring");
    Object.assign(ring.style, { position: "absolute", inset: "0", width: "36px", height: "36px",
      fill: "none", pointerEvents: "none", transform: "rotate(-90deg)" });
    const progressCircle = button.querySelector(".rgmc-download-progress");
    Object.assign(progressCircle.style, { fill: "none", stroke: "currentColor", strokeWidth: "2",
      strokeLinecap: "round", strokeDasharray: "100", strokeDashoffset: "100",
      transition: "stroke-dashoffset 120ms linear" });
    button.addEventListener("click", event => {
      event.preventDefault();
      event.stopPropagation();
      downloadVideo(button, controlRoot.querySelector("video") || video);
    });
    let item = button;
    if (fullscreenItem !== fullscreenButton && fullscreenItem.tagName === "LI") {
      item = document.createElement("li");
      item.className = fullscreenItem.className;
      item.appendChild(button);
    }
    controls.insertBefore(item, fullscreenItem);
  }

  function isTypingTarget(target) {
    return target instanceof Element && Boolean(target.closest(
      "input, textarea, select, [contenteditable='true'], [role='textbox']"));
  }

  function linkDescriptionTags(root = document) {
    root.querySelectorAll(".descriptionText").forEach(description => {
      if (description.querySelector(".rgmc-description-tags")) return;
      const text = description.textContent || "";
      const match = text.match(/(?:\s+|^)((?:#[\p{L}\p{N}_-]+(?:\s+|$))+?)\s*$/u);
      if (!match) return;

      const tags = Array.from(match[1].matchAll(/#([\p{L}\p{N}_-]+)/gu));
      if (!tags.length) return;

      const descriptionText = text.slice(0, match.index).trimEnd();
      const tagList = document.createElement("span");
      tagList.className = "rgmc-description-tags";
      tagList.setAttribute("aria-label", "Tags");
      Object.assign(tagList.style, {
        display: "inline-flex",
        flexWrap: "wrap",
        gap: "0.35em",
        marginLeft: descriptionText ? "0.35em" : "0"
      });

      for (const tagMatch of tags) {
        const tag = tagMatch[1];
        const link = document.createElement("a");
        link.href = `/gifs/${encodeURIComponent(tag)}`;
        link.textContent = `#${tag}`;
        link.className = "rgmc-description-tag";
        tagList.appendChild(link);
      }

      description.replaceChildren(document.createTextNode(descriptionText), tagList);
    });
  }

  document.addEventListener("keydown", event => {
    if (event.ctrlKey || event.metaKey || event.altKey || isTypingTarget(event.target)) return;
    let handled = true;
    switch (event.code) {
      case "KeyF": toggleFullscreen(); break;
      case "KeyM": toggleSound(); break;
      case "Space": togglePlayState(); break;
      case "KeyD": downloadVideo(); break;
      case "ArrowLeft": seekVideo(-5); break;
      case "ArrowRight": seekVideo(5); break;
      case "Digit0": case "Digit1": case "Digit2": case "Digit3": case "Digit4":
      case "Digit5": case "Digit6": case "Digit7": case "Digit8": case "Digit9":
        seekVideo(Number(event.code.slice(-1)), true); break;
      default: handled = false;
    }
    if (handled) { event.preventDefault(); event.stopImmediatePropagation(); }
  }, true);

  document.addEventListener("scroll", queueRefresh, { passive: true });
  document.addEventListener("fullscreenchange", queueRefresh);
  window.addEventListener("popstate", queueRefresh);
  window.addEventListener("focus", queueRefresh);
  new MutationObserver(queueRefresh).observe(document.documentElement, {
    childList: true,
    characterData: true,
    subtree: true
  });
  refreshActiveVideo();
  addDownloadButtons();
  linkDescriptionTags();
  setTimeout(refreshActiveVideo, 1000);

  window.__rgmc__ = { getActiveVideo, getPlayer, getMediaId, toggleSound,
    togglePlayState, toggleFullscreen, downloadVideo, seekVideo };
  console.info("RGMC 3.2.1 initialized");
})();