☰

Rule34.xxx Video Previews

Preview video posts automatically or by keyboard shortcut when hovered over a thumbnail

Bu betiği kurabilmeniz için Tampermonkey, Greasemonkey ya da Violentmonkey gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

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

Bu betiği kurabilmeniz için Tampermonkey ya da Violentmonkey gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

Bu betiği kurabilmeniz için Tampermonkey ya da Userscripts gibi bir kullanıcı betiği eklentisini kurmanız gerekmektedir.

Bu betiği indirebilmeniz için ayrıca Tampermonkey gibi bir eklenti kurmanız gerekmektedir.

Bu betiği yüklemek için bir betik yöneticisi eklentisi yüklemeniz gerekecektir.

(Zaten bir betik yöneticim var, hadi yükleyelim!)

Bu stili yüklemek için Stylus gibi bir uzantı yüklemeniz gerekir.

Bu stili yüklemek için Stylus gibi bir uzantı kurmanız gerekir.

Bu stili yükleyebilmek için Stylus gibi bir uzantı yüklemeniz gerekir.

Bu stili yüklemek için bir kullanıcı stili yöneticisi uzantısı yüklemeniz gerekir.

Bu stili yüklemek için bir kullanıcı stili yöneticisi uzantısı kurmanız gerekir.

Bu stili yükleyebilmek için bir kullanıcı stili yöneticisi uzantısı yüklemeniz gerekir.

(Zateb bir user-style yöneticim var, yükleyeyim!)

// ==UserScript==
// @name          Rule34.xxx Video Previews
// @namespace     861ddd094884eac5bea7a3b12e074f34
// @description   Preview video posts automatically or by keyboard shortcut when hovered over a thumbnail
// @author        Anonymous
// @version       2.1.0
// @license       0BSD
// @match         https://rule34.xxx/index.php?*
// @icon          https://external-content.duckduckgo.com/ip3/rule34.xxx.ico
// @grant         GM.getValue
// @grant         GM.setValue
// @grant         GM.registerMenuCommand
// @grant         GM.unregisterMenuCommand
// @grant         GM.addStyle
// @grant         GM.xmlHttpRequest
// @connect       self
// ==/UserScript==

/* CONTRIBUTORS
******************

Thanks to SepiaMoon for support!

LLM assistance from:
- Claude Haiku 4.5
- Raptor mini
- Grok Code Fast
- Claude Sonnet 4.6
- Claude Fable 5

   TODO
 ********

- implement features
  - easy assignment of custom keybind
  - auto-sense regional image server

*/

// Lineage note: the hover-preview concept originated in Zeus's
//   "Rule34 Preview Videos" 0.2 (MIT); this script is a full independent
//   reimplementation sharing no protectable expression with it.


