Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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