Mouseover Popup Image Viewer

Shows images and videos behind links and thumbnails.

目前为 2020-01-28 提交的版本,查看 最新版本

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