(async function() {
  'use strict';

  let CONFIG = {
    // start preview videos with volume muted
    // required to be true for autoplay to work without user intervention
    'start_muted': await GM.getValue('start_muted', true),
    // duration (ms) to wait after thumbnail hover to load preview
    'hover_delay': await GM.getValue('hover_delay', 500),
    // toggle expectation of using the keybind to activate previews
    'prefer_hotkey': await GM.getValue('prefer_hotkey', false),
    // the key (combination) for activating previews in hotkey mode
    'keybind': await GM.getValue('custom_keybind', 'p'),
    // display video controls on previews?
    'controllable': await GM.getValue('controllable', true),
    // rule34.xxx video cdn fqdn (auto-configured when user is logged in)
    'video_cdn': await GM.getValue('video_cdn', 'https://api-cdn-mp4.rule34.xxx'),
    // rule34.xxx image server fqdn
    'image_server': await GM.getValue('image_server', 'https://us.rule34.xxx'),
    // duration (ms) to wait before inspecting and caching thumbnail list
    // required when using scripts for masonry view such as Rule34 Enhanced Dark Gallery
    'init_delay': await GM.getValue('init_delay', 1000),
  };

  let NAME = 'Rule34.xxx Video Previews';
  let PREVIEWABLES = [];
  let MENU_COMMANDS = [];
  let PARAMS = new URLSearchParams(window.location.search);

  const INPLACE = (async () => {
    const testId = '__inplace_test__';
    const supported = testId === await GM.registerMenuCommand('test', () => {}, { id: testId });
    await GM.unregisterMenuCommand(testId);
    return supported;
  })();

  async function refreshMenuCommand(entry) {
    if (INPLACE) {
      // title is re-evaluated when labelFn() is ran
      await GM.registerMenuCommand(entry.labelFn(), entry.onClick, { id: entry.id });
    } else {
      for (const e of MENU_COMMANDS) await GM.unregisterMenuCommand(e.id);
      for (const e of MENU_COMMANDS) await GM.registerMenuCommand(e.labelFn(), e.onClick, { id: e.id });
    }
  }

  async function toggleSetting(key, entry) {
    CONFIG[key] = !CONFIG[key];
    await GM.setValue(key, CONFIG[key]);
    await refreshMenuCommand(entry);
  }

  async function defineMenuCommand(id, labelFn, onClick) {
    const entry = { id, labelFn, onClick };
    MENU_COMMANDS.push(entry);
    await GM.registerMenuCommand(labelFn(), onClick, { id });
    return entry;
  }

  const cmdHotkey = await defineMenuCommand(
    'prefer_hotkey',
    () => `${CONFIG.prefer_hotkey ? 'Disable' : 'Enable'} hotkey activation (${CONFIG.keybind})`,
    async () => await toggleSetting('prefer_hotkey', cmdHotkey)
  );
  const cmdMute = await defineMenuCommand(
    'start_muted',
    () => `${CONFIG.start_muted ? 'Disable' : 'Enable'} auto-mute`,
    async () => await toggleSetting('start_muted', cmdMute)
  );
  const cmdControls = await defineMenuCommand(
    'controllable',
    () => `${CONFIG.controllable ? 'Disable' : 'Enable'} video controls`,
    async () => await toggleSetting('controllable', cmdControls)
  );

  if (!CONFIG.video_cdn) {
    let xhr = await GM.xmlHttpRequest({
      url: '/index.php?page=account&s=options',
      method: 'GET',
      responseType: 'document'
    });
    if (xhr.status !== 200) {
      console.info(`${NAME}: Initialized with default CDN region.`);
    } else {
      let d = xhr.response;
      let cdnRegion = d.querySelector('input[name="domain"]:checked').id;
      const constructUrl = s => `https://${s}.rule34.xxx`;
      if (cdnRegion === 'domCentral USA') {
        await GM.setValue('video_cdn', constructUrl('uswebm'));
      } else if (cdnRegion === 'domEast USA') {
        await GM.setValue('video_cdn', constructUrl('nymp4'));
      } else if (cdnRegion === 'domWest USA') {
        const randomChoice = arr => arr[Math.floor(Math.random() * arr.length)];
        await GM.setValue('video_cdn', constructUrl(
          randomChoice(['ahrimp4', 'ahri2mp4', 'ahri4mp4'])
        ));
      } else if (cdnRegion === 'domEU') {
        await GM.setValue('video_cdn', constructUrl('wwebm'));
      }
      console.info(`${NAME}: Video CDN loaded from user settings.`);
    }
    CONFIG.video_cdn = await GM.getValue('video_cdn');
  }

  // previews overlay the thumbnail in-place: the video is absolutely
  //   positioned over the image inside the thumb anchor and toggled with
  //   opacity, so the container never changes size (no layout bounce, no
  //   premature mouse events)
  // !important + high-specificity selectors are required to beat Booru
  //   Enhanced Dark Gallery's 'span.thumb video { height: auto !important }'
  await GM.addStyle(`
    .r34vp-host {
      position: relative !important;
    }
    .thumb video.r34vp-video {
      position: absolute !important;
      top: 0 !important;
      left: 0 !important;
      width: 100% !important;
      height: 100% !important;
      max-width: 100% !important;
      max-height: 100% !important;
      object-fit: contain !important;
      opacity: 0;
      pointer-events: none;
      z-index: 10;
      transition: opacity 0.15s ease;
    }
    .thumb .r34vp-active video.r34vp-video,
    .thumb.r34vp-active video.r34vp-video {
      opacity: 1;
      pointer-events: auto;
    }
    .r34vp-active img {
      opacity: 0;
    }
  `);

  const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
  await delay(CONFIG.init_delay);

  function getDeepActiveElement() {
      let el = document.activeElement;
      while (el?.shadowRoot?.activeElement) el = el.shadowRoot.activeElement;
      return el;
  }

  // thumbnail path carries everything needed to address both full-size
  //   media endpoints: /thumbnails/<dir>/thumbnail_<hash>.<ext>
  // leading slashes vary: site emits 'https://us.rule34.xxx//thumbnails/...'
  // masonry scripts (Enhanced Dark Gallery) swap srcs to full '/images/...' paths
  const THUMB_PATH = /^\/*(?:thumbnails|images)(\/.+\/)(?:thumbnail_)?([^/]+)\.(jpe?g|png)$/;

  function createVideoElement(imgPath) {
    const parsed = THUMB_PATH.exec(imgPath);
    if (!parsed) {
      console.warn(`${NAME}: Unrecognized thumbnail path (${imgPath})`);
      return null;
    }
    const [, dir, hash, ext] = parsed;

    const video = document.createElement('video');
    video.className = 'r34vp-video';
    video.muted = CONFIG.start_muted;
    video.controls = CONFIG.controllable;
    video.loop = true;
    video.preload = 'metadata';
    video.poster = `${CONFIG.image_server}/images${dir}${hash}.${ext}`;

    const source = document.createElement('source');
    source.src = `${CONFIG.video_cdn}/images${dir}${hash}.mp4`;
    source.type = 'video/mp4';
    video.append(source);

    return video;
  }

  // select only video thumbnails up front; static images never enter the loop
  for (const img of document.querySelectorAll('.image-list .thumb img.preview.webm-thumb')) {
    const link = img.closest('a');
    const container = img.closest('.thumb');
    if (!link || !container) continue;

    const postId = new URL(link.href).searchParams.get('id');
    const imgPath = new URL(img.src).pathname;

    let video = null;
    const state = {
      hoverTimer: null,
      hotkeyActivated: false,
    };

    const reveal = () => link.classList.add('r34vp-active');

    function showPreview() {
      if (!video) {
        video = createVideoElement(imgPath);
        if (!video) return;
        // mount inside the anchor: it is the visual card under Booru
        //   Enhanced Dark Gallery masonry, while the outer span's height
        //   is a grid allocation that may not match the image
        link.classList.add('r34vp-host');
        link.append(video);
        console.info(`${NAME}: Previewed post (${postId})`);
      }

      video.play();
      // reveal only once frames are decodable to avoid a blank overlay
      if (video.readyState >= 2)
        reveal();
      else
        video.addEventListener('canplay', reveal, { once: true });

      if (CONFIG.prefer_hotkey)
        state.hotkeyActivated = true;
    }

    function hidePreview() {
      if (!video) return;
      video.removeEventListener('canplay', reveal);
      link.classList.remove('r34vp-active');
      video.pause();
      state.hotkeyActivated = false;
    }

    // always bind event listeners even if logic won't execute
    //   to support dynamic re-configuration of preview activation
    container.addEventListener('mouseenter', () => {
      // wait before previewing to minimize disruptive mousing across page
      if (!CONFIG.prefer_hotkey)
        state.hoverTimer = setTimeout(showPreview, CONFIG.hover_delay);
    });

    // moving away resets preview regardless of hotkey preference
    container.addEventListener('mouseleave', () => {
      clearTimeout(state.hoverTimer);
      if (!CONFIG.prefer_hotkey || state.hotkeyActivated)
        hidePreview();
    });

    PREVIEWABLES.push({
      element: container,
      state: state,
      show: showPreview,
      hide: hidePreview,
    });
  }

  document.addEventListener('keydown', async function(e) {
    if (!CONFIG.prefer_hotkey) return;
    const tagExclusions = ['INPUT', 'TEXTAREA', 'SELECT'];
    const active = getDeepActiveElement();
    if (
        active.isContentEditable
        || tagExclusions.includes(active.tagName)
        || active.getAttribute('role') === 'search' // zerochan
    )
        return;
    if (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey) return;
    if (e.key.toLowerCase() !== CONFIG.keybind) return;

    let span = document.querySelector('span:hover');
    if (!span) return;
    let spanCn = span.childElementCount;
    if (spanCn !== 1) return;
    let link = span.children[0];
    let linkCn = link.childElementCount;
    if (linkCn < 1 || linkCn > 2) return; // 2 when video loaded
    let img = link.children[0];
    if (img.tagName !== 'IMG') return;
    if (PARAMS.get('page') !== 'favorites')
      if (!img.classList.contains('preview')) return;

    let entry = PREVIEWABLES.find(d => d.element === span);
    if (!entry) return;
    if (entry.state.hotkeyActivated)
      entry.hide();
    else
      entry.show();
  });
})();