Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

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

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