Greasy Fork 还支持 简体中文。

Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前為 2020-01-14 提交的版本,檢視 最新版本

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