Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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