Image Viewer

View full image without leaving the page or on a new tab without ads

当前为 2022-05-20 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Image Viewer
  3. // @version 1.3.0
  4. // @description View full image without leaving the page or on a new tab without ads
  5. // @namespace https://github.com/nikolay-borzov
  6. // @author nikolay-borzov
  7. // @license MIT
  8. // @icon https://raw.githubusercontent.com/nikolay-borzov/user-scripts/master/image-viewer/icon.png
  9. // @homepageURL https://github.com/nikolay-borzov/user-scripts
  10. // @homepage https://github.com/nikolay-borzov/user-scripts
  11. // @supportURL https://github.com/nikolay-borzov/user-scripts/issues
  12. // @match *://*/*
  13. // @connect fastpic.org
  14. // @connect fastpic.ru
  15. // @connect ibb.co
  16. // @connect imagebam.com
  17. // @connect imagetwist.com
  18. // @connect imagevenue.com
  19. // @connect imgdrive.net
  20. // @connect imgtaxi.com
  21. // @connect www.turboimagehost.com
  22. // @noframes
  23. // @run-at document-start
  24. // @exclude http://imgbb.co/*
  25. // @exclude https://adult-images.ru/*
  26. // @exclude https://fastpic.org/*
  27. // @exclude https://freescreens.ru/*
  28. // @exclude https://imageban.ru/*
  29. // @exclude https://imagetwist.com/*
  30. // @exclude https://imgadult.com/*
  31. // @exclude https://imgbase.ru/*
  32. // @exclude https://imgbox.com/*
  33. // @exclude https://imgbum.ru/*
  34. // @exclude https://imgclick.ru/*
  35. // @exclude https://imgdrive.net/*
  36. // @exclude https://imgtaxi.com/*
  37. // @exclude https://payforpic.ru/*
  38. // @exclude https://piccash.net/*
  39. // @exclude https://picclick.ru/*
  40. // @exclude https://picforall.ru/*
  41. // @exclude https://vfl.ru/*
  42. // @exclude https://www.imagebam.com/*
  43. // @exclude https://www.imagevenue.com/*
  44. // @exclude https://www.turboimagehost.com/*
  45. // @grant GM_addStyle
  46. // @grant GM_xmlhttpRequest
  47. // @grant GM.xmlHttpRequest
  48. // @grant GM_setValue
  49. // @grant GM.setValue
  50. // @grant GM_getValue
  51. // @grant GM.getValue
  52. // @grant GM_registerMenuCommand
  53. // @grant GM.registerMenuCommand
  54. // @grant GM_openInTab
  55. // @grant GM.openInTab
  56. // ==/UserScript==
  57.  
  58. ;(function () {
  59. /* global Bliss */
  60. // eslint-disable-next-line -- blissfuljs v1.0.6 Shy https://blissfuljs.com/
  61. !function(){function e(o,i,t){return i=void 0===i?1:i,(t=t||i+1)-i<=1?function(){if(arguments.length<=i||"string"===c.type(arguments[i]))return o.apply(this,arguments);var t,e,n=arguments[i];for(e in n){var r=Array.prototype.slice.call(arguments);r.splice(i,1,e,n[e]),t=o.apply(this,r);}return t}:e(e(o,i+1,t),i,t-1)}function s(e,n,t){var r=a(t);if("string"===r){var o=Object.getOwnPropertyDescriptor(n,t);!o||o.writable&&o.configurable&&o.enumerable&&!o.get&&!o.set?e[t]=n[t]:(delete e[t],Object.defineProperty(e,t,o));}else if("array"===r)t.forEach(function(t){t in n&&s(e,n,t);});else for(var i in n)t&&("regexp"===r&&!t.test(i)||"function"===r&&!t.call(n,i))||s(e,n,i);return e}function a(t){if(null===t)return "null";if(void 0===t)return "undefined";var e=(Object.prototype.toString.call(t).match(/^\[object\s+(.*?)\]$/)[1]||"").toLowerCase();return "number"==e&&isNaN(t)?"nan":e}var c=self.Bliss=s(function(t,e){return 2==arguments.length&&!e||!t?null:"string"===c.type(t)?(e||document).querySelector(t):t||null},self.Bliss);s(c,{extend:s,overload:e,type:a,property:c.property||"_",listeners:new(self.WeakMap?WeakMap:Map),original:{addEventListener:(self.EventTarget||Node).prototype.addEventListener,removeEventListener:(self.EventTarget||Node).prototype.removeEventListener},sources:{},noop:function(){},$:function(t,e){return t instanceof Node||t instanceof Window?[t]:2!=arguments.length||e?Array.prototype.slice.call("string"==typeof t?(e||document).querySelectorAll(t):t||[]):[]},defined:function(){for(var t=0;t<arguments.length;t++)if(void 0!==arguments[t])return arguments[t]},create:function(t,e){return t instanceof Node?c.set(t,e):(1===arguments.length&&(e="string"===c.type(t)?{}:(t=(e=t).tag,c.extend({},e,function(t){return "tag"!==t}))),c.set(document.createElement(t||"div"),e))},each:function(t,e,n){for(var r in n=n||{},t)n[r]=e.call(t,r,t[r]);return n},ready:function(e,t,n){if("function"!=typeof e||t||(t=e,e=void 0),e=e||document,t&&("loading"!==e.readyState?t():c.once(e,"DOMContentLoaded",function(){t();})),!n)return new Promise(function(t){c.ready(e,t,!0);})},Class:function(t){var e,n,r=["constructor","extends","abstract","static"].concat(Object.keys(c.classProps)),o=t.hasOwnProperty("constructor")?t.constructor:c.noop;2==arguments.length?(n=arguments[0],t=arguments[1]):((n=function(){if(this.constructor.__abstract&&this.constructor===n)throw new Error("Abstract classes cannot be directly instantiated.");n.super&&!e&&n.super.apply(this,arguments),o.apply(this,arguments);}).super=t.extends||null,!n.super||(e=0===(n.super+"").indexOf("class "))&&console.error(`You are using $.Class() to create a fake function-based class that extends a native JS class. This will not work. You should convert your code to use native JS classes too. You can still pass a class into $.Class() to use its conveniences.`),n.prototype=c.extend(Object.create(n.super?n.super.prototype:Object),{constructor:n}),n.prototype.super=n.super?n.super.prototype:null,n.__abstract=!!t.abstract);function i(t){return this.hasOwnProperty(t)&&-1===r.indexOf(t)}if(t.static)for(var s in c.extend(n,t.static,i),c.classProps)s in t.static&&c.classProps[s](n,t.static[s]);for(s in c.extend(n.prototype,t,i),c.classProps)s in t&&c.classProps[s](n.prototype,t[s]);return n},classProps:{lazy:e(function(t,e,n){return Object.defineProperty(t,e,{get:function(){var t=n.call(this);return Object.defineProperty(this,e,{value:t,configurable:!0,enumerable:!0,writable:!0}),t},set:function(t){Object.defineProperty(this,e,{value:t,configurable:!0,enumerable:!0,writable:!0});},configurable:!0,enumerable:!0}),t}),live:e(function(t,n,r){return "function"===c.type(r)&&(r={set:r}),Object.defineProperty(t,n,{get:function(){var t=this["_"+n],e=r.get&&r.get.call(this,t);return void 0!==e?e:t},set:function(t){var e=this["_"+n],e=r.set&&r.set.call(this,t,e);this["_"+n]=void 0!==e?e:t;},configurable:r.configurable,enumerable:r.enumerable}),t})},include:function(){var n=arguments[arguments.length-1],t=2===arguments.length&&arguments[0],r=document.createElement("script");return t?Promise.resolve():new Promise(function(t,e){c.set(r,{async:!0,onload:function(){t(r),r.parentNode&&r.parentNode.removeChild(r);},onerror:function(){e(r);},src:n,inside:document.head});})},load:function t(r,e){e=e?new URL(e,location.href):location.href,r=new URL(r,e);e=t.loading=t.loading||{};return e[r+""]||(/\.css$/.test(r.pathname)?e[r+""]=new Promise(function(t,e){var n=c.create("link",{href:r,rel:"stylesheet",inside:document.head,onload:function(){t(n);},onerror:function(){e(n);}});}):e[r+""]=c.include(r))},fetch:function(t,e){if(!t)throw new TypeError("URL parameter is mandatory and cannot be "+t);var n,r=s({url:new URL(t,location),data:"",method:"GET",headers:{},xhr:new XMLHttpRequest},e);for(n in r.method=r.method.toUpperCase(),c.hooks.run("fetch-args",r),"GET"===r.method&&r.data&&(r.url.search+=r.data),document.body.setAttribute("data-loading",r.url),r.xhr.open(r.method,r.url.href,!1!==r.async,r.user,r.password),e)if("upload"===n)r.xhr.upload&&"object"==typeof e[n]&&c.extend(r.xhr.upload,e[n]);else if(n in r.xhr)try{r.xhr[n]=e[n];}catch(t){self.console&&console.error(t);}var o,t=Object.keys(r.headers).map(function(t){return t.toLowerCase()});for(o in "GET"!==r.method&&-1===t.indexOf("content-type")&&r.xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"),r.headers)void 0!==r.headers[o]&&r.xhr.setRequestHeader(o,r.headers[o]);t=new Promise(function(t,e){r.xhr.onload=function(){document.body.removeAttribute("data-loading"),0===r.xhr.status||200<=r.xhr.status&&r.xhr.status<300||304===r.xhr.status?t(r.xhr):e(c.extend(Error(r.xhr.statusText),{xhr:r.xhr,get status(){return this.xhr.status}}));},r.xhr.onerror=function(){document.body.removeAttribute("data-loading"),e(c.extend(Error("Network Error"),{xhr:r.xhr}));},r.xhr.ontimeout=function(){document.body.removeAttribute("data-loading"),e(c.extend(Error("Network Timeout"),{xhr:r.xhr}));},r.xhr.send("GET"===r.method?null:r.data);});return t.xhr=r.xhr,t},value:function(t){var e="string"!=typeof t;return c.$(arguments).slice(+e).reduce(function(t,e){return t&&t[e]},e?t:self)}}),c.Hooks=new c.Class({add:function(t,e,n){if("string"==typeof arguments[0])(Array.isArray(t)?t:[t]).forEach(function(t){this[t]=this[t]||[],e&&this[t][n?"unshift":"push"](e);},this);else for(var t in arguments[0])this.add(t,arguments[0][t],e);},run:function(t,e){this[t]=this[t]||[],this[t].forEach(function(t){t.call(e&&e.context?e.context:e,e);});}}),c.hooks=new c.Hooks;c.property;c.Element=function(t){this.subject=t,this.data={},this.bliss={};},c.Element.prototype={set:e(function(t,e){t in c.setProps?c.setProps[t].call(this,e):t in this?this[t]=e:this.setAttribute(t,e);},0),transition:function(o,i){return new Promise(function(t,e){var n,r;"transition"in this.style&&0!==i?(n=c.extend({},this.style,/^transition(Duration|Property)$/),c.style(this,{transitionDuration:(i||400)+"ms",transitionProperty:Object.keys(o).join(", ")}),c.once(this,"transitionend",function(){clearTimeout(r),c.style(this,n),t(this);}),r=setTimeout(t,i+50,this),c.style(this,o)):(c.style(this,o),t(this));}.bind(this))},fire:function(t,e){var n=document.createEvent("HTMLEvents");return n.initEvent(t,!0,!0),this.dispatchEvent(c.extend(n,e))},bind:e(function(t,n){var e;1<arguments.length&&("function"===c.type(n)||n.handleEvent)&&(e=n,(n="object"===c.type(arguments[2])?arguments[2]:{capture:!!arguments[2]}).callback=e);var r=c.listeners.get(this)||{};t.trim().split(/\s+/).forEach(function(t){var e;-1<t.indexOf(".")&&(e=(t=t.split("."))[1],t=t[0]),r[t]=r[t]||[],0===r[t].filter(function(t){return t.callback===n.callback&&t.capture==n.capture}).length&&r[t].push(c.extend({className:e},n)),c.original.addEventListener.call(this,t,n.callback,n);},this),c.listeners.set(this,r);},0),unbind:e(function(t,i){var e;i&&("function"===c.type(i)||i.handleEvent)&&(e=i,i=arguments[2]),(i=(i="boolean"==c.type(i)?{capture:i}:i)||{}).callback=i.callback||e;var s=c.listeners.get(this);(t||"").trim().split(/\s+/).forEach(function(t){var e,n;if(-1<t.indexOf(".")&&(e=(t=t.split("."))[1],t=t[0]),!s)return t&&i.callback?c.original.removeEventListener.call(this,t,i.callback,i.capture):void 0;for(n in s)if(!t||n===t)for(var r,o=0;r=s[n][o];o++)e&&e!==r.className||i.callback&&i.callback!==r.callback||!!i.capture!=!!r.capture&&(t||i.callback||void 0!==i.capture)||(s[n].splice(o,1),c.original.removeEventListener.call(this,n,r.callback,r.capture),o--);},this);},0),when:function(r,o){var t=this;return new Promise(function(n){t.addEventListener(r,function t(e){o&&!o.call(this,e)||(this.removeEventListener(r,t),n(e));});})},toggleAttribute:function(t,e,n){(n=arguments.length<3?null!==e:n)?this.setAttribute(t,e):this.removeAttribute(t);}},c.setProps={style:function(t){for(var e in t)e in this.style?this.style[e]=t[e]:this.style.setProperty(e,t[e]);},attributes:function(t){for(var e in t)this.setAttribute(e,t[e]);},properties:function(t){c.extend(this,t);},events:function(t){if(1!=arguments.length||!t||!t.addEventListener)return c.bind.apply(this,[this].concat(c.$(arguments)));var e,n=this;if(c.listeners){var r,o=c.listeners.get(t);for(r in o)o[r].forEach(function(t){c.bind(n,r,t.callback,t.capture);});}for(e in t)0===e.indexOf("on")&&(this[e]=t[e]);},once:e(function(t,e){function n(){return c.unbind(r,t,n),e.apply(r,arguments)}var r=this;c.bind(this,t,n,{once:!0});},0),delegate:e(function(t,e,n){c.bind(this,t,function(t){t.target.closest(e)&&n.call(this,t);});},0,2),contents:function(t){!t&&0!==t||(Array.isArray(t)?t:[t]).forEach(function(t){var e=c.type(t);/^(string|number)$/.test(e)?t=document.createTextNode(t+""):"object"===e&&(t=c.create(t)),t instanceof Node&&this.appendChild(t);},this);},inside:function(t){t&&t.appendChild(this);},before:function(t){t&&t.parentNode.insertBefore(this,t);},after:function(t){t&&t.parentNode.insertBefore(this,t.nextSibling);},start:function(t){t&&t.insertBefore(this,t.firstChild);},around:function(t){t&&t.parentNode&&c.before(this,t),this.appendChild(t);}},c.Array=function(t){this.subject=t;},c.Array.prototype={all:function(t){var e=c.$(arguments).slice(1);return this[t].apply(this,e)}},c.add=e(function(r,n,o,t){o=c.extend({$:!0,element:!0,array:!0},o),"function"==c.type(n)&&(!o.element||r in c.Element.prototype&&t||(c.Element.prototype[r]=function(){return this.subject&&c.defined(n.apply(this.subject,arguments),this.subject)}),!o.array||r in c.Array.prototype&&t||(c.Array.prototype[r]=function(){var e=arguments;return this.subject.map(function(t){return t&&c.defined(n.apply(t,e),t)})}),o.$&&(c.sources[r]=c[r]=n,(o.array||o.element)&&(c[r]=function(){var t=[].slice.apply(arguments),e=t.shift(),n=o.array&&Array.isArray(e)?"Array":"Element";return c[n].prototype[r].apply({subject:e},t)})));},0),c.add(c.Array.prototype,{element:!1}),c.add(c.Element.prototype),c.add(c.setProps),c.add(c.classProps,{element:!1,array:!1});var n=document.createElement("_");c.add(c.extend({},HTMLElement.prototype,function(t){return "function"===c.type(n[t])}),null,!0);}();
  62. // eslint-disable-next-line
  63. const $ = Bliss;
  64. // eslint-disable-next-line
  65. const $$ = Bliss.$;
  66.  
  67. const GM_METHOD_MAP = {
  68. GM_addStyle: 'addStyle',
  69. GM_deleteValue: 'deleteValue',
  70. GM_getResourceURL: 'getResourceUrl',
  71. GM_getValue: 'getValue',
  72. GM_listValues: 'listValues',
  73. GM_notification: 'notification',
  74. GM_openInTab: 'openInTab',
  75. GM_registerMenuCommand: 'registerMenuCommand',
  76. GM_setClipboard: 'setClipboard',
  77. GM_setValue: 'setValue',
  78. GM_xmlhttpRequest: 'xmlHttpRequest',
  79. GM_getResourceText: 'getResourceText',
  80. }
  81.  
  82. function getGM4PolyfilledMethod(methodName) {
  83. const gm4MethodName = GM_METHOD_MAP[methodName]
  84.  
  85. if (GM !== undefined && gm4MethodName in GM) {
  86. return GM[gm4MethodName]
  87. } else if (methodName in window) {
  88. return function (...arguments_) {
  89. return new Promise((resolve, reject) => {
  90. try {
  91. // eslint-disable-next-line unicorn/no-null
  92. resolve(window[methodName].apply(null, arguments_))
  93. } catch (error) {
  94. reject(error)
  95. }
  96. })
  97. }
  98. }
  99.  
  100. return async function () {
  101. throw new Error(`Method ${methodName} is not available. Missing @grant?`)
  102. }
  103. }
  104.  
  105. let addStyle = (css) => {
  106. addStyle =
  107. 'GM_addStyle' in window
  108. ? GM_addStyle // eslint-disable-line camelcase
  109. : (css) => {
  110. const head = document.querySelectorAll('head')[0]
  111. const style = document.createElement('style')
  112.  
  113. style.innerHTML = css
  114. head.append(style)
  115.  
  116. return style
  117. }
  118.  
  119. return addStyle(css)
  120. }
  121.  
  122. let request = (details) => {
  123. request = getGM4PolyfilledMethod('GM_xmlhttpRequest')
  124.  
  125. return request(details)
  126. }
  127.  
  128. const store = {
  129. getValue: (name, defaultValue) => {
  130. store.getValue = getGM4PolyfilledMethod('GM_getValue')
  131.  
  132. return store.getValue(name, defaultValue)
  133. },
  134.  
  135. setValue: (name, value) => {
  136. store.setValue = getGM4PolyfilledMethod('GM_setValue')
  137.  
  138. return store.setValue(name, value)
  139. },
  140.  
  141. async patch(name, value) {
  142. const oldValue = await store.getValue(name)
  143.  
  144. store.setValue(name, {
  145. ...oldValue,
  146. ...value,
  147. })
  148. },
  149. }
  150.  
  151. let registerMenuCommand = (name, onClick, accessKey) => {
  152. registerMenuCommand = getGM4PolyfilledMethod('GM_registerMenuCommand')
  153.  
  154. return registerMenuCommand(name, onClick, accessKey)
  155. }
  156.  
  157. let openInTab = (url, openInBackground) => {
  158. openInTab = getGM4PolyfilledMethod('GM_openInTab')
  159.  
  160. return openInTab(url, openInBackground)
  161. }
  162.  
  163. const imgbum = {
  164. id: 'imgbum',
  165. name: 'imgbum.ru',
  166. linkRegExp: /\/imgbum\.(net|ru)/,
  167.  
  168. async getURL(link) {
  169. return link.thumbnailURL.replace('-thumb', '')
  170. },
  171. }
  172.  
  173. const adultImages = {
  174. id: 'adult-images',
  175. name: 'Adult-Images.ru',
  176. linkRegExp: /\/(adult-images|money-pic)\.ru/,
  177.  
  178. getURL: imgbum.getURL,
  179. }
  180.  
  181. async function getURLFromPage(link, extractor, requestDetails) {
  182. const html = await getPageHtml({ url: link.url, ...requestDetails })
  183.  
  184. const match = extractor.imageURLRegExp?.exec(html)
  185.  
  186. let url
  187.  
  188. if (match) {
  189. url = match.groups ? match.groups.url : match[1]
  190. }
  191.  
  192. if (!url) {
  193. console.error(
  194. `[image-viewer] Failed to get URL from page source: ${link.url}`
  195. )
  196. }
  197.  
  198. return url
  199. }
  200.  
  201. async function getPageHtml(requestDetails) {
  202. const response = await request(requestDetails)
  203.  
  204. return response.responseText
  205. }
  206.  
  207. const fastpic = {
  208. id: 'fastpic',
  209. name: 'FastPic',
  210. linkRegExp: /fastpic\.(?:ru|org)\/view/,
  211. imageURLRegExp: /src="(?<url>http[^"]+)" class="image img-fluid"/,
  212. getURL: getURLFromPage,
  213. }
  214.  
  215. const URL_PARTS_REGEXP = /i(\d+).+\.(ru|org)\/big(\/\d+\/\d+\/).+\/([^/]+)$/
  216.  
  217. const fastpicDirect = {
  218. id: 'fastpicDirect',
  219. name: 'FastPic (direct link)',
  220. linkRegExp: /fastpic\.(?:ru|org)\/big/,
  221.  
  222. async getURL(link) {
  223. const [, index, domain, date, filename] =
  224. URL_PARTS_REGEXP.exec(link.url) || []
  225.  
  226. const url = `https://fastpic.${domain}/view/${index}${date}${filename}.html`
  227.  
  228. return fastpic.getURL({ ...link, url }, fastpic)
  229. },
  230. }
  231.  
  232. const imagebam = {
  233. id: 'imagebam',
  234. name: 'ImageBam',
  235. linkRegExp: /www\.imagebam\.com\//,
  236. imageURLRegExp: /src="(?<url>[^"]+)".+class="main-image/,
  237.  
  238. async getURL(link, extractor) {
  239. return getURLFromPage(link, extractor, {
  240. cookie: 'nsfw_inter=1',
  241. })
  242. },
  243. }
  244.  
  245. const DATE_PATTERN = /(\d{4})\.(\d{2})\.(\d{2})/
  246.  
  247. const imageban = {
  248. id: 'imageban',
  249. name: 'ImageBan.ru',
  250. linkRegExp: /imageban\.ru\/show/,
  251.  
  252. async getURL(link) {
  253. return link.thumbnailURL
  254. .replace('thumbs', 'out')
  255. .replace(DATE_PATTERN, '$1/$2/$3')
  256. },
  257. }
  258.  
  259. const imagebanDirect = {
  260. id: 'imagebanDirect',
  261. name: 'ImageBan.ru (direct link)',
  262. linkRegExp: /imageban\.ru\/out/,
  263.  
  264. async getURL(link) {
  265. return link.url
  266. },
  267. }
  268.  
  269. const imagetwist = {
  270. id: 'imagetwist',
  271. name: 'ImageTwist',
  272. linkRegExp: /imagetwist\.com/,
  273. viewMode: 'origin-download',
  274.  
  275. async getURL(link) {
  276. const imageName = link.url.split('/').pop()?.replace('.html', '')
  277. const extension = imageName?.split('.').pop() ?? ''
  278. const imageUrl = link.thumbnailURL
  279. .replace('/th/', '/i/')
  280. .slice(0, -extension.length)
  281.  
  282. return `${imageUrl}${extension}/${imageName}`
  283. },
  284. }
  285.  
  286. const HOST_REPLACE_REG_EXP = /(picturelol|picshick|imageshimage)/
  287.  
  288. const imagetwistBased = {
  289. id: 'imagetwistBased',
  290. name: 'ImageTwist based (legacy)',
  291. hosts: ['Picturelol.com', 'PicShick.com', 'Imageshimage.com'],
  292. linkRegExp: /(picturelol|picshick|imageshimage)\.com/,
  293. viewMode: 'origin-download',
  294.  
  295. async getURL(link) {
  296. const imageName = link.url.split('/').pop()
  297. const imageUrl = link.thumbnailURL
  298. .replace('/th/', '/i/')
  299. .replace(HOST_REPLACE_REG_EXP, 'imagetwist')
  300.  
  301. return `${imageUrl}/${imageName}`
  302. },
  303. }
  304.  
  305. const imagevenue = {
  306. id: 'imagevenue,',
  307. name: 'ImageVenue.com',
  308. linkRegExp: /imagevenue\.com\//,
  309. imageURLRegExp: /data-toggle="full">\W*<img src="(?<url>[^"]*)/im,
  310. getURL: getURLFromPage,
  311. }
  312.  
  313. const imgadult = {
  314. id: 'imgadult',
  315. name: 'ImgAdult',
  316. linkRegExp: /\/imgadult\.com/,
  317.  
  318. async getURL(link) {
  319. return link.thumbnailURL.replace('/small/', '/big/')
  320. },
  321. }
  322.  
  323. const imgbb = {
  324. id: 'imgbb',
  325. name: 'ImgBB',
  326. linkRegExp: /\/ibb\.co/,
  327. imageURLRegExp: /rel="image_src" href="(?<url>http[^"]+)"/,
  328.  
  329. async getURL(link) {
  330. if (link.thumbnailURL.includes('//thumb')) {
  331. return link.thumbnailURL.replace('//thumb', '//image')
  332. }
  333.  
  334. return getURLFromPage(link, imgbb)
  335. },
  336. }
  337.  
  338. const imgbox = {
  339. id: 'imgbox',
  340. name: 'imgbox',
  341. linkRegExp: /\/imgbox\.com/,
  342.  
  343. async getURL(link) {
  344. return link.thumbnailURL.replace('/thumbs', '/images').replace('_t', '_o')
  345. },
  346. }
  347.  
  348. const imgdrive = {
  349. id: 'imgdrive',
  350. name: 'ImgDrive.net',
  351. linkRegExp: /\/imgdrive\.net/,
  352. viewMode: 'origin-download',
  353.  
  354. async getURL(link) {
  355. return link.thumbnailURL
  356. .replace('/small/', '/big/')
  357. .replace('/small-medium/', '/big/')
  358. },
  359. }
  360.  
  361. const imgtaxi = {
  362. id: 'imgtaxi',
  363. name: 'ImgTaxi.com',
  364. linkRegExp: /\/imgtaxi\.com/,
  365. viewMode: 'origin-download',
  366. getURL: imgdrive.getURL,
  367. }
  368.  
  369. const piccash = {
  370. id: 'piccash',
  371. name: 'PicCash',
  372. linkRegExp: /\/piccash\.net/,
  373.  
  374. async getURL(link) {
  375. return link.thumbnailURL.replace('_thumb', '_full').replace('-thumb', '')
  376. },
  377. }
  378.  
  379. const picforall = {
  380. id: 'picforall',
  381. name: 'PicForAll',
  382. hosts: [
  383. 'freescreens.ru',
  384. 'imgclick.ru',
  385. 'picclick.ru',
  386. 'payforpic.ru',
  387. 'picforall.ru',
  388. 'imgbase.ru',
  389. ],
  390. linkRegExp:
  391. /\/(freescreens|imgclick|picclick|payforpic|picforall|imgbase)\.ru/,
  392. getURL: imgbum.getURL,
  393. }
  394.  
  395. const turboimagehost = {
  396. id: 'turboimagehost',
  397. name: 'TurboImageHost.com',
  398. linkRegExp: /turboimagehost\.com\/p/,
  399. imageURLRegExp: /rel="image_src" href="(?<url>http[^"]+)"/,
  400. viewMode: 'new-tab',
  401. getURL: getURLFromPage,
  402. }
  403.  
  404. const REMOVE_SUFFIX_REGEXP = /_.?(.+)$/
  405.  
  406. const vfl = {
  407. id: 'vfl',
  408. name: 'VFL.Ru',
  409. linkRegExp: /^http:\/\/vfl\.ru/,
  410.  
  411. async getURL(link) {
  412. return link.thumbnailURL.replace(REMOVE_SUFFIX_REGEXP, '$1')
  413. },
  414. }
  415.  
  416. const hostExtractors = /* #__PURE__ */ Object.freeze({
  417. __proto__: null,
  418. adultImages,
  419. fastpic,
  420. fastpicDirect,
  421. imagebam,
  422. imageban,
  423. imagebanDirect,
  424. imagetwist,
  425. imagetwistBased,
  426. imagevenue,
  427. imgadult,
  428. imgbb,
  429. imgbox,
  430. imgbum,
  431. imgdrive,
  432. imgtaxi,
  433. piccash,
  434. picforall,
  435. turboimagehost,
  436. vfl,
  437. })
  438.  
  439. let extractorsActive = []
  440.  
  441. const extractors = Object.values(hostExtractors).filter(Boolean)
  442.  
  443. const extractorsByID = extractors.reduce((result, extractor) => {
  444. result[extractor.id] = extractor
  445.  
  446. return result
  447. }, {})
  448.  
  449. const urlExtractor = {
  450. getImageHostsMetadata() {
  451. const result = extractors.map(({ id, name, hosts }) => ({
  452. id,
  453. name,
  454. description: hosts ? hosts.join(', ') : '',
  455. }))
  456.  
  457. return sortCaseInsensitive(result, ({ name }) => name)
  458. },
  459.  
  460. async getImageURL(link) {
  461. const extractor = extractorsByID[link.host]
  462.  
  463. const imageURL = await extractor.getURL(link, extractor)
  464.  
  465. if (!imageURL) {
  466. console.error(
  467. `[image-viewer] Failed to get URL for ${link.host}:${link.url}`
  468. )
  469. }
  470.  
  471. return imageURL
  472. },
  473.  
  474. getExtractorByHost(hostId) {
  475. return extractorsByID[hostId]
  476. },
  477.  
  478. getHostExtractorMatcher(enabledHosts) {
  479. extractorsActive = extractors.filter((extractor) =>
  480. enabledHosts.includes(extractor.id)
  481. )
  482.  
  483. let previousExtractor
  484.  
  485. return (url) => {
  486. if (previousExtractor && previousExtractor.linkRegExp.test(url)) {
  487. return previousExtractor
  488. }
  489.  
  490. const extractor = extractorsActive.find((extractor) =>
  491. extractor.linkRegExp.test(url)
  492. )
  493.  
  494. if (extractor) {
  495. previousExtractor = extractor
  496.  
  497. return extractor
  498. }
  499. }
  500. },
  501. }
  502.  
  503. function sortCaseInsensitive(items, getValue) {
  504. return items
  505. .map((value, index) => ({ index, value: getValue(value).toLowerCase() }))
  506. .sort((a, b) => {
  507. if (a.value > b.value) {
  508. return 1
  509. }
  510. if (a.value < b.value) {
  511. return -1
  512. }
  513.  
  514. return 0
  515. })
  516. .map((m) => items[m.index])
  517. }
  518.  
  519. const CLASSES$1 = {
  520. open: 'iv-config-form--open',
  521. }
  522.  
  523. let configMenu
  524. const currentHost = unsafeWindow.location.host
  525.  
  526. async function initHostConfig() {
  527. const config = await getHostConfig()
  528.  
  529. await registerMenuCommand('Settings', () => showMenu(config))
  530.  
  531. return config
  532. }
  533.  
  534. async function getHostConfig() {
  535. const hosts = urlExtractor.getImageHostsMetadata()
  536.  
  537. const storedConfig = await store.getValue(currentHost, { hosts: {} })
  538. const enabledHosts = []
  539.  
  540. for (const host of hosts) {
  541. const id = host.id
  542. const isEnabled = id in storedConfig.hosts ? storedConfig.hosts[id] : true
  543.  
  544. host.isEnabled = isEnabled
  545. storedConfig.hosts[id] = isEnabled
  546.  
  547. if (isEnabled) {
  548. enabledHosts.push(id)
  549. }
  550. }
  551.  
  552. storedConfig.hosts = hosts.reduce((result, host) => {
  553. result[host.id] = host.isEnabled
  554.  
  555. return result
  556. }, {})
  557.  
  558. return {
  559. hosts,
  560. storedConfig,
  561. enabledHosts,
  562. }
  563. }
  564.  
  565. function showMenu(config) {
  566. createMenuElement(config).classList.add(CLASSES$1.open)
  567. }
  568.  
  569. function createMenuElement(config) {
  570. if (configMenu) {
  571. return configMenu
  572. }
  573.  
  574. const rows = config.hosts.map((host) => createConfigMenuRow(host))
  575.  
  576. configMenu = $.create('div', {
  577. id: 'iv-config-form',
  578. className: 'iv-config-form',
  579. contents: [
  580. createMenuHeader(),
  581. {
  582. tag: 'div',
  583. className: 'iv-config-form__options',
  584. contents: rows,
  585. },
  586. ],
  587. delegate: {
  588. change: {
  589. '.js-iv-config-checkbox': ({ target: { value, checked } }) =>
  590. updateHostConfig(config.storedConfig, value, checked),
  591. },
  592. },
  593. })
  594.  
  595. document.body.append(configMenu)
  596.  
  597. return configMenu
  598. }
  599.  
  600. function createConfigMenuRow(host) {
  601. return $.create('label', {
  602. className: 'iv-config-form__label',
  603. title: host.description,
  604. contents: [
  605. {
  606. tag: 'input',
  607. type: 'checkbox',
  608. className: 'iv-config-form__checkbox js-iv-config-checkbox',
  609. checked: host.isEnabled,
  610. value: host.id,
  611. },
  612. host.name,
  613. ],
  614. })
  615. }
  616.  
  617. function createMenuHeader() {
  618. const closeButton = $.create('a', {
  619. href: '#',
  620. title: 'Close',
  621. className: `iv-icon-button iv-icon-button--small iv-icon iv-icon--type-close`,
  622. events: {
  623. click: (event) => {
  624. event.preventDefault()
  625. configMenu.classList.remove(CLASSES$1.open)
  626. },
  627. },
  628. })
  629.  
  630. return {
  631. tag: 'div',
  632. className: 'iv-config-form__header',
  633. contents: [
  634. {
  635. tag: 'span',
  636. className: 'iv-config-form__header-title',
  637. contents: `Settings for ${currentHost}`,
  638. },
  639. closeButton,
  640. ],
  641. }
  642. }
  643.  
  644. function updateHostConfig(config, hostName, isEnabled) {
  645. config.hosts[hostName] = isEnabled
  646. store.setValue(currentHost, config)
  647. }
  648.  
  649. const css_248z =
  650. "@keyframes spin{0%{transform:translate(-50%,-50%) rotate(0deg)}to{transform:translate(-50%,-50%) rotate(1turn)}}.iv-icon{position:relative}.iv-icon:after,.iv-image-link img:after{background-position:50%;background-repeat:no-repeat;background-size:contain;content:\"\";height:100%;left:50%;position:absolute;top:50%;transform:translate(-50%,-50%);width:100%;z-index:2}.iv-icon--hover:after{opacity:0;transition:opacity .35s ease}.iv-icon--hover:hover:after{opacity:1}.iv-icon--size-button:after{height:50px;width:50px}.iv-icon--type-loading:after{animation:spin 1s linear infinite;background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff'%3E%3Cpath d='M12 4V2A10 10 0 0 0 2 12h2a8 8 0 0 1 8-8Z'/%3E%3C/svg%3E\")!important;opacity:1}.iv-icon--type-zoom:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24' fill='%23fff'%3E%3Cpath d='M0 0h24v24H0V0z' fill='none'/%3E%3Cpath d='M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm.5-7H9v2H7v1h2v2h1v-2h2V9h-2z'/%3E%3C/svg%3E\")}.iv-icon--type-open-in-new:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24' fill='%23fff'%3E%3Cpath d='M0 0h24v24H0z' fill='none'/%3E%3Cpath d='M19 19H5V5h7V3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z'/%3E%3C/svg%3E\");height:40px;width:40px}.iv-icon--type-next:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24' fill='%23fff'%3E%3Cpath d='M0 0h24v24H0V0z' fill='none'/%3E%3Cpath d='M10.02 6 8.61 7.41 13.19 12l-4.58 4.59L10.02 18l6-6-6-6z'/%3E%3C/svg%3E\")}.iv-icon--type-previous:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24' fill='%23fff'%3E%3Cpath d='M0 0h24v24H0V0z' fill='none'/%3E%3Cpath d='M15.61 7.41 14.2 6l-6 6 6 6 1.41-1.41L11.03 12l4.58-4.59z'/%3E%3C/svg%3E\")}.iv-icon--type-close:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24' fill='%23fff'%3E%3Cpath d='M0 0h24v24H0V0z' fill='none'/%3E%3Cpath d='M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12 19 6.41z'/%3E%3C/svg%3E\")}.iv-icon--type-expand:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24' fill='%23fff'%3E%3Cpath d='M0 0h24v24H0V0z' fill='none'/%3E%3Cpath d='M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z'/%3E%3C/svg%3E\")}.iv-icon--type-shrink:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' height='24' width='24' fill='%23fff'%3E%3Cpath d='M0 0h24v24H0V0z' fill='none'/%3E%3Cpath d='M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z'/%3E%3C/svg%3E\")}.iv-icon--type-image-broken:after,.iv-image-link img:after{background-image:url(\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff'%3E%3Cpath d='M21 5v6.59l-3-3.01-4 4.01-4-4-4 4-3-3.01V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2m-3 6.42 3 3.01V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-6.58l3 2.99 4-4 4 4'/%3E%3C/svg%3E\")}.iv-image-link{border:1px solid rgba(0,0,0,.2);box-shadow:1px 1px 3px rgba(0,0,0,.5);display:inline-flex;margin:3px;min-height:50px;min-width:50px;padding:4px;vertical-align:top}.iv-image-link img{margin:0}.iv-image-link>:not(img){align-items:center;display:flex;justify-content:center;width:100%}.iv-image-link:before{background-color:rgba(0,0,0,.5);bottom:4px;content:\"\";left:4px;opacity:0;position:absolute;right:4px;top:4px;transition:opacity .35s ease;z-index:1}.iv-image-link.iv-icon--type-loading:before,.iv-image-link:hover:before{opacity:1}.iv-image-link img:after,.iv-image-link img:before{content:\"\";position:absolute}.iv-image-link img:before{background-color:rgba(0,0,0,.2);height:100%;left:0;top:0;width:100%}.iv-image-link img:after{height:35px;width:35px;z-index:0}.iv-image-view{background-color:rgba(0,0,0,.8);color:#fff;display:none;flex-direction:column;height:0;opacity:0;transition:opacity .35s ease-out;user-select:none}.iv-image-view--open body,html.iv-image-view--open{overflow:hidden}.iv-image-view--open .iv-image-view{bottom:0;display:flex;height:auto;left:0;opacity:1;position:fixed;right:0;top:0;z-index:3}.iv-image-view--single .single-hide{visibility:hidden}.iv-image-view__footer,.iv-image-view__header{background-color:rgba(0,0,0,.8);display:flex}.iv-image-view__footer-wrapper,.iv-image-view__header-wrapper{z-index:2}.iv-image-view__header-wrapper{box-shadow:0 3px 7px rgba(0,0,0,.7)}.iv-image-view__footer-wrapper{box-shadow:0 -3px 7px rgba(0,0,0,.7)}.iv-image-view__header{justify-content:space-between}.iv-image-view__footer{justify-content:center}.iv-image-view__body{display:flex;height:100%;overflow:auto;position:relative}.iv-image-view__body::-webkit-scrollbar{width:20px}.iv-image-view__body::-webkit-scrollbar-thumb{background-color:rgba(0,0,0,.8)}.iv-image-view__body::-webkit-scrollbar-track{background-color:hsla(0,0%,100%,.8)}.iv-thumbnail-wrapper{display:flex;height:100%;left:0;position:absolute;top:0;width:100%;z-index:0}.iv-image-view__number{align-items:center;display:flex;font-size:18px;padding:0 40px}.iv-image-view__backdrop{height:100%;left:0;position:fixed;top:0;width:100%;z-index:1}.iv-image,.iv-thumbnail{margin:auto;max-height:100%;max-width:100%;object-fit:contain}.iv-image{opacity:1;transition:opacity .35s ease-out;z-index:2}.iv-thumbnail{filter:blur(5px)}.iv-icon--type-error .iv-image,.iv-image-view__image--loading .iv-image,.iv-image-view__image--thumbnail .iv-image{opacity:0}.iv-image-view__image--thumbnail .iv-thumbnail-wrapper{z-index:2}.iv-image-view--full-height .iv-image,.iv-image-view--full-height .iv-thumbnail{cursor:grab;max-height:none}.iv-image-view--full-height .iv-image--grabbing{cursor:grabbing}.iv-icon-button{height:50px;transition:all .35s ease-out;width:50px}.iv-icon-button--small{height:25px;width:25px}.iv-icon-button+.iv-icon-button{margin-left:5px}.iv-icon-button:hover{background-color:hsla(0,0%,100%,.1)}.iv-icon-button--active,.iv-icon-button:active{background-color:hsla(0,0%,100%,.2)}.iv-config-form{background-color:rgba(0,0,0,.85);color:#fff;display:none;flex-direction:column;height:50%;left:10px;max-width:500px;padding:10px;top:10px;width:50%}.iv-config-form--open{display:flex;position:fixed;z-index:3}.iv-config-form__header{align-items:center;display:flex;padding:10px}.iv-config-form__header-title{flex-grow:1}.iv-config-form__options{display:flex;flex-flow:column wrap;flex-grow:1;overflow:auto}.iv-config-form__label{align-items:center;display:flex;flex:0 0 auto;margin:0;padding:10px;transition:all .35s ease-out}.iv-config-form__label:hover{background-color:hsla(0,0%,100%,.15)}.iv-config-form__checkbox{margin:0 5px 0 0!important}"
  651.  
  652. const CLASSES = {
  653. imageLink: 'js-image-link',
  654. imageLinkOpenInNew: 'js-image-link-open-in-new',
  655. zoomIcon: 'iv-icon--type-zoom',
  656. openInNewIcon: 'iv-icon--type-open-in-new',
  657. imageLinkHover: 'iv-icon--hover',
  658. brokenImageIcon: 'iv-icon--type-image-broken',
  659. loadingIcon: 'iv-icon--type-loading',
  660. loading: 'iv-image-view__image--loading',
  661. thumbnail: 'iv-image-view__image--thumbnail',
  662. open: 'iv-image-view--open',
  663. single: 'iv-image-view--single',
  664. fullHeight: 'iv-image-view--full-height',
  665. iconExpand: 'iv-icon--type-expand',
  666. iconShrink: 'iv-icon--type-shrink',
  667. grabbing: 'iv-image--grabbing',
  668. buttonActive: 'iv-icon-button--active',
  669. }
  670.  
  671. const SELECTORS = {
  672. imageLink: `.${CLASSES.imageLink}`,
  673. imageOpenInNewLink: `.${CLASSES.imageLinkOpenInNew}`,
  674. }
  675.  
  676. const EMPTY_SRC =
  677. 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEAAAAALAAAAAABAAEAAAI='
  678.  
  679. const TRANSITION_DURATION = 350
  680.  
  681. function initViewer(enabledHosts) {
  682. addStyle(css_248z)
  683.  
  684. const container = $('body')
  685.  
  686. const linkCommonClasses = [
  687. 'iv-image-link',
  688. 'iv-icon',
  689. 'iv-icon--hover',
  690. 'iv-icon--size-button',
  691. ]
  692.  
  693. const getExtractor = urlExtractor.getHostExtractorMatcher(enabledHosts)
  694.  
  695. const imagesWithLinks = $$('a > img, a > var', container)
  696. .map((img) => ({
  697. link: img.parentElement,
  698. thumbnailUrl: img.src ?? img.title,
  699. }))
  700. .filter(({ link }) => link.href)
  701.  
  702. for (const { link, thumbnailUrl } of imagesWithLinks) {
  703. const extractor = getExtractor(link.href)
  704.  
  705. if (!extractor) {
  706. continue
  707. }
  708.  
  709. link.dataset.ivHost = extractor.id
  710. link.dataset.ivThumbnail = thumbnailUrl
  711.  
  712. let viewModeClasses
  713.  
  714. if (extractor.viewMode === 'new-tab') {
  715. viewModeClasses = [CLASSES.imageLinkOpenInNew, CLASSES.openInNewIcon]
  716. link.setAttribute('title', 'Open in new tab')
  717. } else {
  718. viewModeClasses = [CLASSES.imageLink, CLASSES.zoomIcon]
  719. link.setAttribute('title', 'Open viewer')
  720. }
  721.  
  722. link.classList.add(...linkCommonClasses, ...viewModeClasses)
  723. }
  724.  
  725. $.delegate(container, 'click', {
  726. [SELECTORS.imageLink]: events.openViewerLinkClick,
  727. [SELECTORS.imageOpenInNewLink]: events.openInTabLinkClick,
  728. })
  729. }
  730.  
  731. const elements = {
  732. container: undefined,
  733. image: undefined,
  734. imageThumbnail: undefined,
  735. imageContainer: undefined,
  736. imageNumber: undefined,
  737. imageTotal: undefined,
  738. buttons: {
  739. next: undefined,
  740. previous: undefined,
  741. close: undefined,
  742. toggleFullHeight: undefined,
  743. },
  744. }
  745.  
  746. const state = {
  747. isFirstClick: true,
  748. isOpened: false,
  749. currentLink: undefined,
  750. linksSet: [],
  751. isSingle: false,
  752. getCurrentLinkIndex() {
  753. return this.currentLink === undefined
  754. ? -1
  755. : this.linksSet.indexOf(this.currentLink)
  756. },
  757. getLastLinkIndex() {
  758. return this.linksSet.length - 1
  759. },
  760. dragPosition: 0,
  761. dragging: false,
  762. }
  763.  
  764. const image = {
  765. async getFullSizeURL(link) {
  766. let imageURL = link.dataset.ivImgUrl
  767.  
  768. if (imageURL) {
  769. return imageURL
  770. }
  771.  
  772. const thumbnailURL = link.dataset.ivThumbnail
  773. const imageHost = link.dataset.ivHost
  774.  
  775. if (!thumbnailURL || !imageHost) {
  776. throw new Error(
  777. '[image-viewer] Either thumbnail URL or host is not set'
  778. )
  779. }
  780.  
  781. imageURL = await urlExtractor.getImageURL({
  782. url: link.href,
  783. thumbnailURL,
  784. host: imageHost,
  785. })
  786.  
  787. if (!imageURL) {
  788. image.markAsBroken(link)
  789.  
  790. return
  791. }
  792.  
  793. link.dataset.ivImgUrl = imageURL
  794.  
  795. return imageURL
  796. },
  797.  
  798. async showInViewer(link) {
  799. const {
  800. container,
  801. image: img,
  802. imageThumbnail: thumbnail,
  803. imageNumber,
  804. } = elements
  805.  
  806. state.currentLink = link
  807.  
  808. if (state.isSingle) {
  809. container.classList.add(CLASSES.single)
  810. } else {
  811. container.classList.remove(CLASSES.single)
  812. imageNumber.textContent = (state.getCurrentLinkIndex() + 1).toString()
  813. }
  814.  
  815. if (!state.isOpened) {
  816. document.documentElement.classList.add(CLASSES.open)
  817. state.isOpened = true
  818. }
  819.  
  820. img.src = EMPTY_SRC
  821.  
  822. if (link.classList.contains(CLASSES.brokenImageIcon)) {
  823. container.classList.add(CLASSES.brokenImageIcon)
  824.  
  825. return
  826. }
  827.  
  828. container.classList.remove(CLASSES.brokenImageIcon)
  829.  
  830. container.classList.add(CLASSES.loading, CLASSES.loadingIcon)
  831.  
  832. const isSizeKnown = Boolean(link.dataset.ivWidth)
  833. const thumbnailURL = link.dataset.ivThumbnail
  834. const imageHost = link.dataset.ivHost
  835.  
  836. if (!thumbnailURL || !imageHost) {
  837. throw new Error(
  838. '[image-viewer] Either thumbnail URL or host is not set'
  839. )
  840. }
  841.  
  842. if (isSizeKnown) {
  843. thumbnail.width = Number(link.dataset.ivWidth)
  844. thumbnail.src = thumbnailURL
  845.  
  846. container.classList.add(CLASSES.thumbnail)
  847. }
  848.  
  849. const imageURL = await image.getFullSizeURL(link)
  850.  
  851. if (!imageURL) {
  852. return
  853. }
  854.  
  855. try {
  856. const extractor = urlExtractor.getExtractorByHost(imageHost)
  857.  
  858. if (extractor.viewMode === 'origin-download') {
  859. img.src = await image.loadAsBlob(imageURL)
  860. } else {
  861. await image.preload(
  862. imageURL,
  863. isSizeKnown ? undefined : image.setThumbnailSize
  864. )
  865.  
  866. img.src = imageURL
  867. }
  868.  
  869. container.classList.remove(
  870. CLASSES.thumbnail,
  871. CLASSES.loading,
  872. CLASSES.loadingIcon
  873. )
  874.  
  875. setTimeout(image.hideThumbnail, TRANSITION_DURATION)
  876. } catch {
  877. link.classList.remove(CLASSES.imageLink)
  878. image.markAsBroken(link)
  879.  
  880. link.setAttribute('target', '_blank')
  881. }
  882. },
  883.  
  884. preload(url, onSizeGet) {
  885. return new Promise((resolve, reject) => {
  886. const imageObject = new Image()
  887.  
  888. imageObject.addEventListener('load', () => resolve())
  889. imageObject.addEventListener('error', reject)
  890.  
  891. imageObject.src = url
  892.  
  893. if (onSizeGet) {
  894. image.getSize(imageObject).then(onSizeGet)
  895. }
  896. })
  897. },
  898.  
  899. async loadAsBlob(url) {
  900. const origin = new URL(url).origin
  901.  
  902. const response = await request({
  903. url,
  904. headers: {
  905. referer: origin,
  906. origin,
  907. },
  908. responseType: 'blob',
  909. })
  910.  
  911. return URL.createObjectURL(response.response)
  912. },
  913.  
  914. getSize(img) {
  915. return new Promise((resolve) => {
  916. const intervalId = setInterval(() => {
  917. if (img.naturalWidth) {
  918. clearInterval(intervalId)
  919. resolve({ width: img.naturalWidth, isLoaded: img.complete })
  920. }
  921. }, 10)
  922. })
  923. },
  924.  
  925. setThumbnailSize({ width, isLoaded }) {
  926. if (!state.currentLink) {
  927. throw new Error('[image-viewer] currentLink is not set')
  928. }
  929.  
  930. const thumbnailURL = state.currentLink.dataset.ivThumbnail
  931.  
  932. if (!thumbnailURL) {
  933. throw new Error('[image-viewer] Thumbnail URL is not set')
  934. }
  935.  
  936. elements.imageThumbnail.width = width
  937. elements.imageThumbnail.src = thumbnailURL
  938.  
  939. if (!isLoaded) {
  940. elements.container.classList.add(CLASSES.thumbnail)
  941. }
  942.  
  943. state.currentLink.dataset.ivWidth = width.toString()
  944. },
  945.  
  946. hideThumbnail() {
  947. elements.imageThumbnail.removeAttribute('width')
  948. elements.imageThumbnail.src = EMPTY_SRC
  949. },
  950.  
  951. hide() {
  952. document.documentElement.classList.remove(CLASSES.open)
  953. state.isOpened = false
  954. state.currentLink = undefined
  955. elements.image.src = EMPTY_SRC
  956. events.keyboard.unbind()
  957. },
  958.  
  959. next() {
  960. const currentIndex = state.getCurrentLinkIndex()
  961. const newIndex =
  962. currentIndex < state.getLastLinkIndex() ? currentIndex + 1 : 0
  963.  
  964. image.showInViewer(state.linksSet[newIndex])
  965. },
  966.  
  967. previous() {
  968. const currentIndex = state.getCurrentLinkIndex()
  969. const newIndex =
  970. currentIndex === 0 ? state.getLastLinkIndex() : currentIndex - 1
  971.  
  972. image.showInViewer(state.linksSet[newIndex])
  973. },
  974.  
  975. toggleFullHeight() {
  976. elements.container.classList.toggle(CLASSES.fullHeight)
  977. elements.buttons.toggleFullHeight.classList.toggle(CLASSES.iconExpand)
  978. elements.buttons.toggleFullHeight.classList.toggle(CLASSES.iconShrink)
  979. },
  980.  
  981. markAsBroken(link) {
  982. elements.container.classList.replace(
  983. CLASSES.loadingIcon,
  984. CLASSES.brokenImageIcon
  985. )
  986. elements.container.classList.remove(CLASSES.loading)
  987. link.classList.replace(CLASSES.zoomIcon, CLASSES.brokenImageIcon)
  988. link.setAttribute('title', '')
  989. },
  990. }
  991.  
  992. const events = {
  993. openViewerLinkClick(event) {
  994. event.preventDefault()
  995.  
  996. if (state.isFirstClick) {
  997. create.viewContainer()
  998. state.isFirstClick = false
  999. }
  1000.  
  1001. const link = event.target
  1002.  
  1003. state.linksSet = $$(SELECTORS.imageLink, link.parentElement ?? undefined)
  1004. state.isSingle = state.linksSet.length === 1
  1005.  
  1006. if (!state.isSingle) {
  1007. elements.imageTotal.textContent = state.linksSet.length.toString()
  1008. }
  1009.  
  1010. events.keyboard.bind()
  1011.  
  1012. image.showInViewer(link)
  1013. },
  1014.  
  1015. async openInTabLinkClick(event) {
  1016. event.preventDefault()
  1017.  
  1018. const link = event.target
  1019.  
  1020. link.classList.replace(CLASSES.openInNewIcon, CLASSES.loadingIcon)
  1021.  
  1022. const imageURL = await image.getFullSizeURL(event.target)
  1023.  
  1024. link.classList.replace(CLASSES.loadingIcon, CLASSES.openInNewIcon)
  1025.  
  1026. if (imageURL) {
  1027. openInTab(imageURL, false)
  1028. }
  1029. },
  1030.  
  1031. keyboard: {
  1032. bind() {
  1033. document.addEventListener('keydown', events.keyboard.handler, true)
  1034. },
  1035. unbind() {
  1036. document.removeEventListener('keydown', events.keyboard.handler, true)
  1037. },
  1038.  
  1039. handler(event) {
  1040. if (event.defaultPrevented || event.repeat) {
  1041. return
  1042. }
  1043.  
  1044. switch (event.key) {
  1045. case 'ArrowRight':
  1046. image.next()
  1047. break
  1048.  
  1049. case 'ArrowLeft':
  1050. image.previous()
  1051. break
  1052.  
  1053. case 'Escape':
  1054. image.hide()
  1055. break
  1056.  
  1057. case ' ':
  1058. image.toggleFullHeight()
  1059. break
  1060.  
  1061. default:
  1062. return
  1063. }
  1064.  
  1065. event.preventDefault()
  1066. },
  1067. },
  1068.  
  1069. mouse(event) {
  1070. switch (event.type) {
  1071. case 'mousedown':
  1072. state.dragging = true
  1073. state.dragPosition = event.clientY
  1074. elements.image.classList.add(CLASSES.grabbing)
  1075. break
  1076.  
  1077. case 'mousemove':
  1078. if (state.dragging) {
  1079. elements.imageContainer.scrollTop -=
  1080. event.clientY - state.dragPosition
  1081. state.dragPosition = event.clientY
  1082. }
  1083. break
  1084.  
  1085. case 'mouseup':
  1086.  
  1087. // fall through
  1088. case 'mouseout':
  1089. state.dragging = false
  1090. elements.image.classList.remove(CLASSES.grabbing)
  1091. break
  1092.  
  1093. case 'dblclick':
  1094. image.toggleFullHeight()
  1095. break
  1096.  
  1097. default:
  1098. return
  1099. }
  1100.  
  1101. event.preventDefault()
  1102. },
  1103. }
  1104.  
  1105. const create = {
  1106. viewContainer() {
  1107. elements.container = $.create('div', {
  1108. className: 'iv-image-view iv-icon iv-icon--size-button',
  1109. contents: [
  1110. create.viewContainerHeader(),
  1111. create.viewContainerBody(),
  1112. create.viewContainerFooter(),
  1113. ],
  1114. })
  1115.  
  1116. document.body.append(elements.container)
  1117. },
  1118.  
  1119. viewContainerBody() {
  1120. elements.image = $.create('img', {
  1121. className: 'iv-image',
  1122. events: {
  1123. 'mousedown mouseup mousemove mouseout dblclick': events.mouse,
  1124. },
  1125. })
  1126.  
  1127. elements.imageThumbnail = $.create('img', {
  1128. className: 'iv-thumbnail',
  1129. })
  1130.  
  1131. elements.imageContainer = $.create('div', {
  1132. className: 'iv-image-view__body',
  1133. contents: [
  1134. {
  1135. tag: 'div',
  1136. className: 'iv-image-view__backdrop',
  1137. events: {
  1138. click: image.hide,
  1139. },
  1140. },
  1141. {
  1142. tag: 'div',
  1143. className: 'iv-thumbnail-wrapper',
  1144. contents: elements.imageThumbnail,
  1145. },
  1146. elements.image,
  1147. ],
  1148. })
  1149.  
  1150. return elements.imageContainer
  1151. },
  1152.  
  1153. viewContainerHeader() {
  1154. elements.imageNumber = document.createElement('span')
  1155. elements.imageTotal = document.createElement('span')
  1156. const imageNumber = $.create('div', {
  1157. className: 'iv-image-view__number single-hide',
  1158. contents: [elements.imageNumber, '/', elements.imageTotal],
  1159. })
  1160.  
  1161. elements.buttons.close = create.toolbarButton(
  1162. 'Close (Esc)',
  1163. 'close',
  1164. image.hide
  1165. )
  1166.  
  1167. return {
  1168. tag: 'div',
  1169. className: 'iv-image-view__header-wrapper',
  1170. contents: {
  1171. tag: 'div',
  1172. className: 'iv-image-view__header',
  1173. contents: [imageNumber, elements.buttons.close],
  1174. },
  1175. }
  1176. },
  1177.  
  1178. viewContainerFooter() {
  1179. const buttons = elements.buttons
  1180.  
  1181. buttons.previous = create.toolbarButton(
  1182. 'Previous (←)',
  1183. 'previous',
  1184. image.previous,
  1185. 'single-hide'
  1186. )
  1187. buttons.toggleFullHeight = create.toolbarButton(
  1188. 'Toggle full height (Space)',
  1189. 'expand',
  1190. image.toggleFullHeight
  1191. )
  1192. buttons.next = create.toolbarButton(
  1193. 'Next (→)',
  1194. 'next',
  1195. image.next,
  1196. 'single-hide'
  1197. )
  1198.  
  1199. return {
  1200. tag: 'div',
  1201. className: 'iv-image-view__footer-wrapper',
  1202. contents: {
  1203. tag: 'div',
  1204. className: 'iv-image-view__footer',
  1205. contents: [buttons.previous, buttons.toggleFullHeight, buttons.next],
  1206. },
  1207. }
  1208. },
  1209.  
  1210. toolbarButton(title, icon, handler, className = '') {
  1211. return $.create('a', {
  1212. href: '#',
  1213. title,
  1214. className: `iv-icon-button iv-icon iv-icon--type-${icon} ${className}`,
  1215. events: {
  1216. click: (event) => {
  1217. event.preventDefault()
  1218. handler()
  1219. },
  1220. },
  1221. })
  1222. },
  1223. }
  1224.  
  1225. $.ready().then(async () => {
  1226. const hostConfig = await initHostConfig()
  1227.  
  1228. initViewer(hostConfig.enabledHosts)
  1229. })
  1230. })()