Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

当前为 2020-01-15 提交的版本,查看 最新版本

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