Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前为 2020-01-29 提交的版本。查看 最新版本

  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.14
  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. dotDomain.endsWith('.instagram.com') && {
  747. e: [
  748. 'a[href*="/p/"]',
  749. 'a[role="button"][data-reactid*="scontent-"]',
  750. 'article div',
  751. 'article div div img',
  752. ],
  753. s: (m, node, rule) => {
  754. const {a, data} = rule._getData(node) || {};
  755. rule.follow = !data;
  756. return (
  757. !a ? false :
  758. !data ? a.href :
  759. data.video_url || data.display_url);
  760. },
  761. c: (html, doc, node, rule) =>
  762. tryCatch(() => rule._getData(node).data.edge_media_to_caption.edges[0].node.text) || '',
  763. follow: true,
  764. _getData(node) {
  765. const n = node.closest('a[href*="/p/"], article');
  766. if (!n)
  767. return;
  768. const a = n.tagName === 'A' ? n : $('a[href*="/p/"]', n);
  769. if (!a)
  770. return;
  771. try {
  772. const shortcode = a.pathname.match(/\/p\/(\w+)/)[1];
  773. return {
  774. a,
  775. data: unsafeWindow._sharedData.entry_data.ProfilePage[0]
  776. .graphql.user.edge_owner_to_timeline_media.edges
  777. .find(e => e.node.shortcode === shortcode)
  778. .node,
  779. };
  780. } catch (e) {
  781. return {a};
  782. }
  783. },
  784. },
  785. dotDomain.endsWith('.reddit.com') && {
  786. u: '||i.reddituploads.com/',
  787. },
  788. dotDomain.endsWith('.reddit.com') && {
  789. r: /(preview\.redd\.it\/\w+\.(jpe?g|png|gif))/,
  790. s: 'https://i.$1',
  791. },
  792. dotDomain.endsWith('.tumblr.com') && {
  793. e: 'div.photo_stage_img, div.photo_stage > canvas',
  794. s: (m, node) => /http[^"]+/.exec(node.style.cssText + node.getAttribute('data-img-src'))[0],
  795. follow: true,
  796. },
  797. dotDomain.endsWith('.tweetdeck.twitter.com') && {
  798. e: 'a.media-item, a.js-media-image-link',
  799. s: (m, node) => /http[^)]+/.exec(node.style.backgroundImage)[0],
  800. follow: true,
  801. },
  802. dotDomain.endsWith('.twitter.com') && {
  803. e: '.grid-tweet > .media-overlay',
  804. s: (m, node) => node.previousElementSibling.src,
  805. follow: true,
  806. },
  807. ];
  808.  
  809. const main = [
  810. {
  811. r: /[/?=](https?[^&]+)/,
  812. s: '$1',
  813. follow: true,
  814. },
  815. {
  816. u: [
  817. '||500px.com/photo/',
  818. '||cl.ly/',
  819. '||cweb-pix.com/',
  820. '||ibb.co/',
  821. '||imgcredit.xyz/image/',
  822. ],
  823. r: /\.\w+\/.+/,
  824. q: 'meta[property="og:image"]',
  825. },
  826. {
  827. u: 'attachment.php',
  828. r: /attachment\.php.+attachmentid/,
  829. },
  830. {
  831. u: '||abload.de/image',
  832. q: '#image',
  833. },
  834. {
  835. u: '||deviantart.com/art/',
  836. s: (m, node) =>
  837. /\b(film|lit)/.test(node.className) || /in Flash/.test(node.title) ?
  838. '' :
  839. m.input,
  840. q: [
  841. '#download-button[href*=".jpg"]',
  842. '#download-button[href*=".jpeg"]',
  843. '#download-button[href*=".gif"]',
  844. '#download-button[href*=".png"]',
  845. '#gmi-ResViewSizer_fullimg',
  846. 'img.dev-content-full',
  847. ],
  848. },
  849. {
  850. u: '||dropbox.com/s',
  851. r: /com\/sh?\/.+\.(jpe?g|gif|png)/i,
  852. q: (text, doc) =>
  853. $prop('img.absolute-center', 'src', doc).replace(/(size_mode)=\d+/, '$1=5') || false,
  854. },
  855. {
  856. r: /[./]ebay\.[^/]+\/itm\//,
  857. q: text =>
  858. text.match(/https?:\/\/i\.ebayimg\.com\/[^.]+\.JPG/i)[0]
  859. .replace(/~~60_\d+/, '~~60_57'),
  860. },
  861. {
  862. u: '||i.ebayimg.com/',
  863. s: (m, node) =>
  864. $('.zoom_trigger_mask', node.parentNode) ? '' :
  865. m.input.replace(/~~60_\d+/, '~~60_57'),
  866. },
  867. {
  868. u: [
  869. '||fastpic.ru/big',
  870. '||fastpic.ru/thumb',
  871. ],
  872. r: /\/\/(?:i(\d+)\.)?([^/]+\/)(big|thumb|view)\/([^.]+?)\.(\w+)/,
  873. s: (m, node, rule) => {
  874. const a = node.closest('[href*="fastpic.ru"]');
  875. const am = a && rule.r.exec(decodeURIComponent(a.href)) || [];
  876. const p = a && am[4].split('/');
  877. return `https://i${am[1] || m[1] || am[3] === 'view' && p[0]}.${m[2]}big/${
  878. am[3] === 'big' ? am[4] : m[4]}.${am[5] || m[5]}?noht=1`;
  879. },
  880. xhr: () => 'https://fastpic.ru',
  881. },
  882. {
  883. u: '||fastpic.ru/view/',
  884. q: 'img[src*="/big/"]',
  885. xhr: true,
  886. },
  887. {
  888. u: '||facebook.com/',
  889. r: /photo\.php|[^/]+\/photos\//,
  890. s: (m, node) =>
  891. node.id === 'fbPhotoImage' ? false :
  892. /gradient\.png$/.test(m.input) ? '' :
  893. m.input.replace('www.facebook.com', 'mbasic.facebook.com'),
  894. q: [
  895. 'div + span > a:first-child:not([href*="tag_faces"])',
  896. 'div + span > a[href*="tag_faces"] ~ a',
  897. ],
  898. rect: '#fbProfileCover',
  899. },
  900. {
  901. u: '||fbcdn.',
  902. r: /fbcdn.+?[0-9]+_([0-9]+)_[0-9]+_[a-z]\.(jpg|png)/,
  903. s: m =>
  904. dotDomain.endsWith('.facebook.com') &&
  905. tryCatch(() => unsafeWindow.PhotoSnowlift.getInstance().stream.cache.image[m[1]].url) ||
  906. false,
  907. manual: true,
  908. },
  909. {
  910. u: ['||fbcdn-', 'fbcdn.net/'],
  911. r: /(https?:\/\/(fbcdn-[-\w.]+akamaihd|[-\w.]+?fbcdn)\.net\/[-\w/.]+?)_[a-z]\.(jpg|png)(\?[0-9a-zA-Z0-9=_&]+)?/,
  912. s: (m, node) => {
  913. if (node.id === 'fbPhotoImage') {
  914. const a = $('a.fbPhotosPhotoActionsItem[href$="dl=1"]', doc.body);
  915. if (a)
  916. return a.href.includes(m.input.match(/[0-9]+_[0-9]+_[0-9]+/)[0]) ? '' : a.href;
  917. }
  918. if (m[4])
  919. return false;
  920. if (node.parentNode.outerHTML.includes('/hovercard/'))
  921. return '';
  922. const gp = node.parentNode.parentNode;
  923. if (node.outerHTML.includes('profile') && gp.href.includes('/photo'))
  924. return false;
  925. return m[1].replace(/\/[spc][\d.x]+/g, '').replace('/v/', '/') + '_n.' + m[3];
  926. },
  927. rect: '.photoWrap',
  928. },
  929. {
  930. u: '||flickr.com/photos/',
  931. r: /photos\/([0-9]+@N[0-9]+|[a-z0-9_-]+)\/([0-9]+)/,
  932. s: m =>
  933. m.input.indexOf('/sizes/') < 0 ?
  934. `https://www.flickr.com/photos/${m[1]}/${m[2]}/sizes/sq/` :
  935. false,
  936. q: (text, doc) => {
  937. const links = $$('.sizes-list a', doc);
  938. return 'https://www.flickr.com' + links[links.length - 1].getAttribute('href');
  939. },
  940. follow: true,
  941. },
  942. {
  943. u: '||flickr.com/photos/',
  944. r: /\/sizes\//,
  945. q: '#allsizes-photo > img',
  946. },
  947. {
  948. u: '||gfycat.com/',
  949. r: /(gfycat\.com\/)(gifs\/detail\/|iframe\/)?([a-z]+)/i,
  950. s: 'https://$1$3',
  951. q: [
  952. 'meta[content$=".webm"]',
  953. '#webmsource',
  954. 'source[src$=".webm"]',
  955. ],
  956. },
  957. {
  958. u: [
  959. '||googleusercontent.com/proxy',
  960. '||googleusercontent.com/gadgets/proxy',
  961. ],
  962. r: /\.com\/(proxy|gadgets\/proxy.+?(http.+?)&)/,
  963. s: m => m[2] ? decodeURIComponent(m[2]) : m.input.replace(/w\d+-h\d+($|-p)/, 'w0-h0'),
  964. },
  965. {
  966. u: [
  967. '||googleusercontent.com/',
  968. '||ggpht.com/',
  969. ],
  970. s: (m, node) =>
  971. m.input.includes('webcache.') ||
  972. 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/) ||
  973. node.matches('.g-hovercard *, a[href*="profile_redirector"] > img') ?
  974. '' :
  975. m.input.replace(/\/s\d{2,}-[^/]+|\/w\d+-h\d+/, '/s0')
  976. .replace(/=[-\w]*\d+([&#].*|$)/, ''),
  977. },
  978. {
  979. u: '||gravatar.com/',
  980. r: /([a-z0-9]{32})/,
  981. s: 'https://gravatar.com/avatar/$1?s=200',
  982. },
  983. {
  984. u: '//gyazo.com/',
  985. r: /\.com\/\w{32,}/,
  986. q: 'meta[name="twitter:image"]',
  987. xhr: true,
  988. },
  989. {
  990. u: '||hostingkartinok.com/show-image.php',
  991. q: '.image img',
  992. },
  993. {
  994. u: [
  995. '||imagecurl.com/images/',
  996. '||imagecurl.com/viewer.php',
  997. ],
  998. r: /(?:images\/(\d+)_thumb|file=(\d+))(\.\w+)/,
  999. s: 'https://imagecurl.com/images/$1$2$3',
  1000. },
  1001. {
  1002. u: '||imagebam.com/image/',
  1003. q: 'meta[property="og:image"]',
  1004. tabfix: true,
  1005. xhr: hostname.includes('planetsuzy'),
  1006. },
  1007. {
  1008. u: '||imageban.ru/thumbs',
  1009. r: /(.+?\/)thumbs(\/\d+)\.(\d+)\.(\d+\/.*)/,
  1010. s: '$1out$2/$3/$4',
  1011. },
  1012. {
  1013. u: [
  1014. '||imageban.ru/show',
  1015. '||imageban.net/show',
  1016. '||ibn.im/',
  1017. ],
  1018. q: '#img_main',
  1019. },
  1020. {
  1021. u: '||imageshack.us/img',
  1022. r: /img(\d+)\.(imageshack\.us)\/img\\1\/\d+\/(.+?)\.th(.+)$/,
  1023. s: 'https://$2/download/$1/$3$4',
  1024. },
  1025. {
  1026. u: '||imageshack.us/i/',
  1027. q: '#share-dl',
  1028. },
  1029. {
  1030. u: '||imageteam.org/img',
  1031. q: 'img[alt="image"]',
  1032. },
  1033. {
  1034. u: [
  1035. '||imagetwist.com/',
  1036. '||imageshimage.com/',
  1037. ],
  1038. r: /(\/\/|^)[^/]+\/[a-z0-9]{8,}/,
  1039. q: 'img.pic',
  1040. xhr: true,
  1041. },
  1042. {
  1043. u: '||imageupper.com/i/',
  1044. q: '#img',
  1045. xhr: true,
  1046. },
  1047. {
  1048. u: '||imagevenue.com/img.php',
  1049. q: '#thepic',
  1050. },
  1051. {
  1052. u: '||imagezilla.net/show/',
  1053. q: '#photo',
  1054. xhr: true,
  1055. },
  1056. {
  1057. u: [
  1058. '||images-na.ssl-images-amazon.com/images/',
  1059. '||media-imdb.com/images/',
  1060. ],
  1061. r: /images\/.+?\.jpg/,
  1062. s: '/V1\\.?_.+?\\.//g',
  1063. },
  1064. {
  1065. u: '||imgbox.com/',
  1066. r: /\.com\/([a-z0-9]+)$/i,
  1067. q: '#img',
  1068. xhr: hostname !== 'imgbox.com',
  1069. },
  1070. {
  1071. u: '||imgclick.net/',
  1072. r: /\.net\/(\w+)/,
  1073. q: 'img.pic',
  1074. xhr: true,
  1075. post: m => `op=view&id=${m[1]}&pre=1&submit=Continue%20to%20image...`,
  1076. },
  1077. {
  1078. u: [
  1079. '||imgflip.com/i/',
  1080. '||imgflip.com/gif/',
  1081. ],
  1082. r: /\/(i|gif)\/([^/?#]+)/,
  1083. s: m => `https://i.imgflip.com/${m[2]}${m[1] === 'i' ? '.jpg' : '.mp4'}`,
  1084. },
  1085. {
  1086. u: [
  1087. '||imgur.com/a/',
  1088. '||imgur.com/gallery/',
  1089. '||imgur.com/t/',
  1090. ],
  1091. g: async (text, doc, url, m, rule, cb) => {
  1092. // simplified extraction of JSON as it occupies only one line
  1093. if (!/(?:mergeConfig\('gallery',\s*|Imgur\.Album\.getInstance\()[\s\S]*?[,\s{"'](?:image|album)\s*:\s*({[^\r\n]+?}),?[\r\n]/.test(text))
  1094. return;
  1095. const info = JSON.parse(RegExp.$1);
  1096. let images = info.is_album ? info.album_images.images : [info];
  1097. if (info.num_images > images.length) {
  1098. const url = `https://imgur.com/ajaxalbums/getimages/${info.hash}/hit.json?all=true`;
  1099. images = JSON.parse((await Remoting.gmXhr(url)).responseText).data.images;
  1100. }
  1101. const items = [];
  1102. for (const img of images || []) {
  1103. const u = `https://i.imgur.com/${img.hash}`;
  1104. items.push({
  1105. url: img.ext === '.gif' && img.animated !== false ?
  1106. [`${u}.webm`, `${u}.mp4`, u] :
  1107. u + img.ext,
  1108. desc: [img.title, img.description].filter(Boolean).join(' - '),
  1109. });
  1110. }
  1111. if (images && info.is_album && !safeIncludes(items[0].desc, info.title))
  1112. items.title = info.title;
  1113. cb(items);
  1114. },
  1115. css: '.post > .hover { display:none!important; }',
  1116. },
  1117. {
  1118. u: '||imgur.com/',
  1119. r: /((?:[a-z]{2,}\.)?imgur\.com\/)((?:\w+,)+\w*)/,
  1120. s: 'gallery',
  1121. g: (text, doc, url, m) =>
  1122. m[2].split(',').map(id => ({
  1123. url: `https://i.${m[1]}${id}.jpg`,
  1124. })),
  1125. },
  1126. {
  1127. u: '||imgur.com/',
  1128. r: /([a-z]{2,}\.)?imgur\.com\/(r\/[a-z]+\/|[a-z0-9]+#)?([a-z0-9]{5,})($|\?|\.([a-z]+))/i,
  1129. s: (m, node) => {
  1130. if (/memegen|random|register|search|signin/.test(m.input))
  1131. return '';
  1132. const a = node.closest('a');
  1133. if (a && a !== node && /(i\.([a-z]+\.)?)?imgur\.com\/(a\/|gallery\/)?/.test(a.href))
  1134. return false;
  1135. const id = m[3].replace(/(.{7})[bhm]$/, '$1');
  1136. const ext = m[5] ? m[5].replace(/gifv?/, 'webm') : 'jpg';
  1137. const u = `https://i.${(m[1] || '').replace('www.', '')}imgur.com/${id}.`;
  1138. return ext === 'webm' ?
  1139. [`${u}webm`, `${u}mp4`, `${u}gif`] :
  1140. u + ext;
  1141. },
  1142. },
  1143. {
  1144. u: [
  1145. '||instagr.am/p/',
  1146. '||instagram.com/p/',
  1147. ],
  1148. s: m => m.input.substr(0, m.input.lastIndexOf('/')) + '/?__a=1',
  1149. q: text => {
  1150. const m = JSON.parse(text).graphql.shortcode_media;
  1151. return m.video_url || m.display_url;
  1152. },
  1153. rect: 'div.PhotoGridMediaItem',
  1154. c: text => {
  1155. const m = JSON.parse(text).graphql.shortcode_media.edge_media_to_caption.edges[0];
  1156. return m === undefined ? '(no caption)' : m.node.text;
  1157. },
  1158. },
  1159. {
  1160. u: [
  1161. '||livememe.com/',
  1162. '||lvme.me/',
  1163. ],
  1164. r: /\.\w+\/([^.]+)$/,
  1165. s: 'http://i.lvme.me/$1.jpg',
  1166. },
  1167. {
  1168. u: '||lostpic.net/image',
  1169. q: '.image-viewer-image img',
  1170. },
  1171. {
  1172. u: '||makeameme.org/meme/',
  1173. r: /\/meme\/([^/?#]+)/,
  1174. s: 'https://media.makeameme.org/created/$1.jpg',
  1175. },
  1176. {
  1177. u: '||photobucket.com/',
  1178. r: /(\d+\.photobucket\.com\/.+\/)(\?[a-z=&]+=)?(.+\.(jpe?g|png|gif))/,
  1179. s: 'https://i$1$3',
  1180. xhr: !dotDomain.endsWith('.photobucket.com'),
  1181. },
  1182. {
  1183. u: '||piccy.info/view3/',
  1184. r: /(.+?\/view3)\/(.*)\//,
  1185. s: '$1/$2/orig/',
  1186. q: '#mainim',
  1187. },
  1188. {
  1189. u: '||pimpandhost.com/image/',
  1190. r: /(.+?\/image\/[0-9]+)/,
  1191. s: '$1?size=original',
  1192. q: 'img.original',
  1193. },
  1194. {
  1195. u: [
  1196. '||pixroute.com/',
  1197. '||imgspice.com/',
  1198. ],
  1199. r: /\.html$/,
  1200. q: 'img[id]',
  1201. xhr: true,
  1202. },
  1203. {
  1204. u: '||postima',
  1205. r: /postima?ge?\.org\/image\/\w+/,
  1206. q: [
  1207. 'a[href*="dl="]',
  1208. '#main-image',
  1209. ],
  1210. },
  1211. {
  1212. u: [
  1213. '||prntscr.com/',
  1214. '||prnt.sc/',
  1215. ],
  1216. r: /\.\w+\/.+/,
  1217. q: 'meta[property="og:image"]',
  1218. xhr: true,
  1219. },
  1220. {
  1221. u: '||radikal.ru/',
  1222. r: /\.ru\/(fp|.+\.html)/,
  1223. q: text => text.match(/http:\/\/[a-z0-9]+\.radikal\.ru[a-z0-9/]+\.(jpg|gif|png)/i)[0],
  1224. },
  1225. {
  1226. u: '||tumblr.com',
  1227. r: /_500\.jpg/,
  1228. s: ['/_500/_1280/', ''],
  1229. },
  1230. {
  1231. u: '||twimg.com/',
  1232. r: /\/profile_images/i,
  1233. s: '/_(reasonably_small|normal|bigger|\\d+x\\d+)\\././g',
  1234. },
  1235. {
  1236. u: '||twimg.com/media/',
  1237. r: /.+?format=(jpe?g|png|gif)/i,
  1238. s: '$0&name=large',
  1239. },
  1240. {
  1241. u: '||twimg.com/1/proxy',
  1242. r: /t=([^&_]+)/i,
  1243. s: m => atob(m[1]).match(/http.+/),
  1244. },
  1245. {
  1246. u: '||pic.twitter.com/',
  1247. r: /\.com\/[a-z0-9]+/i,
  1248. q: text => text.match(/https?:\/\/twitter\.com\/[^/]+\/status\/\d+\/photo\/\d+/i)[0],
  1249. follow: true,
  1250. },
  1251. {
  1252. u: '||twitpic.com/',
  1253. r: /\.com(\/show\/[a-z]+)?\/([a-z0-9]+)($|#)/i,
  1254. s: 'https://twitpic.com/show/large/$2',
  1255. },
  1256. {
  1257. u: '||upix.me/files',
  1258. s: '/#//',
  1259. },
  1260. {
  1261. u: '||wiki',
  1262. r: /\/(thumb|images)\/.+\.(jpe?g|gif|png|svg)\/(revision\/)?/i,
  1263. s: '/\\/thumb(?=\\/)|' +
  1264. '\\/scale-to-width(-[a-z]+)?\\/[0-9]+|' +
  1265. '\\/revision\\/latest|\\/[^\\/]+$//g',
  1266. xhr: !hostname.includes('wiki'),
  1267. },
  1268. {
  1269. u: '||ytimg.com/vi/',
  1270. r: /(.+?\/vi\/[^/]+)/,
  1271. s: '$1/0.jpg',
  1272. rect: '.video-list-item',
  1273. },
  1274. {
  1275. u: '/viewer.php?file=',
  1276. r: /(.+?)\/viewer\.php\?file=(.+)/,
  1277. s: '$1/images/$2',
  1278. xhr: true,
  1279. },
  1280. {
  1281. u: '/thumb_',
  1282. r: /\/albums.+\/thumb_[^/]/,
  1283. s: '/thumb_//',
  1284. },
  1285. {
  1286. u: [
  1287. '.th.jp',
  1288. '.th.gif',
  1289. '.th.png',
  1290. ],
  1291. r: /(.+?\.)th\.(jpe?g?|gif|png|svg|webm)$/i,
  1292. s: '$1$2',
  1293. follow: true,
  1294. },
  1295. {
  1296. u: [
  1297. '.jp',
  1298. '.gif',
  1299. '.png',
  1300. '.svg',
  1301. '.webm',
  1302. ],
  1303. r: /[^?:]+\.(jpe?g?|gif|png|svg|webm)($|\?)/i,
  1304. },
  1305. ];
  1306.  
  1307. /** @type mpiv.HostRule[] */
  1308. Ruler.rules = [].concat(customRules, disablers, perDomain, main).filter(Boolean);
  1309. }
  1310.  
  1311. static format(rule, {expand} = {}) {
  1312. const s = JSON.stringify(rule, null, ' ');
  1313. return expand ?
  1314. /* {"a": ...,
  1315. "b": ...,
  1316. "c": ...
  1317. } */
  1318. s.replace(/^{\s+/g, '{') :
  1319. /* {"a": ..., "b": ..., "c": ...} */
  1320. s.replace(/\n\s*/g, ' ').replace(/^({)\s|\s+(})$/g, '$1$2');
  1321. }
  1322.  
  1323. /** @returns mpiv.HostRule | Error | false | undefined */
  1324. static parse(rule) {
  1325. const isBatchOp = this instanceof Map;
  1326. try {
  1327. if (typeof rule === 'string')
  1328. rule = JSON.parse(rule);
  1329. if ('d' in rule && typeof rule.d !== 'string')
  1330. rule.d = undefined;
  1331. else if (isBatchOp && rule.d && !hostname.includes(rule.d))
  1332. return false;
  1333. const compileTo = isBatchOp ? rule : {};
  1334. if (rule.r)
  1335. compileTo.r = new RegExp(rule.r, 'i');
  1336. if (RX_HAS_CODE.test(rule.s))
  1337. compileTo.s = Util.newFunction('m', 'node', 'rule', rule.s);
  1338. if (RX_HAS_CODE.test(rule.q))
  1339. compileTo.q = Util.newFunction('text', 'doc', 'node', 'rule', rule.q);
  1340. if (RX_HAS_CODE.test(rule.c))
  1341. compileTo.c = Util.newFunction('text', 'doc', 'node', 'rule', rule.c);
  1342. return rule;
  1343. } catch (e) {
  1344. if (!e.message.includes('unsafe-eval'))
  1345. if (isBatchOp) {
  1346. this.set(rule, e);
  1347. } else {
  1348. return e;
  1349. }
  1350. }
  1351. }
  1352.  
  1353. static runQ(text, doc, docUrl) {
  1354. let url;
  1355. if (typeof ai.rule.q === 'function') {
  1356. url = ai.rule.q(text, doc, ai.node, ai.rule);
  1357. if (Array.isArray(url)) {
  1358. ai.urls = url.slice(1);
  1359. url = url[0];
  1360. }
  1361. } else {
  1362. const el = $many(ai.rule.q, doc);
  1363. url = el && Remoting.findFileUrl(el, docUrl);
  1364. }
  1365. return url;
  1366. }
  1367.  
  1368. static runS(node, rule, m) {
  1369. let urls = [];
  1370. for (const s of ensureArray(rule.s))
  1371. urls.push(
  1372. typeof s === 'string' ? Util.maybeDecodeURL(Ruler.substituteSingle(s, m)) :
  1373. typeof s === 'function' ? s(m, node, rule) :
  1374. s);
  1375. if (rule.q && urls.length > 1) {
  1376. console.warn('Rule discarded: "s" array is not allowed with "q"\n%o', rule);
  1377. return {skipRule: true};
  1378. }
  1379. if (Array.isArray(urls[0]))
  1380. urls = urls[0];
  1381. // `false` returned by "s" property means "skip this rule"
  1382. // any other falsy value (like say "") means "stop all rules"
  1383. return urls[0] === false ? {skipRule: true} : urls.map(Util.maybeDecodeURL);
  1384. }
  1385.  
  1386. static substituteSingle(s, m) {
  1387. if (!m)
  1388. return s;
  1389. if (s.startsWith('/') && !s.startsWith('//')) {
  1390. const mid = s.search(/[^\\]\//) + 1;
  1391. const end = s.lastIndexOf('/');
  1392. const re = new RegExp(s.slice(1, mid), s.slice(end + 1));
  1393. return m.input.replace(re, s.slice(mid + 1, end));
  1394. }
  1395. if (m.length && s.includes('$')) {
  1396. const maxLength = Math.floor(Math.log10(m.length)) + 1;
  1397. s = s.replace(/\$(\d{1,3})/g, (text, num) => {
  1398. for (let i = maxLength; i >= 0; i--) {
  1399. const part = num.slice(0, i) | 0;
  1400. if (part < m.length)
  1401. return (m[part] || '') + num.slice(i);
  1402. }
  1403. return text;
  1404. });
  1405. }
  1406. return s;
  1407. }
  1408. }
  1409.  
  1410. const SimpleUrlMatcher = (() => {
  1411. // string-to-regexp escaped chars
  1412. const RX_ESCAPE = /[.+*?(){}[\]^$|]/g;
  1413. // rx for '^' symbol in simple url match
  1414. const RX_SEP = /[^\w%._-]/g;
  1415. const RXS_SEP = RX_SEP.source;
  1416. return match => {
  1417. const results = [];
  1418. for (const s of ensureArray(match)) {
  1419. const pinDomain = s.startsWith('||');
  1420. const pinStart = !pinDomain && s.startsWith('|');
  1421. const endSep = s.endsWith('^');
  1422. let fn;
  1423. let needle = s.slice(pinDomain * 2 + pinStart, -endSep || undefined);
  1424. if (needle.includes('^')) {
  1425. const plain = findLongestPart(needle);
  1426. const rx = new RegExp(
  1427. (pinStart ? '^' : '') +
  1428. (pinDomain ? '^(([^/:]+:)?//)?([^./]*\\.)*?' : '') +
  1429. needle.replace(RX_ESCAPE, '\\$&').replace(/\\\^/g, RXS_SEP) +
  1430. (endSep ? `(?:${RXS_SEP}|$)` : ''), 'i');
  1431. needle = [plain, rx];
  1432. fn = regexp;
  1433. } else if (pinStart) {
  1434. fn = endSep ? equals : starts;
  1435. } else if (pinDomain) {
  1436. const slashPos = needle.indexOf('/');
  1437. const domain = slashPos > 0 ? needle.slice(0, slashPos) : needle;
  1438. needle = [needle, domain, slashPos > 0, endSep];
  1439. fn = startsDomainPrescreen;
  1440. } else if (endSep) {
  1441. fn = ends;
  1442. } else {
  1443. fn = has;
  1444. }
  1445. results.push({fn, this: needle});
  1446. }
  1447. return results.length > 1 ?
  1448. {fn: checkArray, this: results} :
  1449. results[0];
  1450. };
  1451. function checkArray(s) {
  1452. return this.some(checkArrayItem, s);
  1453. }
  1454. function checkArrayItem(item) {
  1455. return item.fn.call(item.this, this);
  1456. }
  1457. function equals(s) {
  1458. return s.startsWith(this) && (
  1459. s.length === this.length ||
  1460. s.length === this.length + 1 && endsWithSep(s));
  1461. }
  1462. function starts(s) {
  1463. return s.startsWith(this);
  1464. }
  1465. function ends(s) {
  1466. return s.endsWith(this) || (
  1467. s.length > this.length &&
  1468. s.indexOf(this, s.length - this.length - 1) >= 0 &&
  1469. endsWithSep(s));
  1470. }
  1471. function has(s) {
  1472. return s.includes(this);
  1473. }
  1474. function regexp(s) {
  1475. return s.includes(this[0]) && this[1].test(s);
  1476. }
  1477. function endsWithSep(s) {
  1478. RX_SEP.lastIndex = s.length - 1;
  1479. return RX_SEP.test(s);
  1480. }
  1481. function startsDomainPrescreen(url) {
  1482. return url.includes(this[0]) && startsDomain.call(this, url);
  1483. }
  1484. function startsDomain(url) {
  1485. const [p, gap, host] = url.split('/', 3);
  1486. if (gap || p && !p.endsWith(':'))
  1487. return;
  1488. const [needle, domain, pinDomainEnd, endSep] = this;
  1489. let start = pinDomainEnd ? host.length - domain.length : 0;
  1490. for (; ; start++) {
  1491. start = host.indexOf(domain, start);
  1492. if (start < 0)
  1493. return;
  1494. if (!start || host[start - 1] === '.')
  1495. break;
  1496. }
  1497. start += p.length + 2;
  1498. return url.lastIndexOf(needle, start) === start &&
  1499. (!endSep || start + needle.length === url.length);
  1500. }
  1501. function findLongestPart(s) {
  1502. const len = s.length;
  1503. let maxLen = 0;
  1504. let start;
  1505. for (let i = 0, j; i < len; i = j + 1) {
  1506. j = s.indexOf('^', i);
  1507. if (j < 0)
  1508. j = len;
  1509. if (j - i > maxLen) {
  1510. maxLen = j - i;
  1511. start = i;
  1512. }
  1513. }
  1514. return maxLen < len ? s.substr(start, maxLen) : s;
  1515. }
  1516. })();
  1517.  
  1518. class RuleMatcher {
  1519.  
  1520. /** @returns ?mpiv.RuleMatchInfo */
  1521. static findForLink(a) {
  1522. let url =
  1523. a.getAttribute('data-expanded-url') ||
  1524. a.getAttribute('data-full-url') ||
  1525. a.getAttribute('data-url') ||
  1526. a.href;
  1527. if (url.startsWith('data:'))
  1528. url = false;
  1529. else if (url.includes('//t.co/'))
  1530. url = 'http://' + a.textContent;
  1531. return RuleMatcher.find(url, a);
  1532. }
  1533.  
  1534. /** @returns ?mpiv.RuleMatchInfo */
  1535. static find(url, node, {noHtml, skipRule} = {}) {
  1536. const tn = node.tagName;
  1537. let m, html, urls;
  1538. for (const rule of Ruler.rules) {
  1539. const {e} = rule;
  1540. if (e && !node.matches(e) || rule === skipRule)
  1541. continue;
  1542. const {r, u} = rule;
  1543. if (r && !noHtml && rule.html && (tn === 'A' || tn === 'IMG' || e))
  1544. m = r.exec(html || (html = node.outerHTML));
  1545. else if (r || u)
  1546. m = url && RuleMatcher.makeUrlMatch(url, node, rule);
  1547. else
  1548. m = url ? RuleMatcher.makeDummyMatch(url) : [];
  1549. if (!m ||
  1550. // a rule with follow:true for the currently hovered IMG produced a URL,
  1551. // but we'll only allow it to match rules without 's' in the nested find call
  1552. tn === 'IMG' && !('s' in rule) && !skipRule)
  1553. continue;
  1554. if (rule.s === '')
  1555. return {};
  1556. const hasS = 's' in rule && rule.s !== 'gallery';
  1557. urls = hasS ? Ruler.runS(node, rule, m) : [m.input];
  1558. if (!urls.skipRule) {
  1559. const url = urls[0];
  1560. return !url ? {} :
  1561. hasS && !rule.q && RuleMatcher.isFollowableUrl(url, rule) ?
  1562. RuleMatcher.find(url, node, {skipRule: rule}) :
  1563. RuleMatcher.makeInfo(urls, node, rule, m);
  1564. }
  1565. }
  1566. }
  1567.  
  1568. static makeUrlMatch(url, node, rule) {
  1569. let {r, u} = rule;
  1570. let m;
  1571. if (u) {
  1572. u = rule._u || (rule._u = SimpleUrlMatcher(u));
  1573. m = u.fn.call(u.this, url) && (r || RuleMatcher.makeDummyMatch(url));
  1574. }
  1575. return (m || !u) && r ? r.exec(url) : m;
  1576. }
  1577.  
  1578. static makeDummyMatch(url) {
  1579. const m = [url];
  1580. m.index = 0;
  1581. m.input = url;
  1582. return m;
  1583. }
  1584.  
  1585. /** @returns mpiv.RuleMatchInfo */
  1586. static makeInfo(urls, node, rule, m) {
  1587. const url = urls[0];
  1588. const info = {
  1589. node,
  1590. rule,
  1591. url,
  1592. urls: urls.length > 1 ? urls.slice(1) : null,
  1593. match: m,
  1594. gallery: rule.g && Gallery.makeParser(rule.g),
  1595. post: typeof rule.post === 'function' ? rule.post(m) : rule.post,
  1596. xhr: cfg.xhr && rule.xhr,
  1597. };
  1598. Util.lazyGetRect(info, node, rule.rect);
  1599. if (
  1600. dotDomain.endsWith('.twitter.com') && !/(facebook|google|twimg|twitter)\.com\//.test(url) ||
  1601. dotDomain.endsWith('.github.com') && !/github/.test(url) ||
  1602. dotDomain.endsWith('.facebook.com') && /\bimgur\.com/.test(url)
  1603. ) {
  1604. info.xhr = 'data';
  1605. }
  1606. return info;
  1607. }
  1608.  
  1609. static isFollowableUrl(url, rule) {
  1610. const f = rule.follow;
  1611. return typeof f === 'function' ? f(url) : f;
  1612. }
  1613. }
  1614.  
  1615. class Events {
  1616.  
  1617. static onMouseOver(e) {
  1618. if (!App.enabled || e.shiftKey || ai.zoom)
  1619. return;
  1620. let node = e.target;
  1621. if (node === ai.popup ||
  1622. node === doc.body ||
  1623. node === doc.documentElement)
  1624. return;
  1625.  
  1626. if (node.shadowRoot)
  1627. node = Events.pierceShadow(node, e.clientX, e.clientY);
  1628.  
  1629. if (!Ruler.rules)
  1630. Ruler.init();
  1631.  
  1632. let a, img, url, info;
  1633. if (node.tagName === 'A') {
  1634. a = node;
  1635. } else {
  1636. if (node.tagName === 'IMG') {
  1637. img = node;
  1638. url = !img.src.startsWith('data:') && Util.rel2abs(img.src, location.href);
  1639. }
  1640. info = RuleMatcher.find(url, node);
  1641. a = !info && node.closest('a');
  1642. }
  1643.  
  1644. if (!info && a)
  1645. info = RuleMatcher.findForLink(a);
  1646.  
  1647. if (!info && img) {
  1648. info = Util.lazyGetRect({
  1649. url: img.src,
  1650. node: img,
  1651. rule: {},
  1652. }, img);
  1653. }
  1654.  
  1655. if (info && info.url && info.node !== ai.node)
  1656. App.activate(info, e);
  1657. }
  1658.  
  1659. static pierceShadow(node, x, y) {
  1660. for (let root; (root = node.shadowRoot);) {
  1661. root.addEventListener('mouseover', Events.onMouseOver, PASSIVE);
  1662. root.addEventListener('mouseout', Events.onMouseOutShadow);
  1663. const inner = root.elementFromPoint(x, y);
  1664. if (!inner || inner === node)
  1665. break;
  1666. node = inner;
  1667. }
  1668. return node;
  1669. }
  1670.  
  1671. static onMouseOut(e) {
  1672. if (!e.relatedTarget && !e.shiftKey)
  1673. App.deactivate();
  1674. }
  1675.  
  1676. static onMouseOutShadow(e) {
  1677. const root = e.target.shadowRoot;
  1678. if (root) {
  1679. root.removeEventListener('mouseover', Events.onMouseOver);
  1680. root.removeEventListener('mouseout', Events.onMouseOutShadow);
  1681. }
  1682. }
  1683.  
  1684. static onMouseMove(e) {
  1685. App.updateMouse(e);
  1686. if (e.shiftKey)
  1687. return (ai.lazyUnload = true);
  1688. if (!ai.zoomed && !ai.isOverRect)
  1689. return App.deactivate();
  1690. if (ai.zoom) {
  1691. Popup.move();
  1692. const {height: h, width: w} = ai.view;
  1693. const {clientX: cx, clientY: cy} = ai;
  1694. const bx = w / 6;
  1695. const by = h / 6;
  1696. const onEdge = cx < bx || cx > w - bx || cy < by || cy > h - by;
  1697. App.setStatus(`${onEdge ? '+' : '-'}edge`);
  1698. }
  1699. }
  1700.  
  1701. static onMouseDown({shiftKey, button}) {
  1702. if (button === 0 && shiftKey && ai.popup && ai.popup.controls) {
  1703. ai.controlled = ai.zoomed = true;
  1704. } else if (button === 2 || shiftKey) {
  1705. // we ignore RMB and Shift
  1706. } else {
  1707. App.deactivate({wait: true});
  1708. }
  1709. }
  1710.  
  1711. static onMouseScroll(e) {
  1712. const dir = (e.deltaY || -e.wheelDelta) > 0 ? 1 : -1;
  1713. if (ai.zoom) {
  1714. dropEvent(e);
  1715. const i = ai.scales.indexOf(ai.scale) - dir;
  1716. const n = ai.scales.length;
  1717. if (i >= 0 && i < n)
  1718. ai.scale = ai.scales[i];
  1719. if (i === 0 && cfg.zoomOut !== 'stay') {
  1720. if ((cfg.zoomOut === 'close' || !ai.isOverRect) &&
  1721. (!ai.gItems || ai.gItems.length < 2))
  1722. return App.deactivate({wait: true});
  1723. ai.zoom = false;
  1724. ai.zoomed = false;
  1725. App.updateFileInfo();
  1726. } else {
  1727. ai.popup.classList.toggle(`${PREFIX}zoom-max`, ai.scale >= 4 && i >= n - 1);
  1728. }
  1729. if (ai.zooming)
  1730. ai.popup.classList.add(`${PREFIX}zooming`);
  1731. Popup.move();
  1732. App.updateTitle();
  1733. } else if (ai.gItems && ai.gItems.length > 1 && ai.popup) {
  1734. dropEvent(e);
  1735. Gallery.next(dir);
  1736. } else if (cfg.zoom === 'wheel' && dir < 0 && ai.popup) {
  1737. dropEvent(e);
  1738. App.toggleZoom();
  1739. } else {
  1740. App.deactivate();
  1741. }
  1742. }
  1743.  
  1744. static onKeyDown(e) {
  1745. switch (e.key) {
  1746. case 'Shift':
  1747. App.setStatus('+shift');
  1748. if (ai.popup && 'controls' in ai.popup)
  1749. ai.popup.controls = true;
  1750. break;
  1751. case 'Control':
  1752. if (!ai.popup && (cfg.start !== 'auto' || ai.rule.manual))
  1753. Popup.start();
  1754. break;
  1755. }
  1756. }
  1757.  
  1758. static onKeyUp(e) {
  1759. switch (e.key.length > 1 ? e.key : e.code) {
  1760. case 'Shift':
  1761. App.setStatus('-shift');
  1762. if ((ai.popup || {}).controls)
  1763. ai.popup.controls = false;
  1764. if (ai.controlled) {
  1765. ai.controlled = false;
  1766. return;
  1767. }
  1768. ai.popup && (ai.zoomed || ai.isOverRect !== false) ?
  1769. App.toggleZoom() :
  1770. App.deactivate({wait: true});
  1771. break;
  1772. case 'Control':
  1773. break;
  1774. case 'Escape':
  1775. App.deactivate({wait: true});
  1776. break;
  1777. case 'ArrowRight':
  1778. case 'KeyJ':
  1779. dropEvent(e);
  1780. Gallery.next(1);
  1781. break;
  1782. case 'ArrowLeft':
  1783. case 'KeyK':
  1784. dropEvent(e);
  1785. Gallery.next(-1);
  1786. break;
  1787. case 'KeyD': {
  1788. dropEvent(e);
  1789. Remoting.saveFile();
  1790. break;
  1791. }
  1792. case 'KeyT':
  1793. ai.lazyUnload = true;
  1794. GM_openInTab(
  1795. ai.rule.tabfix && ai.popup.tagName === 'IMG' && !ai.xhr &&
  1796. navigator.userAgent.includes('Gecko/') ?
  1797. Util.tabFixUrl() :
  1798. ai.popup.src);
  1799. App.deactivate();
  1800. break;
  1801. default:
  1802. App.deactivate({wait: true});
  1803. }
  1804. }
  1805.  
  1806. static onContext(e) {
  1807. if (e.shiftKey)
  1808. return;
  1809. if (cfg.zoom === 'context' && ai.popup && App.toggleZoom()) {
  1810. dropEvent(e);
  1811. return;
  1812. }
  1813. if (!ai.popup && (
  1814. cfg.start === 'context' ||
  1815. (cfg.start === 'auto' && ai.rule.manual)
  1816. )) {
  1817. Popup.start();
  1818. dropEvent(e);
  1819. } else {
  1820. setTimeout(App.deactivate, SETTLE_TIME, {wait: true});
  1821. }
  1822. }
  1823. }
  1824.  
  1825. class Popup {
  1826.  
  1827. static schedule(force) {
  1828. if (!cfg.preload) {
  1829. ai.timer = setTimeout(Popup.start, cfg.delay);
  1830. } else if (!force) {
  1831. // we don't want to preload everything in the path of a quickly moving mouse cursor
  1832. ai.timer = setTimeout(Popup.schedule, SETTLE_TIME, true);
  1833. ai.preloadStart = Date.now();
  1834. } else {
  1835. Popup.start();
  1836. App.setStatus('+preloading');
  1837. setTimeout(App.setStatus, cfg.delay, '-preloading');
  1838. }
  1839. }
  1840.  
  1841. static start() {
  1842. App.updateStyles();
  1843. ai.gallery ?
  1844. Popup.startGallery() :
  1845. Popup.startSingle();
  1846. }
  1847.  
  1848. static startSingle() {
  1849. App.setStatusLoading();
  1850. ai.imageUrl = null;
  1851. if (ai.rule.follow && !ai.rule.q && !ai.rule.s) {
  1852. Remoting.findRedirect();
  1853. } else if (ai.rule.q && !Array.isArray(ai.urls)) {
  1854. Popup.startFromQ();
  1855. } else {
  1856. App.updateCaption();
  1857. Popup.render(ai.url);
  1858. }
  1859. }
  1860.  
  1861. static async startFromQ() {
  1862. try {
  1863. const {responseText, doc, finalUrl} = await Remoting.getDoc(ai.url);
  1864. const url = Ruler.runQ(responseText, doc, finalUrl);
  1865. if (!url)
  1866. throw 'File not found.';
  1867. App.updateCaption(responseText, doc);
  1868. if (RuleMatcher.isFollowableUrl(url, ai.rule)) {
  1869. const info = RuleMatcher.find(url, ai.node, {noHtml: true});
  1870. if (!info || !info.url)
  1871. throw `Couldn't follow URL: ${url}`;
  1872. Object.assign(ai, info);
  1873. Popup.startSingle();
  1874. } else {
  1875. Popup.render(url, finalUrl);
  1876. }
  1877. } catch (e) {
  1878. App.handleError(e);
  1879. }
  1880. }
  1881.  
  1882. static async startGallery() {
  1883. App.setStatusLoading();
  1884. try {
  1885. const startUrl = ai.url;
  1886. const p = ai.rule.s === 'gallery' ? {} :
  1887. await Remoting.getDoc(startUrl);
  1888. const items = await new Promise(resolve => {
  1889. const it = ai.gallery(p.responseText, p.doc, p.finalUrl, ai.match, ai.rule, resolve);
  1890. if (Array.isArray(it))
  1891. resolve(it);
  1892. });
  1893. // bail out if the gallery's async callback took too long
  1894. if (ai.url !== startUrl)
  1895. return;
  1896. ai.gItems = items.length && items;
  1897. if (ai.gItems) {
  1898. ai.gIndex = Gallery.findIndex(ai.url);
  1899. setTimeout(Gallery.next);
  1900. } else {
  1901. throw 'Empty gallery';
  1902. }
  1903. } catch (e) {
  1904. App.handleError(e);
  1905. }
  1906. }
  1907.  
  1908. static async render(src, pageUrl) {
  1909. Popup.destroy();
  1910. ai.imageUrl = src;
  1911. if (ai.xhr && src)
  1912. src = await Remoting.getImage(src, pageUrl).catch(App.handleError);
  1913. if (!src)
  1914. return;
  1915. const p = ai.popup =
  1916. src.startsWith('data:video') ||
  1917. !src.startsWith('data:') && /\.(webm|mp4)($|\?)/.test(src) ?
  1918. PopupVideo.create() :
  1919. $create('img');
  1920. p.id = `${PREFIX}popup`;
  1921. p.src = src;
  1922. p.addEventListener('error', App.handleError);
  1923. p.addEventListener('load', Popup.onLoad, {once: true});
  1924. if (ai.zooming)
  1925. p.addEventListener('transitionend', Popup.onZoom);
  1926. doc.body.insertBefore(p, ai.bar || undefined);
  1927. App.checkProgress({start: true});
  1928. }
  1929.  
  1930. static onLoad() {
  1931. this.setAttribute('loaded', '');
  1932. ai.popupLoaded = true;
  1933. if (!ai.bar)
  1934. App.updateFileInfo();
  1935. }
  1936.  
  1937. static onZoom() {
  1938. return this.classList.remove(`${PREFIX}zooming`);
  1939. }
  1940.  
  1941. static move() {
  1942. const p = ai.popup;
  1943. if (!p)
  1944. return;
  1945. let x, y;
  1946. const w = Math.round(ai.scale * ai.nwidth);
  1947. const h = Math.round(ai.scale * ai.nheight);
  1948. const cx = ai.clientX;
  1949. const cy = ai.clientY;
  1950. const vw = ai.view.width - ai.outline * 2;
  1951. const vh = ai.view.height - ai.outline * 2;
  1952. if (!ai.zoom && (!ai.gItems || ai.gItems.length < 2) && !cfg.center) {
  1953. const r = ai.rect;
  1954. const rx = (r.left + r.right) / 2;
  1955. const ry = (r.top + r.bottom) / 2;
  1956. if (vw - r.right - 40 > w + ai.mbw || w + ai.mbw < r.left - 40) {
  1957. if (h + ai.mbh < vh - 60)
  1958. y = clamp(ry - h / 2, 30, vh - h - 30);
  1959. x = rx > vw / 2 ? r.left - 40 - w : r.right + 40;
  1960. } else if (vh - r.bottom - 40 > h + ai.mbh || h + ai.mbh < r.top - 40) {
  1961. if (w + ai.mbw < vw - 60)
  1962. x = clamp(rx - w / 2, 30, vw - w - 30);
  1963. y = ry > vh / 2 ? r.top - 40 - h : r.bottom + 40;
  1964. }
  1965. }
  1966. if (x === undefined) {
  1967. const mid = vw > w ?
  1968. vw / 2 - w / 2 :
  1969. -1 * clamp(5 / 3 * (cx / vw - 0.2), 0, 1) * (w - vw);
  1970. x = Math.round(mid - (ai.pw + ai.mbw) / 2);
  1971. }
  1972. if (y === undefined) {
  1973. const mid = vh > h ?
  1974. vh / 2 - h / 2 :
  1975. -1 * clamp(5 / 3 * (cy / vh - 0.2), 0, 1) * (h - vh);
  1976. y = Math.round(mid - (ai.ph + ai.mbh) / 2);
  1977. }
  1978. p.style.cssText = `
  1979. width: ${w}px !important;
  1980. height: ${h}px !important;
  1981. left: ${x + ai.outline}px !important;
  1982. top: ${y + ai.outline}px !important;
  1983. `;
  1984. }
  1985.  
  1986. static destroy() {
  1987. const p = ai.popup;
  1988. if (!p)
  1989. return;
  1990. p.removeEventListener('error', App.handleError);
  1991. if (typeof p.pause === 'function')
  1992. p.pause();
  1993. if (!ai.lazyUnload) {
  1994. if (p.src.startsWith('blob:'))
  1995. URL.revokeObjectURL(p.src);
  1996. p.src = '';
  1997. }
  1998. p.remove();
  1999. ai.zoom = false;
  2000. ai.popupLoaded = false;
  2001. ai.popup = null;
  2002. }
  2003. }
  2004.  
  2005. class PopupVideo {
  2006. static create() {
  2007. const p = $create('video');
  2008. p.autoplay = true;
  2009. p.loop = true;
  2010. p.volume = 0.5;
  2011. p.controls = false;
  2012. p.addEventListener('progress', PopupVideo.progress);
  2013. p.addEventListener('canplaythrough', PopupVideo.progressDone, {once: true});
  2014. ai.bufferingBar = false;
  2015. ai.bufferingStart = Date.now();
  2016. return p;
  2017. }
  2018.  
  2019. static progress() {
  2020. const {duration} = this;
  2021. if (duration && this.buffered.length && Date.now() - ai.bufferingStart > 2000) {
  2022. const pct = Math.round(this.buffered.end(0) / duration * 100);
  2023. if ((ai.bufferingBar |= pct > 0 && pct < 50))
  2024. App.setBar(`${pct}% of ${Math.round(duration)}s`, 'xhr');
  2025. }
  2026. }
  2027.  
  2028. static progressDone() {
  2029. this.removeEventListener('progress', PopupVideo.progress);
  2030. if (ai.bar && ai.bar.classList.contains(`${PREFIX}xhr`)) {
  2031. App.setBar(false);
  2032. App.updateFileInfo();
  2033. }
  2034. }
  2035. }
  2036.  
  2037. class Gallery {
  2038.  
  2039. static makeParser(g) {
  2040. return (
  2041. typeof g === 'function' ? g :
  2042. typeof g === 'string' ? Util.newFunction('text', 'doc', 'url', 'm', 'rule', 'cb', g) :
  2043. Gallery.defaultParser
  2044. );
  2045. }
  2046.  
  2047. static findIndex(gUrl) {
  2048. const sel = gUrl.split('#')[1];
  2049. if (!sel)
  2050. return 0;
  2051. if (/^\d+$/.test(sel))
  2052. return parseInt(sel);
  2053. for (let i = ai.gItems.length; i--;) {
  2054. let {url} = ai.gItems[i];
  2055. if (Array.isArray(url))
  2056. url = url[0];
  2057. if (url.indexOf(sel, url.lastIndexOf('/')) > 0)
  2058. return i;
  2059. }
  2060. return 0;
  2061. }
  2062.  
  2063. static next(dir) {
  2064. if (dir > 0 && (ai.gIndex += dir) >= ai.gItems.length) {
  2065. ai.gIndex = 0;
  2066. } else if (dir < 0 && (ai.gIndex += dir) < 0) {
  2067. ai.gIndex = ai.gItems.length - 1;
  2068. }
  2069. const item = ai.gItems[ai.gIndex];
  2070. if (Array.isArray(item.url)) {
  2071. ai.urls = item.url.slice(1);
  2072. ai.url = item.url[0];
  2073. } else {
  2074. ai.urls = null;
  2075. ai.url = item.url;
  2076. }
  2077. Popup.destroy();
  2078. Popup.startSingle();
  2079. App.updateFileInfo();
  2080. Gallery.preload(dir);
  2081. }
  2082.  
  2083. static preload(dir) {
  2084. const i = ai.gIndex + dir;
  2085. if (ai.popup && i >= 0 && i < ai.gItems.length) {
  2086. ai.preloadUrl = ensureArray(ai.gItems[i].url)[0];
  2087. ai.popup.addEventListener('load', Gallery.preloadOnLoad, {once: true});
  2088. }
  2089. }
  2090.  
  2091. static preloadOnLoad() {
  2092. $create('img', {src: ai.preloadUrl});
  2093. }
  2094.  
  2095. static defaultParser(text, doc, docUrl, m, rule) {
  2096. const {g} = rule;
  2097. const qEntry = g.entry;
  2098. const qCaption = ensureArray(g.caption);
  2099. const qImage = g.image;
  2100. const qTitle = g.title;
  2101. const fix =
  2102. (typeof g.fix === 'string' ? Util.newFunction('s', 'isURL', g.fix) : g.fix) ||
  2103. (s => s.trim());
  2104. const items = [...$$(qEntry || qImage, doc)]
  2105. .map(processEntry)
  2106. .filter(Boolean);
  2107. items.title = processTitle();
  2108. return items;
  2109.  
  2110. function processEntry(entry) {
  2111. const item = {};
  2112. try {
  2113. const img = qEntry ? $(qImage, entry) : entry;
  2114. item.url = fix(Remoting.findFileUrl(img, docUrl), true);
  2115. item.desc = qCaption.map(processCaption, entry).filter(Boolean).join(' - ');
  2116. } catch (e) {}
  2117. return item.url && item;
  2118. }
  2119.  
  2120. function processCaption(selector) {
  2121. const el = $(selector, this) ||
  2122. $orSelf(selector, this.previousElementSibling) ||
  2123. $orSelf(selector, this.nextElementSibling);
  2124. return el && fix(el.textContent);
  2125. }
  2126.  
  2127. function processTitle() {
  2128. const el = $(qTitle, doc);
  2129. return el && fix(el.getAttribute('content') || el.textContent) || '';
  2130. }
  2131.  
  2132. function $orSelf(selector, el) {
  2133. if (el && !el.matches(qEntry))
  2134. return el.matches(selector) ? el : $(selector, el);
  2135. }
  2136. }
  2137. }
  2138.  
  2139. class Remoting {
  2140.  
  2141. static gmXhr(url, opts = {}) {
  2142. if (ai.req)
  2143. tryCatch.call(ai.req, ai.req.abort);
  2144. return new Promise((resolve, reject) => {
  2145. ai.req = GM_xmlhttpRequest({
  2146. url,
  2147. method: 'GET',
  2148. timeout: 10e3,
  2149. ...opts,
  2150. ontimeout() {
  2151. ai.req = null;
  2152. reject(`Timeout fetching ${url}`);
  2153. },
  2154. onloadend(e) {
  2155. ai.req = null;
  2156. e.status < 400 && !e.error ?
  2157. resolve(e) :
  2158. reject(`Server error ${e.status} ${e.error}\nURL: ${url}`);
  2159. },
  2160. });
  2161. });
  2162. }
  2163.  
  2164. static async getDoc(url) {
  2165. const r = await (!ai.post ?
  2166. Remoting.gmXhr(url) :
  2167. Remoting.gmXhr(url, {
  2168. method: 'POST',
  2169. data: ai.post,
  2170. headers: {
  2171. 'Content-Type': 'application/x-www-form-urlencoded',
  2172. 'Referer': url,
  2173. },
  2174. }));
  2175. r.doc = new DOMParser().parseFromString(r.responseText, 'text/html');
  2176. return r;
  2177. }
  2178.  
  2179. static async getImage(url, pageUrl) {
  2180. ai.bufferingBar = false;
  2181. ai.bufferingStart = Date.now();
  2182. const response = await Remoting.gmXhr(url, {
  2183. responseType: 'blob',
  2184. headers: {
  2185. Accept: 'image/png,image/*;q=0.8,*/*;q=0.5',
  2186. Referer: pageUrl || typeof ai.xhr === 'function' ? ai.xhr(ai.match, ai.node, ai.rule) : url,
  2187. },
  2188. onprogress: Remoting.getImageProgress,
  2189. });
  2190. App.setBar(false);
  2191. const type = Remoting.guessMimeType(response);
  2192. let b = response.response;
  2193. if (b.type !== type)
  2194. b = b.slice(0, b.size, type);
  2195. return ai.xhr === 'data' ?
  2196. Remoting.blobToDataUrl(b) :
  2197. URL.createObjectURL(b);
  2198. }
  2199.  
  2200. static getImageProgress(e) {
  2201. if (!ai.bufferingBar && Date.now() - ai.bufferingStart > 3000 && e.loaded / e.total < 0.5)
  2202. ai.bufferingBar = true;
  2203. if (ai.bufferingBar) {
  2204. const pct = e.loaded / e.total * 100 | 0;
  2205. const size = e.total / 1024 | 0;
  2206. App.setBar(`${pct}% of ${size} kiB`, 'xhr');
  2207. }
  2208. }
  2209.  
  2210. static async findRedirect() {
  2211. try {
  2212. const {finalUrl} = await Remoting.gmXhr(ai.url, {
  2213. method: 'HEAD',
  2214. headers: {
  2215. 'Referer': location.href.split('#', 1)[0],
  2216. },
  2217. });
  2218. const info = RuleMatcher.find(finalUrl, ai.node, {noHtml: true});
  2219. if (!info || !info.url)
  2220. throw `Couldn't follow redirection target: ${finalUrl}`;
  2221. Object.assign(ai, info);
  2222. Popup.startSingle();
  2223. } catch (e) {
  2224. App.handleError(e);
  2225. }
  2226. }
  2227.  
  2228. static async saveFile() {
  2229. let url = ai.popup.src || ai.popup.currentSrc;
  2230. let name = Remoting.getFileName(ai.imageUrl || url);
  2231. if (!name.includes('.'))
  2232. name += '.jpg';
  2233. try {
  2234. if (!url.startsWith('blob:') && !url.startsWith('data:')) {
  2235. const {response} = await Remoting.gmXhr(url, {
  2236. responseType: 'blob',
  2237. headers: {'Referer': url},
  2238. });
  2239. url = URL.createObjectURL(response);
  2240. setTimeout(() => URL.revokeObjectURL(url), 1000);
  2241. }
  2242. $create('a', {href: url, download: name})
  2243. .dispatchEvent(new MouseEvent('click'));
  2244. } catch (e) {
  2245. App.setBar(`Could not download ${name}.`, 'error');
  2246. }
  2247. }
  2248.  
  2249. static getFileName(url) {
  2250. return decodeURIComponent(url).split('/').pop().replace(/[:#?].*/, '');
  2251. }
  2252.  
  2253. static blobToDataUrl(blob) {
  2254. return new Promise((resolve, reject) => {
  2255. const fr = new FileReader();
  2256. fr.onload = () => resolve(fr.result);
  2257. fr.onerror = reject;
  2258. fr.readAsDataURL(blob);
  2259. });
  2260. }
  2261.  
  2262. static guessMimeType({responseHeaders, finalUrl}) {
  2263. if (/Content-Type:\s*(\S+)/i.test(responseHeaders) &&
  2264. !RegExp.$1.includes('text/plain'))
  2265. return RegExp.$1;
  2266. const ext = /\.([a-z0-9]+?)($|\?|#)/i.exec(finalUrl) ? RegExp.$1 : 'jpg';
  2267. switch (ext.toLowerCase()) {
  2268. case 'bmp': return 'image/bmp';
  2269. case 'gif': return 'image/gif';
  2270. case 'jpe': return 'image/jpeg';
  2271. case 'jpeg': return 'image/jpeg';
  2272. case 'jpg': return 'image/jpeg';
  2273. case 'mp4': return 'video/mp4';
  2274. case 'png': return 'image/png';
  2275. case 'svg': return 'image/svg+xml';
  2276. case 'tif': return 'image/tiff';
  2277. case 'tiff': return 'image/tiff';
  2278. case 'webm': return 'video/webm';
  2279. default: return 'application/octet-stream';
  2280. }
  2281. }
  2282.  
  2283. static findFileUrl(n, url) {
  2284. const base = $('base[href]', n.ownerDocument);
  2285. const path =
  2286. n.getAttribute('src') ||
  2287. n.getAttribute('data-m4v') ||
  2288. n.getAttribute('href') ||
  2289. n.getAttribute('content') ||
  2290. /https?:\/\/[./a-z0-9_+%-]+\.(jpe?g|gif|png|svg|webm|mp4)/i.exec(n.outerHTML) &&
  2291. RegExp.lastMatch;
  2292. return path ? Util.rel2abs(path.trim(), base ? base.getAttribute('href') : url) : false;
  2293. }
  2294. }
  2295.  
  2296. class Util {
  2297.  
  2298. static addStyle(name, css) {
  2299. const id = `${PREFIX}style:${name}`;
  2300. const el = doc.getElementById(id) ||
  2301. css && $create('style', {id});
  2302. if (!el)
  2303. return;
  2304. if (el.textContent !== css)
  2305. el.textContent = css;
  2306. if (el.parentElement !== doc.head)
  2307. doc.head.appendChild(el);
  2308. return el;
  2309. }
  2310.  
  2311. static deepEqual(a, b) {
  2312. if (typeof a !== typeof b)
  2313. return false;
  2314. if (!a || !b || typeof a !== 'object')
  2315. return a === b;
  2316. if (Array.isArray(a))
  2317. return Array.isArray(b) &&
  2318. a.length === b.length &&
  2319. a.every((v, i) => Util.deepEqual(v, b[i]));
  2320. const keys = Object.keys(a);
  2321. return keys.length === Object.keys(b).length &&
  2322. keys.every(k => Util.deepEqual(a[k], b[k]));
  2323. }
  2324.  
  2325. static findScale(url, parent) {
  2326. const imgs = $$('img, video', parent);
  2327. for (let i = imgs.length, img; (img = imgs[--i]);) {
  2328. if ((img.src || img.currentSrc) !== url)
  2329. continue;
  2330. const scaleX = (img.naturalWidth || img.videoWidth) / img.offsetWidth;
  2331. const scaleY = (img.naturalHeight || img.videoHeight) / img.offsetHeight;
  2332. const s = Math.max(scaleX, scaleY);
  2333. if (isFinite(s))
  2334. return s;
  2335. }
  2336. }
  2337.  
  2338. static forceLayout(node) {
  2339. // eslint-disable-next-line no-unused-expressions
  2340. node.clientHeight;
  2341. }
  2342.  
  2343. static formatError(e, rule) {
  2344. let {message} = e;
  2345. if (!message) {
  2346. if (e.readyState)
  2347. message = 'Request failed.';
  2348. else if (e.type === 'error')
  2349. message = "File can't be displayed." + (
  2350. $('div[bgactive*="flashblock"]', doc) ?
  2351. ' Check Flashblock settings.' :
  2352. '');
  2353. else
  2354. message = e;
  2355. }
  2356. const m = [
  2357. [`${GM_info.script.name}: %c${message}%c`, 'font-weight:bold;color:yellow'],
  2358. ['', 'font-weight:normal;color:unset'],
  2359. ];
  2360. if (rule.u)
  2361. m.push(['Url simple match: %o', rule.u]);
  2362. if (rule.r)
  2363. m.push(['RegExp match: %o', rule.r]);
  2364. if (ai.url)
  2365. m.push(['URL: %s', ai.url]);
  2366. if (ai.imageUrl && ai.imageUrl !== ai.url)
  2367. m.push(['File: %s', ai.imageUrl]);
  2368. m.push(['Node: %o', ai.node]);
  2369. return {
  2370. message,
  2371. consoleFormat: m.map(([k]) => k).filter(Boolean).join('\n'),
  2372. consoleArgs: m.map(([, v]) => v),
  2373. };
  2374. }
  2375.  
  2376. static lazyGetRect(obj, node, selector) {
  2377. return Object.defineProperty(obj, 'rect', {
  2378. configurable: true,
  2379. get() {
  2380. const value = Util.rect(node, selector);
  2381. Object.defineProperty(obj, 'rect', {value, configurable: true});
  2382. return value;
  2383. },
  2384. });
  2385. }
  2386.  
  2387. // decode only if the main part of the URL is encoded to preserve the encoded parameters
  2388. static maybeDecodeURL(url) {
  2389. if (!url)
  2390. return url;
  2391. const iPct = url.indexOf('%');
  2392. const iColon = url.indexOf(':');
  2393. return iPct >= 0 && (iPct < iColon || iColon < 0) ?
  2394. decodeURIComponent(url) :
  2395. url;
  2396. }
  2397.  
  2398. static newFunction(...args) {
  2399. try {
  2400. return App.NOP || new Function(...args);
  2401. } catch (e) {
  2402. if (!e.message.includes('unsafe-eval'))
  2403. throw e;
  2404. App.NOP = () => {};
  2405. return App.NOP;
  2406. }
  2407. }
  2408.  
  2409. static rect(node, selector) {
  2410. let n = selector && node.closest(selector);
  2411. if (n)
  2412. return n.getBoundingClientRect();
  2413. const nested = node.getElementsByTagName('*');
  2414. let maxArea = 0;
  2415. let maxBounds;
  2416. n = node;
  2417. for (let i = 0; n; n = nested[i++]) {
  2418. const bounds = n.getBoundingClientRect();
  2419. const area = bounds.width * bounds.height;
  2420. if (area > maxArea) {
  2421. maxArea = area;
  2422. maxBounds = bounds;
  2423. node = n;
  2424. }
  2425. }
  2426. return maxBounds;
  2427. }
  2428.  
  2429. static rel2abs(rel, abs) {
  2430. if (rel.startsWith('data:'))
  2431. return rel;
  2432. const rx = /^([a-z]+:)\/\//;
  2433. if (rx.test(rel))
  2434. return rel;
  2435. if (!rx.test(abs))
  2436. return;
  2437. if (rel.indexOf('//') === 0)
  2438. return RegExp.$1 + rel;
  2439. if (rel[0] === '/')
  2440. return abs.substr(0, abs.indexOf('/', RegExp.lastMatch.length)) + rel;
  2441. return abs.substr(0, abs.lastIndexOf('/')) + '/' + rel;
  2442. }
  2443.  
  2444. static suppressHoverTooltip() {
  2445. for (const node of [
  2446. ai.node.parentNode,
  2447. ai.node,
  2448. ai.node.firstElementChild,
  2449. ]) {
  2450. const t = (node || 0).title;
  2451. if (t && t !== node.textContent && !doc.title.includes(t) && !/^https?:\S+$/.test(t)) {
  2452. ai.tooltip = {node, text: t};
  2453. node.title = '';
  2454. break;
  2455. }
  2456. }
  2457. }
  2458.  
  2459. static tabFixUrl() {
  2460. return `data:text/html;charset=utf8,
  2461. <style>
  2462. body {
  2463. margin: 0;
  2464. padding: 0;
  2465. background: #222
  2466. }
  2467. .fit {
  2468. overflow: hidden
  2469. }
  2470. .fit > img {
  2471. max-width: 100vw;
  2472. max-height: 100vh
  2473. }
  2474. body > img {
  2475. margin: auto;
  2476. position: absolute;
  2477. left: 0;
  2478. right: 0;
  2479. top: 0;
  2480. bottom: 0
  2481. }
  2482. </style>
  2483. <body class="fit">
  2484. <img onclick="document.body.classList.toggle('fit')" src="${ai.popup.src}">
  2485. </body>
  2486. `.replace(/[\r\n]+\s*/g, '').replace(/#/g, '%23');
  2487. }
  2488. }
  2489.  
  2490. function setup({rule} = {}) {
  2491. const MPIV_BASE_URL = 'https://w9p.co/userscripts/mpiv/';
  2492. const SETUP_ID = `${PREFIX}setup`;
  2493. const RULE = setup.RULE || (setup.RULE = Symbol('rule'));
  2494. let div = doc.getElementById(SETUP_ID);
  2495. let root = div && div.shadowRoot;
  2496. let {blankRuleElement} = setup;
  2497. /** @type NodeList */
  2498. const UI = new Proxy({}, {
  2499. get(_, id) {
  2500. return root.getElementById(id);
  2501. },
  2502. });
  2503. if (!rule || !div)
  2504. init(new Config({save: true}));
  2505. if (rule)
  2506. installRule(rule);
  2507.  
  2508. function closeSetup(event) {
  2509. if (event && this.id !== 'x') {
  2510. cfg = collectConfig({save: true, clone: this.id === 'apply'});
  2511. Ruler.init();
  2512. if (this.id === 'apply')
  2513. return;
  2514. }
  2515. const el = doc.getElementById(SETUP_ID);
  2516. el && el.remove();
  2517. }
  2518.  
  2519. function collectConfig({save, clone} = {}) {
  2520. const delay = parseInt(UI.delay.value);
  2521. const scale = parseFloat(UI.scale.value.replace(',', '.'));
  2522. let data = {
  2523. css: UI.css.value.trim(),
  2524. delay: !isNaN(delay) && delay >= 0 ? delay : undefined,
  2525. hosts: collectRules(),
  2526. scale: !isNaN(scale) ? Math.max(1, scale) : undefined,
  2527. scales: UI.scales.value
  2528. .trim()
  2529. .split(/[,;]*\s+/)
  2530. .map(x => x.replace(',', '.'))
  2531. .filter(x => !isNaN(parseFloat(x))),
  2532. start: UI.start.value,
  2533. zoom: UI.zoom.value,
  2534. zoomOut: UI.zoomOut.value,
  2535. };
  2536. for (const el of $$('[type="checkbox"]', root))
  2537. data[el.id] = el.checked;
  2538. if (clone)
  2539. data = JSON.parse(JSON.stringify(data));
  2540. return new Config({data, save});
  2541. }
  2542.  
  2543. function collectRules() {
  2544. return [...UI.rules.children]
  2545. .map(el => [el.value.trim(), el[RULE]])
  2546. .sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)
  2547. .map(([s, json]) => json || s)
  2548. .filter(Boolean);
  2549. }
  2550.  
  2551. function exportSettings(e) {
  2552. dropEvent(e);
  2553. const txt = $create('textarea', {
  2554. style: 'opacity:0; position:absolute',
  2555. value: JSON.stringify(collectConfig(), null, ' '),
  2556. });
  2557. root.appendChild(txt);
  2558. txt.select();
  2559. txt.focus();
  2560. document.execCommand('copy');
  2561. e.target.focus();
  2562. txt.remove();
  2563. UI.exportNotification.hidden = false;
  2564. setTimeout(() => (UI.exportNotification.hidden = true), 1000);
  2565. }
  2566.  
  2567. function importSettings(e) {
  2568. dropEvent(e);
  2569. const s = prompt('Paste settings:');
  2570. if (s)
  2571. init(new Config({data: s}));
  2572. }
  2573.  
  2574. function checkRule({target: el}) {
  2575. let json, error;
  2576. const prev = el.previousElementSibling;
  2577. if (el.value) {
  2578. json = Ruler.parse(el.value);
  2579. error = json instanceof Error && (json.message || String(json));
  2580. if (!prev)
  2581. el.insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  2582. } else if (prev) {
  2583. prev.focus();
  2584. el.remove();
  2585. }
  2586. el[RULE] = !error && json;
  2587. el.title = error || '';
  2588. el.setCustomValidity(error || '');
  2589. }
  2590.  
  2591. function focusRule({type, target: el, relatedTarget: from}) {
  2592. if (el === this)
  2593. return;
  2594. if (type === 'paste') {
  2595. setTimeout(() => focusRule.call(this, {target: el}));
  2596. return;
  2597. }
  2598. if (el[RULE])
  2599. el.value = Ruler.format(el[RULE], {expand: true});
  2600. const h = clamp(el.scrollHeight, 15, div.clientHeight / 4);
  2601. if (h > el.offsetHeight)
  2602. el.style.minHeight = h + 'px';
  2603. if (!this.contains(from))
  2604. from = [...$$('[style*="height"]', this)].find(_ => _ !== el);
  2605. if (from) {
  2606. from.style.minHeight = '';
  2607. if (from[RULE])
  2608. from.value = Ruler.format(from[RULE]);
  2609. }
  2610. }
  2611.  
  2612. function installRule(rule) {
  2613. const inputs = UI.rules.children;
  2614. let el = [...inputs].find(el => Util.deepEqual(el[RULE], rule));
  2615. if (!el) {
  2616. el = inputs[0];
  2617. el[RULE] = rule;
  2618. el.value = Ruler.format(rule);
  2619. el.hidden = false;
  2620. const i = Math.max(0, collectRules().indexOf(rule));
  2621. inputs[i].insertAdjacentElement('afterend', el);
  2622. inputs[0].insertAdjacentElement('beforebegin', blankRuleElement.cloneNode());
  2623. }
  2624. const rect = el.getBoundingClientRect();
  2625. if (rect.bottom < 0 ||
  2626. rect.bottom > el.parentNode.offsetHeight)
  2627. el.scrollIntoView();
  2628. el.classList.add('highlight');
  2629. el.addEventListener('animationend', () => el.classList.remove('highlight'), {once: true});
  2630. el.focus();
  2631. }
  2632.  
  2633. function init(config) {
  2634. closeSetup();
  2635. div = $create('div', {
  2636. id: SETUP_ID,
  2637. // prevent the main page from interpreting key presses in inputs as hotkeys
  2638. // which may happen since it sees only the outer <div> in the event |target|
  2639. contentEditable: true,
  2640. });
  2641. root = div.attachShadow({mode: 'open'});
  2642. root.innerHTML = `
  2643. <style>
  2644. :host {
  2645. all: initial !important;
  2646. position: fixed !important;
  2647. z-index: 2147483647 !important;
  2648. top: 20px !important;
  2649. right: 20px !important;
  2650. padding: 20px 30px !important;
  2651. color: #000 !important;
  2652. background: #eee !important;
  2653. box-shadow: 5px 5px 25px 2px #000 !important;
  2654. width: 500px !important;
  2655. border: 1px solid black !important;
  2656. display: flex !important;
  2657. flex-direction: column !important;
  2658. }
  2659. main {
  2660. font: 12px/15px sans-serif;
  2661. }
  2662. ul {
  2663. max-height: calc(100vh - 200px);
  2664. margin: 10px 0 15px 0;
  2665. padding: 0;
  2666. list-style: none;
  2667. }
  2668. li {
  2669. margin: 0;
  2670. padding: .25em 0;
  2671. }
  2672. li.options {
  2673. display: flex;
  2674. align-items: center;
  2675. flex-wrap: wrap;
  2676. }
  2677. label {
  2678. display: inline-flex;
  2679. align-items: center;
  2680. }
  2681. label:not(:last-child) {
  2682. margin-right: 1em;
  2683. }
  2684. label > :not(span) {
  2685. margin-right: .25em;
  2686. }
  2687. label > :not(span):not(:first-child) {
  2688. margin-left: .5em;
  2689. }
  2690. input:first-child {
  2691. margin-left: 0;
  2692. }
  2693. input, select {
  2694. min-height: 1.6em;
  2695. box-sizing: border-box;
  2696. }
  2697. textarea {
  2698. flex: 1;
  2699. resize: vertical;
  2700. margin: 1px 0;
  2701. font: 11px/1.25 Consolas, monospace;
  2702. }
  2703. textarea:invalid {
  2704. background-color: #f002;
  2705. border-color: #800;
  2706. }
  2707. code {
  2708. font-weight: bold;
  2709. }
  2710. a {
  2711. text-decoration: none;
  2712. }
  2713. a:hover {
  2714. text-decoration: underline;
  2715. }
  2716. button {
  2717. padding: .2em 1em;
  2718. margin: 0 1em;
  2719. }
  2720. .column {
  2721. display: flex;
  2722. flex-direction: column;
  2723. }
  2724. .highlight {
  2725. animation: 2s fade-in cubic-bezier(0, .75, .25, 1);
  2726. animation-fill-mode: both;
  2727. }
  2728. #rules textarea {
  2729. word-break: break-all;
  2730. }
  2731. #x {
  2732. position: absolute;
  2733. top: 0;
  2734. right: 0;
  2735. padding: 4px 8px;
  2736. cursor: pointer;
  2737. user-select: none;
  2738. }
  2739. #x:hover {
  2740. background-color: #8884;
  2741. }
  2742. @keyframes fade-in {
  2743. from { background-color: deepskyblue }
  2744. to {}
  2745. }
  2746. @media (prefers-color-scheme: dark) {
  2747. :host {
  2748. color: #aaa !important;
  2749. background: #333 !important;
  2750. }
  2751. a {
  2752. color: deepskyblue;
  2753. }
  2754. textarea, input, select {
  2755. background: #111;
  2756. color: #BBB;
  2757. border-color: #555;
  2758. }
  2759. input[type="checkbox"] {
  2760. filter: invert(1);
  2761. }
  2762. }
  2763. </style>
  2764. <main>
  2765. <a href="${MPIV_BASE_URL}">${GM_info.script.name}</a>
  2766. <div id="x">x</div>
  2767. <ul class="column">
  2768. <li class="options">
  2769. <label>
  2770. <span>Popup:</span>
  2771. <select id="start">
  2772. <option value="auto">automatically
  2773. <option value="context">right click or ctrl
  2774. <option value="ctrl">ctrl
  2775. </select>
  2776. </label>
  2777. <label>
  2778. <span>after</span>
  2779. <input id="delay" type="number" min="0" max="10000" step="50" style="width: 4em">
  2780. <span>ms</span>
  2781. </label>
  2782. <label>
  2783. <input type="checkbox" id="preload">
  2784. <span>Start preloading immediately</span>
  2785. </label>
  2786. </li>
  2787. <li class="options">
  2788. <label>
  2789. <span>Zoom:</span>
  2790. <select id="zoom">
  2791. <option value="context">right click or shift
  2792. <option value="wheel">wheel up or shift
  2793. <option value="shift">shift
  2794. <option value="auto">automatically
  2795. </select>
  2796. </label>
  2797. <label>
  2798. <span>When zoomed out completely</span>
  2799. <select id="zoomOut">
  2800. <option value="stay">stay in zoom mode
  2801. <option value="auto">stay if still hovered
  2802. <option value="close">close popup
  2803. </select>
  2804. </label>
  2805. </li>
  2806. <li class="options">
  2807. <label>
  2808. <span>Only show popup over scaled-down image when natural size is</span>
  2809. <input id="scale" type="number" min="1" max="100" step=".05" style="width: 4em;">
  2810. <span>times larger</span>
  2811. </label>
  2812. </li>
  2813. <li class="options">
  2814. <label>
  2815. <span>Custom scale factors:</span>
  2816. <input id="scales" style="width: 18em"
  2817. placeholder="${Config.DEFAULTS.scales.join(' ')}">
  2818. <span title="${`
  2819. 0 = fit to window
  2820. 0! = same as 0 but also removes smaller values
  2821. * after value marks default zoom factor, example 1*
  2822. Values smaller than non-zoomed size are ignored.
  2823. `.trim().replace(/\n\s+/g, '\n')}" style="cursor:help">(?)</span>
  2824. </label>
  2825. </li>
  2826. <li class="options">
  2827. <label><input type="checkbox" id="center"><span>Always centered</span></label>
  2828. <label><input type="checkbox" id="imgtab"><span>Run in image tabs</span></label>
  2829. <label title="Disable only if you spoof the HTTP headers yourself">
  2830. <input type="checkbox" id="xhr">
  2831. <span>Anti-hotlinking workaround</span>
  2832. </label>
  2833. <label>
  2834. <input type="checkbox" id="globalStatus">
  2835. <span>Expose status on &lt;html&gt; node (note: may cause noticeable slowdown)</small>
  2836. </label>
  2837. </li>
  2838. <li>
  2839. <div class="column">
  2840. <a href="${MPIV_BASE_URL}css.html">Custom CSS:</a>
  2841. <textarea id="css" spellcheck="false"></textarea>
  2842. </div>
  2843. </li>
  2844. <li style="display: flex; justify-content: space-between;">
  2845. <div><a href="${MPIV_BASE_URL}host_rules.html">Custom host rules:</a></div>
  2846. <div style="white-space: nowrap">
  2847. To disable, put any symbol except <code>a..z 0..9 - .</code><br>
  2848. in "d" value, for example <code>"d": "!foo.com"</code>
  2849. </div>
  2850. <div>
  2851. <input id="search" type="search" placeholder="Search"
  2852. style="width: 10em; margin-left: 1em">
  2853. </div>
  2854. </li>
  2855. <li style="
  2856. overflow-y: auto;
  2857. margin-left: -3px;
  2858. margin-right: -3px;
  2859. padding-left: 3px;
  2860. padding-right: 3px;
  2861. ">
  2862. <div id="rules" class="column">
  2863. <textarea rows="1" spellcheck="false"></textarea>
  2864. </div>
  2865. </li>
  2866. <li>
  2867. <div hidden id="installLoading">
  2868. Loading...
  2869. </div>
  2870. <div hidden id="installHint">
  2871. Double-click the rule (or select and press Enter) to add it. Click OK when done.
  2872. </div>
  2873. <a href="${MPIV_BASE_URL}more_host_rules.html" id="install">
  2874. Install rule from repository...</a>
  2875. </li>
  2876. </ul>
  2877. <div style="text-align:center">
  2878. <button id="ok" accesskey="s">Save</button>
  2879. <button id="apply" accesskey="a">Apply</button>
  2880. <button id="import" style="margin-right: 0">Import</button>
  2881. <button id="export" style="margin-left: 0">Export</button>
  2882. <button id="cancel">Cancel</button>
  2883. <div id="exportNotification" hidden style="
  2884. color: green;
  2885. position: absolute;
  2886. bottom: 2px;
  2887. left: 0;
  2888. right: 0;
  2889. font-weight: bold;">Copied to clipboard.</div>
  2890. </div>
  2891. </main>
  2892. `;
  2893. // rules
  2894. const rules = UI.rules;
  2895. rules.addEventListener('input', checkRule);
  2896. rules.addEventListener('focusin', focusRule);
  2897. rules.addEventListener('paste', focusRule);
  2898. blankRuleElement =
  2899. setup.blankRuleElement =
  2900. setup.blankRuleElement || rules.firstElementChild.cloneNode();
  2901. for (const rule of config.hosts || []) {
  2902. const el = blankRuleElement.cloneNode();
  2903. el.value = typeof rule === 'string' ? rule : Ruler.format(rule);
  2904. rules.appendChild(el);
  2905. checkRule({target: el});
  2906. }
  2907. // search rules
  2908. const search = UI.search;
  2909. search.oninput = () => {
  2910. setup.search = search.value;
  2911. const s = search.value.toLowerCase();
  2912. for (const el of rules.children)
  2913. el.hidden = s && !el.value.toLowerCase().includes(s);
  2914. };
  2915. search.value = setup.search || '';
  2916. if (search.value)
  2917. search.oninput();
  2918. // prevent the main page from interpreting key presses in inputs as hotkeys
  2919. // which may happen since it sees only the outer <div> in the event |target|
  2920. root.addEventListener('keydown', e =>
  2921. !e.altKey && !e.ctrlKey && !e.metaKey && e.stopPropagation(), true);
  2922. UI.apply.onclick = UI.cancel.onclick = UI.ok.onclick = UI.x.onclick = closeSetup;
  2923. UI.css.value = config.css;
  2924. UI.delay.value = config.delay;
  2925. UI.export.onclick = exportSettings;
  2926. UI.import.onclick = importSettings;
  2927. UI.install.onclick = setupRuleInstaller;
  2928. UI.scale.value = config.scale;
  2929. UI.scales.value = config.scales.join(' ');
  2930. UI.start.value = config.start;
  2931. UI.start.onchange = function () {
  2932. UI.delay.closest('label').hidden =
  2933. UI.preload.closest('label').hidden =
  2934. this.value !== 'auto';
  2935. };
  2936. UI.start.onchange();
  2937. UI.xhr.onclick = ({target: el}) => el.checked || confirm(el.closest('[title]').title);
  2938. UI.zoom.value = config.zoom;
  2939. UI.zoomOut.value = config.zoomOut;
  2940. for (const el of $$('[type="checkbox"]', root))
  2941. el.checked = config[el.id];
  2942. for (const el of $$('a[href^="http"]', root)) {
  2943. el.target = '_blank';
  2944. el.rel = 'noreferrer noopener external';
  2945. }
  2946. doc.body.appendChild(div);
  2947. requestAnimationFrame(() => {
  2948. UI.css.style.minHeight = clamp(UI.css.scrollHeight, 40, div.clientHeight / 4) + 'px';
  2949. });
  2950. }
  2951. }
  2952.  
  2953. async function setupRuleInstaller(e) {
  2954. dropEvent(e);
  2955. const parent = this.parentElement;
  2956. parent.children.installLoading.hidden = false;
  2957. this.remove();
  2958. let rules;
  2959.  
  2960. try {
  2961. rules = extractRules((await Remoting.getDoc(this.href)).doc);
  2962. const selector = $create('select', {
  2963. size: 8,
  2964. style: 'width: 100%',
  2965. ondblclick: e => e.target !== selector && maybeSetup(e),
  2966. onkeyup: e => e.key === 'Enter' && maybeSetup(e),
  2967. });
  2968. selector.append(...rules.map(renderRule));
  2969. selector.selectedIndex = findMatchingRuleIndex();
  2970. // remove "name" since the installed rules don't need it
  2971. for (const r of rules)
  2972. delete r.name;
  2973. parent.children.installLoading.remove();
  2974. parent.children.installHint.hidden = false;
  2975. parent.appendChild(selector);
  2976. } catch (e) {
  2977. parent.textContent = 'Error loading rules: ' + (e.message || e);
  2978. }
  2979.  
  2980. function extractRules(doc) {
  2981. const code = $('script', doc).textContent;
  2982. // sort by name
  2983. return JSON.parse(code.match(/var\s+rules\s*=\s*(\[.+]);?[\r\n]/)[1])
  2984. .filter(r => !r.d || hostname.includes(r.d))
  2985. .sort((a, b) =>
  2986. (a = a.name.toLowerCase()) < (b = b.name.toLowerCase()) ? -1 :
  2987. a > b ? 1 :
  2988. 0);
  2989. }
  2990.  
  2991. function findMatchingRuleIndex() {
  2992. // get the core part of the current domain that's not "www", "m", etc.
  2993. const h = hostname.split('.');
  2994. const core = h[0] === 'www' || h.length > 2 && h[0].length === 1 ? h[1] : h[0];
  2995. // find a rule matching the domain core
  2996. return rules.findIndex(r =>
  2997. r.name.toLowerCase().includes(core) ||
  2998. r.d && hostname.includes(r.d));
  2999. }
  3000.  
  3001. function renderRule(r) {
  3002. const {name, ...copy} = r;
  3003. return $create('option', {
  3004. textContent: name,
  3005. title: Ruler.format(copy, {expand: true})
  3006. .replace(/^{|\s*}$/g, '')
  3007. .split('\n')
  3008. .slice(0, 12)
  3009. .map(renderTitleLine)
  3010. .filter(Boolean)
  3011. .join('\n'),
  3012. });
  3013. }
  3014.  
  3015. function renderTitleLine(line, i, arr) {
  3016. return (
  3017. // show ... on 10th line if there are more lines
  3018. i === 9 && arr.length > 10 ? '...' :
  3019. i > 10 ? '' :
  3020. // truncate to 100 chars
  3021. (line.length > 100 ? line.slice(0, 100) + '...' : line)
  3022. // strip the leading space
  3023. .replace(/^\s/, ''));
  3024. }
  3025.  
  3026. function maybeSetup(e) {
  3027. if (!e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey)
  3028. setup({rule: rules[e.currentTarget.selectedIndex]});
  3029. }
  3030. }
  3031.  
  3032. App.init();