Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2021-01-27 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Mouseover Popup Image Viewer
  3. // @namespace https://github.com/tophf
  4. // @description Shows images and videos behind links and thumbnails.
  5. //
  6. // @include *
  7. // @connect *
  8. //
  9. // allow rule installer in config dialog
  10. // @connect github.com
  11. //
  12. // @grant GM_getValue
  13. // @grant GM_setValue
  14. // @grant GM_xmlhttpRequest
  15. // @grant GM_download
  16. // @grant GM_openInTab
  17. // @grant GM_registerMenuCommand
  18. // @grant GM_setClipboard
  19. //
  20. // @version 1.1.20
  21. // @author tophf
  22. //
  23. // @original-version 2017.9.29
  24. // @original-author kuehlschrank
  25. //
  26. // @supportURL https://github.com/tophf/mpiv/issues
  27. // @icon https://github.com/tophf/mpiv/raw/master/icon.png
  28. // ==/UserScript==
  29.  
  30. 'use strict';
  31.  
  32. //#region Globals
  33.  
  34. /** @type mpiv.Config */
  35. let cfg;
  36. /** @type mpiv.AppInfo */
  37. let ai = {rule: {}};
  38. /** @type Element */
  39. let elConfig;
  40.  
  41. const doc = document;
  42. const hostname = location.hostname;
  43. const dotDomain = '.' + hostname;
  44. const isGoogleDomain = /(^|\.)google(\.com?)?(\.\w+)?$/.test(hostname);
  45. const isGoogleImages = isGoogleDomain && /[&?]tbm=isch(&|$)/.test(location.search);
  46. const isFF = CSS.supports('-moz-appearance', 'none');
  47. const AudioContext = window.AudioContext || function () {};
  48.  
  49. const PREFIX = 'mpiv-';
  50. const STATUS_ATTR = `${PREFIX}status`;
  51. const MSG = Object.assign({}, ...[
  52. 'getViewSize',
  53. 'viewSize',
  54. ].map(k => ({[k]: `${PREFIX}${k}`})));
  55. const WHEEL_EVENT = 'onwheel' in doc ? 'wheel' : 'mousewheel';
  56. // time for volatile things to settle down meanwhile we postpone action
  57. // examples: loading image from cache, quickly moving mouse over one element to another
  58. const SETTLE_TIME = 50;
  59. // used to detect JS code in host rules
  60. const RX_HAS_CODE = /(^|[^-\w])return[\W\s]/;
  61. const RX_MEDIA_URL = /^[^?]+?\.(bmp|jpe?g?|gif|mp4|png|svg|web[mp])($|\?)/i;
  62. const ZOOM_MAX = 16;
  63. const SYM_U = Symbol('u');
  64.  
  65. //#endregion
  66.  
  67. const App = {
  68.  
  69. isEnabled: true,
  70. isImageTab: false,
  71. globalStyle: '',
  72. popupStyleBase: '',
  73.  
  74. activate(info, event) {
  75. const {match, node, rule, url} = info;
  76. if (elConfig) console.info({node, rule, url, match});
  77. if (ai.node) App.deactivate();
  78. ai = info;
  79. ai.force = event.ctrlKey;
  80. ai.gNum = 0;
  81. ai.zooming = cfg.css.includes(`${PREFIX}zooming`);
  82. Util.suppressTooltip();
  83. Calc.updateViewSize();
  84. Events.toggle(true);
  85. Events.trackMouse(event);
  86. if (CspSniffer.init && location.protocol === 'https:')
  87. CspSniffer.init();
  88. if (ai.force) {
  89. App.start();
  90. } else if (cfg.start === 'auto' && !rule.manual) {
  91. App.belate();
  92. } else {
  93. Status.set('ready');
  94. }
  95. },
  96.  
  97. belate() {
  98. if (cfg.preload) {
  99. ai.preloadStart = now();
  100. App.start();
  101. Status.set('+preloading');
  102. setTimeout(Status.set, cfg.delay, '-preloading');
  103. } else {
  104. ai.timer = setTimeout(App.start, cfg.delay);
  105. }
  106. },
  107.  
  108. checkImageTab() {
  109. const el = doc.body.firstElementChild;
  110. App.isImageTab = el && el === doc.body.lastElementChild && el.matches('img, video');
  111. App.isEnabled = cfg.imgtab || !App.isImageTab;
  112. },
  113.  
  114. checkProgress({start} = {}) {
  115. const p = ai.popup;
  116. if (!p)
  117. return;
  118. const w = ai.nwidth = p.naturalWidth || p.videoWidth || ai.popupLoaded && innerWidth / 2;
  119. const h = ai.nheight = p.naturalHeight || p.videoHeight || ai.popupLoaded && innerHeight / 2;
  120. if (h)
  121. return App.canCommit(w, h);
  122. if (start) {
  123. clearInterval(ai.timerProgress);
  124. ai.timerProgress = setInterval(App.checkProgress, 150);
  125. }
  126. },
  127.  
  128. canCommit(w, h) {
  129. if (!ai.force && ai.rect && !ai.gItems &&
  130. Math.max(w / (ai.rect.width || 1), h / (ai.rect.height || 1)) < cfg.scale) {
  131. App.deactivate();
  132. return false;
  133. }
  134. App.stopTimers();
  135. const wait = ai.preloadStart && (ai.preloadStart + cfg.delay - now());
  136. if (wait > 0) {
  137. ai.timer = setTimeout(App.checkProgress, wait);
  138. } else if ((ai.urls || 0).length && Math.max(w, h) < 130) {
  139. App.handleError({type: 'error'});
  140. } else {
  141. App.commit();
  142. }
  143. return true;
  144. },
  145.  
  146. async commit() {
  147. const p = ai.popup;
  148. const isDecoded = cfg.waitLoad && typeof p.decode === 'function';
  149. if (isDecoded) {
  150. await p.decode();
  151. if (p !== ai.popup)
  152. return;
  153. }
  154. App.updateStyles();
  155. Calc.measurePopup();
  156. const willZoom = cfg.zoom === 'auto' || App.isImageTab && cfg.imgtab;
  157. const willMove = !willZoom || App.toggleZoom({keepScale: true}) === undefined;
  158. if (willMove)
  159. Popup.move();
  160. Bar.updateName();
  161. Bar.updateDetails();
  162. Status.set(!ai.popupLoaded && 'loading');
  163. ai.large = ai.nwidth > p.clientWidth + ai.extras.w ||
  164. ai.nheight > p.clientHeight + ai.extras.h;
  165. if (ai.large) {
  166. Status.set('+large');
  167. // prevent a blank bg+border in FF
  168. if (isFF && p.complete && !isDecoded)
  169. p.style.backgroundImage = `url('${p.src}')`;
  170. }
  171. },
  172.  
  173. deactivate({wait} = {}) {
  174. App.stopTimers();
  175. if (ai.req)
  176. tryCatch.call(ai.req, ai.req.abort);
  177. if (ai.tooltip)
  178. ai.tooltip.node.title = ai.tooltip.text;
  179. Status.set(false);
  180. Bar.set(false);
  181. Events.toggle(false);
  182. Popup.destroy();
  183. if (wait) {
  184. App.isEnabled = false;
  185. setTimeout(App.enable, 200);
  186. }
  187. ai = {rule: {}};
  188. },
  189.  
  190. enable() {
  191. App.isEnabled = true;
  192. },
  193.  
  194. handleError(e, rule = ai.rule) {
  195. if (rule && rule.onerror === 'skip')
  196. return;
  197. const fe = Util.formatError(e, rule);
  198. if (!rule || !ai.urls || !ai.urls.length)
  199. console.warn(fe.consoleFormat, ...fe.consoleArgs);
  200. if (ai.urls && ai.urls.length) {
  201. ai.url = ai.urls.shift();
  202. if (ai.url) {
  203. App.stopTimers();
  204. App.startSingle();
  205. } else {
  206. App.deactivate();
  207. }
  208. } else if (ai.node) {
  209. Status.set('error');
  210. Bar.set(fe.message, 'error');
  211. }
  212. },
  213.  
  214. /** @param {MessageEvent} e */
  215. onMessage(e) {
  216. if (typeof e.data === 'string' && e.data === MSG.getViewSize) {
  217. for (const el of doc.getElementsByTagName('iframe')) {
  218. if (el.contentWindow === e.source) {
  219. const [w, h] = Calc.frameSize(el, window);
  220. e.source.postMessage(`${MSG.viewSize}:${w}:${h}`, '*');
  221. return;
  222. }
  223. }
  224. }
  225. },
  226.  
  227. /** @param {MessageEvent} e */
  228. onMessageChild(e) {
  229. if (e.source === parent && typeof e.data === 'string' && e.data.startsWith(MSG.viewSize)) {
  230. window.removeEventListener('message', App.onMessageChild);
  231. const [w, h] = e.data.split(':').slice(1).map(parseFloat);
  232. if (w && h) ai.view = {w, h};
  233. }
  234. },
  235.  
  236. start() {
  237. // check explicitly as the cursor may have moved into an iframe so mouseout wasn't reported
  238. if (!Util.isHovered(ai.node)) {
  239. App.deactivate();
  240. return;
  241. }
  242. App.updateStyles();
  243. if (ai.gallery)
  244. App.startGallery();
  245. else
  246. App.startSingle();
  247. },
  248.  
  249. startSingle() {
  250. Status.loading();
  251. ai.imageUrl = null;
  252. if (ai.rule.follow && !ai.rule.q && !ai.rule.s) {
  253. Remoting.findRedirect();
  254. } else if (ai.rule.q && !Array.isArray(ai.urls)) {
  255. App.startFromQ();
  256. } else {
  257. Popup.create(ai.url);
  258. Ruler.runC();
  259. }
  260. },
  261.  
  262. async startFromQ() {
  263. try {
  264. const {responseText, doc, finalUrl} = await Remoting.getDoc(ai.url);
  265. const url = Ruler.runQ(responseText, doc, finalUrl);
  266. if (!url)
  267. throw 'The "q" rule did not produce any URL.';
  268. if (RuleMatcher.isFollowableUrl(url, ai.rule)) {
  269. const info = RuleMatcher.find(url, ai.node, {noHtml: true});
  270. if (!info || !info.url)
  271. throw `Couldn't follow URL: ${url}`;
  272. Object.assign(ai, info);
  273. App.startSingle();
  274. } else {
  275. Popup.create(url, finalUrl);
  276. Ruler.runC(responseText, doc);
  277. }
  278. } catch (e) {
  279. App.handleError(e);
  280. }
  281. },
  282.  
  283. async startGallery() {
  284. Status.loading();
  285. try {
  286. const startUrl = ai.url;
  287. const p = ai.rule.s === 'gallery' ? {} : await Remoting.getDoc(startUrl);
  288. const items = await new Promise(resolve => {
  289. const it = ai.gallery(p.responseText, p.doc, p.finalUrl, ai.match, ai.rule, ai.node,
  290. resolve);
  291. if (Array.isArray(it))
  292. resolve(it);
  293. });
  294. // bail out if the gallery's async callback took too long
  295. if (ai.url !== startUrl) return;
  296. ai.gNum = items.length;
  297. ai.gItems = items.length && items;
  298. if (ai.gItems) {
  299. const i = items.index;
  300. ai.gIndex = i === (i | 0) && items[i] ? i | 0 :
  301. typeof i === 'string' ? clamp(items.findIndex(x => x.url === i), 0) :
  302. Gallery.findIndex(ai.url);
  303. setTimeout(Gallery.next);
  304. } else {
  305. throw 'Empty gallery';
  306. }
  307. } catch (e) {
  308. App.handleError(e);
  309. }
  310. },
  311.  
  312. stopTimers() {
  313. for (const timer of ['timer', 'timerBar', 'timerStatus'])
  314. clearTimeout(ai[timer]);
  315. clearInterval(ai.timerProgress);
  316. },
  317.  
  318. toggleZoom({keepScale} = {}) {
  319. const p = ai.popup;
  320. if (!p || !ai.scales || ai.scales.length < 2)
  321. return;
  322. ai.zoomed = !ai.zoomed;
  323. ai.scale = ai.zoomed && Calc.scaleForFirstZoom(keepScale) || ai.scales[0];
  324. if (ai.zooming)
  325. p.classList.add(`${PREFIX}zooming`);
  326. Popup.move();
  327. Bar.updateDetails();
  328. Status.set(ai.zoomed ? 'zoom' : false);
  329. return ai.zoomed;
  330. },
  331.  
  332. updateStyles() {
  333. Util.addStyle('global', (App.globalStyle || createGlobalStyle()) + cfg._getCss());
  334. Util.addStyle('rule', ai.rule.css || '');
  335. },
  336. };
  337.  
  338. const Bar = {
  339.  
  340. set(label, className) {
  341. let b = ai.bar;
  342. if (typeof label !== 'string') {
  343. $remove(b);
  344. ai.bar = null;
  345. return;
  346. }
  347. if (!b) b = ai.bar = $create('div', {id: `${PREFIX}bar`});
  348. App.updateStyles();
  349. Bar.updateDetails();
  350. Bar.show();
  351. b.innerHTML = label;
  352. if (!b.parentNode) {
  353. doc.body.appendChild(b);
  354. Util.forceLayout(b);
  355. }
  356. b.className = `${PREFIX}show ${PREFIX}${className}`;
  357. },
  358.  
  359. show() {
  360. clearTimeout(ai.timerBar);
  361. ai.bar.style.removeProperty('opacity');
  362. ai.timerBar = setTimeout(() => ai.bar && $css(ai.bar, {opacity: 0}), 3000);
  363. },
  364.  
  365. updateName() {
  366. const {gItems: gi, gIndex: i, gNum: n} = ai;
  367. if (gi) {
  368. const item = gi[i];
  369. const noDesc = !gi.some(_ => _.desc);
  370. const c = `${n > 1 ? `[${i + 1}/${n}] ` : ''}${[
  371. gi.title && (!i || noDesc) && !`${item.desc || ''}`.includes(gi.title) && gi.title || '',
  372. item.desc,
  373. ].filter(Boolean).join(' - ')}`;
  374. Bar.set(c.trim() || ' ', 'gallery', true);
  375. } else if ('caption' in ai) {
  376. Bar.set(ai.caption, 'caption');
  377. } else if (ai.tooltip) {
  378. Bar.set(ai.tooltip.text, 'tooltip');
  379. } else {
  380. Bar.set(' ', 'info');
  381. }
  382. },
  383.  
  384. updateDetails() {
  385. if (!ai.bar) return;
  386. const r = ai.rotate;
  387. const zoom = ai.nwidth && `${
  388. Math.round(ai.scale * 100)
  389. }%${
  390. ai.flipX || ai.flipY ? `, ${ai.flipX ? '⇆' : ''}${ai.flipY ? '⇅' : ''}` : ''
  391. }${
  392. r ? ', ' + (r > 180 ? r - 360 : r) + '°' : ''
  393. }, ${
  394. ai.nwidth
  395. } x ${
  396. ai.nheight
  397. } px, ${
  398. Math.round(100 * (ai.nwidth * ai.nheight / 1e6)) / 100
  399. } MP`.replace(/\x20/g, '\xA0');
  400. if (ai.bar.dataset.zoom !== zoom || !ai.nwidth) {
  401. if (zoom) ai.bar.dataset.zoom = zoom;
  402. else delete ai.bar.dataset.zoom;
  403. Bar.show();
  404. }
  405. },
  406. };
  407.  
  408. const Calc = {
  409.  
  410. frameSize(elFrame, parentWindow) {
  411. if (!elFrame) return;
  412. const r = elFrame.getBoundingClientRect();
  413. const w = clamp(r.width, 0, parentWindow.innerWidth - r.left);
  414. const h = clamp(r.height, 0, parentWindow.innerHeight - r.top);
  415. return [w, h];
  416. },
  417.  
  418. generateScales(fit) {
  419. let [scale, goal] = fit < 1 ? [fit, 1] : [1, fit];
  420. const zoomStep = cfg.zoomStep / 100;
  421. const arr = [scale];
  422. if (fit !== 1) {
  423. const diff = goal / scale;
  424. const steps = Math.log(diff) / Math.log(zoomStep) | 0;
  425. const step = steps && Math.pow(diff, 1 / steps);
  426. for (let i = steps; --i > 0;)
  427. arr.push((scale *= step));
  428. arr.push(scale = goal);
  429. }
  430. while ((scale *= zoomStep) <= ZOOM_MAX)
  431. arr.push(scale);
  432. return arr;
  433. },
  434.  
  435. measurePopup() {
  436. let {popup: p, nwidth: nw, nheight: nh} = ai;
  437. // overriding custom CSS to detect an unrestricted SVG that scales to the entire page
  438. p.setAttribute('style', 'display:inline !important;' + App.popupStyleBase);
  439. if (p.clientWidth > nw) {
  440. const w = clamp(p.clientWidth, nw, innerWidth / 2) | 0;
  441. nh = ai.nheight = w / nw * nh | 0;
  442. nw = ai.nwidth = w;
  443. p.style.cssText = `width: ${nw}px !important; height: ${nh}px !important;`;
  444. }
  445. p.className = `${PREFIX}show`;
  446. p.removeAttribute('style');
  447. const s = getComputedStyle(p);
  448. const o2 = sumProps(s.outlineOffset, s.outlineWidth) * 2;
  449. const inw = sumProps(s.paddingLeft, s.paddingRight, s.borderLeftWidth, s.borderRightWidth);
  450. const inh = sumProps(s.paddingTop, s.paddingBottom, s.borderTopWidth, s.borderBottomWidth);
  451. const outw = o2 + sumProps(s.marginLeft, s.marginRight);
  452. const outh = o2 + sumProps(s.marginTop, s.marginBottom);
  453. ai.extras = {
  454. inw, inh,
  455. outw, outh,
  456. o: o2 / 2,
  457. w: inw + outw,
  458. h: inh + outh,
  459. };
  460. const fit = Math.min(
  461. (ai.view.w - ai.extras.w) / ai.nwidth,
  462. (ai.view.h - ai.extras.h) / ai.nheight) || 1;
  463. const isCustom = !cfg.fit && cfg.scales.length;
  464. let cutoff = Math.min(1, fit);
  465. let scaleZoom = cfg.fit === 'all' && fit || cfg.fit === 'no' && 1 || cutoff;
  466. if (isCustom) {
  467. const dst = [];
  468. for (const scale of cfg.scales) {
  469. const val = parseFloat(scale) || fit;
  470. dst.push(val);
  471. if (isCustom && typeof scale === 'string') {
  472. if (scale.includes('!')) cutoff = val;
  473. if (scale.includes('*')) scaleZoom = val;
  474. }
  475. }
  476. ai.scales = dst.sort(compareNumbers).filter(Calc.scaleBiggerThan, cutoff);
  477. } else {
  478. ai.scales = Calc.generateScales(fit);
  479. }
  480. ai.scale = cfg.zoom === 'auto' ? scaleZoom : Math.min(1, fit);
  481. ai.scaleFit = fit;
  482. ai.scaleZoom = scaleZoom;
  483. },
  484.  
  485. rect() {
  486. let {node, rule} = ai;
  487. let n = rule.rect && node.closest(rule.rect);
  488. if (n) return n.getBoundingClientRect();
  489. const nested = node.getElementsByTagName('*');
  490. let maxArea = 0;
  491. let maxBounds;
  492. n = node;
  493. for (let i = 0; n; n = nested[i++]) {
  494. const bounds = n.getBoundingClientRect();
  495. const area = bounds.width * bounds.height;
  496. if (area > maxArea) {
  497. maxArea = area;
  498. maxBounds = bounds;
  499. node = n;
  500. }
  501. }
  502. return maxBounds;
  503. },
  504.  
  505. scaleBiggerThan(scale, i, arr) {
  506. return scale >= this && (!i || Math.abs(scale - arr[i - 1]) > .01);
  507. },
  508.  
  509. scaleIndex(dir) {
  510. const i = ai.scales.indexOf(ai.scale);
  511. if (i >= 0) return i + dir;
  512. for (
  513. let len = ai.scales.length,
  514. i = dir > 0 ? 0 : len - 1;
  515. i >= 0 && i < len;
  516. i += dir
  517. ) {
  518. if (Math.sign(ai.scales[i] - ai.scale) === dir)
  519. return i;
  520. }
  521. return -1;
  522. },
  523.  
  524. scaleForFirstZoom(keepScale) {
  525. const z = ai.scaleZoom;
  526. return keepScale || z !== ai.scale ? z : ai.scales.find(x => x > z);
  527. },
  528.  
  529. updateViewSize() {
  530. const view = doc.compatMode === 'BackCompat' ? doc.body : doc.documentElement;
  531. ai.view = {
  532. w: view.clientWidth,
  533. h: view.clientHeight,
  534. };
  535. if (window === top) return;
  536. const [w, h] = Calc.frameSize(frameElement, parent) || [];
  537. if (w && h) {
  538. ai.view = {w, h};
  539. } else {
  540. window.addEventListener('message', App.onMessageChild);
  541. parent.postMessage(MSG.getViewSize, '*');
  542. }
  543. },
  544. };
  545.  
  546. /** @namespace mpiv.Config */
  547. class Config {
  548.  
  549. constructor({data: c = GM_getValue('cfg'), save}) {
  550. if (typeof c === 'string')
  551. c = tryCatch(JSON.parse, c);
  552. if (typeof c !== 'object' || !c)
  553. c = {};
  554. const {/** @type mpiv.Config */ DEFAULTS} = Config;
  555. c.fit = ['all', 'large', 'no', ''].includes(c.fit) ? c.fit :
  556. !(c.scales || 0).length || `${c.scales}` === `${DEFAULTS.scales}` ? 'large' :
  557. '';
  558. if (c.version !== DEFAULTS.version) {
  559. if (typeof c.hosts === 'string')
  560. c.hosts = c.hosts.split('\n')
  561. .map(s => tryCatch(JSON.parse, s) || s)
  562. .filter(Boolean);
  563. if (c.close === true || c.close === false)
  564. c.zoomOut = c.close ? 'auto' : 'stay';
  565. for (const key in DEFAULTS)
  566. if (typeof c[key] !== typeof DEFAULTS[key])
  567. c[key] = DEFAULTS[key];
  568. if (c.version === 3 && c.scales[0] === 0)
  569. c.scales[0] = '0!';
  570. for (const key in c)
  571. if (!(key in DEFAULTS))
  572. delete c[key];
  573. c.version = DEFAULTS.version;
  574. if (save)
  575. GM_setValue('cfg', c);
  576. }
  577. if (Object.keys(cfg || {}).some(k => /^ui|^(css|globalStatus)$/.test(k) && cfg[k] !== c[k]))
  578. App.globalStyle = '';
  579. if (!Array.isArray(c.scales))
  580. c.scales = [];
  581. c.scales = [...new Set(c.scales)].sort((a, b) => parseFloat(a) - parseFloat(b));
  582. Object.assign(this, DEFAULTS, c);
  583. }
  584.  
  585. _getCss() {
  586. const {css} = this;
  587. return css.includes('{') ? css : `#${PREFIX}-popup {${css}}`;
  588. }
  589. }
  590.  
  591. Config.DEFAULTS = /** @type mpiv.Config */ Object.assign(Object.create(null), {
  592. center: false,
  593. css: '',
  594. delay: 500,
  595. fit: '',
  596. globalStatus: false,
  597. // prefer ' inside rules because " will be displayed as \"
  598. // example: "img[src*='icon']"
  599. hosts: [{
  600. name: 'No popup for YouTube thumbnails',
  601. d: 'www.youtube.com',
  602. e: 'ytd-rich-item-renderer *, ytd-thumbnail *',
  603. s: '',
  604. }, {
  605. name: 'No popup for SVG/PNG icons',
  606. d: '',
  607. e: "img[src*='icon']",
  608. r: '//[^/]+/.*\\bicons?\\b.*\\.(?:png|svg)',
  609. s: '',
  610. }],
  611. imgtab: false,
  612. mute: false,
  613. preload: false,
  614. scale: 1.25,
  615. scales: ['0!', 0.125, 0.25, 0.5, 0.75, 1, 1.5, 2, 2.5, 3, 4, 5, 8, 16],
  616. start: 'auto',
  617. uiBackgroundColor: '#ffffff',
  618. uiBackgroundOpacity: 100,
  619. uiBorderColor: '#000000',
  620. uiBorderOpacity: 100,
  621. uiBorder: 0,
  622. uiFadein: true,
  623. uiShadowColor: '#000000',
  624. uiShadowOpacity: 80,
  625. uiShadow: 20,
  626. uiPadding: 0,
  627. uiMargin: 0,
  628. version: 6,
  629. waitLoad: false,
  630. xhr: true,
  631. zoom: 'context',
  632. zoomOut: 'auto',
  633. zoomStep: 133,
  634. });
  635.  
  636. const CspSniffer = {
  637.  
  638. /** @type {?Object<string,string[]>} */
  639. csp: null,
  640. /** @type {?Promise<void>} */
  641. initPending: null,
  642. selfUrl: location.origin + '/',
  643.  
  644. // will be null when done
  645. init() {
  646. this.initPending = this.initPending || new Promise(resolve => {
  647. GM_xmlhttpRequest({
  648. url: location.href,
  649. method: 'HEAD',
  650. onload: response => {
  651. this.csp = this._parse(response);
  652. this.init = this.initPending = null;
  653. resolve();
  654. },
  655. });
  656. });
  657. },
  658.  
  659. async check(url) {
  660. await this.initPending;
  661. const isVideo = Util.isVideoUrl(url);
  662. let mode;
  663. if (this.csp) {
  664. const src = this.csp[isVideo ? 'media' : 'img'];
  665. if (!src.some(this._srcMatches, url))
  666. mode = [mode, 'blob', 'data'].find(m => src.includes(`${m}:`));
  667. }
  668. return [mode || ai.xhr, isVideo];
  669. },
  670.  
  671. _parse({responseHeaders}) {
  672. const csp = responseHeaders.match(/(?:^|[\r\n])\s*Content-Security-Policy:([^\r\n]*)/i);
  673. if (!csp) return;
  674. const src = {};
  675. const rx = /[\s;](default|img|media)-src ([^;]+)/g;
  676. for (let m; (m = rx.exec(csp[1]));)
  677. src[m[1]] = m[2].trim().split(/\s+/);
  678. if (!src.img) src.img = src.default || [];
  679. if (!src.media) src.media = src.default || [];
  680. for (const set of [src.img, src.media]) {
  681. set.forEach((item, i) => {
  682. if (item !== '*' && item.includes('*')) {
  683. set[i] = new RegExp(
  684. (/^\w+:/.test(item) ? '^' : '^\\w+://') +
  685. item
  686. .replace(/[.+?^$|()[\]{}]/g, '\\$&')
  687. .replace(/(\\\.)?(\*)(\\\.)?/g, (_, a, b, c) =>
  688. `${a ? '\\.?' : ''}[^:/]*${c ? '\\.?' : ''}`)
  689. .replace(/[^/]$/, '$&/'));
  690. }
  691. });
  692. }
  693. return src;
  694. },
  695.  
  696. /** @this string */
  697. _srcMatches(src) {
  698. return src instanceof RegExp ? src.test(this) :
  699. src === '*' ||
  700. src && this.startsWith(src) && (src.endsWith('/') || this[src.length] === '/') ||
  701. src === "'self'" && this.startsWith(CspSniffer.selfUrl);
  702. },
  703. };
  704.  
  705. const Events = {
  706.  
  707. hoverData: [],
  708. hoverTimer: 0,
  709.  
  710. onMouseOver(e) {
  711. let node = e.target;
  712. if (!App.isEnabled ||
  713. e.shiftKey ||
  714. ai.zoomed ||
  715. node === ai.popup ||
  716. node === doc.body ||
  717. node === doc.documentElement ||
  718. node === elConfig ||
  719. ai.gallery && ai.rectHovered)
  720. return;
  721. if (node.shadowRoot)
  722. node = Events.pierceShadow(node, e.clientX, e.clientY);
  723. // we don't want to process everything in the path of a quickly moving mouse cursor
  724. Events.hoverData = [now(), e, node];
  725. Events.hoverTimer = Events.hoverTimer || setTimeout(Events.onMouseOverThrottled, SETTLE_TIME);
  726. },
  727.  
  728. onMouseOverThrottled() {
  729. const [start, e, node] = Events.hoverData;
  730. // clearTimeout + setTimeout is expensive so we'll use the cheaper perf.now() for rescheduling
  731. const wait = start + SETTLE_TIME - now();
  732. Events.hoverTimer = wait > 10 && setTimeout(Events.onMouseOverThrottled, wait);
  733. if (Events.hoverTimer || !Util.isHovered(node))
  734. return;
  735. if (!Ruler.rules)
  736. Ruler.init();
  737. let a;
  738. const tag = node.tagName;
  739. const src = node.currentSrc || node.src;
  740. const isPic = tag === 'IMG' || tag === 'VIDEO' && /\.(webm|mp4)(\?|$)/.test(src);
  741. const info =
  742. // note that data URLs aren't passed to rules as those may have fatally ineffective regexps
  743. tag !== 'A' &&
  744. RuleMatcher.find(isPic && !src.startsWith('data:') && Util.rel2abs(src), node) ||
  745. (a = node.closest('A')) &&
  746. RuleMatcher.findForLink(a) ||
  747. isPic &&
  748. {node, rule: {}, url: src};
  749. if (info && info.url && info.node !== ai.node)
  750. App.activate(info, e);
  751. },
  752.  
  753. onMouseOut(e) {
  754. if (!e.relatedTarget && !e.shiftKey)
  755. App.deactivate();
  756. },
  757.  
  758. onMouseOutShadow(e) {
  759. const root = e.target.shadowRoot;
  760. if (root) {
  761. root.removeEventListener('mouseover', Events.onMouseOver);
  762. root.removeEventListener('mouseout', Events.onMouseOutShadow);
  763. }
  764. },
  765.  
  766. onMouseMove(e) {
  767. Events.trackMouse(e);
  768. if (e.shiftKey) {
  769. ai.lazyUnload = true;
  770. } else if (!ai.zoomed && !ai.rectHovered) {
  771. App.deactivate();
  772. } else if (ai.zoomed) {
  773. Popup.move();
  774. const {cx, cy, view: {w, h}} = ai;
  775. const bx = w / 6;
  776. const by = h / 6;
  777. const onEdge = cx < bx || cx > w - bx || cy < by || cy > h - by;
  778. Status.set(`${onEdge ? '+' : '-'}edge`);
  779. }
  780. },
  781.  
  782. onMouseDown({shiftKey, button}) {
  783. if (button === 0 && shiftKey && ai.popup && ai.popup.controls) {
  784. ai.controlled = ai.zoomed = true;
  785. } else if (button === 2 || shiftKey) {
  786. // we ignore RMB and Shift
  787. } else {
  788. App.deactivate({wait: true});
  789. doc.addEventListener('mouseup', App.enable, {once: true});
  790. }
  791. },
  792.  
  793. onMouseScroll(e) {
  794. const dir = (e.deltaY || -e.wheelDelta) < 0 ? 1 : -1;
  795. if (ai.zoomed) {
  796. Events.zoomInOut(dir);
  797. } else if (ai.gNum > 1 && ai.popup) {
  798. Gallery.next(-dir);
  799. } else if (cfg.zoom === 'wheel' && dir > 0 && ai.popup) {
  800. App.toggleZoom();
  801. } else {
  802. App.deactivate();
  803. return;
  804. }
  805. dropEvent(e);
  806. },
  807.  
  808. onKeyDown(e) {
  809. const key = eventModifiers(e) + (e.key.length > 1 ? e.key : e.code);
  810. const p = ai.popup;
  811. switch (key) {
  812. case '+Shift':
  813. Status.set('+shift');
  814. if (p && p.tagName === 'VIDEO')
  815. p.controls = true;
  816. return;
  817. case '^Control':
  818. if (!p && (cfg.start !== 'auto' || ai.rule.manual))
  819. App.start();
  820. return;
  821. case 'ArrowRight':
  822. case 'KeyJ':
  823. Gallery.next(1);
  824. break;
  825. case 'ArrowLeft':
  826. case 'KeyK':
  827. Gallery.next(-1);
  828. break;
  829. case 'KeyD':
  830. Remoting.saveFile();
  831. break;
  832. case 'KeyH': // flip horizontally
  833. case 'KeyV': // flip vertically
  834. case 'KeyL': // rotate left
  835. case 'KeyR': // rotate right
  836. if (!p)
  837. return;
  838. if (key === 'KeyH' || key === 'KeyV') {
  839. const side = !!(ai.rotate % 180) ^ (key === 'KeyH') ? 'flipX' : 'flipY';
  840. ai[side] = !ai[side];
  841. } else {
  842. ai.rotate = ((ai.rotate || 0) + 90 * (key === 'KeyL' ? -1 : 1) + 360) % 360;
  843. }
  844. Bar.updateDetails();
  845. Popup.move();
  846. break;
  847. case 'KeyM':
  848. if (p && p.tagName === 'VIDEO')
  849. p.muted = !p.muted;
  850. break;
  851. case 'KeyT':
  852. ai.lazyUnload = true;
  853. GM_openInTab(Util.tabFixUrl() || p.src);
  854. App.deactivate();
  855. break;
  856. case 'Minus':
  857. case 'NumpadSubtract':
  858. if (ai.zoomed) {
  859. Events.zoomInOut(-1);
  860. } else {
  861. App.toggleZoom();
  862. }
  863. break;
  864. case 'Equal':
  865. case 'NumpadAdd':
  866. if (ai.zoomed) {
  867. Events.zoomInOut(1);
  868. } else {
  869. App.toggleZoom();
  870. }
  871. break;
  872. case 'Escape':
  873. App.deactivate({wait: true});
  874. break;
  875. case '!Alt':
  876. return;
  877. default:
  878. App.deactivate({wait: true});
  879. return;
  880. }
  881. dropEvent(e);
  882. },
  883.  
  884. onKeyUp(e) {
  885. if (e.key === 'Shift') {
  886. Status.set('-shift');
  887. if ((ai.popup || {}).controls)
  888. ai.popup.controls = false;
  889. if (ai.controlled)
  890. ai.controlled = false;
  891. else if (ai.popup && (ai.zoomed || ai.rectHovered !== false))
  892. App.toggleZoom();
  893. else
  894. App.deactivate({wait: true});
  895. }
  896. },
  897.  
  898. onContext(e) {
  899. if (e.shiftKey) return;
  900. if (cfg.zoom === 'context' && ai.popup && App.toggleZoom()) {
  901. dropEvent(e);
  902. } else if (!ai.popup && (cfg.start === 'context' || (cfg.start === 'auto' && ai.rule.manual))) {
  903. App.start();
  904. dropEvent(e);
  905. } else {
  906. setTimeout(App.deactivate, SETTLE_TIME, {wait: true});
  907. }
  908. },
  909.  
  910. pierceShadow(node, x, y) {
  911. for (let root; (root = node.shadowRoot);) {
  912. root.addEventListener('mouseover', Events.onMouseOver, {passive: true});
  913. root.addEventListener('mouseout', Events.onMouseOutShadow);
  914. const inner = root.elementFromPoint(x, y);
  915. if (!inner || inner === node)
  916. break;
  917. node = inner;
  918. }
  919. return node;
  920. },
  921.  
  922. toggle(enable) {
  923. const onOff = enable ? doc.addEventListener : doc.removeEventListener;
  924. const passive = enable ? {passive: true} : undefined;
  925. onOff.call(doc, 'mousemove', Events.onMouseMove, passive);
  926. onOff.call(doc, 'mouseout', Events.onMouseOut, passive);
  927. onOff.call(doc, 'mousedown', Events.onMouseDown, passive);
  928. onOff.call(doc, 'contextmenu', Events.onContext);
  929. onOff.call(doc, 'keydown', Events.onKeyDown, true); // override normal page listeners
  930. onOff.call(doc, 'keyup', Events.onKeyUp);
  931. onOff.call(doc, WHEEL_EVENT, Events.onMouseScroll, enable ? {passive: false} : undefined);
  932. },
  933.  
  934. trackMouse(e) {
  935. const cx = ai.cx = e.clientX;
  936. const cy = ai.cy = e.clientY;
  937. const r = ai.rect || (ai.rect = Calc.rect());
  938. ai.rectHovered =
  939. cx > r.left - 2 && cx < r.right + 2 &&
  940. cy > r.top - 2 && cy < r.bottom + 2;
  941. },
  942.  
  943. zoomInOut(dir) {
  944. const i = Calc.scaleIndex(dir);
  945. const n = ai.scales.length;
  946. if (i >= 0 && i < n)
  947. ai.scale = ai.scales[i];
  948. const zo = cfg.zoomOut;
  949. if (i <= 0 && zo !== 'stay') {
  950. if (ai.scaleFit < ai.scale * .99) {
  951. ai.scales.unshift(ai.scale = ai.scaleFit);
  952. } else if ((i <= 0 && zo === 'close' || i < 0 && !ai.rectHovered) && ai.gNum < 2) {
  953. App.deactivate({wait: true});
  954. return;
  955. }
  956. ai.zoomed = zo !== 'unzoom';
  957. } else {
  958. ai.popup.classList.toggle(`${PREFIX}zoom-max`, ai.scale >= 4 && i >= n - 1);
  959. }
  960. if (ai.zooming)
  961. ai.popup.classList.add(`${PREFIX}zooming`);
  962. Popup.move();
  963. Bar.updateDetails();
  964. },
  965. };
  966.  
  967. const Gallery = {
  968.  
  969. functionParams: ['text', 'doc', 'url', 'm', 'rule', 'node', 'cb'],
  970.  
  971. makeParser(g) {
  972. return (
  973. typeof g === 'function' ? g :
  974. typeof g === 'string' ? Util.newFunction(...Gallery.functionParams, g) :
  975. Gallery.defaultParser
  976. );
  977. },
  978.  
  979. findIndex(gUrl) {
  980. const sel = gUrl.split('#')[1];
  981. if (!sel)
  982. return 0;
  983. if (/^\d+$/.test(sel))
  984. return parseInt(sel);
  985. for (let i = ai.gNum; i--;) {
  986. let {url} = ai.gItems[i];
  987. if (Array.isArray(url))
  988. url = url[0];
  989. if (url.indexOf(sel, url.lastIndexOf('/')) > 0)
  990. return i;
  991. }
  992. return 0;
  993. },
  994.  
  995. next(dir) {
  996. if (dir) ai.gIndex = Gallery.nextIndex(dir);
  997. const item = ai.gItems[ai.gIndex];
  998. if (Array.isArray(item.url)) {
  999. ai.urls = item.url.slice(1);
  1000. ai.url = item.url[0];
  1001. } else {
  1002. ai.urls = null;
  1003. ai.url = item.url;
  1004. }
  1005. ai.preloadUrl = ensureArray(ai.gItems[Gallery.nextIndex(dir || 1)].url)[0];
  1006. App.startSingle();
  1007. Bar.updateName();
  1008. },
  1009.  
  1010. nextIndex(dir) {
  1011. return (ai.gIndex + dir + ai.gNum) % ai.gNum;
  1012. },
  1013.  
  1014. defaultParser(text, doc, docUrl, m, rule) {
  1015. const {g} = rule;
  1016. const qEntry = g.entry;
  1017. const qCaption = ensureArray(g.caption);
  1018. const qImage = g.image;
  1019. const qTitle = g.title;
  1020. const fix =
  1021. (typeof g.fix === 'string' ? Util.newFunction('s', 'isURL', g.fix) : g.fix) ||
  1022. (s => s.trim());
  1023. const items = [...$$(qEntry || qImage, doc)]
  1024. .map(processEntry)
  1025. .filter(Boolean);
  1026. items.title = processTitle();
  1027. items.index =
  1028. typeof g.index === 'string' &&
  1029. Remoting.findImageUrl(tryCatch($, g.index, doc), docUrl) ||
  1030. RX_HAS_CODE.test(g.index) &&
  1031. Util.newFunction('items', 'node', g.index)(items, ai.node) ||
  1032. g.index;
  1033. return items;
  1034.  
  1035. function processEntry(entry) {
  1036. const item = {};
  1037. try {
  1038. const img = qEntry ? $(qImage, entry) : entry;
  1039. item.url = fix(Remoting.findImageUrl(img, docUrl), true);
  1040. item.desc = qCaption.map(processCaption, entry).filter(Boolean).join(' - ');
  1041. } catch (e) {}
  1042. return item.url && item;
  1043. }
  1044.  
  1045. function processCaption(selector) {
  1046. const el = $(selector, this) ||
  1047. $orSelf(selector, this.previousElementSibling) ||
  1048. $orSelf(selector, this.nextElementSibling);
  1049. return el && fix(el.textContent);
  1050. }
  1051.  
  1052. function processTitle() {
  1053. const el = $(qTitle, doc);
  1054. return el && fix(el.getAttribute('content') || el.textContent) || '';
  1055. }
  1056.  
  1057. function $orSelf(selector, el) {
  1058. if (el && !el.matches(qEntry))
  1059. return el.matches(selector) ? el : $(selector, el);
  1060. }
  1061. },
  1062. };
  1063.  
  1064. const Popup = {
  1065.  
  1066. async create(src, pageUrl) {
  1067. Popup.destroy();
  1068. ai.imageUrl = src;
  1069. if (!src)
  1070. return;
  1071. const myAi = ai;
  1072. let [xhr, isVideo] = await CspSniffer.check(src);
  1073. if (ai !== myAi)
  1074. return;
  1075. if (xhr)
  1076. [src, isVideo] = await Remoting.getImage(src, pageUrl, xhr).catch(App.handleError) || [];
  1077. if (ai !== myAi || !src)
  1078. return;
  1079. const p = ai.popup = isVideo ? PopupVideo.create() : $create('img');
  1080. p.id = `${PREFIX}popup`;
  1081. p.src = src;
  1082. p.addEventListener('error', App.handleError);
  1083. if (ai.zooming)
  1084. p.addEventListener('transitionend', Popup.onZoom);
  1085. doc.body.insertBefore(p, ai.bar || undefined);
  1086. await 0;
  1087. if (App.checkProgress({start: true}) === false)
  1088. return;
  1089. if (p.complete)
  1090. Popup.onLoad.call(ai.popup);
  1091. else if (!isVideo)
  1092. p.addEventListener('load', Popup.onLoad, {once: true});
  1093. },
  1094.  
  1095. destroy() {
  1096. const p = ai.popup;
  1097. if (!p) return;
  1098. p.removeEventListener('load', Popup.onLoad);
  1099. p.removeEventListener('error', App.handleError);
  1100. if (typeof p.pause === 'function')
  1101. p.pause();
  1102. if (!ai.lazyUnload) {
  1103. if (p.src.startsWith('blob:'))
  1104. URL.revokeObjectURL(p.src);
  1105. }
  1106. p.remove();
  1107. ai.zoomed = ai.popup = ai.popupLoaded = null;
  1108. },
  1109.  
  1110. move() {
  1111. let x, y;
  1112. const {cx, cy, extras, view} = ai;
  1113. const vw = view.w - extras.outw;
  1114. const vh = view.h - extras.outh;
  1115. const w0 = ai.scale * ai.nwidth + extras.inw;
  1116. const h0 = ai.scale * ai.nheight + extras.inh;
  1117. const isSwapped = ai.rotate % 180;
  1118. const w = isSwapped ? h0 : w0;
  1119. const h = isSwapped ? w0 : h0;
  1120. if (!ai.zoomed && ai.gNum < 2 && !cfg.center) {
  1121. const r = ai.rect;
  1122. const rx = (r.left + r.right) / 2;
  1123. const ry = (r.top + r.bottom) / 2;
  1124. if (vw - r.right - 40 > w || w < r.left - 40) {
  1125. if (h < vh - 60)
  1126. y = clamp(ry - h / 2, 30, vh - h - 30);
  1127. x = rx > vw / 2 ? r.left - 40 - w : r.right + 40;
  1128. } else if (vh - r.bottom - 40 > h || h < r.top - 40) {
  1129. if (w < vw - 60)
  1130. x = clamp(rx - w / 2, 30, vw - w - 30);
  1131. y = ry > vh / 2 ? r.top - 40 - h : r.bottom + 40;
  1132. }
  1133. }
  1134. if (x == null)
  1135. x = (vw - w) * (vw > w ? .5 : clamp(5 / 3 * (cx / vw - .2), 0, 1));
  1136. if (y == null)
  1137. y = (vh - h) * (vh > h ? .5 : clamp(5 / 3 * (cy / vh - .2), 0, 1));
  1138. const diff = isSwapped ? (w0 - h0) / 2 : 0;
  1139. x += extras.o - diff;
  1140. y += extras.o + diff;
  1141. $css(ai.popup, {
  1142. transform: `translate(${Math.round(x)}px, ${Math.round(y)}px) ` +
  1143. `rotate(${ai.rotate || 0}deg) ` +
  1144. `scale(${ai.flipX ? -1 : 1},${ai.flipY ? -1 : 1})`,
  1145. width: `${Math.round(w0)}px`,
  1146. height: `${Math.round(h0)}px`,
  1147. });
  1148. },
  1149.  
  1150. onLoad() {
  1151. if (this === ai.popup) {
  1152. this.setAttribute('loaded', '');
  1153. ai.popupLoaded = true;
  1154. Status.set('-loading');
  1155. if (ai.preloadUrl) {
  1156. $create('img', {src: ai.preloadUrl});
  1157. ai.preloadUrl = null;
  1158. }
  1159. }
  1160. },
  1161.  
  1162. onZoom() {
  1163. this.classList.remove(`${PREFIX}zooming`);
  1164. },
  1165. };
  1166.  
  1167. const PopupVideo = {
  1168. create() {
  1169. ai.bufBar = false;
  1170. ai.bufStart = now();
  1171. const shouldMute = cfg.mute || new AudioContext().state === 'suspended';
  1172. return $create('video', {
  1173. autoplay: true,
  1174. controls: shouldMute,
  1175. muted: shouldMute,
  1176. loop: true,
  1177. volume: clamp(+GM_getValue('volume') || .5, 0, 1),
  1178. onprogress: PopupVideo.progress,
  1179. oncanplaythrough: PopupVideo.progressDone,
  1180. onvolumechange: PopupVideo.rememberVolume,
  1181. });
  1182. },
  1183.  
  1184. progress() {
  1185. const {duration} = this;
  1186. if (duration && this.buffered.length && now() - ai.bufStart > 2000) {
  1187. const pct = Math.round(this.buffered.end(0) / duration * 100);
  1188. if ((ai.bufBar |= pct > 0 && pct < 50))
  1189. Bar.set(`${pct}% of ${Math.round(duration)}s`, 'xhr');
  1190. }
  1191. },
  1192.  
  1193. progressDone() {
  1194. this.onprogress = this.oncanplaythrough = null;
  1195. if (ai.bar && ai.bar.classList.contains(`${PREFIX}xhr`))
  1196. Bar.set(false);
  1197. Popup.onLoad.call(this);
  1198. },
  1199.  
  1200. rememberVolume() {
  1201. GM_setValue('volume', this.volume);
  1202. },
  1203. };
  1204.  
  1205. const Ruler = {
  1206. /*
  1207. 'u' works only with URLs so it's ignored if 'html' is true
  1208. ||some.domain = matches some.domain, anything.some.domain, etc.
  1209. |foo = url or text must start with foo
  1210. ^ = separator like / or ? or : but not a letter/number, not %._-
  1211. when used at the end like "foo^" it additionally matches when the source ends with "foo"
  1212. 'r' is checked only if 'u' matches first
  1213. */
  1214. init() {
  1215. const errors = new Map();
  1216. const customRules = (cfg.hosts || []).map(Ruler.parse, errors);
  1217. for (const rule of errors.keys())
  1218. App.handleError('Invalid custom host rule:', rule);
  1219.  
  1220. // rules that disable previewing
  1221. const disablers = [
  1222. dotDomain.endsWith('.stackoverflow.com') && {
  1223. e: '.post-tag, .post-tag img',
  1224. s: '',
  1225. },
  1226. {
  1227. u: '||disqus.com/',
  1228. s: '',
  1229. },
  1230. ];
  1231.  
  1232. // optimization: a rule is created only when on domain
  1233. const perDomain = [
  1234. hostname.includes('startpage') && {
  1235. r: /\boiu=(.+)/,
  1236. s: '$1',
  1237. follow: true,
  1238. },
  1239. dotDomain.endsWith('.4chan.org') && {
  1240. e: '.is_catalog .thread a[href*="/thread/"], .catalog-thread a[href*="/thread/"]',
  1241. q: '.op .fileText a',
  1242. css: '#post-preview{display:none}',
  1243. },
  1244. hostname.includes('amazon.') && {
  1245. r: /.+?images\/I\/.+?\./,
  1246. s: m => {
  1247. const uh = doc.getElementById('universal-hover');
  1248. return uh ? '' : m[0] + 'jpg';
  1249. },
  1250. css: '#zoomWindow{display:none!important;}',
  1251. },
  1252. dotDomain.endsWith('.bing.com') && {
  1253. e: 'a[m*="murl"]',
  1254. r: /murl&quot;:&quot;(.+?)&quot;/,
  1255. s: '$1',
  1256. html: true,
  1257. },
  1258. ...dotDomain.endsWith('.deviantart.com') && [{
  1259. e: '[data-super-full-img] *, img[src*="/th/"]',
  1260. s: (m, node) =>
  1261. $propUp(node, 'data-super-full-img') ||
  1262. (node = node.dataset.embedId && node.nextElementSibling) &&
  1263. node.dataset.embedId && node.src,
  1264. }, {
  1265. e: '.dev-view-deviation img',
  1266. s: () => [
  1267. $('.dev-page-download').href,
  1268. $('.dev-content-full').src,
  1269. ].filter(Boolean),
  1270. }, {
  1271. e: 'a[data-hook=deviation_link]',
  1272. q: 'link[as=image]',
  1273. }] || [],
  1274. dotDomain.endsWith('.dropbox.com') && {
  1275. r: /(.+?&size_mode)=\d+(.*)/,
  1276. s: '$1=5$2',
  1277. },
  1278. dotDomain.endsWith('.facebook.com') && {
  1279. e: 'a[href*="ref=hovercard"]',
  1280. s: (m, node) =>
  1281. 'https://www.facebook.com/photo.php?fbid=' +
  1282. /\/[0-9]+_([0-9]+)_/.exec($('img', node).src)[1],
  1283. follow: true,
  1284. },
  1285. dotDomain.endsWith('.facebook.com') && {
  1286. r: /(fbcdn|external).*?(app_full_proxy|safe_image).+?(src|url)=(http.+?)[&"']/,
  1287. s: (m, node) =>
  1288. node.parentNode.className.includes('video') && m[4].includes('fbcdn') ? '' :
  1289. decodeURIComponent(m[4]),
  1290. html: true,
  1291. follow: true,
  1292. },
  1293. dotDomain.endsWith('.flickr.com') &&
  1294. tryCatch(() => unsafeWindow.YUI_config.flickr.api.site_key) && {
  1295. r: /flickr\.com\/photos\/[^/]+\/(\d+)/,
  1296. s: m => `https://www.flickr.com/services/rest/?${
  1297. new URLSearchParams({
  1298. photo_id: m[1],
  1299. api_key: unsafeWindow.YUI_config.flickr.api.site_key,
  1300. method: 'flickr.photos.getSizes',
  1301. format: 'json',
  1302. nojsoncallback: 1,
  1303. }).toString()}`,
  1304. q: text => JSON.parse(text).sizes.size.pop().source,
  1305. },
  1306. dotDomain.endsWith('.github.com') && {
  1307. r: new RegExp([
  1308. /(avatars.+?&s=)\d+/,
  1309. /(raw\.github)(\.com\/.+?\/img\/.+)$/,
  1310. /\/(github)(\.com\/.+?\/)blob\/([^/]+\/.+?\.(?:png|jpe?g|bmp|gif|cur|ico))$/,
  1311. ].map(rx => rx.source).join('|')),
  1312. s: m => `https://${
  1313. m[1] ? `${m[1]}460` :
  1314. m[2] ? `${m[2]}usercontent${m[3]}` :
  1315. `raw.${m[4]}usercontent${m[5]}${m[6]}`
  1316. }`,
  1317. },
  1318. isGoogleImages && {
  1319. e: 'a[href*="imgres?imgurl="] img',
  1320. s: (m, node) => new URLSearchParams(node.closest('a').search).get('imgurl'),
  1321. follow: true,
  1322. },
  1323. isGoogleImages && {
  1324. e: '[data-tbnid] a:not([href])',
  1325. s: (m, a) => {
  1326. const a2 = $('a[jsaction*="mousedown"]', a.closest('[data-tbnid]')) || a;
  1327. new MutationObserver((_, mo) => {
  1328. mo.disconnect();
  1329. App.isEnabled = true;
  1330. a.alt = a2.innerText;
  1331. const {left, top} = a.getBoundingClientRect();
  1332. Events.onMouseOver({target: $('img', a), clientX: left, clientY: top});
  1333. }).observe(a, {attributes: true, attributeFilter: ['href']});
  1334. a2.dispatchEvent(new MouseEvent('mousedown', {bubbles: true}));
  1335. a2.dispatchEvent(new MouseEvent('mouseup', {bubbles: true}));
  1336. },
  1337. },
  1338. dotDomain.endsWith('.instagram.com') && {
  1339. e: [
  1340. 'a[href*="/p/"]',
  1341. 'article [role="button"][tabindex="0"], article [role="button"][tabindex="0"] div',
  1342. ],
  1343. s: (m, node, rule) => {
  1344. let data, a, n, img, src;
  1345. if (location.pathname.startsWith('/p/')) {
  1346. img = $('img[srcset], video', node.parentNode);
  1347. if (img && (img.localName === 'video' || parseFloat(img.sizes) > 900))
  1348. src = (img.srcset || img.currentSrc).split(',').pop().split(' ')[0];
  1349. }
  1350. if (!src && (n = node.closest('a[href*="/p/"], article'))) {
  1351. a = n.tagName === 'A' ? n : $('a[href*="/p/"]', n);
  1352. data = a && tryCatch(this._getEdge, a.pathname.split('/')[2]);
  1353. }
  1354. Ruler.toggle(rule, 'q', data && data.is_video && !data.video_url);
  1355. Ruler.toggle(rule, 'g', a && $('[class*="Carousel"]', a));
  1356. rule.follow = !data && !rule.g;
  1357. rule._data = data;
  1358. rule._img = img;
  1359. return (
  1360. !a && !src ? false :
  1361. !data || rule.q || rule.g ? `${src || a.href}${rule.g ? '?__a=1' : ''}` :
  1362. data.video_url || data.display_url);
  1363. },
  1364. c: (html, doc, node, rule) =>
  1365. tryCatch(rule._getCaption, rule._data) || (rule._img || 0).alt || '',
  1366. follow: true,
  1367. _q: 'meta[property="og:video"]',
  1368. _g(text, doc, url, m, rule) {
  1369. const media = JSON.parse(text).graphql.shortcode_media;
  1370. const items = media.edge_sidecar_to_children.edges.map(e => ({
  1371. url: e.node.video_url || e.node.display_url,
  1372. }));
  1373. items.title = tryCatch(rule._getCaption, media) || '';
  1374. return items;
  1375. },
  1376. _getCaption: data => data && data.edge_media_to_caption.edges[0].node.text,
  1377. _getEdge: shortcode => unsafeWindow._sharedData.entry_data.ProfilePage[0].graphql.user
  1378. .edge_owner_to_timeline_media.edges.find(e => e.node.shortcode === shortcode).node,
  1379. },
  1380. ...dotDomain.endsWith('.reddit.com') && [{
  1381. u: '||i.reddituploads.com/',
  1382. }, {
  1383. e: '[data-url*="i.redd.it"] img[src*="thumb"]',
  1384. s: (m, node) => $propUp(node, 'data-url'),
  1385. }, {
  1386. r: /preview(\.redd\.it\/\w+\.(jpe?g|png|gif))/,
  1387. s: 'https://i$1',
  1388. }] || [],
  1389. dotDomain.endsWith('.tumblr.com') && {
  1390. e: 'div.photo_stage_img, div.photo_stage > canvas',
  1391. s: (m, node) => /http[^"]+/.exec(node.style.cssText + node.getAttribute('data-img-src'))[0],
  1392. follow: true,
  1393. },
  1394. dotDomain.endsWith('.tweetdeck.twitter.com') && {
  1395. e: 'a.media-item, a.js-media-image-link',
  1396. s: (m, node) => /http[^)]+/.exec(node.style.backgroundImage)[0],
  1397. follow: true,
  1398. },
  1399. dotDomain.endsWith('.twitter.com') && {
  1400. e: '.grid-tweet > .media-overlay',
  1401. s: (m, node) => node.previousElementSibling.src,
  1402. follow: true,
  1403. },
  1404. ];
  1405.  
  1406. const main = [
  1407. {
  1408. r: /[/?=](https?%3A%2F%2F[^&]+)/i,
  1409. s: '$1',
  1410. follow: true,
  1411. onerror: 'skip',
  1412. },
  1413. {
  1414. u: [
  1415. '||500px.com/photo/',
  1416. '||cl.ly/',
  1417. '||cweb-pix.com/',
  1418. '||ibb.co/',
  1419. '||imgcredit.xyz/image/',
  1420. ],
  1421. r: /\.\w+\/.+/,
  1422. q: 'meta[property="og:image"]',
  1423. },
  1424. {
  1425. u: 'attachment.php',
  1426. r: /attachment\.php.+attachmentid/,
  1427. },
  1428. {
  1429. u: '||abload.de/image',
  1430. q: '#image',
  1431. },
  1432. {
  1433. u: '||deviantart.com/art/',
  1434. s: (m, node) =>
  1435. /\b(film|lit)/.test(node.className) || /in Flash/.test(node.title) ?
  1436. '' :
  1437. m.input,
  1438. q: [
  1439. '#download-button[href*=".jpg"]',
  1440. '#download-button[href*=".jpeg"]',
  1441. '#download-button[href*=".gif"]',
  1442. '#download-button[href*=".png"]',
  1443. '#gmi-ResViewSizer_fullimg',
  1444. 'img.dev-content-full',
  1445. ],
  1446. },
  1447. {
  1448. u: '||dropbox.com/s',
  1449. r: /com\/sh?\/.+\.(jpe?g|gif|png)/i,
  1450. q: (text, doc) =>
  1451. $prop('img.absolute-center', 'src', doc).replace(/(size_mode)=\d+/, '$1=5') || false,
  1452. },
  1453. {
  1454. r: /[./]ebay\.[^/]+\/itm\//,
  1455. q: text =>
  1456. text.match(/https?:\/\/i\.ebayimg\.com\/[^.]+\.JPG/i)[0]
  1457. .replace(/~~60_\d+/, '~~60_57'),
  1458. },
  1459. {
  1460. u: '||i.ebayimg.com/',
  1461. s: (m, node) =>
  1462. $('.zoom_trigger_mask', node.parentNode) ? '' :
  1463. m.input.replace(/~~60_\d+/, '~~60_57'),
  1464. },
  1465. {
  1466. u: '||fastpic.ru',
  1467. e: 'a',
  1468. q: 'img[src*="/big/"]',
  1469. xhr: true,
  1470. },
  1471. {
  1472. u: '||facebook.com/',
  1473. r: /photo\.php|[^/]+\/photos\//,
  1474. s: (m, node) =>
  1475. node.id === 'fbPhotoImage' ? false :
  1476. /gradient\.png$/.test(m.input) ? '' :
  1477. m.input.replace('www.facebook.com', 'mbasic.facebook.com'),
  1478. q: [
  1479. 'div + span > a:first-child:not([href*="tag_faces"])',
  1480. 'div + span > a[href*="tag_faces"] ~ a',
  1481. ],
  1482. rect: '#fbProfileCover',
  1483. },
  1484. {
  1485. u: '||fbcdn.',
  1486. r: /fbcdn.+?[0-9]+_([0-9]+)_[0-9]+_[a-z]\.(jpg|png)/,
  1487. s: m =>
  1488. dotDomain.endsWith('.facebook.com') &&
  1489. tryCatch(() => unsafeWindow.PhotoSnowlift.getInstance().stream.cache.image[m[1]].url) ||
  1490. false,
  1491. manual: true,
  1492. },
  1493. {
  1494. u: ['||fbcdn-', 'fbcdn.net/'],
  1495. r: /(https?:\/\/(fbcdn-[-\w.]+akamaihd|[-\w.]+?fbcdn)\.net\/[-\w/.]+?)_[a-z]\.(jpg|png)(\?[0-9a-zA-Z0-9=_&]+)?/,
  1496. s: (m, node) => {
  1497. if (node.id === 'fbPhotoImage') {
  1498. const a = $('a.fbPhotosPhotoActionsItem[href$="dl=1"]', doc.body);
  1499. if (a) return a.href.includes(m.input.match(/[0-9]+_[0-9]+_[0-9]+/)[0]) ? '' : a.href;
  1500. }
  1501. if (m[4])
  1502. return false;
  1503. const pn = node.parentNode;
  1504. if (pn.outerHTML.includes('/hovercard/'))
  1505. return '';
  1506. if (node.outerHTML.includes('profile') && pn.parentNode.href.includes('/photo'))
  1507. return false;
  1508. return m[1].replace(/\/[spc][\d.x]+/g, '').replace('/v/', '/') + '_n.' + m[3];
  1509. },
  1510. rect: '.photoWrap',
  1511. },
  1512. {
  1513. u: '||flickr.com/photos/',
  1514. r: /photos\/([0-9]+@N[0-9]+|[a-z0-9_-]+)\/([0-9]+)/,
  1515. s: m =>
  1516. m.input.indexOf('/sizes/') < 0 ?
  1517. `https://www.flickr.com/photos/${m[1]}/${m[2]}/sizes/sq/` :
  1518. false,
  1519. q: (text, doc) => {
  1520. const links = $$('.sizes-list a', doc);
  1521. return 'https://www.flickr.com' + links[links.length - 1].getAttribute('href');
  1522. },
  1523. follow: true,
  1524. },
  1525. {
  1526. u: '||flickr.com/photos/',
  1527. r: /\/sizes\//,
  1528. q: '#allsizes-photo > img',
  1529. },
  1530. {
  1531. u: '||gfycat.com/',
  1532. r: /(gfycat\.com\/)(gifs\/detail\/|iframe\/)?([a-z]+)/i,
  1533. s: 'https://$1$3',
  1534. q: [
  1535. 'meta[content$=".webm"]',
  1536. '#webmsource',
  1537. 'source[src$=".webm"]',
  1538. ],
  1539. },
  1540. {
  1541. u: [
  1542. '||googleusercontent.com/proxy',
  1543. '||googleusercontent.com/gadgets/proxy',
  1544. ],
  1545. r: /\.com\/(proxy|gadgets\/proxy.+?(http.+?)&)/,
  1546. s: m => m[2] ? decodeURIComponent(m[2]) : m.input.replace(/w\d+-h\d+($|-p)/, 'w0-h0'),
  1547. },
  1548. {
  1549. u: [
  1550. '||googleusercontent.com/',
  1551. '||ggpht.com/',
  1552. ],
  1553. s: m => m.input.includes('webcache.') ? '' :
  1554. m.input.replace(/\/s\d{2,}-[^/]+|\/w\d+-h\d+/, '/s0')
  1555. .replace(/([&?]sz)?=[-\w]+([&#].*)?/, ''),
  1556. },
  1557. {
  1558. u: '||gravatar.com/',
  1559. r: /([a-z0-9]{32})/,
  1560. s: 'https://gravatar.com/avatar/$1?s=200',
  1561. },
  1562. {
  1563. u: '//gyazo.com/',
  1564. r: /\bgyazo\.com\/\w{32,}(\.\w+)?/,
  1565. s: (m, _, rule) => Ruler.toggle(rule, 'q', !m[1]) ? m.input : `https://i.${m[0]}`,
  1566. _q: 'meta[name="twitter:image"]',
  1567. },
  1568. {
  1569. u: '||hostingkartinok.com/show-image.php',
  1570. q: '.image img',
  1571. },
  1572. {
  1573. u: [
  1574. '||imagecurl.com/images/',
  1575. '||imagecurl.com/viewer.php',
  1576. ],
  1577. r: /(?:images\/(\d+)_thumb|file=(\d+))(\.\w+)/,
  1578. s: 'https://imagecurl.com/images/$1$2$3',
  1579. },
  1580. {
  1581. u: '||imagebam.com/image/',
  1582. q: 'meta[property="og:image"]',
  1583. tabfix: true,
  1584. xhr: hostname.includes('planetsuzy'),
  1585. },
  1586. {
  1587. u: '||imageban.ru/thumbs',
  1588. r: /(.+?\/)thumbs(\/\d+)\.(\d+)\.(\d+\/.*)/,
  1589. s: '$1out$2/$3/$4',
  1590. },
  1591. {
  1592. u: [
  1593. '||imageban.ru/show',
  1594. '||imageban.net/show',
  1595. '||ibn.im/',
  1596. ],
  1597. q: '#img_main',
  1598. },
  1599. {
  1600. u: '||imageshack.us/img',
  1601. r: /img(\d+)\.(imageshack\.us)\/img\\1\/\d+\/(.+?)\.th(.+)$/,
  1602. s: 'https://$2/download/$1/$3$4',
  1603. },
  1604. {
  1605. u: '||imageshack.us/i/',
  1606. q: '#share-dl',
  1607. },
  1608. {
  1609. u: '||imageteam.org/img',
  1610. q: 'img[alt="image"]',
  1611. },
  1612. {
  1613. u: [
  1614. '||imagetwist.com/',
  1615. '||imageshimage.com/',
  1616. ],
  1617. r: /(\/\/|^)[^/]+\/[a-z0-9]{8,}/,
  1618. q: 'img.pic',
  1619. xhr: true,
  1620. },
  1621. {
  1622. u: '||imageupper.com/i/',
  1623. q: '#img',
  1624. xhr: true,
  1625. },
  1626. {
  1627. u: '||imagevenue.com/',
  1628. q: 'a[data-toggle="full"] img',
  1629. },
  1630. {
  1631. u: '||imagezilla.net/show/',
  1632. q: '#photo',
  1633. xhr: true,
  1634. },
  1635. {
  1636. u: [
  1637. '||images-na.ssl-images-amazon.com/images/',
  1638. '||media-imdb.com/images/',
  1639. ],
  1640. r: /images\/.+?\.jpg/,
  1641. s: '/V1\\.?_.+?\\.//g',
  1642. },
  1643. {
  1644. u: '||imgbox.com/',
  1645. r: /\.com\/([a-z0-9]+)$/i,
  1646. q: '#img',
  1647. xhr: hostname !== 'imgbox.com',
  1648. },
  1649. {
  1650. u: '||imgclick.net/',
  1651. r: /\.net\/(\w+)/,
  1652. q: 'img.pic',
  1653. xhr: true,
  1654. post: m => `op=view&id=${m[1]}&pre=1&submit=Continue%20to%20image...`,
  1655. },
  1656. {
  1657. u: '.imgcredit.xyz/',
  1658. r: /^https?(:.*\.xyz\/\d[\w/]+)\.md(.+)/,
  1659. s: ['https$1$2', 'https$1.png']
  1660. },
  1661. {
  1662. u: [
  1663. '||imgflip.com/i/',
  1664. '||imgflip.com/gif/',
  1665. ],
  1666. r: /\/(i|gif)\/([^/?#]+)/,
  1667. s: m => `https://i.imgflip.com/${m[2]}${m[1] === 'i' ? '.jpg' : '.mp4'}`,
  1668. },
  1669. {
  1670. u: [
  1671. '||imgur.com/a/',
  1672. '||imgur.com/gallery/',
  1673. ],
  1674. g: async (text, doc, url, m, rule, node, cb) => {
  1675. let u = `https://imgur.com/ajaxalbums/getimages/${url.split(/[/?#]/)[4]}/hit.json?all=true`;
  1676. const info = tryCatch(JSON.parse, (await Remoting.gmXhr(u)).responseText);
  1677. const images = ((info || 0).data || 0).images;
  1678. const items = [];
  1679. for (const img of images || []) {
  1680. u = `https://i.imgur.com/${img.hash}`;
  1681. items.push({
  1682. url: img.ext === '.gif' && img.animated !== false ?
  1683. [`${u}.webm`, `${u}.mp4`, u] :
  1684. u + img.ext,
  1685. desc: [img.title, img.description].filter(Boolean).join(' - '),
  1686. });
  1687. }
  1688. if (items[0] && info.title && !`${items[0].desc || ''}`.includes(info.title))
  1689. items.title = info.title;
  1690. cb(items);
  1691. },
  1692. css: '.post > .hover { display:none!important; }',
  1693. },
  1694. {
  1695. u: '||imgur.com/',
  1696. r: /((?:[a-z]{2,}\.)?imgur\.com\/)((?:\w+,)+\w*)/,
  1697. s: 'gallery',
  1698. g: (text, doc, url, m) =>
  1699. m[2].split(',').map(id => ({
  1700. url: `https://i.${m[1]}${id}.jpg`,
  1701. })),
  1702. },
  1703. {
  1704. u: '||imgur.com/',
  1705. r: /([a-z]{2,}\.)?imgur\.com\/(r\/[a-z]+\/|[a-z0-9]+#)?([a-z0-9]{5,})($|\?|\.(mp4|[a-z]+))/i,
  1706. s: (m, node) => {
  1707. if (/memegen|random|register|search|signin/.test(m.input))
  1708. return '';
  1709. const a = node.closest('a');
  1710. if (a && a !== node && /(i\.([a-z]+\.)?)?imgur\.com\/(a\/|gallery\/)?/.test(a.href))
  1711. return false;
  1712. // postfixes: huge, large, medium, thumbnail, big square, small square
  1713. const id = m[3].replace(/(.{7})[hlmtbs]$/, '$1');
  1714. const ext = m[5] ? m[5].replace(/gifv?/, 'webm') : 'jpg';
  1715. const u = `https://i.${(m[1] || '').replace('www.', '')}imgur.com/${id}.`;
  1716. return ext === 'webm' ?
  1717. [`${u}webm`, `${u}mp4`, `${u}gif`] :
  1718. u + ext;
  1719. },
  1720. },
  1721. {
  1722. u: [
  1723. '||instagr.am/p/',
  1724. '||instagram.com/p/',
  1725. ],
  1726. s: m => m.input.substr(0, m.input.lastIndexOf('/')) + '/?__a=1',
  1727. q: text => {
  1728. const m = JSON.parse(text).graphql.shortcode_media;
  1729. return m.video_url || m.display_url;
  1730. },
  1731. rect: 'div.PhotoGridMediaItem',
  1732. c: text => {
  1733. const m = JSON.parse(text).graphql.shortcode_media.edge_media_to_caption.edges[0];
  1734. return m === undefined ? '(no caption)' : m.node.text;
  1735. },
  1736. },
  1737. {
  1738. u: [
  1739. '||livememe.com/',
  1740. '||lvme.me/',
  1741. ],
  1742. r: /\.\w+\/([^.]+)$/,
  1743. s: 'http://i.lvme.me/$1.jpg',
  1744. },
  1745. {
  1746. u: '||lostpic.net/image',
  1747. q: '.image-viewer-image img',
  1748. },
  1749. {
  1750. u: '||makeameme.org/meme/',
  1751. r: /\/meme\/([^/?#]+)/,
  1752. s: 'https://media.makeameme.org/created/$1.jpg',
  1753. },
  1754. {
  1755. u: '||photobucket.com/',
  1756. r: /(\d+\.photobucket\.com\/.+\/)(\?[a-z=&]+=)?(.+\.(jpe?g|png|gif))/,
  1757. s: 'https://i$1$3',
  1758. xhr: !dotDomain.endsWith('.photobucket.com'),
  1759. },
  1760. {
  1761. u: '||piccy.info/view3/',
  1762. r: /(.+?\/view3)\/(.*)\//,
  1763. s: '$1/$2/orig/',
  1764. q: '#mainim',
  1765. },
  1766. {
  1767. u: '||pimpandhost.com/image/',
  1768. r: /(.+?\/image\/[0-9]+)/,
  1769. s: '$1?size=original',
  1770. q: 'img.original',
  1771. },
  1772. {
  1773. u: [
  1774. '||pixroute.com/',
  1775. '||imgspice.com/',
  1776. ],
  1777. r: /\.html$/,
  1778. q: 'img[id]',
  1779. xhr: true,
  1780. },
  1781. {
  1782. u: '||postima',
  1783. r: /postima?ge?\.org\/image\/\w+/,
  1784. q: [
  1785. 'a[href*="dl="]',
  1786. '#main-image',
  1787. ],
  1788. },
  1789. {
  1790. u: [
  1791. '||prntscr.com/',
  1792. '||prnt.sc/',
  1793. ],
  1794. r: /\.\w+\/.+/,
  1795. q: 'meta[property="og:image"]',
  1796. xhr: true,
  1797. },
  1798. {
  1799. u: '||radikal.ru/',
  1800. r: /\.ru\/(fp|.+?\.html)|^(.+?)t\.jpg/,
  1801. s: (m, node, rule) =>
  1802. m[2] && /radikal\.ru[\w%/]+?(\.\w+)/.test($propUp(node, 'href')) ? m[2] + RegExp.$1 :
  1803. Ruler.toggle(rule, 'q', m[1]) ? m.input : [m[2] + '.jpg', m[2] + '.png'],
  1804. _q: text => text.match(/https?:\/\/\w+\.radikal\.ru[\w/]+\.(jpg|gif|png)/i)[0],
  1805. },
  1806. {
  1807. u: '||tumblr.com',
  1808. r: /_500\.jpg/,
  1809. s: ['/_500/_1280/', ''],
  1810. },
  1811. {
  1812. u: '||twimg.com/',
  1813. r: /\/profile_images/i,
  1814. s: '/_(reasonably_small|normal|bigger|\\d+x\\d+)\\././g',
  1815. },
  1816. {
  1817. u: '||twimg.com/media/',
  1818. r: /.+?format=(jpe?g|png|gif)/i,
  1819. s: '$0&name=orig',
  1820. },
  1821. {
  1822. u: '||twimg.com/1/proxy',
  1823. r: /t=([^&_]+)/i,
  1824. s: m => atob(m[1]).match(/http.+/),
  1825. },
  1826. {
  1827. u: '||pic.twitter.com/',
  1828. r: /\.com\/[a-z0-9]+/i,
  1829. q: text => text.match(/https?:\/\/twitter\.com\/[^/]+\/status\/\d+\/photo\/\d+/i)[0],
  1830. follow: true,
  1831. },
  1832. {
  1833. u: '||twitpic.com/',
  1834. r: /\.com(\/show\/[a-z]+)?\/([a-z0-9]+)($|#)/i,
  1835. s: 'https://twitpic.com/show/large/$2',
  1836. },
  1837. {
  1838. u: '||wiki',
  1839. r: /\/(thumb|images)\/.+\.(jpe?g|gif|png|svg)\/(revision\/)?/i,
  1840. s: '/\\/thumb(?=\\/)|' +
  1841. '\\/scale-to-width(-[a-z]+)?\\/[0-9]+|' +
  1842. '\\/revision\\/latest|\\/[^\\/]+$//g',
  1843. xhr: !hostname.includes('wiki'),
  1844. },
  1845. {
  1846. u: '||ytimg.com/vi/',
  1847. r: /(.+?\/vi\/[^/]+)/,
  1848. s: '$1/0.jpg',
  1849. rect: '.video-list-item',
  1850. },
  1851. {
  1852. u: '/viewer.php?file=',
  1853. r: /(.+?)\/viewer\.php\?file=(.+)/,
  1854. s: '$1/images/$2',
  1855. xhr: true,
  1856. },
  1857. {
  1858. u: '/thumb_',
  1859. r: /\/albums.+\/thumb_[^/]/,
  1860. s: '/thumb_//',
  1861. },
  1862. {
  1863. u: [
  1864. '.th.jp',
  1865. '.th.gif',
  1866. '.th.png',
  1867. ],
  1868. r: /(.+?\.)th\.(jpe?g?|gif|png|svg|webm)$/i,
  1869. s: '$1$2',
  1870. follow: true,
  1871. },
  1872. {
  1873. r: RX_MEDIA_URL,
  1874. },
  1875. ];
  1876.  
  1877. /** @type mpiv.HostRule[] */
  1878. Ruler.rules = [].concat(customRules, disablers, perDomain, main).filter(Boolean);
  1879. },
  1880.  
  1881. format(rule, {expand} = {}) {
  1882. const s = Util.stringify(rule, null, ' ');
  1883. return expand ?
  1884. /* {"a": ...,
  1885. "b": ...,
  1886. "c": ...
  1887. } */
  1888. s.replace(/^{\s+/g, '{') :
  1889. /* {"a": ..., "b": ..., "c": ...} */
  1890. s.replace(/\n\s*/g, ' ').replace(/^({)\s|\s+(})$/g, '$1$2');
  1891. },
  1892.  
  1893. fromElement(el) {
  1894. const text = el.textContent.trim();
  1895. if (text.startsWith('{') &&
  1896. text.endsWith('}') &&
  1897. /[{,]\s*"[degqrsu]"\s*:\s*"/.test(text)) {
  1898. const rule = tryCatch(JSON.parse, text);
  1899. return rule && Object.keys(rule).some(k => /^[degqrsu]$/.test(k)) && rule;
  1900. }
  1901. },
  1902.  
  1903. /** @returns mpiv.HostRule | Error | false | undefined */
  1904. parse(rule) {
  1905. const isBatchOp = this instanceof Map;
  1906. try {
  1907. if (typeof rule === 'string')
  1908. rule = JSON.parse(rule);
  1909. if ('d' in rule && typeof rule.d !== 'string')
  1910. rule.d = undefined;
  1911. else if (isBatchOp && rule.d && !hostname.includes(rule.d))
  1912. return false;
  1913. const compileTo = isBatchOp ? rule : {};
  1914. if (rule.r)
  1915. compileTo.r = new RegExp(rule.r, 'i');
  1916. if (RX_HAS_CODE.test(rule.s))
  1917. compileTo.s = Util.newFunction('m', 'node', 'rule', rule.s);
  1918. if (RX_HAS_CODE.test(rule.q))
  1919. compileTo.q = Util.newFunction('text', 'doc', 'node', 'rule', rule.q);
  1920. if (RX_HAS_CODE.test(rule.c))
  1921. compileTo.c = Util.newFunction('text', 'doc', 'node', 'rule', rule.c);
  1922. return rule;
  1923. } catch (e) {
  1924. if (!e.message.includes('unsafe-eval'))
  1925. if (isBatchOp) {
  1926. this.set(rule, e);
  1927. } else {
  1928. return e;
  1929. }
  1930. }
  1931. },
  1932.  
  1933. runC(text, doc = document) {
  1934. const fn = Ruler.runCHandler[typeof ai.rule.c] || Ruler.runCHandler.default;
  1935. ai.caption = fn(text, doc);
  1936. },
  1937.  
  1938. runCHandler: {
  1939. function: (text, doc) =>
  1940. ai.rule.c(text || doc.documentElement.outerHTML, doc, ai.node, ai.rule),
  1941. string: (text, doc) => {
  1942. const el = $many(ai.rule.c, doc);
  1943. return !el ? '' :
  1944. el.getAttribute('content') ||
  1945. el.getAttribute('title') ||
  1946. el.textContent;
  1947. },
  1948. default: () =>
  1949. (ai.tooltip || 0).text ||
  1950. ai.node.alt ||
  1951. $propUp(ai.node, 'title') ||
  1952. Remoting.getFileName(
  1953. ai.node.tagName === (ai.popup || 0).tagName
  1954. ? ai.url
  1955. : ai.node.src || $propUp(ai.node, 'href')),
  1956. },
  1957.  
  1958. runQ(text, doc, docUrl) {
  1959. let url;
  1960. if (typeof ai.rule.q === 'function') {
  1961. url = ai.rule.q(text, doc, ai.node, ai.rule);
  1962. if (Array.isArray(url)) {
  1963. ai.urls = url.slice(1);
  1964. url = url[0];
  1965. }
  1966. } else {
  1967. const el = $many(ai.rule.q, doc);
  1968. url = Remoting.findImageUrl(el, docUrl);
  1969. }
  1970. return url;
  1971. },
  1972.  
  1973. /** @returns {?Array} if falsy then the rule should be skipped */
  1974. runS(node, rule, m) {
  1975. let urls = [];
  1976. for (const s of ensureArray(rule.s))
  1977. urls.push(
  1978. typeof s === 'string' ? Util.decodeUrl(Ruler.substituteSingle(s, m)) :
  1979. typeof s === 'function' ? s(m, node, rule) :
  1980. s);
  1981. if (rule.q && urls.length > 1) {
  1982. console.warn('Rule discarded: "s" array is not allowed with "q"\n%o', rule);
  1983. return;
  1984. }
  1985. if (Array.isArray(urls[0]))
  1986. urls = urls[0];
  1987. // `false` returned by "s" property means "skip this rule", "" means "stop all rules"
  1988. return urls[0] !== false && Array.from(new Set(urls), Util.decodeUrl);
  1989. },
  1990.  
  1991. substituteSingle(s, m) {
  1992. if (!m) return s;
  1993. if (s.startsWith('/') && !s.startsWith('//')) {
  1994. const mid = s.search(/[^\\]\//) + 1;
  1995. const end = s.lastIndexOf('/');
  1996. const re = new RegExp(s.slice(1, mid), s.slice(end + 1));
  1997. return m.input.replace(re, s.slice(mid + 1, end));
  1998. }
  1999. if (m.length && s.includes('$')) {
  2000. const maxLength = Math.floor(Math.log10(m.length)) + 1;
  2001. s = s.replace(/\$(\d{1,3})/g, (text, num) => {
  2002. for (let i = maxLength; i >= 0; i--) {
  2003. const part = num.slice(0, i) | 0;
  2004. if (part < m.length)
  2005. return (m[part] || '') + num.slice(i);
  2006. }
  2007. return text;
  2008. });
  2009. }
  2010. return s;
  2011. },
  2012.  
  2013. toggle(rule, prop, condition) {
  2014. rule[prop] = condition ? rule[`_${prop}`] : null;
  2015. return condition;
  2016. },
  2017. };
  2018.  
  2019. const RuleMatcher = {
  2020.  
  2021. /** @returns ?mpiv.RuleMatchInfo */
  2022. findForLink(a) {
  2023. let url =
  2024. a.getAttribute('data-expanded-url') ||
  2025. a.getAttribute('data-full-url') ||
  2026. a.getAttribute('data-url') ||
  2027. a.href;
  2028. if (url.startsWith('data:'))
  2029. url = false;
  2030. else if (url.includes('//t.co/'))
  2031. url = 'http://' + a.textContent;
  2032. return RuleMatcher.find(url, a);
  2033. },
  2034.  
  2035. /** @returns ?mpiv.RuleMatchInfo */
  2036. find(url, node, {noHtml, skipRules} = {}) {
  2037. const tn = node.tagName;
  2038. const isPic = tn === 'IMG' || tn === 'VIDEO';
  2039. const isPicOrLink = isPic || tn === 'A';
  2040. let m, html;
  2041. for (const rule of Ruler.rules) {
  2042. const u = rule[SYM_U] || rule.u && (rule[SYM_U] = UrlMatcher(rule.u));
  2043. if (u && (!url || !u.fn.call(u.data, url)) ||
  2044. rule.e && !node.matches(rule.e) ||
  2045. skipRules && skipRules.includes(rule))
  2046. continue;
  2047. if (rule.r)
  2048. m = !noHtml && rule.html && (isPicOrLink || rule.e)
  2049. ? rule.r.exec(html || (html = node.outerHTML))
  2050. : url && rule.r.exec(url);
  2051. else if (url)
  2052. m = Object.assign([url], {index: 0, input: url});
  2053. else
  2054. m = [];
  2055. if (!m)
  2056. continue;
  2057. if (rule.s === '')
  2058. return {};
  2059. let hasS = rule.s != null;
  2060. // a rule with follow:true for the currently hovered IMG produced a URL,
  2061. // but we'll only allow it to match rules without 's' in the nested find call
  2062. if (isPic && !hasS && !skipRules)
  2063. continue;
  2064. hasS &= rule.s !== 'gallery';
  2065. const urls = hasS ? Ruler.runS(node, rule, m) : [m.input];
  2066. if (urls)
  2067. return RuleMatcher.makeInfo(hasS, rule, m, node, skipRules, urls);
  2068. }
  2069. },
  2070.  
  2071. /** @returns ?mpiv.RuleMatchInfo */
  2072. makeInfo(hasS, rule, match, node, skipRules, urls) {
  2073. let info;
  2074. let url = `${urls[0]}`;
  2075. const follow = url && hasS && !rule.q && RuleMatcher.isFollowableUrl(url, rule);
  2076. if (!url)
  2077. info = {};
  2078. if (follow)
  2079. info = RuleMatcher.find(url, node, {skipRules: [...skipRules || [], rule]});
  2080. if (!info && (!follow || RX_MEDIA_URL.test(url))) {
  2081. const xhr = cfg.xhr && rule.xhr;
  2082. if (url.startsWith('//'))
  2083. url = location.protocol + url;
  2084. info = {
  2085. match,
  2086. node,
  2087. rule,
  2088. url,
  2089. urls: urls.length > 1 ? urls.slice(1) : null,
  2090. gallery: rule.g && Gallery.makeParser(rule.g),
  2091. post: typeof rule.post === 'function' ? rule.post(match) : rule.post,
  2092. xhr: xhr != null ? xhr : isSecureContext && !url.startsWith(location.protocol),
  2093. };
  2094. }
  2095. return info;
  2096. },
  2097.  
  2098. isFollowableUrl(url, rule) {
  2099. const f = rule.follow;
  2100. return typeof f === 'function' ? f(url) : f;
  2101. },
  2102. };
  2103.  
  2104. const Remoting = {
  2105.  
  2106. gmXhr(url, opts = {}) {
  2107. if (ai.req)
  2108. tryCatch.call(ai.req, ai.req.abort);
  2109. return new Promise((resolve, reject) => {
  2110. ai.req = GM_xmlhttpRequest({
  2111. url,
  2112. method: 'GET',
  2113. anonymous: (ai.rule || {}).anonymous,
  2114. timeout: 30e3,
  2115. ...opts,
  2116. onload: done,
  2117. onerror: done,
  2118. ontimeout() {
  2119. ai.req = null;
  2120. reject(`Timeout fetching ${url}`);
  2121. },
  2122. });
  2123. function done(r) {
  2124. ai.req = null;
  2125. if (r.status < 400 && !r.error)
  2126. resolve(r);
  2127. else
  2128. reject(`Server error ${r.status} ${r.error}\nURL: ${url}`);
  2129. }
  2130. });
  2131. },
  2132.  
  2133. async getDoc(url) {
  2134. const r = await (!ai.post ?
  2135. Remoting.gmXhr(url) :
  2136. Remoting.gmXhr(url, {
  2137. method: 'POST',
  2138. data: ai.post,
  2139. headers: {
  2140. 'Content-Type': 'application/x-www-form-urlencoded',
  2141. 'Referer': url,
  2142. },
  2143. }));
  2144. r.doc = new DOMParser().parseFromString(r.responseText, 'text/html');
  2145. return r;
  2146. },
  2147.  
  2148. async getImage(url, pageUrl, xhr = ai.xhr) {
  2149. ai.bufBar = false;
  2150. ai.bufStart = now();
  2151. const response = await Remoting.gmXhr(url, {
  2152. responseType: 'blob',
  2153. headers: {
  2154. Accept: 'image/png,image/*;q=0.8,*/*;q=0.5',
  2155. Referer: pageUrl || (typeof xhr === 'function' ? xhr() : url),
  2156. },
  2157. onprogress: Remoting.getImageProgress,
  2158. });
  2159. Bar.set(false);
  2160. const type = Remoting.guessMimeType(response);
  2161. let b = response.response;
  2162. if (!b) throw 'Empty response';
  2163. if (b.type !== type)
  2164. b = b.slice(0, b.size, type);
  2165. return [
  2166. xhr === 'blob' ? URL.createObjectURL(b) : await Remoting.blobToDataUrl(b),
  2167. type.startsWith('video'),
  2168. ];
  2169. },
  2170.  
  2171. getImageProgress(e) {
  2172. if (!ai.bufBar && now() - ai.bufStart > 3000 && e.loaded / e.total < 0.5)
  2173. ai.bufBar = true;
  2174. if (ai.bufBar) {
  2175. const pct = e.loaded / e.total * 100 | 0;
  2176. const size = e.total / 1024 | 0;
  2177. Bar.set(`${pct}% of ${size} kiB`, 'xhr');
  2178. }
  2179. },
  2180.  
  2181. async findRedirect() {
  2182. try {
  2183. const {finalUrl} = await Remoting.gmXhr(ai.url, {
  2184. method: 'HEAD',
  2185. headers: {
  2186. 'Referer': location.href.split('#', 1)[0],
  2187. },
  2188. });
  2189. const info = RuleMatcher.find(finalUrl, ai.node, {noHtml: true});
  2190. if (!info || !info.url)
  2191. throw `Couldn't follow redirection target: ${finalUrl}`;
  2192. Object.assign(ai, info);
  2193. App.startSingle();
  2194. } catch (e) {
  2195. App.handleError(e);
  2196. }
  2197. },
  2198.  
  2199. async saveFile() {
  2200. const url = ai.popup.src || ai.popup.currentSrc;
  2201. let name = Remoting.getFileName(ai.imageUrl || url);
  2202. if (!name.includes('.'))
  2203. name += '.jpg';
  2204. if (url.startsWith('blob:') || url.startsWith('data:')) {
  2205. $create('a', {href: url, download: name})
  2206. .dispatchEvent(new MouseEvent('click'));
  2207. } else {
  2208. Status.set('+loading');
  2209. const onload = () => Status.set('-loading');
  2210. GM_download({
  2211. url,
  2212. name,
  2213. headers: {Referer: url},
  2214. onerror: e => {
  2215. Bar.set(`Could not download ${name}: ${e.error || e.message || e}.`, 'error');
  2216. onload();
  2217. },
  2218. onprogress: Remoting.getImageProgress,
  2219. onload,
  2220. });
  2221. }
  2222. },
  2223.  
  2224. getFileName(url) {
  2225. return decodeURIComponent(url).split('/').pop().replace(/[:#?].*/, '');
  2226. },
  2227.  
  2228. blobToDataUrl(blob) {
  2229. return new Promise((resolve, reject) => {
  2230. const fr = new FileReader();
  2231. fr.onload = () => resolve(fr.result);
  2232. fr.onerror = reject;
  2233. fr.readAsDataURL(blob);
  2234. });
  2235. },
  2236.  
  2237. guessMimeType({responseHeaders, finalUrl}) {
  2238. if (/Content-Type:\s*(\S+)/i.test(responseHeaders) &&
  2239. !RegExp.$1.includes('text/plain'))
  2240. return RegExp.$1;
  2241. const ext = /\.([a-z0-9]+?)($|\?|#)/i.exec(finalUrl) ? RegExp.$1 : 'jpg';
  2242. switch (ext.toLowerCase()) {
  2243. case 'bmp': return 'image/bmp';
  2244. case 'gif': return 'image/gif';
  2245. case 'jpe': return 'image/jpeg';
  2246. case 'jpeg': return 'image/jpeg';
  2247. case 'jpg': return 'image/jpeg';
  2248. case 'mp4': return 'video/mp4';
  2249. case 'png': return 'image/png';
  2250. case 'svg': return 'image/svg+xml';
  2251. case 'tif': return 'image/tiff';
  2252. case 'tiff': return 'image/tiff';
  2253. case 'webm': return 'video/webm';
  2254. default: return 'application/octet-stream';
  2255. }
  2256. },
  2257.  
  2258. findImageUrl(n, url) {
  2259. if (!n) return;
  2260. let html;
  2261. const path =
  2262. n.getAttribute('src') ||
  2263. n.getAttribute('data-m4v') ||
  2264. n.getAttribute('href') ||
  2265. n.getAttribute('content') ||
  2266. (html = n.outerHTML).includes('http') &&
  2267. html.match(/https?:\/\/[^\s"<>]+?\.(jpe?g|gif|png|svg|web[mp]|mp4)[^\s"<>]*|$/i)[0];
  2268. return !!path && Util.rel2abs(Util.decodeHtmlEntities(path),
  2269. $prop('base[href]', 'href', n.ownerDocument) || url);
  2270. },
  2271. };
  2272.  
  2273. const Status = {
  2274.  
  2275. set(status) {
  2276. if (!status && !cfg.globalStatus) {
  2277. ai.node && ai.node.removeAttribute(STATUS_ATTR);
  2278. return;
  2279. }
  2280. const prefix = cfg.globalStatus ? PREFIX : '';
  2281. const action = status && /^[+-]/.test(status) && status[0];
  2282. const name = status && `${prefix}${action ? status.slice(1) : status}`;
  2283. const el = cfg.globalStatus ? doc.documentElement :
  2284. name === 'edge' ? ai.popup :
  2285. ai.node;
  2286. if (!el) return;
  2287. const attr = cfg.globalStatus ? 'class' : STATUS_ATTR;
  2288. const oldValue = (el.getAttribute(attr) || '').trim();
  2289. const cls = new Set(oldValue ? oldValue.split(/\s+/) : []);
  2290. switch (action) {
  2291. case '-':
  2292. cls.delete(name);
  2293. break;
  2294. case false:
  2295. for (const c of cls)
  2296. if (c.startsWith(prefix) && c !== name)
  2297. cls.delete(c);
  2298. // fallthrough to +
  2299. case '+':
  2300. if (name)
  2301. cls.add(name);
  2302. break;
  2303. }
  2304. const newValue = [...cls].join(' ');
  2305. if (newValue !== oldValue)
  2306. el.setAttribute(attr, newValue);
  2307. },
  2308.  
  2309. loading(force) {
  2310. if (!force) {
  2311. clearTimeout(ai.timerStatus);
  2312. ai.timerStatus = setTimeout(Status.loading, SETTLE_TIME, true);
  2313. } else if (!ai.popupLoaded) {
  2314. Status.set('+loading');
  2315. }
  2316. },
  2317. };
  2318.  
  2319. const UrlMatcher = (() => {
  2320. // string-to-regexp escaped chars
  2321. const RX_ESCAPE = /[.+*?(){}[\]^$|]/g;
  2322. // rx for '^' symbol in simple url match
  2323. const RX_SEP = /[^\w%._-]/y;
  2324. const RXS_SEP = RX_SEP.source;
  2325. return match => {
  2326. const results = [];
  2327. for (const s of ensureArray(match)) {
  2328. const pinDomain = s.startsWith('||');
  2329. const pinStart = !pinDomain && s.startsWith('|');
  2330. const endSep = s.endsWith('^');
  2331. let fn;
  2332. let needle = s.slice(pinDomain * 2 + pinStart, -endSep || undefined);
  2333. if (needle.includes('^')) {
  2334. let plain = '';
  2335. for (const part of needle.split('^'))
  2336. if (part.length > plain.length)
  2337. plain = part;
  2338. const rx = new RegExp(
  2339. (pinStart ? '^' : '') +
  2340. (pinDomain ? '^(([^/:]+:)?//)?([^./]*\\.)*?' : '') +
  2341. needle.replace(RX_ESCAPE, '\\$&').replace(/\\\^/g, RXS_SEP) +
  2342. (endSep ? `(?:${RXS_SEP}|$)` : ''), 'i');
  2343. needle = [plain, rx];
  2344. fn = regexp;
  2345. } else if (pinStart) {
  2346. fn = endSep ? equals : starts;
  2347. } else if (pinDomain) {
  2348. const slashPos = needle.indexOf('/');
  2349. const domain = slashPos > 0 ? needle.slice(0, slashPos) : needle;
  2350. needle = [needle, domain, slashPos > 0, endSep];
  2351. fn = startsDomainPrescreen;
  2352. } else if (endSep) {
  2353. fn = ends;
  2354. } else {
  2355. fn = has;
  2356. }
  2357. results.push({fn, data: needle});
  2358. }
  2359. return results.length > 1 ?
  2360. {fn: checkArray, data: results} :
  2361. results[0];
  2362. };
  2363. function checkArray(s) {
  2364. return this.some(checkArrayItem, s);
  2365. }
  2366. function checkArrayItem(item) {
  2367. return item.fn.call(item.data, this);
  2368. }
  2369. function ends(s) {
  2370. return s.endsWith(this) || (
  2371. s.length > this.length &&
  2372. s.indexOf(this, s.length - this.length - 1) >= 0 &&
  2373. endsWithSep(s));
  2374. }
  2375. function endsWithSep(s, pos = s.length - 1) {
  2376. RX_SEP.lastIndex = pos;
  2377. return RX_SEP.test(s);
  2378. }
  2379. function equals(s) {
  2380. return s.startsWith(this) && (
  2381. s.length === this.length ||
  2382. s.length === this.length + 1 && endsWithSep(s));
  2383. }
  2384. function has(s) {
  2385. return s.includes(this);
  2386. }
  2387. function regexp(s) {
  2388. return s.includes(this[0]) && this[1].test(s);
  2389. }
  2390. function starts(s) {
  2391. return s.startsWith(this);
  2392. }
  2393. function startsDomainPrescreen(url) {
  2394. return url.includes(this[0]) && startsDomain.call(this, url);
  2395. }
  2396. function startsDomain(url) {
  2397. let hostStart = url.indexOf('//');
  2398. if (hostStart && url[hostStart - 1] !== ':')
  2399. return;
  2400. hostStart = hostStart < 0 ? 0 : hostStart + 2;
  2401. const host = url.slice(hostStart, (url.indexOf('/', hostStart) + 1 || url.length + 1) - 1);
  2402. const [needle, domain, pinDomainEnd, endSep] = this;
  2403. let start = pinDomainEnd ? host.length - domain.length : 0;
  2404. for (; ; start++) {
  2405. start = host.indexOf(domain, start);
  2406. if (start < 0)
  2407. return;
  2408. if (!start || host[start - 1] === '.')
  2409. break;
  2410. }
  2411. start += hostStart;
  2412. if (url.lastIndexOf(needle, start) !== start)
  2413. return;
  2414. const end = start + needle.length;
  2415. return !endSep || end === host.length || end === url.length || endsWithSep(url, end);
  2416. }
  2417. })();
  2418.  
  2419. const Util = {
  2420.  
  2421. addStyle(name, css) {
  2422. const id = `${PREFIX}style:${name}`;
  2423. const el = doc.getElementById(id) ||
  2424. css && $create('style', {id});
  2425. if (!el) return;
  2426. if (el.textContent !== css)
  2427. el.textContent = css;
  2428. if (el.parentElement !== doc.head)
  2429. doc.head.appendChild(el);
  2430. return el;
  2431. },
  2432.  
  2433. color(color, opacity = cfg[`ui${color}Opacity`]) {
  2434. return (color.startsWith('#') ? color : cfg[`ui${color}Color`]) +
  2435. (0x100 + Math.round(opacity / 100 * 255)).toString(16).slice(1);
  2436. },
  2437.  
  2438. decodeHtmlEntities(s) {
  2439. return s
  2440. .replace(/&quot;/g, '"')
  2441. .replace(/&apos;/g, '\'')
  2442. .replace(/&lt;/g, '<')
  2443. .replace(/&gt;/g, '>')
  2444. .replace(/&amp;/g, '&');
  2445. },
  2446.  
  2447. // decode only if the main part of the URL is encoded to preserve the encoded parameters
  2448. decodeUrl(url) {
  2449. if (!url) return url;
  2450. const iPct = url.indexOf('%');
  2451. const iColon = url.indexOf(':');
  2452. return iPct >= 0 && (iPct < iColon || iColon < 0) ?
  2453. decodeURIComponent(url) :
  2454. url;
  2455. },
  2456.  
  2457. deepEqual(a, b) {
  2458. if (!a || !b || typeof a !== 'object' || typeof a !== typeof b)
  2459. return a === b;
  2460. if (Array.isArray(a)) {
  2461. return Array.isArray(b) &&
  2462. a.length === b.length &&
  2463. a.every((v, i) => Util.deepEqual(v, b[i]));
  2464. }
  2465. const keys = Object.keys(a);
  2466. return keys.length === Object.keys(b).length &&
  2467. keys.every(k => Util.deepEqual(a[k], b[k]));
  2468. },
  2469.  
  2470. forceLayout(node) {
  2471. // eslint-disable-next-line no-unused-expressions
  2472. node.clientHeight;
  2473. },
  2474.  
  2475. formatError(e, rule) {
  2476. const message =
  2477. e.message ||
  2478. e.readyState && 'Request failed.' ||
  2479. e.type === 'error' && `File can't be displayed.${
  2480. $('div[bgactive*="flashblock"]', doc) ? ' Check Flashblock settings.' : ''
  2481. }` ||
  2482. e;
  2483. const m = [
  2484. [`${GM_info.script.name}: %c${message}%c`, 'font-weight:bold;color:yellow'],
  2485. ['', 'font-weight:normal;color:unset'],
  2486. ];
  2487. m.push(...[
  2488. ['Node: %o', ai.node],
  2489. ['Rule: %o', rule],
  2490. ai.url && ['URL: %s', ai.url],
  2491. ai.imageUrl && ai.imageUrl !== ai.url && ['File: %s', ai.imageUrl],
  2492. ].filter(Boolean));
  2493. return {
  2494. message,
  2495. consoleFormat: m.map(([k]) => k).filter(Boolean).join('\n'),
  2496. consoleArgs: m.map(([, v]) => v),
  2497. };
  2498. },
  2499.  
  2500. isHovered(el) {
  2501. // doesn't work in image tabs, browser bug?
  2502. return App.isImageTab || el.closest(':hover');
  2503. },
  2504.  
  2505. isVideoUrl(url) {
  2506. return url.startsWith('data:video') ||
  2507. !url.startsWith('data:') && /\.(webm|mp4)($|\?)/.test(url);
  2508. },
  2509.  
  2510. newFunction(...args) {
  2511. try {
  2512. return App.NOP || new Function(...args);
  2513. } catch (e) {
  2514. if (!e.message.includes('unsafe-eval'))
  2515. throw e;
  2516. App.NOP = () => {};
  2517. return App.NOP;
  2518. }
  2519. },
  2520.  
  2521. rel2abs(rel, abs = location.href) {
  2522. try {
  2523. return rel.startsWith('data:') ? rel :
  2524. rel.startsWith('blob:') ? '' : // blobs don't work because they're usually revoked
  2525. new URL(rel, abs).href;
  2526. } catch (e) {
  2527. return rel;
  2528. }
  2529. },
  2530.  
  2531. stringify(...args) {
  2532. const p = Array.prototype;
  2533. const {toJSON} = p;
  2534. if (toJSON) p.toJSON = null;
  2535. const res = JSON.stringify(...args);
  2536. if (toJSON) p.toJSON = toJSON;
  2537. return res;
  2538. },
  2539.  
  2540. suppressTooltip() {
  2541. for (const node of [
  2542. ai.node.parentNode,
  2543. ai.node,
  2544. ai.node.firstElementChild,
  2545. ]) {
  2546. const t = (node || 0).title;
  2547. if (t && t !== node.textContent && !doc.title.includes(t) && !/^https?:\S+$/.test(t)) {
  2548. ai.tooltip = {node, text: t};
  2549. node.title = '';
  2550. break;
  2551. }
  2552. }
  2553. },
  2554.  
  2555. tabFixUrl() {
  2556. return ai.rule.tabfix && ai.popup.tagName === 'IMG' && !ai.xhr &&
  2557. navigator.userAgent.includes('Gecko/') &&
  2558. flattenHtml(`data:text/html;charset=utf8,
  2559. <style>
  2560. body {
  2561. margin: 0;
  2562. padding: 0;
  2563. background: #222;
  2564. }
  2565. .fit {
  2566. overflow: hidden
  2567. }
  2568. .fit > img {
  2569. max-width: 100vw;
  2570. max-height: 100vh;
  2571. }
  2572. body > img {
  2573. margin: auto;
  2574. position: absolute;
  2575. left: 0;
  2576. right: 0;
  2577. top: 0;
  2578. bottom: 0;
  2579. }
  2580. </style>
  2581. <body class=fit>
  2582. <img onclick="document.body.classList.toggle('fit')" src="${ai.popup.src}">
  2583. </body>
  2584. `).replace(/\x20?([:>])\x20/g, '$1').replace(/#/g, '%23');
  2585. },
  2586. };
  2587.  
  2588. function setup({rule} = {}) {
  2589. if (typeof doc.body.attachShadow !== 'function') {
  2590. alert('Cannot show MPIV config dialog: the browser is probably too old.\n' +
  2591. 'You can edit the script\'s storage directly in your userscript manager.');
  2592. return;
  2593. }
  2594. const RULE = setup.RULE || (setup.RULE = Symbol('rule'));
  2595. let uiCfg;
  2596. let root = (elConfig || 0).shadowRoot;
  2597. let {blankRuleElement} = setup;
  2598. /** @type NodeList */
  2599. const UI = new Proxy({}, {
  2600. get(_, id) {
  2601. return root.getElementById(id);
  2602. },
  2603. });
  2604. if (!rule || !elConfig)
  2605. init(new Config({save: true}));
  2606. if (rule)
  2607. installRule(rule);
  2608.  
  2609. function init(data) {
  2610. uiCfg = data;
  2611. $remove(elConfig);
  2612. elConfig = $create('div', {contentEditable: true});
  2613. root = elConfig.attachShadow({mode: 'open'});
  2614. root.innerHTML = createConfigHtml();
  2615. initEvents();
  2616. renderAll();
  2617. renderCustomScales();
  2618. renderRules();
  2619. doc.body.appendChild(elConfig);
  2620. requestAnimationFrame(() => {
  2621. UI.css.style.minHeight = clamp(UI.css.scrollHeight, 40, elConfig.clientHeight / 4) + 'px';
  2622. });
  2623. }
  2624.  
  2625. function initEvents() {
  2626. UI._apply.onclick = UI._cancel.onclick = UI._ok.onclick = UI._x.onclick = closeSetup;
  2627. UI._export.onclick = e => {
  2628. dropEvent(e);
  2629. GM_setClipboard(Util.stringify(collectConfig(), null, ' '));
  2630. UI._exportNotification.hidden = false;
  2631. setTimeout(() => (UI._exportNotification.hidden = true), 1000);
  2632. };
  2633. UI._import.onclick = e => {
  2634. dropEvent(e);
  2635. const s = prompt('Paste settings:');
  2636. if (s)
  2637. init(new Config({data: s}));
  2638. };
  2639. UI._install.onclick = setupRuleInstaller;
  2640. const /** @type {HTMLTextAreaElement} */ cssApp = UI._cssApp;
  2641. UI._reveal.onclick = e => {
  2642. e.preventDefault();
  2643. cssApp.hidden = !cssApp.hidden;
  2644. if (!cssApp.hidden) {
  2645. if (!cssApp.value) {
  2646. App.updateStyles();
  2647. cssApp.value = App.globalStyle.trim();
  2648. cssApp.setSelectionRange(0, 0);
  2649. }
  2650. cssApp.focus();
  2651. }
  2652. };
  2653. UI.start.onchange = function () {
  2654. UI.delay.closest('label').hidden =
  2655. UI.preload.closest('label').hidden =
  2656. this.value !== 'auto';
  2657. };
  2658. UI.start.onchange();
  2659. UI.xhr.onclick = ({target: el}) => el.checked || confirm($propUp(el, 'title'));
  2660. // color
  2661. for (const el of $$('[type="color"]', root)) {
  2662. el.oninput = colorOnInput;
  2663. el.elSwatch = el.nextElementSibling;
  2664. el.elOpacity = UI[el.id.replace('Color', 'Opacity')];
  2665. el.elOpacity.elColor = el;
  2666. }
  2667. function colorOnInput() {
  2668. this.elSwatch.style.setProperty('--color',
  2669. Util.color(this.value, this.elOpacity.valueAsNumber));
  2670. }
  2671. // range
  2672. for (const el of $$('[type="range"]', root)) {
  2673. el.oninput = rangeOnInput;
  2674. el.onblur = rangeOnBlur;
  2675. el.addEventListener('focusin', rangeOnFocus);
  2676. }
  2677. function rangeOnBlur(e) {
  2678. if (this.elEdit && e.relatedTarget !== this.elEdit)
  2679. this.elEdit.onblur(e);
  2680. }
  2681. function rangeOnFocus() {
  2682. if (this.elEdit) return;
  2683. const {min, max, step, value} = this;
  2684. this.elEdit = $create('input', {
  2685. value, min, max, step,
  2686. className: 'range-edit',
  2687. style: `left: ${this.offsetLeft}px; margin-top: ${this.offsetHeight + 1}px`,
  2688. type: 'number',
  2689. elRange: this,
  2690. onblur: rangeEditOnBlur,
  2691. oninput: rangeEditOnInput,
  2692. });
  2693. this.insertAdjacentElement('afterend', this.elEdit);
  2694. }
  2695. function rangeOnInput() {
  2696. this.title = (this.dataset.title || '').replace('$', this.value);
  2697. if (this.elColor) this.elColor.oninput();
  2698. if (this.elEdit) this.elEdit.valueAsNumber = this.valueAsNumber;
  2699. }
  2700. // range-edit
  2701. function rangeEditOnBlur(e) {
  2702. if (e.relatedTarget !== this.elRange) {
  2703. this.remove();
  2704. this.elRange.elEdit = null;
  2705. }
  2706. }
  2707. function rangeEditOnInput() {
  2708. this.elRange.valueAsNumber = this.valueAsNumber;
  2709. this.elRange.oninput();
  2710. }
  2711. // prevent the main page from interpreting key presses in inputs as hotkeys
  2712. // which may happen since it sees only the outer <div> in the event |target|
  2713. root.addEventListener('keydown', e => !e.altKey && !e.metaKey && e.stopPropagation(), true);
  2714. }
  2715.  
  2716. function closeSetup(event) {
  2717. const isApply = this.id === '_apply';
  2718. if (event && (this.id === '_ok' || isApply)) {
  2719. cfg = uiCfg = collectConfig({save: true, clone: isApply});
  2720. Ruler.init();
  2721. if (isApply) {
  2722. renderCustomScales();
  2723. UI._css.textContent = cfg._getCss();
  2724. return;
  2725. }
  2726. }
  2727. $remove(elConfig);
  2728. elConfig = null;
  2729. }
  2730.  
  2731. function collectConfig({save, clone} = {}) {
  2732. let data = {};
  2733. for (const el of $$('input[id], select[id]', root))
  2734. data[el.id] = el.type === 'checkbox' ? el.checked :
  2735. (el.type === 'number' || el.type === 'range') ? el.valueAsNumber :
  2736. el.value || '';
  2737. Object.assign(data, {
  2738. css: UI.css.value.trim(),
  2739. delay: UI.delay.valueAsNumber * 1000,
  2740. hosts: collectRules(),
  2741. scale: clamp(UI.scale.valueAsNumber / 100, 0, 1) + 1,
  2742. scales: UI.scales.value
  2743. .trim()
  2744. .split(/[,;]*\s+/)
  2745. .map(x => x.replace(',', '.'))
  2746. .filter(x => !isNaN(parseFloat(x))),
  2747. });
  2748. if (clone)
  2749. data = JSON.parse(Util.stringify(data));
  2750. return new Config({data, save});
  2751. }
  2752.  
  2753. function collectRules() {
  2754. return [...UI._rules.children]
  2755. .map(el => [el.value.trim(), el[RULE]])
  2756. .sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
  2757. .map(([s, json]) => json || s)
  2758. .filter(Boolean);
  2759. }
  2760.  
  2761. function checkRule({target: el}) {
  2762. let json, error, title;
  2763. const prev = el.previousElementSibling;
  2764. if (el.value) {
  2765. json = Ruler.parse(el.value);
  2766. error = json instanceof Error && (json.message || String(json));
  2767. const invalidDomain = !error && json && typeof json.d === 'string' &&
  2768. !/^[-.a-z0-9]*$/i.test(json.d);
  2769. title = [invalidDomain && 'Disabled due to invalid characters in "d"', error]
  2770. .filter(Boolean).join('\n');
  2771. el.classList.toggle('invalid-domain', invalidDomain);
  2772. el.classList.toggle('matching-domain', !!json.d && hostname.includes(json.d));
  2773. if (!prev)
  2774. el.insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  2775. } else if (prev) {
  2776. prev.focus();
  2777. el.remove();
  2778. }
  2779. el[RULE] = !error && json;
  2780. el.title = title;
  2781. el.setCustomValidity(error || '');
  2782. }
  2783.  
  2784. function focusRule({type, target: el, relatedTarget: from}) {
  2785. if (el === this)
  2786. return;
  2787. if (type === 'paste') {
  2788. setTimeout(() => focusRule.call(this, {target: el}));
  2789. return;
  2790. }
  2791. if (el[RULE])
  2792. el.value = Ruler.format(el[RULE], {expand: true});
  2793. const h = clamp(el.scrollHeight, 15, elConfig.clientHeight / 4);
  2794. if (h > el.offsetHeight)
  2795. el.style.minHeight = h + 'px';
  2796. if (!this.contains(from))
  2797. from = [...$$('[style*="height"]', this)].find(_ => _ !== el);
  2798. if (from) {
  2799. from.style.minHeight = '';
  2800. if (from[RULE])
  2801. from.value = Ruler.format(from[RULE]);
  2802. }
  2803. }
  2804.  
  2805. function installRule(rule) {
  2806. const inputs = UI._rules.children;
  2807. let el = [...inputs].find(el => Util.deepEqual(el[RULE], rule));
  2808. if (!el) {
  2809. el = inputs[0];
  2810. el[RULE] = rule;
  2811. el.value = Ruler.format(rule);
  2812. el.hidden = false;
  2813. const i = Math.max(0, collectRules().indexOf(rule));
  2814. inputs[i].insertAdjacentElement('afterend', el);
  2815. inputs[0].insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  2816. }
  2817. const rect = el.getBoundingClientRect();
  2818. if (rect.bottom < 0 ||
  2819. rect.bottom > el.parentNode.offsetHeight)
  2820. el.scrollIntoView();
  2821. el.classList.add('highlight');
  2822. el.addEventListener('animationend', () => el.classList.remove('highlight'), {once: true});
  2823. el.focus();
  2824. }
  2825.  
  2826. function renderRules() {
  2827. const rules = UI._rules;
  2828. rules.addEventListener('input', checkRule);
  2829. rules.addEventListener('focusin', focusRule);
  2830. rules.addEventListener('paste', focusRule);
  2831. blankRuleElement =
  2832. setup.blankRuleElement =
  2833. setup.blankRuleElement || rules.firstElementChild.cloneNode();
  2834. for (const rule of uiCfg.hosts || []) {
  2835. const el = blankRuleElement.cloneNode();
  2836. el.value = typeof rule === 'string' ? rule : Ruler.format(rule);
  2837. rules.appendChild(el);
  2838. checkRule({target: el});
  2839. }
  2840. const search = UI._search;
  2841. search.oninput = () => {
  2842. setup.search = search.value;
  2843. const s = search.value.toLowerCase();
  2844. for (const el of rules.children)
  2845. el.hidden = s && !el.value.toLowerCase().includes(s);
  2846. };
  2847. search.value = setup.search || '';
  2848. if (search.value)
  2849. search.oninput();
  2850. }
  2851.  
  2852. function renderCustomScales() {
  2853. UI.scales.value = uiCfg.scales.join(' ').trim() || Config.DEFAULTS.scales.join(' ');
  2854. }
  2855.  
  2856. function renderAll() {
  2857. for (const el of $$('input[id], select[id], textarea[id]', root))
  2858. if (el.id in uiCfg)
  2859. el[el.type === 'checkbox' ? 'checked' : 'value'] = uiCfg[el.id];
  2860. for (const el of $$('input[type="range"]', root))
  2861. el.oninput();
  2862. for (const el of $$('a[href^="http"]', root))
  2863. Object.assign(el, {target: '_blank', rel: 'noreferrer noopener external'});
  2864. UI.delay.valueAsNumber = uiCfg.delay / 1000;
  2865. UI.scale.valueAsNumber = Math.round(clamp(uiCfg.scale - 1, 0, 1) * 100);
  2866. }
  2867. }
  2868.  
  2869. function setupClickedRule(event) {
  2870. let rule;
  2871. const el = event.target.closest('blockquote, code, pre');
  2872. if (el && !event.button && !eventModifiers(event) && (rule = Ruler.fromElement(el))) {
  2873. dropEvent(event);
  2874. setup({rule});
  2875. }
  2876. }
  2877.  
  2878. async function setupRuleInstaller(e) {
  2879. dropEvent(e);
  2880. const parent = this.parentElement;
  2881. parent.children._installLoading.hidden = false;
  2882. this.remove();
  2883. let rules;
  2884.  
  2885. try {
  2886. rules = extractRules(await Remoting.getDoc(this.href));
  2887. const selector = $create('select', {
  2888. size: 8,
  2889. style: 'width: 100%',
  2890. ondblclick: e => e.target !== selector && maybeSetup(e),
  2891. onkeyup: e => e.key === 'Enter' && maybeSetup(e),
  2892. });
  2893. selector.append(...rules.map(renderRule));
  2894. selector.selectedIndex = findMatchingRuleIndex();
  2895. parent.children._installLoading.remove();
  2896. parent.children._installHint.hidden = false;
  2897. parent.appendChild(selector);
  2898. requestAnimationFrame(() => {
  2899. const optY = selector.selectedOptions[0].offsetTop - selector.offsetTop;
  2900. selector.scrollTo(0, optY - selector.offsetHeight / 2);
  2901. selector.focus();
  2902. });
  2903. } catch (e) {
  2904. parent.textContent = 'Error loading rules: ' + (e.message || e);
  2905. }
  2906.  
  2907. function extractRules({doc}) {
  2908. // sort by name
  2909. return [...$$('#wiki-body tr', doc)]
  2910. .map(tr => [
  2911. tr.cells[0].textContent.trim(),
  2912. Ruler.fromElement(tr.cells[1]),
  2913. ])
  2914. .filter(([name, r]) =>
  2915. name && r && (!r.d || hostname.includes(r.d)))
  2916. .sort(([a], [b]) =>
  2917. (a = a.toLowerCase()) < (b = b.toLowerCase()) ? -1 :
  2918. a > b ? 1 :
  2919. 0);
  2920. }
  2921.  
  2922. function findMatchingRuleIndex() {
  2923. const dottedHost = `.${hostname}.`;
  2924. let maxCount = 0, maxIndex = 0, index = 0;
  2925. for (const [name, {d}] of rules) {
  2926. let count = !!(d && hostname.includes(d)) * 10;
  2927. for (const part of name.toLowerCase().split(/[^a-z\d.-]+/i))
  2928. count += dottedHost.includes(`.${part}.`) && part.length;
  2929. if (count > maxCount) {
  2930. maxCount = count;
  2931. maxIndex = index;
  2932. }
  2933. index++;
  2934. }
  2935. return maxIndex;
  2936. }
  2937.  
  2938. function renderRule([name, rule]) {
  2939. return $create('option', {
  2940. textContent: name,
  2941. title: Ruler.format(rule, {expand: true})
  2942. .replace(/^{|\s*}$/g, '')
  2943. .split('\n')
  2944. .slice(0, 12)
  2945. .map(renderTitleLine)
  2946. .filter(Boolean)
  2947. .join('\n'),
  2948. });
  2949. }
  2950.  
  2951. function renderTitleLine(line, i, arr) {
  2952. return (
  2953. // show ... on 10th line if there are more lines
  2954. i === 9 && arr.length > 10 ? '...' :
  2955. i > 10 ? '' :
  2956. // truncate to 100 chars
  2957. (line.length > 100 ? line.slice(0, 100) + '...' : line)
  2958. // strip the leading space
  2959. .replace(/^\s/, ''));
  2960. }
  2961.  
  2962. function maybeSetup(e) {
  2963. if (!eventModifiers(e))
  2964. setup({rule: rules[e.currentTarget.selectedIndex][1]});
  2965. }
  2966. }
  2967.  
  2968. function createConfigHtml() {
  2969. const MPIV_BASE_URL = 'https://github.com/tophf/mpiv/wiki/Rules';
  2970. const scalesHint = 'Leave it empty and click Apply or OK to restore the default values.';
  2971. const trimLeft = s => s.trim().replace(/\n\s+/g, '\r');
  2972. return flattenHtml(`
  2973. <style>
  2974. :host {
  2975. all: initial !important;
  2976. position: fixed !important;
  2977. z-index: 2147483647 !important;
  2978. top: 20px !important;
  2979. right: 20px !important;
  2980. padding: 1.5em !important;
  2981. color: #000 !important;
  2982. background: #eee !important;
  2983. box-shadow: 5px 5px 25px 2px #000 !important;
  2984. width: 32em !important;
  2985. border: 1px solid black !important;
  2986. display: flex !important;
  2987. flex-direction: column !important;
  2988. }
  2989. main {
  2990. font: 12px/15px sans-serif;
  2991. }
  2992. ul {
  2993. max-height: calc(100vh - 200px);
  2994. margin: 10px 0 15px 0;
  2995. padding: 0;
  2996. list-style: none;
  2997. }
  2998. li {
  2999. margin: 0;
  3000. padding: .25em 0;
  3001. }
  3002. li.options {
  3003. display: flex;
  3004. align-items: center;
  3005. justify-content: space-between;
  3006. }
  3007. li.row {
  3008. flex-wrap: wrap;
  3009. justify-content: flex-start;
  3010. }
  3011. li.row label {
  3012. flex-direction: row;
  3013. align-items: center;
  3014. }
  3015. li.row input {
  3016. margin-right: .25em;
  3017. }
  3018. li.stretch label {
  3019. flex: 1;
  3020. white-space: nowrap;
  3021. }
  3022. li.stretch label > span {
  3023. display: flex;
  3024. flex-direction: row;
  3025. flex: 1;
  3026. }
  3027. label {
  3028. display: inline-flex;
  3029. flex-direction: column;
  3030. }
  3031. label:not(:last-child) {
  3032. margin-right: 1em;
  3033. }
  3034. input, select {
  3035. min-height: 1.6em;
  3036. box-sizing: border-box;
  3037. }
  3038. input[type=checkbox] {
  3039. margin-left: 0;
  3040. }
  3041. input[type=number] {
  3042. width: 4em;
  3043. }
  3044. input:not([type=checkbox]) {
  3045. padding: 0 .25em;
  3046. }
  3047. input[type=range] {
  3048. flex: 1;
  3049. width: 100%;
  3050. margin: 0 .25em;
  3051. padding: 0;
  3052. filter: saturate(0);
  3053. opacity: .5;
  3054. }
  3055. u + input[type=range] {
  3056. max-width: 3em;
  3057. }
  3058. input[type=range]:hover {
  3059. filter: none;
  3060. opacity: 1;
  3061. }
  3062. input[type=color] {
  3063. position: absolute;
  3064. width: calc(1.5em + 2px);
  3065. opacity: 0;
  3066. cursor: pointer;
  3067. }
  3068. u {
  3069. display: inline-block;
  3070. position: relative;
  3071. width: 1.5em;
  3072. height: 1.5em;
  3073. border: 1px solid #888;
  3074. pointer-events: none;
  3075. color: #888;
  3076. background-image:
  3077. linear-gradient(45deg, currentColor 25%, transparent 25%, transparent 75%, currentColor 75%),
  3078. linear-gradient(45deg, currentColor 25%, transparent 25%, transparent 75%, currentColor 75%);
  3079. background-size: .5em .5em;
  3080. background-position: 0 0, .25em .25em;
  3081. }
  3082. u::after {
  3083. position: absolute;
  3084. top: 0;
  3085. left: 0;
  3086. right: 0;
  3087. bottom: 0;
  3088. content: "";
  3089. background-color: var(--color);
  3090. }
  3091. .range-edit {
  3092. position: absolute;
  3093. box-shadow: 0 0.25em 1em #000;
  3094. z-index: 99;
  3095. }
  3096. #_rules input,
  3097. textarea {
  3098. flex: 1;
  3099. resize: vertical;
  3100. margin: 1px 0;
  3101. font: 11px/1.25 Consolas, monospace;
  3102. }
  3103. :invalid {
  3104. background-color: #f002;
  3105. border-color: #800;
  3106. }
  3107. code {
  3108. font-weight: bold;
  3109. }
  3110. a {
  3111. text-decoration: none;
  3112. }
  3113. a:hover {
  3114. text-decoration: underline;
  3115. }
  3116. button {
  3117. padding: .2em 1em;
  3118. margin: 0 1em;
  3119. }
  3120. kbd {
  3121. padding: 1px 6px;
  3122. font-weight: bold;
  3123. font-family: Consolas, monospace;
  3124. border: 1px solid #888;
  3125. border-radius: 3px;
  3126. box-shadow: inset 1px 1px 5px #8888, .25px .5px 2px #0008;
  3127. }
  3128. .column {
  3129. display: flex;
  3130. flex-direction: column;
  3131. }
  3132. .highlight {
  3133. animation: 2s fade-in cubic-bezier(0, .75, .25, 1);
  3134. animation-fill-mode: both;
  3135. }
  3136. #_rules > * {
  3137. word-break: break-all;
  3138. }
  3139. #_rules > :not(:focus) {
  3140. overflow: hidden; /* prevents wrapping in FF */
  3141. }
  3142. .invalid-domain {
  3143. opacity: .5;
  3144. }
  3145. .matching-domain {
  3146. border-color: #56b8ff;
  3147. background: #d7eaff;
  3148. }
  3149. #_x {
  3150. position: absolute;
  3151. top: 0;
  3152. right: 0;
  3153. padding: 4px 8px;
  3154. cursor: pointer;
  3155. user-select: none;
  3156. }
  3157. #_x:hover {
  3158. background-color: #8884;
  3159. }
  3160. #_cssApp {
  3161. color: seagreen;
  3162. }
  3163. #_exportNotification {
  3164. color: green;
  3165. font-weight: bold;
  3166. position: absolute;
  3167. left: 0;
  3168. right: 0;
  3169. bottom: 2px;
  3170. }
  3171. #_installHint {
  3172. color: green;
  3173. }
  3174. @keyframes fade-in {
  3175. from { background-color: deepskyblue }
  3176. to {}
  3177. }
  3178. @media (prefers-color-scheme: dark) {
  3179. :host {
  3180. color: #aaa !important;
  3181. background: #333 !important;
  3182. }
  3183. a {
  3184. color: deepskyblue;
  3185. }
  3186. button {
  3187. background: linear-gradient(-5deg, #333, #555);
  3188. border: 1px solid #000;
  3189. box-shadow: 0 2px 6px #181818;
  3190. border-radius: 3px;
  3191. cursor: pointer;
  3192. }
  3193. button:hover {
  3194. background: linear-gradient(-5deg, #333, #666);
  3195. }
  3196. textarea, input, select {
  3197. background: #111;
  3198. color: #BBB;
  3199. border: 1px solid #555;
  3200. }
  3201. input[type=checkbox] {
  3202. filter: invert(1);
  3203. }
  3204. input[type=range] {
  3205. filter: invert(1) saturate(0);
  3206. }
  3207. input[type=range]:hover {
  3208. filter: invert(1);
  3209. }
  3210. kbd {
  3211. border-color: #666;
  3212. }
  3213. @supports (-moz-appearance: none) {
  3214. input[type=checkbox],
  3215. input[type=range],
  3216. input[type=range]:hover {
  3217. filter: none;
  3218. }
  3219. }
  3220. .range-edit {
  3221. box-shadow: 0 .5em 1em .5em #000;
  3222. }
  3223. .matching-domain {
  3224. border-color: #0065af;
  3225. background: #032b58;
  3226. color: #ddd;
  3227. }
  3228. #_cssApp {
  3229. color: darkseagreen;
  3230. }
  3231. #_installHint {
  3232. color: greenyellow;
  3233. }
  3234. ::-webkit-scrollbar {
  3235. width: 14px;
  3236. height: 14px;
  3237. background: #333;
  3238. }
  3239. ::-webkit-scrollbar-button:single-button {
  3240. background: radial-gradient(circle at center, #555 40%, #333 40%)
  3241. }
  3242. ::-webkit-scrollbar-track-piece {
  3243. background: #444;
  3244. border: 4px solid #333;
  3245. border-radius: 8px;
  3246. }
  3247. ::-webkit-scrollbar-thumb {
  3248. border: 3px solid #333;
  3249. border-radius: 8px;
  3250. background: #666;
  3251. }
  3252. ::-webkit-resizer {
  3253. background: #111 linear-gradient(-45deg, transparent 3px, #888 3px, #888 4px, transparent 4px, transparent 6px, #888 6px, #888 7px, transparent 7px) no-repeat;
  3254. border: 2px solid transparent;
  3255. }
  3256. }
  3257. </style>
  3258. <style id="_css">${cfg._getCss()}</style>
  3259. <main id="${PREFIX}setup">
  3260. <div id=_x>x</div>
  3261. <ul class=column>
  3262. <details style="margin: -2em 0 1em">
  3263. <summary style="cursor:pointer"><b>Click to view help & hotkeys</b></summary>
  3264. <table style="text-align:left">
  3265. <tr><th>Activate</th><td>move mouse cursor over thumbnail</td></tr>
  3266. <tr><th>Deactivate</th><td>move cursor off thumbnail, or click, or zoom out fully</td></tr>
  3267. <tr><th>Prevent/freeze</th><td>hold down <kbd>Shift</kbd> while entering/leaving thumbnail</td></tr>
  3268. <tr><th>Force-activate<br>(for small pics)</th>
  3269. <td>hold <kbd>Ctrl</kbd> while entering image element</td></tr>
  3270. <tr><td>&nbsp;</td></tr>
  3271. <tr><th>Start zooming</th>
  3272. <td>configurable: automatic or via right-click / <kbd>Shift</kbd> while popup is visible</td></tr>
  3273. <tr><th>Zoom</th><td>mouse wheel</td></tr>
  3274. <tr><th>Rotate</th><td><kbd>L</kbd> <kbd>r</kbd> keys (left or right)</td></tr>
  3275. <tr><th>Flip/mirror</th><td><kbd>h</kbd> <kbd>v</kbd> keys (horizontally or vertically)</td></tr>
  3276. <tr><th>Previous/next<br>in album</th>
  3277. <td>mouse wheel, <kbd>j</kbd> <kbd>k</kbd> or <kbd>←</kbd> <kbd>→</kbd> keys</td></tr>
  3278. <tr><td>&nbsp;</td></tr>
  3279. <tr><th>Download</th><td><kbd>d</kbd> key while popup is visible</td></tr>
  3280. <tr><th>Mute/unmute</th><td><kbd>m</kbd> key while popup is visible</td></tr>
  3281. <tr><th>Open in tab</th><td><kbd>t</kbd> key while popup is visible</td></tr>
  3282. </table>
  3283. </details>
  3284. <li class=options>
  3285. <label>Popup shows on
  3286. <select id=start>
  3287. <option value=auto>automatically
  3288. <option value=context>Right click / Ctrl
  3289. <option value=ctrl>Ctrl
  3290. </select>
  3291. </label>
  3292. <label>after, sec<input id=delay type=number min=0.05 max=10 step=0.05 title=seconds></label>
  3293. <label title="(if the full version of the hovered image is ...% larger)">
  3294. if larger, %<input id=scale type=number min=0 max=100 step=1>
  3295. </label>
  3296. <label>Zoom activates on
  3297. <select id=zoom>
  3298. <option value=context>Right click / Shift
  3299. <option value=wheel>Wheel up / Shift
  3300. <option value=shift>Shift
  3301. <option value=auto>automatically
  3302. </select>
  3303. </label>
  3304. <label>...and zooms to
  3305. <select id=fit>
  3306. <option value=all>fit to window
  3307. <option value=large>fit if larger
  3308. <option value=no>100%
  3309. <option value="" title="Use custom scale factors">custom
  3310. </select>
  3311. </label>
  3312. </li>
  3313. <li class=options>
  3314. <label>Zoom step, %<input id=zoomStep type=number min=100 max=400 step=1>
  3315. </label>
  3316. <label>When fully zoomed out:
  3317. <select id=zoomOut>
  3318. <option value=stay>stay in zoom mode
  3319. <option value=auto>stay if still hovered
  3320. <option value=unzoom>undo zoom mode
  3321. <option value=close>close popup
  3322. </select>
  3323. </label>
  3324. <label style="flex: 1" title="${trimLeft(`
  3325. Scale factors to use when zooms to selector is set to custom”.
  3326. 0 = fit to window,
  3327. 0! = same as 0 but also removes smaller values,
  3328. * after a value marks the default zoom factor, for example: 1*
  3329. The popup won't shrink below the image's natural size or window size for bigger mages.
  3330. ${scalesHint}
  3331. `)}">Custom scale factors:
  3332. <input id=scales placeholder="${scalesHint}">
  3333. </label>
  3334. </li>
  3335. <li class="options row">
  3336. <label title="...or try to keep the original link/thumbnail unobscured by the popup">
  3337. <input type=checkbox id=center>Centered*</label>
  3338. <label title="Provides smoother experience but increases network traffic">
  3339. <input type=checkbox id=preload>Preload on hover*</label>
  3340. <label title="...or show a partial image while still loading">
  3341. <input type=checkbox id=waitLoad>Show when fully loaded*</label>
  3342. <label><input type=checkbox id=uiFadein>Fade-in transition</label>
  3343. <label><input type=checkbox id=mute>Mute videos</label>
  3344. <label><input type=checkbox id=imgtab>Run in image tabs</label>
  3345. <label title="Causes slowdowns so don't enable unless you explicitly use it in your custom CSS">
  3346. <input type=checkbox id=globalStatus>Expose status on &lt;html&gt;*</label>
  3347. <label title="Disable only if you spoof the HTTP headers yourself">
  3348. <input type=checkbox id=xhr>Spoof hotlinking*</label>
  3349. </li>
  3350. <li class="options stretch">
  3351. <label>Background
  3352. <span>
  3353. <input id=uiBackgroundColor type=color><u></u>
  3354. <input id=uiBackgroundOpacity type=range min=0 max=100 step=1 data-title="Opacity: $%">
  3355. </span>
  3356. </label>
  3357. <label>Border color, opacity, size
  3358. <span>
  3359. <input id=uiBorderColor type=color><u></u>
  3360. <input id=uiBorderOpacity type=range min=0 max=100 step=1 data-title="Opacity: $%">
  3361. <input id=uiBorder type=range min=0 max=20 step=1 data-title="Border size: $px">
  3362. </span>
  3363. </label>
  3364. <label>Shadow color, opacity, size
  3365. <span>
  3366. <input id=uiShadowColor type=color><u></u>
  3367. <input id=uiShadowOpacity type=range min=0 max=100 step=1 data-title="Opacity: $%">
  3368. <input id=uiShadow type=range min=0 max=100 step=1 data-title="
  3369. ${'Shadow blur radius: $px\n"0" disables the shadow.'}">
  3370. </span>
  3371. </label>
  3372. <label>Padding
  3373. <span><input id=uiPadding type=range min=0 max=100 step=1 data-title="Padding: $px"></span>
  3374. </label>
  3375. <label>Margin
  3376. <span><input id=uiMargin type=range min=0 max=100 step=1 data-title="Margin: $px"></span>
  3377. </label>
  3378. </li>
  3379. <li>
  3380. <a href="${MPIV_BASE_URL}css.html">Custom CSS:</a>&nbsp;
  3381. e.g. <b>#mpiv-popup { animation: none !important }</b>
  3382. <a href="#" id=_reveal style="float: right"
  3383. title="You can copy parts of it to override them in your custom CSS">
  3384. View the built-in CSS</a>
  3385. <div class=column>
  3386. <textarea id=css spellcheck=false></textarea>
  3387. <textarea id=_cssApp spellcheck=false hidden readonly rows=30></textarea>
  3388. </div>
  3389. </li>
  3390. <li style="display: flex; justify-content: space-between;">
  3391. <div><a href="${MPIV_BASE_URL}host_rules.html">Custom host rules:</a></div>
  3392. <div style="white-space: nowrap">
  3393. To disable, put any symbol except <code>a..z 0..9 - .</code><br>
  3394. in "d" value, for example <code>"d": "!foo.com"</code>
  3395. </div>
  3396. <div>
  3397. <input id=_search type=search placeholder=Search style="width: 10em; margin-left: 1em">
  3398. </div>
  3399. </li>
  3400. <li style="margin-left: -3px; margin-right: -3px; overflow-y: auto; padding-left: 3px; padding-right: 3px;">
  3401. <div id=_rules class=column>
  3402. <textarea rows=1 spellcheck=false></textarea>
  3403. </div>
  3404. </li>
  3405. <li>
  3406. <div hidden id=_installLoading>Loading...</div>
  3407. <div hidden id=_installHint>Double-click the rule (or select and press Enter) to add it
  3408. . Click <code>Apply</code> or <code>OK</code> to confirm.</div>
  3409. <a href="${MPIV_BASE_URL}" id=_install>Install rule from repository...</a>
  3410. </li>
  3411. </ul>
  3412. <div style="text-align:center">
  3413. <button id=_ok accesskey=s>OK</button>
  3414. <button id=_apply accesskey=a>Apply</button>
  3415. <button id=_import style="margin-right: 0">Import</button>
  3416. <button id=_export style="margin-left: 0">Export</button>
  3417. <button id=_cancel>Cancel</button>
  3418. <div id=_exportNotification hidden>Copied to clipboard.</div>
  3419. </div>
  3420. </main>`);
  3421. }
  3422.  
  3423. function createGlobalStyle() {
  3424. App.globalStyle = /*language=CSS*/ (String.raw`
  3425. #\mpiv-bar {
  3426. position: fixed;
  3427. z-index: 2147483647;
  3428. top: 0;
  3429. left: 0;
  3430. right: 0;
  3431. opacity: 0;
  3432. transition: opacity 1s ease .25s;
  3433. text-align: center;
  3434. font-family: sans-serif;
  3435. font-size: 15px;
  3436. font-weight: bold;
  3437. background: #0005;
  3438. color: white;
  3439. padding: 4px 10px;
  3440. text-shadow: .5px .5px 2px #000;
  3441. }
  3442. #\mpiv-bar.\mpiv-show {
  3443. opacity: 1;
  3444. }
  3445. #\mpiv-bar[data-zoom]::after {
  3446. content: " (" attr(data-zoom) ")";
  3447. opacity: .8;
  3448. }
  3449. #\mpiv-popup.\mpiv-show {
  3450. display: inline;
  3451. }
  3452. #\mpiv-popup {
  3453. display: none;
  3454. cursor: none;
  3455. ${cfg.uiFadein ? String.raw`
  3456. animation: .2s \mpiv-fadein both;
  3457. transition: box-shadow .25s, background-color .25s;
  3458. ` : ''}
  3459. ${App.popupStyleBase = `
  3460. border: none;
  3461. box-sizing: border-box;
  3462. position: fixed;
  3463. z-index: 2147483647;
  3464. padding: 0;
  3465. margin: 0;
  3466. top: 0;
  3467. left: 0;
  3468. width: auto;
  3469. height: auto;
  3470. transform-origin: center;
  3471. max-width: none;
  3472. max-height: none;
  3473. `}
  3474. }
  3475. #\mpiv-popup.\mpiv-show {
  3476. ${cfg.uiBorder ? `border: ${cfg.uiBorder}px solid ${Util.color('Border')};` : ''}
  3477. ${cfg.uiPadding ? `padding: ${cfg.uiPadding}px;` : ''}
  3478. ${cfg.uiMargin ? `margin: ${cfg.uiMargin}px;` : ''}
  3479. box-shadow: ${cfg.uiShadow ? `2px 4px ${cfg.uiShadow}px 4px transparent` : 'none'};
  3480. }
  3481. #\mpiv-popup.\mpiv-show[loaded] {
  3482. background-color: ${Util.color('Background')};
  3483. ${cfg.uiShadow ? `box-shadow: 2px 4px ${cfg.uiShadow}px 4px ${Util.color('Shadow')};` : ''}
  3484. }
  3485. #\mpiv-popup.\mpiv-zoom-max {
  3486. image-rendering: pixelated;
  3487. }
  3488. #\mpiv-setup {
  3489. }
  3490. @keyframes \mpiv-fadein {
  3491. from {
  3492. opacity: 0;
  3493. border-color: transparent;
  3494. }
  3495. to {
  3496. opacity: 1;
  3497. }
  3498. }
  3499. ` + (cfg.globalStatus ? String.raw`
  3500. :root.\mpiv-loading:not(.\mpiv-preloading) *:hover {
  3501. cursor: progress !important;
  3502. }
  3503. :root.\mpiv-edge #\mpiv-popup {
  3504. cursor: default;
  3505. }
  3506. :root.\mpiv-error *:hover {
  3507. cursor: not-allowed !important;
  3508. }
  3509. :root.\mpiv-ready *:hover,
  3510. :root.\mpiv-large *:hover {
  3511. cursor: zoom-in !important;
  3512. }
  3513. :root.\mpiv-shift *:hover {
  3514. cursor: default !important;
  3515. }
  3516. ` : String.raw`
  3517. [\mpiv-status~="loading"]:not([\mpiv-status~="preloading"]):hover {
  3518. cursor: progress;
  3519. }
  3520. [\mpiv-status~="edge"]:hover {
  3521. cursor: default;
  3522. }
  3523. [\mpiv-status~="error"]:hover {
  3524. cursor: not-allowed;
  3525. }
  3526. [\mpiv-status~="ready"]:hover,
  3527. [\mpiv-status~="large"]:hover {
  3528. cursor: zoom-in;
  3529. }
  3530. [\mpiv-status~="shift"]:hover {
  3531. cursor: default;
  3532. }
  3533. `)).replace(/\\mpiv-status/g, STATUS_ATTR).replace(/\\mpiv-/g, PREFIX);
  3534. App.popupStyleBase = App.popupStyleBase.replace(/;/g, '!important;');
  3535. return App.globalStyle;
  3536. }
  3537.  
  3538. //#region Global utilities
  3539.  
  3540. const clamp = (v, min, max) =>
  3541. v < min ? min : v > max ? max : v;
  3542.  
  3543. const compareNumbers = (a, b) =>
  3544. a - b;
  3545.  
  3546. const flattenHtml = str =>
  3547. str.trim().replace(/\n\s*/g, '');
  3548.  
  3549. const dropEvent = e =>
  3550. (e.preventDefault(), e.stopPropagation());
  3551.  
  3552. const ensureArray = v =>
  3553. Array.isArray(v) ? v : [v];
  3554.  
  3555. /** @param {KeyboardEvent} e */
  3556. const eventModifiers = e =>
  3557. (e.altKey ? '!' : '') +
  3558. (e.ctrlKey ? '^' : '') +
  3559. (e.metaKey ? '#' : '') +
  3560. (e.shiftKey ? '+' : '');
  3561.  
  3562. const now = performance.now.bind(performance);
  3563.  
  3564. const sumProps = (...props) => {
  3565. let sum = 0;
  3566. for (const p of props)
  3567. sum += parseFloat(p) || 0;
  3568. return sum;
  3569. };
  3570.  
  3571. const tryCatch = function (fn, ...args) {
  3572. try {
  3573. return fn.apply(this, args);
  3574. } catch (e) {}
  3575. };
  3576.  
  3577. const $ = (sel, node = doc) =>
  3578. node.querySelector(sel) || false;
  3579.  
  3580. const $$ = (sel, node = doc) =>
  3581. node.querySelectorAll(sel);
  3582.  
  3583. const $create = (tag, props) =>
  3584. Object.assign(doc.createElement(tag), props);
  3585.  
  3586. const $css = (el, props) =>
  3587. Object.entries(props).forEach(([k, v]) =>
  3588. el.style.setProperty(k, v, 'important'));
  3589.  
  3590. const $many = (q, doc) => {
  3591. for (const selector of ensureArray(q)) {
  3592. const el = selector && $(selector, doc);
  3593. if (el)
  3594. return el;
  3595. }
  3596. };
  3597.  
  3598. const $prop = (sel, prop, node = doc) =>
  3599. (node = $(sel, node)) && node[prop] || '';
  3600.  
  3601. const $propUp = (node, prop) =>
  3602. (node = node.closest(`[${prop}]`)) &&
  3603. (prop.startsWith('data-') ? node.getAttribute(prop) : node[prop]) ||
  3604. '';
  3605.  
  3606. const $remove = node =>
  3607. node && node.remove();
  3608.  
  3609. //#endregion
  3610. //#region Init
  3611.  
  3612. cfg = new Config({save: true});
  3613.  
  3614. if (window === top)
  3615. GM_registerMenuCommand('MPIV: configure', setup);
  3616.  
  3617. if (doc.body) App.checkImageTab();
  3618. else doc.addEventListener('DOMContentLoaded', App.checkImageTab, {once: true});
  3619.  
  3620. doc.addEventListener('mouseover', Events.onMouseOver, {passive: true});
  3621. if (['gf.qytechs.cn', 'github.com'].includes(hostname))
  3622. doc.addEventListener('click', setupClickedRule);
  3623. window.addEventListener('message', App.onMessage);
  3624.  
  3625. //#endregion

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址