re621 - e621 Reimagined

Subscription manager, mass downloader, thumbnail enhancer, and more for e621

Per 15-08-2020. Zie de nieuwste versie.

// ==UserScript==
// @name            re621 - e621 Reimagined
// @namespace       re621.github.io
// @version         1.3.20
// @description     Subscription manager, mass downloader, thumbnail enhancer, and more for e621
// @author          re621 team
// @license         GPL-3.0-only
// @supportURL      https://github.com/re621/re621/issues
// @homepageURL     https://e621.net/forum_topics/25872
// @match           https://e621.net/*
// @match           https://e926.net/*
// @require         https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js
// @require         https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js
// @require         https://cdnjs.cloudflare.com/ajax/libs/jszip/3.3.0/jszip.min.js
// @require         https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js
// @require         https://cdn.jsdelivr.net/npm/jquery.hotkeys@0.1.0/jquery.hotkeys.min.js
// @require         https://cdn.jsdelivr.net/gh/re621/re621-lib@c8a82094eefeefdd4389538f87022bacdcf5c459/lazysizes/lazysizes.min.js
// @require         https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.2.0/plugins/unload/ls.unload.min.js
// @require         https://cdn.jsdelivr.net/npm/ua-parser-js@0.7.21/src/ua-parser.min.js
// @resource        re621_css https://github.com/re621/re621/releases/download/1.3.20/style.min.css
// @grant           GM.info
// @grant           GM.setValue
// @grant           GM.getValue
// @grant           GM.deleteValue
// @grant           GM.openInTab
// @grant           GM.setClipboard
// @grant           GM.getResourceUrl
// @grant           GM_getResourceURL
// @grant           GM_getResourceText
// @grant           GM.xmlHttpRequest
// @grant           GM_xmlhttpRequest
// @grant           GM_addValueChangeListener
// @grant           GM_removeValueChangeListener
// @grant           unsafeWindow
// @icon64          https://cdn.jsdelivr.net/gh/re621/re621.github.io@master/images/icons/icon64.png
// @connect         api.github.com
// @connect         static1.e621.net
// @connect         re621.bitwolfy.com
// @run-at          document-start
// ==/UserScript==


window.re621 = new function() {
    this.name = "re621";
    this.displayName = "re621 - e621 Reimagined";
    this.version = "1.3.20";
    this.build = "200815:0123";
    this.type = "script";
    this.links = {
        website: "https://e621.net/forum_topics/25872",
        repository: "https://github.com/re621/re621/",
        issues: "https://github.com/re621/re621/issues/",
        releases: "https://github.com/re621/re621/releases",
        forum: "https://e621.net/forum_topics/25872",
    };
    this.useragent = "re621:script/1.3";
    this.debug = true;
};

/* This is a minified build. To see the source, visit the project's github page. */


!function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){return o(e[i][1][r]||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({1:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ModuleController=void 0;const Debug_1=require("./utility/Debug"),ErrorHandler_1=require("./utility/ErrorHandler");class ModuleController{static async register(moduleList){Array.isArray(moduleList)||(moduleList=[moduleList]),Debug_1.Debug.perfStart("re621.total");let activeModules=0;for(const moduleClass of moduleList){Debug_1.Debug.perfStart(moduleClass.prototype.constructor.name);try{const moduleInstance=moduleClass.getInstance();this.modules.set(moduleClass.prototype.constructor.name,moduleInstance),await moduleInstance.prepare(),moduleInstance.canInitialize()&&(moduleInstance.isWaitingForDOM()?$(()=>{try{moduleInstance.create()}catch(error){ErrorHandler_1.ErrorHandler.error(moduleClass,error.stack,"init")}}):moduleInstance.create(),activeModules++)}catch(error){ErrorHandler_1.ErrorHandler.error(moduleClass,error.stack,"init")}Debug_1.Debug.perfEnd(moduleClass.prototype.constructor.name)}return Debug_1.Debug.perfEnd("re621.total"),Promise.resolve(activeModules)}static get(module){return"string"==typeof module?this.modules.get(module):this.get(module.prototype.constructor.name)}static getAll(){return this.modules}}exports.ModuleController=ModuleController,ModuleController.modules=new Map},{"./utility/Debug":28,"./utility/ErrorHandler":29}],2:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RE6Module=void 0;const XM_1=require("./api/XM"),Hotkeys_1=require("./data/Hotkeys"),Page_1=require("./data/Page");exports.RE6Module=class{constructor(constraint,waitForDOM=!1,settingsTag){this.initialized=!1,this.constraint=[],this.hotkeys=[],void 0===constraint?this.constraint=[]:constraint instanceof RegExp?this.constraint.push(constraint):this.constraint=constraint,this.waitForDOM=waitForDOM,this.settingsTag=settingsTag||this.constructor.name}async prepare(){await this.loadSettingsCache(),this.enabled=this.fetchSettings("enabled")}isInitialized(){return this.initialized}canInitialize(){return!this.initialized&&this.pageMatchesFilter()&&this.enabled}getSettingsTag(){return this.settingsTag}isWaitingForDOM(){return this.waitForDOM}pageMatchesFilter(){return 0==this.constraint.length||Page_1.Page.matches(this.constraint)}create(){this.initialized=!0}destroy(){this.initialized=!1}isEnabled(){return this.enabled}setEnabled(enabled){this.enabled=enabled}fetchSettings(property,fresh){if(fresh)return new Promise(async resolve=>{await this.loadSettingsCache(),resolve(this.fetchSettings(property))});if(Array.isArray(property)){const result={};return property.forEach(entry=>{result[entry]=this.settings[entry]}),result}return this.settings[property]}async fetchSettingsGently(property){return Promise.resolve((await this.loadSettingsValues())[property])}async pushSettings(property,value){return this.loadSettingsCache().then(()=>("string"==typeof property?this.settings[property]=value:Object.keys(property).forEach(key=>{this.settings[key]=property[key]}),this.saveSettingsCache()))}async clearSettings(){return XM_1.XM.Storage.deleteValue("re621."+this.settingsTag).then(()=>this.loadSettingsCache())}getDefaultSettings(){return{enabled:!0}}async loadSettingsCache(){return this.settings=await this.loadSettingsValues(),Promise.resolve(!0)}async loadSettingsValues(){const defaultValues=this.getDefaultSettings(),result=await XM_1.XM.Storage.getValue("re621."+this.settingsTag,defaultValues);for(const key of Object.keys(defaultValues))void 0===result[key]&&(result[key]=defaultValues[key]);return Promise.resolve(result)}async saveSettingsCache(){return XM_1.XM.Storage.setValue("re621."+this.settingsTag,this.settings)}async refreshSettings(){return this.loadSettingsCache()}async getSavedSettings(){return{name:"re621."+this.settingsTag,data:await XM_1.XM.Storage.getValue("re621."+this.settingsTag,{})}}async resetHotkeys(){await this.loadSettingsCache();const enabled=this.pageMatchesFilter();this.hotkeys.forEach(value=>{this.fetchSettings(value.keys).split("|").forEach(key=>{""!==key&&(enabled?Hotkeys_1.Hotkeys.register(key,value.fnct,value.element,value.selector):Hotkeys_1.Hotkeys.register(key,()=>{}))})})}registerHotkeys(...hotkeys){this.hotkeys.push(...hotkeys),this.resetHotkeys()}static getInstance(){return null==this.instance&&(this.instance=new this),this.instance}static on(name,callback){$(document).on("re621.module."+this.getInstance().constructor.name+"."+name,(event,data)=>{callback(event,data)})}static off(name){$(document).off("re621.module."+this.getInstance().constructor.name+"."+name)}static trigger(name,data){$(document).trigger("re621.module."+this.getInstance().constructor.name+"."+name,data)}}},{"./api/XM":7,"./data/Hotkeys":16,"./data/Page":17}],3:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Danbooru=void 0;const XM_1=require("./XM");class Danbooru{static getModules(){return XM_1.XM.Window.Danbooru}static hasModules(){return void 0!==XM_1.XM.Window.Danbooru}static notice(input,permanent){Danbooru.hasModules()?Danbooru.getModules().notice(input,permanent):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Notice","notice",[input,permanent])}static error(input){Danbooru.hasModules()?Danbooru.getModules().error(input):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Notice","error",[input])}}exports.Danbooru=Danbooru,Danbooru.Autocomplete={initialize_all(){Danbooru.hasModules()?Danbooru.getModules().Autocomplete.initialize_all():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Autocomplete","initialize_all")}},Danbooru.Blacklist={apply(){Danbooru.hasModules()?Danbooru.getModules().Blacklist.apply():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Blacklist","apply")},initialize_anonymous_blacklist(){Danbooru.hasModules()?Danbooru.getModules().Blacklist.initialize_anonymous_blacklist():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Blacklist","initialize_anonymous_blacklist")},initialize_all(){Danbooru.hasModules()?Danbooru.getModules().Blacklist.initialize_all():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Blacklist","initialize_all")},initialize_disable_all_blacklists(){Danbooru.hasModules()?Danbooru.getModules().Blacklist.initialize_disable_all_blacklists():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Blacklist","initialize_disable_all_blacklists")},stub_vanilla_functions(){Danbooru.hasModules()?(Danbooru.getModules().Blacklist.apply=()=>{},Danbooru.getModules().Blacklist.initialize_disable_all_blacklists=()=>{},Danbooru.getModules().Blacklist.initialize_all=()=>{}):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Blacklist","stub_vanilla_functions")}},Danbooru.Post={vote(postid,scoreDifference,preventUnvote){Danbooru.hasModules()?Danbooru.getModules().Post.vote(postid,scoreDifference,preventUnvote):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","vote",[postid,scoreDifference,preventUnvote])}},Danbooru.PostModeMenu={change(){Danbooru.hasModules()?Danbooru.getModules().PostModeMenu.change():XM_1.XM.Chrome.execInjectorRequest("Danbooru","PostModeMenu","change")}},Danbooru.Note={Box:{scale_all(){Danbooru.hasModules()?Danbooru.getModules().Note.Box.scale_all():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Note.Box","scale_all")}},TranslationMode:{active:state=>Danbooru.hasModules()?(void 0!==state&&(Danbooru.getModules().Note.TranslationMode.active=state),Promise.resolve(Danbooru.getModules().Note.TranslationMode.active)):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Note.TranslationMode","active",[state]),toggle(){Danbooru.hasModules()?Danbooru.getModules().Note.TranslationMode.toggle(new CustomEvent("re621.dummy-event")):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Note.TranslationMode","toggle")}}},Danbooru.Thumbnails={initialize(){Danbooru.hasModules()?Danbooru.getModules().Thumbnails.initialize():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Thumbnails","initialize")}},Danbooru.Utility={disableShortcuts:state=>Danbooru.hasModules()?(void 0!==state&&(Danbooru.getModules().Utility.disableShortcuts=state),Promise.resolve(Danbooru.getModules().Utility.disableShortcuts)):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Utility","disableShortcuts",[state])},Danbooru.E621={addDeferredPosts(posts){Danbooru.hasModules()?(XM_1.XM.Window.___deferred_posts=XM_1.XM.Window.___deferred_posts||{},XM_1.XM.Window.___deferred_posts=$.extend(XM_1.XM.Window.___deferred_posts,posts)):XM_1.XM.Chrome.execInjectorRequest("Danbooru","E621","addDeferredPosts",[posts])}}},{"./XM":7}],4:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DownloadQueue=void 0;const XM_1=require("./XM");class DownloadQueue{constructor(){this.queue=[],this.zip=new JSZip}getThreadCount(){return DownloadQueue.concurrent}getQueueLength(){return this.queue.length}add(file,listeners){file.unid=void 0===file.unid?0:file.unid,file.date=void 0===file.date?new Date:new Date(file.date),file.tags=void 0===file.tags?"":file.tags,listeners.onStart=void 0===listeners.onStart?function(){}:listeners.onStart,listeners.onFinish=void 0===listeners.onFinish?function(){}:listeners.onFinish,listeners.onLoadStart=void 0===listeners.onLoadStart?function(){}:listeners.onLoadStart,listeners.onLoadFinish=void 0===listeners.onLoadFinish?function(){}:listeners.onLoadFinish,listeners.onLoadProgress=void 0===listeners.onLoadProgress?function(){}:listeners.onLoadProgress,listeners.onError=void 0===listeners.onError?function(){}:listeners.onError,this.queue.push({file:file,listeners:listeners})}async run(onArchiveProgress){const processes=[];for(let i=0;i<DownloadQueue.concurrent;i++)processes.push(this.createNewProcess(i));return Promise.all(processes).then(()=>this.zip.generateAsync({type:"blob",compression:"STORE",comment:"Downloaded from e621 on "+(new Date).toUTCString()},onArchiveProgress))}async createNewProcess(thread){return new Promise(async resolve=>{let index,item;for(;this.queue.length>0;)index=this.queue.length,item=this.queue.pop(),item.listeners.onStart(item.file,thread,index),await this.zip.file(item.file.name,await this.getDataBlob(item,thread),{binary:!0,date:item.file.date,comment:item.file.tags}),item.listeners.onFinish(item.file,thread,index);void 0!==item&&item.listeners.onWorkerFinish(item.file,thread),resolve()})}async getDataBlob(item,thread){return new Promise((resolve,reject)=>{let timer;XM_1.XM.Connect.xmlHttpRequest({method:"GET",url:item.file.path,headers:{"User-Agent":window.re621.useragent,"X-User-Agent":window.re621.useragent},responseType:"arraybuffer",onloadstart:event=>{item.listeners.onLoadStart(item.file,thread,event)},onerror:event=>{item.listeners.onError(item.file,thread,event),reject(item.file)},ontimeout:event=>{item.listeners.onError(item.file,thread,event),reject(item.file)},onprogress:event=>{timer&&clearTimeout(timer),timer=window.setTimeout(()=>{item.listeners.onLoadProgress(item.file,thread,event)},500)},onload:event=>{item.listeners.onLoadFinish(item.file,thread,event),resolve(event.response)}})})}}exports.DownloadQueue=DownloadQueue,DownloadQueue.concurrent=4},{"./XM":7}],5:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.E621=void 0;const Debug_1=require("../utility/Debug"),Util_1=require("../utility/Util"),ENDPOINT_DEFS=[{name:"posts",path:"posts.json",node:"posts"},{name:"post",path:"posts/%ID%.json",node:"post"},{name:"post_votes",path:"posts/%ID%/votes.json"},{name:"tags",path:"tags.json"},{name:"tag",path:"tags/%ID%.json"},{name:"tag_aliases",path:"tag_aliases.json"},{name:"tag_implications",path:"tag_implications.json"},{name:"notes",path:"notes.json"},{name:"favorites",path:"favorites.json",node:"posts"},{name:"favorite",path:"favorites/%ID%.json"},{name:"pools",path:"pools.json"},{name:"pool",path:"pools/%ID%.json"},{name:"sets",path:"post_sets.json"},{name:"set",path:"post_sets/%ID%.json"},{name:"set_add_post",path:"post_sets/%ID%/add_posts.json"},{name:"set_remove_post",path:"post_sets/%ID%/remove_posts.json"},{name:"users",path:"users.json"},{name:"user",path:"users/%ID%.json"},{name:"blips",path:"blips.json"},{name:"wiki_pages",path:"wiki_pages.json"},{name:"comments",path:"comments.json"},{name:"comment",path:"comments/%ID%.json"},{name:"forum_posts",path:"forum_posts.json"},{name:"forum_post",path:"forum_posts/%ID%.json"},{name:"forum_topics",path:"forum_topics.json"},{name:"forum_topic",path:"forum_topics/%ID%.json"},{name:"dtext_preview",path:"dtext_preview"},{name:"iqdb_queries",path:"iqdb_queries.json"}];class APIEndpoint{constructor(queue,endpoint){this.queue=queue,this.path=endpoint.path,this.name=endpoint.name,this.node=endpoint.node}id(param){return this.param=param+"",this}async get(query,delay){return this.queue.createRequest(this.getParsedPath(),this.queryToString(query),"GET","",this.name,this.node,delay).then(response=>{const result=this.formatData(response[0],response[2]);return Promise.resolve(result)},response=>Promise.reject(response[0]))}async first(query,delay){return this.get(query,delay).then(response=>response.length>0?Promise.resolve(response[0]):Promise.resolve(null))}async post(data,delay){return this.queue.createRequest(this.getParsedPath(),"","POST",this.queryToString(data,!0),this.name,this.node,delay).then(data=>Promise.resolve(data),error=>Promise.reject(error))}async delete(data,delay){return this.queue.createRequest(this.getParsedPath(),"","DELETE",this.queryToString(data,!0),this.name,this.node,delay).then(data=>Promise.resolve(data),error=>Promise.reject(error))}getParsedPath(){if(this.param){const output=this.path.replace(/%ID%/g,this.param);return this.param=void 0,output}return this.path}queryToString(query,post=!1){if(void 0===query)return"";if("string"==typeof query)return query;const keys=Object.keys(query);if(0===keys.length)return"";const queryString=[];return keys.forEach(key=>{let value=query[key];Array.isArray(value)&&(value=value.join("+")),post?queryString.push(encodeURIComponent(key)+"="+encodeURIComponent(value)):queryString.push(encodeURIComponent(key)+"="+encodeURIComponent(value).replace(/%2B/g,"+"))}),queryString.join("&")}formatData(data,node){return void 0!==node&&(data=data[node]),Array.isArray(data)?data:[data]}}class E621{constructor(){this.emitter=$({}),this.processing=!1,this.requestIndex=0,this.endpoints={},this.authToken=$("head meta[name=csrf-token]").attr("content"),this.queue=[],ENDPOINT_DEFS.forEach(definition=>{this.endpoints[definition.name]=new APIEndpoint(this,definition)})}static getEndpoint(name){return void 0===this.instance&&(this.instance=new E621),this.instance.endpoints[name]}async createRequest(path,query,method,requestBody,endpoint,node,delay){void 0===delay?delay=E621.requestRateLimit:delay<500&&(delay=500);const requestInfo={credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":window.re621.useragent,"X-User-Agent":window.re621.useragent},method:method,mode:"cors"};"POST"!==method&&"DELETE"!==method||(null==this.authToken&&(Debug_1.Debug.log("authToken is undefined, regenerating"),this.authToken=$("head meta[name=csrf-token]").attr("content")),requestInfo.body=requestBody+(requestBody.length>0?"&":"")+"authenticity_token="+encodeURIComponent(this.authToken)),query=query+(query.length>0?"&":"")+"_client="+encodeURIComponent(window.re621.useragent);const entry=new Request(location.origin+"/"+path+"?"+query,requestInfo),index=this.requestIndex++,final=new Promise((resolve,reject)=>{this.emitter.one("api.re621.result-"+index,(e,data,status,endpoint,node)=>{null===data&&(data=[]),void 0===data[endpoint]||["posts","post"].includes(endpoint)||(data=[]),void 0===data.error?resolve([data,status,node]):reject([data,status,node])})});return this.add({request:entry,index:index,delay:delay,endpoint:endpoint,node:node}),final}async add(newItem){if(this.queue.push(newItem),!this.processing){for(this.processing=!0;this.queue.length>0;){const item=this.queue.shift();Debug_1.Debug.connectLog(item.request.url),await new Promise(async resolve=>{fetch(item.request).then(async response=>{if(response.ok){let responseText=await response.text();responseText||(responseText="[]"),this.emitter.trigger("api.re621.result-"+item.index,[JSON.parse(responseText),response.status,item.endpoint,item.node])}else this.emitter.trigger("api.re621.result-"+item.index,[{error:response.status+" "+response.statusText},response.status,item.endpoint,item.node]);resolve()},error=>{this.emitter.trigger("api.re621.result-"+item.index,[{error:error[1]+" "+error[0].error},error[1],item.endpoint,item.node]),resolve()})}),await Util_1.Util.sleep(item.delay)}this.processing=!1}}}exports.E621=E621,E621.requestRateLimit=1e3,E621.Posts=E621.getEndpoint("posts"),E621.Post=E621.getEndpoint("post"),E621.PostVotes=E621.getEndpoint("post_votes"),E621.Tags=E621.getEndpoint("tags"),E621.Tag=E621.getEndpoint("tag"),E621.TagAliases=E621.getEndpoint("tag_aliases"),E621.TagImplications=E621.getEndpoint("tag_implications"),E621.Notes=E621.getEndpoint("notes"),E621.Favorites=E621.getEndpoint("favorites"),E621.Favorite=E621.getEndpoint("favorite"),E621.Pools=E621.getEndpoint("pools"),E621.Pool=E621.getEndpoint("pool"),E621.Sets=E621.getEndpoint("sets"),E621.Set=E621.getEndpoint("set"),E621.SetAddPost=E621.getEndpoint("set_add_post"),E621.SetRemovePost=E621.getEndpoint("set_remove_post"),E621.Users=E621.getEndpoint("users"),E621.User=E621.getEndpoint("user"),E621.Blips=E621.getEndpoint("blips"),E621.Wiki=E621.getEndpoint("wiki_pages"),E621.Comments=E621.getEndpoint("comments"),E621.Comment=E621.getEndpoint("comment"),E621.ForumPosts=E621.getEndpoint("forum_posts"),E621.ForumPost=E621.getEndpoint("forum_post"),E621.ForumTopics=E621.getEndpoint("forum_topics"),E621.ForumTopic=E621.getEndpoint("forum_topic"),E621.DTextPreview=E621.getEndpoint("dtext_preview"),E621.IQDBQueries=E621.getEndpoint("iqdb_queries")},{"../utility/Debug":28,"../utility/Util":32}],6:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostHtml=void 0;const DomUtilities_1=require("../structure/DomUtilities"),APIPost_1=require("./responses/APIPost");exports.PostHtml=class{static create(json,lazyload=!0,loadlarge=!1){const allTags=APIPost_1.APIPost.getTagString(json),$article=$("<article>").attr({id:"post_"+json.id,"data-id":json.id,"data-flags":APIPost_1.APIPost.getFlagString(json),"data-tags":allTags,"data-rating":json.rating,"data-uploader-id":json.uploader_id,"data-file-ext":json.file.ext,"data-file-url":json.file.url,"data-large-file-url":json.sample.url,"data-preview-file-url":json.preview.url,"data-uploader":json.uploader_id}).addClass(this.getArticleClasses(json).join(" ")),$href=$("<a>").addClass("preview-box").attr("href","/posts/"+json.id).appendTo($article),$picture=$("<picture>").appendTo($href),$img=$("<img>").addClass("has-cropped-false resized").attr({title:`Rating: ${json.rating}\nID: ${json.id}\nDate: ${json.created_at}\nScore: ${json.score.total}\n\n ${allTags}`,alt:allTags,src:DomUtilities_1.DomUtilities.getPlaceholderImage()}).css("--native-ratio",json.file.height/json.file.width).appendTo($picture);"swf"===json.file.ext||$article.attr("data-flags").includes("deleted")||($img.addClass(lazyload?"lazyload":"later-lazyload"),loadlarge?$img.attr("data-src",json.sample.url):$img.attr("data-src",json.preview.url));const scoreInfo=this.getScoreInfo(json);return $("<div>").attr("class","desc").html(`\n                <div class="post-score" id="post-score-${json.id}">\n                    <span class="post-score-score ${scoreInfo.class}">${scoreInfo.modifier+json.score.total}</span>\n                    <span class="post-score-faves">♥${json.fav_count}</span>\n                    <span class="post-score-comments">C${json.comment_count}</span>\n                    <span class="post-score-rating">${json.rating.toUpperCase()}</span>\n                    <span class="post-score-extra">${this.getExtra(json)}</span>\n                </div>\n            `).appendTo($article),$article}static getScoreInfo(json){return json.score.total>0?{class:"score-positive",modifier:"↑"}:json.score.total<0?{class:"score-negative",modifier:"↓"}:{class:"score-neutral",modifier:"↕"}}static getArticleClasses(json){const result=["blacklisted","captioned","post-preview"];switch(json.rating){case"s":result.push("post-rating-safe");break;case"q":result.push("post-rating-questionable");break;case"e":result.push("post-rating-explicit")}for(const flag of APIPost_1.APIPost.getFlagSet(json))result.push("post-status-"+flag);return json.relationships.has_active_children&&result.push("post-status-has-children"),null!==json.relationships.parent_id&&result.push("post-status-has-parent"),result}static getExtra(json){let result="";return null!==json.relationships.parent_id&&(result+="P"),json.relationships.has_active_children&&(result+="C"),json.flags.pending&&(result+="U"),json.flags.flagged&&(result+="F"),result}}},{"../structure/DomUtilities":23,"./responses/APIPost":12}],7:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XM=void 0;const XMChrome_1=require("./XMChrome"),XMConnect_1=require("./XMConnect"),XMStorage_1=require("./XMStorage"),XMUtil_1=require("./XMUtil");class XM{static info(){return"undefined"==typeof GM?{script:null,scriptMetaStr:null,scriptHandler:window.re621.type,version:"1.0"}:GM.info}}exports.XM=XM,XM.Storage=XMStorage_1.XMStorage,XM.Connect=XMConnect_1.XMConnect,XM.Util=XMUtil_1.XMUtil,XM.Chrome=XMChrome_1.XMChrome,XM.Window="undefined"==typeof unsafeWindow?window:unsafeWindow},{"./XMChrome":8,"./XMConnect":9,"./XMStorage":10,"./XMUtil":11}],8:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XMChrome=void 0;const Util_1=require("../utility/Util");class XMChrome{static async execBackgroundRequest(component,module,method,args){return new Promise(resolve=>{chrome.runtime.sendMessage(XMChrome.formatRequestData(component,module,method,args),response=>{XMChrome.requests=XMChrome.requests.filter(e=>e!==response.eventID),resolve(response.data)})})}static async execBackgroundConnection(component){return Promise.resolve(chrome.runtime.connect({name:component}))}static async execInjectorRequest(component,module,method,args){return new Promise(resolve=>{const request=XMChrome.formatRequestData(component,module,method,args),callback=function(event){const response=event.detail;document.removeEventListener("re621.chrome.message.response-"+response.eventID,callback),XMChrome.requests=XMChrome.requests.filter(e=>e!==response.eventID),resolve(response.data)};document.addEventListener("re621.chrome.message.response-"+request.eventID,callback),document.dispatchEvent(new CustomEvent("re621.chrome.message",{detail:request}))})}static formatRequestData(component,module,method,args){return{component:component,module:module,method:method,eventID:function(){let id;do{id=Util_1.Util.ID.make(8,!1)}while(XMChrome.requests.includes(id));return XMChrome.requests.push(id),id}(),args:void 0===args?[]:args}}static getResourceURL(name){return chrome.extension.getURL(name)}}exports.XMChrome=XMChrome,XMChrome.requests=[]},{"../utility/Util":32}],9:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XMConnect=void 0;const Debug_1=require("../utility/Debug"),XM_1=require("./XM");class XMConnect{static xmlHttpRequest(details){Debug_1.Debug.connectLog(details.url);const validDetails=XMConnect.validateXHRDetails(details);"undefined"!=typeof GM&&"function"==typeof GM.xmlHttpRequest?GM.xmlHttpRequest(validDetails):"function"==typeof GM_xmlhttpRequest?GM_xmlhttpRequest(validDetails):XM_1.XM.Chrome.execBackgroundConnection("XHR").then(port=>{port.postMessage(validDetails),port.onMessage.addListener(async response=>{"onload"===response.event&&("blob"===details.responseType?response.response=await fetch(response.response).then(r=>r.blob()):"arraybuffer"===details.responseType&&(response.response=await fetch(response.response).then(r=>r.arrayBuffer())),URL.revokeObjectURL(response.responseURL)),details[response.event](response)})})}static xmlHttpPromise(details){const validDetails=XMConnect.validateXHRDetails(details);return new Promise((resolve,reject)=>{const callbacks={onabort:validDetails.onabort,onerror:validDetails.onerror,onload:validDetails.onload,onloadstart:validDetails.onloadstart,onprogress:validDetails.onprogress,onreadystatechange:validDetails.onreadystatechange,ontimeout:validDetails.ontimeout};details.onabort=event=>{callbacks.onabort(event),reject(event)},details.onerror=event=>{callbacks.onerror(event),reject(event)},details.onload=event=>{callbacks.onload(event),resolve(event)},details.onloadstart=event=>{callbacks.onloadstart(event)},details.onprogress=event=>{callbacks.onprogress(event)},details.onreadystatechange=event=>{callbacks.onreadystatechange(event)},details.ontimeout=event=>{callbacks.ontimeout(event),reject(event)},XMConnect.xmlHttpRequest(validDetails)})}static validateXHRDetails(details){return void 0===details.headers&&(details.headers={}),void 0===details.headers["User-Agent"]&&(details.headers["User-Agent"]=window.re621.useragent,details.headers["X-User-Agent"]=window.re621.useragent),void 0===details.onabort&&(details.onabort=()=>{}),void 0===details.onerror&&(details.onerror=()=>{}),void 0===details.onload&&(details.onload=()=>{}),void 0===details.onloadstart&&(details.onloadstart=()=>{}),void 0===details.onprogress&&(details.onprogress=()=>{}),void 0===details.onreadystatechange&&(details.onreadystatechange=()=>{}),void 0===details.ontimeout&&(details.ontimeout=()=>{}),details}static async getResourceText(name){return"function"==typeof GM_getResourceText?Promise.resolve(GM_getResourceText(name)):"undefined"!=typeof GM?XMConnect.getResourceTextGM(name):XMConnect.xmlHttpPromise({url:window.resources[name].startsWith("http")?window.resources[name]:XM_1.XM.Chrome.getResourceURL(window.resources[name]),method:"GET"}).then(data=>Promise.resolve(data.responseText),error=>Promise.reject(error.status+" "+error.statusText))}static async getResourceTextGM(name){const resource="function"==typeof GM.getResourceUrl?await GM.getResourceUrl(name):GM_getResourceURL(name);return resource.startsWith("data:")?Promise.resolve(atob(resource.replace(/^data:(.*);base64,/g,""))):resource.startsWith("blob:")?new Promise(async(resolve,reject)=>{const request=await fetch(resource,{credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded","User-Agent":window.re621.useragent,"X-User-Agent":window.re621.useragent},method:"GET",mode:"cors"});request.ok?resolve(await request.text()):reject()}):Promise.reject()}static async getResourceJSON(name){return XMConnect.getResourceText(name).then(resolved=>Promise.resolve(JSON.parse(resolved)),rejected=>Promise.reject(rejected))}static download(a,b){let timer;"string"==typeof a&&(a={url:a,name:b}),void 0===a.headers&&(a.headers={"User-Agent":window.re621.useragent,"X-User-Agent":window.re621.useragent}),void 0===a.onerror&&(a.onerror=()=>{}),void 0===a.onload&&(a.onload=()=>{}),void 0===a.onprogress&&(a.onprogress=()=>{}),void 0===a.ontimeout&&(a.ontimeout=()=>{}),XMConnect.xmlHttpRequest({url:a.url,method:"GET",headers:a.headers,responseType:"blob",onerror:event=>{a.onerror(event)},ontimeout:event=>{a.ontimeout(event)},onprogress:event=>{timer&&clearTimeout(timer),timer=window.setTimeout(()=>{a.onprogress(event)},500)},onload:event=>{a.onload(event),saveAs(event.response,a.name)}})}}exports.XMConnect=XMConnect},{"../utility/Debug":28,"./XM":7}],10:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XMStorage=void 0;exports.XMStorage=class{static async setValue(name,value){return new Promise(async resolve=>{"undefined"==typeof GM?await new Promise(resolve=>{chrome.storage.sync.set({[name]:value},()=>{resolve()})}):await GM.setValue(name,value),resolve(!0)})}static async getValue(name,defaultValue){return new Promise(async resolve=>{"undefined"==typeof GM?chrome.storage.sync.get(name,result=>{void 0===result[name]?resolve(Promise.resolve(defaultValue)):resolve(Promise.resolve(result[name]))}):resolve(GM.getValue(name,defaultValue))})}static async deleteValue(name){return new Promise(async resolve=>{"undefined"==typeof GM?await new Promise(resolve=>{chrome.storage.sync.set({name:void 0},()=>{resolve()})}):await GM.deleteValue(name),resolve()})}static addListener(name,callback){if("undefined"!=typeof GM_addValueChangeListener)return GM_addValueChangeListener(name,callback);chrome.storage.onChanged.addListener((function(changes){for(const key in changes){if(key!==name)return;callback(key,changes[key].oldValue,changes[key].newValue,!0)}}))}static removeListener(listenerId){"undefined"!=typeof GM_removeValueChangeListener&&GM_removeValueChangeListener(listenerId)}}},{}],11:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.XMUtil=void 0;const XM_1=require("./XM");exports.XMUtil=class{static openInTab(path,active=!0){"undefined"==typeof GM?XM_1.XM.Chrome.execBackgroundRequest("XM","Util","openInTab",[path,active]):GM.openInTab(path,{active:active})}static setClipboard(data,info){"undefined"==typeof GM?XM_1.XM.Chrome.execBackgroundRequest("XM","Util","setClipboard",[data]):GM.setClipboard(data,info)}}},{"./XM":7}],12:[function(require,module,exports){"use strict";var PostRating,PostRatingAliases;Object.defineProperty(exports,"__esModule",{value:!0}),exports.APIPost=exports.PostRating=void 0,function(PostRating){PostRating.Safe="s",PostRating.Questionable="q",PostRating.Explicit="e"}(PostRating=exports.PostRating||(exports.PostRating={})),function(PostRatingAliases){PostRatingAliases.s="s",PostRatingAliases.safe="s",PostRatingAliases.q="q",PostRatingAliases.questionable="q",PostRatingAliases.e="e",PostRatingAliases.explicit="e"}(PostRatingAliases||(PostRatingAliases={})),function(PostRating){PostRating.fromValue=function(value){return PostRatingAliases[value]},PostRating.toString=function(postRating){for(const key of Object.keys(PostRating))if(PostRating[key]===postRating)return key}}(PostRating=exports.PostRating||(exports.PostRating={})),function(APIPost){APIPost.getTags=function(post){return[...post.tags.artist,...post.tags.character,...post.tags.copyright,...post.tags.general,...post.tags.invalid,...post.tags.lore,...post.tags.meta,...post.tags.species]},APIPost.getTagString=function(post){return APIPost.getTags(post).join(" ")},APIPost.getFlagString=function(post){const flags=[];return post.flags.deleted&&flags.push("deleted"),post.flags.flagged&&flags.push("flagged"),post.flags.pending&&flags.push("pending"),flags.join(" ")},APIPost.getFlagSet=function(post){const flags=new Set;return post.flags.deleted&&flags.add("deleted"),post.flags.flagged&&flags.add("flagged"),post.flags.pending&&flags.add("pending"),flags},APIPost.fromDomElement=function($element){let md5;$element.attr("data-md5")?md5=$element.attr("data-md5"):$element.attr("data-file-url")&&(md5=$element.attr("data-file-url").substring(36,68));const ext=$element.attr("data-file-ext");let score;$element.attr("data-score")?score=parseInt($element.attr("data-score")):0!==$element.find(".post-score-score").length&&(score=parseInt($element.find(".post-score-score").first().html().substring(1)));const flagString=$element.attr("data-flags");return{error:"",id:parseInt($element.attr("data-id")),change_seq:-1,comment_count:-1,created_at:"",description:"",fav_count:-1,file:{ext:ext,height:-1,width:-1,md5:md5,size:-1,url:$element.attr("data-file-url")?$element.attr("data-file-url"):getFileName(md5)},flags:{deleted:flagString.includes("deleted"),flagged:flagString.includes("flagged"),note_locked:!1,pending:flagString.includes("pending"),rating_locked:!1,status_locked:!1},locked_tags:[],pools:[],preview:{height:-1,width:-1,url:$element.attr("data-preview-file-url")?$element.attr("data-preview-file-url"):getFileName(md5,"preview")},rating:PostRating.fromValue($element.attr("data-rating")),relationships:{children:[],has_active_children:!1,has_children:!1},sample:{has:!0,height:-1,width:-1,url:$element.attr("data-large-file-url")?$element.attr("data-large-file-url"):getFileName(md5,"sample")},score:{down:0,total:score,up:0},sources:[],tags:{artist:[],character:[],copyright:[],general:$element.attr("data-tags").split(" "),invalid:[],lore:[],meta:[],species:[]},updated_at:"",uploader_id:parseInt($element.attr("data-uploader-id"))};function getFileName(md5,prefix){return void 0===md5?"/images/deleted-preview.png":prefix?`https://static1.e621.net/data/${prefix}/${md5.substring(0,2)}/${md5.substring(2,4)}/${md5}.jpg`:`https://static1.e621.net/data/${md5.substring(0,2)}/${md5.substring(2,4)}/${md5}.jpg`}}}(exports.APIPost||(exports.APIPost={}))},{}],13:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.AvoidPosting=void 0;const E621_1=require("../api/E621"),Util_1=require("../utility/Util");class AvoidPosting{static getCache(){return void 0===AvoidPosting.cache&&(AvoidPosting.cache=new Set(JSON.parse(window.localStorage.getItem("re621.dnpcache.data")||"[]"))),AvoidPosting.cache}static save(){window.localStorage.setItem("re621.dnpcache.data",JSON.stringify(Array.from(AvoidPosting.getCache())))}static clear(){AvoidPosting.cache=new Set,AvoidPosting.save()}static size(){return AvoidPosting.getCache().size}static has(tag){return AvoidPosting.getCache().has(tag)}static add(tag){AvoidPosting.getCache().add(tag),AvoidPosting.save()}static async update(status){status||(status=$("<span>")),AvoidPosting.clear();let result=[],page=0;do{page++,status.html(`<i class="fas fa-circle-notch fa-spin"></i> Processing tags: batch ${page} / ?`),result=await E621_1.E621.TagImplications.get({"search[consequent_name]":"avoid_posting+conditional_dnp",page:page,limit:1e3},500);for(const entry of result)AvoidPosting.add(entry.antecedent_name)}while(320==result.length);return status.html(`<i class="far fa-check-circle"></i> Cache reloaded: ${AvoidPosting.size()} entries`),window.localStorage.setItem("re621.dnpcache.update",Util_1.Util.Time.now()+""),Promise.resolve(AvoidPosting.size())}static getUpdateTime(){return parseInt(window.localStorage.getItem("re621.dnpcache.update"))||0}static isUpdateRequired(){return AvoidPosting.getUpdateTime()+Util_1.Util.Time.DAY<Util_1.Util.Time.now()||0==AvoidPosting.size()}}exports.AvoidPosting=AvoidPosting},{"../api/E621":5,"../utility/Util":32}],14:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FavoriteCache=void 0;const E621_1=require("../api/E621"),User_1=require("../data/User"),Util_1=require("../utility/Util");class FavoriteCache{static isEnabled(){return void 0===FavoriteCache.enabled&&(FavoriteCache.enabled="false"!==window.localStorage.getItem("re621.favcache.enabled")),FavoriteCache.enabled}static setEnabled(state){FavoriteCache.enabled=state,window.localStorage.setItem("re621.favcache.enabled",state+"")}static getCache(){return void 0===FavoriteCache.cache&&(FavoriteCache.cache=FavoriteCache.isEnabled()?new Set(JSON.parse(window.localStorage.getItem("re621.favcache.data")||"[]")):new Set),FavoriteCache.cache}static save(){window.localStorage.setItem("re621.favcache.data",JSON.stringify(Array.from(FavoriteCache.getCache())))}static clear(){FavoriteCache.cache=new Set,FavoriteCache.save(),window.localStorage.removeItem("re621.favcache.update"),window.localStorage.removeItem("re621.favcache.invalid")}static size(){return FavoriteCache.getCache().size}static has(post){return FavoriteCache.getCache().has(post)}static add(post,save=!0){FavoriteCache.isEnabled()&&(FavoriteCache.getCache().add(post),save&&FavoriteCache.save())}static remove(post){return!(!FavoriteCache.isEnabled()||!FavoriteCache.has(post))&&(FavoriteCache.getCache().delete(post),FavoriteCache.save(),!0)}static async update(status){status||(status=$("<span>")),FavoriteCache.clear();let result=[],page=0;const totalPages=Math.ceil((await User_1.User.getCurrentSettings()).favorite_count/320);do{page++,status.html(`<i class="fas fa-circle-notch fa-spin"></i> Processing favorites: batch ${page} / ${totalPages}`),result=await E621_1.E621.Posts.get({tags:`fav:${User_1.User.getUsername()} status:any`,page:page,limit:320},1e3);for(const entry of result)FavoriteCache.add(entry.id,!1)}while(320==result.length);return FavoriteCache.save(),status.html(`<i class="far fa-check-circle"></i> Cache reloaded: ${FavoriteCache.size()} entries`),window.localStorage.setItem("re621.favcache.update",Util_1.Util.Time.now()+""),window.localStorage.setItem("re621.favcache.invalid","false"),Promise.resolve(FavoriteCache.size())}static async quickUpdate(status){status||(status=$("<span>")),status.html('<i class="fas fa-circle-notch fa-spin"></i> Attempting recovery . . .');for(const entry of await E621_1.E621.Favorites.get({user_id:""+User_1.User.getUserID(),limit:320},1e3))FavoriteCache.add(entry.id,!1);return FavoriteCache.save(),status.html(`<i class="far fa-check-circle"></i> Recovery complete: ${FavoriteCache.size()} entries`),await FavoriteCache.getStoredFavNumber()==FavoriteCache.size()?(window.localStorage.setItem("re621.favcache.update",Util_1.Util.Time.now()+""),window.localStorage.setItem("re621.favcache.invalid","false"),Promise.resolve(!0)):Promise.resolve(!1)}static getUpdateTime(){return parseInt(window.localStorage.getItem("re621.favcache.update"))||0}static async isUpdateRequired(){if(FavoriteCache.checkOverride||FavoriteCache.getUpdateTime()+Util_1.Util.Time.DAY<Util_1.Util.Time.now()){const updateRequired=await FavoriteCache.getStoredFavNumber()!==FavoriteCache.size();return window.localStorage.setItem("re621.favcache.update",Util_1.Util.Time.now()+""),window.localStorage.setItem("re621.favcache.invalid",updateRequired+""),Promise.resolve(updateRequired)}return Promise.resolve("true"==window.localStorage.getItem("re621.favcache.invalid"))}static async getStoredFavNumber(force=!1){return(force||null==FavoriteCache.storedFavNumber)&&(FavoriteCache.storedFavNumber=(await User_1.User.getCurrentSettings()).favorite_count),Promise.resolve(FavoriteCache.storedFavNumber)}}exports.FavoriteCache=FavoriteCache,FavoriteCache.checkOverride=!1},{"../api/E621":5,"../data/User":22,"../utility/Util":32}],15:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Blacklist=void 0;const Post_1=require("./Post"),PostFilter_1=require("./PostFilter");class Blacklist{constructor(){this.blacklist=new Map;const filters=$("head meta[name=blacklisted-tags]").attr("content"),blacklistEnabled=$("#disable-all-blacklists").is(":visible");if(void 0!==filters)for(const filter of JSON.parse(filters))this.createFilter(filter,blacklistEnabled)}static getInstance(){return null==this.instance&&(this.instance=new Blacklist),this.instance}static get(){return this.getInstance().blacklist}createFilter(filter,enabled=!0){let postFilter=this.blacklist.get(filter);void 0===postFilter&&(postFilter=new PostFilter_1.PostFilter(filter,enabled),this.blacklist.set(filter,postFilter));const posts=Post_1.Post.fetchPosts();for(const post of posts)postFilter.addPost(post,!1)}static createFilter(filter,enabled=!0){return this.getInstance().createFilter(filter,enabled)}deleteFilter(filter){this.blacklist.delete(filter)}static deleteFilter(filter){return this.getInstance().deleteFilter(filter)}}exports.Blacklist=Blacklist},{"./Post":18,"./PostFilter":20}],16:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Hotkeys=void 0;const Danbooru_1=require("../api/Danbooru"),Page_1=require("./Page"),validKeys=["1","2","3","4","5","6","7","8","9","0","-","+","=",".",",","/","*","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","escape","ctrl","alt","shift","return","up","down","left","right"];class Hotkeys{constructor(){this.listeners=[],Danbooru_1.Danbooru.Utility.disableShortcuts(!0),Page_1.Page.matches(Page_1.PageDefintion.post)&&"swf"===$("section#image-container").attr("data-file-ext")&&(Hotkeys.enabled=!1)}static getInstance(){return void 0===this.instance&&(this.instance=new Hotkeys),this.instance}static recordSingleKeypress(callback){$("body").attr("data-recording-hotkey","true");let keys=[];$(document).on("keydown.re621.record",event=>{const key=event.key.toLowerCase().replace(/enter/g,"return").replace(/control/g,"ctrl").replace(/arrow/g,"");-1!=validKeys.indexOf(key)&&keys.push(key)}),$(document).on("keyup.re621.record",()=>{if(0!==keys.length)return $(document).off(".re621.record"),callback(keys.join("+")),void $("body").attr("data-recording-hotkey","false");keys=[]})}static getListeners(){return this.getInstance().listeners}static isRegistered(key){return-1!=this.getInstance().listeners.indexOf(key)}static register(key,fn,element,selector){return void 0===element&&(element=$(document)),void 0===selector&&(selector=null),this.unregister(key,element),element.on("keydown.re621.hotkey-"+key,selector,key,(function(event){if(!Hotkeys.enabled||"true"===$("body").attr("data-recording-hotkey"))return!1;fn(event,key)})),this.getListeners().push(key),!0}static unregister(key,element=$(document)){return!!this.isRegistered(key)&&($(element).off("keydown.re621.hotkey-"+key),this.getInstance().listeners=this.getListeners().filter(e=>e!==key),!0)}}exports.Hotkeys=Hotkeys,Hotkeys.enabled=!0},{"../api/Danbooru":3,"./Page":17}],17:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PageDefintion=exports.Page=void 0;class Page{constructor(){this.url=new URL(window.location.toString())}static matches(filter){filter instanceof RegExp&&(filter=[filter]);const pathname=this.getInstance().url.pathname.replace(/[\/?]$/g,"");let result=!1;return filter.forEach((function(constraint){result=result||constraint.test(pathname)})),result}static getURL(){return this.getInstance().url}static getQueryParameter(key){return this.getInstance().url.searchParams.get(key)}static setQueryParameter(key,value){this.getInstance().url.searchParams.set(key,value),this.refreshCurrentUrl()}static removeQueryParameter(key){this.getInstance().url.searchParams.delete(key),this.refreshCurrentUrl()}static refreshCurrentUrl(){const url=this.getInstance().url,searchPrefix=0===url.searchParams.toString().length?"":"?";history.replaceState({},"",url.origin+url.pathname+searchPrefix+url.searchParams.toString())}static getSiteName(){return this.getInstance().url.hostname.replace(/\.net/g,"")}static getPageID(){return this.getInstance().url.pathname.split("/")[2]}static getInstance(){return void 0===this.instance&&(this.instance=new Page),this.instance}}exports.Page=Page,exports.PageDefintion={title:/^(\/)?$/,search:/^\/posts\/?$/,post:/^\/posts\/\d+\/?(show_seq)?$/,upload:/\/uploads\/new\/?/,forum:/^\/forum_topics\/?.*/,forumPost:/^\/forum_topics\/\d+.*/,pool:/^\/pools\/.+/,set:/^\/post_sets\/.+/,popular:/^\/explore\/posts\/popular.?/,favorites:/^\/favorites\/?.*/,wiki:/^\/wiki_pages\/[0-9]+/,wikiNA:/^\/wiki_pages\/show_or_new.*/,artist:/^\/artists\/[0-9]+/,comments:/^\/comments\??.*/g,settings:/^\/users\/\d+\/edit$/g}},{}],18:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ViewingPost=exports.Post=void 0;const PostHtml_1=require("../api/PostHtml"),APIPost_1=require("../api/responses/APIPost"),Blacklist_1=require("./Blacklist"),Page_1=require("./Page");class Post{constructor(element){element instanceof jQuery?(element=element,this.apiElement=APIPost_1.APIPost.fromDomElement(element),this.htmlElement=element,element.hasClass("blacklisted-active")&&(element.removeClass("blacklisted-active"),this.hide())):(element=element,this.apiElement=element,this.htmlElement=PostHtml_1.PostHtml.create(element));for(const filter of Blacklist_1.Blacklist.get().values())filter.addPost(this,!1);this.tags=APIPost_1.APIPost.getTags(this.apiElement)}static fetchPosts(){if(void 0===this.initalPosts){const imageContainer=$("section#image-container");if(this.initalPosts=[],0===imageContainer.length){const previews=Page_1.Page.matches(Page_1.PageDefintion.favorites)?$("#posts").children(".post-preview").get():$("#posts-container").children(".post-preview").get();for(const preview of previews)this.initalPosts.push(new Post($(preview)))}else this.initalPosts.push(new ViewingPost(imageContainer));for(const thumbnail of $(".post-thumbnail").get())this.postThumbnails.push(new Post($(thumbnail)))}return[...this.initalPosts,...this.addedPosts,...this.postThumbnails]}static appendPost(post){this.addedPosts.push(post)}static getViewingPost(){const posts=this.fetchPosts();if(posts[0]instanceof ViewingPost)return posts[0]}static createPreviewUrlFromMd5(md5){return""===md5?"https://static1.e621.net/images/download-preview.png":`https://static1.e621.net/data/preview/${md5.substring(0,2)}/${md5.substring(2,4)}/${md5}.jpg`}static createThumbnailURLFromMd5(md5){return`https://static1.e621.net/data/crop/${md5.substring(0,2)}/${md5.substring(2,4)}/${md5}.jpg`}applyBlacklist(){this.matchesBlacklist()?this.hide():this.show()}matchesBlacklist(ignoreDisabled=!1){for(const filter of Blacklist_1.Blacklist.get().values())if(filter.matchesPost(this,ignoreDisabled))return!0;return!1}hide(){this.htmlElement.addClass("filtered")}show(){this.matchesBlacklist()||this.htmlElement.removeClass("filtered")}getDomElement(){return this.htmlElement}getId(){return this.apiElement.id}getMD5(){return this.apiElement.file.md5}getRating(){return this.apiElement.rating}getFavCount(){return this.apiElement.fav_count}getScoreCount(){return this.apiElement.score.total}getAPIElement(){return this.apiElement}getTags(){return this.getTagString()}getTagString(){return APIPost_1.APIPost.getTagString(this.apiElement)}getTagArray(tagType){return void 0===tagType?this.tags:this.apiElement.tags[tagType]}hasTag(tag){const tagPieces=tag.split(":");if(1==tagPieces.length)return this.tags.includes(tag);const value=tagPieces[1];switch(tagPieces[0]){case"id":return matchRange(this.getId(),value);case"score":return matchRange(this.getScoreCount(),value);case"favcount":return matchRange(this.getFavCount(),value);case"comments":return!1;case"tagcount":return matchRange(this.getTagArray().length,value);case"gentags":return matchRange(this.getTagArray("general").length,value);case"arttags":return matchRange(this.getTagArray("artist").length,value);case"chartags":return matchRange(this.getTagArray("character").length,value);case"copytags":return matchRange(this.getTagArray("copyright").length,value);case"speciestags":return matchRange(this.getTagArray("species").length,value);case"loretags":return matchRange(this.getTagArray("lore").length,value);case"metatags":return matchRange(this.getTagArray("meta").length,value)}return!1;function matchRange(target,value){return"<"===value.substr(0,1)?"="===value.substr(1,1)?target<=parseInt(value.substr(2)):target<parseInt(value.substr(1)):">"===value.substr(0,1)?"="===value.substr(1,1)?target>=parseInt(value.substr(2)):target>parseInt(value.substr(1)):target==parseInt(value)}}getImageURL(){return this.apiElement.file.url}getSampleURL(){return this.apiElement.sample.url}getPreviewURL(){return this.apiElement.preview.url}getFileExtension(){return this.apiElement.file.ext}getUploaderID(){return this.apiElement.uploader_id}hasSound(){return-1!==this.getTags().indexOf("sound")}getFlags(){return APIPost_1.APIPost.getFlagString(this.apiElement)}getFlagsSet(){return APIPost_1.APIPost.getFlagSet(this.apiElement)}}exports.Post=Post,Post.addedPosts=[],Post.postThumbnails=[];class ViewingPost extends Post{constructor($image){super($image),this.isFaved="none"===$("#add-to-favorites").css("display"),this.isUpvoted=$(".post-vote-up-"+this.apiElement.id).first().hasClass("score-positive"),this.isDownvoted=$(".post-vote-down-"+this.apiElement.id).first().hasClass("score-negative"),this.artistTags=this.getAllFromTaggroup("artist"),this.characterTags=this.getAllFromTaggroup("character"),this.copyrightTags=this.getAllFromTaggroup("copyright"),this.speciesTags=this.getAllFromTaggroup("species"),this.generalTags=this.getAllFromTaggroup("general"),this.metaTags=this.getAllFromTaggroup("meta"),this.loreTags=this.getAllFromTaggroup("lore")}getAllFromTaggroup(taggroup){const result=[];for(const element of $(`#tag-list .${taggroup}-tag-list`).children())result.push($(element).find(".search-tag").text().replace(/ /g,"_"));return result}getIsFaved(){return this.isFaved}getIsUpvoted(){return this.isUpvoted}getIsDownvoted(){return this.isDownvoted}getTagsFromType(tagType){return this[tagType+"Tags"]}}exports.ViewingPost=ViewingPost},{"../api/PostHtml":6,"../api/responses/APIPost":12,"./Blacklist":15,"./Page":17}],19:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostActions=void 0;const E621_1=require("../api/E621");class PostActions{static async toggleSet(setID,postID){const setData=await E621_1.E621.Set.id(setID).first({},500);if(null==setData)return Danbooru.error("Error: active set moved or deleted"),Promise.resolve(!1);setData.post_ids.includes(postID)?PostActions.removeSet(setID,postID):PostActions.addSet(setID,postID)}static addSet(setID,postID){return E621_1.E621.SetAddPost.id(setID).post({"post_ids[]":[postID]},500).then(response=>201==response[1]?(Danbooru.notice(`<a href="/post_sets/${setID}">${response[0].name}</a>: post <a href="/posts/${postID}">#${postID}</a> added (${response[0].post_count} total)`),Promise.resolve(!0)):(Danbooru.error("Error occured while adding the post to set: "+response[1]),Promise.resolve(!1)),response=>(Danbooru.error("Error occured while adding the post to set: "+response[1]),Promise.resolve(!1)))}static removeSet(setID,postID){return E621_1.E621.SetRemovePost.id(setID).post({"post_ids[]":[postID]},500).then(response=>201==response[1]?(Danbooru.notice(`<a href="/post_sets/${setID}">${response[0].name}</a>: post <a href="/posts/${postID}">#${postID}</a> removed (${response[0].post_count} total)`),Promise.resolve(!0)):(Danbooru.error("Error occured while removing the post from set: "+response[1]),Promise.resolve(!1)),response=>(Danbooru.error("Error occured while removing the post from set: "+response[1]),Promise.resolve(!1)))}}exports.PostActions=PostActions},{"../api/E621":5}],20:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Comparable=exports.PostFilterType=exports.PostFilter=void 0;const APIPost_1=require("../api/responses/APIPost"),FavoriteCache_1=require("../cache/FavoriteCache"),Tag_1=require("./Tag");var PostFilterType,Comparable;exports.PostFilter=class{constructor(input,enabled=!0){this.entries=[],this.enabled=enabled,this.matchesIds=new Set;for(let filter of input.split(" ")){const inverse=filter.startsWith("-");filter=inverse?filter.substring(1):filter;let filterType=PostFilterType.getFromString(filter);void 0===filterType?filterType=PostFilterType.Tags:filter=filter.substring(filterType.length);let comparable=Comparable.getFromString(filter);void 0===comparable?comparable=Comparable.Equals:filter=filter.substring(comparable.length),this.entries.push({type:filterType,content:filter,invert:inverse,comparable:comparable})}}addPost(post,shouldDecrement){let result=!0;for(const filter of this.entries){if(!1===result)break;const content=filter.content;switch(filter.type){case PostFilterType.Flag:result=post.getFlagsSet().has(content);break;case PostFilterType.Id:result=this.compareNumbers(post.getId(),parseInt(content),filter.comparable);break;case PostFilterType.Rating:result=post.getRating()===APIPost_1.PostRating.fromValue(content);break;case PostFilterType.Score:result=this.compareNumbers(post.getScoreCount(),parseInt(content),filter.comparable);break;case PostFilterType.Tags:result=this.tagsMatchesFilter(post,content);break;case PostFilterType.Uploader:result=post.getUploaderID()===parseInt(content);break;case PostFilterType.Fav:result=FavoriteCache_1.FavoriteCache.has(post.getId())}result=result!==filter.invert}return!0===result?this.matchesIds.add(post.getId()):!1===result&&shouldDecrement&&this.matchesIds.delete(post.getId()),result}matchesPost(post,ignoreDisabled=!1){return(this.enabled||ignoreDisabled)&&this.matchesIds.has(post.getId())}compareNumbers(a,b,mode){switch(mode){case Comparable.Equals:return a===b;case Comparable.Smaller:return a<b;case Comparable.EqualsSmaller:return a<=b;case Comparable.Larger:return a>b;case Comparable.EqualsLarger:return a>=b}}tagsMatchesFilter(post,filter){if(filter.includes("*")){return Tag_1.Tag.escapeSearchToRegex(filter).test(post.getTags())}for(const tag of post.getTags().split(" "))if(tag===filter)return!0;return!1}getMatches(){return this.matchesIds.size}getMatchesIds(){return this.matchesIds}toggleEnabled(){this.enabled=!this.enabled}setEnabled(enabled){this.enabled=enabled}isEnabled(){return this.enabled}},function(PostFilterType){PostFilterType.Tags="tag:",PostFilterType.Id="id:",PostFilterType.Score="score:",PostFilterType.Rating="rating:",PostFilterType.Uploader="uplaoder:",PostFilterType.Flag="status:",PostFilterType.Fav="fav:"}(PostFilterType=exports.PostFilterType||(exports.PostFilterType={})),function(PostFilterType){PostFilterType.getFromString=function(value){for(const key of Object.keys(PostFilterType))if(value.startsWith(PostFilterType[key]))return PostFilterType[key]}}(PostFilterType=exports.PostFilterType||(exports.PostFilterType={})),function(Comparable){Comparable.EqualsSmaller="<=",Comparable.EqualsLarger=">=",Comparable.Equals="=",Comparable.Smaller="<",Comparable.Larger=">"}(Comparable=exports.Comparable||(exports.Comparable={})),function(Comparable){Comparable.getFromString=function(value){for(const key of Object.keys(Comparable))if(value.startsWith(Comparable[key]))return Comparable[key]}}(Comparable=exports.Comparable||(exports.Comparable={}))},{"../api/responses/APIPost":12,"../cache/FavoriteCache":14,"./Tag":21}],21:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Tag=exports.TagTypes=void 0,function(TagTypes){TagTypes.Artist="artist",TagTypes.Character="character",TagTypes.Copyright="copyright",TagTypes.Species="species",TagTypes.General="general",TagTypes.Meta="meta",TagTypes.Lore="lore"}(exports.TagTypes||(exports.TagTypes={}));class Tag{static isArist(tag){return-1===Tag.nonArtistTags.indexOf(tag)}static escapeSearchToRegex(string){return new RegExp(string.replace(/[-\/\\^$+?.()|[\]{}]/g,"\\$&").replace(/\*/g,"[\\S]*?"))}}exports.Tag=Tag,Tag.nonArtistTags=["unknown_artist","unknown_artist_signature","unknown_colorist","anonymous_artist","avoid_posting","conditional_dnp","sound_warning","epilepsy_warning"]},{}],22:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.User=void 0;const E621_1=require("../api/E621");exports.User=class{constructor(){const $ref=$("body");this.loggedin="false"==$ref.attr("data-user-is-anonymous"),this.username=$ref.attr("data-user-name")||"Anonymous",this.userid=parseInt($ref.attr("data-user-id"))||0,this.level=$ref.attr("data-user-level-string")||"Guest"}static isLoggedIn(){return this.getInstance().loggedin}static getUsername(){return this.getInstance().username}static getUserID(){return this.getInstance().userid}static getLevel(){return this.getInstance().level}static async getCurrentSettings(){return E621_1.E621.User.id(this.getUserID()).first().then(response=>Promise.resolve(response))}static async setSettings(data){const json={_method:"patch"};for(const key of Object.keys(data))json["user["+key+"]"]=data[key];await E621_1.E621.User.id(this.getUserID()).post(json)}static getInstance(){return null==this.instance&&(this.instance=new this),this.instance}}},{"../api/E621":5}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DomUtilities=void 0;const XM_1=require("../api/XM"),Page_1=require("../data/Page"),ErrorHandler_1=require("../utility/ErrorHandler"),Util_1=require("../utility/Util");class DomUtilities{static async createStructure(){return new Promise(async(resolve,reject)=>{try{await DomUtilities.elementReady("head",DomUtilities.addStylesheets)}catch(error){ErrorHandler_1.ErrorHandler.error("DOM",error.stack,"styles")}let stage="prepare";try{const promises=[];promises.push(DomUtilities.elementReady("head",DomUtilities.injectChromeScript)),promises.push(DomUtilities.elementReady("body",DomUtilities.createThemes)),promises.push(DomUtilities.elementReady("#page",DomUtilities.createModalContainer)),promises.push(DomUtilities.elementReady("#nav",DomUtilities.createHeader)),Promise.all(promises).then(()=>{stage="build",DomUtilities.createSearchbox(),DomUtilities.createTagList(),DomUtilities.createFormattedTextareas(),resolve()})}catch(error){return ErrorHandler_1.ErrorHandler.error("DOM",error.stack,stage),void reject()}})}static injectChromeScript(){return"undefined"!=typeof GM||$("<script>").attr("src",XM_1.XM.Chrome.getResourceURL("injector.js")).appendTo("head"),Promise.resolve()}static addStylesheets(){return XM_1.XM.Connect.getResourceText("re621_css").then(css=>{const stylesheet=DomUtilities.addStyle(css);return $(()=>{stylesheet.appendTo("head")}),Promise.resolve(stylesheet)},()=>Promise.reject())}static createThemes(){$("body").attr("data-th-main",window.localStorage.getItem("theme")),$("body").attr("data-th-extra",window.localStorage.getItem("theme-extra")),$("body").attr("data-th-nav",window.localStorage.getItem("theme-nav"))}static createModalContainer(){$("<div>").attr("id","modal-container").prependTo("div#page")}static createHeader(){const $menuContainer=$("nav#nav"),$menuMain=$("menu.main");$("#nav").find("menu").length<2&&$menuContainer.append("<menu>");const titlePageRouting=Util_1.Util.LS.getItem("re621.mainpage")||"default";$("<menu>").addClass("logo desktop-only").html(`<a href="${"default"==titlePageRouting?"/":"/"+titlePageRouting}" data-ytta-id="-">`+Page_1.Page.getSiteName()+"</a>").prependTo($menuContainer),$menuMain.find("a[href='/']").remove(),$("<menu>").addClass("extra").insertAfter($menuMain),$menuContainer.addClass("grid")}static createSearchbox(){if(Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.post,Page_1.PageDefintion.favorites])&&$("aside#sidebar").length>0){const $searchContainer=$("<div>").attr("id","re621-search").prependTo("aside#sidebar");$("aside#sidebar section#search-box").appendTo($searchContainer),$("aside#sidebar section#mode-box").appendTo($searchContainer);new IntersectionObserver(([event])=>{$(event.target).toggleClass("re621-search-sticky bg-foreground",event.intersectionRatio<1)},{threshold:[1]}).observe($searchContainer[0])}}static createTagList(){$("#tag-box > ul > li, #tag-list > ul > li").each((index,element)=>{const $container=$(element),$tagLink=$container.find("a.search-tag").first(),$tagWrap=$("<span>").addClass("tag-wrap").insertAfter($tagLink).append($tagLink),$actionsBox=$("<div>").addClass("tag-actions").attr("data-tag",$container.find("a.search-tag").text().replace(/ /g,"_")).appendTo($container);$container.find("a.wiki-link").first().insertBefore($tagWrap),$("<span>").addClass("tag-action-blacklist").appendTo($actionsBox);const $countBox=$container.find(".post-count").first();$countBox.addClass("re621-post-count").attr("data-count-short",$countBox.text()).insertAfter($tagLink),$("<span>").addClass("tag-action-subscribe").appendTo($actionsBox)})}static createFormattedTextareas(){if(Page_1.Page.matches(Page_1.PageDefintion.upload)||Page_1.Page.matches(Page_1.PageDefintion.post)){const $textarea=$("textarea#post_description");$("<div>").addClass("dtext-previewable").append($('<div class="dtext-preview">')).insertBefore($textarea).append($textarea)}}static async elementReady(element,callback){return new Promise(async(resolve,reject)=>{let timeout=0;for(;0==$(element).length&&timeout<1e4;)await new Promise(resolve=>{window.setTimeout(()=>{resolve()},250)}),timeout+=250;$(element).length>0?window.setTimeout(()=>{callback(),resolve()},250):reject()})}static addSettingsButton(config){void 0===config.name&&(config.name="T"),void 0===config.href&&(config.href=""),void 0===config.title&&(config.title=""),void 0===config.tabClass&&(config.tabClass=""),void 0===config.linkClass&&(config.linkClass=""),void 0===config.attr&&(config.attr={});const $tab=$("<li>").appendTo("menu.extra"),$link=$("<a>").html(config.name).attr({title:config.title,id:config.id}).appendTo($tab);return config.href&&$link.attr("href",config.href),config.tabClass&&$tab.addClass(config.tabClass),config.linkClass&&$link.addClass(config.linkClass),config.attr&&$link.attr(config.attr),$link}static addStyle(css){return $("<style>").attr({id:Util_1.Util.ID.make(),type:"text/css"}).html(css).appendTo("head")}static getPlaceholderImage(){return"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="}}exports.DomUtilities=DomUtilities},{"../api/XM":7,"../data/Page":17,"../utility/ErrorHandler":29,"../utility/Util":32}],24:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FormElement=exports.Form=void 0;const XM_1=require("../api/XM"),Hotkeys_1=require("../data/Hotkeys"),Util_1=require("../utility/Util");class Form{constructor(options,content,onSubmit){options.name||(options.name=Util_1.Util.ID.make()),options.columns||(options.columns=1),options.width||(options.width=options.columns),this.element=$("<form>").addClass("form-section"+(options.wrapper?" "+options.wrapper:"")).attr({id:options.name,columns:1!==options.columns?options.columns:null,formspan:1!==options.width?options.width:null}).on("submit",event=>{event.preventDefault();const values={};this.inputList.forEach((input,name)=>{"checkbox"==input.attr("type")?values[name]=input.is(":checked"):values[name]=input.val().toString()}),onSubmit(values,this)}),this.content=content,this.inputList=new Map}render(force=!1){if(this.created&&!force)return this.element;this.element[0].innerHTML="";const formID=this.element.attr("id");for(const entry of this.content)for(const childElem of entry.build(formID,force))childElem.appendTo(this.element);for(const entry of this.content)for(const input of entry.getInputs()){const name=input.attr("name");void 0!==name&&this.inputList.set(name,input)}return this.created=!0,this.element}reset(){this.inputList.forEach(input=>{const defval=input.attr("defval");void 0!==defval&&("checkbox"==input.attr("type")?input.prop("checked","true"==defval):input.val(defval))})}getInputList(...names){if(0==names.length)return this.inputList;const results=new Map;return this.inputList.forEach((input,name)=>{names.includes(name)&&results.set(name,input)}),results}static placeholder(width=1){return new Form({columns:width,width:width},[Form.spacer(width)]).render()}static section(options,content){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.columns||(options.columns=1),options.width||(options.width=options.columns),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=$("<form-section>").toggleClass(options.wrapper,options.wrapper).attr({id:options.name,labeled:void 0!==options.label?"":null,columns:1!==options.columns?options.columns:null,colspan:1!==options.width?options.width:null});return new FormElement($element,void 0,$label,content)}static accordion(options,content){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.columns||(options.columns=1),options.width||(options.width=options.columns),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=$("<form-accordion>").toggleClass(options.wrapper,options.wrapper).attr({id:options.name,labeled:void 0!==options.label?"":null,columns:1!==options.columns?options.columns:null,colspan:1!==options.width?options.width:null});return new FormElement($element,void 0,$label,content,void 0,postElement=>{postElement.accordion({active:options.active,animate:!1,collapsible:!0===options.collapsible,header:"form-header"}),postElement.find("form-section[aria-hidden=false]").css("display","")})}static accordionTab(options,content){options.name||(options.name=Util_1.Util.ID.make()),options.columns||(options.columns=1),options.width||(options.width=options.columns);const $label=$("<form-header>").attr("for",options.name).html(options.label||"TITLE_ERROR");options.subheader&&$("<span>").addClass("form-collapse-subheader").append(options.subheader).appendTo($label),options.badge&&$("<span>").addClass("form-collapse-badge").append(options.badge).appendTo($label);const $element=$("<form-section>").addClass("collapse-content").attr({id:options.name,labeled:void 0!==options.label?"":null,columns:1!==options.columns?options.columns:null,colspan:1!==options.width?options.width:null});return new FormElement($element,void 0,$label,content)}static collapse(options,content){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.columns||(options.columns=1),options.width||(options.width=options.columns),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=$("<form-collapse>").attr({id:options.name,colspan:options.width||1}),header=$("<h3>").addClass("collapse-header").html(options.title||"Details").appendTo($element);options.badge&&$("<span>").addClass("form-collapse-badge").append(options.badge).appendTo(header);const container=$("<form-section>").addClass("collapse-content").attr({labeled:void 0!==options.label?"":null,columns:1!==options.columns?options.columns:null,colspan:1!==options.width?options.width:null}).appendTo($element);return $element.accordion({active:!options.collapsed,animate:!1,collapsible:!0,header:"h3"}),new FormElement($element,void 0,$label,content,container)}static input(options,changed){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width),$input=$("<input>").attr({type:"text",id:options.name,name:options.name}).addClass("bg-section color-text").prop("disabled",1==options.disabled).appendTo($element);if(void 0!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":$input.val(options.value.text());break;case"boolean":options.value=options.value+"";default:$input.val(options.value).attr("defval",options.value)}if(options.pattern&&$input.attr("pattern",options.pattern),options.required&&$input.attr("required",""),void 0!==changed){let timer;$input.on("input",()=>{timer&&clearTimeout(timer),timer=window.setTimeout(()=>{changed($input.val().toString(),$input)},Form.inputTimeout)})}return new FormElement($element,$input,$label)}static copy(options){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width).addClass("copybox"),$input=$("<input>").attr({type:"text",id:options.name,readonly:""}).addClass("bg-section color-text").appendTo($element);if(void 0!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":$input.val(options.value.text());break;case"boolean":options.value=options.value+"";default:$input.val(options.value).attr("defval",options.value)}const $copybutton=$("<button>").attr({type:"button",id:options.name+"-copy"}).addClass("button btn-neutral border-highlight border-left").html('<i class="far fa-copy"></i>').appendTo($element);let copyTimer;return $($copybutton).click((function(){XM_1.XM.Util.setClipboard($input.val()),window.clearTimeout(copyTimer),$input.addClass("highlight"),copyTimer=window.setTimeout(()=>$input.removeClass("highlight"),250)})),new FormElement($element,$input,$label)}static key(options,changed){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width).addClass("keyinput"),$input=$("<input>").attr({type:"text",id:options.name,readonly:""}).addClass("bg-section color-text").appendTo($element);if(void 0!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":$input.val(options.value.text());break;case"boolean":options.value=options.value+"";default:$input.val(options.value).attr("defval",options.value)}const $recordbutton=$("<button>").attr({type:"button",id:options.name+"-key"}).addClass("button btn-neutral border-highlight border-left").html('<i class="far fa-keyboard"></i>').appendTo($element);let occupied=!1;return $($recordbutton).click((function(){if(occupied)return;occupied=!0;const $oldKey=$input.val();$input.addClass("input-info").val("Recording"),Hotkeys_1.Hotkeys.recordSingleKeypress((function(key){key.includes("escape")?($input.removeClass("input-info").val(""),void 0!==changed&&changed(["",$oldKey],$input),occupied=!1):Hotkeys_1.Hotkeys.isRegistered(key)?($input.val("Already Taken"),setTimeout(()=>{$input.removeClass("input-info").val($oldKey),occupied=!1},1e3)):($input.removeClass("input-info").val(key),void 0!==changed&&changed([key,$oldKey],$input),occupied=!1)}))})),new FormElement($element,$input,$label)}static file(options,changed){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width).addClass("fileinput"),$input=$("<input>").attr({type:"file",accept:options.accept,id:options.name}).addClass("bg-section color-text").prop("disabled",1==options.disabled).appendTo($element);return void 0!==changed&&$input.on("change",()=>{changed($input.prop("files"),$input)}),new FormElement($element,$input,$label)}static icon(options,content,changed){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width),$input=$("<input>").attr({type:"text",id:options.name,name:options.name}).css("display","none").appendTo($element);if(void 0!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":$input.val(options.value.text());break;case"boolean":options.value=options.value+"";default:$input.val(options.value).attr("defval",options.value)}const $selectContainer=$("<div>").addClass("icon-picker").appendTo($element);for(const key in content)$("<a>").attr("href","#").attr("data-value",key).html(content[key]).appendTo($selectContainer);return $selectContainer.find("a").click(event=>{event.preventDefault(),$selectContainer.find("a").removeClass("active");const $target=$(event.target);$input.val($target.attr("data-value")),$target.addClass("active"),changed&&changed($input.val().toString(),$input)}),options.value?$selectContainer.find("a[data-value='"+options.value+"']").first().click():$selectContainer.find("a").first().click(),$input.on("re621:form:update",()=>{""==$input.val()?$selectContainer.find("a").first().click():$selectContainer.find("a[data-value='"+$input.val()+"']").first().click()}),new FormElement($element,$input,$label)}static button(options,changed){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width),$input=$("<button>").attr({id:options.name,type:options.type?options.type:"button"}).addClass("button btn-neutral").prop("disabled",1==options.disabled).appendTo($element);if(void 0!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":$input.append(options.value);break;case"number":case"boolean":options.value=options.value+"";default:$input.html(options.value).attr("defval",options.value)}return void 0!==changed&&$input.on("click",event=>{event.preventDefault(),changed(!0,$input)}),new FormElement($element,$input,$label)}static checkbox(options,changed){options.name||(options.name=Util_1.Util.ID.make());const $element=FormUtils.makeInputWrapper(void 0,options.wrapper,options.width).addClass("checkbox-switch"),$input=$("<input>").attr({id:options.name,name:options.name,type:"checkbox"}).addClass("switch").prop("disabled",1==options.disabled).appendTo($element);if(void 0!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":break;default:$input.prop("checked",options.value).attr("defval",options.value+"")}return $("<label>").attr("for",options.name).addClass("switch").appendTo($element),options.label&&$("<label>").attr("for",options.name).html(options.label).appendTo($element),void 0!==changed&&$input.on("change",()=>{changed($input.is(":checked"),$input)}),new FormElement($element,$input)}static select(options,content,changed){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width),$input=$("<select>").attr({id:options.name,name:options.name}).addClass("button btn-neutral").prop("disabled",1==options.disabled).appendTo($element);if(void 0!==content){"function"==typeof content&&(content=content());for(const key in content)$("<option>").val(key).text(content[key]).appendTo($input)}if(void 0!==options.value)switch(typeof options.value){case"function":options.value($input);break;case"object":$input.val(options.value.text());break;case"boolean":options.value=options.value+"";default:$input.val(options.value).attr("defval",options.value)}return void 0!==changed&&$input.on("change",()=>{changed($input.val().toString(),$input)}),new FormElement($element,$input,$label)}static header(text,width){const $element=FormUtils.makeInputWrapper(void 0,void 0,width);return $("<h3>").attr("id",Util_1.Util.ID.make()).addClass("color-text").html(text).appendTo($element),new FormElement($element)}static div(options){let $label;options.name||(options.name=Util_1.Util.ID.make()),options.label&&($label=FormUtils.makeLabel(options.name,options.label));const $element=FormUtils.makeInputWrapper(options.label,options.wrapper,options.width).addClass("text-div").attr("id",options.name);if(void 0!==options.value)switch(typeof options.value){case"function":options.value($element);break;case"object":$element.append(options.value);break;case"number":case"boolean":options.value=options.value+"";default:$element.html(options.value).attr("defval",options.value)}return new FormElement($element,void 0,$label)}static text(text,width=1,wrapper){return Form.div({value:text,width:width,wrapper:wrapper})}static subheader(header,subheader,width=1,name,wrapper){return Form.div({value:`<b>${header}</b><br />${subheader}`,width:width,wrapper:"subheader"+(wrapper?" "+wrapper:""),name:name})}static hr(width){const $element=FormUtils.makeInputWrapper(void 0,void 0,width);return $("<hr>").attr("id",Util_1.Util.ID.make()).addClass("color-text-muted").appendTo($element),new FormElement($element)}static spacer(width,unmargin=!1){const $element=FormUtils.makeInputWrapper(void 0,void 0,width);return $("<spacer>").attr("id",Util_1.Util.ID.make()).toggleClass("unmargin",unmargin).appendTo($element),new FormElement($element)}}exports.Form=Form,Form.inputTimeout=500;class FormUtils{static makeLabel(name,text){return $("<label>").attr("for",name).html(text)}static makeInputWrapper(label,wrapper,width=1){return $("<form-input>").addClass(wrapper?" "+wrapper:"").attr({labeled:void 0!==label?"":null,colspan:1!==width?width:null})}}class FormElement{constructor(wrapper,input,label,content,container,postProcessing){this.wrapper=wrapper,this.input=input,this.label=label,this.content=content||[],this.container=container||wrapper,this.postProcessing=postProcessing||(()=>{})}getInput(){return this.input}getInputs(){const result=[];this.input&&result.push(this.input);for(const entry of this.content)result.push(...entry.getInputs());return result}build(parentID,force=!1){if(force||!this.created){for(const entry of this.content)for(const childElem of entry.build(parentID+"-"+this.wrapper.attr("id"),force))childElem.appendTo(this.container);switch(void 0!==this.label&&this.label.attr("for",parentID+"-"+this.label.attr("for")),void 0!==this.input&&this.input.attr("id",parentID+"-"+this.input.attr("id")),this.wrapper.prop("tagName")){case"FORM-INPUT":this.wrapper.attr("id")&&this.wrapper.attr("id",parentID+"-"+this.wrapper.attr("id"));for(const label of this.wrapper.find("> label")){const $subLabel=$(label);$subLabel.attr("for",parentID+"-"+$subLabel.attr("for"))}break;case"FORM-SECTION":case"FORM-ACCORDION":this.wrapper.attr("id",parentID+"-"+this.wrapper.attr("id"))}this.postProcessing(this.wrapper),this.created=!0}return this.label?[this.label,this.wrapper]:[this.wrapper]}}exports.FormElement=FormElement},{"../api/XM":7,"../data/Hotkeys":16,"../utility/Util":32}],25:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Modal=void 0;const Util_1=require("../utility/Util");exports.Modal=class{constructor(config){if(this.triggers=[],this.id=Util_1.Util.ID.make(),this.config=this.validateConfig(config),this.$modal=$("<div>").addClass(config.wrapperClass).attr("title",config.title).append(this.config.content).appendTo("div#modal-container").dialog({autoOpen:!1,appendTo:"#modal-container",closeOnEscape:config.escapable,draggable:config.draggable,resizable:config.resizable,width:"auto",minWidth:config.minWidth,minHeight:config.minHeight,position:{my:config.position.my,at:config.position.at,of:$("#modal-container"),within:$("#modal-container"),collision:"none"},classes:{"ui-dialog":"bg-foreground border-section color-text","ui-dialog-titlebar":"color-text","ui-dialog-titlebar-close":"border-foreground"}}),this.$modal.dialog("widget").addClass("re621-ui-dialog").removeClass("ui-dialog ui-widget ui-widget-content").toggleClass("modal-reserve-height",config.reserveHeight).draggable({disabled:!config.draggable,containment:"parent"}).resizable({disabled:!config.resizable,containment:"parent"}),config.structure){let modalOpened=!1;this.$modal.on("dialogopen",()=>{modalOpened||(modalOpened=!0,this.$modal.html(""),this.$modal.append(config.structure.render()))})}if(config.fixed){const widget=this.$modal.dialog("widget");widget.addClass("modal-fixed"),this.$modal.dialog("option","position",{my:config.position.my,at:config.position.at,of:window,within:"div#modal-container",collision:"none"}),widget.draggable("option","containment","window"),widget.resizable("option","containment","window");let timer=0,left=widget.css("left"),top=widget.css("top");const style=$("<style>").attr({id:"style-"+this.id,type:"text/css"}).html(`\n                    .modal-fixed-${this.id} {\n                        left: ${left} !important;\n                        top: ${top} !important;\n                    }\n                `).appendTo("head");$(window).scroll(()=>{timer?clearTimeout(timer):(left=widget.css("left"),top=widget.css("top"),style.html(`\n                        .modal-fixed-${this.id} {\n                            left: ${left} !important;\n                            top: ${top} !important;\n                        }\n                    `),widget.addClass("modal-fixed-"+this.id)),timer=window.setTimeout(()=>{timer=0,widget.removeClass("modal-fixed-"+this.id),widget.css("left",left),widget.css("top",top)},500)})}for(const trigger of config.triggers)this.registerTrigger(trigger)}validateConfig(config){return void 0===config.title&&(config.title="Dialog"),void 0===config.content&&(config.content=$("")),void 0===config.triggers&&(config.triggers=[]),void 0===config.triggerMulti&&(config.triggerMulti=!1),void 0===config.escapable&&(config.escapable=!0),void 0===config.draggable&&(config.draggable=!0),void 0===config.resizable&&(config.resizable=!1),void 0===config.minWidth&&(config.minWidth=150),void 0===config.minHeight&&(config.minHeight=150),void 0===config.fixed&&(config.fixed=!1),void 0===config.reserveHeight&&(config.reserveHeight=!1),void 0===config.wrapperClass&&(config.wrapperClass=""),void 0===config.disabled&&(config.disabled=!1),void 0===config.position&&(config.position={my:"center",at:"center"}),config}addContent($content){this.$modal.append($content)}setContent($content){this.$modal.html(""),this.$modal.append($content)}registerTrigger(trigger){void 0===trigger.event&&(trigger.event="click"),0==this.triggers.length&&(this.$activeTrigger=trigger.element),this.triggers.push(trigger),trigger.element.on(trigger.event,event=>{if(this.isDisabled())return;const $target=$(event.currentTarget);return this.config.triggerMulti&&!this.$activeTrigger.is($target)&&this.isOpen()&&this.toggle(),this.$activeTrigger=$target,event.preventDefault(),this.toggle(),!1})}getElement(){return this.$modal}toggle(){this.isOpen()?this.close():this.open()}isOpen(){return this.$modal.dialog("isOpen")}open(){return this.$modal.dialog("open")}close(){return this.$modal.dialog("close")}isDisabled(){return this.config.disabled}enable(){this.config.disabled=!1}disable(){this.config.disabled=!0}destroy(){this.$modal.dialog("destroy"),this.$modal.remove()}getActiveTrigger(){return this.$activeTrigger}}},{"../utility/Util":32}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Prompt=void 0;const Modal_1=require("./Modal");class Prompt extends Modal_1.Modal{constructor(title="Prompt"){super({title:title,fixed:!0,minHeight:50}),this.createForm(),this.addContent(this.$form),this.open(),this.$input.focus(),this.promise=new Promise((resolve,reject)=>{this.$form.submit(event=>{event.preventDefault(),this.destroy(),resolve(this.$input.val()),reject()})})}createForm(){this.$form=$("<form>").addClass("prompt-input"),this.$input=$("<input>").attr("id","text").appendTo(this.$form),$("<button>").attr("type","submit").html("Submit").appendTo(this.$form)}getPromise(){return this.promise}}exports.Prompt=Prompt},{"./Modal":25}],27:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Tabbed=void 0;const Util_1=require("../utility/Util");exports.Tabbed=class{constructor(config){this.id=Util_1.Util.ID.make(),this.config=config}render(clearCache=!1){if(void 0!==this.$container&&!clearCache)return this.$container;this.$container=$("<div>");const $tabList=$("<ul>").appendTo(this.$container);return this.config.content.forEach((entry,index)=>{let $tab;$tab="string"==typeof entry.name?$("<a>").html(entry.name):entry.name,$tab.attr("href","#"+this.id+"-fragment-"+index),$("<li>").appendTo($tabList).append($tab);const elem=$("<div>").attr("id",this.id+"-fragment-"+index).appendTo(this.$container);entry.content&&elem.append(entry.content),entry.structure&&elem.append(entry.structure.render())}),this.$container.tabs({classes:{"ui-tabs":"color-text","ui-tabs-tab":"color-text"}}),this.$container.tabs("widget").find(".ui-tabs-nav li").off("keydown"),this.$container}replace(index,$element){this.$container.find("#"+this.id+"-fragment-"+index).children().replaceWith($element)}}},{"../utility/Util":32}],28:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Debug=void 0;const XM_1=require("../api/XM");class Debug{static async init(){return Debug.enabled=await XM_1.XM.Storage.getValue("re621.debug.enabled",!1),Debug.connect=await XM_1.XM.Storage.getValue("re621.debug.connect",!1),Debug.perform=await XM_1.XM.Storage.getValue("re621.debug.perform",!1),Promise.resolve(!0)}static getState(type){return Debug[type]}static setState(type,enabled){Debug[type]=enabled,enabled?XM_1.XM.Storage.setValue("re621.debug."+type,enabled):XM_1.XM.Storage.deleteValue("re621.debug."+type)}static log(...data){Debug.enabled&&console.log(...data)}static connectLog(...data){Debug.connect&&console.log("CONNECT",...data)}static perfStart(input){Debug.perform&&console.time(input)}static perfEnd(input){Debug.perform&&console.timeEnd(input)}}exports.Debug=Debug},{"../api/XM":7}],29:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ErrorHandler=void 0;const XM_1=require("../api/XM"),Modal_1=require("../structure/Modal"),Patcher_1=require("./Patcher");class ErrorHandler{constructor(){const $contentWrapper=$("<div>").html(`\n                <p>RE621 has encountered an error during script execution.</p>\n                <p>Please, report this message, including the error log below, through the <a href="${window.re621.links.issues}">issue tracker</a>, or in the <a href="${window.re621.links.forum}">forum thread</a>.</p>\n            `);this.feedback=$("<textarea>").addClass("error-feedback bg-section color-text").val(`${window.re621.name} v.${window.re621.version}-${window.re621.build}-${Patcher_1.Patcher.version} for ${XM_1.XM.info().scriptHandler} v.${XM_1.XM.info().version}\n`+window.navigator.userAgent+"\n").prop("readonly",!0).appendTo($contentWrapper),this.trigger=$("<a>"),this.modal=new Modal_1.Modal({title:"An error has occurred",content:$contentWrapper,triggers:[{element:this.trigger}],fixed:!0}),this.modal.getElement().dialog("open")}static getInstance(){return void 0===this.instance&&(this.instance=new ErrorHandler),this.instance}static log(module,message,context){const instance=this.getInstance();"string"!=typeof module&&(module=module.prototype.constructor.name),void 0!==context&&(module+="/"+context),instance.feedback.val((index,value)=>{const entry=""===value?module+"\n"+message+"\n":value+"\n"+module+"\n"+message+"\n";return console.log(entry),entry})}static error(module,message,context){const instance=this.getInstance();instance.modal.isOpen()||instance.trigger.get(0).click(),this.log(module,message,context)}}exports.ErrorHandler=ErrorHandler},{"../api/XM":7,"../structure/Modal":25,"./Patcher":30}],30:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Patcher=void 0;const XM_1=require("../api/XM"),Debug_1=require("./Debug");class Patcher{static async run(){let counter=0;switch(Patcher.version=await XM_1.XM.Storage.getValue("re621.patchVersion",0),Patcher.version){case 0:for(const type of["Comment","Forum","Pool","Tag"]){const entry=await XM_1.XM.Storage.getValue("re621."+type+"Subscriptions",void 0);void 0!==entry&&(void 0!==entry.cache&&(await XM_1.XM.Storage.setValue("re621."+type+"Tracker.cache",entry.cache),delete entry.cache,counter++),await XM_1.XM.Storage.setValue("re621."+type+"Tracker",entry),await XM_1.XM.Storage.deleteValue("re621."+type+"Subscriptions"),counter++)}Patcher.version=1;case 1:{const miscSettings=await XM_1.XM.Storage.getValue("re621.Miscellaneous",{}),searchUtilities=await XM_1.XM.Storage.getValue("re621.SearchUtilities",{});for(const property of["improveTagCount","shortenTagNames","collapseCategories","hotkeyFocusSearch","hotkeyRandomPost"])miscSettings.hasOwnProperty(property)&&(searchUtilities[property]=miscSettings[property],delete miscSettings[property],counter++);for(const property of["removeSearchQueryString","categoryData"])miscSettings.hasOwnProperty(property)&&(delete miscSettings[property],counter++);await XM_1.XM.Storage.setValue("re621.Miscellaneous",miscSettings),await XM_1.XM.Storage.setValue("re621.SearchUtilities",searchUtilities),Patcher.version=2}case 2:void 0!==await XM_1.XM.Storage.getValue("re621.report",void 0)&&(await XM_1.XM.Storage.deleteValue("re621.report"),counter++),Patcher.version=3;case 3:window.localStorage.removeItem("re621.favorites"),window.localStorage.removeItem("re621.dnp.cache"),counter+=2,Patcher.version=4;case 4:{const taConf=await XM_1.XM.Storage.getValue("re621.TinyAlias",void 0);if(void 0!==taConf&&void 0!==taConf.data){let output="";for(const[key,value]of Object.entries(taConf.data))output+=`${key} -> ${value}\n`,counter++;const saConf=await XM_1.XM.Storage.getValue("re621.SmartAlias",{data:""});saConf.data=saConf.data+(""==saConf.data?"":"\n\n")+"# Imported from TinyAlias\n"+output,await XM_1.XM.Storage.setValue("re621.SmartAlias",saConf),await XM_1.XM.Storage.deleteValue("re621.TinyAlias")}Patcher.version=5}}Debug_1.Debug.log(`Patcher: ${counter} records changed`),await XM_1.XM.Storage.setValue("re621.patchVersion",Patcher.version)}}exports.Patcher=Patcher},{"../api/XM":7,"./Debug":28}],31:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Sync=void 0;const CommentTracker_1=require("../../modules/subscriptions/CommentTracker"),ForumTracker_1=require("../../modules/subscriptions/ForumTracker"),PoolTracker_1=require("../../modules/subscriptions/PoolTracker"),TagTracker_1=require("../../modules/subscriptions/TagTracker"),XM_1=require("../api/XM"),ModuleController_1=require("../ModuleController"),Debug_1=require("./Debug"),Util_1=require("./Util");class Sync{static async init(){const settings=await XM_1.XM.Storage.getValue("re621.sync",{});return Sync.enabled=void 0!==settings.enabled&&settings.enabled,Sync.userID=void 0===settings.userID?"-1":settings.userID,Sync.version=void 0===settings.version?"0.0.1":settings.version,Sync.timestamp=void 0===settings.timestamp?0:settings.timestamp,Sync.infoUpdate=void 0===settings.infoUpdate?0:settings.infoUpdate,"-1"===Sync.userID&&await XM_1.XM.Connect.xmlHttpPromise({method:"POST",url:"https://re621.bitwolfy.com/sync/login",headers:{"User-Agent":window.re621.useragent},onload:async data=>{Debug_1.Debug.log(data.responseText);const response=JSON.parse(data.responseText);void 0===response.error&&(Sync.userID=response.userID)}}),!1!==Sync.version&&0!==Util_1.Util.versionCompare(Sync.version,window.re621.version)&&(Sync.infoUpdate=0,await XM_1.XM.Connect.xmlHttpPromise({method:"POST",url:"https://re621.bitwolfy.com/sync/report",headers:{"User-Agent":window.re621.useragent},data:JSON.stringify(Sync.getEnvData()),onload:data=>{Debug_1.Debug.log(data.responseText),Sync.version=window.re621.version}})),Sync.saveSettings()}static async saveSettings(){return XM_1.XM.Storage.setValue("re621.sync",{enabled:Sync.enabled,userID:Sync.userID,version:Sync.version,timestamp:Sync.timestamp,infoUpdate:Sync.infoUpdate})}static getEnvData(){const userAgent=UAParser(navigator.userAgent);return{userID:Sync.userID,browserName:userAgent.browser.name,browserVersion:userAgent.browser.major,osName:userAgent.os.name,osVersion:userAgent.os.version,handlerName:XM_1.XM.info().scriptHandler,handlerVersion:XM_1.XM.info().version,scriptVersion:window.re621.version}}static async download(){return new Promise(resolve=>{XM_1.XM.Connect.xmlHttpPromise({method:"POST",url:"https://re621.bitwolfy.com/sync/data/download",headers:{"User-Agent":window.re621.useragent},data:JSON.stringify({userID:Sync.userID}),onload:data=>{resolve(JSON.parse(data.responseText).data)}})})}static async upload(){return new Promise(resolve=>{XM_1.XM.Connect.xmlHttpPromise({method:"POST",url:"https://re621.bitwolfy.com/sync/data/upload",headers:{"User-Agent":window.re621.useragent},data:JSON.stringify({userID:Sync.userID,timestamp:Util_1.Util.Time.now(),data:{CommentTracker:ModuleController_1.ModuleController.get(CommentTracker_1.CommentTracker).fetchSettings("data"),ForumTracker:ModuleController_1.ModuleController.get(ForumTracker_1.ForumTracker).fetchSettings("data"),PoolTracker:ModuleController_1.ModuleController.get(PoolTracker_1.PoolTracker).fetchSettings("data"),TagTracker:ModuleController_1.ModuleController.get(TagTracker_1.TagTracker).fetchSettings("data")}}),onload:async data=>{const response=JSON.parse(data.responseText);response.timestamp&&(Sync.timestamp=new Date(response.timestamp+"Z").getTime(),await Sync.saveSettings()),resolve(response)}})})}}exports.Sync=Sync},{"../../modules/subscriptions/CommentTracker":59,"../../modules/subscriptions/ForumTracker":60,"../../modules/subscriptions/PoolTracker":61,"../../modules/subscriptions/TagTracker":64,"../ModuleController":1,"../api/XM":7,"./Debug":28,"./Util":32}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Util=void 0;const UtilID_1=require("./UtilID"),UtilTime_1=require("./UtilTime");class Util{static downloadAsJSON(data,file){$("<a>").attr({download:file+".json",href:"data:application/json,"+encodeURIComponent(JSON.stringify(data,null,4))}).appendTo("body").click((function(){$(this).remove()}))[0].click()}static async sleep(time){return new Promise(resolve=>{setTimeout(()=>{resolve()},time)})}static chunkArray(input,size,altMode=!1){Array.isArray(input)||(input=Array.from(input));const result=[];if(altMode)result[0]=input.slice(0,size),result[1]=input.slice(size);else for(let i=0;i<input.length;i+=size)result.push(input.slice(i,i+size));return result}static getArrayIndexes(input,value){const indexes=[];let i=0;for(;i<input.length;i++)input[i]===value&&indexes.push(i);return indexes}static quickParseMarkdown(input){return void 0===input?"":input.replace(/\*\*(.*?)\*\*/gm,"<strong>$1</strong>").replace(/^[-]+(.*)?/gim,"<ul><li>$1</li></ul>").replace(/\<\/ul\>\r\n\<ul\>/gm,"").replace(/\n(?!<)/gm,"<br />")}static parseDText(input,removeSections=!0){return removeSections&&(input=input.replace(/\[quote\][\s\S]*\[\/quote\]/g,"").replace(/\[code\][\s\S]*\[\/code\]/g,"").replace(/\\[section[\s\S]*\[\/section\]/g,"")),input=input.replace(/\[b\]([\s\S]*)\[\/b\]/g,"<b>$1</b>").replace(/\[i\]([\s\S]*)\[\/i\]/g,"<i>$1</i>").replace(/\[u\]([\s\S]*)\[\/u\]/g,"<u>$1</u>").replace(/\[o\]([\s\S]*)\[\/o\]/g,"<o>$1</o>").replace(/\[s\]([\s\S]*)\[\/s\]/g,"<s>$1</s>").replace(/\[sup\]([\s\S]*)\[\/sup\]/g,"<sup>$1</sup>").replace(/\[sub\]([\s\S]*)\[\/sub\]/g,"<sub>$1</sub>").replace(/\[spoiler\]([\s\S]*)\[\/spoiler\]/g,"<span>$1</span>").replace(/\[color\]([\s\S]*)\[\/color\]/g,"<span>$1</span>")}static formatBytes(bytes,decimals=2){if(0===bytes)return"0 B";const dm=decimals<0?0:decimals,i=Math.floor(Math.log(bytes)/Math.log(1024));return parseFloat((bytes/Math.pow(1024,i)).toFixed(dm))+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][i]}static versionCompare(v1,v2,options){const lexicographical=options&&options.lexicographical,zeroExtend=options&&options.zeroExtend;let v1parts=v1.split("."),v2parts=v2.split(".");function isValidPart(x){return(lexicographical?/^\d+[A-Za-z]*$/:/^\d+$/).test(x)}if(!v1parts.every(isValidPart)||!v2parts.every(isValidPart))return NaN;if(zeroExtend){for(;v1parts.length<v2parts.length;)v1parts.push("0");for(;v2parts.length<v1parts.length;)v2parts.push("0")}lexicographical||(v1parts=v1parts.map(Number),v2parts=v2parts.map(Number));for(let i=0;i<v1parts.length;++i){if(v2parts.length==i)return 1;if(v1parts[i]!=v2parts[i])return v1parts[i]>v2parts[i]?1:-1}return v1parts.length!=v2parts.length?-1:0}}exports.Util=Util,Util.Time=UtilTime_1.UtilTime,Util.ID=UtilID_1.UtilID,Util.LS=window.localStorage},{"./UtilID":33,"./UtilTime":34}],33:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UtilID=void 0;class UtilID{static make(length=8,unique=!0){if(!unique)return getRandomString(length);let uniqueID;do{uniqueID=getRandomString(length)}while(UtilID.uniqueIDs.has(uniqueID));return UtilID.uniqueIDs.add(uniqueID),uniqueID;function getRandomString(length){let result="";const chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",charLength=chars.length;for(let i=0;i<length;i++)result+=chars.charAt(Math.floor(Math.random()*charLength));return result}}static has(id){return UtilID.uniqueIDs.has(id)}static remove(id){return!!UtilID.has(id)&&(UtilID.uniqueIDs.delete(id),!0)}}exports.UtilID=UtilID,UtilID.uniqueIDs=new Set},{}],34:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UtilTime=void 0,function(UtilTime){UtilTime[UtilTime.SECOND=1e3]="SECOND",UtilTime[UtilTime.MINUTE=6e4]="MINUTE",UtilTime[UtilTime.HOUR=36e5]="HOUR",UtilTime[UtilTime.DAY=864e5]="DAY",UtilTime[UtilTime.WEEK=6048e5]="WEEK"}(exports.UtilTime||(exports.UtilTime={})),function(UtilTime){UtilTime.now=function(){return(new Date).getTime()},UtilTime.ago=function(time){switch(typeof time){case"string":time=+new Date(time);break;case"object":time=time.getTime()}const timeFormats=[[60,"seconds",1],[120,"1 minute ago","1 minute from now"],[3600,"minutes",60],[7200,"1 hour ago","1 hour from now"],[86400,"hours",3600],[172800,"Yesterday","Tomorrow"],[604800,"days",86400],[1209600,"Last week","Next week"],[2419200,"weeks",604800],[4838400,"Last month","Next month"],[29030400,"months",2419200],[58060800,"Last year","Next year"],[290304e4,"years",29030400],[580608e4,"Last century","Next century"],[580608e5,"centuries",290304e4]];let seconds=(+new Date-time)/1e3,token="ago",listChoice=1;if(seconds>=0&&seconds<2)return"Just now";seconds<0&&(seconds=Math.abs(seconds),token="from now",listChoice=2);let format,i=0;for(;format=timeFormats[i++];)if(seconds<format[0])return"string"==typeof format[2]?format[listChoice]:Math.floor(seconds/format[2])+" "+format[1]+" "+token;return time+""},UtilTime.format=function(date=new Date){"number"==typeof date&&(date=new Date(date));const parts={year:""+date.getFullYear(),month:""+(date.getMonth()+1),day:""+date.getDate(),hours:""+date.getHours(),minutes:""+date.getMinutes(),seconds:""+date.getSeconds()};for(const id in parts)parts[id].length<2&&(parts[id]="0"+parts[id]);return parts.year+"-"+parts.month+"-"+parts.day+" "+parts.hours+":"+parts.minutes+":"+parts.seconds},UtilTime.getDatetimeShort=function(){function twoDigit(n){return(n<10?"0":"")+n}const date=new Date;return(date.getFullYear()+"").substring(2)+twoDigit(date.getMonth()+1)+twoDigit(date.getDate())+"-"+twoDigit(date.getHours())+twoDigit(date.getMinutes())}}(exports.UtilTime||(exports.UtilTime={}))},{}],35:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const Page_1=require("./components/data/Page"),ModuleController_1=require("./components/ModuleController"),DomUtilities_1=require("./components/structure/DomUtilities"),Debug_1=require("./components/utility/Debug"),Patcher_1=require("./components/utility/Patcher"),Sync_1=require("./components/utility/Sync"),Util_1=require("./components/utility/Util"),FavDownloader_1=require("./modules/downloader/FavDownloader"),MassDownloader_1=require("./modules/downloader/MassDownloader"),PoolDownloader_1=require("./modules/downloader/PoolDownloader"),FormattingHelper_1=require("./modules/general/FormattingHelper"),HeaderCustomizer_1=require("./modules/general/HeaderCustomizer"),Miscellaneous_1=require("./modules/general/Miscellaneous"),SettingsController_1=require("./modules/general/SettingsController"),ThemeCustomizer_1=require("./modules/general/ThemeCustomizer"),SmartAlias_1=require("./modules/misc/SmartAlias"),UploadUtilities_1=require("./modules/misc/UploadUtilities"),WikiEnhancer_1=require("./modules/misc/WikiEnhancer"),DownloadCustomizer_1=require("./modules/post/DownloadCustomizer"),ImageScaler_1=require("./modules/post/ImageScaler"),PoolNavigator_1=require("./modules/post/PoolNavigator"),PostViewer_1=require("./modules/post/PostViewer"),TitleCustomizer_1=require("./modules/post/TitleCustomizer"),BlacklistEnhancer_1=require("./modules/search/BlacklistEnhancer"),CustomFlagger_1=require("./modules/search/CustomFlagger"),InfiniteScroll_1=require("./modules/search/InfiniteScroll"),InstantSearch_1=require("./modules/search/InstantSearch"),PostSuggester_1=require("./modules/search/PostSuggester"),SearchUtilities_1=require("./modules/search/SearchUtilities"),ThumbnailsEnhancer_1=require("./modules/search/ThumbnailsEnhancer"),CommentTracker_1=require("./modules/subscriptions/CommentTracker"),ForumTracker_1=require("./modules/subscriptions/ForumTracker"),PoolTracker_1=require("./modules/subscriptions/PoolTracker"),SubscriptionManager_1=require("./modules/subscriptions/SubscriptionManager"),TagTracker_1=require("./modules/subscriptions/TagTracker"),loadOrder=[FormattingHelper_1.FormattingManager,HeaderCustomizer_1.HeaderCustomizer,ThemeCustomizer_1.ThemeCustomizer,DownloadCustomizer_1.DownloadCustomizer,ImageScaler_1.ImageScaler,PoolNavigator_1.PoolNavigator,PostViewer_1.PostViewer,TitleCustomizer_1.TitleCustomizer,CustomFlagger_1.CustomFlagger,InfiniteScroll_1.InfiniteScroll,InstantSearch_1.InstantSearch,ThumbnailsEnhancer_1.ThumbnailEnhancer,PostSuggester_1.PostSuggester,SearchUtilities_1.SearchUtilities,Miscellaneous_1.Miscellaneous,BlacklistEnhancer_1.BlacklistEnhancer,SmartAlias_1.SmartAlias,WikiEnhancer_1.WikiEnhancer,UploadUtilities_1.UploadUtilities,FavDownloader_1.FavDownloader,PoolDownloader_1.PoolDownloader,MassDownloader_1.MassDownloader,SubscriptionManager_1.SubscriptionManager,SettingsController_1.SettingsController],subscriptions=[TagTracker_1.TagTracker,PoolTracker_1.PoolTracker,ForumTracker_1.ForumTracker,CommentTracker_1.CommentTracker];if(console.log(`${window.re621.name} v.${window.re621.version} build ${window.re621.build}`),Page_1.Page.matches(Page_1.PageDefintion.title)){const page=Util_1.Util.LS.getItem("re621.mainpage");page&&"default"!==page&&window.location.replace("/"+page)}DomUtilities_1.DomUtilities.createStructure().then(async()=>{await Debug_1.Debug.init(),await Patcher_1.Patcher.run(),await Sync_1.Sync.init(),await ModuleController_1.ModuleController.register(subscriptions),await SubscriptionManager_1.SubscriptionManager.register(subscriptions),await ModuleController_1.ModuleController.register(loadOrder)})},{"./components/ModuleController":1,"./components/data/Page":17,"./components/structure/DomUtilities":23,"./components/utility/Debug":28,"./components/utility/Patcher":30,"./components/utility/Sync":31,"./components/utility/Util":32,"./modules/downloader/FavDownloader":36,"./modules/downloader/MassDownloader":37,"./modules/downloader/PoolDownloader":38,"./modules/general/FormattingHelper":39,"./modules/general/HeaderCustomizer":40,"./modules/general/Miscellaneous":41,"./modules/general/SettingsController":42,"./modules/general/ThemeCustomizer":43,"./modules/misc/SmartAlias":44,"./modules/misc/UploadUtilities":45,"./modules/misc/WikiEnhancer":46,"./modules/post/DownloadCustomizer":47,"./modules/post/ImageScaler":48,"./modules/post/PoolNavigator":49,"./modules/post/PostViewer":50,"./modules/post/TitleCustomizer":51,"./modules/search/BlacklistEnhancer":52,"./modules/search/CustomFlagger":53,"./modules/search/InfiniteScroll":54,"./modules/search/InstantSearch":55,"./modules/search/PostSuggester":56,"./modules/search/SearchUtilities":57,"./modules/search/ThumbnailsEnhancer":58,"./modules/subscriptions/CommentTracker":59,"./modules/subscriptions/ForumTracker":60,"./modules/subscriptions/PoolTracker":61,"./modules/subscriptions/SubscriptionManager":62,"./modules/subscriptions/TagTracker":64}],36:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FavDownloader=void 0;const DownloadQueue_1=require("../../components/api/DownloadQueue"),E621_1=require("../../components/api/E621"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),InfiniteScroll_1=require("../search/InfiniteScroll"),MassDownloader_1=require("./MassDownloader");class FavDownloader extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.favorites),this.processing=!1,this.downloadOverSize=!1,this.batchOverSize=!0,this.posts=[],this.fileTimestamp=Util_1.Util.Time.getDatetimeShort(),this.downloadIndex=1}getDefaultSettings(){return{enabled:!0,template:"%artist%/%postid%-%copyright%-%character%-%species%",autoDownloadArchive:!0,fixedSection:!0}}create(){super.create(),this.section=$("<section>").attr({id:"fav-downloader-box","data-fixed":this.fetchSettings("fixedSection")+""}).html("<h1>Download</h1>").appendTo("aside#sidebar");const usernameMatch=/^(?:.*\s)?fav:([^\s]+)\s.*$/g.exec($("input#tags").val()+"");null!=usernameMatch&&null!=usernameMatch[1]&&(this.username=usernameMatch[1],this.actButton=$("<a>").html("Download All").addClass("pool-download-button button btn-neutral").appendTo(this.section).on("click",event=>{event.preventDefault(),this.processFiles()}),this.infoText=$("<div>").addClass("download-info").appendTo(this.section),this.infoFile=$("<div>").addClass("download-file").appendTo(this.section))}destroy(){super.destroy()}toggleFixedSection(){"true"===this.section.attr("data-fixed")?this.section.attr("data-fixed","false"):this.section.attr("data-fixed","true")}async processFiles(){if(this.processing)return;let lookup;this.processing=!0,this.actButton.attr("disabled","disabled"),InfiniteScroll_1.InfiniteScroll.trigger("pauseScroll",!0),this.infoText.attr("data-state","loading").html("Indexing favorites . . ."),0==this.posts.length?(this.infoText.attr("data-state","loading").html("Fetching API data . . ."),lookup=async function recursiveLookup(output,info,username,index){return info.html(" &nbsp; &nbsp;request "+index+" ["+output.length+"]"),E621_1.E621.Posts.get({tags:"fav:"+username,page:index,limit:320}).then(data=>(output.push(...data),320==data.length?recursiveLookup(output,info,username,++index):Promise.resolve(output)))}([],this.infoFile,this.username,1)):lookup=Promise.resolve(this.posts),lookup.then(output=>{this.posts=output;const downloadQueue=new DownloadQueue_1.DownloadQueue,threadInfo=[];this.infoFile.html("");for(let i=0;i<downloadQueue.getThreadCount();i++)threadInfo.push($("<span>").appendTo(this.infoFile));let processingPost,totalFileSize=0,queueSize=0;for(this.batchOverSize=!1;processingPost=this.posts.pop();){const post=processingPost;if(totalFileSize+=post.file.size,totalFileSize>FavDownloader.maxBlobSize){this.batchOverSize=!0,this.downloadOverSize=!0;break}downloadQueue.add({name:this.createFilename(post),path:post.file.url,file:post.file.url.replace(/^https:\/\/static1\.e621\.net\/data\/..\/..\//g,""),unid:post.id,date:null===post.updated_at?new Date(post.created_at):new Date(post.updated_at),tags:post.tags.general.join(" ")},{onStart:(item,thread,index)=>{this.infoText.html('Downloading ... <span class="float-right">'+(queueSize-index)+" / "+queueSize+"</span>"),threadInfo[thread].html(item.file).css("--progress","0%"),$("article.post-preview#post_"+post.id).attr("data-state","loading")},onFinish:()=>{$("article.post-preview#post_"+post.id).attr("data-state","done")},onError:()=>{$("article.post-preview#post_"+post.id).attr("data-state","error")},onLoadProgress:(item,thread,event)=>{event.lengthComputable&&threadInfo[thread].css("--progress",Math.round(event.loaded/event.total*100)+"%")},onWorkerFinish:(item,thread)=>{threadInfo[thread].remove()}})}return queueSize=downloadQueue.getQueueLength(),this.infoText.html("Processing . . . "),downloadQueue.run(metadata=>{this.infoText.html("Compressing . . . "+metadata.percent.toFixed(2)+"%"),metadata.currentFile?this.infoFile.html(metadata.currentFile):this.infoFile.html("")})}).then(zipData=>{let filename=this.username+"-fav-"+this.fileTimestamp;filename+=this.downloadOverSize?"-part"+this.downloadIndex+".zip":".zip",this.infoText.attr("data-state","done").html("Done! "),this.infoFile.html("");const $downloadLink=$("<a>").attr("href",filename).html("Download Archive").appendTo(this.infoText).on("click",event=>{event.preventDefault(),saveAs(zipData,filename)});this.fetchSettings("autoDownloadArchive")&&$downloadLink.get(0).click(),this.downloadIndex++,this.actButton.removeAttr("disabled"),this.processing=!1,this.batchOverSize?this.fetchSettings("autoDownloadArchive")?this.actButton.get(0).click():$("<div>").addClass("download-notice").html("Download has exceeded the maximum file size.<br /><br />Click the download button again for the next part.").appendTo(this.infoText):InfiniteScroll_1.InfiniteScroll.trigger("pauseScroll",!1)})}createFilename(data){return MassDownloader_1.MassDownloader.createFilenameBase(this.fetchSettings("template"),data).slice(0,128).replace(/-{2,}/g,"-").replace(/-*$/g,"")+"."+data.file.ext}}exports.FavDownloader=FavDownloader,FavDownloader.maxBlobSize=838860800},{"../../components/RE6Module":2,"../../components/api/DownloadQueue":4,"../../components/api/E621":5,"../../components/data/Page":17,"../../components/utility/Util":32,"../search/InfiniteScroll":54,"./MassDownloader":37}],37:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MassDownloader=void 0;const DownloadQueue_1=require("../../components/api/DownloadQueue"),E621_1=require("../../components/api/E621"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),InfiniteScroll_1=require("../search/InfiniteScroll"),ThumbnailsEnhancer_1=require("../search/ThumbnailsEnhancer");class MassDownloader extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.search),this.showInterface=!1,this.processing=!1,this.downloadOverSize=!1,this.batchOverSize=!0,this.fileTimestamp=Util_1.Util.Time.getDatetimeShort(),this.downloadIndex=1}getDefaultSettings(){return{enabled:!0,template:"%artist%/%postid%-%copyright%-%character%-%species%",autoDownloadArchive:!0,fixedSection:!0}}create(){super.create(),this.section=$("<section>").attr({id:"downloader-box","data-fixed":this.fetchSettings("fixedSection")+""}).html("<h1>Download</h1>").appendTo("aside#sidebar"),this.selectButton=$("<a>").html("Select").attr("id","download-select").addClass("button btn-neutral").appendTo(this.section).on("click",event=>{event.preventDefault(),this.toggleInterface()}),this.actButton=$("<a>").html("Download").attr("id","download-act").addClass("button btn-neutral").appendTo(this.section).on("click",event=>{event.preventDefault(),this.processFiles()}),this.infoText=$("<div>").addClass("download-info").appendTo(this.section),this.infoFile=$("<div>").addClass("download-file").appendTo(this.section),this.container=$("#posts-container")}destroy(){super.destroy(),InfiniteScroll_1.InfiniteScroll.off("pageLoad.MassDownloader")}toggleInterface(){this.showInterface=!this.showInterface,ThumbnailsEnhancer_1.ThumbnailEnhancer.trigger("pauseHoverActions",this.showInterface),this.showInterface?(this.selectButton.html("Cancel"),this.section.attr("data-interface","true"),this.infoText.html('Click on thumbnails to select them, then press "Download"'),this.container.attr("data-downloading","true").selectable({autoRefresh:!1,filter:"article.post-preview",selected:function(event,ui){$(ui.selected).toggleClass("download-item").attr("data-state","ready")}}),InfiniteScroll_1.InfiniteScroll.on("pageLoad.MassDownloader",()=>{this.container.selectable("refresh")})):(this.selectButton.html("Select"),this.section.attr("data-interface","false"),this.container.attr("data-downloading","false").selectable("destroy"),InfiniteScroll_1.InfiniteScroll.off("pageLoad.MassDownloader"))}toggleFixedSection(){"true"===this.section.attr("data-fixed")?this.section.attr("data-fixed","false"):this.section.attr("data-fixed","true")}processFiles(){if(this.processing)return;this.processing=!0,this.actButton.attr("disabled","disabled"),InfiniteScroll_1.InfiniteScroll.trigger("pauseScroll",!0),this.infoText.attr("data-state","loading").html("Indexing selected files . . .");const imageList=[];if($("article.post-preview.download-item[data-state=ready]").each((index,element)=>{imageList.push(parseInt($(element).attr("data-id")))}),0===imageList.length)return void this.infoText.attr("data-state","error").html("Error: No files selected!");this.infoText.attr("data-state","loading").html("Fetching API data . . .");const dataQueue=[],resultPages=Util_1.Util.chunkArray(imageList,MassDownloader.chunkSize);this.infoFile.html(" &nbsp; &nbsp;request 1 / "+resultPages.length),resultPages.forEach((value,index)=>{dataQueue.push(new Promise(async resolve=>{const result=await E621_1.E621.Posts.get({tags:"id:"+value.join(",")});this.infoFile.html(" &nbsp; &nbsp;request "+(index+1)+" / "+resultPages.length),resolve(result)}))}),Promise.all(dataQueue.reverse()).then(dataChunks=>{const downloadQueue=new DownloadQueue_1.DownloadQueue,threadInfo=[];this.infoFile.html("");for(let i=0;i<downloadQueue.getThreadCount();i++)threadInfo.push($("<span>").appendTo(this.infoFile));let totalFileSize=0,queueSize=0;return this.batchOverSize=!1,dataChunks.forEach(chunk=>{this.batchOverSize||chunk.forEach(post=>{if(totalFileSize+=post.file.size,totalFileSize>MassDownloader.maxBlobSize)return this.batchOverSize=!0,void(this.downloadOverSize=!0);$("article.post-preview#post_"+post.id).attr("data-state","preparing"),downloadQueue.add({name:this.createFilename(post),path:post.file.url,file:post.file.url.replace(/^https:\/\/static1\.e621\.net\/data\/..\/..\//g,""),unid:post.id,date:null===post.updated_at?new Date(post.created_at):new Date(post.updated_at),tags:post.tags.general.join(" ")},{onStart:(item,thread,index)=>{this.infoText.html('Downloading ... <span class="float-right">'+(queueSize-index)+" / "+queueSize+"</span>"),threadInfo[thread].html(item.file).css("--progress","0%"),$("article.post-preview#post_"+post.id).attr("data-state","loading")},onFinish:()=>{$("article.post-preview#post_"+post.id).attr("data-state","done")},onError:()=>{$("article.post-preview#post_"+post.id).attr("data-state","error")},onLoadProgress:(item,thread,event)=>{event.lengthComputable&&threadInfo[thread].css("--progress",Math.round(event.loaded/event.total*100)+"%")},onWorkerFinish:(item,thread)=>{threadInfo[thread].remove()}})})}),queueSize=downloadQueue.getQueueLength(),this.infoText.html("Processing . . . "),downloadQueue.run(metadata=>{this.infoText.html("Compressing . . . "+metadata.percent.toFixed(2)+"%"),metadata.currentFile?this.infoFile.html(metadata.currentFile):this.infoFile.html("")})}).then(zipData=>{let filename="e621-"+this.fileTimestamp;filename+=this.downloadOverSize?"-part"+this.downloadIndex+".zip":".zip",this.infoText.attr("data-state","done").html("Done! "),this.infoFile.html("");const $downloadLink=$("<a>").attr("href",filename).html("Download Archive").appendTo(this.infoText).on("click",event=>{event.preventDefault(),saveAs(zipData,filename)});this.fetchSettings("autoDownloadArchive")&&$downloadLink.get(0).click(),this.downloadIndex++,this.actButton.removeAttr("disabled"),this.processing=!1,this.batchOverSize?this.fetchSettings("autoDownloadArchive")?this.actButton.get(0).click():$("<div>").addClass("download-notice").html("Download has exceeded the maximum file size.<br /><br />Click the download button again for the next part.").appendTo(this.infoText):InfiniteScroll_1.InfiniteScroll.trigger("pauseScroll",!1)})}createFilename(data){return MassDownloader.createFilenameBase(this.fetchSettings("template"),data).slice(0,128).replace(/-{2,}/g,"-").replace(/-*$/g,"")+"."+data.file.ext}static createFilenameBase(template,data){return template.replace(/%postid%/g,data.id+"").replace(/%artist%/g,data.tags.artist.join("-")).replace(/%copyright%/g,data.tags.copyright.join("-")).replace(/%character%/g,data.tags.character.join("-")).replace(/%species%/g,data.tags.species.join("-")).replace(/%meta%/g,data.tags.meta.join("-")).replace(/%md5%/g,data.file.md5)}}exports.MassDownloader=MassDownloader,MassDownloader.chunkSize=100,MassDownloader.maxBlobSize=838860800},{"../../components/RE6Module":2,"../../components/api/DownloadQueue":4,"../../components/api/E621":5,"../../components/data/Page":17,"../../components/utility/Util":32,"../search/InfiniteScroll":54,"../search/ThumbnailsEnhancer":58}],38:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PoolDownloader=void 0;const DownloadQueue_1=require("../../components/api/DownloadQueue"),E621_1=require("../../components/api/E621"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),MassDownloader_1=require("./MassDownloader");class PoolDownloader extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.pool,Page_1.PageDefintion.set]),this.processing=!1,this.downloadOverSize=!1,this.batchOverSize=!0,this.fileTimestamp=Util_1.Util.Time.getDatetimeShort(),this.downloadIndex=1,this.poolName="",this.poolFiles=[],this.poolDownloaded=[],this.blacklistSkipped=0}getDefaultSettings(){return{enabled:!0,template:"%pool%/%index%-%postid%-%artist%-%copyright%-%character%-%species%",autoDownloadArchive:!0}}create(){super.create();const base=Page_1.Page.matches(Page_1.PageDefintion.pool)?"div#c-pools":"div#c-sets",container=$(base).addClass("pool-container"),overview=$("#a-show").addClass("pool-overview");this.actButton=$("<button>").addClass("pool-download-button").addClass("button btn-neutral").html("Download").prependTo(overview).on("click",event=>{event.preventDefault(),container.attr("data-interface","true"),this.processFiles()});const sidebar=$("<aside>").addClass("pool-sidebar").appendTo(container);this.section=$("<section>").attr("id","pool-downloader-box").html("<h1>Download</h1>").appendTo(sidebar),this.infoText=$("<div>").addClass("download-info").appendTo(this.section),this.infoFile=$("<div>").addClass("download-file").appendTo(this.section)}processFiles(){if(this.processing)return;let source;this.processing=!0,this.actButton.attr("disabled","disabled"),this.infoText.attr("data-state","loading").html("Indexing pool files . . .");let poolName="UnknownPostGroup";source=Page_1.Page.matches(Page_1.PageDefintion.pool)?E621_1.E621.Pools.get({"search[id]":Page_1.Page.getPageID()}):E621_1.E621.Sets.get({"search[id]":Page_1.Page.getPageID()}),source.then(poolData=>{if(poolData.length<1)return Promise.reject("Pool not found");const pool=poolData[0],imageList=pool.post_ids.filter(n=>!this.poolDownloaded.includes(n));if(this.poolFiles=pool.post_ids,poolName=pool.name,0===imageList.length)return this.infoText.attr("data-state","error").html("Error: Pool is empty!"),Promise.reject("Pool is empty");this.poolName=pool.name,this.infoText.attr("data-state","loading").html("Fetching API data . . .");const dataQueue=[],resultPages=Math.ceil(imageList.length/320);this.infoFile.html(" &nbsp; &nbsp;request 1 / "+resultPages);for(let i=1;i<=resultPages;i++)dataQueue.push(new Promise(async resolve=>{const result=await E621_1.E621.Posts.get({tags:(Page_1.Page.matches(Page_1.PageDefintion.pool)?"pool:":"set:")+pool.id,page:i,limit:320},500);this.infoFile.html(" &nbsp; &nbsp;request "+(i+1)+" / "+resultPages),resolve(result)}));return Promise.all(dataQueue)}).then(dataChunks=>{const downloadQueue=new DownloadQueue_1.DownloadQueue,threadInfo=[];this.infoFile.html("");for(let i=0;i<downloadQueue.getThreadCount();i++)threadInfo.push($("<span>").appendTo(this.infoFile));let totalFileSize=0,queueSize=0;return this.batchOverSize=!1,this.blacklistSkipped=0,dataChunks.forEach(chunk=>{this.batchOverSize||chunk.forEach(post=>{if(totalFileSize+=post.file.size,totalFileSize>PoolDownloader.maxBlobSize)return this.batchOverSize=!0,void(this.downloadOverSize=!0);null!==post.file.url?($("article.post-preview#post_"+post.id).attr("data-state","preparing"),downloadQueue.add({name:this.createFilename(post),path:post.file.url,file:post.file.url.replace(/^https:\/\/static1\.e621\.net\/data\/..\/..\//g,""),unid:post.id,date:null===post.updated_at?new Date(post.created_at):new Date(post.updated_at),tags:post.tags.general.join(" ")},{onStart:(item,thread,index)=>{this.infoText.html('Downloading ... <span class="float-right">'+(queueSize-index)+" / "+queueSize+"</span>"),threadInfo[thread].html(item.file).css("--progress","0%"),$("article.post-preview#post_"+post.id).attr("data-state","loading")},onFinish:()=>{$("article.post-preview#post_"+post.id).attr("data-state","done")},onError:()=>{$("article.post-preview#post_"+post.id).attr("data-state","error")},onLoadProgress:(item,thread,event)=>{event.lengthComputable&&threadInfo[thread].css("--progress",Math.round(event.loaded/event.total*100)+"%")},onWorkerFinish:(item,thread)=>{threadInfo[thread].remove()}}),this.poolDownloaded.push(post.id)):this.blacklistSkipped++})}),queueSize=downloadQueue.getQueueLength(),this.infoText.html("Processing . . . "),downloadQueue.run(metadata=>{this.infoText.html("Compressing . . . "+metadata.percent.toFixed(2)+"%"),metadata.currentFile?this.infoFile.html(metadata.currentFile):this.infoFile.html("")})}).then(zipData=>{let filename=this.createPoolFilename(poolName)+"-"+this.fileTimestamp;filename+=this.downloadOverSize?"-part"+this.downloadIndex+".zip":".zip",this.infoText.attr("data-state","done").html("Done! "),this.infoFile.html("");const $downloadLink=$("<a>").attr("href",filename).html("Download Archive").appendTo(this.infoText).on("click",event=>{event.preventDefault(),saveAs(zipData,filename)});this.fetchSettings("autoDownloadArchive")&&$downloadLink.get(0).click(),this.downloadIndex++,this.actButton.removeAttr("disabled"),this.processing=!1,this.batchOverSize&&(this.fetchSettings("autoDownloadArchive")?this.actButton.get(0).click():$("<div>").addClass("download-notice").html("Download has exceeded the maximum file size.<br /><br />Click the download button again for the next part.").appendTo(this.infoText)),this.blacklistSkipped>0&&$("<div>").addClass("download-notice").html('Some files could not be downloaded due to the <a href="/help/global_blacklist">global blacklist</a>.').appendTo(this.infoText)})}createFilename(data){return MassDownloader_1.MassDownloader.createFilenameBase(this.fetchSettings("template"),data).replace(/%pool%/g,this.poolName).replace(/%index%/g,""+(this.poolFiles.indexOf(data.id)+1)).slice(0,128).replace(/-{2,}/g,"-").replace(/-*$/g,"")+"."+data.file.ext}createPoolFilename(name){return name.slice(0,64).replace(/\s/g,"_").replace(/_{2,}/g,"_").replace(/-{2,}/g,"-").replace(/-*$/g,"")}}exports.PoolDownloader=PoolDownloader,PoolDownloader.chunkSize=100,PoolDownloader.maxBlobSize=838860800},{"../../components/RE6Module":2,"../../components/api/DownloadQueue":4,"../../components/api/E621":5,"../../components/data/Page":17,"../../components/utility/Util":32,"./MassDownloader":37}],39:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FormattingManager=void 0;const Danbooru_1=require("../../components/api/Danbooru"),E621_1=require("../../components/api/E621"),RE6Module_1=require("../../components/RE6Module"),Form_1=require("../../components/structure/Form"),Modal_1=require("../../components/structure/Modal"),Prompt_1=require("../../components/structure/Prompt"),iconDefinitions={spacer:"&nbsp;",bold:"&#xf032",italic:"&#xf033",strikethrough:"&#xf0cc",underscore:"&#xf0cd",superscript:"&#xf12b",subscript:"&#xf12c",spoiler:"&#xf29e",color:"&#xf53f",code:"&#xf121",heading:"&#xf1dc",quote:"&#xf10e",section:"&#xf103",tag:"&#xf02b",wiki:"&#xf002",keyboard:"&#xf11c",link:"&#xf0c1",unlink:"&#xf127",link_prompt:"&#xf35d",lemon:"&#xf094",pepper:"&#xf816",drumstick:"&#xf6d7",magic:"&#xf0d0",clipboard:"&#xf328",paperclip:"&#xf0c6",fountainpen:"&#xf5ad",comment:"&#xf27a",bell:"&#xf0f3",bullhorn:"&#xf0a1",heart:"&#xf004","plus-square":"&#xf0fe","minus-square":"&#xf146",baby:"&#xf77c",scales:"&#xf24e","chart-pie":"&#xf200",dice:"&#xf522",hotdog:"&#xf80f",leaf:"&#xf06c","paper-plane":"&#xf1d8",anchor:"&#xf13d",crown:"&#xf521",crow:"&#xf520"};class FormattingManager extends RE6Module_1.RE6Module{constructor(){super(...arguments),this.formatters=[],this.index=0}getDefaultSettings(){return{enabled:!0,buttonsActive:[{name:"Bold",icon:"bold",text:"[b]%selection%[/b]"},{name:"Italic",icon:"italic",text:"[i]%selection%[/i]"},{name:"Strikethrough",icon:"strikethrough",text:"[s]%selection%[/s]"},{name:"Underscore",icon:"underscore",text:"[u]%selection%[/u]"},{name:"Spacer",icon:"spacer",text:""},{name:"Heading",icon:"heading",text:"h2.%selection%"},{name:"Spoiler",icon:"spoiler",text:"[spoiler]%selection%[/spoiler]"},{name:"Code",icon:"code",text:"`%selection%`"},{name:"Quote",icon:"quote",text:"[quote]%selection%[/quote]"},{name:"Section",icon:"section",text:"[section=Title]%selection%[/section]"},{name:"Tag",icon:"tag",text:"{{%selection%}}"},{name:"Link",icon:"link",text:'"%selection%":'}],buttonInactive:[{name:"Superscript",icon:"superscript",text:"[sup]%selection%[/sup]"},{name:"Color",icon:"color",text:"[color=]%selection%[/color]"},{name:"Wiki",icon:"wiki",text:"[[%selection%]]"},{name:"Link (Prompted)",icon:"link_prompt",text:'"%selection%":%prompt:Address%'}]}}create(){super.create(),$("div.dtext-previewable:has(textarea)").each((i,element)=>{const $container=$(element),newFormatter=new FormattingHelper($container,this,this.index);this.formatters.push(newFormatter),$container.on("re621:formatter:update",()=>{this.formatters.forEach(element=>{element.getContainer().is(newFormatter.getContainer())||element.loadButtons()})}),this.index++})}destroy(){this.formatters.forEach(entry=>{entry.destroy()}),this.formatters=[]}}exports.FormattingManager=FormattingManager;class FormattingHelper{constructor($targetContainer,parent,id){this.parent=parent,this.id=id,this.$container=$targetContainer,this.createDOM()}getContainer(){return this.$container}createDOM(){this.$container.attr("data-editing","true"),this.$container.attr("data-drawer","false"),this.$form=this.$container.parents("form.simple_form").first(),this.$textarea=this.$container.find("textarea"),this.$preview=this.$container.find("div.dtext-preview"),this.createToolbar(),this.createButtonDrawer(),this.createCharacterCounter(),this.$form.find("input.dtext-preview-button").css("display","none"),this.$form.find("input[type=submit]").addClass("dtext-submit"),this.$form.addClass("formatting-helper"),this.$textarea.attr({rows:"0",cols:"0"}).addClass("border-foreground"),this.$preview.addClass("border-foreground color-text"),this.$formatButtons.sortable({helper:"clone",forceHelperSize:!0,cursor:"grabbing",containment:this.$container,connectWith:this.$formatButtonsDrawer,disabled:!0,update:()=>{this.saveButtons()}}),this.$formatButtonsDrawer.sortable({helper:"clone",forceHelperSize:!0,cursor:"grabbing",containment:this.$container,connectWith:this.$formatButtons,disabled:!0});const $editButtonsForm=new Form_1.Form({name:"dtext-edit-button-"+this.id,columns:2,width:2},[Form_1.Form.input({name:"name",label:"Name",width:2}),Form_1.Form.icon({name:"icon",label:"Icon",width:2},iconDefinitions),Form_1.Form.input({name:"text",label:"Content",width:2}),Form_1.Form.button({name:"delete",value:"Delete"},async()=>{this.deleteButton(this.$editButtonsModal.getActiveTrigger().parent()),this.$editButtonsModal.close()}),Form_1.Form.button({name:"update",value:"Update",type:"submit"}),Form_1.Form.hr(2),Form_1.Form.div({value:"Available variables:",width:2}),Form_1.Form.copy({label:"Selection",value:"%selection%",width:2}),Form_1.Form.copy({label:"Prompt",value:"%prompt%",width:2})],async values=>{this.updateButton(this.$editButtonsModal.getActiveTrigger().parent(),{name:values.name,icon:values.icon,text:values.text}),this.$editButtonsModal.close()});this.$editButtonsModal=new Modal_1.Modal({title:"Edit Button",content:Form_1.Form.placeholder(),structure:$editButtonsForm,triggers:[],triggerMulti:!0,fixed:!0,disabled:!0}),this.$editButtonsModal.getElement().on("dialogopen",()=>{const $button=this.$editButtonsModal.getActiveTrigger().parent(),$updateTabInputs=$editButtonsForm.getInputList();$updateTabInputs.get("name").val($button.attr("data-name")),$updateTabInputs.get("icon").val($button.attr("data-icon")).trigger("re621:form:update"),$updateTabInputs.get("text").val($button.attr("data-text"))}),this.loadButtons()}destroy(){this.$container.find(".comment-header, .dtext-button-drawer-title, .dtext-button-drawer, .dtext-character-counter-box").remove(),this.$form.find("input.dtext-preview-button").css("display","")}createToolbar(){const $bar=$("<div>").addClass("comment-header").addClass("border-foreground").prependTo(this.$container);this.$toggleTabs=$("<div>").addClass("comment-tabs").html('\n                <a class="toggle-editing active">Write</a>\n                <a class="toggle-preview">Preview</a>\n            ').appendTo($bar),this.$toggleTabs.find("a").click(e=>{e.preventDefault(),this.toggleEditing()}),this.$formatButtons=$("<div>").addClass("comment-buttons").appendTo($bar);const $drawerButtonBox=$("<li>").appendTo($("<div>").addClass("settings-buttons").appendTo($bar));$("<a>").html("&#xf1de").attr("title","Settings").appendTo($drawerButtonBox).click(event=>{event.preventDefault(),this.toggleButtonDrawer()})}createButtonDrawer(){const $newFormatButton=$("<a>").html("Add Button");$("<div>").addClass("dtext-button-drawer-title").addClass("border-foreground color-text").append($newFormatButton).appendTo(this.$container);const newFormatForm=new Form_1.Form({name:"dtext-custom-button-"+this.id,columns:2,width:2},[Form_1.Form.input({name:"name",label:"Name",width:2}),Form_1.Form.icon({name:"icon",label:"Icon",width:2},iconDefinitions),Form_1.Form.input({name:"text",label:"Content",width:2}),Form_1.Form.spacer(),Form_1.Form.button({name:"submit",value:"Create",type:"submit"}),Form_1.Form.hr(2),Form_1.Form.div({value:"Available variables:",width:2}),Form_1.Form.copy({label:"Selection",value:"%selection%",width:2}),Form_1.Form.copy({label:"Prompt",value:"%prompt%",width:2})],values=>{this.createButton({name:values.name,icon:values.icon,text:values.text}).box.appendTo(this.$formatButtonsDrawer),newFormatForm.reset(),newFormatModal.close(),this.saveButtons()}),newFormatModal=new Modal_1.Modal({title:"New Custom Button",content:Form_1.Form.placeholder(),structure:newFormatForm,triggers:[{element:$newFormatButton}],fixed:!0});this.$formatButtonsDrawer=$("<div>").addClass("dtext-button-drawer").addClass("border-foreground color-text").appendTo(this.$container)}createCharacterCounter(){const charCounter=$("<span>").addClass("char-counter").html((this.$textarea.val()+"").length+" / 50000");$("<div>").addClass("dtext-character-counter-box").append(charCounter).appendTo(this.$container),this.$textarea.keyup(()=>{charCounter.html((this.$textarea.val()+"").length+" / 50000")})}loadButtons(){this.$formatButtons.empty(),this.parent.fetchSettings("buttonsActive",!0).then(response=>{response.forEach(data=>{const buttonElement=this.createButton(data);buttonElement.box.appendTo(this.$formatButtons),""===buttonElement.box.attr("data-text")&&(buttonElement.button.addClass("disabled"),buttonElement.button.removeAttr("title"))})}),this.$formatButtonsDrawer.empty(),this.parent.fetchSettings("buttonInactive",!0).then(response=>{response.forEach(data=>{this.createButton(data).box.appendTo(this.$formatButtonsDrawer)})})}async saveButtons(){let buttonData=[];function fetchData(element){const $button=$(element);return{name:$button.attr("data-name"),icon:$button.attr("data-icon"),text:$button.attr("data-text")}}this.$formatButtons.find("li").each((function(i,element){buttonData.push(fetchData(element))})),await this.parent.pushSettings("buttonsActive",buttonData),buttonData=[],this.$formatButtonsDrawer.find("li").each((function(i,element){buttonData.push(fetchData(element))})),await this.parent.pushSettings("buttonInactive",buttonData),this.$container.trigger("re621:formatter:update",[this])}parseButtonConfig(config){return void 0===config.name&&(config.name="New Button"),void 0===config.icon&&(config.icon="#"),void 0===config.text&&(config.text=""),config}createButton(config){config=this.parseButtonConfig(config);const box=$("<li>").attr({"data-name":config.name,"data-icon":config.icon,"data-text":config.text}).appendTo(this.$formatButtons),button=$("<a>").html(this.getIcon(config.icon)).addClass("format-button").attr("title",config.name).appendTo(box);return this.$editButtonsModal.registerTrigger({element:button}),button.click(event=>{event.preventDefault(),"false"===this.$container.attr("data-drawer")&&this.processFormattingTag(box.attr("data-text"))}),{button:button,box:box}}updateButton($element,config){config=this.parseButtonConfig(config),$element.attr("data-name",config.name).attr("data-icon",config.icon).attr("data-text",config.text),$element.find("a").first().html(this.getIcon(config.icon)).attr("title",config.name),this.saveButtons()}deleteButton($element){$element.remove(),this.saveButtons()}toggleEditing(){"true"===this.$container.attr("data-editing")?(this.$container.attr("data-editing","false"),this.$toggleTabs.find("a").toggleClass("active"),E621_1.E621.DTextPreview.post({body:this.$textarea.val()}).then(response=>{this.$preview.html(response[0].html),Danbooru_1.Danbooru.E621.addDeferredPosts(response[0].posts),Danbooru_1.Danbooru.Thumbnails.initialize()})):(this.$container.attr("data-editing","true"),this.$toggleTabs.find("a").toggleClass("active"))}toggleButtonDrawer(){"true"===this.$container.attr("data-drawer")?(this.$container.attr("data-drawer","false"),this.$formatButtons.sortable("disable"),this.$formatButtonsDrawer.sortable("disable"),this.$editButtonsModal.disable()):(this.$container.attr("data-drawer","true"),this.$formatButtons.sortable("enable"),this.$formatButtonsDrawer.sortable("enable"),this.$editButtonsModal.enable())}getIcon(name){return iconDefinitions[name]||""}processFormattingTag(content){const promises=[],lookup=content.match(/%prompt[:]?[^%]*?(%|$)/g),replacedTags=[];null!==lookup&&lookup.forEach((function(element){const title=element.replace(/(%$)|(^%prompt[:]?)/g,"");replacedTags.push(element),promises.push(new Prompt_1.Prompt(title).getPromise())})),Promise.all(promises).then(data=>{replacedTags.forEach((function(tag,index){content=content.replace(tag,data[index])}));const currentText=this.$textarea.val()+"",position={start:this.$textarea.prop("selectionStart"),end:this.$textarea.prop("selectionEnd")};content=content.replace(/%selection%/g,currentText.substring(position.start,position.end)),this.$textarea.focus(),document.execCommand("insertText",!1,content)||this.$textarea.val(currentText.substring(0,position.start)+content+currentText.substring(position.end,currentText.length)),this.$textarea.prop("selectionStart",position.start),this.$textarea.prop("selectionEnd",position.start+content.length),this.$textarea.keyup()})}}},{"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/api/E621":5,"../../components/structure/Form":24,"../../components/structure/Modal":25,"../../components/structure/Prompt":26}],40:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.HeaderCustomizer=void 0;const Page_1=require("../../components/data/Page"),User_1=require("../../components/data/User"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),Form_1=require("../../components/structure/Form"),Modal_1=require("../../components/structure/Modal");class HeaderCustomizer extends RE6Module_1.RE6Module{constructor(){super(),this.registerHotkeys({keys:"hotkeyTab1",fnct:()=>{HeaderCustomizer.openTabNum(0)}},{keys:"hotkeyTab2",fnct:()=>{HeaderCustomizer.openTabNum(1)}},{keys:"hotkeyTab3",fnct:()=>{HeaderCustomizer.openTabNum(2)}},{keys:"hotkeyTab4",fnct:()=>{HeaderCustomizer.openTabNum(3)}},{keys:"hotkeyTab5",fnct:()=>{HeaderCustomizer.openTabNum(4)}},{keys:"hotkeyTab6",fnct:()=>{HeaderCustomizer.openTabNum(5)}},{keys:"hotkeyTab7",fnct:()=>{HeaderCustomizer.openTabNum(6)}},{keys:"hotkeyTab8",fnct:()=>{HeaderCustomizer.openTabNum(7)}},{keys:"hotkeyTab9",fnct:()=>{HeaderCustomizer.openTabNum(8)}})}getDefaultSettings(){return{enabled:!0,hotkeyTab1:"1",hotkeyTab2:"2",hotkeyTab3:"3",hotkeyTab4:"4",hotkeyTab5:"5",hotkeyTab6:"6",hotkeyTab7:"7",hotkeyTab8:"8",hotkeyTab9:"9",tabs:[{name:"Account",href:"/users/home"},{name:"Posts",href:"/posts"},{name:"Comments",href:"/comments?group_by=post"},{name:"Artists",href:"/artists"},{name:"Tags",href:"/tags"},{name:"Blips",href:"/blips"},{name:"Pools",href:"/pools"},{name:"Sets",href:"/post_sets"},{name:"Wiki",href:"/wiki_pages?title=help%3Ahome"},{name:"Forum",href:"/forum_topics"},{name:"Discord",href:"/static/discord"},{name:"Help",href:"/help"},{name:"More »",href:"/static/site_map"}],forumUpdateDot:!0}}create(){super.create(),this.hasForumUpdates=$("li#nav-forum").hasClass("forum-updated"),this.$menu=$("menu.main"),this.$oldMenu=$("<div>").css("display","none").appendTo("body"),this.$menu.children().appendTo(this.$oldMenu),this.$menu.addClass("custom");for(const value of this.fetchSettings("tabs"))this.createTabElement(value);this.reloadTabMargins(),this.$menu.sortable({axis:"x",containment:"parent",helper:"clone",forceHelperSize:!0,opacity:.75,cursor:"grabbing",disabled:!0,update:()=>{this.reloadTabMargins(),this.saveNavbarSettings()}}),this.createConfigInterface(),this.toggleForumDot(this.fetchSettings("forumUpdateDot")),this.addTabModal.getElement().on("dialogopen",()=>{this.enableEditingMode()}),this.addTabModal.getElement().on("dialogclose",()=>{this.disableEditingMode()})}destroy(){this.isInitialized()&&(super.destroy(),this.$menu.removeClass("custom").empty(),this.$menu.sortable("destroy"),this.addTabButton.remove(),this.addTabModal.destroy(),this.updateTabModal.destroy(),this.$oldMenu.children().appendTo(this.$menu),this.$oldMenu.remove())}createConfigInterface(){this.addTabButton=DomUtilities_1.DomUtilities.addSettingsButton({id:"header-button-customizer",name:'<i class="fas fa-tasks"></i>',title:"Edit Header Tabs",tabClass:"float-left"});const newTabForm=new Form_1.Form({name:"header-customizer-new"},[Form_1.Form.input({label:"Name",name:"name",value:"",required:!0,pattern:"[\\S ]+"}),Form_1.Form.input({label:"Hover",value:"",name:"title"}),Form_1.Form.input({label:"Link",value:"",name:"href"}),Form_1.Form.checkbox({label:"Attach to the right side",value:!1,name:"right"}),Form_1.Form.button({value:"Submit",type:"submit"}),Form_1.Form.hr(),Form_1.Form.div({value:"Available variables:"}),Form_1.Form.copy({label:"Unique ID",value:"%userid%"}),Form_1.Form.copy({label:"Username",value:"%username%"}),Form_1.Form.hr(),Form_1.Form.div({value:"Drag-and-drop tabs to re-arrange.<br />Click on a tab to edit it."})],(values,form)=>{this.addTab({name:values.name,title:values.title,href:values.href,right:values.right}),form.reset(),this.reloadTabMargins()});this.addTabModal=new Modal_1.Modal({title:"Add Tab",triggers:[{element:this.addTabButton}],content:Form_1.Form.placeholder(),structure:newTabForm,position:{my:"right top",at:"right top"}}),this.updateTabForm=new Form_1.Form({name:"header-customizer-update"},[Form_1.Form.input({label:"Name",name:"name",value:"",required:!0,pattern:"[\\S ]+"}),Form_1.Form.input({label:"Hover",value:"",name:"title"}),Form_1.Form.input({label:"Link",value:"",name:"href"}),Form_1.Form.checkbox({label:"Attach to the right side",value:!1,name:"right"}),Form_1.Form.button({value:"Delete",type:"button"},()=>{this.deleteTab(this.updateTabModal.getActiveTrigger().parent()),this.updateTabModal.close()}),Form_1.Form.button({value:"Update",type:"submit"})],(values,form)=>{this.updateTab(this.updateTabModal.getActiveTrigger().parent(),{name:values.name,title:values.title,href:values.href,right:values.right}),this.updateTabModal.close(),form.reset(),this.reloadTabMargins()}),this.updateTabModal=new Modal_1.Modal({title:"Update Tab",triggers:[{element:$("menu.main li a")}],content:Form_1.Form.placeholder(),structure:this.updateTabForm,position:{my:"center top",at:"center top"},triggerMulti:!0,disabled:!0})}enableEditingMode(){this.$menu.attr("data-editing","true"),this.$menu.sortable("enable"),this.updateTabModal.enable(),this.updateTabModal.getElement().on("dialogopen",()=>{const $tab=this.updateTabModal.getActiveTrigger().parent(),$updateTabInputs=this.updateTabForm.getInputList();$updateTabInputs.get("name").val($tab.data("tab.name")),$updateTabInputs.get("title").val($tab.data("tab.title")),$updateTabInputs.get("href").val($tab.data("tab.href")),$updateTabInputs.get("right").prop("checked",$tab.data("tab.right"))})}disableEditingMode(){this.$menu.attr("data-editing","false"),this.$menu.sortable("disable"),this.updateTabModal.close(),this.updateTabModal.disable()}toggleForumDot(state){this.$menu.attr("data-forumdot",""+state)}createTabElement(config,triggerUpdate=!1){config=this.parseHeaderTabConfig(config);const $tab=$("<li>").data({"tab.name":config.name,"tab.title":config.title,"tab.href":config.href,"tab.right":config.right}).attr("align",config.right?"true":void 0).appendTo(this.$menu),$link=$("<a>").html(this.processTabVariables(config.name)).appendTo($tab);return""!==config.title&&$link.attr("title",this.processTabVariables(config.title)),""!==config.href&&$link.attr("href",this.processTabVariables(config.href)),"/forum_topics"===config.href&&this.hasForumUpdates&&$link.addClass("tab-has-updates"),triggerUpdate&&this.saveNavbarSettings(),""!==config.href.trim()&&Page_1.Page.getURL().pathname.includes(this.processTabVariables(config.href).split("?")[0])&&$tab.addClass("bg-foreground"),{tab:$tab,link:$link}}parseHeaderTabConfig(config){return void 0===config.name&&(config.name="New Tab"),void 0===config.href&&(config.href=""),void 0===config.title&&(config.title=""),void 0===config.right&&(config.right=!1),config}addTab(config){config=this.parseHeaderTabConfig(config);const newTab=this.createTabElement(config,!0);this.updateTabModal.registerTrigger({element:newTab.link})}updateTab($element,config){config=this.parseHeaderTabConfig(config),$element.data({"tab.name":config.name,"tab.title":config.title,"tab.href":config.href,"tab.right":config.right}).removeAttr("align").attr("align",config.right?"true":void 0),$element.find("a").first().html(this.processTabVariables(config.name)).attr("title",this.processTabVariables(config.title)).attr("href",this.processTabVariables(config.href)),this.saveNavbarSettings()}deleteTab($element){$element.remove(),this.saveNavbarSettings()}processTabVariables(text){return text.replace(/%userid%/g,User_1.User.getUserID()+"").replace(/%username%/g,User_1.User.getUsername())}async saveNavbarSettings(){const tabData=[];function formatVal(value){if(value)return value}this.$menu.find("li").each((function(i,element){const $tab=$(element);tabData.push({name:formatVal($tab.data("tab.name")),title:formatVal($tab.data("tab.title")),href:formatVal($tab.data("tab.href")),right:!!$tab.data("tab.right")||void 0})})),await this.pushSettings("tabs",tabData)}static openTabNum(num){const tabs=ModuleController_1.ModuleController.get(HeaderCustomizer).$menu.find("li > a");num>tabs.length||tabs[num].click()}reloadTabMargins(){this.$menu.children("li").removeClass("margined"),this.$menu.find("li[align=true]").first().addClass("margined")}}exports.HeaderCustomizer=HeaderCustomizer},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/data/Page":17,"../../components/data/User":22,"../../components/structure/DomUtilities":23,"../../components/structure/Form":24,"../../components/structure/Modal":25}],41:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Miscellaneous=void 0;const E621_1=require("../../components/api/E621"),XM_1=require("../../components/api/XM"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),ThumbnailsEnhancer_1=require("../search/ThumbnailsEnhancer");class Miscellaneous extends RE6Module_1.RE6Module{constructor(){super(),this.registerHotkeys({keys:"hotkeyNewComment",fnct:this.openNewComment},{keys:"hotkeyEditPost",fnct:this.openEditTab},{keys:"hotkeySubmit",fnct:this.handleSubmitForm,element:$("body"),selector:"textarea, input"})}getDefaultSettings(){return{enabled:!0,hotkeyNewComment:"n",hotkeyEditPost:"e",hotkeySubmit:"alt+return",stickySearchbox:!0,stickyHeader:!1,stickyEditBox:!0,avatarClick:!0,fixForumTitle:!0}}create(){if(super.create(),Page_1.Page.matches([Page_1.PageDefintion.post,Page_1.PageDefintion.forum])&&this.handleQuoteButton(),Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.post,Page_1.PageDefintion.favorites])&&this.createStickySearchbox(this.fetchSettings("stickySearchbox")),this.createStickyHeader(this.fetchSettings("stickyHeader")),Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.favorites])&&this.createStickyEditBox(this.fetchSettings("stickyEditBox")),this.handleAvatarClick(this.fetchSettings("avatarClick")),this.fetchSettings("fixForumTitle")&&Page_1.Page.matches(Page_1.PageDefintion.forum)){const title=/^(?:Forum - )(.+)(?: - (e621|e926))$/g.exec(document.title);title&&(document.title=`${title[1]} - Forum - ${title[2]}`)}Page_1.Page.matches(Page_1.PageDefintion.settings)&&this.modifyBlacklistForm(),DomUtilities_1.DomUtilities.addSettingsButton({id:"header-button-dmail",name:'<i class="fas fa-envelope"></i>',href:"/dmails",title:"DMail"})}openNewComment(){Page_1.Page.matches(Page_1.PageDefintion.post)?($("menu#post-sections > li > a[href$=comments]")[0].click(),$("a.expand-comment-response")[0].click()):Page_1.Page.matches(Page_1.PageDefintion.forum)&&$("a#new-response-link")[0].click()}openEditTab(){Page_1.Page.matches(Page_1.PageDefintion.post)&&window.setTimeout(()=>{$("#post-edit-link")[0].click()},100)}createStickySearchbox(state=!0){$("#re621-search").attr("data-sticky",state+"")}createStickyHeader(state=!0){$("body").attr("data-sticky-header",state+"")}createStickyEditBox(state=!0){$("body").attr("data-sticky-editbox",state+"")}handleQuoteButton(){Page_1.Page.matches(Page_1.PageDefintion.forum)?($(".forum-post-reply-link").each((function(index,element){const $newLink=$("<a>").attr("href","#").addClass("re621-forum-post-reply").html("Respond");$(element).after($newLink).remove()})),$(".re621-forum-post-reply").on("click",event=>{event.preventDefault();const $parent=$(event.target).parents("article.forum-post");this.quote($parent,"forum",$parent.data("forum-post-id"),$("#forum_post_body"),$("a#new-response-link"))})):Page_1.Page.matches(Page_1.PageDefintion.post)&&($(".comment-reply-link").each((function(index,element){const $newLink=$("<a>").attr("href","#").addClass("re621-comment-reply").html("Respond");$(element).after($newLink).remove()})),$(".re621-comment-reply").on("click",event=>{event.preventDefault();const $parent=$(event.target).parents("article.comment");this.quote($parent,"comment",$parent.data("comment-id"),$("#comment_body_for_"),$("a.expand-comment-response"))}))}async quote($parent,endpoint,id,$textarea,$responseButton){let strippedBody="";const selection=window.getSelection().toString();if(""===selection){strippedBody=("forum"===endpoint?await E621_1.E621.ForumPost.id(id).first():await E621_1.E621.Comment.id(id).first()).body.replace(/\[quote\](?:.|\n|\r)+?\[\/quote\][\n\r]*/gm,""),strippedBody='[quote]"'+$parent.data("creator")+'":/user/show/'+$parent.data("creator-id")+" said:\n"+strippedBody+"\n[/quote]"}else strippedBody='[quote]"'+$parent.data("creator")+'":/user/show/'+$parent.data("creator-id")+" said:\n"+selection+"\n[/quote]";($textarea.val()+"").length>0&&(strippedBody="\n\n"+strippedBody),$responseButton[0].click(),$textarea.scrollTop($textarea[0].scrollHeight);const newVal=$textarea.val()+strippedBody;$textarea.focus().val("").val(newVal)}handleAvatarClick(state=!0){if($("div.avatar > div.active > a").off("click.re621.thumbnail").off("dblclick.re621.thumbnail"),!state)return;const clickAction=ThumbnailsEnhancer_1.ThumbnailEnhancer.getClickAction(),avatars=$("div.avatar > div > a").get();for(const element of avatars){const $link=$(element);let dbclickTimer,prevent=!1;$link.on("click.re621.thumbnail",event=>{0!==event.button||event.shiftKey||event.ctrlKey||event.altKey||event.metaKey||(event.preventDefault(),dbclickTimer=window.setTimeout(()=>{prevent||($link.off("click.re621.thumbnail"),$link[0].click()),prevent=!1},200))}).on("dblclick.re621.thumbnail",event=>{0!==event.button||event.shiftKey||event.ctrlKey||event.altKey||event.metaKey||(event.preventDefault(),window.clearTimeout(dbclickTimer),prevent=!0,clickAction===ThumbnailsEnhancer_1.ThumbnailClickAction.NewTab?XM_1.XM.Util.openInTab(window.location.origin+$link.attr("href"),!1):($link.off("click.re621.thumbnail"),$link[0].click()))})}}handleSubmitForm(event){$(event.target).parents("form").submit()}modifyBlacklistForm(){const $textarea=$("textarea#user_blacklisted_tags"),$container=$("div.user_blacklisted_tags"),charCounter=$("<span>").addClass("char-counter").html(($textarea.val()+"").length+" / 50000");$("<div>").addClass("blacklist-character-counter-box").append(charCounter).appendTo($container),$textarea.keyup(()=>{charCounter.html(($textarea.val()+"").length+" / 50000")})}}exports.Miscellaneous=Miscellaneous},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/api/XM":7,"../../components/data/Page":17,"../../components/structure/DomUtilities":23,"../search/ThumbnailsEnhancer":58}],42:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SettingsController=void 0;const E621_1=require("../../components/api/E621"),XM_1=require("../../components/api/XM"),AvoidPosting_1=require("../../components/cache/AvoidPosting"),FavoriteCache_1=require("../../components/cache/FavoriteCache"),Hotkeys_1=require("../../components/data/Hotkeys"),User_1=require("../../components/data/User"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),Form_1=require("../../components/structure/Form"),Modal_1=require("../../components/structure/Modal"),Tabbed_1=require("../../components/structure/Tabbed"),Debug_1=require("../../components/utility/Debug"),Patcher_1=require("../../components/utility/Patcher"),Sync_1=require("../../components/utility/Sync"),Util_1=require("../../components/utility/Util"),FavDownloader_1=require("../downloader/FavDownloader"),MassDownloader_1=require("../downloader/MassDownloader"),PoolDownloader_1=require("../downloader/PoolDownloader"),SmartAlias_1=require("../misc/SmartAlias"),UploadUtilities_1=require("../misc/UploadUtilities"),DownloadCustomizer_1=require("../post/DownloadCustomizer"),ImageScaler_1=require("../post/ImageScaler"),PoolNavigator_1=require("../post/PoolNavigator"),PostViewer_1=require("../post/PostViewer"),TitleCustomizer_1=require("../post/TitleCustomizer"),BlacklistEnhancer_1=require("../search/BlacklistEnhancer"),CustomFlagger_1=require("../search/CustomFlagger"),InfiniteScroll_1=require("../search/InfiniteScroll"),SearchUtilities_1=require("../search/SearchUtilities"),ThumbnailsEnhancer_1=require("../search/ThumbnailsEnhancer"),ForumTracker_1=require("../subscriptions/ForumTracker"),PoolTracker_1=require("../subscriptions/PoolTracker"),SubscriptionManager_1=require("../subscriptions/SubscriptionManager"),HeaderCustomizer_1=require("./HeaderCustomizer"),Miscellaneous_1=require("./Miscellaneous");class SettingsController extends RE6Module_1.RE6Module{constructor(){super(),this.registerHotkeys({keys:"hotkeyOpenSettings",fnct:this.openSettings})}getDefaultSettings(){return{enabled:!0,hotkeyOpenSettings:"",newVersionAvailable:!1,changelog:""}}create(){this.openSettingsButton=DomUtilities_1.DomUtilities.addSettingsButton({id:"header-button-settings",name:'<i class="fas fa-wrench"></i>',title:"Settings",tabClass:"float-right",attr:{"data-loading":"false","data-updates":"0"},linkClass:"update-notification"});const $settings=new Tabbed_1.Tabbed({name:"settings-tabs",content:[{name:"General",structure:this.createGeneralTab()},{name:"Downloads",structure:this.createDownloadsTab()},{name:"Custom Flags",structure:this.createFlagsTab()},{name:"Smart Alias",structure:this.createUploadsTab()},{name:"Hotkeys",structure:this.createHotkeysTab()},{name:"Features",structure:this.createFeaturesTab()},{name:this.utilTabButton=$("<a>").attr({"data-loading":"false","data-updates":"0",id:"conf-tab-util"}).addClass("update-notification").html("Utilities"),structure:this.createMiscTab()},{name:"About",structure:this.createAboutTab()}]});if(new Modal_1.Modal({title:"Settings",triggers:[{element:this.openSettingsButton}],escapable:!1,fixed:!0,reserveHeight:!0,content:Form_1.Form.placeholder(3),structure:$settings,position:{my:"center",at:"center"}}),Sync_1.Sync.infoUpdate+Util_1.Util.Time.HOUR<Util_1.Util.Time.now()){const releases={latest:null,current:null};async function getGithubData(node){return XM_1.XM.Connect.xmlHttpPromise({url:"https://api.github.com/repos/re621/re621/releases/"+node,method:"GET"}).then(response=>Promise.resolve(JSON.parse(response.responseText)),()=>{throw Error("Failed to fetch Github release data")})}(async()=>{releases.latest=await getGithubData("latest"),releases.current=await getGithubData("tags/"+window.re621.version),await this.pushSettings("newVersionAvailable",releases.latest.name!==releases.current.name),await this.pushSettings("changelog",releases.current.body),Sync_1.Sync.infoUpdate=Util_1.Util.Time.now(),await Sync_1.Sync.saveSettings(),$("#changelog-list").html(Util_1.Util.quickParseMarkdown(releases.current.body)),$("#project-update-button").attr("data-available",(releases.latest.name!==releases.current.name)+"")})()}}pushNotificationsCount(count=0){this.openSettingsButton.attr("data-updates",(parseInt(this.openSettingsButton.attr("data-updates"))||0)+count),this.utilTabButton.attr("data-updates",(parseInt(this.utilTabButton.attr("data-updates"))||0)+count)}createGeneralTab(){const titleCustomizer=ModuleController_1.ModuleController.get(TitleCustomizer_1.TitleCustomizer),miscellaneous=ModuleController_1.ModuleController.get(Miscellaneous_1.Miscellaneous),postViewer=ModuleController_1.ModuleController.get(PostViewer_1.PostViewer),blacklistEnhancer=ModuleController_1.ModuleController.get(BlacklistEnhancer_1.BlacklistEnhancer),imageScaler=ModuleController_1.ModuleController.get(ImageScaler_1.ImageScaler),infiniteScroll=ModuleController_1.ModuleController.get(InfiniteScroll_1.InfiniteScroll),thumbnailEnhancer=ModuleController_1.ModuleController.get(ThumbnailsEnhancer_1.ThumbnailEnhancer),headerCustomizer=ModuleController_1.ModuleController.get(HeaderCustomizer_1.HeaderCustomizer),searchUtilities=ModuleController_1.ModuleController.get(SearchUtilities_1.SearchUtilities);return new Form_1.Form({name:"optgeneral",columns:3,width:3},[Form_1.Form.accordion({name:"gencollapse",columns:3,width:3,active:0},[Form_1.Form.accordionTab({name:"layout",label:"Layout",columns:3,width:3},[Form_1.Form.div({value:"<b>Main Page</b><br />Reroute the title page to the one specified",width:2}),Form_1.Form.select({value:Util_1.Util.LS.getItem("re621.mainpage")||"default"},{default:"Default",posts:"Posts",forum_topics:"Forums",blips:"Blips"},value=>{Util_1.Util.LS.setItem("re621.mainpage",value)}),Form_1.Form.spacer(3,!0),Form_1.Form.input({name:"template",value:titleCustomizer.fetchSettings("template"),label:"<b>Page Title</b>",width:3},async data=>{await titleCustomizer.pushSettings("template",data),titleCustomizer.isInitialized()&&titleCustomizer.refreshPageTitle()}),Form_1.Form.section({columns:3,width:3},[Form_1.Form.div({value:'<div class="notice unmargin">The following variables can be used:</div>',width:3}),Form_1.Form.copy({value:"%postid%",label:"Post ID"}),Form_1.Form.copy({value:"%artist%",label:"Artist"}),Form_1.Form.copy({value:"%copyright%",label:"Copyright"}),Form_1.Form.copy({value:"%character%",label:"Characters"}),Form_1.Form.copy({value:"%species%",label:"Species"}),Form_1.Form.copy({value:"%meta%",label:"Meta"})]),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:titleCustomizer.fetchSettings("symbolsEnabled"),label:"<b>Title Icons</b>",width:3},async data=>{await titleCustomizer.pushSettings("symbolsEnabled",data),titleCustomizer.isInitialized()&&titleCustomizer.refreshPageTitle()}),Form_1.Form.input({value:titleCustomizer.fetchSettings("symbolFav"),label:"Favorite"},async data=>{await titleCustomizer.pushSettings("symbolFav",data),titleCustomizer.isInitialized()&&titleCustomizer.refreshPageTitle()}),Form_1.Form.input({value:titleCustomizer.fetchSettings("symbolVoteUp"),label:"Upvoted"},async data=>{await titleCustomizer.pushSettings("symbolVoteUp",data),titleCustomizer.isInitialized()&&titleCustomizer.refreshPageTitle()}),Form_1.Form.input({value:titleCustomizer.fetchSettings("symbolVoteDown"),label:"Downvoted"},async data=>{await titleCustomizer.pushSettings("symbolVoteDown",data),titleCustomizer.isInitialized()&&titleCustomizer.refreshPageTitle()}),Form_1.Form.hr(3),Form_1.Form.checkbox({value:searchUtilities.fetchSettings("improveTagCount"),label:"<b>Expanded Tag Count</b><br />Replace the rounded tag count in the sidebar with the precise one",width:3},async data=>{await searchUtilities.pushSettings("improveTagCount",data),searchUtilities.isInitialized()&&searchUtilities.improveTagCount(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:searchUtilities.fetchSettings("shortenTagNames"),label:"<b>Shorten Tag Names</b><br />Cut off long tag names to make them fit on one line",width:3},async data=>{await searchUtilities.pushSettings("shortenTagNames",data),searchUtilities.isInitialized()&&searchUtilities.shortenTagNames(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:searchUtilities.fetchSettings("hidePlusMinusIcons"),label:"<b>Hide + and - Icons</b><br />Remove these icons from view",width:3},async data=>{await searchUtilities.pushSettings("hidePlusMinusIcons",data),searchUtilities.isInitialized()&&searchUtilities.hidePlusMinusIcons(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:miscellaneous.fetchSettings("stickyHeader"),label:"<b>Fixed Header</b><br />Make the page header stick to the top when scrolling",width:3},async data=>{await miscellaneous.pushSettings("stickyHeader",data),miscellaneous.createStickyHeader(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:miscellaneous.fetchSettings("stickySearchbox"),label:"<b>Fixed Searchbox</b><br />Make the searchbox remain visible when scrolling",width:3},async data=>{await miscellaneous.pushSettings("stickySearchbox",data),miscellaneous.createStickySearchbox(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:miscellaneous.fetchSettings("stickyEditBox"),label:"<b>Fixed Edit Form</b><br />Make the quick tags form stick to the top when scrolling",width:3},async data=>{await miscellaneous.pushSettings("stickyEditBox",data),miscellaneous.createStickyEditBox(data)})]),Form_1.Form.accordionTab({name:"thumb",label:"Thumbnails",columns:3,width:3},[Form_1.Form.subheader("Hi-Res Thumbnails","Replace 150x150 thumbnails with high-resolution ones",2),Form_1.Form.select({value:thumbnailEnhancer.fetchSettings("upscale")},{disabled:"Disabled",hover:"On Hover",always:"Always"},async data=>{await thumbnailEnhancer.pushSettings("upscale",data);const zoomDisabled=data===ThumbnailsEnhancer_1.ThumbnailPerformanceMode.Disabled;$("#optgeneral-gencollapse-thumb-scalingconf-hoverzoom-desc").toggleClass("input-disabled",zoomDisabled),$("#optgeneral-gencollapse-thumb-scalingconf-hoverzoom").prop("disabled",zoomDisabled).parent().toggleClass("input-disabled",zoomDisabled)}),Form_1.Form.spacer(2),Form_1.Form.text('<div class="unmargin text-center text-bold">Requires a page reload</div>'),Form_1.Form.subheader("Double-Click Action","Action taken when a thumbnail is double-clicked",2),Form_1.Form.select({value:thumbnailEnhancer.fetchSettings("clickAction")},{disabled:"Disabled",newtab:"Open New Tab",copyid:"Copy Post ID",blacklist:"Add to Blacklist",addtoset:"Add to Current Set ",toggleset:"Toggle Current Set "},async data=>{await ThumbnailsEnhancer_1.ThumbnailEnhancer.setClickAction(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:thumbnailEnhancer.fetchSettings("preserveHoverText"),label:"<b>Preserve Hover Text</b><br />Restores text displayed when hovering over the thumbnail",width:2},async data=>{await thumbnailEnhancer.pushSettings("preserveHoverText",data)}),Form_1.Form.text('<div class="text-center text-bold">Requires a page reload</div>',1,"align-middle"),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:thumbnailEnhancer.fetchSettings("crop"),label:"<b>Thumbnail Rescaling</b><br />Resize thumbnail images according to settings below",width:3},async data=>{await thumbnailEnhancer.pushSettings("crop",data),thumbnailEnhancer.isInitialized()&&thumbnailEnhancer.toggleThumbCrop(data)}),Form_1.Form.collapse({name:"scalingconf",columns:3,width:3,title:"Scaling Options",collapsed:!0},[Form_1.Form.subheader("Thumbnail Size","Thumbnail width, in px, em, or rem",2),Form_1.Form.input({value:thumbnailEnhancer.fetchSettings("cropSize"),pattern:"^\\d{2,3}(px|rem|em)$"},async(data,input)=>{input.get()[0].checkValidity()&&(await thumbnailEnhancer.pushSettings("cropSize",data),thumbnailEnhancer.isInitialized()&&thumbnailEnhancer.setThumbSize(data))}),Form_1.Form.spacer(3),Form_1.Form.checkbox({name:"croppreserveratio",value:thumbnailEnhancer.fetchSettings("cropPreserveRatio"),label:"<b>Preserve Ratio</b><br />Keep the image ratio of the original image",width:3},async data=>{await thumbnailEnhancer.pushSettings("cropPreserveRatio",data),thumbnailEnhancer.isInitialized()&&thumbnailEnhancer.toggleThumbPreserveRatio(data),$("#optgeneral-gencollapse-thumb-scalingconf-cropratio-desc").toggleClass("input-disabled",data),$("#optgeneral-gencollapse-thumb-scalingconf-cropratio").prop("disabled",data).parent().toggleClass("input-disabled",data)}),Form_1.Form.spacer(3),Form_1.Form.subheader("Image Ratio","Height to width ratio of the image",2,"cropratio-desc",thumbnailEnhancer.fetchSettings("cropPreserveRatio")?"input-disabled":void 0),Form_1.Form.input({name:"cropratio",value:thumbnailEnhancer.fetchSettings("cropRatio"),pattern:"^(([01](\\.\\d+)?)|2)$",wrapper:thumbnailEnhancer.fetchSettings("cropPreserveRatio")?"input-disabled":void 0,disabled:thumbnailEnhancer.fetchSettings("cropPreserveRatio")},async(data,input)=>{input.get()[0].checkValidity()&&(await thumbnailEnhancer.pushSettings("cropRatio",data),thumbnailEnhancer.isInitialized()&&thumbnailEnhancer.setThumbRatio(data))}),Form_1.Form.hr(3),Form_1.Form.subheader("Zoom on Hover","Increases the size of the thumbnail when hovering over it",2,"hoverzoom-desc",thumbnailEnhancer.fetchSettings("upscale")===ThumbnailsEnhancer_1.ThumbnailPerformanceMode.Disabled?"input-disabled":void 0),Form_1.Form.select({name:"hoverzoom",value:thumbnailEnhancer.fetchSettings("zoom"),wrapper:thumbnailEnhancer.fetchSettings("upscale")===ThumbnailsEnhancer_1.ThumbnailPerformanceMode.Disabled?"input-disabled":void 0,disabled:thumbnailEnhancer.fetchSettings("upscale")===ThumbnailsEnhancer_1.ThumbnailPerformanceMode.Disabled},{true:"Enabled",false:"Disabled",onshift:"Holding Shift"},async data=>{await thumbnailEnhancer.pushSettings("zoom",data),thumbnailEnhancer.isInitialized()&&thumbnailEnhancer.toggleHoverZoom(data)}),Form_1.Form.spacer(3),Form_1.Form.subheader("Zoom scale","The ratio of the enlarged thumbnail to its original size",2),Form_1.Form.input({value:thumbnailEnhancer.fetchSettings("zoomScale"),pattern:"^[1-9](\\.\\d+)?$"},async(data,input)=>{input.get()[0].checkValidity()&&(await thumbnailEnhancer.pushSettings("zoomScale",data),thumbnailEnhancer.isInitialized()&&thumbnailEnhancer.setZoomScale(data))}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:thumbnailEnhancer.fetchSettings("zoomContextual"),label:"<b>Contextual Zoom</b><br />Only enable thumbnail zoom in the viewing mode",width:3},async data=>{await thumbnailEnhancer.pushSettings("zoomContextual",data),thumbnailEnhancer.isInitialized()&&thumbnailEnhancer.toggleZoomContextual(data)}),Form_1.Form.spacer(3)]),Form_1.Form.checkbox({value:thumbnailEnhancer.fetchSettings("autoPlayGIFs"),label:"<b>Auto-Play GIFs</b><br />If disabled, animated GIFs will only play on hover",width:2},async data=>{await thumbnailEnhancer.pushSettings("autoPlayGIFs",data),thumbnailEnhancer.isInitialized()&&ThumbnailsEnhancer_1.ThumbnailEnhancer.setAutoPlayGIFs(data)}),Form_1.Form.text('<div class="text-center text-bold">Requires a page reload</div>',1,"align-middle"),Form_1.Form.spacer(3),Form_1.Form.checkbox({name:"votebutton",value:thumbnailEnhancer.fetchSettings("vote"),label:"<b>Voting Buttons</b><br />Adds voting buttons when hovering over a thumbnail",width:3},async data=>{await thumbnailEnhancer.pushSettings("vote",data),thumbnailEnhancer.isInitialized()&&thumbnailEnhancer.toggleHoverVote(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({name:"favbutton",value:thumbnailEnhancer.fetchSettings("fav"),label:"<b>Favorite Button</b><br />Adds a +favorite button when hovering over a thumbnail",width:3},async data=>{await thumbnailEnhancer.pushSettings("fav",data),thumbnailEnhancer.isInitialized()&&thumbnailEnhancer.toggleHoverFav(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:thumbnailEnhancer.fetchSettings("ribbons"),label:"<b>Status Ribbons</b><br />Use corner ribbons instead of colored borders for flags",width:3},async data=>{await thumbnailEnhancer.pushSettings("ribbons",data),thumbnailEnhancer.isInitialized()&&thumbnailEnhancer.toggleStatusRibbons(data),$("input#optgeneral-gencollapse-thumb-relations-ribbons").prop("disabled",!data).parent().toggleClass("input-disabled",!data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({name:"relations-ribbons",value:thumbnailEnhancer.fetchSettings("relRibbons"),label:"<b>Relations Ribbons</b><br />Display ribbons for parent/child relationships",width:3,wrapper:thumbnailEnhancer.fetchSettings("ribbons")?void 0:"input-disabled",disabled:!thumbnailEnhancer.fetchSettings("ribbons")},async data=>{await thumbnailEnhancer.pushSettings("relRibbons",data),thumbnailEnhancer.isInitialized()&&thumbnailEnhancer.toggleRelationRibbons(data)})]),Form_1.Form.accordionTab({name:"misc",label:"Other",columns:3,width:3},[Form_1.Form.checkbox({value:infiniteScroll.fetchSettings("keepHistory"),label:"<b>Preserve Scroll History</b><br />Load all result pages up to the current one (Infinite Scroll)",width:2},async data=>{await infiniteScroll.pushSettings("keepHistory",data)}),Form_1.Form.text('<div class="text-center text-bold">Requires a page reload</div>',1,"align-middle"),Form_1.Form.hr(3),Form_1.Form.text("<b>Persistent Tags</b>"),Form_1.Form.input({value:searchUtilities.fetchSettings("persistentTags"),width:2},async data=>{await searchUtilities.pushSettings("persistentTags",data)}),Form_1.Form.text("Tags added to every search, used to emulate server-side blacklisting",2),Form_1.Form.text('<div class="text-center text-bold">Requires a page reload</div>',1,"align-middle"),Form_1.Form.hr(3),Form_1.Form.checkbox({value:postViewer.fetchSettings("upvoteOnFavorite"),label:"<b>Auto-Upvote Favorites</b><br />Automatically upvote a post when adding it to the favorites",width:3},async data=>{await postViewer.pushSettings("upvoteOnFavorite",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:imageScaler.fetchSettings("clickScale"),label:"<b>Quick Rescale</b><br />Click on a post image to cycle through scaling options",width:3},async data=>{await imageScaler.pushSettings("clickScale",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:searchUtilities.fetchSettings("collapseCategories"),label:"<b>Remember Collapsed Tag Categories</b><br />Preserve the minimized state of the tag categories in the sidebar",width:3},async data=>{await searchUtilities.pushSettings("collapseCategories",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:blacklistEnhancer.fetchSettings("quickaddTags"),label:"<b>Quick Blacklist</b><br />Click X next to the tag in the sidebar to add it to the blacklist",width:3},async data=>{await blacklistEnhancer.pushSettings("quickaddTags",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:headerCustomizer.fetchSettings("forumUpdateDot"),label:"<b>Forum Notifications</b><br />Red dot on the Forum tab in the header if there are new posts",width:3},async data=>{headerCustomizer.toggleForumDot(data),await headerCustomizer.pushSettings("forumUpdateDot",data)}),Form_1.Form.spacer(3)])])])}createDownloadsTab(){const downloadCustomizer=ModuleController_1.ModuleController.get(DownloadCustomizer_1.DownloadCustomizer),massDownloader=ModuleController_1.ModuleController.get(MassDownloader_1.MassDownloader),poolDownloader=ModuleController_1.ModuleController.get(PoolDownloader_1.PoolDownloader),favDownloader=ModuleController_1.ModuleController.get(FavDownloader_1.FavDownloader);return new Form_1.Form({name:"optdownload",columns:3,width:3},[Form_1.Form.section({name:"customizer",columns:3,width:3},[Form_1.Form.header("Download Customizer"),Form_1.Form.div({value:'<div class="notice float-right">Download individual files</div>',width:2}),Form_1.Form.text("<b>File name</b>"),Form_1.Form.input({value:downloadCustomizer.fetchSettings("template"),width:2},async data=>{await downloadCustomizer.pushSettings("template",data),downloadCustomizer.isInitialized()&&downloadCustomizer.refreshDownloadLink()}),Form_1.Form.section({columns:3,width:3},[Form_1.Form.div({value:'<div class="notice unmargin">The following variables can be used:</div>',width:3}),Form_1.Form.copy({value:"%postid%",label:"Post ID"}),Form_1.Form.copy({value:"%artist%",label:"Artist"}),Form_1.Form.copy({value:"%copyright%",label:"Copyright"}),Form_1.Form.copy({value:"%character%",label:"Characters"}),Form_1.Form.copy({value:"%species%",label:"Species"}),Form_1.Form.copy({value:"%meta%",label:"Meta"}),Form_1.Form.copy({value:"%md5%",label:"MD5"})])]),Form_1.Form.spacer(3),Form_1.Form.accordion({name:"downcollapse",columns:3,width:3,active:0},[Form_1.Form.accordionTab({name:"mass",label:"Mass Downloader",subheader:"Download files from the search page",columns:3,width:3},[Form_1.Form.text("<b>Archive name</b>"),Form_1.Form.input({value:massDownloader.fetchSettings("template"),width:2},async data=>{await massDownloader.pushSettings("template",data)}),Form_1.Form.div({value:'<div class="notice unmargin">The same variables as above can be used. Add a forward slash ( / ) to signify a folder.</div>',width:3}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:massDownloader.fetchSettings("autoDownloadArchive"),label:"<b>Auto Download</b><br />The archive will be downloaded automatically after being created",width:3},async data=>{await massDownloader.pushSettings("autoDownloadArchive",data)}),Form_1.Form.checkbox({value:massDownloader.fetchSettings("fixedSection"),label:"<b>Fixed Interface</b><br />The downloader interface will remain on the screen as you scroll",width:3},async data=>{await massDownloader.pushSettings("fixedSection",data),massDownloader.toggleFixedSection()})]),Form_1.Form.accordionTab({name:"fav",label:"Favorites Downloader",subheader:"Download all favorites at once",columns:3,width:3},[Form_1.Form.text("<b>Archive name</b>"),Form_1.Form.input({value:favDownloader.fetchSettings("template"),width:2},async data=>{await favDownloader.pushSettings("template",data)}),Form_1.Form.div({value:'<div class="notice unmargin">The same variables as above can be used. Add a forward slash ( / ) to signify a folder.</div>',width:3}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:favDownloader.fetchSettings("autoDownloadArchive"),label:"<b>Auto Download</b><br />The archive will be downloaded automatically after being created",width:3},async data=>{await favDownloader.pushSettings("autoDownloadArchive",data)}),Form_1.Form.checkbox({value:favDownloader.fetchSettings("fixedSection"),label:"<b>Fixed Interface</b><br />The downloader interface will remain on the screen as you scroll",width:3},async data=>{await favDownloader.pushSettings("fixedSection",data),favDownloader.toggleFixedSection()})]),Form_1.Form.accordionTab({name:"pool",label:"Pool Downloader",subheader:"Download image pools or sets",columns:3,width:3},[Form_1.Form.text("<b>Archive name</b>"),Form_1.Form.input({value:poolDownloader.fetchSettings("template"),width:2},async data=>{await poolDownloader.pushSettings("template",data)}),Form_1.Form.section({name:"template-vars-pool",columns:3,width:3},[Form_1.Form.div({value:'<div class="notice unmargin">The same variables as above can be used. Add a forward slash ( / ) to signify a folder.</div>',width:3}),Form_1.Form.div({value:'<div class="notice unmargin">The following variables can also be used:</div>',width:3}),Form_1.Form.copy({value:"%pool%",label:"Pool Name"}),Form_1.Form.copy({value:"%index%",label:"Index"})]),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:poolDownloader.fetchSettings("autoDownloadArchive"),label:"<b>Auto Download</b><br />The archive will be downloaded automatically after being created",width:3},async data=>{await poolDownloader.pushSettings("autoDownloadArchive",data)})])])])}createFlagsTab(){const customFlagger=ModuleController_1.ModuleController.get(CustomFlagger_1.CustomFlagger),defsContainer=$("<div>").attr("id","flag-defs-container");return customFlagger.fetchSettings("flags").forEach(flag=>{makeDefInput(flag).appendTo(defsContainer)}),new Form_1.Form({name:"optflags",columns:3,width:3},[Form_1.Form.header("Flag Definitions",2),Form_1.Form.button({value:"New Flag"},async()=>{makeDefInput({name:"",color:"#"+Math.floor(16777215*Math.random()).toString(16),tags:""}).appendTo(defsContainer)}),Form_1.Form.div({value:defsContainer,width:3}),Form_1.Form.button({value:"Save"},async()=>{const confirmBox=$("span#defs-confirm").html("Saving . . ."),defData=[],defInputs=$(defsContainer).find("div.flag-defs-inputs").get();for(const inputContainer of defInputs){const inputs=$(inputContainer).find("input").get(),name=$(inputs[0]),color=$(inputs[1]),tags=$(inputs[2]);0==name.val().length&&name.val("FLAG"),color.val().match(/^#(?:[0-9a-f]{3}){1,2}$/i)||color.val("#800000"),0!=tags.val().length&&defData.push({name:name.val(),color:color.val(),tags:tags.val()})}await customFlagger.pushSettings("flags",defData),confirmBox.html("Settings Saved"),window.setTimeout(()=>{confirmBox.html("")},1e3)}),Form_1.Form.div({value:'<span id="defs-confirm"></span>'}),Form_1.Form.div({value:"\n                <b>Custom Flags</b> allow you to automatically highlight posts that match specified tags. For example:<br />\n                <pre>-solo -duo -group -zero_pictured</pre>: posts that do not include character count tags.<br />\n                <pre>tagcount:&lt;5</pre>: posts with less than 5 tags<br />\n                Flag names must be unique. Duplicate tag strings are allowed, but their corresponding flag may not display.",width:3})]);function makeDefInput(flag){const flagContainer=$("<div>").addClass("flag-defs-inputs");return $("<input>").attr({type:"text",placeholder:"name"}).val(void 0===flag?"":flag.name).appendTo(flagContainer),$("<input>").attr({type:"text",placeholder:"color"}).val(void 0===flag?"":flag.color).css("border-left-color",void 0===flag?"transparent":flag.color).appendTo(flagContainer).keyup(event=>{const $target=$(event.target);($target.val()+"").match(/^#(?:[0-9a-f]{3}){1,2}$/i)&&$target.css("border-left-color",$target.val()+"")}),$("<input>").attr({type:"text",placeholder:"tags"}).val(void 0===flag?"":flag.tags).appendTo(flagContainer),$("<button>").html('<i class="far fa-trash-alt"></i>').appendTo(flagContainer).click(()=>{flagContainer.remove()}),flagContainer}}createUploadsTab(){const smartAlias=ModuleController_1.ModuleController.get(SmartAlias_1.SmartAlias),uploadUtilities=ModuleController_1.ModuleController.get(UploadUtilities_1.UploadUtilities),aliasContainer=$("<textarea>").attr("id","alias-list-container").val(smartAlias.fetchSettings("data"));return new Form_1.Form({name:"optalias",columns:3,width:3},[Form_1.Form.accordion({name:"aliascollapse",columns:3,width:3,active:0},[Form_1.Form.accordionTab({name:"validatior",label:"Validation Configuration",columns:3,width:3},[Form_1.Form.checkbox({value:uploadUtilities.fetchSettings("checkDuplicates"),label:"<b>Check Duplicates</b><br />Search for visually similar images on e621 when uploading",width:2},async data=>{await uploadUtilities.pushSettings("checkDuplicates",data)}),Form_1.Form.text('<div class="text-center text-bold">Requires a page reload</div>'),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:uploadUtilities.fetchSettings("addSourceLinks"),label:"<b>Source Link Buttons</b><br />Add utility buttons to the upload source inputs",width:2},async data=>{await uploadUtilities.pushSettings("addSourceLinks",data)}),Form_1.Form.text('<div class="text-center text-bold">Requires a page reload</div>'),Form_1.Form.hr(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("autoLoad"),label:"<b>Run Automatically</b><br />Either validate tag input as you type, or by pressing a button",width:3},async data=>{await smartAlias.pushSettings("autoLoad",data),await smartAlias.reload()}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("replaceAliasedTags"),label:"<b>Replace Aliases</b><br />Automatically replace aliased tag names with their consequent version",width:3},data=>{smartAlias.pushSettings("replaceAliasedTags",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("fixCommonTypos"),label:"<b>Fix Common Typos</b><br />Correct several common typos in the tag fields",width:3},data=>{smartAlias.pushSettings("fixCommonTypos",data)}),Form_1.Form.spacer(3),Form_1.Form.subheader("Tag Display Order","How the tags should be arranged in the display box",2),Form_1.Form.select({value:smartAlias.fetchSettings("tagOrder")},{default:"Original",alphabetical:"Alphabetical",grouped:"Grouped by Category"},data=>{smartAlias.pushSettings("tagOrder",data)}),Form_1.Form.spacer(3),Form_1.Form.subheader("Minimum Posts Warning","Highlight tags that have less than the specified number of posts",2),Form_1.Form.input({value:smartAlias.fetchSettings("minPostsWarning"),width:1,pattern:"\\d+"},(data,input)=>{input.get()[0].checkValidity()&&smartAlias.pushSettings("minPostsWarning",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("compactOutput"),label:"<b>Compact Display</b><br />Limit the tag information section to a set height",width:3},async data=>{await smartAlias.pushSettings("compactOutput",data),smartAlias.setCompactOutput(data)})]),Form_1.Form.accordionTab({name:"aliasref",label:"Validated Inputs",columns:3,width:3},[Form_1.Form.checkbox({value:smartAlias.fetchSettings("quickTagsForm"),label:"<b>Quick Tags</b><br />SmartAlias validation on the search page editing mode form",width:3},async data=>{await smartAlias.pushSettings("quickTagsForm",data),await smartAlias.reload()}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("editTagsForm"),label:"<b>Post Editing</b><br />SmartAlias validation on the individual post editing form",width:3},async data=>{await smartAlias.pushSettings("editTagsForm",data),await smartAlias.reload()}),Form_1.Form.hr(3),Form_1.Form.header("Upload Page"),Form_1.Form.checkbox({value:smartAlias.fetchSettings("uploadCharactersForm"),label:"<b>Artist Tags</b>",width:3},async data=>{await smartAlias.pushSettings("uploadCharactersForm",data),await smartAlias.reload()}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("uploadSexesForm"),label:"<b>Characters</b>",width:3},async data=>{await smartAlias.pushSettings("uploadSexesForm",data),await smartAlias.reload()}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("uploadBodyTypesForm"),label:"<b>Species</b>",width:3},async data=>{await smartAlias.pushSettings("uploadBodyTypesForm",data),await smartAlias.reload()}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("uploadThemesForm"),label:"<b>Themes</b>",width:3},async data=>{await smartAlias.pushSettings("uploadThemesForm",data),await smartAlias.reload()}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:smartAlias.fetchSettings("uploadTagsForm"),label:"<b>Other Tags</b>",width:3},async data=>{await smartAlias.pushSettings("uploadTagsForm",data),await smartAlias.reload()}),Form_1.Form.spacer(3)]),Form_1.Form.accordionTab({name:"aliasdef",label:"Alias Definitions",columns:3,width:3},[Form_1.Form.div({value:aliasContainer,width:3}),Form_1.Form.button({value:"Save"},async()=>{const confirmBox=$("span#defs-confirm").html("Saving . . .");await smartAlias.pushSettings("data",$("#alias-list-container").val().toString().trim()),confirmBox.html("Settings Saved"),window.setTimeout(()=>{confirmBox.html("")},1e3)}),Form_1.Form.div({value:'<span id="defs-confirm"></span>'}),Form_1.Form.div({value:'<div class="float-right">[ <a href="https://github.com/re621/re621/wiki/SmartAlias">syntax help</a> ]</div>'})])])])}createHotkeysTab(){const postViewer=ModuleController_1.ModuleController.get(PostViewer_1.PostViewer),poolNavigator=ModuleController_1.ModuleController.get(PoolNavigator_1.PoolNavigator),imageScaler=ModuleController_1.ModuleController.get(ImageScaler_1.ImageScaler),miscellaneous=ModuleController_1.ModuleController.get(Miscellaneous_1.Miscellaneous),headerCustomizer=ModuleController_1.ModuleController.get(HeaderCustomizer_1.HeaderCustomizer),subscriptionManager=ModuleController_1.ModuleController.get(SubscriptionManager_1.SubscriptionManager),searchUtilities=ModuleController_1.ModuleController.get(SearchUtilities_1.SearchUtilities);function createInputs(module,label,settingsKey){const values=module.fetchSettings(settingsKey).split("|"),bindings=[void 0===values[0]?"":values[0],void 0===values[1]?"":values[1]];return[Form_1.Form.div({value:label}),Form_1.Form.key({value:bindings[0]},async data=>{await handleRebinding(data,0)}),Form_1.Form.key({value:bindings[1]},async data=>{await handleRebinding(data,1)})];async function handleRebinding(data,index){bindings[index]=data[0],await module.pushSettings(settingsKey,bindings.join("|")),Hotkeys_1.Hotkeys.unregister(data[1]),await module.resetHotkeys()}}function createCustomInputs(module,label,dataLabel,settingsKey,pattern){const values=module.fetchSettings(settingsKey).split("|"),dataVal=module.fetchSettings(settingsKey+"_data"),bindings=[void 0===values[0]?"":values[0],void 0===values[1]?"":values[1]];return[Form_1.Form.div({value:label}),Form_1.Form.key({value:bindings[0]},async data=>{await async function(data,index){bindings[index]=data[0],await module.pushSettings(settingsKey,bindings.join("|")),Hotkeys_1.Hotkeys.unregister(data[1]),await module.resetHotkeys()}(data,0)}),Form_1.Form.input({value:dataVal,label:dataLabel,pattern:pattern},async(data,input)=>{input.get()[0].checkValidity()&&await module.pushSettings(settingsKey+"_data",data)})]}return new Form_1.Form({name:"opthotkeys",columns:3,width:3},[Form_1.Form.header("Listing",3),...createInputs(searchUtilities,"Search","hotkeyFocusSearch"),...createInputs(searchUtilities,"Random Post","hotkeyRandomPost"),Form_1.Form.hr(3),Form_1.Form.header("Posts",3),...createInputs(postViewer,"Upvote","hotkeyUpvote"),...createInputs(postViewer,"Downvote","hotkeyDownvote"),...createInputs(postViewer,"Toggle Favorite","hotkeyFavorite"),...createInputs(postViewer,"Add to Favorites","hotkeyAddFavorite"),...createInputs(postViewer,"Remove From Favorites","hotkeyRemoveFavorite"),...createInputs(imageScaler,"Fullscreen Mode","hotkeyFullscreen"),Form_1.Form.spacer(3,!0),...createInputs(poolNavigator,"Previous Post","hotkeyPrev"),...createInputs(poolNavigator,"Next Post","hotkeyNext"),...createInputs(poolNavigator,"Cycle Navigation","hotkeyCycle"),...createInputs(imageScaler,"Change Scale","hotkeyScale"),Form_1.Form.spacer(3,!0),...createInputs(postViewer,"Open `Add to Set` Dialog","hotkeyAddSet"),...createInputs(postViewer,"Open `Add to Pool` Dialog","hotkeyAddPool"),...createInputs(postViewer,"Toggle Current Set","hotkeyToggleSetLatest"),...createInputs(postViewer,"Add to Current Set","hotkeyAddSetLatest"),...createInputs(postViewer,"Remove from Current Set","hotkeyRemoveSetLatest"),Form_1.Form.spacer(3,!0),...createCustomInputs(postViewer,"Add to Set","Set ID","hotkeyAddSetCustom1","\\d+"),...createCustomInputs(postViewer,"Add to Set","Set ID","hotkeyAddSetCustom2","\\d+"),...createCustomInputs(postViewer,"Add to Set","Set ID","hotkeyAddSetCustom3","\\d+"),Form_1.Form.hr(3),Form_1.Form.header("Actions",3),...createInputs(miscellaneous,"New Comment","hotkeyNewComment"),...createInputs(miscellaneous,"Edit Post","hotkeyEditPost"),...createInputs(postViewer,"Toggle Notes","hotkeyHideNotes"),...createInputs(postViewer,"Edit Notes","hotkeyNewNote"),Form_1.Form.hr(3),Form_1.Form.header("Search Modes",3),...createInputs(searchUtilities,"View","hotkeySwitchModeView"),...createInputs(searchUtilities,"Edit","hotkeySwitchModeEdit"),...createInputs(searchUtilities,"Add Favorite","hotkeySwitchModeAddFav"),...createInputs(searchUtilities,"Remove Favorite","hotkeySwitchModeRemFav"),...createInputs(searchUtilities,"Add to Set","hotkeySwitchModeAddSet"),...createInputs(searchUtilities,"Remove from Set","hotkeySwitchModeRemSet"),Form_1.Form.hr(3),Form_1.Form.header("Header Tabs",3),...createInputs(headerCustomizer,"Tab #1","hotkeyTab1"),...createInputs(headerCustomizer,"Tab #2","hotkeyTab2"),...createInputs(headerCustomizer,"Tab #3","hotkeyTab3"),...createInputs(headerCustomizer,"Tab #4","hotkeyTab4"),...createInputs(headerCustomizer,"Tab #5","hotkeyTab5"),...createInputs(headerCustomizer,"Tab #6","hotkeyTab6"),...createInputs(headerCustomizer,"Tab #7","hotkeyTab7"),...createInputs(headerCustomizer,"Tab #8","hotkeyTab8"),...createInputs(headerCustomizer,"Tab #9","hotkeyTab9"),...createInputs(this,"Open Settings","hotkeyOpenSettings"),...createInputs(subscriptionManager,"Open Notifications","hotkeyOpenNotifications"),Form_1.Form.hr(3),Form_1.Form.header("Miscellaneous",3),...createInputs(miscellaneous,"Submit Form","hotkeySubmit")])}createFeaturesTab(){const modules=ModuleController_1.ModuleController.getAll();function createInput(moduleName,label,description){const module=modules.get(moduleName);return[Form_1.Form.checkbox({name:moduleName+"-enabled",value:module.fetchSettings("enabled"),label:`<b>${label}</b><br />${description}`,width:3},data=>{module.pushSettings("enabled",data),module.setEnabled(data),!0===data?module.canInitialize()&&module.create():module.destroy()}),Form_1.Form.spacer(3)]}return new Form_1.Form({name:"settings-modules",columns:3,width:3},[Form_1.Form.header("Features",3),...createInput("HeaderCustomizer","Header Customizer","Add, delete, and customize header links to your heart's content."),...createInput("InfiniteScroll","Infinite Scroll","New posts are automatically loaded as you scroll."),...createInput("InstantSearch","Instant Filters","Quickly add filters to your current search."),...createInput("FormattingManager","Formatting Helper","Fully customizable toolbar for easy DText formatting."),...createInput("SmartAlias","Smart Alias","A more intelligent way to quickly fill out post tags.")])}createSyncTab(){return new Form_1.Form({name:"optsync",columns:3,width:3},[Form_1.Form.header("Settings Synchronization",3),Form_1.Form.checkbox({value:Sync_1.Sync.enabled,label:"Enabled"},async data=>{console.log(data)}),Form_1.Form.spacer(2),Form_1.Form.div({value:"ID"}),Form_1.Form.input({value:Sync_1.Sync.userID},async data=>{console.log(data)}),Form_1.Form.input({value:"password"},async data=>{console.log(data)})])}createMiscTab(){const modules=ModuleController_1.ModuleController.getAll(),moduleSelector={none:"------"};modules.forEach(module=>{moduleSelector[module.getSettingsTag()]=module.getSettingsTag()});let selectedModule="none",favcacheUpdated=!0,dnpcacheUpdated=!0;return new Form_1.Form({name:"optmisc",columns:3,width:3},[Form_1.Form.header("Miscellaneous",3),Form_1.Form.accordion({name:"misccollapse",columns:3,width:3,active:0},[Form_1.Form.accordionTab({name:"cache",label:"Cache",columns:3,width:3},[Form_1.Form.section({name:"favcache",columns:3,width:3},[Form_1.Form.div({value:"<b>Favorites Cache</b><br />Recorded to minimize the number of API calls",width:2}),Form_1.Form.button({name:"reset",value:"Reset"},async(data,input)=>{input.prop("disabled",!0),await FavoriteCache_1.FavoriteCache.update($("#favcache-status")),input.prop("disabled",!1),favcacheUpdated||(favcacheUpdated=!0,this.pushNotificationsCount(-1))}),Form_1.Form.div({value:async element=>{const $status=$("<div>").attr("id","favcache-status").html('<i class="fas fa-circle-notch fa-spin"></i> Initializing . . .').appendTo(element);FavoriteCache_1.FavoriteCache.isEnabled()?await FavoriteCache_1.FavoriteCache.isUpdateRequired()?await FavoriteCache_1.FavoriteCache.quickUpdate($status)?$status.html(`<i class="far fa-check-circle"></i> Cache recovered (${FavoriteCache_1.FavoriteCache.size()} items)`):($status.html('\n                                            <i class="far fa-times-circle"></i> \n                                            <span style="color:gold">Reset required</span>: Cache integrity failure\n                                        '),this.pushNotificationsCount(1),favcacheUpdated=!1):$status.html('<i class="far fa-check-circle"></i> Cache integrity verified'):$status.html('<i class="far fa-times-circle"></i> Cache disabled')},width:2}),Form_1.Form.div({value:element=>{const lastUpdate=FavoriteCache_1.FavoriteCache.getUpdateTime();lastUpdate?element.html(Util_1.Util.Time.format(lastUpdate)):element.html("")},wrapper:"text-center input-disabled"}),Form_1.Form.checkbox({value:!FavoriteCache_1.FavoriteCache.isEnabled(),label:"<b>Disable Favorite Caching</b><br />All systems that deal with favorites will become non-functional",width:2},data=>{FavoriteCache_1.FavoriteCache.setEnabled(!data),FavoriteCache_1.FavoriteCache.clear()}),Form_1.Form.text('<div class="text-center text-bold">Requires a page reload</div>')]),Form_1.Form.spacer(3),Form_1.Form.section({name:"dnpcache",columns:3,width:3},[Form_1.Form.div({value:"<b>Avoid Posting List</b><br />Used to speed up SmartAlias tag checking",width:2}),Form_1.Form.button({name:"reset",value:"Reset"},async(data,input)=>{input.prop("disabled","true"),await AvoidPosting_1.AvoidPosting.update($("#dnpcache-status")),input.prop("disabled","false"),dnpcacheUpdated||(dnpcacheUpdated=!1,this.pushNotificationsCount(-1))}),Form_1.Form.div({value:async element=>{const $status=$("<div>").attr("id","dnpcache-status").html('<i class="fas fa-circle-notch fa-spin"></i> Initializing . . .').appendTo(element);0==AvoidPosting_1.AvoidPosting.getUpdateTime()&&await AvoidPosting_1.AvoidPosting.update(),0==AvoidPosting_1.AvoidPosting.size()?($status.html('\n                                        <i class="far fa-times-circle"></i> \n                                        <span style="color:gold">Reset required</span>: Cache integrity failure\n                                    '),this.pushNotificationsCount(1),dnpcacheUpdated=!0):$status.html('<i class="far fa-check-circle"></i> Cache integrity verified')},width:2}),Form_1.Form.div({value:element=>{const lastUpdate=AvoidPosting_1.AvoidPosting.getUpdateTime();lastUpdate?element.html(Util_1.Util.Time.format(lastUpdate)):element.html("")},wrapper:"text-center input-disabled"})])]),Form_1.Form.accordionTab({name:"export",label:"Import / Export",columns:3,width:3},[Form_1.Form.section({name:"file",columns:3,width:3},[Form_1.Form.header("Import / Export from file"),Form_1.Form.div({value:'<div class="notice float-right">Import subscription data from file</div>',width:2}),Form_1.Form.text("Export to File"),Form_1.Form.button({value:"Export",width:2},()=>{!function(){const promises=[];ModuleController_1.ModuleController.getAll().forEach(module=>{promises.push(module.getSavedSettings())}),Promise.all(promises).then(response=>{Debug_1.Debug.log(response);const storedData={meta:"re621/1.0"};response.forEach(data=>{storedData[data.name]=data.data,storedData[data.name].cache&&(storedData[data.name].cache={})}),Util_1.Util.downloadAsJSON(storedData,"re621-"+User_1.User.getUsername()+"-userdata")})}()}),Form_1.Form.text("Import from File"),Form_1.Form.file({accept:"json",width:2},data=>{!function(data){if(!data)return;const $info=$("#file-import-status").html("Loading . . ."),reader=new FileReader;reader.readAsText(data[0],"UTF-8"),reader.onload=function(event){const parsedData=JSON.parse(event.target.result.toString());parsedData.meta&&"re621/1.0"===parsedData.meta?(delete parsedData.meta,Object.keys(parsedData).forEach(key=>{$info.html("Importing "+key),XM_1.XM.Storage.setValue(key,parsedData[key])}),$info.html("Settings imported!")):$info.html("Invalid file format")},reader.onerror=function(){$info.html("Error loading file")}}(data)}),Form_1.Form.spacer(),Form_1.Form.div({value:'<div id="file-import-status" class="unmargin"></div>',label:" ",width:3})]),Form_1.Form.section({name:"esix",columns:3,width:3,wrapper:Debug_1.Debug.getState("enabled")?void 0:"display-none"},[Form_1.Form.header("eSix Extended"),Form_1.Form.div({value:'<div class="notice float-right">Import the settings from eSix Extended (Legacy)</div>',width:2}),Form_1.Form.text("Select File"),Form_1.Form.file({accept:"json",width:2},data=>{!function(data){if(!data)return;const $info=$("#file-esix-status").html("Loading . . ."),reader=new FileReader;reader.readAsText(data,"UTF-8"),reader.onload=async event=>{const parsedData=event.target.result.toString().split("\n");"eSixExtend User Prefs"===parsedData[0]?(parsedData.forEach((value,index)=>{0!==index&&(parsedData[index]=JSON.parse(atob(value).replace(/^\d+\|/,"")))}),await async function(settings,$info){$info.html("Processing pools . . .");const poolSubs=PoolTracker_1.PoolTracker.getInstance(),poolData=poolSubs.fetchSettings("data");for(const entry of settings)poolData[entry.id]={md5:entry.thumb.url.substr(6,32),lastID:entry.last};poolSubs.pushSettings("data",poolData)}(parsedData[2],$info),await async function(settings,$info){$info.html("Processing forums . . .");const forumSubs=ForumTracker_1.ForumTracker.getInstance(),forumData=forumSubs.fetchSettings("data"),postIDs=[];for(const entry of settings)postIDs.push(entry.id);(await E621_1.E621.ForumPosts.get({"search[id]":postIDs.join(",")})).forEach(postData=>{forumData[postData.topic_id]={}}),forumSubs.pushSettings("data",forumData)}(parsedData[3],$info),$info.html("Settings imported!")):$info.html("Invalid file format")},reader.onerror=function(){$info.html("Error loading file")}}(data)}),Form_1.Form.spacer(),Form_1.Form.div({value:'<div id="file-esix-status" class="unmargin"></div>',label:" ",width:3}),Form_1.Form.text("From LocalStorage"),Form_1.Form.button({value:"Load",width:2},()=>{!async function(){const $info=$("#localstorage-esix-status").html("Loading . . .");null!==localStorage.getItem("poolSubscriptions")&&await this.importPoolData(JSON.parse(localStorage.getItem("poolSubscriptions")),$info);null!==localStorage.getItem("forumSubscriptions")&&await this.importForumData(JSON.parse(localStorage.getItem("forumSubscriptions")),$info);$info.html("Settings imported!")}()}),Form_1.Form.spacer(),Form_1.Form.div({value:'<div id="localstorage-esix-status" class="unmargin"></div>',label:" ",width:3})])]),Form_1.Form.accordionTab({name:"reset",label:"Reset Modules",columns:3,width:3},[Form_1.Form.text("<b>Everything</b><br />Delete settings for all modules. <b>This cannot be undone.</b>",2),Form_1.Form.button({value:"Clear"},()=>{confirm("Are you absolutely sure?")&&(ModuleController_1.ModuleController.getAll().forEach(module=>{module.clearSettings()}),location.reload())}),Form_1.Form.spacer(3),Form_1.Form.text("<b>Module</b><br />Reset a specific module",2),Form_1.Form.select({value:selectedModule},moduleSelector,data=>{selectedModule=data}),Form_1.Form.text('<div class="text-bold">Requires a page reload</div>',2),Form_1.Form.button({value:"Reset"},()=>{"none"!==selectedModule&&ModuleController_1.ModuleController.get(selectedModule).clearSettings()}),Form_1.Form.spacer(3)]),Form_1.Form.accordionTab({name:"debug",label:"Debugging Tools",columns:3,width:3},[Form_1.Form.checkbox({value:Debug_1.Debug.getState("enabled"),label:"<b>Debug Mode</b><br />Enable debug messages in the console log",width:3},data=>{Debug_1.Debug.setState("enabled",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:Debug_1.Debug.getState("connect"),label:"<b>Connections Log</b><br />Logs all outbound connections in the console",width:3},data=>{Debug_1.Debug.setState("connect",data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:Debug_1.Debug.getState("perform"),label:"<b>Performance Metrics</b><br />Write script performance analysis into the console log",width:3},data=>{Debug_1.Debug.setState("perform",data)}),Form_1.Form.spacer(3)])])])}createAboutTab(){return new Form_1.Form({name:"optabout",columns:3,width:3},[Form_1.Form.div({value:`<h3 class="display-inline"><a href="${window.re621.links.website}">${window.re621.name} v.${window.re621.version}</a></h3> <span class="display-inline">build ${window.re621.build}:${Patcher_1.Patcher.version}</span>`,width:2}),Form_1.Form.div({value:`<span class="float-right" id="project-update-button" data-available="${this.fetchSettings("newVersionAvailable")}">\n                    <a href="${window.re621.links.releases}">Update Available</a>\n                    </span>`}),Form_1.Form.div({value:`<b>${window.re621.name}</b> is a comprehensive set of tools designed to enhance the website for both casual and power users. It is created and maintained by unpaid volunteers, with the hope that it will be useful for the community.`,width:3}),Form_1.Form.div({value:`Keeping the script - and the website - fully functional is our highest priority. If you are experiencing bugs or issues, do not hesitate to create a new ticket on <a href="${window.re621.links.issues}">github</a>, or leave us a message in the <a href="${window.re621.links.forum}">forum thread</a>. Feature requests, comments, and overall feedback are also appreciated.`,width:3}),Form_1.Form.div({value:"Thank you for downloading and using this script. We hope that you enjoy the experience.",width:3}),Form_1.Form.spacer(3),Form_1.Form.header(`<a href="${window.re621.links.releases}" class="unmargin">What's new?</a>`,3),Form_1.Form.div({value:`<div id="changelog-list">${Util_1.Util.quickParseMarkdown(this.fetchSettings("changelog"))}</div>`,width:3})])}openSettings(){$("a#header-button-settings")[0].click()}}exports.SettingsController=SettingsController},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/api/XM":7,"../../components/cache/AvoidPosting":13,"../../components/cache/FavoriteCache":14,"../../components/data/Hotkeys":16,"../../components/data/User":22,"../../components/structure/DomUtilities":23,"../../components/structure/Form":24,"../../components/structure/Modal":25,"../../components/structure/Tabbed":27,"../../components/utility/Debug":28,"../../components/utility/Patcher":30,"../../components/utility/Sync":31,"../../components/utility/Util":32,"../downloader/FavDownloader":36,"../downloader/MassDownloader":37,"../downloader/PoolDownloader":38,"../misc/SmartAlias":44,"../misc/UploadUtilities":45,"../post/DownloadCustomizer":47,"../post/ImageScaler":48,"../post/PoolNavigator":49,"../post/PostViewer":50,"../post/TitleCustomizer":51,"../search/BlacklistEnhancer":52,"../search/CustomFlagger":53,"../search/InfiniteScroll":54,"../search/SearchUtilities":57,"../search/ThumbnailsEnhancer":58,"../subscriptions/ForumTracker":60,"../subscriptions/PoolTracker":61,"../subscriptions/SubscriptionManager":62,"./HeaderCustomizer":40,"./Miscellaneous":41}],43:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ThemeCustomizer=void 0;const RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),Form_1=require("../../components/structure/Form"),Modal_1=require("../../components/structure/Modal");class ThemeCustomizer extends RE6Module_1.RE6Module{getDefaultSettings(){return{enabled:!0}}create(){super.create();const openCustomizerButton=DomUtilities_1.DomUtilities.addSettingsButton({id:"header-button-theme",name:'<i class="fas fa-paint-brush"></i>',title:"Change Theme"}),form=new Form_1.Form({name:"theme-customizer"},[Form_1.Form.select({label:"Theme",value:window.localStorage.getItem("theme")||"hexagon"},{hexagon:"Hexagon",pony:"Pony",bloodlust:"Bloodlust",serpent:"Serpent",hotdog:"Hotdog"},data=>{window.localStorage.setItem("theme",data),$("body").attr("data-th-main",data)}),Form_1.Form.select({label:"Extras",value:window.localStorage.getItem("theme-extra")||"hexagons"},{none:"None",autumn:"Autumn",winter:"Winter",spring:"Spring",aurora:"Aurora",hexagons:"Hexagons",space:"Space",stars:"Stars"},data=>{window.localStorage.setItem("theme-extra",data),$("body").attr("data-th-extra",data)}),Form_1.Form.select({label:"Post Navbar",value:window.localStorage.getItem("theme-nav")||"top"},{top:"Top",bottom:"Bottom",none:"None"},data=>{window.localStorage.setItem("theme-nav",data),$("body").attr("data-th-nav",data)})]);new Modal_1.Modal({title:"Themes",triggers:[{element:openCustomizerButton}],content:Form_1.Form.placeholder(),structure:form,position:{my:"right top",at:"right top"}})}}exports.ThemeCustomizer=ThemeCustomizer},{"../../components/RE6Module":2,"../../components/structure/DomUtilities":23,"../../components/structure/Form":24,"../../components/structure/Modal":25}],44:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SmartAlias=void 0;const E621_1=require("../../components/api/E621"),AvoidPosting_1=require("../../components/cache/AvoidPosting"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util");class SmartAlias extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.upload,Page_1.PageDefintion.post,Page_1.PageDefintion.search,Page_1.PageDefintion.favorites],!0)}getDefaultSettings(){return{enabled:!0,autoLoad:!0,tagOrder:TagOrder.Default,quickTagsForm:!0,editTagsForm:!0,uploadCharactersForm:!0,uploadSexesForm:!0,uploadBodyTypesForm:!0,uploadThemesForm:!0,uploadTagsForm:!0,replaceAliasedTags:!0,fixCommonTypos:!1,minPostsWarning:20,compactOutput:!1,data:""}}async prepare(){await super.prepare(),Page_1.Page.matches(Page_1.PageDefintion.post)&&($("#post_tag_string").is(":visible")||(SmartAlias.postPageLockout=!0,$("#post-edit-link").one("click.re621",()=>{SmartAlias.postPageLockout=!1,this.reload()})))}async reload(){return this.destroy(),new Promise(resolve=>{setTimeout(()=>{this.create(),resolve()},100)})}destroy(){if(this.isInitialized()){super.destroy();for(const inputElement of $("textarea#post_tags, textarea#post_tag_string").get())$(inputElement).off("focus.re621.smart-alias").off("focusout.re621.smart-alias");$("smart-alias").remove(),$("smart-tag-counter").remove(),$("button.smart-alias-validate").remove()}}create(){if(super.create(),!this.fetchSettings("quickTagsForm")&&Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.favorites]))return;if(!this.fetchSettings("editTagsForm")&&Page_1.Page.matches(Page_1.PageDefintion.post))return;if(this.setCompactOutput(this.fetchSettings("compactOutput")),SmartAlias.postPageLockout)return;if(void 0===SmartAlias.aliasCache){const cacheData=this.fetchSettings("data");SmartAlias.aliasCache=SmartAlias.getAliasData(cacheData),SmartAlias.aliasCacheLength=cacheData.length}$(".the_secret_switch").one("click",()=>{this.reload()});const inputs=new Set(Array.from(SmartAlias.inputSelector)),enabledInputs=this.fetchSettings(["uploadCharactersForm","uploadSexesForm","uploadBodyTypesForm","uploadThemesForm","uploadTagsForm"]);enabledInputs.uploadCharactersForm||inputs.delete("#post_characters"),enabledInputs.uploadSexesForm||inputs.delete("#post_sexes"),enabledInputs.uploadBodyTypesForm||inputs.delete("#post_bodyTypes"),enabledInputs.uploadThemesForm||inputs.delete("#post_themes"),enabledInputs.uploadTagsForm||inputs.delete("#post_tags");const mode=this.fetchSettings("autoLoad");for(const inputElement of $([...inputs].join(", ")).get()){const $textarea=$(inputElement),$container=$("<smart-alias>").attr("ready","true").insertAfter($textarea),$counter=$("<smart-tag-counter>").insertAfter($textarea);let updateTimeout;mode?this.manageAutoLoad($textarea,$container):this.manageManualLoad($textarea,$container),Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.favorites])&&$("article.post-preview").on("click.danbooru",()=>{mode?this.handleTagInput($textarea,$container,!1):$container.html("")}),$textarea.on("input",()=>{updateTimeout||(updateTimeout=window.setTimeout(()=>{updateTimeout=0},500),$counter.html(SmartAlias.getInputTags($textarea).length+""))})}}static getInputString(input){return input.val().toString().trim().toLowerCase().replace(/\r?\n|\r/g," ").replace(/(?:\s){2,}/g," ")}static getInputTags(input){return("string"==typeof input?input:SmartAlias.getInputString(input)).split(" ").filter(el=>null!=el&&""!=el)}manageAutoLoad($textarea,$container){let typingTimeout;$textarea.on("input",()=>{"true"!==$textarea.data("vue-event")?(window.clearInterval(typingTimeout),typingTimeout=window.setInterval(()=>{"true"===$container.attr("ready")&&(window.clearInterval(typingTimeout),this.handleTagInput($textarea,$container))},1e3)):$textarea.data("vue-event","false")}),this.handleTagInput($textarea,$container,!1)}manageManualLoad($textarea,$container){$("<button>").html("Validate").addClass("smart-alias-validate").insertBefore($container).on("click",()=>{this.handleTagInput($textarea,$container,!1)})}async handleTagInput($textarea,$container,scrollToBottom=!0){if("true"!==$container.attr("ready"))return;$container.attr("ready","false"),AvoidPosting_1.AvoidPosting.isUpdateRequired()&&await AvoidPosting_1.AvoidPosting.update(),this.fetchSettings("fixCommonTypos")&&$textarea.val((index,currentValue)=>currentValue.toLowerCase().replace(/\-/g,"_")+(0==currentValue.length||currentValue.endsWith(" ")?"":" "));const inputString=SmartAlias.getInputString($textarea);let tags=SmartAlias.getInputTags(inputString);if(0==tags.length)return $container.html(""),void $container.attr("ready","true");const minPostsWarning=this.fetchSettings("minPostsWarning"),tagOrder=this.fetchSettings("tagOrder"),aliasCacheRaw=await this.fetchSettings("data",!0);aliasCacheRaw.length!==SmartAlias.aliasCacheLength&&(SmartAlias.aliasCache=SmartAlias.getAliasData(aliasCacheRaw),SmartAlias.aliasCacheLength=aliasCacheRaw.length),SmartAlias.aliasCache.length>0&&($textarea.val((index,currentValue)=>{let changes=0,iterations=0;do{changes=0;for(const aliasDef of SmartAlias.aliasCache)currentValue=currentValue.replace(getTagRegex(aliasDef.lookup),(...args)=>{changes++;let output=aliasDef.output;for(let i=3;i<args.length-3;i++)output=output.replace(new RegExp("\\$"+(i-2),"gi"),args[i]);const result=new Set;for(const part of output.split(" "))getTagRegex(part).test(currentValue)||result.add(part);return 0==result.size?" ":args[1]+[...result].join(" ")+args[args.length-3]});iterations++}while(0!=changes&&iterations<SmartAlias.ITERATIONS_LIMIT);return currentValue}),triggerUpdateEvent($textarea),tags=SmartAlias.getInputTags($textarea));const lookup=new Set;for(const tagName of tags)void 0===SmartAlias.tagData[tagName]&&lookup.add(tagName);redrawContainerContents($container,tags,minPostsWarning,tagOrder,lookup);const invalidTags=new Set,ambiguousTags=new Set;for(const batch of Util_1.Util.chunkArray([...lookup].filter(value=>null==SmartAlias.tagAliases[value]),40))for(const result of await E621_1.E621.TagAliases.get({"search[antecedent_name]":batch.join("+"),limit:1e3},500)){if("active"!==result.status)continue;const currentName=result.antecedent_name,trueName=result.consequent_name;"invalid_tag"!=trueName&&"invalid_color"!=trueName?trueName.endsWith("_(disambiguation)")?ambiguousTags.add(currentName):(lookup.delete(currentName),null==SmartAlias.tagData[trueName]&&lookup.add(trueName),SmartAlias.tagAliases[currentName]=trueName):invalidTags.add(currentName)}if(this.fetchSettings("replaceAliasedTags")&&($textarea.val((index,currentValue)=>{for(const[antecedent,consequent]of Object.entries(SmartAlias.tagAliases))currentValue=currentValue.replace(getTagRegex(antecedent),"$1"+consequent+"$3");return currentValue}),triggerUpdateEvent($textarea),tags=SmartAlias.getInputTags($textarea)),lookup.size>0){for(const batch of Util_1.Util.chunkArray(lookup,100))for(const result of await E621_1.E621.Tags.get({"search[name]":batch.join(","),"search[hide_empty]":!1,limit:100},500))SmartAlias.tagData[result.name]={count:result.post_count,category:result.category,ambiguous:ambiguousTags.has(result.name),invalid:invalidTags.has(result.name),dnp:AvoidPosting_1.AvoidPosting.has(result.name)},lookup.delete(result.name);for(const tagName of lookup)SmartAlias.tagData[tagName]={count:-1,category:-1,ambiguous:!1,invalid:!0,dnp:AvoidPosting_1.AvoidPosting.has(tagName)}}function triggerUpdateEvent($textarea){const e=document.createEvent("HTMLEvents");e.initEvent("input",!0,!0),$textarea.data("vue-event","true"),$textarea[0].dispatchEvent(e)}function getTagRegex(input){input="string"==typeof input?[input]:[...input];for(let i=0;i<input.length;i++)input[i]=input[i].replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"(\\S*)");return new RegExp("(^|\n| )("+input.join("|")+")( |\n|$)","gi")}function redrawContainerContents($container,tags,minPostsWarning,tagOrder,loading=new Set){$container.html("").toggleClass("grouped",tagOrder==TagOrder.Grouped),tagOrder!==TagOrder.Default&&(tags=tags.sort());for(let tagName of tags){let displayName=tagName;null!=SmartAlias.tagAliases[tagName]&&(tagName=SmartAlias.tagAliases[tagName]);const data=SmartAlias.tagData[tagName],isLoading=loading.has(tagName);if(null==data&&!isLoading)continue;let symbol,color,text;isLoading?(symbol="loading",color="success",text=""):data.dnp?(symbol="error",color="error",text="avoid posting"):Util_1.Util.getArrayIndexes(tags,tagName).length>1?(symbol="info",color="info",text="duplicate"):data.invalid?(symbol="error",color="error",text="invalid"):data.ambiguous||tagName.endsWith("_(disambiguation)")?(symbol="info",color="warning",text="ambiguous",displayName=displayName.replace("_(disambiguation)","")):0==data.count?(symbol="error",color="error",text="empty"):data.count<minPostsWarning?(symbol="error",color="error",text=data.count+""):(symbol="success",color="success",text=data.count+""),displayName=displayName.replace(/_/g,"_&#8203;"),$("<smart-tag>").addClass(isLoading?"":"category-"+data.category).attr({name:tagName,symbol:symbol,color:color}).html(`<a href="/wiki_pages/show_or_new?title=${tagName}" target="_blank">${displayName}</a> ${text}`).appendTo($container)}}redrawContainerContents($container,tags,minPostsWarning,tagOrder),scrollToBottom&&$container.scrollTop($container[0].scrollHeight-$container[0].clientHeight),$container.attr("ready","true")}static getAliasData(rawData){const data=rawData.split("\n").reverse(),result=[],aliasList=new Set;for(const line of data){const parts=line.split("#")[0].trim().split("->");if(2!==parts.length)continue;const def={lookup:new Set,output:(input=parts[1],input.trim().replace(/\s{2,}/g," "))};for(const part of formatLookup(parts[0]))aliasList.has(part)||(aliasList.add(part),def.lookup.add(part));0!=def.lookup.size&&result.push(def)}var input;return result;function formatLookup(input){return new Set(input.split(" ").filter(e=>""!=e))}}setCompactOutput(state=!1){$("#page").attr("data-smartalias-compact",state+"")}}var TagOrder;exports.SmartAlias=SmartAlias,SmartAlias.ITERATIONS_LIMIT=10,SmartAlias.inputSelector=new Set(["#post_tag_string","#post_characters","#post_sexes","#post_bodyTypes","#post_themes","#post_tags"]),SmartAlias.tagData={},SmartAlias.tagAliases={},SmartAlias.postPageLockout=!1,function(TagOrder){TagOrder.Default="default",TagOrder.Alphabetical="alphabetical",TagOrder.Grouped="grouped"}(TagOrder||(TagOrder={})),function(TagOrder){TagOrder.fromString=function(input){for(const value of Object.values(TagOrder))if(value==input)return value;return TagOrder.Default}}(TagOrder||(TagOrder={}))},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/cache/AvoidPosting":13,"../../components/data/Page":17,"../../components/utility/Util":32}],45:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UploadUtilities=void 0;const E621_1=require("../../components/api/E621"),XM_1=require("../../components/api/XM"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util");class UploadUtilities extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.upload])}getDefaultSettings(){return{enabled:!0,checkDuplicates:!0,addSourceLinks:!0}}create(){super.create(),this.fetchSettings("checkDuplicates")&&this.handleDuplicateCheck(),this.fetchSettings("addSourceLinks")&&this.handleSourceEnhancements()}static findSection(label,id){return $("label[for="+label+"]").parent().parent().attr("id",id)}handleDuplicateCheck(){const fileContainer=UploadUtilities.findSection("post_file","section-file").find("div.col2").first().attr("id","file-container"),dupesContainer=$("<div>").attr("id","dupes-container").appendTo(fileContainer),risContainer=$("<div>").attr("id","ris-container").html("").appendTo("div.upload_preview_container");let working=!1;function makePostThumbnail(entry){const postData=entry.post.posts,article=$("<div>"),link=$("<a>").attr({href:"/posts/"+postData.id,target:"_blank"}).appendTo(article);return $("<img>").attr({src:postData.is_deleted?"/images/deleted-preview.png":postData.preview_file_url,title:`${postData.image_width}x${postData.image_height} ${Util_1.Util.formatBytes(postData.file_size)} ${Math.round(entry.score)}% match\n${postData.tag_string_artist}\n${postData.tag_string_copyright}\n${postData.tag_string_character}\n${postData.tag_string_species}`}).appendTo(link),$("<loading>").css("--progress",Math.round(entry.score)+"%").appendTo(link),$("<span>").html(`${postData.image_width}x${postData.image_height} ${Util_1.Util.formatBytes(postData.file_size)}`).appendTo(article),article}$(fileContainer).on("input","input",event=>{if(working)return;const value=$(event.target).val()+"";return""==value?(dupesContainer.html(""),void risContainer.html("")):/^https?:\/\//.test(value)?(working=!0,dupesContainer.html('<span class="fullspan">Checking for duplicates . . .</span>'),E621_1.E621.IQDBQueries.get({url:value}).then(response=>{if(console.log(response),dupesContainer.html(""),0==response.length||void 0!==response[0]&&null==response[0].post_id)working=!1;else{$("<h3>").html(`<a href="/iqdb_queries?url=${encodeURI(value)}" target="_blank">Duplicates Found:</a> ${response.length}`).appendTo(dupesContainer);for(const entry of response)makePostThumbnail(entry).appendTo(dupesContainer);working=!1}},error=>{console.log(error),dupesContainer.html(`"<span class="fullspan error">IQDB server responded with: Internal Error ${error}</span>`),working=!1}),void risContainer.html(`\n                <a href="/iqdb_queries?url=${encodeURI(value)}" target="_blank">e621</a>\n                <a href="https://www.google.com/searchbyimage?image_url=${encodeURI(value)}" target="_blank">Google</a>\n                <a href="https://saucenao.com/search.php?url=${encodeURI(value)}" target="_blank">SauceNAO</a>\n                <a href="https://derpibooru.org/search/reverse?url=${encodeURI(value)}" target="_blank">Derpibooru</a>\n                <a href="https://kheina.com/?url=${encodeURI(value)}" target="_blank">Kheina</a>\n            `)):(dupesContainer.html('<span class="fullspan">Unable to parse image path. <a href="/iqdb_queries" target="_blank">Check manually</a>?</span>'),void risContainer.html(""))}),fileContainer.find("input[type=text").trigger("input")}handleSourceEnhancements(){const sourceContainer=UploadUtilities.findSection("post_sources","section-sources").find("div.col2").children("div").eq(1).attr("id","source-container");$(sourceContainer).on("input","input.upload-source-input",event=>{const $input=$(event.target),$parent=$input.parent();$parent.find("button.source-copy").remove(),$parent.find("button.source-link").remove(),""!=$input.val()&&($("<button>").addClass("source-copy").html("copy").appendTo($parent).on("click",()=>{XM_1.XM.Util.setClipboard($input.val())}),$("<button>").addClass("source-link").html("open").appendTo($parent).on("click",()=>{window.open($input.val()+"","_blank")}))}),$("input.upload-source-input").trigger("input")}}exports.UploadUtilities=UploadUtilities},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/api/XM":7,"../../components/data/Page":17,"../../components/utility/Util":32}],46:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.WikiEnhancer=void 0;const XM_1=require("../../components/api/XM"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module");class WikiEnhancer extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.wiki,Page_1.PageDefintion.wikiNA,Page_1.PageDefintion.artist])}getDefaultSettings(){return{enabled:!0}}create(){super.create();const $title=Page_1.Page.matches(Page_1.PageDefintion.artist)?$("#a-show h1").first():$("#wiki-page-title"),tagName=$title.text().trim().replace(/^((Species|Character|Copyright|Artist|Lore|Meta): )/g,"").replace(/ /g,"_");$("<button>").attr("id","wiki-page-copy-tag").addClass("button btn-neutral border-highlight border-left").html('<i class="far fa-copy"></i>').appendTo($title).on("click",()=>{XM_1.XM.Util.setClipboard(tagName)})}destroy(){this.isInitialized()&&(super.destroy(),$("#wiki-page-copy-tag").remove())}}exports.WikiEnhancer=WikiEnhancer},{"../../components/RE6Module":2,"../../components/api/XM":7,"../../components/data/Page":17}],47:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DownloadCustomizer=void 0;const XM_1=require("../../components/api/XM"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/data/Post"),Tag_1=require("../../components/data/Tag"),RE6Module_1=require("../../components/RE6Module");class DownloadCustomizer extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.post,!0)}getDefaultSettings(){return{enabled:!0,template:"%postid%-%artist%-%copyright%-%character%"}}create(){super.create(),this.post=Post_1.Post.getViewingPost(),this.link=$("#image-download-link").find("a").first(),this.refreshDownloadLink(),this.link.click(event=>{event.preventDefault(),event.stopImmediatePropagation(),XM_1.XM.Connect.download(this.link.attr("href"),this.link.attr("download"))})}refreshDownloadLink(){this.link.attr("download",this.parseTemplate())}parseTemplate(){return this.fetchSettings("template").replace(/%postid%/g,this.post.getId()).replace(/%artist%/g,this.post.getTagsFromType(Tag_1.TagTypes.Artist).join("-")).replace(/%copyright%/g,this.post.getTagsFromType(Tag_1.TagTypes.Copyright).join("-")).replace(/%character%/g,this.post.getTagsFromType(Tag_1.TagTypes.Character).join("-")).replace(/%species%/g,this.post.getTagsFromType(Tag_1.TagTypes.Species).join("-")).replace(/%meta%/g,this.post.getTagsFromType(Tag_1.TagTypes.Meta).join("-")).replace(/%md5%/g,this.post.getMD5()).slice(0,128).replace(/-{2,}/g,"-").replace(/-*$/g,"")+"."+this.post.getFileExtension()}}exports.DownloadCustomizer=DownloadCustomizer},{"../../components/RE6Module":2,"../../components/api/XM":7,"../../components/data/Page":17,"../../components/data/Post":18,"../../components/data/Tag":21}],48:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ImageScaler=void 0;const Danbooru_1=require("../../components/api/Danbooru"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/data/Post"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module");class ImageScaler extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.post,!0),this.registerHotkeys({keys:"hotkeyScale",fnct:()=>{this.setScale()}},{keys:"hotkeyFullscreen",fnct:this.openFullscreen})}getDefaultSettings(){return{enabled:!0,hotkeyScale:"v|0",hotkeyFullscreen:"",clickScale:!0,size:"fit-vertical"}}create(){super.create(),this.post=Post_1.Post.getViewingPost(),this.image=$("img#image");const resizeButtonContainer=$("#image-resize-cycle").empty();this.setImageSize(this.fetchSettings("size")),this.resizeSelector=$("<select>").html('\n                <option value="sample">Sample</option>\n                <option value="fit-vertical">Fill Screen</option>\n                <option value="fit-horizontal">Fit Horizontally</option>\n                <option value="original">Original</option>\n            ').val(this.fetchSettings("size")).addClass("button btn-neutral").appendTo(resizeButtonContainer).change(async(event,save)=>{const size=$(event.target).val()+"";this.setImageSize(size),!1!==save&&await this.pushSettings("size",size)}),$("<a>").attr({href:this.post.getImageURL(),id:"re621-imagescaler-fullscreen"}).addClass("button btn-neutral").html("Fullscreen").appendTo(resizeButtonContainer),this.image.click(async()=>{this.fetchSettings("clickScale")&&!await Danbooru_1.Danbooru.Note.TranslationMode.active()&&this.setScale("",!1)})}setScale(size="",save=!0){const selector=ModuleController_1.ModuleController.get(ImageScaler).resizeSelector;if(""===size){const $next=selector.find("option:selected").next();size=$next.length>0?$next.val()+"":selector.find("option").first().val()+""}selector.val(size).trigger("change",save)}setImageSize(size){switch(this.image.removeClass(),this.image.parent().addClass("loading"),this.image.on("load",()=>{Danbooru_1.Danbooru.Note.Box.scale_all(),this.image.parent().removeClass("loading")}),size){case"sample":this.image.attr("src",this.post.getSampleURL());break;case"fit-vertical":this.image.addClass("re621-fit-vertical"),this.image.attr("src")!==this.post.getImageURL()?this.image.attr("src",this.post.getImageURL()):this.image.parent().removeClass("loading");break;case"fit-horizontal":this.image.addClass("re621-fit-horizontal"),this.image.attr("src")!==this.post.getImageURL()?this.image.attr("src",this.post.getImageURL()):this.image.parent().removeClass("loading");break;case"original":this.image.attr("src")!==this.post.getImageURL()?this.image.attr("src",this.post.getImageURL()):this.image.parent().removeClass("loading")}Danbooru_1.Danbooru.Note.Box.scale_all()}openFullscreen(){$("#re621-imagescaler-fullscreen")[0].click()}}exports.ImageScaler=ImageScaler},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/data/Page":17,"../../components/data/Post":18}],49:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PoolNavigator=void 0;const Page_1=require("../../components/data/Page"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module");class PoolNavigator extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.post),this.activeNav=0,this.navbars=[],this.registerHotkeys({keys:"hotkeyCycle",fnct:this.cycleNavbars},{keys:"hotkeyNext",fnct:this.triggerNextPost},{keys:"hotkeyPrev",fnct:this.triggerPrevPost})}getDefaultSettings(){return{enabled:!0,hotkeyCycle:"x|.",hotkeyPrev:"a|left",hotkeyNext:"d|right"}}create(){super.create(),this.buildDOM(),$("input[type='radio'].post-nav-switch").change(event=>{this.activeNav=parseInt($(event.target).val()+"")})}cycleNavbars(){const poolNavigator=ModuleController_1.ModuleController.get(PoolNavigator),navbars=poolNavigator.navbars,active=poolNavigator.activeNav;0!=navbars.length&&(active+1>=navbars.length?navbars[0].checkbox.click():navbars[active+1].checkbox.click())}triggerNextPost(){const poolNavigator=ModuleController_1.ModuleController.get(PoolNavigator),navbars=poolNavigator.navbars,active=poolNavigator.activeNav;if(0==navbars.length)return;const button=navbars[active].element.find("a.next").first()[0];void 0!==button&&button.click()}triggerPrevPost(){const poolNavigator=ModuleController_1.ModuleController.get(PoolNavigator),navbars=poolNavigator.navbars,active=poolNavigator.activeNav;if(0==navbars.length)return;const button=navbars[active].element.find("a.prev").first()[0];void 0!==button&&button.click()}buildDOM(){$("#search-seq-nav").length&&this.navbars.push({type:"search",element:$("#search-seq-nav > ul > li").first(),checkbox:void 0});for(const element of $("#pool-nav").find("ul > li").get())this.navbars.push({type:"pool",element:$(element),checkbox:void 0});for(const element of $("#set-nav").find("ul > li").get())this.navbars.push({type:"set",element:$(element),checkbox:void 0});this.navbars.forEach((nav,index)=>{nav.element.addClass("post-nav");const $radioBox=$("<div>").addClass("post-nav-switch-box").prependTo(nav.element);$("<div>").addClass("post-nav-spacer").appendTo(nav.element),nav.checkbox=$("<input>").attr("type","radio").attr("id","post-nav-switch-"+index).attr("name","nav").val(index).addClass("post-nav-switch").appendTo($radioBox),index===this.activeNav&&nav.checkbox.attr("checked",""),$("<label>").attr("for","post-nav-switch-"+index).appendTo($radioBox)}),1==this.navbars.length&&this.navbars[0].checkbox.parent().addClass("vis-hidden"),$("#nav-links").find(".first").each((index,element)=>{$(element).html("&laquo;")}),$("#nav-links").find(".last").each((index,element)=>{$(element).html("&raquo;")})}}exports.PoolNavigator=PoolNavigator},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/data/Page":17}],50:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostViewer=void 0;const Danbooru_1=require("../../components/api/Danbooru"),FavoriteCache_1=require("../../components/cache/FavoriteCache"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/data/Post"),PostActions_1=require("../../components/data/PostActions"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module");class PostViewer extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.post,!0),this.registerHotkeys({keys:"hotkeyUpvote",fnct:this.triggerUpvote},{keys:"hotkeyDownvote",fnct:this.triggerDownvote},{keys:"hotkeyFavorite",fnct:this.toggleFavorite},{keys:"hotkeyAddFavorite",fnct:this.addFavorite},{keys:"hotkeyRemoveFavorite",fnct:this.removeFavorite},{keys:"hotkeyHideNotes",fnct:this.toggleNotes},{keys:"hotkeyNewNote",fnct:this.switchNewNote},{keys:"hotkeyAddSet",fnct:this.addSet},{keys:"hotkeyAddPool",fnct:this.addPool},{keys:"hotkeyToggleSetLatest",fnct:this.toggleSetLatest},{keys:"hotkeyAddSetLatest",fnct:this.addSetLatest},{keys:"hotkeyRemoveSetLatest",fnct:this.removeSetLatest},{keys:"hotkeyAddSetCustom1",fnct:()=>{this.addSetCustom("hotkeyAddSetCustom1_data")}},{keys:"hotkeyAddSetCustom2",fnct:()=>{this.addSetCustom("hotkeyAddSetCustom2_data")}},{keys:"hotkeyAddSetCustom3",fnct:()=>{this.addSetCustom("hotkeyAddSetCustom3_data")}})}getDefaultSettings(){return{enabled:!0,hotkeyUpvote:"w",hotkeyDownvote:"s",hotkeyFavorite:"f",hotkeyAddFavorite:"",hotkeyRemoveFavorite:"",hotkeyHideNotes:"o",hotkeyNewNote:"p",hotkeyAddSet:"",hotkeyAddPool:"",hotkeyToggleSetLatest:"",hotkeyAddSetLatest:"",hotkeyRemoveSetLatest:"",hotkeyAddSetCustom1:"",hotkeyAddSetCustom1_data:"0",hotkeyAddSetCustom2:"",hotkeyAddSetCustom2_data:"0",hotkeyAddSetCustom3:"",hotkeyAddSetCustom3_data:"0",upvoteOnFavorite:!0,hideNotes:!1}}create(){super.create(),this.post=Post_1.Post.getViewingPost();const $addToContainer=$("<div>").attr("id","image-add-links").insertAfter("div#image-download-link");$("li#add-to-set-list > a").addClass("image-add-set").addClass("button btn-neutral").html("+ Set").appendTo($addToContainer),$("li#add-to-pool-list > a").addClass("image-add-pool").addClass("button btn-neutral").html("+ Pool").appendTo($addToContainer);const $noteToggleCountainer=$("<div>").attr("id","image-toggle-notes").insertAfter("div#image-add-links");$("<a>").attr({id:"image-note-button",href:"#"}).addClass("button btn-neutral").html(this.fetchSettings("hideNotes")?"Notes: Off":"Notes: On").appendTo($noteToggleCountainer).on("click",event=>{event.preventDefault(),this.toggleNotes()}),$("#note-container").css("display","").attr("data-hidden",this.fetchSettings("hideNotes"));$(".parent-children").insertAfter($("#search-box")),$("#add-fav-button").on("click",()=>{this.fetchSettings("upvoteOnFavorite")&&Danbooru_1.Danbooru.Post.vote(Post_1.Post.getViewingPost().getId(),1,!0),FavoriteCache_1.FavoriteCache.add(this.post.getId())}),$("#remove-fav-button").on("click",()=>{FavoriteCache_1.FavoriteCache.remove(this.post.getId())})}triggerUpvote(){Danbooru_1.Danbooru.Post.vote(Post_1.Post.getViewingPost().getId(),1)}triggerDownvote(){Danbooru_1.Danbooru.Post.vote(Post_1.Post.getViewingPost().getId(),-1)}toggleFavorite(){$("div.fav-buttons").hasClass("fav-buttons-false")?$("button#add-fav-button")[0].click():$("button#remove-fav-button")[0].click()}addFavorite(){$("div.fav-buttons").hasClass("fav-buttons-false")&&$("button#add-fav-button")[0].click()}removeFavorite(){$("div.fav-buttons").hasClass("fav-buttons-false")||$("button#remove-fav-button")[0].click()}async toggleNotes(){const module=ModuleController_1.ModuleController.get(PostViewer),hideNotes=module.fetchSettings("hideNotes");hideNotes?($("#note-container").attr("data-hidden","false"),$("a#image-note-button").html("Notes: ON")):($("#note-container").attr("data-hidden","true"),$("a#image-note-button").html("Notes: OFF")),await module.pushSettings("hideNotes",!hideNotes)}async switchNewNote(){$("#note-container").attr("data-hidden","false"),$("a#image-note-button").html("Notes: ON"),await ModuleController_1.ModuleController.get(PostViewer).pushSettings("hideNotes",!1),Danbooru_1.Danbooru.Note.TranslationMode.toggle(new Event("re621.dummy-event"))}addSet(){$("a#set")[0].click()}toggleSetLatest(){const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.toggleSet(lastSet,Post_1.Post.getViewingPost().getId()):Danbooru_1.Danbooru.error("Error: no set selected")}addSetLatest(){const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.addSet(lastSet,Post_1.Post.getViewingPost().getId()):Danbooru_1.Danbooru.error("Error: no set selected")}removeSetLatest(){const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.removeSet(lastSet,Post_1.Post.getViewingPost().getId()):Danbooru_1.Danbooru.error("Error: no set selected")}addSetCustom(dataKey){PostActions_1.PostActions.addSet(this.fetchSettings(dataKey),Post_1.Post.getViewingPost().getId())}addPool(){$("a#pool")[0].click()}}exports.PostViewer=PostViewer},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/cache/FavoriteCache":14,"../../components/data/Page":17,"../../components/data/Post":18,"../../components/data/PostActions":19}],51:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TitleCustomizer=void 0;const Page_1=require("../../components/data/Page"),Post_1=require("../../components/data/Post"),Tag_1=require("../../components/data/Tag"),RE6Module_1=require("../../components/RE6Module");class TitleCustomizer extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.post,!0)}getDefaultSettings(){return{enabled:!0,template:"#%postid% by %artist% (%copyright%) - %character%",symbolsEnabled:!0,symbolFav:"♥",symbolVoteUp:"↑",symbolVoteDown:"↓"}}create(){super.create(),this.post=Post_1.Post.getViewingPost(),this.refreshPageTitle()}refreshPageTitle(){document.title=this.parseTemplate()}parseTemplate(){let prefix="";return this.fetchSettings("symbolsEnabled")&&(this.post.getIsFaved()&&(prefix+=this.fetchSettings("symbolFav")),this.post.getIsUpvoted()?prefix+=this.fetchSettings("symbolVoteUp"):this.post.getIsDownvoted()&&(prefix+=this.fetchSettings("symbolVoteDown")),prefix&&(prefix+=" ")),prefix+this.fetchSettings("template").replace(/%postid%/g,this.post.getId().toString()).replace(/%artist%/g,this.post.getTagsFromType(Tag_1.TagTypes.Artist).filter(tag=>Tag_1.Tag.isArist(tag)).join(", ")).replace(/%copyright%/g,this.post.getTagsFromType(Tag_1.TagTypes.Copyright).join(", ")).replace(/%character%/g,this.post.getTagsFromType(Tag_1.TagTypes.Character).join(", ")).replace(/%species%/g,this.post.getTagsFromType(Tag_1.TagTypes.Species).join(", ")).replace(/%meta%/g,this.post.getTagsFromType(Tag_1.TagTypes.Meta).join(", ")).replace(/\(\)|( - )$/g,"").replace(/[ ]{2,}|^ | $/g,"")+" - "+Page_1.Page.getSiteName()}}exports.TitleCustomizer=TitleCustomizer},{"../../components/RE6Module":2,"../../components/data/Page":17,"../../components/data/Post":18,"../../components/data/Tag":21}],52:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.BlacklistEnhancer=void 0;const Danbooru_1=require("../../components/api/Danbooru"),Blacklist_1=require("../../components/data/Blacklist"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/data/Post"),User_1=require("../../components/data/User"),RE6Module_1=require("../../components/RE6Module");class BlacklistEnhancer extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.search,Page_1.PageDefintion.post],!0)}getDefaultSettings(){return{enabled:!0,quickaddTags:!0}}create(){super.create(),Danbooru_1.Danbooru.Blacklist.stub_vanilla_functions(),Danbooru_1.Danbooru.Blacklist.initialize_disable_all_blacklists(),$("#blacklisted-hider").remove(),BlacklistEnhancer.$box=$("section#blacklist-box"),BlacklistEnhancer.$list=$("#blacklist-list").html("");const $disableAllButton=$("#disable-all-blacklists").text("Disable all filters"),$enableAllbutton=$("#re-enable-all-blacklists").text("Enable all filters");$disableAllButton.off("click.danbooru").on("click.re621",()=>{for(const filter of Blacklist_1.Blacklist.get().values())filter.setEnabled(!1);BlacklistEnhancer.applyBlacklist(),$disableAllButton.hide(),$enableAllbutton.show()}),$enableAllbutton.off("click.danbooru").on("click.re621",()=>{for(const filter of Blacklist_1.Blacklist.get().values())filter.setEnabled(!0);BlacklistEnhancer.applyBlacklist(),$disableAllButton.show(),$enableAllbutton.hide()}),$disableAllButton.is(":visible")||$enableAllbutton.is(":visible")||$enableAllbutton[0].click(),!0===this.fetchSettings("quickaddTags")&&User_1.User.isLoggedIn()&&$("div.tag-actions span.tag-action-blacklist").each((index,element)=>{const $container=$(element);$("<a>").attr({href:"#",title:"Blacklist Tag"}).addClass("blacklist-tag-toggle").html('<i class="fas fa-times"></i>').prependTo($container).click(event=>{event.preventDefault(),BlacklistEnhancer.toggleBlacklistTag($container.parent().attr("data-tag"))})}),BlacklistEnhancer.applyBlacklist(),BlacklistEnhancer.on("updateSidebar.main",()=>{BlacklistEnhancer.updateSidebar()})}destroy(){super.destroy(),BlacklistEnhancer.off("updateSidebar.main")}static async toggleBlacklistTag(tagName){let currentBlacklist=(await User_1.User.getCurrentSettings()).blacklisted_tags.split("\n");return-1===currentBlacklist.indexOf(tagName)?(currentBlacklist.push(tagName),Blacklist_1.Blacklist.createFilter(tagName),Danbooru_1.Danbooru.notice(`Adding ${getTagLink(tagName)} to blacklist`)):(currentBlacklist=currentBlacklist.filter(e=>e!==tagName),Blacklist_1.Blacklist.deleteFilter(tagName),Danbooru_1.Danbooru.notice(`Removing ${getTagLink(tagName)} from blacklist`)),await User_1.User.setSettings({blacklisted_tags:currentBlacklist.join("\n")}),await BlacklistEnhancer.applyBlacklist(),Promise.resolve();function getTagLink(tagName){return tagName.startsWith("id:")?`<a href="/posts/${tagName.substr(3)}" target="_blank">${tagName}</a>`:`<a href="/wiki_pages/show_or_new?title=${tagName}">${tagName}</a>`}}static async applyBlacklist(){const posts=Post_1.Post.fetchPosts();for(const post of posts)post instanceof Post_1.ViewingPost||post.applyBlacklist();return this.updateSidebar(),Promise.resolve()}static async updateSidebar(){BlacklistEnhancer.$list.html("");const blacklist=Blacklist_1.Blacklist.get();let filtered=new Set;for(const[filterString,filter]of blacklist.entries())addSidebarEntry(filterString,filter),filtered=new Set([...filtered,...filter.getMatchesIds()]);function addSidebarEntry(filterString,filter){if(0===filter.getMatches())return!1;const $entry=$("<li>"),$link=$("<a>").text(filterString).addClass("blacklist-toggle-link").toggleClass("blacklisted-active",!filter.isEnabled()).attr({href:"/posts?tags="+encodeURIComponent(filterString),title:filterString,rel:"nofollow"}).appendTo($entry).on("click",event=>{event.preventDefault(),filter.toggleEnabled(),BlacklistEnhancer.applyBlacklist(),$link.toggleClass("blacklisted-active")});return $entry.append(" "),$("<span>").html(filter.getMatches()+"").addClass("post-count").appendTo($entry),BlacklistEnhancer.$list.append($entry),!0}0===filtered.size?BlacklistEnhancer.$box.hide():BlacklistEnhancer.$box.show(),$("#blacklisted-count").text("("+filtered.size+")")}}exports.BlacklistEnhancer=BlacklistEnhancer},{"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/data/Blacklist":15,"../../components/data/Page":17,"../../components/data/Post":18,"../../components/data/User":22}],53:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomFlagger=void 0;const Page_1=require("../../components/data/Page"),Post_1=require("../../components/data/Post"),PostFilter_1=require("../../components/data/PostFilter"),RE6Module_1=require("../../components/RE6Module");class CustomFlagger extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.post,Page_1.PageDefintion.search,Page_1.PageDefintion.favorites,Page_1.PageDefintion.popular],!0)}getDefaultSettings(){return{enabled:!0,flags:[]}}create(){const posts=Post_1.Post.fetchPosts();CustomFlagger.filters=new Map;for(const flag of this.fetchSettings("flags"))CustomFlagger.filters.get(flag.tags)||CustomFlagger.filters.set(flag.tags,{data:flag,filter:new PostFilter_1.PostFilter(flag.tags,!0)});Page_1.Page.matches(Page_1.PageDefintion.post)?this.createPostPage():posts.forEach(post=>{CustomFlagger.modifyThumbnail(post)})}createPostPage(){const viewingPost=Post_1.Post.getViewingPost(),flagContainer=$("<div>").insertAfter("div.input#tags-container");let activeFlags=0;CustomFlagger.filters.forEach(entry=>{entry.filter.addPost(viewingPost,!1),entry.filter.matchesPost(viewingPost)&&($("<div>").addClass("custom-flag").html(`<span class="custom-flag-title" style="--flag-color: ${entry.data.color}">${entry.data.name}</span> ${entry.data.tags}`).appendTo(flagContainer),activeFlags++)}),activeFlags>0&&$("<b>").html("Flags").addClass("display-block").prependTo(flagContainer)}static async modifyThumbnail(post){let $picture=post.getDomElement().find("picture");if(0==$picture.length){const $img=post.getDomElement().find("img");$picture=$("<picture>").insertAfter($img).append($img)}const flagContainer=$("<div>").addClass("flag-container").appendTo(post.getDomElement().find("picture"));CustomFlagger.filters.forEach(entry=>{entry.filter.addPost(post,!1),entry.filter.matchesPost(post)&&$("<span>").addClass("custom-flag-thumb").html(entry.data.name).css("--flag-color",entry.data.color).appendTo(flagContainer)})}}exports.CustomFlagger=CustomFlagger},{"../../components/RE6Module":2,"../../components/data/Page":17,"../../components/data/Post":18,"../../components/data/PostFilter":20}],54:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.InfiniteScroll=void 0;const Danbooru_1=require("../../components/api/Danbooru"),E621_1=require("../../components/api/E621"),PostHtml_1=require("../../components/api/PostHtml"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/data/Post"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module"),BlacklistEnhancer_1=require("./BlacklistEnhancer"),CustomFlagger_1=require("./CustomFlagger"),InstantSearch_1=require("./InstantSearch"),ThumbnailsEnhancer_1=require("./ThumbnailsEnhancer");class InfiniteScroll extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.search),this.scrollPaused=!1}getDefaultSettings(){return{enabled:!0,keepHistory:!1}}create(){super.create(),this.$postContainer=$("#posts-container"),this.$loadingIndicator=$("<div>").attr("id","re-infinite-scroll-loading").html('<i class="fas fa-circle-notch fa-5x fa-spin"></i>').insertAfter(this.$postContainer),this.$loadingIndicator.hide(),this.$nextButton=$("<a>").text("Load next").on("click",()=>{this.addMorePosts(!0)}),this.$nextButton.attr("id","re-infinite-scroll-next").addClass("text-center").insertAfter(this.$postContainer),this.currentQuery=null!==Page_1.Page.getQueryParameter("tags")?Page_1.Page.getQueryParameter("tags"):"";const keepHistory=this.fetchSettings("keepHistory");this.currentPage=keepHistory?parseInt(Page_1.Page.getQueryParameter("xpage"))||1:parseInt(Page_1.Page.getQueryParameter("page"))||1,this.isInProgress=!1,this.pagesLeft=!0,InfiniteScroll.on("pauseScroll.main",(event,scrollPaused)=>{void 0!==scrollPaused&&(this.scrollPaused=scrollPaused)}),$(async()=>{if(keepHistory){let processingPage=2;for(;processingPage<=this.currentPage;)await this.loadPage(processingPage,{scrollToPage:!0,lazyload:!1}),processingPage++;$("img.later-lazyload").removeClass("later-lazyload").addClass("lazyload")}let timer;$(window).scroll(()=>{timer||(timer=window.setTimeout(async()=>{await this.addMorePosts(),timer=null},1e3))})})}destroy(){super.destroy(),this.$nextButton.remove(),InfiniteScroll.off("pauseScroll.main")}async addMorePosts(override=!1){if(!this.isEnabled()||this.isInProgress||!this.pagesLeft||!this.shouldAddMore(override)||this.scrollPaused)return Promise.resolve(!1);const pageLoaded=await this.loadPage(this.currentPage+1);return pageLoaded&&(Page_1.Page.setQueryParameter((this.fetchSettings("keepHistory")?"x":"")+"page",(this.currentPage+1).toString()),this.currentPage++,InfiniteScroll.trigger("pageLoad")),Promise.resolve(pageLoaded)}async loadPage(page,options={scrollToPage:!1,lazyload:!0}){this.isInProgress=!0,this.$loadingIndicator.show();const posts=await E621_1.E621.Posts.get({tags:this.currentQuery,page:page},500);if(0===posts.length)return this.pagesLeft=!1,this.$loadingIndicator.hide(),this.$nextButton.hide(),Danbooru_1.Danbooru.notice("No more posts!"),Promise.resolve(!1);const keepHistory=this.fetchSettings("keepHistory");$("<a>").attr({href:document.location.href+"#"+(keepHistory?"x":"")+"page-link-"+page,id:(keepHistory?"x":"")+"page-link-"+page}).addClass("instantsearch-seperator").html("<h2>Page: "+page+"</h2>").appendTo(this.$postContainer),options.scrollToPage&&$([document.documentElement,document.body]).animate({scrollTop:$("a#"+(keepHistory?"x":"")+"page-link-"+page).offset().top},"0");const thumbnailEnhancer=ModuleController_1.ModuleController.get(ThumbnailsEnhancer_1.ThumbnailEnhancer),upscaleMode=thumbnailEnhancer.fetchSettings("upscale"),preserveHoverText=thumbnailEnhancer.fetchSettings("preserveHoverText"),promises=[];for(const json of posts)promises.push(new Promise(resolve=>{const element=PostHtml_1.PostHtml.create(json,options.lazyload,upscaleMode===ThumbnailsEnhancer_1.ThumbnailPerformanceMode.Always),post=new Post_1.Post(element);void 0!==post.getImageURL()&&(Post_1.Post.appendPost(post),post.applyBlacklist(),this.$postContainer.append(element),ThumbnailsEnhancer_1.ThumbnailEnhancer.modifyThumbnail(element,upscaleMode,preserveHoverText),CustomFlagger_1.CustomFlagger.modifyThumbnail(post)),resolve()}));return Promise.all(promises).then(()=>{this.isInProgress=!1,this.$loadingIndicator.hide(),BlacklistEnhancer_1.BlacklistEnhancer.trigger("updateSidebar"),InstantSearch_1.InstantSearch.trigger("applyFilter")}),Promise.resolve(!0)}shouldAddMore(override){return $(window).scrollTop()+$(window).height()>$(document).height()-50||override}}exports.InfiniteScroll=InfiniteScroll},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/api/E621":5,"../../components/api/PostHtml":6,"../../components/data/Page":17,"../../components/data/Post":18,"./BlacklistEnhancer":52,"./CustomFlagger":53,"./InstantSearch":55,"./ThumbnailsEnhancer":58}],55:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.InstantSearch=void 0;const Page_1=require("../../components/data/Page"),Post_1=require("../../components/data/Post"),PostFilter_1=require("../../components/data/PostFilter"),RE6Module_1=require("../../components/RE6Module");class InstantSearch extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.search,!0)}getDefaultSettings(){return{enabled:!0}}create(){let typingTimeout;super.create(),this.createDOM(),this.$searchbox.on("input",()=>{clearTimeout(typingTimeout),typingTimeout=window.setTimeout(()=>{this.applyFilter()},500)}),this.$searchbox.trigger("input"),InstantSearch.on("applyFilter.main",()=>{this.applyFilter()})}destroy(){super.destroy(),this.$searchbox.val(""),this.applyFilter(),$("section#re-instantsearch").remove(),InstantSearch.off("applyFilter.main")}applyFilter(){const filterText=this.$searchbox.val().toString().trim(),filter=new PostFilter_1.PostFilter(filterText);sessionStorage.setItem("re-instantsearch",filterText);const posts=Post_1.Post.fetchPosts();if(""===filterText)for(const post of posts)post.show();else for(const post of posts)filter.addPost(post,!0)?post.show():post.hide()}createDOM(){const $section=$("<section>").attr("id","re-instantsearch").html("<h1>Filter</h1>").insertAfter("section#search-box"),$searchForm=$("<form>").appendTo($section);this.$searchbox=$("<input>").attr("id","re-instantsearch-input").attr("type","text").val(sessionStorage.getItem("re-instantsearch")).appendTo($searchForm),$("<button>").attr("type","submit").html('<i class="fas fa-search"></i>').appendTo($searchForm)}}exports.InstantSearch=InstantSearch},{"../../components/RE6Module":2,"../../components/data/Page":17,"../../components/data/Post":18,"../../components/data/PostFilter":20}],56:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostSuggester=void 0;const E621_1=require("../../components/api/E621"),APIPost_1=require("../../components/api/responses/APIPost"),Page_1=require("../../components/data/Page"),User_1=require("../../components/data/User"),RE6Module_1=require("../../components/RE6Module"),Modal_1=require("../../components/structure/Modal");class PostSuggester extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefintion.search)}getDefaultSettings(){return{enabled:!0}}create(){if(super.create(),!User_1.User.isLoggedIn())return;const listItem=$("<li>").appendTo("ul#related-list"),button=$("<a>").html("Recommended").appendTo(listItem),modalContent=$("<div>").addClass("post-suggester");this.status=$("<div>").addClass("post-suggester-status").appendTo(modalContent),this.content=$("<div>").addClass("post-suggester-content").appendTo(modalContent);const modal=new Modal_1.Modal({title:"Post Recommendations",triggers:[{element:button}],fixed:!0,content:modalContent,position:{my:"center",at:"center"}});let triggered=!1;modal.getElement().on("dialogopen",()=>{triggered||(triggered=!0,this.handleRecommendation())})}async handleRecommendation(){this.status.html("Compiling favorites data");const data={};let result;for(let i=1;i<=PostSuggester.maxPages&&(this.status.html(`Analyzing favorites [ ${i} / ${PostSuggester.maxPages} ]`),result=await E621_1.E621.Posts.get({tags:"fav:"+User_1.User.getUsername(),page:i,limit:320},500),result.forEach(post=>{APIPost_1.APIPost.getTags(post).forEach(tag=>{data[tag]?data[tag]=data[tag]+1:data[tag]=1})}),320===result.length);i++);this.status.html("Lookup complete");let processedData=[];for(const tag in data)processedData.push([tag,data[tag]]);processedData=processedData.sort((a,b)=>b[1]-a[1]);for(let year=1973;year<=(new Date).getFullYear();year++)PostSuggester.removedTags.push(year+"");processedData=processedData.filter(entry=>!PostSuggester.removedTags.includes(entry[0])&&entry[1]>PostSuggester.minTagCount),processedData.length>100&&(processedData.length=100),this.content[0].innerHTML="";let checkedNum=0,shouldCheck=!0;for(const[tag,count]of processedData){const container=$("<span>").appendTo(this.content);shouldCheck=checkedNum<10&&!PostSuggester.ignoredTags.includes(tag),shouldCheck&&checkedNum++,$("<input>").attr({type:"checkbox",name:"post-suggester-selector",value:tag,id:"tag-"+tag,"data-tag":tag,"data-count":count}).prop("checked",shouldCheck).appendTo(container),$("<label>").attr({for:"tag-"+tag}).html(tag.replace(/_/g," ")).appendTo(container),$("<a>").attr("href","/posts?tags="+tag).html("?").appendTo(container),$("<span>").addClass("tag-count").html(""+count).appendTo(container)}return this.status[0].innerHTML="",$("<a>").html("Search").addClass("button btn-neutral post-suggester-search").appendTo(this.status).click(event=>{event.preventDefault();const checkedEls=$("input[name=post-suggester-selector]:checked").get(),query=[];for(const checkedEl of checkedEls)query.push("~"+encodeURIComponent($(checkedEl).attr("data-tag")));query.push(encodeURIComponent("order:random")),query.push(encodeURIComponent("score:>10")),window.location.href="/posts?tags="+query.join("+")}),Promise.resolve(!0)}}exports.PostSuggester=PostSuggester,PostSuggester.maxPages=5,PostSuggester.minTagCount=10,PostSuggester.removedTags=["hi_res","absurd_res","digital_media_(artwork)","solo","duo","group","simple_background","detailed_background","text","english_text"],PostSuggester.ignoredTags=["male","female","intersex","mammal","scalie","biped","anthro","feral","genitals","penis","balls","animal_genitalia","humanoid_penis","erection","pussy","butt","anus","breasts","nipples","non-mammal_breasts","genital_fluids","bodily_fluids","cum","wings","membrane_(anatomy)","membranous_wings","claws","horn","scales","teeth","smile","tongue","feathers","toes","hair","fur","clothing","clothed","nude","sex","penetration","male_penetrating"]},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/api/responses/APIPost":12,"../../components/data/Page":17,"../../components/data/User":22,"../../components/structure/Modal":25}],57:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SearchUtilities=void 0;const Danbooru_1=require("../../components/api/Danbooru"),FavoriteCache_1=require("../../components/cache/FavoriteCache"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module");class SearchUtilities extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.search,Page_1.PageDefintion.post,Page_1.PageDefintion.favorites]),this.registerHotkeys({keys:"hotkeyFocusSearch",fnct:this.focusSearchbar},{keys:"hotkeyRandomPost",fnct:this.randomPost},{keys:"hotkeySwitchModeView",fnct:this.switchModeView},{keys:"hotkeySwitchModeEdit",fnct:this.switchModeEdit},{keys:"hotkeySwitchModeAddFav",fnct:this.switchModeAddFav},{keys:"hotkeySwitchModeRemFav",fnct:this.switchModeRemFav},{keys:"hotkeySwitchModeAddSet",fnct:this.switchModeAddSet},{keys:"hotkeySwitchModeRemSet",fnct:this.switchModeRemSet})}getDefaultSettings(){return{enabled:!0,improveTagCount:!0,shortenTagNames:!0,hidePlusMinusIcons:!1,collapseCategories:!0,categoryData:[],persistentTags:"",hotkeyFocusSearch:"q",hotkeyRandomPost:"r",hotkeySwitchModeView:"",hotkeySwitchModeEdit:"",hotkeySwitchModeAddFav:"",hotkeySwitchModeRemFav:"",hotkeySwitchModeAddSet:"",hotkeySwitchModeRemSet:""}}create(){if(super.create(),Page_1.Page.matches(Page_1.PageDefintion.search)){const searchbox=$("section#search-box input");""==searchbox.val()&&searchbox.focus()}Page_1.Page.matches(Page_1.PageDefintion.post)&&this.removeSearchQueryString(),Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.post])&&(this.improveTagCount(this.fetchSettings("improveTagCount")),this.shortenTagNames(this.fetchSettings("shortenTagNames")),this.hidePlusMinusIcons(this.fetchSettings("hidePlusMinusIcons"))),!0===this.fetchSettings("collapseCategories")&&Page_1.Page.matches(Page_1.PageDefintion.post)&&this.collapseTagCategories();const persistentTags=this.fetchSettings("persistentTags").trim().toLowerCase();if(""!==persistentTags&&Page_1.Page.matches([Page_1.PageDefintion.search,Page_1.PageDefintion.post,Page_1.PageDefintion.favorites])){const $tagInput=$("input#tags");$tagInput.val(($tagInput.val()+"").replace(persistentTags,"")),$("section#search-box form").on("submit",()=>($tagInput.val($tagInput.val()+" "+persistentTags),!0))}$(".post-preview a").on("click.danbooru",event=>{const mode=$("#mode-box-mode").val(),postID=$(event.target).closest("article").data("id");switch(mode){case"add-fav":FavoriteCache_1.FavoriteCache.add(postID);break;case"remove-fav":FavoriteCache_1.FavoriteCache.remove(postID)}})}removeSearchQueryString(){Page_1.Page.removeQueryParameter("q")}async improveTagCount(state=!0){const source=state?"data-count":"data-count-short";$("span.re621-post-count").each((function(index,element){const tag=$(element);tag.text(tag.attr(source))}))}shortenTagNames(state=!0){$("section#tag-box, section#tag-list").attr("data-shorten-tagnames",state+"")}hidePlusMinusIcons(state=!0){$("section#tag-box, section#tag-list").attr("data-hide-plusminus",state+"")}async collapseTagCategories(){let storedCats=new Set(await this.fetchSettings("categoryData",!0));for(const element of $("section#tag-list .tag-list-header").get()){const $header=$(element),cat=$header.attr("data-category");storedCats.has(cat)&&$header.get(0).click(),$header.on("click.danbooru",async()=>{storedCats=new Set(await this.fetchSettings("categoryData",!0)),$header.hasClass("hidden-category")?storedCats.add(cat):storedCats.delete(cat),await this.pushSettings("categoryData",Array.from(storedCats))})}}focusSearchbar(event){event.preventDefault(),$("section#search-box input").focus()}randomPost(){location.pathname="/posts/random"}switchModeView(){SearchUtilities.switchMode("view")}switchModeEdit(){SearchUtilities.switchMode("edit")}switchModeAddFav(){SearchUtilities.switchMode("add-fav")}switchModeRemFav(){SearchUtilities.switchMode("remove-fav")}switchModeAddSet(){SearchUtilities.switchMode("add-to-set"),$("#set-id").focus()}switchModeRemSet(){SearchUtilities.switchMode("remove-from-set"),$("#set-id").focus()}static switchMode(mode){$("select#mode-box-mode").val(mode),Danbooru_1.Danbooru.PostModeMenu.change()}}exports.SearchUtilities=SearchUtilities},{"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/cache/FavoriteCache":14,"../../components/data/Page":17}],58:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ThumbnailEnhancer=exports.ThumbnailZoomMode=exports.ThumbnailClickAction=exports.ThumbnailPerformanceMode=void 0;const Danbooru_1=require("../../components/api/Danbooru"),E621_1=require("../../components/api/E621"),XM_1=require("../../components/api/XM"),FavoriteCache_1=require("../../components/cache/FavoriteCache"),Page_1=require("../../components/data/Page"),PostActions_1=require("../../components/data/PostActions"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),Util_1=require("../../components/utility/Util"),BlacklistEnhancer_1=require("./BlacklistEnhancer");var ThumbnailPerformanceMode,ThumbnailClickAction,ThumbnailZoomMode;!function(ThumbnailPerformanceMode){ThumbnailPerformanceMode.Disabled="disabled",ThumbnailPerformanceMode.Hover="hover",ThumbnailPerformanceMode.Always="always"}(ThumbnailPerformanceMode=exports.ThumbnailPerformanceMode||(exports.ThumbnailPerformanceMode={})),function(ThumbnailClickAction){ThumbnailClickAction.Disabled="disabled",ThumbnailClickAction.NewTab="newtab",ThumbnailClickAction.CopyID="copyid",ThumbnailClickAction.Blacklist="blacklist",ThumbnailClickAction.AddToSet="addtoset",ThumbnailClickAction.ToggleSet="toggleset"}(ThumbnailClickAction=exports.ThumbnailClickAction||(exports.ThumbnailClickAction={})),function(ThumbnailZoomMode){ThumbnailZoomMode.Enabled="true",ThumbnailZoomMode.Disabled="false",ThumbnailZoomMode.OnShift="onshift"}(ThumbnailZoomMode=exports.ThumbnailZoomMode||(exports.ThumbnailZoomMode={}));class ThumbnailEnhancer extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefintion.search,Page_1.PageDefintion.popular,Page_1.PageDefintion.favorites,Page_1.PageDefintion.comments],!0)}getDefaultSettings(){return{enabled:!0,upscale:ThumbnailPerformanceMode.Hover,zoom:ThumbnailZoomMode.Disabled,zoomScale:"2",zoomContextual:!0,vote:!0,fav:!1,favSync:0,favReq:!0,crop:!0,cropSize:"150px",cropRatio:"0.9",cropPreserveRatio:!1,autoPlayGIFs:!0,ribbons:!0,relRibbons:!0,preserveHoverText:!1,clickAction:ThumbnailClickAction.NewTab}}async prepare(){await super.prepare(),"boolean"==typeof this.fetchSettings("zoom")&&await this.pushSettings("zoom",this.fetchSettings("zoom")+""),ThumbnailEnhancer.clickAction=this.fetchSettings("clickAction"),ThumbnailEnhancer.autoPlayGIFs=this.fetchSettings("autoPlayGIFs"),this.pageMatchesFilter()&&(this.postsLoading=$("<div>").attr("id","postContainerOverlay").html('\n                <span>\n                    <div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>\n                </span>\n            ').insertBefore("#posts"))}create(){super.create(),this.postContainer=$("#page");const upscaleMode=this.fetchSettings("upscale"),preserveHoverText=this.fetchSettings("preserveHoverText"),thumbnails=this.postContainer.find("article.post-preview, div.post-preview").get();for(const thumb of thumbnails)ThumbnailEnhancer.modifyThumbnail($(thumb),upscaleMode,preserveHoverText);this.toggleHoverZoom(this.fetchSettings("zoom")),this.setZoomScale(this.fetchSettings("zoomScale")),this.toggleZoomContextual(this.fetchSettings("zoomContextual")),this.toggleHoverVote(this.fetchSettings("vote")),this.toggleHoverFav(this.fetchSettings("fav")),this.toggleThumbCrop(this.fetchSettings("crop")),this.setThumbSize(this.fetchSettings("cropSize")),this.setThumbRatio(this.fetchSettings("cropRatio")),this.toggleThumbPreserveRatio(this.fetchSettings("cropPreserveRatio")),this.toggleStatusRibbons(this.fetchSettings("ribbons")),this.toggleRelationRibbons(this.fetchSettings("relRibbons")),this.postsLoading.addClass("display-none-important"),ThumbnailEnhancer.on("pauseHoverActions.main",(event,zoomPaused)=>{if(void 0!==zoomPaused){if(zoomPaused)$("#page").attr({"data-thumb-zoom":"false","data-thumb-vote":"false"});else{const module=ModuleController_1.ModuleController.get(ThumbnailEnhancer);$("#page").attr({"data-thumb-zoom":module.fetchSettings("zoom"),"data-thumb-vote":module.fetchSettings("vote")})}ThumbnailEnhancer.zoomPaused=zoomPaused}})}destroy(){super.destroy(),ThumbnailEnhancer.off("pauseHoverActions.main")}toggleHoverZoom(state=ThumbnailZoomMode.Disabled){if(this.postContainer.attr("data-thumb-zoom",state),$(document).off("keydown.re621.thumbnailzoom").off("keyup.re621.thumbnailzoom"),state!==ThumbnailZoomMode.OnShift)return;let keydown=!1;$(document).on("keydown.re621.thumbnailzoom",null,"shift",()=>{keydown||(keydown=!0,this.postContainer.attr("data-thumb-zoom",ThumbnailZoomMode.Enabled))}).on("keyup.re621.thumbnailzoom",null,"shift",()=>{keydown=!1,this.postContainer.attr("data-thumb-zoom",ThumbnailZoomMode.OnShift)})}setZoomScale(scale){this.postContainer.css("--thumbnail-zoom",scale)}toggleZoomContextual(state=!0){this.postContainer.attr("data-thumb-zoom-context",state+"")}toggleHoverVote(state=!0){this.postContainer.attr("data-thumb-vote",state+"")}toggleHoverFav(state=!0){this.postContainer.attr("data-thumb-fav",state+"")}toggleThumbCrop(state=!0){this.postContainer.attr("data-thumb-crop",state+"")}setThumbSize(size){this.postContainer.css("--thumbnail-size",size)}setThumbRatio(ratio){this.postContainer.css("--thumbnail-ratio",ratio)}toggleThumbPreserveRatio(state=!0){this.postContainer.attr("data-thumb-preserve-ratio",state+"")}toggleStatusRibbons(state=!0){this.postContainer.attr("data-thumb-ribbons",state+"")}toggleRelationRibbons(state=!0){this.postContainer.attr("data-thumb-rel-ribbons",state+"")}static getClickAction(){return ThumbnailEnhancer.clickAction}static async setClickAction(state){return ThumbnailEnhancer.clickAction=state,ModuleController_1.ModuleController.get(ThumbnailEnhancer).pushSettings("clickAction",state)}static setAutoPlayGIFs(state){ThumbnailEnhancer.autoPlayGIFs=state}static async modifyThumbnail($article,upscaleMode=ThumbnailPerformanceMode.Hover,preserveHoverText){const $link=$article.find("a").first(),postID=parseInt($article.attr("data-id")),$img=$article.find("img"),$imgData=$img.attr("title")?$img.attr("title").split("\n").slice(0,-2):[];$article.find("source").remove(),preserveHoverText||$img.removeAttr("title"),$img.attr("alt","#"+$article.attr("data-id"));let $picture=$article.find("picture");if(0==$picture.length){const $img=$article.find("img");$picture=$("<picture>").insertAfter($img).append($img)}$link.addClass("preview-box"),$("<div>").addClass("preview-load").html('<i class="fas fa-circle-notch fa-2x fa-spin"></i>').appendTo($link);let isFavorited=FavoriteCache_1.FavoriteCache.has(postID);$article.attr("data-is-favorited",isFavorited+""),$picture.addClass("picture-container");const state=$("<div>").addClass("rel-ribbon").append($("<span>")).appendTo($picture);let stateText="";$article.hasClass("post-status-has-children")&&(state.addClass("thumb-ribbon thumb-ribbon-has-children"),stateText+="Child posts\n"),$article.hasClass("post-status-has-parent")&&(state.addClass("thumb-ribbon thumb-ribbon-has-parent"),stateText+="Parent posts\n"),state.hasClass("thumb-ribbon")?state.addClass("left").attr("title",stateText):state.remove();const ribbon=$("<div>").addClass("flag-ribbon").append($("<span>")).appendTo($picture);let ribbonText="";$article.hasClass("post-status-flagged")&&(ribbon.addClass("thumb-ribbon thumb-ribbon-flagged"),ribbonText+="Flagged\n"),$article.hasClass("post-status-pending")&&(ribbon.addClass("thumb-ribbon thumb-ribbon-pending"),ribbonText+="Pending\n"),ribbon.hasClass("thumb-ribbon")?ribbon.addClass("right").attr("title",ribbonText):ribbon.remove();const $extrasBox=$("<div>").addClass("bg-highlight preview-extras").appendTo($picture);void 0===$imgData[4]?$("<span>").html("Score: ?").appendTo($extrasBox):$("<span>").html($imgData[4]).appendTo($extrasBox),void 0===$imgData[0]?$("<span>").html("unknown").appendTo($extrasBox):$("<span>").html(function(input){switch(input){case"Rating: e":return"Explicit";case"Rating: q":return"Questionable";case"Rating: s":return"Safe";default:return"Unknown"}}($imgData[0])).appendTo($extrasBox),void 0===$imgData[2]?$("<span>").html("unknown").appendTo($extrasBox):$("<span>").html(function(input){const date=new Date(input.split(": ").pop().replace(" ","T").replace(" ",""));return'<span title="'+date.toLocaleString()+'">'+Util_1.Util.Time.ago(date)+"</span>"}($imgData[2])).appendTo($extrasBox);let buttonBlock=!1;const $voteBox=$("<div>").addClass("preview-voting").appendTo($link);$("<button>").attr("href","#").html('<i class="far fa-thumbs-up"></i>').addClass("button voteButton vote post-vote-up-"+postID+" score-neutral").appendTo($voteBox).click(event=>{event.preventDefault(),buttonBlock||(buttonBlock=!0,Danbooru_1.Danbooru.Post.vote(postID,1),buttonBlock=!1)}),$("<button>").attr("href","#").html('<i class="far fa-thumbs-down"></i>').addClass("button voteButton vote post-vote-down-"+postID+" score-neutral").appendTo($voteBox).click(event=>{event.preventDefault(),buttonBlock||(buttonBlock=!0,Danbooru_1.Danbooru.Post.vote(postID,-1),buttonBlock=!1)});const $favorite=$("<button>").attr("href","#").html('<i class="far fa-star"></i>').addClass("button voteButton fav post-favorite-"+postID+" score-neutral"+(isFavorited?" score-favorite":"")).appendTo($voteBox).click(async event=>{event.preventDefault(),buttonBlock||(buttonBlock=!0,isFavorited?(isFavorited=!1,E621_1.E621.Favorite.id(postID).delete(),FavoriteCache_1.FavoriteCache.remove(postID),$favorite.removeClass("score-favorite")):(isFavorited=!0,E621_1.E621.Favorites.post({post_id:postID}),FavoriteCache_1.FavoriteCache.add(postID),$favorite.addClass("score-favorite")),$article.attr("data-is-favorited",isFavorited+""),buttonBlock=!1)});if(ThumbnailEnhancer.clickAction!==ThumbnailClickAction.Disabled){let dbclickTimer;const delay=200;let prevent=!1;$link.on("click.re621.thumbnail",event=>{console.log("click"),0!==event.button||event.shiftKey||event.ctrlKey||event.altKey||event.metaKey||ThumbnailEnhancer.zoomPaused||$(event.target).hasClass("voteButton")||$(event.target).parent().hasClass("voteButton")||"view"!==$("#mode-box-mode").val()||(event.preventDefault(),dbclickTimer=window.setTimeout(()=>{prevent||($link.off("click.re621.thumbnail"),$link[0].click()),prevent=!1},delay))}).on("dblclick.re621.thumbnail",event=>{if(!(0!==event.button||event.shiftKey||event.ctrlKey||event.altKey||event.metaKey||ThumbnailEnhancer.zoomPaused||$(event.target).hasClass("voteButton")||$(event.target).parent().hasClass("voteButton")||"view"!==$("#mode-box-mode").val()))switch(event.preventDefault(),window.clearTimeout(dbclickTimer),prevent=!0,$article.addClass("highlight"),window.setTimeout(()=>$article.removeClass("highlight"),250),ThumbnailEnhancer.clickAction){case ThumbnailClickAction.NewTab:XM_1.XM.Util.openInTab(window.location.origin+$link.attr("href"),!1);break;case ThumbnailClickAction.CopyID:Danbooru_1.Danbooru.notice(`Copied post ID to clipboard: <a href="/posts/${postID}" target="_blank">#${postID}</a>`),XM_1.XM.Util.setClipboard($article.attr("data-id"),"text");break;case ThumbnailClickAction.Blacklist:BlacklistEnhancer_1.BlacklistEnhancer.toggleBlacklistTag("id:"+postID);break;case ThumbnailClickAction.AddToSet:{const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.addSet(lastSet,postID):Danbooru_1.Danbooru.error("Error: no set selected");break}case ThumbnailClickAction.ToggleSet:{const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.toggleSet(lastSet,postID):Danbooru_1.Danbooru.error("Error: no set selected");break}default:$link.off("click.re621.thumbnail"),$link[0].click()}})}if("swf"===$article.attr("data-file-ext")||$article.attr("data-flags").includes("deleted"))$("<img>").attr("src",DomUtilities_1.DomUtilities.getPlaceholderImage()).css("--native-ratio",1).addClass("re621-placeholder-replacer resized").appendTo($picture),$img.addClass("re621-placeholder-default"),$picture.addClass("color-text post-placeholder"),"swf"===$article.attr("data-file-ext")&&$picture.addClass("flash"),"deleted"===$article.attr("data-flags")&&$picture.addClass("deleted");else if("gif"!==$article.attr("data-file-ext")||upscaleMode!==ThumbnailPerformanceMode.Always||ThumbnailEnhancer.autoPlayGIFs){const sampleURL=$article.attr("data-large-file-url");if(upscaleMode===ThumbnailPerformanceMode.Hover){let timer;resolveRatio(),$article.on("mouseenter",()=>{ThumbnailEnhancer.zoomPaused||(timer=window.setTimeout(()=>{$img.attr("data-src")!=sampleURL&&($link.addClass("loading"),$img.attr("data-src",sampleURL).addClass("lazyload").one("lazyloaded",()=>{$link.removeClass("loading"),$article.addClass("loaded")}))},200))}),$article.on("mouseleave",()=>{window.clearTimeout(timer)})}else upscaleMode===ThumbnailPerformanceMode.Always?($link.addClass("loading"),$img.attr("data-src",sampleURL).addClass($img.hasClass("later-lazyload")?"":"lazyload").one("lazyloaded",()=>{resolveRatio(),$link.removeClass("loading"),$article.addClass("loaded")})):resolveRatio()}else{const sampleURL=$article.attr("data-large-file-url");let timer;resolveRatio(),$article.on("mouseenter",()=>{ThumbnailEnhancer.zoomPaused||(timer=window.setTimeout(()=>{$img.attr("data-src")!=sampleURL&&($link.addClass("loading"),$img.attr("data-src",sampleURL).addClass("lazyload").one("lazyloaded",()=>{$link.removeClass("loading"),$article.addClass("loaded")}))},200))}),$article.on("mouseleave",()=>{window.clearTimeout(timer)})}function resolveRatio(force=!1){!force&&$img.hasClass("resized")||($img.css("--native-ratio",$img.height()/$img.width()),$img.addClass("resized"))}}}exports.ThumbnailEnhancer=ThumbnailEnhancer,ThumbnailEnhancer.zoomPaused=!1,ThumbnailEnhancer.clickAction="unset",ThumbnailEnhancer.autoPlayGIFs=!1},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/api/E621":5,"../../components/api/XM":7,"../../components/cache/FavoriteCache":14,"../../components/data/Page":17,"../../components/data/PostActions":19,"../../components/structure/DomUtilities":23,"../../components/utility/Util":32,"./BlacklistEnhancer":52}],59:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CommentTracker=void 0;const E621_1=require("../../components/api/E621"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/data/Post"),User_1=require("../../components/data/User"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),SubscriptionTracker_1=require("./SubscriptionTracker");class CommentTracker extends RE6Module_1.RE6Module{constructor(){super(),this.updateActions={imageSrc:data=>Post_1.Post.createPreviewUrlFromMd5(data.md5),imageHref:data=>"/posts/"+data.extra.parent,imageRemoveOnError:!0,updateHref:data=>"/users/"+data.extra.author,updateText:data=>data.name,sourceHref:data=>`/posts/${data.extra.parent}#comment-${data.id}`,sourceText:()=>"Reply"},this.subBatchSize=100,this.maxSubscriptions=500,this.cache=new SubscriptionTracker_1.UpdateCache(this)}getDefaultSettings(){return{enabled:!0,data:{}}}getName(){return"Comments"}makeSubscribeButton(){return $("<button>").addClass("large-subscribe-button subscribe").addClass("button btn-success").html("Subscribe")}makeUnsubscribeButton(){return $("<button>").addClass("large-subscribe-button unsubscribe").addClass("button btn-danger").html("Unsubscribe")}getButtonAttachment(){return Page_1.Page.matches(Page_1.PageDefintion.post)?$("menu#post-sections").first():$()}insertButton($element,$button){$element.append($button)}getSubscriberId(){return Page_1.Page.getPageID()}getSubscriberName(){return"#"+$("section#image-container").attr("data-id")}getCache(){return this.cache}async getUpdatedEntries(lastUpdate,status){const results={};status.append("<div>. . . retrieving settings</div>");const storedSubs=await this.fetchSettings("data",!0);if(0===Object.keys(storedSubs).length)return results;status.append("<div>. . . sending an API request</div>"),status.append("<div>&nbsp; &nbsp; &nbsp; fetching posts</div>");const storedSubChunks=Util_1.Util.chunkArray(Object.keys(storedSubs),this.subBatchSize),postsJSON=[];for(const[index,chunk]of storedSubChunks.entries())storedSubChunks.length>1&&status.append(`<div>&nbsp; &nbsp; &nbsp; - processing batch #${index}</div>`),postsJSON.push(...await E621_1.E621.Posts.get({tags:"id:"+chunk.join(",")},500));status.append("<div>&nbsp; &nbsp; &nbsp; fetching comments</div>");const commentsJSON=[];for(const[index,chunk]of storedSubChunks.entries())storedSubChunks.length>1&&status.append(`<div>&nbsp; &nbsp; &nbsp; - processing batch #${index}</div>`),commentsJSON.push(...await E621_1.E621.Comments.get({group_by:"comment","search[post_id]":chunk.join(",")},500));status.append("<div>. . . processing data</div>");const posts=new Map;postsJSON.forEach(post=>{posts.set(post.id,post)});const data=new Map;commentsJSON.forEach(value=>{(void 0===data.get(value.post_id)||data.get(value.post_id).created_at<value.created_at)&&data.set(value.post_id,value)}),status.append("<div>. . . formatting output</div>");for(const comment of data.values())new Date(comment.created_at).getTime()>lastUpdate&&comment.updater_id!==User_1.User.getUserID()&&(results[new Date(comment.created_at).getTime()]=await this.formatCommentUpdate(comment,posts.get(comment.post_id))),storedSubs[comment.post_id].name="#"+comment.post_id;return status.append("<div>. . . outputting results</div>"),await this.pushSettings("data",storedSubs),results}async formatCommentUpdate(value,post){const body=Util_1.Util.parseDText(value.body);return{id:value.id,name:value.creator_name,nameExtra:body.length>256?body.substr(0,255)+"&hellip;":body,md5:"swf"===post.file.ext?"":post.file.md5,extra:{parent:post.id,author:value.creator_id},new:!0}}}exports.CommentTracker=CommentTracker},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/data/Page":17,"../../components/data/Post":18,"../../components/data/User":22,"../../components/utility/Util":32,"./SubscriptionTracker":63}],60:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ForumTracker=void 0;const E621_1=require("../../components/api/E621"),Page_1=require("../../components/data/Page"),User_1=require("../../components/data/User"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),SubscriptionTracker_1=require("./SubscriptionTracker");class ForumTracker extends RE6Module_1.RE6Module{constructor(){super(),this.updateActions={imageSrc:()=>"",updateHref:data=>`/forum_topics/${data.id}?page=${Math.ceil(data.extra.count/75)}`,updateText:data=>data.name,sourceHref:data=>"/forum_topics/"+data.id,sourceText:()=>"First Page"},this.subBatchSize=100,this.maxSubscriptions=500,this.cache=new SubscriptionTracker_1.UpdateCache(this)}getDefaultSettings(){return{enabled:!0,data:{}}}getName(){return"Forums"}makeSubscribeButton(){return $("<button>").addClass("large-subscribe-button subscribe").addClass("button btn-success").html("Subscribe")}makeUnsubscribeButton(){return $("<button>").addClass("large-subscribe-button unsubscribe").addClass("button btn-danger").html("Unsubscribe")}getButtonAttachment(){return Page_1.Page.matches(Page_1.PageDefintion.forumPost)?$("#c-forum-topics").first():$()}insertButton($element,$button){$element.prepend($button)}getSubscriberId(){return Page_1.Page.getPageID()}getSubscriberName(){return $("div#c-forum-topics div#a-show h1").first().text().trim().replace("Topic: ","")}getCache(){return this.cache}async getUpdatedEntries(lastUpdate,status){const results={};status.append("<div>. . . retrieving settings</div>");const storedSubs=await this.fetchSettings("data",!0);if(0===Object.keys(storedSubs).length)return results;status.append("<div>. . . sending an API request</div>");const storedSubChunks=Util_1.Util.chunkArray(Object.keys(storedSubs),this.subBatchSize),apiData=[];for(const[index,chunk]of storedSubChunks.entries())storedSubChunks.length>1&&status.append(`<div>&nbsp; &nbsp; &nbsp; - processing batch #${index}</div>`),apiData.push(...await E621_1.E621.ForumTopics.get({"search[id]":chunk.join(",")},500));status.append("<div>. . . formatting output</div>");for(const forumJson of apiData)new Date(forumJson.updated_at).getTime()>lastUpdate&&forumJson.updater_id!==User_1.User.getUserID()&&(results[new Date(forumJson.updated_at).getTime()]=await this.formatForumUpdate(forumJson)),storedSubs[forumJson.id].name=forumJson.title.replace(/_/g," ");return status.append("<div>. . . outputting results</div>"),await this.pushSettings("data",storedSubs),results}async formatForumUpdate(value){return{id:value.id,name:value.title,md5:"",extra:{count:value.response_count},new:!0}}}exports.ForumTracker=ForumTracker},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/data/Page":17,"../../components/data/User":22,"../../components/utility/Util":32,"./SubscriptionTracker":63}],61:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PoolTracker=void 0;const E621_1=require("../../components/api/E621"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/data/Post"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),SubscriptionTracker_1=require("./SubscriptionTracker");class PoolTracker extends RE6Module_1.RE6Module{constructor(){super(),this.updateActions={imageSrc:data=>Post_1.Post.createPreviewUrlFromMd5(data.md5),imageHref:data=>"/pools/"+data.id,updateHref:data=>`/posts/${data.extra.last}?pool_id=${data.id}`,updateText:data=>data.name,sourceHref:data=>"/pools/"+data.id,sourceText:()=>"All Posts"},this.subBatchSize=100,this.maxSubscriptions=500,this.cache=new SubscriptionTracker_1.UpdateCache(this)}getDefaultSettings(){return{enabled:!0,data:{}}}getName(){return"Pools"}makeSubscribeButton(){return $("<button>").addClass("large-subscribe-button subscribe").addClass("button btn-success").html("Subscribe")}makeUnsubscribeButton(){return $("<button>").addClass("large-subscribe-button unsubscribe").addClass("button btn-danger").html("Unsubscribe")}getButtonAttachment(){return $("div#c-pools > div#a-show").first()}insertButton($element,$button){$element.prepend($button)}getSubscriberId(){return Page_1.Page.getPageID()}getSubscriberName(){return $("div#c-pools div#a-show h2 a").first().text().trim()}getCache(){return this.cache}async getUpdatedEntries(lastUpdate,status){const results={};status.append("<div>. . . retrieving settings</div>");const storedSubs=await this.fetchSettings("data",!0);if(0===Object.keys(storedSubs).length)return results;status.append("<div>. . . sending an API request</div>");const storedSubChunks=Util_1.Util.chunkArray(Object.keys(storedSubs),this.subBatchSize),apiData=[];for(const[index,chunk]of storedSubChunks.entries())storedSubChunks.length>1&&status.append(`<div>&nbsp; &nbsp; &nbsp; - processing batch #${index}</div>`),apiData.push(...await E621_1.E621.Pools.get({"search[id]":chunk.join(",")},500));status.append("<div>. . . formatting output</div>");for(const poolJson of apiData){void 0!==storedSubs[poolJson.id].lastId&&poolJson.post_ids.includes(storedSubs[poolJson.id].lastId)||(storedSubs[poolJson.id].lastId=poolJson.post_ids[poolJson.post_ids.length-1]);const previousStop=poolJson.post_ids.indexOf(storedSubs[poolJson.id].lastId);new Date(poolJson.updated_at).getTime()>lastUpdate&&poolJson.post_ids.length>previousStop&&(results[new Date(poolJson.updated_at).getTime()]=await this.formatPoolUpdate(poolJson,storedSubs)),storedSubs[poolJson.id].lastId=poolJson.post_ids[poolJson.post_ids.length-1],storedSubs[poolJson.id].name=poolJson.name.replace(/_/g," ")}return status.append("<div>. . . outputting results</div>"),await this.pushSettings("data",storedSubs),results}async formatPoolUpdate(value,subSettings){const poolInfo=subSettings[value.id];if(void 0===poolInfo.md5){const lookup=await E621_1.E621.Post.id(value.post_ids[0]).get();0==lookup.length?poolInfo.md5="":poolInfo.md5="swf"===lookup[0].file.ext?"":lookup[0].file.md5}return{id:value.id,name:value.name.replace(/_/g," "),md5:poolInfo.md5,extra:{last:value.post_ids[value.post_ids.length-1]},new:!0}}}exports.PoolTracker=PoolTracker},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/data/Page":17,"../../components/data/Post":18,"../../components/utility/Util":32,"./SubscriptionTracker":63}],62:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SubscriptionManager=void 0;const Danbooru_1=require("../../components/api/Danbooru"),XM_1=require("../../components/api/XM"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),Form_1=require("../../components/structure/Form"),Modal_1=require("../../components/structure/Modal"),Tabbed_1=require("../../components/structure/Tabbed"),Debug_1=require("../../components/utility/Debug"),Sync_1=require("../../components/utility/Sync"),Util_1=require("../../components/utility/Util"),ThumbnailsEnhancer_1=require("../search/ThumbnailsEnhancer"),CommentTracker_1=require("./CommentTracker"),ForumTracker_1=require("./ForumTracker"),PoolTracker_1=require("./PoolTracker"),TagTracker_1=require("./TagTracker");class SubscriptionManager extends RE6Module_1.RE6Module{constructor(){super(),this.trackers=new Map,this.notificationsAlreadyOpened=!1,this.registerHotkeys({keys:"hotkeyOpenNotifications",fnct:this.openNotifications})}getDefaultSettings(){return{enabled:!0,lastUpdate:0,updateStarted:0,cacheSize:60,updateInterval:36e5,cacheMaxAge:0,hotkeyOpenNotifications:""}}static async register(moduleList){Array.isArray(moduleList)||(moduleList=[moduleList]);const trackers=this.getInstance().trackers;for(const moduleClass of moduleList)trackers.set(moduleClass.prototype.constructor.name,{instance:ModuleController_1.ModuleController.get(moduleClass)});return Promise.resolve(moduleList.length)}getTracker(id){if("string"==typeof id)return this.trackers.get(id);for(const value of this.trackers.values())if(value.tabIndex===id)return value}async create(){super.create();const settings=this.fetchSettings(["lastUpdate","cacheVersion"]),cacheInvalid=void 0===settings.cacheVersion||settings.cacheVersion<SubscriptionManager.cacheVersion;cacheInvalid&&this.pushSettings("cacheVersion",SubscriptionManager.cacheVersion),this.$openSubsButton=DomUtilities_1.DomUtilities.addSettingsButton({id:"header-button-notifications",name:'<i class="fas fa-bell"></i>',title:"Notifications",attr:{"data-loading":"false","data-updates":"0"},linkClass:"update-notification"});const content=[];let tabIndex=0;this.trackers.forEach((data,name)=>{data.tabElement=$("<a>").attr({"data-loading":"false","data-updates":"0"}).addClass("update-notification").html(data.instance.getName()),data.tabIndex=tabIndex,data.content=$("<div>").addClass("subscriptions-list subscription-"+data.instance.getName()).attr({"data-subscription-class":name,"data-updates":"0"}),$("<div>").addClass("subscription-load-status").html("Initializing . . .").appendTo(data.content),cacheInvalid?data.instance.getCache().clear():data.instance.getCache().load(),this.addSubscribeButtons(data.instance),content.push({name:data.tabElement,content:data.content}),tabIndex++}),content.push({name:"Info",content:this.buildInfoPage().render()}),this.tabs=new Tabbed_1.Tabbed({name:"notifications-tabs",content:content}).render(),this.modal=new Modal_1.Modal({title:"Subscriptions",triggers:[{element:this.$openSubsButton}],escapable:!1,reserveHeight:!0,content:this.tabs,position:{my:"right top",at:"right top"}}),SubscriptionManager.on("update.main",()=>{this.executeUpdateEvent()}),SubscriptionManager.on("timerRefresh.main",()=>{this.executeTimerRefreshEvent()}),this.trackers.forEach(trackerData=>{XM_1.XM.Storage.addListener("re621."+trackerData.instance.getSettingsTag()+".cache",(name,oldValue,newValue,remote)=>{remote&&(Debug_1.Debug.log(`SubM${trackerData.tabIndex}: Cache updated`),this.executeReloadEvent(trackerData))})}),this.modal.getElement().on("dialogopen.onUpdate",()=>{if(!SubscriptionManager.updateInProgress){if(!this.notificationsAlreadyOpened){this.notificationsAlreadyOpened=!0;let index=0;for(const sub of this.trackers){if(parseInt(sub[1].tabElement.attr("data-updates"))>0){this.tabs.tabs("option","active",index);break}index++}}this.clearTabNotification(this.tabs.tabs("option","active")),window.setTimeout(()=>{this.clearTabNotification(this.tabs.tabs("option","active"))},1e3)}}),this.tabs.on("tabsactivate.onUpdate",(event,tabProperties)=>{SubscriptionManager.updateInProgress||this.clearTabNotification(tabProperties.newTab.index())}),SubscriptionManager.trigger("timerRefresh"),this.updateRequired().then(updateRequired=>{updateRequired?this.executeUpdateEvent():this.trackers.forEach(trackerData=>{this.executeReloadEvent(trackerData)})}),setInterval(async()=>{SubscriptionManager.updateInProgress||(await this.updateRequired()?SubscriptionManager.trigger("update"):SubscriptionManager.trigger("timerRefresh"))},Util_1.Util.Time.MINUTE)}buildInfoPage(){return new Form_1.Form({name:"subscriptions-controls",columns:2,width:2},[Form_1.Form.header("Subscriptions"),makeSubSection(this.getTracker("TagTracker").instance,2),makeSubSection(this.getTracker("PoolTracker").instance,1),makeSubSection(this.getTracker("ForumTracker").instance,1),makeSubSection(this.getTracker("CommentTracker").instance,2),Form_1.Form.hr(2),Form_1.Form.header("Settings"),Form_1.Form.section({name:"settings",columns:2,width:2},[Form_1.Form.div({value:"Cache Size"}),Form_1.Form.input({value:this.fetchSettings("cacheSize"),pattern:"^([1-9][0-9]|[12][0-9]{2}|3[01][0-9]|320)$"},async(data,input)=>{input.get()[0].checkValidity()&&await this.pushSettings("cacheSize",parseInt(data))}),Form_1.Form.div({value:'<div class="unmargin">Number of items kept in the update cache. Must be at least 10, but no more than 320. Large values may lead to performance drops.</div>',width:2}),Form_1.Form.spacer(2),Form_1.Form.div({value:"Update Interval"}),Form_1.Form.select({value:this.fetchSettings("updateInterval")/Util_1.Util.Time.HOUR},{.5:"30 minutes",1:"1 hour",6:"6 hours",12:"12 hours",24:"24 hours"},async data=>{data<30*Util_1.Util.Time.MINUTE&&(data=30*Util_1.Util.Time.MINUTE),await this.pushSettings("updateInterval",parseFloat(data)*Util_1.Util.Time.HOUR),SubscriptionManager.trigger("timerRefresh")}),Form_1.Form.div({value:'<div class="unmargin">How often should the subscriptions be checked for updates.</div>',width:2}),Form_1.Form.spacer(2),Form_1.Form.div({value:"Cache Expiration"}),Form_1.Form.select({value:this.fetchSettings("cacheMaxAge")/Util_1.Util.Time.WEEK},{0:"Never",7:"1 week",2:"2 weeks",4:"1 month",24:"6 months"},async data=>{await this.pushSettings("cacheMaxAge",parseInt(data)*Util_1.Util.Time.WEEK),SubscriptionManager.trigger("timerRefresh")}),Form_1.Form.div({value:'<div class="unmargin">Updates older than this are removed automatically</div>',width:2})]),Form_1.Form.hr(2),Form_1.Form.section({name:"status",columns:2},[Form_1.Form.header("Other",2),Form_1.Form.div({value:"Last Update"}),Form_1.Form.div({value:$("<span>").attr("id","subscriptions-lastupdate").html("Initializing . . .")}),Form_1.Form.div({value:"Next Update"}),Form_1.Form.div({value:$("<span>").attr("id","subscriptions-nextupdate").html("Initializing . . .")}),Form_1.Form.button({value:'<i class="fas fa-sync-alt fa-xs fa-spin" id="subscription-action-update"></i> Manual Update'},()=>{SubscriptionManager.updateInProgress?Danbooru_1.Danbooru.notice("Update is already in progress"):SubscriptionManager.trigger("update")}),Form_1.Form.button({value:"Clear Cache"},()=>{this.trackers.forEach(async subscription=>{await subscription.instance.getCache().clear(),subscription.content[0].innerHTML=""})})])]);function makeSubSection(instance,columns){const $subsSection=$("<div>").addClass("subscriptions-manage-list col-"+columns),$badge=$("<span>");return executeSubUpdateEvent(),XM_1.XM.Storage.addListener("re621."+instance.getSettingsTag(),()=>{Debug_1.Debug.log("SubM: Subscriptions updated"),executeSubUpdateEvent()}),Form_1.Form.collapse({title:instance.getName(),columns:2,width:2,badge:$badge},[Form_1.Form.div({value:$subsSection,width:2})]);async function executeSubUpdateEvent(){const subData=await instance.fetchSettings("data",!0);var unordered;$subsSection.html(""),(unordered=subData,Object.keys(unordered).sort((a,b)=>{const aName=unordered[a].name?unordered[a].name.toLowerCase():"zzz_undefined",bName=unordered[b].name?unordered[b].name.toLowerCase():"zzz_undefined";return aName==bName?0:aName<bName?-1:1})).forEach(key=>{(function(instance,key,entry){const output=$("<item>");let currentlySubbed=!0;const heart=$("<i>").addClass("fas fa-heart");$("<a>").addClass("sub-manage-unsub").append(heart).appendTo(output).on("click",async event=>{event.preventDefault();const subData=await instance.fetchSettings("data",!0);currentlySubbed?(delete subData[key],Danbooru_1.Danbooru.notice("Successfully unsubscribed")):(subData[key]=entry,Danbooru_1.Danbooru.notice("Successfully subscribed")),instance.pushSettings("data",subData),currentlySubbed=!currentlySubbed,heart.toggleClass("fas far")});const link=$("<a>").html(entry.name?entry.name:key).appendTo(output);switch(instance.getName()){case"Pools":link.attr("href","/pools/"+key);break;case"Forums":link.attr("href","/forum_topics/"+key);break;case"Tags":link.attr("href","/posts?tags="+key);break;case"Comments":link.attr("href","/posts/"+key)}return output})(instance,key,subData[key]).appendTo($subsSection)}),$badge.html(Object.keys(subData).length+"")}}}async updateRequired(){const time=await this.fetchSettings(["lastUpdate","updateStarted","now","updateInterval"],!0);return void 0===time.now&&(time.now=Util_1.Util.Time.now()),Promise.resolve(!SubscriptionManager.updateInProgress&&(time.now-time.lastUpdate>=time.updateInterval||0!==time.updateStarted&&time.now-time.updateStarted>=SubscriptionManager.updateTimeout))}async executeUpdateEvent(){SubscriptionManager.updateInProgress=!0;const now=Util_1.Util.Time.now(),prevUpdate=await this.fetchSettings("lastUpdate",!0);if(await this.pushSettings("updateStarted",now),SubscriptionManager.trigger("timerRefresh"),this.$openSubsButton.attr({"data-loading":"true","data-updates":"0"}),Sync_1.Sync.enabled){const syncData=await Sync_1.Sync.download();if(null===syncData)await Sync_1.Sync.upload();else{const time=new Date(syncData.timestamp+"Z").getTime();time>Sync_1.Sync.timestamp?(Debug_1.Debug.log("SYNC: downloading remote"),await ModuleController_1.ModuleController.get(CommentTracker_1.CommentTracker).pushSettings("data",syncData.data.CommentTracker),await ModuleController_1.ModuleController.get(ForumTracker_1.ForumTracker).pushSettings("data",syncData.data.ForumTracker),await ModuleController_1.ModuleController.get(PoolTracker_1.PoolTracker).pushSettings("data",syncData.data.PoolTracker),await ModuleController_1.ModuleController.get(TagTracker_1.TagTracker).pushSettings("data",syncData.data.TagTracker),Sync_1.Sync.timestamp=time,await Sync_1.Sync.saveSettings()):Debug_1.Debug.log("SYNC: up to date")}}const updateThreads=[];for(const trackerData of this.trackers.values())updateThreads.push(new Promise(async resolve=>{Debug_1.Debug.log("SubM: redrawing [update]"),trackerData.tabElement.attr("data-updates","0"),trackerData.tabElement.attr("data-loading","true"),trackerData.content[0].innerHTML="";const status=$("<div>").addClass("subscription-load-status").html("Loading . . .").appendTo(trackerData.content),cache=trackerData.instance.getCache();await cache.load(),await cache.update(prevUpdate,status),trackerData.tabElement.attr("data-loading","false"),await this.executeReloadEvent(trackerData),resolve()}));if(await Promise.all(updateThreads),SubscriptionManager.updateInProgress=!1,await this.pushSettings({lastUpdate:now,updateStarted:0}),SubscriptionManager.trigger("timerRefresh"),this.$openSubsButton.attr("data-loading","false"),this.refreshHeaderNotifications(),this.modal.isOpen()){const activeTab=this.tabs.tabs("option","active");window.setTimeout(()=>{this.clearTabNotification(activeTab)},1e3)}}async executeReloadEvent(trackerData){const cache=trackerData.instance.getCache();await cache.load(),Debug_1.Debug.log(`SubM${trackerData.tabIndex}: drawing ${cache.getSize()} items`),trackerData.content[0].innerHTML="",cache.getSize()>0&&trackerData.content.append(this.createCacheDivider());const clickAction=ThumbnailsEnhancer_1.ThumbnailEnhancer.getClickAction();if(cache.forEach((content,timestamp)=>{trackerData.content.append(this.createUpdateEntry(timestamp,content,trackerData,clickAction))}),this.refreshTabNotifications(trackerData),this.refreshHeaderNotifications(),this.modal.isOpen()){const activeTab=this.tabs.tabs("option","active");window.setTimeout(()=>{this.clearTabNotification(activeTab)},1e3)}}async executeTimerRefreshEvent(){this.refreshSettings();const time=await this.fetchSettings(["lastUpdate","updateInterval","updateStarted"],!0);var lastUpdate,updateStarted;$("span#subscriptions-lastupdate").attr("title",(lastUpdate=time.lastUpdate,updateStarted=time.updateStarted,SubscriptionManager.updateInProgress?"":0!==updateStarted?Util_1.Util.Time.format(updateStarted):0===lastUpdate?"":Util_1.Util.Time.format(lastUpdate))).html(function(lastUpdate,updateStarted){return SubscriptionManager.updateInProgress?"In progress . . .":0!==updateStarted?Util_1.Util.Time.ago(updateStarted)+" (interrupted)":0===lastUpdate?"Never":Util_1.Util.Time.ago(lastUpdate)}(time.lastUpdate,time.updateStarted)),$("span#subscriptions-nextupdate").attr("title",function(lastUpdate,updateInterval,updateStarted){const now=Util_1.Util.Time.now();if(SubscriptionManager.updateInProgress)return"";return 0!==updateStarted?Util_1.Util.Time.format(updateStarted+SubscriptionManager.updateTimeout):0===lastUpdate?Util_1.Util.Time.format(now+updateInterval):lastUpdate+updateInterval<now?"":Util_1.Util.Time.format(lastUpdate+updateInterval)}(time.lastUpdate,time.updateInterval,time.updateStarted)).html(function(lastUpdate,updateInterval,updateStarted){const now=Util_1.Util.Time.now();if(SubscriptionManager.updateInProgress)return"In progress . . .";return 0!==updateStarted?Util_1.Util.Time.ago(updateStarted+SubscriptionManager.updateTimeout+Util_1.Util.Time.MINUTE):0===lastUpdate?Util_1.Util.Time.ago(now+updateInterval):lastUpdate+updateInterval<now?"Less than a minute":Util_1.Util.Time.ago(lastUpdate+updateInterval+Util_1.Util.Time.MINUTE)}(time.lastUpdate,time.updateInterval,time.updateStarted)),$("i#subscription-action-update").toggleClass("fa-spin",SubscriptionManager.updateInProgress)}refreshHeaderNotifications(){let totalCount=0;return this.trackers.forEach(subscription=>{totalCount+=parseInt(subscription.tabElement.attr("data-updates"))}),this.$openSubsButton.attr("data-updates",totalCount),totalCount}refreshTabNotifications(subscription){const curCount=subscription.content.find(".new").length;return subscription.content.attr("data-updates",curCount),subscription.tabElement.attr("data-updates",curCount),curCount}async clearTabNotification(tabIndex){const subscription=this.getTracker(tabIndex);if(void 0===subscription)return;const newItems=subscription.content.find(".new").get();for(const item of newItems)$(item).removeClass("new").addClass("new-viewed");this.refreshTabNotifications(subscription),this.refreshHeaderNotifications();const cache=subscription.instance.getCache();let cleared=0;cache.forEach(entry=>(entry.new&&cleared++,delete entry.new,entry)),cleared>0&&await cache.save()}addSubscribeButtons(instance){let subscriptionData=instance.fetchSettings("data");const elements=instance.getButtonAttachment().get();for(const element of elements){const $element=$(element);if($element.find("button.subscribe, a.subscribe").length>0)continue;const id=instance.getSubscriberId($element),$subscribeButton=instance.makeSubscribeButton(),$unsubscribeButton=instance.makeUnsubscribeButton();void 0===subscriptionData[id]?$unsubscribeButton.addClass("display-none"):$subscribeButton.addClass("display-none"),instance.insertButton($element,$subscribeButton),instance.insertButton($element,$unsubscribeButton);let processing=!1;$subscribeButton.click(async event=>{event.preventDefault(),processing||(processing=!0,execSubscribe(id,$subscribeButton,$unsubscribeButton,$element).then(()=>{processing=!1}))}),$unsubscribeButton.click(async event=>{event.preventDefault(),processing||(processing=!0,execUnsubscribe(id,$subscribeButton,$unsubscribeButton).then(()=>{processing=!1}))})}async function execSubscribe(id,$subscribeButton,$unsubscribeButton,$element){return subscriptionData=await instance.fetchSettings("data",!0),Object.keys(subscriptionData).length>=instance.maxSubscriptions?(Danbooru_1.Danbooru.error(`Error: Maximum number of subscriptions reached (${instance.maxSubscriptions})`),Promise.resolve(!1)):(subscriptionData[id]={name:instance.getSubscriberName($element)},subscriptionData=sortSubscriptions(subscriptionData),$subscribeButton.addClass("display-none"),$unsubscribeButton.removeClass("display-none"),Sync_1.Sync.enabled&&await Sync_1.Sync.upload(),instance.pushSettings("data",subscriptionData))}async function execUnsubscribe(id,$subscribeButton,$unsubscribeButton){return subscriptionData=await instance.fetchSettings("data",!0),delete subscriptionData[id],subscriptionData=sortSubscriptions(subscriptionData),$subscribeButton.removeClass("display-none"),$unsubscribeButton.addClass("display-none"),Sync_1.Sync.enabled&&await Sync_1.Sync.upload(),instance.pushSettings("data",subscriptionData)}function sortSubscriptions(unordered){const ordered={};return Object.keys(unordered).sort().forEach((function(key){ordered[key]=unordered[key]})),ordered}}createCacheDivider(){return $("<div>").addClass("subscription-update notice notice-cached").html('<div class="subscription-update-title">Older Updates</div>')}createUpdateEntry(timestamp,data,subscription,clickAction){const actions=subscription.instance.updateActions,cache=subscription.instance.getCache(),$content=$("<div>").addClass("subscription-update"+(data.new?" new":"")),timeAgo=Util_1.Util.Time.ago(timestamp),timeString=new Date(timestamp).toLocaleString(),$imageDiv=$("<div>").addClass("subscription-update-preview").appendTo($content),$image=$("<img>").attr({src:DomUtilities_1.DomUtilities.getPlaceholderImage(),"data-src":actions.imageSrc(data),title:actions.updateText(data)+"\n"+timeAgo+"\n"+timeString}).addClass("lazyload").on("error",()=>{actions.imageRemoveOnError&&($content.remove(),cache.deleteItem(timestamp),cache.save())});if(void 0===actions.imageHref)$image.appendTo($imageDiv);else{const $link=$("<a>").addClass("subscription-update-thumbnail").attr("href",actions.imageHref(data)).appendTo($imageDiv).append($image);let dbclickTimer,prevent=!1;$link.on("click.re621.thumbnail",event=>{0===event.button&&(event.preventDefault(),dbclickTimer=window.setTimeout(()=>{prevent||($link.off("click.re621.thumbnail"),$link[0].click()),prevent=!1},200))}).on("dblclick.re621.thumbnail",event=>{0===event.button&&(event.preventDefault(),window.clearTimeout(dbclickTimer),prevent=!0,clickAction===ThumbnailsEnhancer_1.ThumbnailClickAction.NewTab?XM_1.XM.Util.openInTab(window.location.origin+$link.attr("href"),!1):($link.off("click.re621.thumbnail"),$link[0].click()))})}const $title=$("<div>").addClass("subscription-update-title").appendTo($content);void 0===actions.updateHref?$("<div>").html(actions.updateText(data)).attr("data-id",data.id).appendTo($title):$("<a>").html(actions.updateText(data)).attr({href:actions.updateHref(data),"data-id":data.id}).appendTo($title),data.nameExtra&&$("<span>").addClass("subscriptions-update-title-extra").html(data.nameExtra).appendTo($title);const $remove=$("<div>").addClass("subscription-update-remove").appendTo($content);$("<a>").addClass("sub-"+subscription.tabIndex+"-remove").attr("title","Remove").html('<i class="fas fa-times"></i>').appendTo($remove).click(async event=>{event.preventDefault();const $buttons=$("a.sub-"+subscription.tabIndex+"-remove");$buttons.css("visibility","hidden"),cache.deleteItem(timestamp),await cache.save(),$buttons.css("visibility",""),$content.css("display","none")});const $full=$("<div>").addClass("subscription-update-full").appendTo($content);void 0===actions.sourceHref?$("<div>").html(actions.sourceText(data)).appendTo($full):$("<a>").attr("href",actions.sourceHref(data)).html(actions.sourceText(data)).appendTo($full);const $date=$("<div>").addClass("subscription-update-date").appendTo($content);return $("<span>").html(timeAgo).attr("title",timeString).appendTo($date),$content}openNotifications(){$("a#header-button-notifications")[0].click()}}exports.SubscriptionManager=SubscriptionManager,SubscriptionManager.cacheVersion=1,SubscriptionManager.updateInProgress=!1,SubscriptionManager.updateTimeout=5*Util_1.Util.Time.MINUTE},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/api/XM":7,"../../components/structure/DomUtilities":23,"../../components/structure/Form":24,"../../components/structure/Modal":25,"../../components/structure/Tabbed":27,"../../components/utility/Debug":28,"../../components/utility/Sync":31,"../../components/utility/Util":32,"../search/ThumbnailsEnhancer":58,"./CommentTracker":59,"./ForumTracker":60,"./PoolTracker":61,"./TagTracker":64}],63:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UpdateCache=void 0;const XM_1=require("../../components/api/XM"),ModuleController_1=require("../../components/ModuleController"),Util_1=require("../../components/utility/Util"),SubscriptionManager_1=require("./SubscriptionManager");exports.UpdateCache=class{constructor(instance){this.instance=instance,this.data={},this.updateIndex()}getStorageTag(){return"re621."+this.instance.getSettingsTag()+".cache"}async load(){return this.data=await XM_1.XM.Storage.getValue(this.getStorageTag(),{}),this.updateIndex(),Promise.resolve(!0)}async update(lastUpdate,status){const updates=await this.instance.getUpdatedEntries(lastUpdate,status);return Object.keys(updates).length>0?(this.push(updates),this.save()):Promise.resolve(!1)}async save(){return XM_1.XM.Storage.setValue(this.getStorageTag(),this.data)}async clear(){return this.data={},this.updateIndex(),this.save()}getIndex(){return this.index}getSize(){return this.index.length}getItem(timestamp){return this.data[timestamp]}deleteItem(timestamp){const el=this.index.indexOf(timestamp);-1!==el&&(this.index.splice(el,1),delete this.data[timestamp])}push(newData){Object.keys(newData).forEach(key=>{this.data[key]=newData[key]}),this.updateIndex(),this.trim()}updateIndex(){this.index=Object.keys(this.data).map(x=>parseInt(x)).sort((a,b)=>b-a)}trim(){const params=ModuleController_1.ModuleController.get(SubscriptionManager_1.SubscriptionManager).fetchSettings(["cacheMaxAge","cacheSize"]),ageLimit=0===params.cacheMaxAge?0:Util_1.Util.Time.now()-params.cacheMaxAge,uniqueKeys=[];this.index.forEach(timestamp=>{const update=this.data[timestamp];timestamp<ageLimit&&!update.new?delete this.data[timestamp]:-1===uniqueKeys.indexOf(update.id)?uniqueKeys.push(update.id):delete this.data[timestamp]}),this.updateIndex();const chunks=Util_1.Util.chunkArray(this.index,params.cacheSize,!0);this.index=chunks[0],chunks[1].forEach(entry=>{delete this.data[entry]})}forEach(fn){this.index.forEach(timestamp=>{const result=fn(this.data[timestamp],timestamp);void 0!==result&&(this.data[timestamp]=result)})}}},{"../../components/ModuleController":1,"../../components/api/XM":7,"../../components/utility/Util":32,"./SubscriptionManager":62}],64:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TagTracker=void 0;const E621_1=require("../../components/api/E621"),Post_1=require("../../components/data/Post"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util"),SubscriptionManager_1=require("./SubscriptionManager"),SubscriptionTracker_1=require("./SubscriptionTracker");class TagTracker extends RE6Module_1.RE6Module{constructor(){super(),this.updateActions={imageSrc:data=>Post_1.Post.createPreviewUrlFromMd5(data.md5),imageHref:data=>"/posts/"+data.id,imageRemoveOnError:!0,updateText:data=>data.name,sourceHref:data=>"/posts?tags="+encodeURIComponent(data.name.replace(/ /g,"_")),sourceText:()=>"View Tag"},this.subBatchSize=40,this.maxSubscriptions=1200,this.cache=new SubscriptionTracker_1.UpdateCache(this)}getDefaultSettings(){return{enabled:!0,data:{}}}getName(){return"Tags"}makeSubscribeButton(){return $("<a>").attr({href:"#",title:"Subscribe"}).addClass("tag-subscription-button subscribe").html('<i class="far fa-heart"></i>')}makeUnsubscribeButton(){return $("<a>").attr({href:"#",title:"Unsubscribe"}).addClass("tag-subscription-button unsubscribe").html('<i class="fas fa-heart"></i>')}getButtonAttachment(){return $("#tag-box li span.tag-action-subscribe, #tag-list li span.tag-action-subscribe")}insertButton($element,$button){$element.append($button)}getSubscriberId($element){return $element.parent().attr("data-tag")}getSubscriberName($element){return $element.parent().attr("data-tag").replace(/_/g," ")}getCache(){return this.cache}async getUpdatedEntries(lastUpdate,status){const results={};status.append("<div>. . . retrieving settings</div>");const storedSubs=await this.fetchSettings("data",!0);if(0===Object.keys(storedSubs).length)return results;status.append("<div>. . . sending an API request</div>");const storedSubChunks=Util_1.Util.chunkArray(Object.keys(storedSubs),this.subBatchSize),apiResult={};for(const[index,chunk]of storedSubChunks.entries()){storedSubChunks.length>1&&status.append(`<div>&nbsp; &nbsp; &nbsp; - processing batch #${index}</div>`),10==index&&status.append('<div><span style="color:gold">warning</span> connection throttled</div>');for(const post of await E621_1.E621.Posts.get({tags:chunk.map(el=>"~"+el).join("+"),limit:320},index<10?500:1e3)){const timestamp=new Date(post.created_at).getTime();if(timestamp<lastUpdate)break;apiResult[timestamp]=post}}Debug_1.Debug.log(apiResult),status.append("<div>. . . formatting output</div>");const postLimit=ModuleController_1.ModuleController.get(SubscriptionManager_1.SubscriptionManager).fetchSettings("cacheSize");for(const key of Object.keys(apiResult).sort()){if(Object.keys(results).length>postLimit){Debug_1.Debug.log("TgT: postlimit");break}const post=apiResult[key];Debug_1.Debug.log(`TgT: ${post.id} ${Util_1.Util.Time.format(new Date(post.created_at))}`),new Post_1.Post(post).matchesBlacklist(!0)?Debug_1.Debug.log("TgT: blacklist"):results[new Date(post.created_at).getTime()]=await this.formatPostUpdate(post)}return status.append("<div>. . . outputting results</div>"),await this.pushSettings("data",storedSubs),results}async formatPostUpdate(value){return{id:value.id,name:"post #"+value.id,md5:"swf"===value.file.ext?"":value.file.md5,new:!0}}}exports.TagTracker=TagTracker},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/data/Post":18,"../../components/utility/Debug":28,"../../components/utility/Util":32,"./SubscriptionManager":62,"./SubscriptionTracker":63}]},{},[35]);