Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2020-02-11 提交的版本,查看 最新版本

  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 http*
  7. // @connect *
  8.  
  9. // allow rule installer in config dialog https://w9p.co/userscripts/mpiv/more_host_rules.html
  10. // @connect w9p.co
  11.  
  12. // @grant GM_getValue
  13. // @grant GM_setValue
  14. // @grant GM_xmlhttpRequest
  15. // @grant GM_openInTab
  16. // @grant GM_registerMenuCommand
  17.  
  18. // @version 1.0.17
  19. // @author tophf
  20.  
  21. // @original-version 2017.9.29
  22. // @original-author kuehlschrank
  23.  
  24. // @supportURL https://github.com/tophf/mpiv/issues
  25. // @homepage https://w9p.co/userscripts/mpiv/
  26. // @icon https://w9p.co/userscripts/mpiv/icon.png
  27. // ==/UserScript==
  28.  
  29. 'use strict';
  30.  
  31. const doc = document;
  32. const hostname = location.hostname;
  33. const dotDomain = '.' + hostname;
  34. const trustedDomains = ['greasyfork.org', 'w9p.co'];
  35. const isGoogleDomain = /(^|\.)google(\.com?)?(\.\w+)?$/.test(hostname);
  36. const isGoogleImages = isGoogleDomain && /[&?]tbm=isch(&|$)/.test(location.search);
  37.  
  38. const POSTMSG_PREFIX = GM_info.script.name + ':';
  39. const PREFIX = 'mpiv-';
  40. const STATUS_ATTR = `${PREFIX}status`;
  41. const WHEEL_EVENT = 'onwheel' in doc ? 'wheel' : 'mousewheel';
  42. const PASSIVE = {passive: true};
  43. // time for volatile things to settle down meanwhile we postpone action
  44. // examples: loading image from cache, quickly moving mouse over one element to another
  45. const SETTLE_TIME = 50;
  46. // used to detect JS code in host rules
  47. const RX_HAS_CODE = /(^|[^-\w])return[\W\s]/;
  48.  
  49. /** @type mpiv.Config */
  50. let cfg;
  51. /** @type mpiv.AppInfo */
  52. let ai = {rule: {}};
  53.  
  54. const clamp = (v, min, max) => v < min ? min : v > max ? max : v;
  55. const ensureArray = v => Array.isArray(v) ? v : [v];
  56. const safeIncludes = (a, b) => typeof a === 'string' && a.includes(b);
  57. const sumProps = (...props) => props.reduce((sum, v) => sum + (parseFloat(v) || 0), 0);
  58. const tryCatch = function (fn, ...args) {
  59. try {
  60. return fn.apply(this, args);
  61. } catch (e) {}
  62. };
  63. const $ = (s, n = doc) => n.querySelector(s) || 0;
  64. const $$ = (s, n = doc) => n.querySelectorAll(s);
  65. const $create = (tag, props) => Object.assign(document.createElement(tag), props);
  66. const $many = (q, doc) => q && ensureArray(q).reduce((el, sel) => el || $(sel, doc), null);
  67. const $prop = (s, prop, n = doc) => (n.querySelector(s) || 0)[prop] || '';
  68. const dropEvent = e => (e.preventDefault(), e.stopPropagation());
  69.  
  70. class App {
  71.  
  72. static init() {
  73. /** @type mpiv.Config */
  74. Config.DEFAULTS = Object.assign(Object.create(null), {
  75. center: false,
  76. css: '',
  77. delay: 500,
  78. globalStatus: false,
  79. // prefer ' inside rules because " will be displayed as \"
  80. // example: "img[src*='icon']"
  81. hosts: [{
  82. name: 'No popup for YouTube thumbnails',
  83. d: 'www.youtube.com',
  84. e: 'ytd-rich-item-renderer *, ytd-thumbnail *',
  85. s: '',
  86. }, {
  87. name: 'No popup for SVG/PNG icons',
  88. d: '',
  89. e: "img[src*='icon']",
  90. r: '//[^/]+/.*\\bicons?\\b.*\\.(?:png|svg)',
  91. s: '',
  92. }],
  93. imgtab: false,
  94. preload: false,
  95. scale: 1.25,
  96. scales: ['0!', 0.125, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 5, 8, 16],
  97. start: 'auto',
  98. version: 6,
  99. xhr: true,
  100. zoom: 'context',
  101. zoomOut: 'auto',
  102. });
  103. cfg = new Config({save: true});
  104. App.isImageTab = doc.images.length === 1 &&
  105. doc.images[0].parentNode === doc.body &&
  106. !doc.links.length;
  107. App.enabled = cfg.imgtab || !App.isImageTab;
  108.  
  109. GM_registerMenuCommand('MPIV: configure', setup);
  110. doc.addEventListener('mouseover', Events.onMouseOver, PASSIVE);
  111.  
  112. if (isGoogleDomain && doc.getElementById('main'))
  113. doc.getElementById('main').addEventListener('mouseover', Events.onMouseOver, PASSIVE);
  114.  
  115. if (trustedDomains.includes(hostname)) {
  116. doc.addEventListener('click', e => {
  117. const el = e.target.closest('blockquote, code, pre');
  118. const text = el && el.textContent.trim();
  119. let rule;
  120. if (text && e.button === 0 &&
  121. /^\s*{\s*"\w+"\s*:[\s\S]+}\s*$/.test(text) &&
  122. (rule = tryCatch(JSON.parse, text))) {
  123. setup({rule});
  124. dropEvent(e);
  125. }
  126. });
  127. }
  128.  
  129. window.addEventListener('message', App.onMessageParent);
  130. }
  131.  
  132. /** @param {MessageEvent} e */
  133. static onMessageParent(e) {
  134. if (typeof e.data === 'string' && e.data.startsWith(POSTMSG_PREFIX)) {
  135. for (const el of $$('iframe, frame')) {
  136. if (el.contentWindow === e.source) {
  137. const r = el.getBoundingClientRect();
  138. const w = clamp(r.width, 0, innerWidth - r.left);
  139. const h = clamp(r.height, 0, innerHeight - r.top);
  140. e.source.postMessage(`${POSTMSG_PREFIX}${w}:${h}`, '*');
  141. }
  142. }
  143. }
  144. }
  145.  
  146. /** @param {MessageEvent} e */
  147. static onMessageChild(e) {
  148. if (e.source === parent && typeof e.data === 'string' && e.data.startsWith(POSTMSG_PREFIX)) {
  149. const [width, height] = e.data.slice(POSTMSG_PREFIX.length).split(':').map(parseFloat);
  150. if (width && height) {
  151. ai.view = {width, height};
  152. window.removeEventListener('message', App.onMessageChild);
  153. }
  154. }
  155. }
  156.  
  157. static activate(info, event) {
  158. const force = event.ctrlKey;
  159. if (!force) {
  160. const scale = Util.findScale(info.url, info.node.parentNode);
  161. if (scale && scale < cfg.scale)
  162. return;
  163. }
  164. if (ai.node)
  165. App.deactivate();
  166. ai = info;
  167. const view = doc.compatMode === 'BackCompat' ? doc.body : doc.documentElement;
  168. ai.view = {
  169. width: view.clientWidth,
  170. height: view.clientHeight,
  171. };
  172. if (window !== top) {
  173. window.addEventListener('message', App.onMessageChild);
  174. parent.postMessage(POSTMSG_PREFIX + 'getDimensions', '*');
  175. }
  176. ai.zooming = cfg.css.includes(`${PREFIX}zooming`);
  177. Util.suppressHoverTooltip();
  178. App.setListeners();
  179. App.updateMouse(event);
  180. if (force) {
  181. Popup.start();
  182. } else if (cfg.start === 'auto' && !ai.rule.manual) {
  183. Popup.schedule();
  184. } else {
  185. App.setStatus('ready');
  186. }
  187. }
  188.  
  189. static checkProgress({start} = {}) {
  190. const p = ai.popup;
  191. if (p) {
  192. ai.nheight = p.naturalHeight || p.videoHeight || ai.popupLoaded && 800;
  193. ai.nwidth = p.naturalWidth || p.videoWidth || ai.popupLoaded && 1200;
  194. if (ai.nheight)
  195. return App.updateProgress();
  196. }
  197. if (start)
  198. ai.timerProgress = setInterval(App.checkProgress, 150);
  199. }
  200.  
  201. static deactivate({wait} = {}) {
  202. App.stopTimers();
  203. if (ai.req)
  204. tryCatch.call(ai.req, ai.req.abort);
  205. if (ai.tooltip)
  206. ai.tooltip.node.title = ai.tooltip.text;
  207. App.setStatus(false);
  208. App.setBar(false);
  209. App.setListeners(false);
  210. Popup.destroy();
  211. if (wait) {
  212. App.enabled = false;
  213. setTimeout(App.enable, 200);
  214. }
  215. ai = {rule: {}};
  216. }
  217.  
  218. static enable() {
  219. App.enabled = true;
  220. }
  221.  
  222. static handleError(e, rule = ai.rule) {
  223. const fe = Util.formatError(e, rule);
  224. if (!rule || !ai.urls || !ai.urls.length)
  225. console.warn(fe.consoleFormat, ...fe.consoleArgs);
  226. if (cfg.xhr && !ai.xhr && isGoogleImages) {
  227. ai.xhr = true;
  228. Popup.startSingle();
  229. } else if (ai.urls && ai.urls.length) {
  230. ai.url = ai.urls.shift();
  231. if (ai.url) {
  232. App.stopTimers();
  233. Popup.startSingle();
  234. } else {
  235. App.deactivate();
  236. }
  237. } else if (ai.node) {
  238. App.setStatus('error');
  239. App.setBar(fe.message, 'error');
  240. }
  241. }
  242.  
  243. static setBar(label, className) {
  244. let b = ai.bar;
  245. if (typeof label !== 'string') {
  246. b && b.remove();
  247. ai.bar = null;
  248. return;
  249. }
  250. if (!b)
  251. b = ai.bar = $create('div', {id: `${PREFIX}bar`});
  252. App.updateStyles();
  253. App.updateTitle();
  254. App.updateBar();
  255. b.innerHTML = label;
  256. if (!b.parentNode) {
  257. doc.body.appendChild(b);
  258. Util.forceLayout(b);
  259. }
  260. b.className = `${PREFIX}show ${PREFIX}${className}`;
  261. }
  262.  
  263. static setListeners(enable = true) {
  264. const onOff = enable ? doc.addEventListener : doc.removeEventListener;
  265. const passive = enable ? PASSIVE : undefined;
  266. onOff.call(doc, 'mousemove', Events.onMouseMove, passive);
  267. onOff.call(doc, 'mouseout', Events.onMouseOut, passive);
  268. onOff.call(doc, 'mousedown', Events.onMouseDown, passive);
  269. onOff.call(doc, 'contextmenu', Events.onContext);
  270. onOff.call(doc, 'keydown', Events.onKeyDown);
  271. onOff.call(doc, 'keyup', Events.onKeyUp);
  272. onOff.call(doc, WHEEL_EVENT, Events.onMouseScroll, enable ? {passive: false} : undefined);
  273. }
  274.  
  275. static setStatus(status) {
  276. if (!status && !cfg.globalStatus)
  277. return ai.node && ai.node.removeAttribute(STATUS_ATTR);
  278. const prefix = cfg.globalStatus ? PREFIX : '';
  279. const action = status && /^[+-]/.test(status) && status[0];
  280. const name = status && `${prefix}${action ? status.slice(1) : status}`;
  281. const el = cfg.globalStatus ? doc.documentElement :
  282. name === 'edge' ? ai.popup :
  283. ai.node;
  284. if (!el)
  285. return;
  286. const attr = cfg.globalStatus ? 'class' : STATUS_ATTR;
  287. const oldValue = (el.getAttribute(attr) || '').trim();
  288. const cls = new Set(oldValue ? oldValue.split(/\s+/) : []);
  289. switch (action) {
  290. case '-':
  291. cls.delete(name);
  292. break;
  293. case false:
  294. for (const c of cls)
  295. if (c.startsWith(prefix) && c !== name)
  296. cls.delete(c);
  297. // fallthrough to +
  298. case '+':
  299. if (name)
  300. cls.add(name);
  301. break;
  302. }
  303. const newValue = [...cls].join(' ');
  304. if (newValue !== oldValue)
  305. el.setAttribute(attr, newValue);
  306. }
  307.  
  308. static setStatusLoading(force) {
  309. if (!force) {
  310. clearTimeout(ai.timerStatus);
  311. ai.timerStatus = setTimeout(App.setStatusLoading, SETTLE_TIME, true);
  312. } else if (!ai.popupLoaded) {
  313. App.setStatus('+loading');
  314. }
  315. }
  316.  
  317. static stopTimers() {
  318. clearTimeout(ai.timer);
  319. clearTimeout(ai.timerStatus);
  320. clearInterval(ai.timerProgress);
  321. }
  322.  
  323. static toggleZoom() {
  324. const p = ai.popup;
  325. if (!p || !ai.scales || ai.scales.length < 2)
  326. return;
  327. ai.zoom = !ai.zoom;
  328. ai.zoomed = true;
  329. const z = ai.scales.indexOf(ai.zscale);
  330. ai.scale = ai.scales[ai.zoom ? (z > 0 ? z : 1) : 0];
  331. if (ai.zooming)
  332. p.classList.add(`${PREFIX}zooming`);
  333. Popup.move();
  334. App.updateTitle();
  335. App.setStatus(ai.zoom ? 'zoom' : false);
  336. if (!ai.zoom)
  337. App.updateFileInfo();
  338. return ai.zoom;
  339. }
  340.  
  341. static updateBar() {
  342. if (ai.timerBar)
  343. return;
  344. clearTimeout(ai.timerBar);
  345. ai.bar.style.removeProperty('opacity');
  346. ai.timerBar = setTimeout(() => {
  347. ai.timerBar = 0;
  348. if (ai.bar)
  349. ai.bar.style.setProperty('opacity', 0);
  350. }, 3000);
  351. }
  352.  
  353. static updateCaption(text, doc = document) {
  354. switch (typeof ai.rule.c) {
  355. case 'function':
  356. // not specifying as a parameter's default value to get the html only when needed
  357. if (text === undefined)
  358. text = doc.documentElement.outerHTML;
  359. ai.caption = ai.rule.c(text, doc, ai.node, ai.rule);
  360. break;
  361. case 'string': {
  362. const el = $many(ai.rule.c, doc);
  363. ai.caption = !el ? '' :
  364. el.getAttribute('content') ||
  365. el.getAttribute('title') ||
  366. el.textContent;
  367. break;
  368. }
  369. default: {
  370. ai.caption = (ai.tooltip || 0).text || ai.node.alt || '';
  371. if (ai.caption)
  372. return;
  373. const el = ai.node.closest('a[title], img[title], video[title]');
  374. if (el && (ai.caption = el.title || ''))
  375. return;
  376. const url = ai.node.src || (ai.node.closest('[href]') || 0).href;
  377. ai.caption = url ? Remoting.getFileName(url) : '';
  378. }
  379. }
  380. }
  381.  
  382. static updateFileInfo() {
  383. const gi = ai.gItems;
  384. if (gi) {
  385. const item = gi[ai.gIndex];
  386. let c = gi.length > 1 ? '[' + (ai.gIndex + 1) + '/' + gi.length + '] ' : '';
  387. if (ai.gIndex === 0 && gi.title && (!item.desc || !safeIncludes(item.desc, gi.title)))
  388. c += gi.title + (item.desc ? ' - ' : '');
  389. if (item.desc)
  390. c += item.desc;
  391. App.setBar(c.trim() || ' ', 'gallery', true);
  392. } else if ('caption' in ai) {
  393. App.setBar(ai.caption, 'caption');
  394. } else if (ai.tooltip) {
  395. App.setBar(ai.tooltip.text, 'tooltip');
  396. } else {
  397. App.setBar(' ', 'info');
  398. }
  399. }
  400.  
  401. static updateMouse(e) {
  402. const cx = ai.clientX = e.clientX;
  403. const cy = ai.clientY = e.clientY;
  404. const r = ai.rect;
  405. if (r)
  406. ai.isOverRect =
  407. cx > r.left - 2 && cx < r.right + 2 &&
  408. cy > r.top - 2 && cy < r.bottom + 2;
  409. }
  410.  
  411. static updateProgress() {
  412. App.stopTimers();
  413. let wait;
  414. if (ai.preloadStart && (wait = ai.preloadStart + cfg.delay - Date.now()) > 0)
  415. return (ai.timer = setTimeout(App.checkProgress, wait));
  416. if ((ai.urls || 0).length && Math.max(ai.nheight, ai.nwidth) < 130) {
  417. App.handleError({type: 'error'});
  418. return;
  419. }
  420. App.setStatus(false);
  421. Util.forceLayout(ai.popup);
  422. ai.popup.className = `${PREFIX}show`;
  423. App.updateSpacing();
  424. App.updateScales();
  425. App.updateTitle();
  426. Popup.move();
  427. if (!ai.bar)
  428. App.updateFileInfo();
  429. ai.large = ai.nwidth > ai.popup.clientWidth + ai.mbw ||
  430. ai.nheight > ai.popup.clientHeight + ai.mbh;
  431. if (ai.large)
  432. App.setStatus('large');
  433. if (cfg.imgtab && App.isImageTab || cfg.zoom === 'auto')
  434. App.toggleZoom();
  435. }
  436.  
  437. static updateScales() {
  438. const scales = cfg.scales.length ? cfg.scales : Config.DEFAULTS.scales.slice();
  439. const fit = Math.min(
  440. (ai.view.width - ai.mbw - ai.outline * 2) / ai.nwidth,
  441. (ai.view.height - ai.mbh - ai.outline * 2) / ai.nheight);
  442. let cutoff = ai.scale = Math.min(1, fit);
  443. ai.scales = [];
  444. for (let i = scales.length; i--;) {
  445. const scale = scales[i];
  446. const val = parseFloat(scale) || fit;
  447. const option = typeof scale === 'string' && scale.slice(-1);
  448. if (option === '!')
  449. cutoff = val;
  450. if (option === '*')
  451. ai.zscale = val;
  452. if (val !== ai.scale)
  453. ai.scales.push(val);
  454. }
  455. ai.scales = ai.scales
  456. .filter(x => x >= cutoff)
  457. .sort((a, b) => a - b);
  458. ai.scales.unshift(ai.scale);
  459. }
  460.  
  461. static updateSpacing() {
  462. const s = getComputedStyle(ai.popup);
  463. ai.outline = sumProps(s.outlineOffset, s.outlineWidth);
  464. ai.pw = sumProps(s.paddingLeft, s.paddingRight);
  465. ai.ph = sumProps(s.paddingTop, s.paddingBottom);
  466. ai.mbw = sumProps(s.marginLeft, s.marginRight, s.borderLeftWidth, s.borderRightWidth);
  467. ai.mbh = sumProps(s.marginTop, s.marginBottom, s.borderTopWidth, s.borderBottomWidth);
  468. }
  469.  
  470. static updateStyles() {
  471. Util.addStyle('global', /*language=CSS*/ App.globalStyle || (App.globalStyle = `
  472. #${PREFIX}bar {
  473. position: fixed;
  474. z-index: 2147483647;
  475. left: 0;
  476. right: 0;
  477. top: 0;
  478. opacity: 0;
  479. transition: opacity 1s ease .25s;
  480. text-align: center;
  481. font-family: sans-serif;
  482. font-size: 15px;
  483. font-weight: bold;
  484. background: #0005;
  485. color: white;
  486. padding: 4px 10px;
  487. text-shadow: .5px .5px 2px #000;
  488. }
  489. #${PREFIX}bar.${PREFIX}show {
  490. opacity: 1;
  491. }
  492. #${PREFIX}bar[data-zoom]::after {
  493. content: " (" attr(data-zoom) ")";
  494. opacity: .8;
  495. }
  496. #${PREFIX}popup.${PREFIX}show {
  497. display: inline;
  498. }
  499. #${PREFIX}popup {
  500. display: none;
  501. border: none;
  502. box-sizing: content-box;
  503. position: fixed;
  504. z-index: 2147483647;
  505. margin: 0;
  506. max-width: none;
  507. max-height: none;
  508. will-change: display, width, height, left, top;
  509. cursor: none;
  510. animation: .2s ${PREFIX}fadein both;
  511. }
  512. #${PREFIX}popup.${PREFIX}show {
  513. box-shadow: 6px 6px 30px transparent;
  514. transition: box-shadow .25s, background-color .25s;
  515. }
  516. #${PREFIX}popup.${PREFIX}show[loaded] {
  517. box-shadow: 6px 6px 30px black;
  518. background-color: white;
  519. }
  520. #${PREFIX}popup.${PREFIX}zoom-max {
  521. image-rendering: pixelated;
  522. }
  523. @keyframes ${PREFIX}fadein {
  524. from { opacity: 0; }
  525. to { opacity: 1; }
  526. }` + (
  527. cfg.globalStatus ? `
  528. .${PREFIX}loading:not(.${PREFIX}preloading) * {
  529. cursor: wait !important;
  530. }
  531. .${PREFIX}edge #${PREFIX}popup {
  532. cursor: default;
  533. }
  534. .${PREFIX}error * {
  535. cursor: not-allowed !important;
  536. }
  537. .${PREFIX}ready *, .${PREFIX}large * {
  538. cursor: zoom-in !important;
  539. }
  540. .${PREFIX}shift * {
  541. cursor: default !important;
  542. }
  543. ` : `
  544. [${STATUS_ATTR}~="loading"]:not([${STATUS_ATTR}~="preloading"]) {
  545. cursor: wait !important;
  546. }
  547. #${PREFIX}popup[${STATUS_ATTR}~="edge"] {
  548. cursor: default !important;
  549. }
  550. [${STATUS_ATTR}~="error"] {
  551. cursor: not-allowed !important;
  552. }
  553. [${STATUS_ATTR}~="ready"],
  554. [${STATUS_ATTR}~="large"] {
  555. cursor: zoom-in !important;
  556. }
  557. [${STATUS_ATTR}~="shift"] {
  558. cursor: default !important;
  559. }
  560. `
  561. ) + (/*language=none*/
  562. cfg.css.includes('{') ? cfg.css : `#${PREFIX}popup {${cfg.css}}`
  563. )));
  564. Util.addStyle('rule', ai.rule.css || '');
  565. }
  566.  
  567. static updateTitle() {
  568. if (!ai.bar)
  569. return;
  570. const zoom = `${
  571. Math.round(ai.scale * 100)
  572. }%, ${
  573. ai.nwidth
  574. } x ${
  575. ai.nheight
  576. } px, ${
  577. Math.round(100 * (ai.nwidth * ai.nheight / 1e6)) / 100
  578. } MP`.replace(/\x20/g, '\xA0');
  579. if (ai.bar.dataset.zoom !== zoom) {
  580. ai.bar.dataset.zoom = zoom;
  581. App.updateBar();
  582. }
  583. }
  584. }
  585.  
  586. class Config {
  587. constructor({data: c = GM_getValue('cfg'), save}) {
  588. if (typeof c === 'string')
  589. c = tryCatch(JSON.parse, c);
  590. if (typeof c !== 'object' || !c)
  591. c = {};
  592. const {DEFAULTS} = Config;
  593. if (c.version !== DEFAULTS.version) {
  594. if (typeof c.hosts === 'string')
  595. c.hosts = c.hosts.split('\n')
  596. .map(s => tryCatch(JSON.parse, s) || s)
  597. .filter(Boolean);
  598. if (c.close === true || c.close === false)
  599. c.zoomOut = c.close ? 'auto' : 'stay';
  600. for (const key in DEFAULTS)
  601. if (typeof c[key] !== typeof DEFAULTS[key])
  602. c[key] = DEFAULTS[key];
  603. if (c.version === 3 && c.scales[0] === 0)
  604. c.scales[0] = '0!';
  605. for (const key in c)
  606. if (!(key in DEFAULTS))
  607. delete c[key];
  608. c.version = DEFAULTS.version;
  609. if (save)
  610. GM_setValue('cfg', JSON.stringify(c));
  611. }
  612. if (cfg && (
  613. cfg.css !== c.css ||
  614. cfg.globalStatus !== c.globalStatus
  615. )) {
  616. App.globalStyle = '';
  617. }
  618. Object.assign(this, c);
  619. }
  620. }
  621.  
  622. class Ruler {
  623. /*
  624. 'u' works only with URLs so it's ignored if 'html' is true
  625. ||some.domain = matches some.domain, anything.some.domain, etc.
  626. |foo = url or text must start with foo
  627. ^ = separator like / or ? or : but not a letter/number, not %._-
  628. when used at the end like "foo^" it additionally matches when the source ends with "foo"
  629. 'r' is checked only if 'u' matches first
  630. */
  631. static init() {
  632. const errors = new Map();
  633. const customRules = (cfg.hosts || []).map(Ruler.parse, errors);
  634. for (const rule of errors.keys())
  635. App.handleError('Invalid custom host rule:', rule);
  636.  
  637. // rules that disable previewing
  638. const disablers = [
  639. dotDomain.endsWith('.stackoverflow.com') && {
  640. e: '.post-tag, .post-tag img',
  641. s: '',
  642. },
  643. {
  644. u: '||disqus.com/',
  645. s: '',
  646. },
  647. ];
  648.  
  649. // optimization: a rule is created only when on domain
  650. const perDomain = [
  651. hostname.includes('startpage') && {
  652. r: /\boiu=(.+)/,
  653. s: '$1',
  654. follow: true,
  655. },
  656. dotDomain.endsWith('.4chan.org') && {
  657. e: '.is_catalog .thread a[href*="/thread/"], .catalog-thread a[href*="/thread/"]',
  658. q: '.op .fileText a',
  659. css: '#post-preview{display:none}',
  660. },
  661. hostname.includes('amazon.') && {
  662. r: /.+?images\/I\/.+?\./,
  663. s: m => {
  664. const uh = doc.getElementById('universal-hover');
  665. return uh ? '' : m[0] + 'jpg';
  666. },
  667. css: '#zoomWindow{display:none!important;}',
  668. },
  669. dotDomain.endsWith('.bing.com') && {
  670. e: 'a[m*="murl"]',
  671. r: /murl&quot;:&quot;(.+?)&quot;/,
  672. s: '$1',
  673. html: true,
  674. },
  675. dotDomain.endsWith('.deviantart.com') && {
  676. e: '[data-super-full-img] *, img[src*="/th/"]',
  677. s: (m, node) => {
  678. let el = node.closest('[data-super-full-img]');
  679. if (el)
  680. return el.dataset.superFullImg;
  681. el = node.dataset.embedId && node.nextElementSibling;
  682. if (el && el.dataset.embedId)
  683. return el.src;
  684. },
  685. },
  686. dotDomain.endsWith('.deviantart.com') && {
  687. e: '.dev-view-deviation img',
  688. s: () => [
  689. $('.dev-page-download').href,
  690. $('.dev-content-full').src,
  691. ].filter(Boolean),
  692. },
  693. dotDomain.endsWith('.deviantart.com') && {
  694. u: ',strp/',
  695. s: '/\\/v1\\/.*//',
  696. },
  697. dotDomain.endsWith('.dropbox.com') && {
  698. r: /(.+?&size_mode)=\d+(.*)/,
  699. s: '$1=5$2',
  700. },
  701. dotDomain.endsWith('.facebook.com') && {
  702. e: 'a[href*="ref=hovercard"]',
  703. s: (m, node) =>
  704. 'https://www.facebook.com/photo.php?fbid=' +
  705. /\/[0-9]+_([0-9]+)_/.exec($('img', node).src)[1],
  706. follow: true,
  707. },
  708. dotDomain.endsWith('.facebook.com') && {
  709. r: /(fbcdn|external).*?(app_full_proxy|safe_image).+?(src|url)=(http.+?)[&"']/,
  710. s: (m, node) =>
  711. node.parentNode.className.includes('video') && m[4].includes('fbcdn') ? '' :
  712. decodeURIComponent(m[4]),
  713. html: true,
  714. follow: true,
  715. },
  716. dotDomain.endsWith('.flickr.com') &&
  717. tryCatch(() => unsafeWindow.YUI_config.flickr.api.site_key) && {
  718. r: /flickr\.com\/photos\/[^/]+\/(\d+)/,
  719. s: m => `https://www.flickr.com/services/rest/?${
  720. new URLSearchParams({
  721. photo_id: m[1],
  722. api_key: unsafeWindow.YUI_config.flickr.api.site_key,
  723. method: 'flickr.photos.getSizes',
  724. format: 'json',
  725. nojsoncallback: 1,
  726. }).toString()}`,
  727. q: text => JSON.parse(text).sizes.size.pop().source,
  728. },
  729. dotDomain.endsWith('.github.com') && {
  730. r: new RegExp([
  731. /(avatars.+?&s=)\d+/,
  732. /(raw\.github)(\.com\/.+?\/img\/.+)$/,
  733. /\/(github)(\.com\/.+?\/)blob\/([^/]+\/.+?\.(?:png|jpe?g|bmp|gif|cur|ico))$/,
  734. ].map(rx => rx.source).join('|')),
  735. s: m => `https://${
  736. m[1] ? `${m[1]}460` :
  737. m[2] ? `${m[2]}usercontent${m[3]}` :
  738. `raw.${m[4]}usercontent${m[5]}${m[6]}`
  739. }`,
  740. },
  741. isGoogleImages && {
  742. e: 'a',
  743. r: /imgres\?imgurl=([^&]+)/,
  744. s: '$1',
  745. },
  746. isGoogleImages && {
  747. e: '[data-tbnid] a',
  748. s: (m, node, rule) => {
  749. const id = node.closest('[data-tbnid]').dataset.tbnid;
  750. for (const {text} of $$('script', doc)) {
  751. let i = text.indexOf(id);
  752. if (i < 0) continue;
  753. i = text.indexOf('[', i + id.length + 9) + 2;
  754. const url = text.slice(i, text.indexOf('"', i + 1));
  755. if (!url.startsWith('http')) continue;
  756. rule.xhr = !url.startsWith(location.protocol);
  757. return url;
  758. }
  759. },
  760. },
  761. dotDomain.endsWith('.instagram.com') && {
  762. e: [
  763. 'a[href*="/p/"]',
  764. 'a[role="button"][data-reactid*="scontent-"]',
  765. 'article div',
  766. 'article div div img',
  767. ],
  768. s: (m, node, rule) => {
  769. const {a, data} = rule._getData(node) || {};
  770. rule.follow = !data;
  771. return (
  772. !a ? false :
  773. !data ? a.href :
  774. data.video_url || data.display_url);
  775. },
  776. c: (html, doc, node, rule) =>
  777. tryCatch(() => rule._getData(node).data.edge_media_to_caption.edges[0].node.text) || '',
  778. follow: true,
  779. _getData(node) {
  780. const n = node.closest('a[href*="/p/"], article');
  781. if (!n)
  782. return;
  783. const a = n.tagName === 'A' ? n : $('a[href*="/p/"]', n);
  784. if (!a)
  785. return;
  786. try {
  787. const shortcode = a.pathname.match(/\/p\/(\w+)/)[1];
  788. return {
  789. a,
  790. data: unsafeWindow._sharedData.entry_data.ProfilePage[0]
  791. .graphql.user.edge_owner_to_timeline_media.edges
  792. .find(e => e.node.shortcode === shortcode)
  793. .node,
  794. };
  795. } catch (e) {
  796. return {a};
  797. }
  798. },
  799. },
  800. dotDomain.endsWith('.reddit.com') && {
  801. u: '||i.reddituploads.com/',
  802. },
  803. dotDomain.endsWith('.reddit.com') && {
  804. r: /(preview\.redd\.it\/\w+\.(jpe?g|png|gif))/,
  805. s: 'https://i.$1',
  806. },
  807. dotDomain.endsWith('.tumblr.com') && {
  808. e: 'div.photo_stage_img, div.photo_stage > canvas',
  809. s: (m, node) => /http[^"]+/.exec(node.style.cssText + node.getAttribute('data-img-src'))[0],
  810. follow: true,
  811. },
  812. dotDomain.endsWith('.tweetdeck.twitter.com') && {
  813. e: 'a.media-item, a.js-media-image-link',
  814. s: (m, node) => /http[^)]+/.exec(node.style.backgroundImage)[0],
  815. follow: true,
  816. },
  817. dotDomain.endsWith('.twitter.com') && {
  818. e: '.grid-tweet > .media-overlay',
  819. s: (m, node) => node.previousElementSibling.src,
  820. follow: true,
  821. },
  822. ];
  823.  
  824. const main = [
  825. {
  826. r: /[/?=](https?[^&]+)/,
  827. s: '$1',
  828. follow: true,
  829. },
  830. {
  831. u: [
  832. '||500px.com/photo/',
  833. '||cl.ly/',
  834. '||cweb-pix.com/',
  835. '||ibb.co/',
  836. '||imgcredit.xyz/image/',
  837. ],
  838. r: /\.\w+\/.+/,
  839. q: 'meta[property="og:image"]',
  840. },
  841. {
  842. u: 'attachment.php',
  843. r: /attachment\.php.+attachmentid/,
  844. },
  845. {
  846. u: '||abload.de/image',
  847. q: '#image',
  848. },
  849. {
  850. u: '||deviantart.com/art/',
  851. s: (m, node) =>
  852. /\b(film|lit)/.test(node.className) || /in Flash/.test(node.title) ?
  853. '' :
  854. m.input,
  855. q: [
  856. '#download-button[href*=".jpg"]',
  857. '#download-button[href*=".jpeg"]',
  858. '#download-button[href*=".gif"]',
  859. '#download-button[href*=".png"]',
  860. '#gmi-ResViewSizer_fullimg',
  861. 'img.dev-content-full',
  862. ],
  863. },
  864. {
  865. u: '||dropbox.com/s',
  866. r: /com\/sh?\/.+\.(jpe?g|gif|png)/i,
  867. q: (text, doc) =>
  868. $prop('img.absolute-center', 'src', doc).replace(/(size_mode)=\d+/, '$1=5') || false,
  869. },
  870. {
  871. r: /[./]ebay\.[^/]+\/itm\//,
  872. q: text =>
  873. text.match(/https?:\/\/i\.ebayimg\.com\/[^.]+\.JPG/i)[0]
  874. .replace(/~~60_\d+/, '~~60_57'),
  875. },
  876. {
  877. u: '||i.ebayimg.com/',
  878. s: (m, node) =>
  879. $('.zoom_trigger_mask', node.parentNode) ? '' :
  880. m.input.replace(/~~60_\d+/, '~~60_57'),
  881. },
  882. {
  883. u: [
  884. '||fastpic.ru/big',
  885. '||fastpic.ru/thumb',
  886. ],
  887. r: /\/\/(?:i(\d+)\.)?([^/]+\/)(big|thumb|view)\/([^.]+?)\.(\w+)/,
  888. s: (m, node, rule) => {
  889. const a = node.closest('[href*="fastpic.ru"]');
  890. const am = a && rule.r.exec(decodeURIComponent(a.href)) || [];
  891. const p = a && am[4].split('/');
  892. return `https://i${am[1] || m[1] || am[3] === 'view' && p[0]}.${m[2]}big/${
  893. am[3] === 'big' ? am[4] : m[4]}.${am[5] || m[5]}?noht=1`;
  894. },
  895. xhr: () => 'https://fastpic.ru',
  896. },
  897. {
  898. u: '||fastpic.ru/view/',
  899. q: 'img[src*="/big/"]',
  900. xhr: true,
  901. },
  902. {
  903. u: '||facebook.com/',
  904. r: /photo\.php|[^/]+\/photos\//,
  905. s: (m, node) =>
  906. node.id === 'fbPhotoImage' ? false :
  907. /gradient\.png$/.test(m.input) ? '' :
  908. m.input.replace('www.facebook.com', 'mbasic.facebook.com'),
  909. q: [
  910. 'div + span > a:first-child:not([href*="tag_faces"])',
  911. 'div + span > a[href*="tag_faces"] ~ a',
  912. ],
  913. rect: '#fbProfileCover',
  914. },
  915. {
  916. u: '||fbcdn.',
  917. r: /fbcdn.+?[0-9]+_([0-9]+)_[0-9]+_[a-z]\.(jpg|png)/,
  918. s: m =>
  919. dotDomain.endsWith('.facebook.com') &&
  920. tryCatch(() => unsafeWindow.PhotoSnowlift.getInstance().stream.cache.image[m[1]].url) ||
  921. false,
  922. manual: true,
  923. },
  924. {
  925. u: ['||fbcdn-', 'fbcdn.net/'],
  926. r: /(https?:\/\/(fbcdn-[-\w.]+akamaihd|[-\w.]+?fbcdn)\.net\/[-\w/.]+?)_[a-z]\.(jpg|png)(\?[0-9a-zA-Z0-9=_&]+)?/,
  927. s: (m, node) => {
  928. if (node.id === 'fbPhotoImage') {
  929. const a = $('a.fbPhotosPhotoActionsItem[href$="dl=1"]', doc.body);
  930. if (a)
  931. return a.href.includes(m.input.match(/[0-9]+_[0-9]+_[0-9]+/)[0]) ? '' : a.href;
  932. }
  933. if (m[4])
  934. return false;
  935. if (node.parentNode.outerHTML.includes('/hovercard/'))
  936. return '';
  937. const gp = node.parentNode.parentNode;
  938. if (node.outerHTML.includes('profile') && gp.href.includes('/photo'))
  939. return false;
  940. return m[1].replace(/\/[spc][\d.x]+/g, '').replace('/v/', '/') + '_n.' + m[3];
  941. },
  942. rect: '.photoWrap',
  943. },
  944. {
  945. u: '||flickr.com/photos/',
  946. r: /photos\/([0-9]+@N[0-9]+|[a-z0-9_-]+)\/([0-9]+)/,
  947. s: m =>
  948. m.input.indexOf('/sizes/') < 0 ?
  949. `https://www.flickr.com/photos/${m[1]}/${m[2]}/sizes/sq/` :
  950. false,
  951. q: (text, doc) => {
  952. const links = $$('.sizes-list a', doc);
  953. return 'https://www.flickr.com' + links[links.length - 1].getAttribute('href');
  954. },
  955. follow: true,
  956. },
  957. {
  958. u: '||flickr.com/photos/',
  959. r: /\/sizes\//,
  960. q: '#allsizes-photo > img',
  961. },
  962. {
  963. u: '||gfycat.com/',
  964. r: /(gfycat\.com\/)(gifs\/detail\/|iframe\/)?([a-z]+)/i,
  965. s: 'https://$1$3',
  966. q: [
  967. 'meta[content$=".webm"]',
  968. '#webmsource',
  969. 'source[src$=".webm"]',
  970. ],
  971. },
  972. {
  973. u: [
  974. '||googleusercontent.com/proxy',
  975. '||googleusercontent.com/gadgets/proxy',
  976. ],
  977. r: /\.com\/(proxy|gadgets\/proxy.+?(http.+?)&)/,
  978. s: m => m[2] ? decodeURIComponent(m[2]) : m.input.replace(/w\d+-h\d+($|-p)/, 'w0-h0'),
  979. },
  980. {
  981. u: [
  982. '||googleusercontent.com/',
  983. '||ggpht.com/',
  984. ],
  985. s: (m, node) =>
  986. m.input.includes('webcache.') ||
  987. node.outerHTML.match(/favicons\?|\b(Ol Rf Ep|Ol Zb ag|Zb HPb|Zb Gtb|Rf Pg|ho PQc|Uk wi hE|go wi Wh|we D0b|Bea)\b/) ||
  988. node.matches('.g-hovercard *, a[href*="profile_redirector"] > img') ?
  989. '' :
  990. m.input.replace(/\/s\d{2,}-[^/]+|\/w\d+-h\d+/, '/s0')
  991. .replace(/=[-\w]+([&#].*|$)/, ''),
  992. },
  993. {
  994. u: '||gravatar.com/',
  995. r: /([a-z0-9]{32})/,
  996. s: 'https://gravatar.com/avatar/$1?s=200',
  997. },
  998. {
  999. u: '//gyazo.com/',
  1000. r: /\.com\/\w{32,}/,
  1001. q: 'meta[name="twitter:image"]',
  1002. xhr: true,
  1003. },
  1004. {
  1005. u: '||hostingkartinok.com/show-image.php',
  1006. q: '.image img',
  1007. },
  1008. {
  1009. u: [
  1010. '||imagecurl.com/images/',
  1011. '||imagecurl.com/viewer.php',
  1012. ],
  1013. r: /(?:images\/(\d+)_thumb|file=(\d+))(\.\w+)/,
  1014. s: 'https://imagecurl.com/images/$1$2$3',
  1015. },
  1016. {
  1017. u: '||imagebam.com/image/',
  1018. q: 'meta[property="og:image"]',
  1019. tabfix: true,
  1020. xhr: hostname.includes('planetsuzy'),
  1021. },
  1022. {
  1023. u: '||imageban.ru/thumbs',
  1024. r: /(.+?\/)thumbs(\/\d+)\.(\d+)\.(\d+\/.*)/,
  1025. s: '$1out$2/$3/$4',
  1026. },
  1027. {
  1028. u: [
  1029. '||imageban.ru/show',
  1030. '||imageban.net/show',
  1031. '||ibn.im/',
  1032. ],
  1033. q: '#img_main',
  1034. },
  1035. {
  1036. u: '||imageshack.us/img',
  1037. r: /img(\d+)\.(imageshack\.us)\/img\\1\/\d+\/(.+?)\.th(.+)$/,
  1038. s: 'https://$2/download/$1/$3$4',
  1039. },
  1040. {
  1041. u: '||imageshack.us/i/',
  1042. q: '#share-dl',
  1043. },
  1044. {
  1045. u: '||imageteam.org/img',
  1046. q: 'img[alt="image"]',
  1047. },
  1048. {
  1049. u: [
  1050. '||imagetwist.com/',
  1051. '||imageshimage.com/',
  1052. ],
  1053. r: /(\/\/|^)[^/]+\/[a-z0-9]{8,}/,
  1054. q: 'img.pic',
  1055. xhr: true,
  1056. },
  1057. {
  1058. u: '||imageupper.com/i/',
  1059. q: '#img',
  1060. xhr: true,
  1061. },
  1062. {
  1063. u: '||imagevenue.com/img.php',
  1064. q: '#thepic',
  1065. },
  1066. {
  1067. u: '||imagezilla.net/show/',
  1068. q: '#photo',
  1069. xhr: true,
  1070. },
  1071. {
  1072. u: [
  1073. '||images-na.ssl-images-amazon.com/images/',
  1074. '||media-imdb.com/images/',
  1075. ],
  1076. r: /images\/.+?\.jpg/,
  1077. s: '/V1\\.?_.+?\\.//g',
  1078. },
  1079. {
  1080. u: '||imgbox.com/',
  1081. r: /\.com\/([a-z0-9]+)$/i,
  1082. q: '#img',
  1083. xhr: hostname !== 'imgbox.com',
  1084. },
  1085. {
  1086. u: '||imgclick.net/',
  1087. r: /\.net\/(\w+)/,
  1088. q: 'img.pic',
  1089. xhr: true,
  1090. post: m => `op=view&id=${m[1]}&pre=1&submit=Continue%20to%20image...`,
  1091. },
  1092. {
  1093. u: [
  1094. '||imgflip.com/i/',
  1095. '||imgflip.com/gif/',
  1096. ],
  1097. r: /\/(i|gif)\/([^/?#]+)/,
  1098. s: m => `https://i.imgflip.com/${m[2]}${m[1] === 'i' ? '.jpg' : '.mp4'}`,
  1099. },
  1100. {
  1101. u: [
  1102. '||imgur.com/a/',
  1103. '||imgur.com/gallery/',
  1104. '||imgur.com/t/',
  1105. ],
  1106. g: async (text, doc, url, m, rule, cb) => {
  1107. // simplified extraction of JSON as it occupies only one line
  1108. if (!/(?:mergeConfig\('gallery',\s*|Imgur\.Album\.getInstance\()[\s\S]*?[,\s{"'](?:image|album)\s*:\s*({[^\r\n]+?}),?[\r\n]/.test(text))
  1109. return;
  1110. const info = JSON.parse(RegExp.$1);
  1111. let images = info.is_album ? info.album_images.images : [info];
  1112. if (info.num_images > images.length) {
  1113. const url = `https://imgur.com/ajaxalbums/getimages/${info.hash}/hit.json?all=true`;
  1114. images = JSON.parse((await Remoting.gmXhr(url)).responseText).data.images;
  1115. }
  1116. const items = [];
  1117. for (const img of images || []) {
  1118. const u = `https://i.imgur.com/${img.hash}`;
  1119. items.push({
  1120. url: img.ext === '.gif' && img.animated !== false ?
  1121. [`${u}.webm`, `${u}.mp4`, u] :
  1122. u + img.ext,
  1123. desc: [img.title, img.description].filter(Boolean).join(' - '),
  1124. });
  1125. }
  1126. if (images && info.is_album && !safeIncludes(items[0].desc, info.title))
  1127. items.title = info.title;
  1128. cb(items);
  1129. },
  1130. css: '.post > .hover { display:none!important; }',
  1131. },
  1132. {
  1133. u: '||imgur.com/',
  1134. r: /((?:[a-z]{2,}\.)?imgur\.com\/)((?:\w+,)+\w*)/,
  1135. s: 'gallery',
  1136. g: (text, doc, url, m) =>
  1137. m[2].split(',').map(id => ({
  1138. url: `https://i.${m[1]}${id}.jpg`,
  1139. })),
  1140. },
  1141. {
  1142. u: '||imgur.com/',
  1143. r: /([a-z]{2,}\.)?imgur\.com\/(r\/[a-z]+\/|[a-z0-9]+#)?([a-z0-9]{5,})($|\?|\.([a-z]+))/i,
  1144. s: (m, node) => {
  1145. if (/memegen|random|register|search|signin/.test(m.input))
  1146. return '';
  1147. const a = node.closest('a');
  1148. if (a && a !== node && /(i\.([a-z]+\.)?)?imgur\.com\/(a\/|gallery\/)?/.test(a.href))
  1149. return false;
  1150. const id = m[3].replace(/(.{7})[bhm]$/, '$1');
  1151. const ext = m[5] ? m[5].replace(/gifv?/, 'webm') : 'jpg';
  1152. const u = `https://i.${(m[1] || '').replace('www.', '')}imgur.com/${id}.`;
  1153. return ext === 'webm' ?
  1154. [`${u}webm`, `${u}mp4`, `${u}gif`] :
  1155. u + ext;
  1156. },
  1157. },
  1158. {
  1159. u: [
  1160. '||instagr.am/p/',
  1161. '||instagram.com/p/',
  1162. ],
  1163. s: m => m.input.substr(0, m.input.lastIndexOf('/')) + '/?__a=1',
  1164. q: text => {
  1165. const m = JSON.parse(text).graphql.shortcode_media;
  1166. return m.video_url || m.display_url;
  1167. },
  1168. rect: 'div.PhotoGridMediaItem',
  1169. c: text => {
  1170. const m = JSON.parse(text).graphql.shortcode_media.edge_media_to_caption.edges[0];
  1171. return m === undefined ? '(no caption)' : m.node.text;
  1172. },
  1173. },
  1174. {
  1175. u: [
  1176. '||livememe.com/',
  1177. '||lvme.me/',
  1178. ],
  1179. r: /\.\w+\/([^.]+)$/,
  1180. s: 'http://i.lvme.me/$1.jpg',
  1181. },
  1182. {
  1183. u: '||lostpic.net/image',
  1184. q: '.image-viewer-image img',
  1185. },
  1186. {
  1187. u: '||makeameme.org/meme/',
  1188. r: /\/meme\/([^/?#]+)/,
  1189. s: 'https://media.makeameme.org/created/$1.jpg',
  1190. },
  1191. {
  1192. u: '||photobucket.com/',
  1193. r: /(\d+\.photobucket\.com\/.+\/)(\?[a-z=&]+=)?(.+\.(jpe?g|png|gif))/,
  1194. s: 'https://i$1$3',
  1195. xhr: !dotDomain.endsWith('.photobucket.com'),
  1196. },
  1197. {
  1198. u: '||piccy.info/view3/',
  1199. r: /(.+?\/view3)\/(.*)\//,
  1200. s: '$1/$2/orig/',
  1201. q: '#mainim',
  1202. },
  1203. {
  1204. u: '||pimpandhost.com/image/',
  1205. r: /(.+?\/image\/[0-9]+)/,
  1206. s: '$1?size=original',
  1207. q: 'img.original',
  1208. },
  1209. {
  1210. u: [
  1211. '||pixroute.com/',
  1212. '||imgspice.com/',
  1213. ],
  1214. r: /\.html$/,
  1215. q: 'img[id]',
  1216. xhr: true,
  1217. },
  1218. {
  1219. u: '||postima',
  1220. r: /postima?ge?\.org\/image\/\w+/,
  1221. q: [
  1222. 'a[href*="dl="]',
  1223. '#main-image',
  1224. ],
  1225. },
  1226. {
  1227. u: [
  1228. '||prntscr.com/',
  1229. '||prnt.sc/',
  1230. ],
  1231. r: /\.\w+\/.+/,
  1232. q: 'meta[property="og:image"]',
  1233. xhr: true,
  1234. },
  1235. {
  1236. u: '||radikal.ru/',
  1237. r: /\.ru\/(fp|.+\.html)/,
  1238. q: text => text.match(/http:\/\/[a-z0-9]+\.radikal\.ru[a-z0-9/]+\.(jpg|gif|png)/i)[0],
  1239. },
  1240. {
  1241. u: '||tumblr.com',
  1242. r: /_500\.jpg/,
  1243. s: ['/_500/_1280/', ''],
  1244. },
  1245. {
  1246. u: '||twimg.com/',
  1247. r: /\/profile_images/i,
  1248. s: '/_(reasonably_small|normal|bigger|\\d+x\\d+)\\././g',
  1249. },
  1250. {
  1251. u: '||twimg.com/media/',
  1252. r: /.+?format=(jpe?g|png|gif)/i,
  1253. s: '$0&name=large',
  1254. },
  1255. {
  1256. u: '||twimg.com/1/proxy',
  1257. r: /t=([^&_]+)/i,
  1258. s: m => atob(m[1]).match(/http.+/),
  1259. },
  1260. {
  1261. u: '||pic.twitter.com/',
  1262. r: /\.com\/[a-z0-9]+/i,
  1263. q: text => text.match(/https?:\/\/twitter\.com\/[^/]+\/status\/\d+\/photo\/\d+/i)[0],
  1264. follow: true,
  1265. },
  1266. {
  1267. u: '||twitpic.com/',
  1268. r: /\.com(\/show\/[a-z]+)?\/([a-z0-9]+)($|#)/i,
  1269. s: 'https://twitpic.com/show/large/$2',
  1270. },
  1271. {
  1272. u: '||upix.me/files',
  1273. s: '/#//',
  1274. },
  1275. {
  1276. u: '||wiki',
  1277. r: /\/(thumb|images)\/.+\.(jpe?g|gif|png|svg)\/(revision\/)?/i,
  1278. s: '/\\/thumb(?=\\/)|' +
  1279. '\\/scale-to-width(-[a-z]+)?\\/[0-9]+|' +
  1280. '\\/revision\\/latest|\\/[^\\/]+$//g',
  1281. xhr: !hostname.includes('wiki'),
  1282. },
  1283. {
  1284. u: '||ytimg.com/vi/',
  1285. r: /(.+?\/vi\/[^/]+)/,
  1286. s: '$1/0.jpg',
  1287. rect: '.video-list-item',
  1288. },
  1289. {
  1290. u: '/viewer.php?file=',
  1291. r: /(.+?)\/viewer\.php\?file=(.+)/,
  1292. s: '$1/images/$2',
  1293. xhr: true,
  1294. },
  1295. {
  1296. u: '/thumb_',
  1297. r: /\/albums.+\/thumb_[^/]/,
  1298. s: '/thumb_//',
  1299. },
  1300. {
  1301. u: [
  1302. '.th.jp',
  1303. '.th.gif',
  1304. '.th.png',
  1305. ],
  1306. r: /(.+?\.)th\.(jpe?g?|gif|png|svg|webm)$/i,
  1307. s: '$1$2',
  1308. follow: true,
  1309. },
  1310. {
  1311. u: [
  1312. '.jp',
  1313. '.gif',
  1314. '.png',
  1315. '.svg',
  1316. '.webm',
  1317. ],
  1318. r: /[^?:]+\.(jpe?g?|gif|png|svg|webm)($|\?)/i,
  1319. },
  1320. ];
  1321.  
  1322. /** @type mpiv.HostRule[] */
  1323. Ruler.rules = [].concat(customRules, disablers, perDomain, main).filter(Boolean);
  1324. }
  1325.  
  1326. static format(rule, {expand} = {}) {
  1327. const s = JSON.stringify(rule, null, ' ');
  1328. return expand ?
  1329. /* {"a": ...,
  1330. "b": ...,
  1331. "c": ...
  1332. } */
  1333. s.replace(/^{\s+/g, '{') :
  1334. /* {"a": ..., "b": ..., "c": ...} */
  1335. s.replace(/\n\s*/g, ' ').replace(/^({)\s|\s+(})$/g, '$1$2');
  1336. }
  1337.  
  1338. /** @returns mpiv.HostRule | Error | false | undefined */
  1339. static parse(rule) {
  1340. const isBatchOp = this instanceof Map;
  1341. try {
  1342. if (typeof rule === 'string')
  1343. rule = JSON.parse(rule);
  1344. if ('d' in rule && typeof rule.d !== 'string')
  1345. rule.d = undefined;
  1346. else if (isBatchOp && rule.d && !hostname.includes(rule.d))
  1347. return false;
  1348. const compileTo = isBatchOp ? rule : {};
  1349. if (rule.r)
  1350. compileTo.r = new RegExp(rule.r, 'i');
  1351. if (RX_HAS_CODE.test(rule.s))
  1352. compileTo.s = Util.newFunction('m', 'node', 'rule', rule.s);
  1353. if (RX_HAS_CODE.test(rule.q))
  1354. compileTo.q = Util.newFunction('text', 'doc', 'node', 'rule', rule.q);
  1355. if (RX_HAS_CODE.test(rule.c))
  1356. compileTo.c = Util.newFunction('text', 'doc', 'node', 'rule', rule.c);
  1357. return rule;
  1358. } catch (e) {
  1359. if (!e.message.includes('unsafe-eval'))
  1360. if (isBatchOp) {
  1361. this.set(rule, e);
  1362. } else {
  1363. return e;
  1364. }
  1365. }
  1366. }
  1367.  
  1368. static runQ(text, doc, docUrl) {
  1369. let url;
  1370. if (typeof ai.rule.q === 'function') {
  1371. url = ai.rule.q(text, doc, ai.node, ai.rule);
  1372. if (Array.isArray(url)) {
  1373. ai.urls = url.slice(1);
  1374. url = url[0];
  1375. }
  1376. } else {
  1377. const el = $many(ai.rule.q, doc);
  1378. url = el && Remoting.findFileUrl(el, docUrl);
  1379. }
  1380. return url;
  1381. }
  1382.  
  1383. static runS(node, rule, m) {
  1384. let urls = [];
  1385. for (const s of ensureArray(rule.s))
  1386. urls.push(
  1387. typeof s === 'string' ? Util.maybeDecodeURL(Ruler.substituteSingle(s, m)) :
  1388. typeof s === 'function' ? s(m, node, rule) :
  1389. s);
  1390. if (rule.q && urls.length > 1) {
  1391. console.warn('Rule discarded: "s" array is not allowed with "q"\n%o', rule);
  1392. return {skipRule: true};
  1393. }
  1394. if (Array.isArray(urls[0]))
  1395. urls = urls[0];
  1396. // `false` returned by "s" property means "skip this rule"
  1397. // any other falsy value (like say "") means "stop all rules"
  1398. return urls[0] === false ? {skipRule: true} : urls.map(Util.maybeDecodeURL);
  1399. }
  1400.  
  1401. static substituteSingle(s, m) {
  1402. if (!m)
  1403. return s;
  1404. if (s.startsWith('/') && !s.startsWith('//')) {
  1405. const mid = s.search(/[^\\]\//) + 1;
  1406. const end = s.lastIndexOf('/');
  1407. const re = new RegExp(s.slice(1, mid), s.slice(end + 1));
  1408. return m.input.replace(re, s.slice(mid + 1, end));
  1409. }
  1410. if (m.length && s.includes('$')) {
  1411. const maxLength = Math.floor(Math.log10(m.length)) + 1;
  1412. s = s.replace(/\$(\d{1,3})/g, (text, num) => {
  1413. for (let i = maxLength; i >= 0; i--) {
  1414. const part = num.slice(0, i) | 0;
  1415. if (part < m.length)
  1416. return (m[part] || '') + num.slice(i);
  1417. }
  1418. return text;
  1419. });
  1420. }
  1421. return s;
  1422. }
  1423. }
  1424.  
  1425. const SimpleUrlMatcher = (() => {
  1426. // string-to-regexp escaped chars
  1427. const RX_ESCAPE = /[.+*?(){}[\]^$|]/g;
  1428. // rx for '^' symbol in simple url match
  1429. const RX_SEP = /[^\w%._-]/g;
  1430. const RXS_SEP = RX_SEP.source;
  1431. return match => {
  1432. const results = [];
  1433. for (const s of ensureArray(match)) {
  1434. const pinDomain = s.startsWith('||');
  1435. const pinStart = !pinDomain && s.startsWith('|');
  1436. const endSep = s.endsWith('^');
  1437. let fn;
  1438. let needle = s.slice(pinDomain * 2 + pinStart, -endSep || undefined);
  1439. if (needle.includes('^')) {
  1440. const plain = findLongestPart(needle);
  1441. const rx = new RegExp(
  1442. (pinStart ? '^' : '') +
  1443. (pinDomain ? '^(([^/:]+:)?//)?([^./]*\\.)*?' : '') +
  1444. needle.replace(RX_ESCAPE, '\\$&').replace(/\\\^/g, RXS_SEP) +
  1445. (endSep ? `(?:${RXS_SEP}|$)` : ''), 'i');
  1446. needle = [plain, rx];
  1447. fn = regexp;
  1448. } else if (pinStart) {
  1449. fn = endSep ? equals : starts;
  1450. } else if (pinDomain) {
  1451. const slashPos = needle.indexOf('/');
  1452. const domain = slashPos > 0 ? needle.slice(0, slashPos) : needle;
  1453. needle = [needle, domain, slashPos > 0, endSep];
  1454. fn = startsDomainPrescreen;
  1455. } else if (endSep) {
  1456. fn = ends;
  1457. } else {
  1458. fn = has;
  1459. }
  1460. results.push({fn, this: needle});
  1461. }
  1462. return results.length > 1 ?
  1463. {fn: checkArray, this: results} :
  1464. results[0];
  1465. };
  1466. function checkArray(s) {
  1467. return this.some(checkArrayItem, s);
  1468. }
  1469. function checkArrayItem(item) {
  1470. return item.fn.call(item.this, this);
  1471. }
  1472. function equals(s) {
  1473. return s.startsWith(this) && (
  1474. s.length === this.length ||
  1475. s.length === this.length + 1 && endsWithSep(s));
  1476. }
  1477. function starts(s) {
  1478. return s.startsWith(this);
  1479. }
  1480. function ends(s) {
  1481. return s.endsWith(this) || (
  1482. s.length > this.length &&
  1483. s.indexOf(this, s.length - this.length - 1) >= 0 &&
  1484. endsWithSep(s));
  1485. }
  1486. function has(s) {
  1487. return s.includes(this);
  1488. }
  1489. function regexp(s) {
  1490. return s.includes(this[0]) && this[1].test(s);
  1491. }
  1492. function endsWithSep(s) {
  1493. RX_SEP.lastIndex = s.length - 1;
  1494. return RX_SEP.test(s);
  1495. }
  1496. function startsDomainPrescreen(url) {
  1497. return url.includes(this[0]) && startsDomain.call(this, url);
  1498. }
  1499. function startsDomain(url) {
  1500. const [p, gap, host] = url.split('/', 3);
  1501. if (gap || p && !p.endsWith(':'))
  1502. return;
  1503. const [needle, domain, pinDomainEnd, endSep] = this;
  1504. let start = pinDomainEnd ? host.length - domain.length : 0;
  1505. for (; ; start++) {
  1506. start = host.indexOf(domain, start);
  1507. if (start < 0)
  1508. return;
  1509. if (!start || host[start - 1] === '.')
  1510. break;
  1511. }
  1512. start += p.length + 2;
  1513. return url.lastIndexOf(needle, start) === start &&
  1514. (!endSep || start + needle.length === url.length);
  1515. }
  1516. function findLongestPart(s) {
  1517. const len = s.length;
  1518. let maxLen = 0;
  1519. let start;
  1520. for (let i = 0, j; i < len; i = j + 1) {
  1521. j = s.indexOf('^', i);
  1522. if (j < 0)
  1523. j = len;
  1524. if (j - i > maxLen) {
  1525. maxLen = j - i;
  1526. start = i;
  1527. }
  1528. }
  1529. return maxLen < len ? s.substr(start, maxLen) : s;
  1530. }
  1531. })();
  1532.  
  1533. class RuleMatcher {
  1534.  
  1535. /** @returns ?mpiv.RuleMatchInfo */
  1536. static findForLink(a) {
  1537. let url =
  1538. a.getAttribute('data-expanded-url') ||
  1539. a.getAttribute('data-full-url') ||
  1540. a.getAttribute('data-url') ||
  1541. a.href;
  1542. if (url.startsWith('data:'))
  1543. url = false;
  1544. else if (url.includes('//t.co/'))
  1545. url = 'http://' + a.textContent;
  1546. return RuleMatcher.find(url, a);
  1547. }
  1548.  
  1549. /** @returns ?mpiv.RuleMatchInfo */
  1550. static find(url, node, {noHtml, skipRule} = {}) {
  1551. const tn = node.tagName;
  1552. let m, html, urls;
  1553. for (const rule of Ruler.rules) {
  1554. const {e} = rule;
  1555. if (e && !node.matches(e) || rule === skipRule)
  1556. continue;
  1557. const {r, u} = rule;
  1558. if (r && !noHtml && rule.html && (tn === 'A' || tn === 'IMG' || e))
  1559. m = r.exec(html || (html = node.outerHTML));
  1560. else if (r || u)
  1561. m = url && RuleMatcher.makeUrlMatch(url, node, rule);
  1562. else
  1563. m = url ? RuleMatcher.makeDummyMatch(url) : [];
  1564. if (!m ||
  1565. // a rule with follow:true for the currently hovered IMG produced a URL,
  1566. // but we'll only allow it to match rules without 's' in the nested find call
  1567. tn === 'IMG' && !('s' in rule) && !skipRule)
  1568. continue;
  1569. if (rule.s === '')
  1570. return {};
  1571. const hasS = 's' in rule && rule.s !== 'gallery';
  1572. urls = hasS ? Ruler.runS(node, rule, m) : [m.input];
  1573. if (!urls.skipRule) {
  1574. const url = urls[0];
  1575. return !url ? {} :
  1576. hasS && !rule.q && RuleMatcher.isFollowableUrl(url, rule) ?
  1577. RuleMatcher.find(url, node, {skipRule: rule}) :
  1578. RuleMatcher.makeInfo(urls, node, rule, m);
  1579. }
  1580. }
  1581. }
  1582.  
  1583. static makeUrlMatch(url, node, rule) {
  1584. let {r, u} = rule;
  1585. let m;
  1586. if (u) {
  1587. u = rule._u || (rule._u = SimpleUrlMatcher(u));
  1588. m = u.fn.call(u.this, url) && (r || RuleMatcher.makeDummyMatch(url));
  1589. }
  1590. return (m || !u) && r ? r.exec(url) : m;
  1591. }
  1592.  
  1593. static makeDummyMatch(url) {
  1594. const m = [url];
  1595. m.index = 0;
  1596. m.input = url;
  1597. return m;
  1598. }
  1599.  
  1600. /** @returns mpiv.RuleMatchInfo */
  1601. static makeInfo(urls, node, rule, m) {
  1602. const url = urls[0];
  1603. const info = {
  1604. node,
  1605. rule,
  1606. url,
  1607. urls: urls.length > 1 ? urls.slice(1) : null,
  1608. match: m,
  1609. gallery: rule.g && Gallery.makeParser(rule.g),
  1610. post: typeof rule.post === 'function' ? rule.post(m) : rule.post,
  1611. xhr: cfg.xhr && rule.xhr,
  1612. };
  1613. Util.lazyGetRect(info, node, rule.rect);
  1614. if (
  1615. dotDomain.endsWith('.twitter.com') && !/(facebook|google|twimg|twitter)\.com\//.test(url) ||
  1616. dotDomain.endsWith('.github.com') && !/github/.test(url) ||
  1617. dotDomain.endsWith('.facebook.com') && /\bimgur\.com/.test(url)
  1618. ) {
  1619. info.xhr = 'data';
  1620. }
  1621. return info;
  1622. }
  1623.  
  1624. static isFollowableUrl(url, rule) {
  1625. const f = rule.follow;
  1626. return typeof f === 'function' ? f(url) : f;
  1627. }
  1628. }
  1629.  
  1630. class Events {
  1631.  
  1632. static onMouseOver(e) {
  1633. if (!App.enabled || e.shiftKey || ai.zoom)
  1634. return;
  1635. let node = e.target;
  1636. if (node === ai.popup ||
  1637. node === doc.body ||
  1638. node === doc.documentElement)
  1639. return;
  1640.  
  1641. if (node.shadowRoot)
  1642. node = Events.pierceShadow(node, e.clientX, e.clientY);
  1643.  
  1644. if (!Ruler.rules)
  1645. Ruler.init();
  1646.  
  1647. let a, img, url, info;
  1648. if (node.tagName === 'A') {
  1649. a = node;
  1650. } else {
  1651. if (node.tagName === 'IMG') {
  1652. img = node;
  1653. url = !img.src.startsWith('data:') && Util.rel2abs(img.src, location.href);
  1654. }
  1655. info = RuleMatcher.find(url, node);
  1656. a = !info && node.closest('a');
  1657. }
  1658.  
  1659. if (!info && a)
  1660. info = RuleMatcher.findForLink(a);
  1661.  
  1662. if (!info && img) {
  1663. info = Util.lazyGetRect({
  1664. url: img.src,
  1665. node: img,
  1666. rule: {},
  1667. }, img);
  1668. }
  1669.  
  1670. if (info && info.url && info.node !== ai.node)
  1671. App.activate(info, e);
  1672. }
  1673.  
  1674. static pierceShadow(node, x, y) {
  1675. for (let root; (root = node.shadowRoot);) {
  1676. root.addEventListener('mouseover', Events.onMouseOver, PASSIVE);
  1677. root.addEventListener('mouseout', Events.onMouseOutShadow);
  1678. const inner = root.elementFromPoint(x, y);
  1679. if (!inner || inner === node)
  1680. break;
  1681. node = inner;
  1682. }
  1683. return node;
  1684. }
  1685.  
  1686. static onMouseOut(e) {
  1687. if (!e.relatedTarget && !e.shiftKey)
  1688. App.deactivate();
  1689. }
  1690.  
  1691. static onMouseOutShadow(e) {
  1692. const root = e.target.shadowRoot;
  1693. if (root) {
  1694. root.removeEventListener('mouseover', Events.onMouseOver);
  1695. root.removeEventListener('mouseout', Events.onMouseOutShadow);
  1696. }
  1697. }
  1698.  
  1699. static onMouseMove(e) {
  1700. App.updateMouse(e);
  1701. if (e.shiftKey)
  1702. return (ai.lazyUnload = true);
  1703. if (!ai.zoomed && !ai.isOverRect)
  1704. return App.deactivate();
  1705. if (ai.zoom) {
  1706. Popup.move();
  1707. const {height: h, width: w} = ai.view;
  1708. const {clientX: cx, clientY: cy} = ai;
  1709. const bx = w / 6;
  1710. const by = h / 6;
  1711. const onEdge = cx < bx || cx > w - bx || cy < by || cy > h - by;
  1712. App.setStatus(`${onEdge ? '+' : '-'}edge`);
  1713. }
  1714. }
  1715.  
  1716. static onMouseDown({shiftKey, button}) {
  1717. if (button === 0 && shiftKey && ai.popup && ai.popup.controls) {
  1718. ai.controlled = ai.zoomed = true;
  1719. } else if (button === 2 || shiftKey) {
  1720. // we ignore RMB and Shift
  1721. } else {
  1722. App.deactivate({wait: true});
  1723. }
  1724. }
  1725.  
  1726. static onMouseScroll(e) {
  1727. const dir = (e.deltaY || -e.wheelDelta) > 0 ? 1 : -1;
  1728. if (ai.zoom) {
  1729. dropEvent(e);
  1730. const i = ai.scales.indexOf(ai.scale) - dir;
  1731. const n = ai.scales.length;
  1732. if (i >= 0 && i < n)
  1733. ai.scale = ai.scales[i];
  1734. if (i === 0 && cfg.zoomOut !== 'stay') {
  1735. if ((cfg.zoomOut === 'close' || !ai.isOverRect) &&
  1736. (!ai.gItems || ai.gItems.length < 2))
  1737. return App.deactivate({wait: true});
  1738. ai.zoom = false;
  1739. ai.zoomed = false;
  1740. App.updateFileInfo();
  1741. } else {
  1742. ai.popup.classList.toggle(`${PREFIX}zoom-max`, ai.scale >= 4 && i >= n - 1);
  1743. }
  1744. if (ai.zooming)
  1745. ai.popup.classList.add(`${PREFIX}zooming`);
  1746. Popup.move();
  1747. App.updateTitle();
  1748. } else if (ai.gItems && ai.gItems.length > 1 && ai.popup) {
  1749. dropEvent(e);
  1750. Gallery.next(dir);
  1751. } else if (cfg.zoom === 'wheel' && dir < 0 && ai.popup) {
  1752. dropEvent(e);
  1753. App.toggleZoom();
  1754. } else {
  1755. App.deactivate();
  1756. }
  1757. }
  1758.  
  1759. static onKeyDown(e) {
  1760. switch (e.key) {
  1761. case 'Shift':
  1762. App.setStatus('+shift');
  1763. if (ai.popup && 'controls' in ai.popup)
  1764. ai.popup.controls = true;
  1765. break;
  1766. case 'Control':
  1767. if (!ai.popup && (cfg.start !== 'auto' || ai.rule.manual))
  1768. Popup.start();
  1769. break;
  1770. }
  1771. }
  1772.  
  1773. static onKeyUp(e) {
  1774. switch (e.key.length > 1 ? e.key : e.code) {
  1775. case 'Shift':
  1776. App.setStatus('-shift');
  1777. if ((ai.popup || {}).controls)
  1778. ai.popup.controls = false;
  1779. if (ai.controlled) {
  1780. ai.controlled = false;
  1781. return;
  1782. }
  1783. ai.popup && (ai.zoomed || ai.isOverRect !== false) ?
  1784. App.toggleZoom() :
  1785. App.deactivate({wait: true});
  1786. break;
  1787. case 'Control':
  1788. break;
  1789. case 'Escape':
  1790. App.deactivate({wait: true});
  1791. break;
  1792. case 'ArrowRight':
  1793. case 'KeyJ':
  1794. dropEvent(e);
  1795. Gallery.next(1);
  1796. break;
  1797. case 'ArrowLeft':
  1798. case 'KeyK':
  1799. dropEvent(e);
  1800. Gallery.next(-1);
  1801. break;
  1802. case 'KeyD': {
  1803. dropEvent(e);
  1804. Remoting.saveFile();
  1805. break;
  1806. }
  1807. case 'KeyT':
  1808. ai.lazyUnload = true;
  1809. GM_openInTab(
  1810. ai.rule.tabfix && ai.popup.tagName === 'IMG' && !ai.xhr &&
  1811. navigator.userAgent.includes('Gecko/') ?
  1812. Util.tabFixUrl() :
  1813. ai.popup.src);
  1814. App.deactivate();
  1815. break;
  1816. default:
  1817. App.deactivate({wait: true});
  1818. }
  1819. }
  1820.  
  1821. static onContext(e) {
  1822. if (e.shiftKey)
  1823. return;
  1824. if (cfg.zoom === 'context' && ai.popup && App.toggleZoom()) {
  1825. dropEvent(e);
  1826. return;
  1827. }
  1828. if (!ai.popup && (
  1829. cfg.start === 'context' ||
  1830. (cfg.start === 'auto' && ai.rule.manual)
  1831. )) {
  1832. Popup.start();
  1833. dropEvent(e);
  1834. } else {
  1835. setTimeout(App.deactivate, SETTLE_TIME, {wait: true});
  1836. }
  1837. }
  1838. }
  1839.  
  1840. class Popup {
  1841.  
  1842. static schedule(force) {
  1843. if (!cfg.preload) {
  1844. ai.timer = setTimeout(Popup.start, cfg.delay);
  1845. } else if (!force) {
  1846. // we don't want to preload everything in the path of a quickly moving mouse cursor
  1847. ai.timer = setTimeout(Popup.schedule, SETTLE_TIME, true);
  1848. ai.preloadStart = Date.now();
  1849. } else {
  1850. Popup.start();
  1851. App.setStatus('+preloading');
  1852. setTimeout(App.setStatus, cfg.delay, '-preloading');
  1853. }
  1854. }
  1855.  
  1856. static start() {
  1857. App.updateStyles();
  1858. ai.gallery ?
  1859. Popup.startGallery() :
  1860. Popup.startSingle();
  1861. }
  1862.  
  1863. static startSingle() {
  1864. App.setStatusLoading();
  1865. ai.imageUrl = null;
  1866. if (ai.rule.follow && !ai.rule.q && !ai.rule.s) {
  1867. Remoting.findRedirect();
  1868. } else if (ai.rule.q && !Array.isArray(ai.urls)) {
  1869. Popup.startFromQ();
  1870. } else {
  1871. App.updateCaption();
  1872. Popup.render(ai.url);
  1873. }
  1874. }
  1875.  
  1876. static async startFromQ() {
  1877. try {
  1878. const {responseText, doc, finalUrl} = await Remoting.getDoc(ai.url);
  1879. const url = Ruler.runQ(responseText, doc, finalUrl);
  1880. if (!url)
  1881. throw 'File not found.';
  1882. App.updateCaption(responseText, doc);
  1883. if (RuleMatcher.isFollowableUrl(url, ai.rule)) {
  1884. const info = RuleMatcher.find(url, ai.node, {noHtml: true});
  1885. if (!info || !info.url)
  1886. throw `Couldn't follow URL: ${url}`;
  1887. Object.assign(ai, info);
  1888. Popup.startSingle();
  1889. } else {
  1890. Popup.render(url, finalUrl);
  1891. }
  1892. } catch (e) {
  1893. App.handleError(e);
  1894. }
  1895. }
  1896.  
  1897. static async startGallery() {
  1898. App.setStatusLoading();
  1899. try {
  1900. const startUrl = ai.url;
  1901. const p = ai.rule.s === 'gallery' ? {} :
  1902. await Remoting.getDoc(startUrl);
  1903. const items = await new Promise(resolve => {
  1904. const it = ai.gallery(p.responseText, p.doc, p.finalUrl, ai.match, ai.rule, resolve);
  1905. if (Array.isArray(it))
  1906. resolve(it);
  1907. });
  1908. // bail out if the gallery's async callback took too long
  1909. if (ai.url !== startUrl)
  1910. return;
  1911. ai.gItems = items.length && items;
  1912. if (ai.gItems) {
  1913. ai.gIndex = Gallery.findIndex(ai.url);
  1914. setTimeout(Gallery.next);
  1915. } else {
  1916. throw 'Empty gallery';
  1917. }
  1918. } catch (e) {
  1919. App.handleError(e);
  1920. }
  1921. }
  1922.  
  1923. static async render(src, pageUrl) {
  1924. Popup.destroy();
  1925. ai.imageUrl = src;
  1926. if (ai.xhr && src)
  1927. src = await Remoting.getImage(src, pageUrl).catch(App.handleError);
  1928. if (!src)
  1929. return;
  1930. const p = ai.popup =
  1931. src.startsWith('data:video') ||
  1932. !src.startsWith('data:') && /\.(webm|mp4)($|\?)/.test(src) ?
  1933. PopupVideo.create() :
  1934. $create('img');
  1935. p.id = `${PREFIX}popup`;
  1936. p.src = src;
  1937. p.addEventListener('error', App.handleError);
  1938. p.addEventListener('load', Popup.onLoad, {once: true});
  1939. if (ai.zooming)
  1940. p.addEventListener('transitionend', Popup.onZoom);
  1941. doc.body.insertBefore(p, ai.bar || undefined);
  1942. App.checkProgress({start: true});
  1943. }
  1944.  
  1945. static onLoad() {
  1946. this.setAttribute('loaded', '');
  1947. ai.popupLoaded = true;
  1948. if (!ai.bar)
  1949. App.updateFileInfo();
  1950. }
  1951.  
  1952. static onZoom() {
  1953. return this.classList.remove(`${PREFIX}zooming`);
  1954. }
  1955.  
  1956. static move() {
  1957. const p = ai.popup;
  1958. if (!p)
  1959. return;
  1960. let x, y;
  1961. const w = Math.round(ai.scale * ai.nwidth);
  1962. const h = Math.round(ai.scale * ai.nheight);
  1963. const cx = ai.clientX;
  1964. const cy = ai.clientY;
  1965. const vw = ai.view.width - ai.outline * 2;
  1966. const vh = ai.view.height - ai.outline * 2;
  1967. if (!ai.zoom && (!ai.gItems || ai.gItems.length < 2) && !cfg.center) {
  1968. const r = ai.rect;
  1969. const rx = (r.left + r.right) / 2;
  1970. const ry = (r.top + r.bottom) / 2;
  1971. if (vw - r.right - 40 > w + ai.mbw || w + ai.mbw < r.left - 40) {
  1972. if (h + ai.mbh < vh - 60)
  1973. y = clamp(ry - h / 2, 30, vh - h - 30);
  1974. x = rx > vw / 2 ? r.left - 40 - w : r.right + 40;
  1975. } else if (vh - r.bottom - 40 > h + ai.mbh || h + ai.mbh < r.top - 40) {
  1976. if (w + ai.mbw < vw - 60)
  1977. x = clamp(rx - w / 2, 30, vw - w - 30);
  1978. y = ry > vh / 2 ? r.top - 40 - h : r.bottom + 40;
  1979. }
  1980. }
  1981. if (x === undefined) {
  1982. const mid = vw > w ?
  1983. vw / 2 - w / 2 :
  1984. -1 * clamp(5 / 3 * (cx / vw - 0.2), 0, 1) * (w - vw);
  1985. x = Math.round(mid - (ai.pw + ai.mbw) / 2);
  1986. }
  1987. if (y === undefined) {
  1988. const mid = vh > h ?
  1989. vh / 2 - h / 2 :
  1990. -1 * clamp(5 / 3 * (cy / vh - 0.2), 0, 1) * (h - vh);
  1991. y = Math.round(mid - (ai.ph + ai.mbh) / 2);
  1992. }
  1993. p.style.cssText = `
  1994. width: ${w}px !important;
  1995. height: ${h}px !important;
  1996. left: ${x + ai.outline}px !important;
  1997. top: ${y + ai.outline}px !important;
  1998. `;
  1999. }
  2000.  
  2001. static destroy() {
  2002. const p = ai.popup;
  2003. if (!p)
  2004. return;
  2005. p.removeEventListener('error', App.handleError);
  2006. if (typeof p.pause === 'function')
  2007. p.pause();
  2008. if (!ai.lazyUnload) {
  2009. if (p.src.startsWith('blob:'))
  2010. URL.revokeObjectURL(p.src);
  2011. p.src = '';
  2012. }
  2013. p.remove();
  2014. ai.zoom = false;
  2015. ai.popupLoaded = false;
  2016. ai.popup = null;
  2017. }
  2018. }
  2019.  
  2020. class PopupVideo {
  2021. static create() {
  2022. const p = $create('video');
  2023. p.autoplay = true;
  2024. p.loop = true;
  2025. p.volume = 0.5;
  2026. p.controls = false;
  2027. p.addEventListener('progress', PopupVideo.progress);
  2028. p.addEventListener('canplaythrough', PopupVideo.progressDone, {once: true});
  2029. ai.bufferingBar = false;
  2030. ai.bufferingStart = Date.now();
  2031. return p;
  2032. }
  2033.  
  2034. static progress() {
  2035. const {duration} = this;
  2036. if (duration && this.buffered.length && Date.now() - ai.bufferingStart > 2000) {
  2037. const pct = Math.round(this.buffered.end(0) / duration * 100);
  2038. if ((ai.bufferingBar |= pct > 0 && pct < 50))
  2039. App.setBar(`${pct}% of ${Math.round(duration)}s`, 'xhr');
  2040. }
  2041. }
  2042.  
  2043. static progressDone() {
  2044. this.removeEventListener('progress', PopupVideo.progress);
  2045. if (ai.bar && ai.bar.classList.contains(`${PREFIX}xhr`)) {
  2046. App.setBar(false);
  2047. App.updateFileInfo();
  2048. }
  2049. }
  2050. }
  2051.  
  2052. class Gallery {
  2053.  
  2054. static makeParser(g) {
  2055. return (
  2056. typeof g === 'function' ? g :
  2057. typeof g === 'string' ? Util.newFunction('text', 'doc', 'url', 'm', 'rule', 'cb', g) :
  2058. Gallery.defaultParser
  2059. );
  2060. }
  2061.  
  2062. static findIndex(gUrl) {
  2063. const sel = gUrl.split('#')[1];
  2064. if (!sel)
  2065. return 0;
  2066. if (/^\d+$/.test(sel))
  2067. return parseInt(sel);
  2068. for (let i = ai.gItems.length; i--;) {
  2069. let {url} = ai.gItems[i];
  2070. if (Array.isArray(url))
  2071. url = url[0];
  2072. if (url.indexOf(sel, url.lastIndexOf('/')) > 0)
  2073. return i;
  2074. }
  2075. return 0;
  2076. }
  2077.  
  2078. static next(dir) {
  2079. if (dir > 0 && (ai.gIndex += dir) >= ai.gItems.length) {
  2080. ai.gIndex = 0;
  2081. } else if (dir < 0 && (ai.gIndex += dir) < 0) {
  2082. ai.gIndex = ai.gItems.length - 1;
  2083. }
  2084. const item = ai.gItems[ai.gIndex];
  2085. if (Array.isArray(item.url)) {
  2086. ai.urls = item.url.slice(1);
  2087. ai.url = item.url[0];
  2088. } else {
  2089. ai.urls = null;
  2090. ai.url = item.url;
  2091. }
  2092. Popup.destroy();
  2093. Popup.startSingle();
  2094. App.updateFileInfo();
  2095. Gallery.preload(dir);
  2096. }
  2097.  
  2098. static preload(dir) {
  2099. const i = ai.gIndex + dir;
  2100. if (ai.popup && i >= 0 && i < ai.gItems.length) {
  2101. ai.preloadUrl = ensureArray(ai.gItems[i].url)[0];
  2102. ai.popup.addEventListener('load', Gallery.preloadOnLoad, {once: true});
  2103. }
  2104. }
  2105.  
  2106. static preloadOnLoad() {
  2107. $create('img', {src: ai.preloadUrl});
  2108. }
  2109.  
  2110. static defaultParser(text, doc, docUrl, m, rule) {
  2111. const {g} = rule;
  2112. const qEntry = g.entry;
  2113. const qCaption = ensureArray(g.caption);
  2114. const qImage = g.image;
  2115. const qTitle = g.title;
  2116. const fix =
  2117. (typeof g.fix === 'string' ? Util.newFunction('s', 'isURL', g.fix) : g.fix) ||
  2118. (s => s.trim());
  2119. const items = [...$$(qEntry || qImage, doc)]
  2120. .map(processEntry)
  2121. .filter(Boolean);
  2122. items.title = processTitle();
  2123. return items;
  2124.  
  2125. function processEntry(entry) {
  2126. const item = {};
  2127. try {
  2128. const img = qEntry ? $(qImage, entry) : entry;
  2129. item.url = fix(Remoting.findFileUrl(img, docUrl), true);
  2130. item.desc = qCaption.map(processCaption, entry).filter(Boolean).join(' - ');
  2131. } catch (e) {}
  2132. return item.url && item;
  2133. }
  2134.  
  2135. function processCaption(selector) {
  2136. const el = $(selector, this) ||
  2137. $orSelf(selector, this.previousElementSibling) ||
  2138. $orSelf(selector, this.nextElementSibling);
  2139. return el && fix(el.textContent);
  2140. }
  2141.  
  2142. function processTitle() {
  2143. const el = $(qTitle, doc);
  2144. return el && fix(el.getAttribute('content') || el.textContent) || '';
  2145. }
  2146.  
  2147. function $orSelf(selector, el) {
  2148. if (el && !el.matches(qEntry))
  2149. return el.matches(selector) ? el : $(selector, el);
  2150. }
  2151. }
  2152. }
  2153.  
  2154. class Remoting {
  2155.  
  2156. static gmXhr(url, opts = {}) {
  2157. if (ai.req)
  2158. tryCatch.call(ai.req, ai.req.abort);
  2159. return new Promise((resolve, reject) => {
  2160. ai.req = GM_xmlhttpRequest({
  2161. url,
  2162. method: 'GET',
  2163. timeout: 10e3,
  2164. ...opts,
  2165. onload: done,
  2166. onerror: done,
  2167. ontimeout() {
  2168. ai.req = null;
  2169. reject(`Timeout fetching ${url}`);
  2170. },
  2171. });
  2172. function done(r) {
  2173. ai.req = null;
  2174. r.status < 400 && !r.error ?
  2175. resolve(r) :
  2176. reject(`Server error ${r.status} ${r.error}\nURL: ${url}`);
  2177. }
  2178. });
  2179. }
  2180.  
  2181. static async getDoc(url) {
  2182. const r = await (!ai.post ?
  2183. Remoting.gmXhr(url) :
  2184. Remoting.gmXhr(url, {
  2185. method: 'POST',
  2186. data: ai.post,
  2187. headers: {
  2188. 'Content-Type': 'application/x-www-form-urlencoded',
  2189. 'Referer': url,
  2190. },
  2191. }));
  2192. r.doc = new DOMParser().parseFromString(r.responseText, 'text/html');
  2193. return r;
  2194. }
  2195.  
  2196. static async getImage(url, pageUrl) {
  2197. ai.bufferingBar = false;
  2198. ai.bufferingStart = Date.now();
  2199. const response = await Remoting.gmXhr(url, {
  2200. responseType: 'blob',
  2201. headers: {
  2202. Accept: 'image/png,image/*;q=0.8,*/*;q=0.5',
  2203. Referer: pageUrl || (typeof ai.xhr === 'function' ? ai.xhr() : url),
  2204. },
  2205. onprogress: Remoting.getImageProgress,
  2206. });
  2207. App.setBar(false);
  2208. const type = Remoting.guessMimeType(response);
  2209. let b = response.response;
  2210. if (b.type !== type)
  2211. b = b.slice(0, b.size, type);
  2212. return ai.xhr === 'data' ?
  2213. Remoting.blobToDataUrl(b) :
  2214. URL.createObjectURL(b);
  2215. }
  2216.  
  2217. static getImageProgress(e) {
  2218. if (!ai.bufferingBar && Date.now() - ai.bufferingStart > 3000 && e.loaded / e.total < 0.5)
  2219. ai.bufferingBar = true;
  2220. if (ai.bufferingBar) {
  2221. const pct = e.loaded / e.total * 100 | 0;
  2222. const size = e.total / 1024 | 0;
  2223. App.setBar(`${pct}% of ${size} kiB`, 'xhr');
  2224. }
  2225. }
  2226.  
  2227. static async findRedirect() {
  2228. try {
  2229. const {finalUrl} = await Remoting.gmXhr(ai.url, {
  2230. method: 'HEAD',
  2231. headers: {
  2232. 'Referer': location.href.split('#', 1)[0],
  2233. },
  2234. });
  2235. const info = RuleMatcher.find(finalUrl, ai.node, {noHtml: true});
  2236. if (!info || !info.url)
  2237. throw `Couldn't follow redirection target: ${finalUrl}`;
  2238. Object.assign(ai, info);
  2239. Popup.startSingle();
  2240. } catch (e) {
  2241. App.handleError(e);
  2242. }
  2243. }
  2244.  
  2245. static async saveFile() {
  2246. let url = ai.popup.src || ai.popup.currentSrc;
  2247. let name = Remoting.getFileName(ai.imageUrl || url);
  2248. if (!name.includes('.'))
  2249. name += '.jpg';
  2250. try {
  2251. if (!url.startsWith('blob:') && !url.startsWith('data:')) {
  2252. const {response} = await Remoting.gmXhr(url, {
  2253. responseType: 'blob',
  2254. headers: {'Referer': url},
  2255. });
  2256. url = URL.createObjectURL(response);
  2257. setTimeout(() => URL.revokeObjectURL(url), 1000);
  2258. }
  2259. $create('a', {href: url, download: name})
  2260. .dispatchEvent(new MouseEvent('click'));
  2261. } catch (e) {
  2262. App.setBar(`Could not download ${name}.`, 'error');
  2263. }
  2264. }
  2265.  
  2266. static getFileName(url) {
  2267. return decodeURIComponent(url).split('/').pop().replace(/[:#?].*/, '');
  2268. }
  2269.  
  2270. static blobToDataUrl(blob) {
  2271. return new Promise((resolve, reject) => {
  2272. const fr = new FileReader();
  2273. fr.onload = () => resolve(fr.result);
  2274. fr.onerror = reject;
  2275. fr.readAsDataURL(blob);
  2276. });
  2277. }
  2278.  
  2279. static guessMimeType({responseHeaders, finalUrl}) {
  2280. if (/Content-Type:\s*(\S+)/i.test(responseHeaders) &&
  2281. !RegExp.$1.includes('text/plain'))
  2282. return RegExp.$1;
  2283. const ext = /\.([a-z0-9]+?)($|\?|#)/i.exec(finalUrl) ? RegExp.$1 : 'jpg';
  2284. switch (ext.toLowerCase()) {
  2285. case 'bmp': return 'image/bmp';
  2286. case 'gif': return 'image/gif';
  2287. case 'jpe': return 'image/jpeg';
  2288. case 'jpeg': return 'image/jpeg';
  2289. case 'jpg': return 'image/jpeg';
  2290. case 'mp4': return 'video/mp4';
  2291. case 'png': return 'image/png';
  2292. case 'svg': return 'image/svg+xml';
  2293. case 'tif': return 'image/tiff';
  2294. case 'tiff': return 'image/tiff';
  2295. case 'webm': return 'video/webm';
  2296. default: return 'application/octet-stream';
  2297. }
  2298. }
  2299.  
  2300. static findFileUrl(n, url) {
  2301. const base = $('base[href]', n.ownerDocument);
  2302. const path =
  2303. n.getAttribute('src') ||
  2304. n.getAttribute('data-m4v') ||
  2305. n.getAttribute('href') ||
  2306. n.getAttribute('content') ||
  2307. /https?:\/\/[./a-z0-9_+%-]+\.(jpe?g|gif|png|svg|webm|mp4)/i.exec(n.outerHTML) &&
  2308. RegExp.lastMatch;
  2309. return path ? Util.rel2abs(path.trim(), base ? base.getAttribute('href') : url) : false;
  2310. }
  2311. }
  2312.  
  2313. class Util {
  2314.  
  2315. static addStyle(name, css) {
  2316. const id = `${PREFIX}style:${name}`;
  2317. const el = doc.getElementById(id) ||
  2318. css && $create('style', {id});
  2319. if (!el)
  2320. return;
  2321. if (el.textContent !== css)
  2322. el.textContent = css;
  2323. if (el.parentElement !== doc.head)
  2324. doc.head.appendChild(el);
  2325. return el;
  2326. }
  2327.  
  2328. static deepEqual(a, b) {
  2329. if (typeof a !== typeof b)
  2330. return false;
  2331. if (!a || !b || typeof a !== 'object')
  2332. return a === b;
  2333. if (Array.isArray(a))
  2334. return Array.isArray(b) &&
  2335. a.length === b.length &&
  2336. a.every((v, i) => Util.deepEqual(v, b[i]));
  2337. const keys = Object.keys(a);
  2338. return keys.length === Object.keys(b).length &&
  2339. keys.every(k => Util.deepEqual(a[k], b[k]));
  2340. }
  2341.  
  2342. static findScale(url, parent) {
  2343. const imgs = $$('img, video', parent);
  2344. for (let i = imgs.length, img; (img = imgs[--i]);) {
  2345. if ((img.src || img.currentSrc) !== url)
  2346. continue;
  2347. const scaleX = (img.naturalWidth || img.videoWidth) / img.offsetWidth;
  2348. const scaleY = (img.naturalHeight || img.videoHeight) / img.offsetHeight;
  2349. const s = Math.max(scaleX, scaleY);
  2350. if (isFinite(s))
  2351. return s;
  2352. }
  2353. }
  2354.  
  2355. static forceLayout(node) {
  2356. // eslint-disable-next-line no-unused-expressions
  2357. node.clientHeight;
  2358. }
  2359.  
  2360. static formatError(e, rule) {
  2361. let {message} = e;
  2362. if (!message) {
  2363. if (e.readyState)
  2364. message = 'Request failed.';
  2365. else if (e.type === 'error')
  2366. message = "File can't be displayed." + (
  2367. $('div[bgactive*="flashblock"]', doc) ?
  2368. ' Check Flashblock settings.' :
  2369. '');
  2370. else
  2371. message = e;
  2372. }
  2373. const m = [
  2374. [`${GM_info.script.name}: %c${message}%c`, 'font-weight:bold;color:yellow'],
  2375. ['', 'font-weight:normal;color:unset'],
  2376. ];
  2377. if (rule.u)
  2378. m.push(['Url simple match: %o', rule.u]);
  2379. if (rule.r)
  2380. m.push(['RegExp match: %o', rule.r]);
  2381. if (ai.url)
  2382. m.push(['URL: %s', ai.url]);
  2383. if (ai.imageUrl && ai.imageUrl !== ai.url)
  2384. m.push(['File: %s', ai.imageUrl]);
  2385. m.push(['Node: %o', ai.node]);
  2386. return {
  2387. message,
  2388. consoleFormat: m.map(([k]) => k).filter(Boolean).join('\n'),
  2389. consoleArgs: m.map(([, v]) => v),
  2390. };
  2391. }
  2392.  
  2393. static lazyGetRect(obj, node, selector) {
  2394. return Object.defineProperty(obj, 'rect', {
  2395. configurable: true,
  2396. get() {
  2397. const value = Util.rect(node, selector);
  2398. Object.defineProperty(obj, 'rect', {value, configurable: true});
  2399. return value;
  2400. },
  2401. });
  2402. }
  2403.  
  2404. // decode only if the main part of the URL is encoded to preserve the encoded parameters
  2405. static maybeDecodeURL(url) {
  2406. if (!url)
  2407. return url;
  2408. const iPct = url.indexOf('%');
  2409. const iColon = url.indexOf(':');
  2410. return iPct >= 0 && (iPct < iColon || iColon < 0) ?
  2411. decodeURIComponent(url) :
  2412. url;
  2413. }
  2414.  
  2415. static newFunction(...args) {
  2416. try {
  2417. return App.NOP || new Function(...args);
  2418. } catch (e) {
  2419. if (!e.message.includes('unsafe-eval'))
  2420. throw e;
  2421. App.NOP = () => {};
  2422. return App.NOP;
  2423. }
  2424. }
  2425.  
  2426. static rect(node, selector) {
  2427. let n = selector && node.closest(selector);
  2428. if (n)
  2429. return n.getBoundingClientRect();
  2430. const nested = node.getElementsByTagName('*');
  2431. let maxArea = 0;
  2432. let maxBounds;
  2433. n = node;
  2434. for (let i = 0; n; n = nested[i++]) {
  2435. const bounds = n.getBoundingClientRect();
  2436. const area = bounds.width * bounds.height;
  2437. if (area > maxArea) {
  2438. maxArea = area;
  2439. maxBounds = bounds;
  2440. node = n;
  2441. }
  2442. }
  2443. return maxBounds;
  2444. }
  2445.  
  2446. static rel2abs(rel, abs) {
  2447. if (rel.startsWith('data:'))
  2448. return rel;
  2449. const rx = /^([a-z]+:)\/\//;
  2450. if (rx.test(rel))
  2451. return rel;
  2452. if (!rx.test(abs))
  2453. return;
  2454. if (rel.indexOf('//') === 0)
  2455. return RegExp.$1 + rel;
  2456. if (rel[0] === '/')
  2457. return abs.substr(0, abs.indexOf('/', RegExp.lastMatch.length)) + rel;
  2458. return abs.substr(0, abs.lastIndexOf('/')) + '/' + rel;
  2459. }
  2460.  
  2461. static suppressHoverTooltip() {
  2462. for (const node of [
  2463. ai.node.parentNode,
  2464. ai.node,
  2465. ai.node.firstElementChild,
  2466. ]) {
  2467. const t = (node || 0).title;
  2468. if (t && t !== node.textContent && !doc.title.includes(t) && !/^https?:\S+$/.test(t)) {
  2469. ai.tooltip = {node, text: t};
  2470. node.title = '';
  2471. break;
  2472. }
  2473. }
  2474. }
  2475.  
  2476. static tabFixUrl() {
  2477. return `data:text/html;charset=utf8,
  2478. <style>
  2479. body {
  2480. margin: 0;
  2481. padding: 0;
  2482. background: #222;
  2483. }
  2484. .fit {
  2485. overflow: hidden
  2486. }
  2487. .fit > img {
  2488. max-width: 100vw;
  2489. max-height: 100vh;
  2490. }
  2491. body > img {
  2492. margin: auto;
  2493. position: absolute;
  2494. left: 0;
  2495. right: 0;
  2496. top: 0;
  2497. bottom: 0;
  2498. }
  2499. </style>
  2500. <body class=fit>
  2501. <img onclick="document.body.classList.toggle('fit')" src="${ai.popup.src}">
  2502. </body>
  2503. `.replace(/\n\s*/g, '').replace(/\x20?([:>])\x20/g, '$1').replace(/#/g, '%23');
  2504. }
  2505. }
  2506.  
  2507. function setup({rule} = {}) {
  2508. const MPIV_BASE_URL = 'https://w9p.co/userscripts/mpiv/';
  2509. const SETUP_ID = `${PREFIX}setup`;
  2510. const RULE = setup.RULE || (setup.RULE = Symbol('rule'));
  2511. let div = doc.getElementById(SETUP_ID);
  2512. let root = div && div.shadowRoot;
  2513. let {blankRuleElement} = setup;
  2514. /** @type NodeList */
  2515. const UI = new Proxy({}, {
  2516. get(_, id) {
  2517. return root.getElementById(id);
  2518. },
  2519. });
  2520. if (!rule || !div)
  2521. init(new Config({save: true}));
  2522. if (rule)
  2523. installRule(rule);
  2524.  
  2525. function closeSetup(event) {
  2526. if (event && this.id !== 'x') {
  2527. cfg = collectConfig({save: true, clone: this.id === 'apply'});
  2528. Ruler.init();
  2529. if (this.id === 'apply')
  2530. return;
  2531. }
  2532. const el = doc.getElementById(SETUP_ID);
  2533. el && el.remove();
  2534. }
  2535.  
  2536. function collectConfig({save, clone} = {}) {
  2537. const delay = parseInt(UI.delay.value);
  2538. const scale = parseFloat(UI.scale.value.replace(',', '.'));
  2539. let data = {
  2540. css: UI.css.value.trim(),
  2541. delay: !isNaN(delay) && delay >= 0 ? delay : undefined,
  2542. hosts: collectRules(),
  2543. scale: !isNaN(scale) ? Math.max(1, scale) : undefined,
  2544. scales: UI.scales.value
  2545. .trim()
  2546. .split(/[,;]*\s+/)
  2547. .map(x => x.replace(',', '.'))
  2548. .filter(x => !isNaN(parseFloat(x))),
  2549. start: UI.start.value,
  2550. zoom: UI.zoom.value,
  2551. zoomOut: UI.zoomOut.value,
  2552. };
  2553. for (const el of $$('[type="checkbox"]', root))
  2554. data[el.id] = el.checked;
  2555. if (clone)
  2556. data = JSON.parse(JSON.stringify(data));
  2557. return new Config({data, save});
  2558. }
  2559.  
  2560. function collectRules() {
  2561. return [...UI.rules.children]
  2562. .map(el => [el.value.trim(), el[RULE]])
  2563. .sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
  2564. .map(([s, json]) => json || s)
  2565. .filter(Boolean);
  2566. }
  2567.  
  2568. function exportSettings(e) {
  2569. dropEvent(e);
  2570. const txt = $create('textarea', {
  2571. style: 'opacity:0; position:absolute',
  2572. value: JSON.stringify(collectConfig(), null, ' '),
  2573. });
  2574. root.appendChild(txt);
  2575. txt.select();
  2576. txt.focus();
  2577. document.execCommand('copy');
  2578. e.target.focus();
  2579. txt.remove();
  2580. UI.exportNotification.hidden = false;
  2581. setTimeout(() => (UI.exportNotification.hidden = true), 1000);
  2582. }
  2583.  
  2584. function importSettings(e) {
  2585. dropEvent(e);
  2586. const s = prompt('Paste settings:');
  2587. if (s)
  2588. init(new Config({data: s}));
  2589. }
  2590.  
  2591. function checkRule({target: el}) {
  2592. let json, error;
  2593. const prev = el.previousElementSibling;
  2594. if (el.value) {
  2595. json = Ruler.parse(el.value);
  2596. error = json instanceof Error && (json.message || String(json));
  2597. if (!prev)
  2598. el.insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  2599. } else if (prev) {
  2600. prev.focus();
  2601. el.remove();
  2602. }
  2603. el[RULE] = !error && json;
  2604. el.title = error || '';
  2605. el.setCustomValidity(error || '');
  2606. }
  2607.  
  2608. function focusRule({type, target: el, relatedTarget: from}) {
  2609. if (el === this)
  2610. return;
  2611. if (type === 'paste') {
  2612. setTimeout(() => focusRule.call(this, {target: el}));
  2613. return;
  2614. }
  2615. if (el[RULE])
  2616. el.value = Ruler.format(el[RULE], {expand: true});
  2617. const h = clamp(el.scrollHeight, 15, div.clientHeight / 4);
  2618. if (h > el.offsetHeight)
  2619. el.style.minHeight = h + 'px';
  2620. if (!this.contains(from))
  2621. from = [...$$('[style*="height"]', this)].find(_ => _ !== el);
  2622. if (from) {
  2623. from.style.minHeight = '';
  2624. if (from[RULE])
  2625. from.value = Ruler.format(from[RULE]);
  2626. }
  2627. }
  2628.  
  2629. function installRule(rule) {
  2630. const inputs = UI.rules.children;
  2631. let el = [...inputs].find(el => Util.deepEqual(el[RULE], rule));
  2632. if (!el) {
  2633. el = inputs[0];
  2634. el[RULE] = rule;
  2635. el.value = Ruler.format(rule);
  2636. el.hidden = false;
  2637. const i = Math.max(0, collectRules().indexOf(rule));
  2638. inputs[i].insertAdjacentElement('afterend', el);
  2639. inputs[0].insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  2640. }
  2641. const rect = el.getBoundingClientRect();
  2642. if (rect.bottom < 0 ||
  2643. rect.bottom > el.parentNode.offsetHeight)
  2644. el.scrollIntoView();
  2645. el.classList.add('highlight');
  2646. el.addEventListener('animationend', () => el.classList.remove('highlight'), {once: true});
  2647. el.focus();
  2648. }
  2649.  
  2650. function init(config) {
  2651. closeSetup();
  2652. div = $create('div', {
  2653. id: SETUP_ID,
  2654. // prevent the main page from interpreting key presses in inputs as hotkeys
  2655. // which may happen since it sees only the outer <div> in the event |target|
  2656. contentEditable: true,
  2657. });
  2658. root = div.attachShadow({mode: 'open'});
  2659. root.innerHTML = `
  2660. <style>
  2661. :host {
  2662. all: initial !important;
  2663. position: fixed !important;
  2664. z-index: 2147483647 !important;
  2665. top: 20px !important;
  2666. right: 20px !important;
  2667. padding: 20px 30px !important;
  2668. color: #000 !important;
  2669. background: #eee !important;
  2670. box-shadow: 5px 5px 25px 2px #000 !important;
  2671. width: 500px !important;
  2672. border: 1px solid black !important;
  2673. display: flex !important;
  2674. flex-direction: column !important;
  2675. }
  2676. main {
  2677. font: 12px/15px sans-serif;
  2678. }
  2679. ul {
  2680. max-height: calc(100vh - 200px);
  2681. margin: 10px 0 15px 0;
  2682. padding: 0;
  2683. list-style: none;
  2684. }
  2685. li {
  2686. margin: 0;
  2687. padding: .25em 0;
  2688. }
  2689. li.options {
  2690. display: flex;
  2691. align-items: center;
  2692. flex-wrap: wrap;
  2693. }
  2694. label {
  2695. display: inline-flex;
  2696. align-items: center;
  2697. }
  2698. label:not(:last-child) {
  2699. margin-right: 1em;
  2700. }
  2701. label > :not(span) {
  2702. margin-right: .25em;
  2703. }
  2704. label > :not(span):not(:first-child) {
  2705. margin-left: .5em;
  2706. }
  2707. input:first-child {
  2708. margin-left: 0;
  2709. }
  2710. input, select {
  2711. min-height: 1.6em;
  2712. box-sizing: border-box;
  2713. }
  2714. textarea {
  2715. flex: 1;
  2716. resize: vertical;
  2717. margin: 1px 0;
  2718. font: 11px/1.25 Consolas, monospace;
  2719. }
  2720. textarea:invalid {
  2721. background-color: #f002;
  2722. border-color: #800;
  2723. }
  2724. code {
  2725. font-weight: bold;
  2726. }
  2727. a {
  2728. text-decoration: none;
  2729. }
  2730. a:hover {
  2731. text-decoration: underline;
  2732. }
  2733. button {
  2734. padding: .2em 1em;
  2735. margin: 0 1em;
  2736. }
  2737. .column {
  2738. display: flex;
  2739. flex-direction: column;
  2740. }
  2741. .highlight {
  2742. animation: 2s fade-in cubic-bezier(0, .75, .25, 1);
  2743. animation-fill-mode: both;
  2744. }
  2745. #rules textarea {
  2746. word-break: break-all;
  2747. }
  2748. #x {
  2749. position: absolute;
  2750. top: 0;
  2751. right: 0;
  2752. padding: 4px 8px;
  2753. cursor: pointer;
  2754. user-select: none;
  2755. }
  2756. #x:hover {
  2757. background-color: #8884;
  2758. }
  2759. @keyframes fade-in {
  2760. from { background-color: deepskyblue }
  2761. to {}
  2762. }
  2763. @media (prefers-color-scheme: dark) {
  2764. :host {
  2765. color: #aaa !important;
  2766. background: #333 !important;
  2767. }
  2768. a {
  2769. color: deepskyblue;
  2770. }
  2771. textarea, input, select {
  2772. background: #111;
  2773. color: #BBB;
  2774. border-color: #555;
  2775. }
  2776. input[type="checkbox"] {
  2777. filter: invert(1);
  2778. }
  2779. }
  2780. </style>
  2781. <main>
  2782. <a href="${MPIV_BASE_URL}">${GM_info.script.name}</a>
  2783. <div id=x>x</div>
  2784. <ul class=column>
  2785. <li class=options>
  2786. <label>
  2787. <span>Popup:</span>
  2788. <select id=start>
  2789. <option value=auto>automatically
  2790. <option value=context>right click or ctrl
  2791. <option value=ctrl>ctrl
  2792. </select>
  2793. </label>
  2794. <label>
  2795. <span>after</span>
  2796. <input id=delay type=number min=0 max=10000 step=50 style="width: 4em">
  2797. <span>ms</span>
  2798. </label>
  2799. <label>
  2800. <input type=checkbox id=preload>
  2801. <span>Start preloading immediately</span>
  2802. </label>
  2803. </li>
  2804. <li class=options>
  2805. <label>
  2806. <span>Zoom:</span>
  2807. <select id=zoom>
  2808. <option value=context>right click or shift
  2809. <option value=wheel>wheel up or shift
  2810. <option value=shift>shift
  2811. <option value=auto>automatically
  2812. </select>
  2813. </label>
  2814. <label>
  2815. <span>When zoomed out completely</span>
  2816. <select id=zoomOut>
  2817. <option value=stay>stay in zoom mode
  2818. <option value=auto>stay if still hovered
  2819. <option value=close>close popup
  2820. </select>
  2821. </label>
  2822. </li>
  2823. <li class=options>
  2824. <label>
  2825. <span>Only show popup over scaled-down image when natural size is</span>
  2826. <input id=scale type=number min=1 max=100 step=.05 style="width: 4em;">
  2827. <span>times larger</span>
  2828. </label>
  2829. </li>
  2830. <li class=options>
  2831. <label>
  2832. <span>Custom scale factors:</span>
  2833. <input id=scales style="width: 18em" placeholder="${Config.DEFAULTS.scales.join(' ')}">
  2834. <span title="${`
  2835. 0 = fit to window
  2836. 0! = same as 0 but also removes smaller values
  2837. * after value marks default zoom factor, for example: 1*
  2838. Values smaller than non-zoomed size are ignored.
  2839. `.trim().replace(/\n\s+/g, '\n')}" style="cursor:help">(?)</span>
  2840. </label>
  2841. </li>
  2842. <li class=options>
  2843. <label><input type=checkbox id=center><span>Always centered</span></label>
  2844. <label><input type=checkbox id=imgtab><span>Run in image tabs</span></label>
  2845. <label title="Disable only if you spoof the HTTP headers yourself">
  2846. <input type=checkbox id=xhr>
  2847. <span>Anti-hotlinking workaround</span>
  2848. </label>
  2849. <label>
  2850. <input type=checkbox id=globalStatus>
  2851. <span>Expose status on &lt;html&gt; node (note: may cause noticeable slowdown)</small>
  2852. </label>
  2853. </li>
  2854. <li>
  2855. <a href="${MPIV_BASE_URL}css.html">Custom CSS:</a>
  2856. e.g. <code>#mpiv-popup.mpiv-show { animation: none }</code>
  2857. <div class=column>
  2858. <textarea id=css spellcheck=false></textarea>
  2859. </div>
  2860. </li>
  2861. <li style="display: flex; justify-content: space-between;">
  2862. <div><a href="${MPIV_BASE_URL}host_rules.html">Custom host rules:</a></div>
  2863. <div style="white-space: nowrap">
  2864. To disable, put any symbol except <code>a..z 0..9 - .</code><br>
  2865. in "d" value, for example <code>"d": "!foo.com"</code>
  2866. </div>
  2867. <div>
  2868. <input id=search type=search placeholder=Search style="width: 10em; margin-left: 1em">
  2869. </div>
  2870. </li>
  2871. <li style="margin-left: -3px; margin-right: -3px; overflow-y: auto;
  2872. padding-left: 3px; padding-right: 3px; ">
  2873. <div id="rules" class="column">
  2874. <textarea rows="1" spellcheck="false"></textarea>
  2875. </div>
  2876. </li>
  2877. <li>
  2878. <div hidden id=installLoading>Loading...</div>
  2879. <div hidden id=installHint>Double-click the rule (or select and press Enter) to add it.
  2880. Click OK when done.</div>
  2881. <a href="${MPIV_BASE_URL}more_host_rules.html" id=install>Install rule from repository...</a>
  2882. </li>
  2883. </ul>
  2884. <div style="text-align:center">
  2885. <button id=ok accesskey=s>Save</button>
  2886. <button id=apply accesskey=a>Apply</button>
  2887. <button id=import style="margin-right: 0">Import</button>
  2888. <button id=export style="margin-left: 0">Export</button>
  2889. <button id=cancel>Cancel</button>
  2890. <div id=exportNotification hidden style="color: green; font-weight: bold;
  2891. position: absolute; bottom: 2px; left: 0; right: 0;">Copied to clipboard.</div>
  2892. </div>
  2893. </main>
  2894. `;
  2895. // rules
  2896. const rules = UI.rules;
  2897. rules.addEventListener('input', checkRule);
  2898. rules.addEventListener('focusin', focusRule);
  2899. rules.addEventListener('paste', focusRule);
  2900. blankRuleElement =
  2901. setup.blankRuleElement =
  2902. setup.blankRuleElement || rules.firstElementChild.cloneNode();
  2903. for (const rule of config.hosts || []) {
  2904. const el = blankRuleElement.cloneNode();
  2905. el.value = typeof rule === 'string' ? rule : Ruler.format(rule);
  2906. rules.appendChild(el);
  2907. checkRule({target: el});
  2908. }
  2909. // search rules
  2910. const search = UI.search;
  2911. search.oninput = () => {
  2912. setup.search = search.value;
  2913. const s = search.value.toLowerCase();
  2914. for (const el of rules.children)
  2915. el.hidden = s && !el.value.toLowerCase().includes(s);
  2916. };
  2917. search.value = setup.search || '';
  2918. if (search.value)
  2919. search.oninput();
  2920. // prevent the main page from interpreting key presses in inputs as hotkeys
  2921. // which may happen since it sees only the outer <div> in the event |target|
  2922. root.addEventListener('keydown', e =>
  2923. !e.altKey && !e.ctrlKey && !e.metaKey && e.stopPropagation(), true);
  2924. UI.apply.onclick = UI.cancel.onclick = UI.ok.onclick = UI.x.onclick = closeSetup;
  2925. UI.css.value = config.css;
  2926. UI.delay.value = config.delay;
  2927. UI.export.onclick = exportSettings;
  2928. UI.import.onclick = importSettings;
  2929. UI.install.onclick = setupRuleInstaller;
  2930. UI.scale.value = config.scale;
  2931. UI.scales.value = config.scales.join(' ');
  2932. UI.start.value = config.start;
  2933. UI.start.onchange = function () {
  2934. UI.delay.closest('label').hidden =
  2935. UI.preload.closest('label').hidden =
  2936. this.value !== 'auto';
  2937. };
  2938. UI.start.onchange();
  2939. UI.xhr.onclick = ({target: el}) => el.checked || confirm(el.closest('[title]').title);
  2940. UI.zoom.value = config.zoom;
  2941. UI.zoomOut.value = config.zoomOut;
  2942. for (const el of $$('[type="checkbox"]', root))
  2943. el.checked = config[el.id];
  2944. for (const el of $$('a[href^="http"]', root)) {
  2945. el.target = '_blank';
  2946. el.rel = 'noreferrer noopener external';
  2947. }
  2948. doc.body.appendChild(div);
  2949. requestAnimationFrame(() => {
  2950. UI.css.style.minHeight = clamp(UI.css.scrollHeight, 40, div.clientHeight / 4) + 'px';
  2951. });
  2952. }
  2953. }
  2954.  
  2955. async function setupRuleInstaller(e) {
  2956. dropEvent(e);
  2957. const parent = this.parentElement;
  2958. parent.children.installLoading.hidden = false;
  2959. this.remove();
  2960. let rules;
  2961.  
  2962. try {
  2963. rules = extractRules((await Remoting.getDoc(this.href)).doc);
  2964. const selector = $create('select', {
  2965. size: 8,
  2966. style: 'width: 100%',
  2967. ondblclick: e => e.target !== selector && maybeSetup(e),
  2968. onkeyup: e => e.key === 'Enter' && maybeSetup(e),
  2969. });
  2970. selector.append(...rules.map(renderRule));
  2971. selector.selectedIndex = findMatchingRuleIndex();
  2972. // remove "name" since the installed rules don't need it
  2973. for (const r of rules)
  2974. delete r.name;
  2975. parent.children.installLoading.remove();
  2976. parent.children.installHint.hidden = false;
  2977. parent.appendChild(selector);
  2978. } catch (e) {
  2979. parent.textContent = 'Error loading rules: ' + (e.message || e);
  2980. }
  2981.  
  2982. function extractRules(doc) {
  2983. const code = $('script', doc).textContent;
  2984. // sort by name
  2985. return JSON.parse(code.match(/var\s+rules\s*=\s*(\[.+]);?[\r\n]/)[1])
  2986. .filter(r => !r.d || hostname.includes(r.d))
  2987. .sort((a, b) =>
  2988. (a = a.name.toLowerCase()) < (b = b.name.toLowerCase()) ? -1 :
  2989. a > b ? 1 :
  2990. 0);
  2991. }
  2992.  
  2993. function findMatchingRuleIndex() {
  2994. // get the core part of the current domain that's not "www", "m", etc.
  2995. const h = hostname.split('.');
  2996. const core = h[0] === 'www' || h.length > 2 && h[0].length === 1 ? h[1] : h[0];
  2997. // find a rule matching the domain core
  2998. return rules.findIndex(r =>
  2999. r.name.toLowerCase().includes(core) ||
  3000. r.d && hostname.includes(r.d));
  3001. }
  3002.  
  3003. function renderRule(r) {
  3004. const {name, ...copy} = r;
  3005. return $create('option', {
  3006. textContent: name,
  3007. title: Ruler.format(copy, {expand: true})
  3008. .replace(/^{|\s*}$/g, '')
  3009. .split('\n')
  3010. .slice(0, 12)
  3011. .map(renderTitleLine)
  3012. .filter(Boolean)
  3013. .join('\n'),
  3014. });
  3015. }
  3016.  
  3017. function renderTitleLine(line, i, arr) {
  3018. return (
  3019. // show ... on 10th line if there are more lines
  3020. i === 9 && arr.length > 10 ? '...' :
  3021. i > 10 ? '' :
  3022. // truncate to 100 chars
  3023. (line.length > 100 ? line.slice(0, 100) + '...' : line)
  3024. // strip the leading space
  3025. .replace(/^\s/, ''));
  3026. }
  3027.  
  3028. function maybeSetup(e) {
  3029. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey)
  3030. setup({rule: rules[e.currentTarget.selectedIndex]});
  3031. }
  3032. }
  3033.  
  3034. App.init();