// ==UserScript==
// @name re621 - e621 Reimagined
// @namespace re621.github.io
// @version 1.4.27
// @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.1/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/jquery.hotkeys/0.1.0/jquery.hotkeys.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/jszip/3.5.0/jszip.min.js
// @resource re621_css https://github.com/re621/re621/releases/download/1.4.27/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
// @icon https://cdn.jsdelivr.net/gh/re621/re621.github.io@master/images/icons/icon64.png
// @icon64 https://cdn.jsdelivr.net/gh/re621/re621.github.io@master/images/icons/icon64.png
// @connect api.github.com
// @connect static1.e621.net
// @run-at document-start
// ==/UserScript==
window.re621 = new function() {
this.name = "re621";
this.displayName = "re621 - e621 Reimagined";
this.version = "1.4.27";
this.build = "201010:0605";
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.4";
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 CleanSlate_1=require("./structure/CleanSlate"),Debug_1=require("./utility/Debug"),ErrorHandler_1=require("./utility/ErrorHandler"),Util_1=require("./utility/Util");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 instance=moduleClass.getInstance();this.modules.set(moduleClass.prototype.constructor.name,instance),await instance.prepare()}catch(error){ErrorHandler_1.ErrorHandler.error(moduleClass.prototype.constructor.name,error.stack,"prepare")}}for(const instance of this.modules.values())if(instance.canInitialize()){try{instance.isWaitingForDOM()?$(async()=>{await Util_1.Util.sleep(50),instance.isWaitingForFocus()&&await CleanSlate_1.CleanSlate.awaitFocus(),instance.create()}):(instance.isWaitingForFocus()&&await CleanSlate_1.CleanSlate.awaitFocus(),instance.create()),activeModules++}catch(error){ErrorHandler_1.ErrorHandler.error(instance,error.stack,"init")}Debug_1.Debug.perfEnd(instance.constructor.name)}else Debug_1.Debug.perfEnd(instance.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},{"./structure/CleanSlate":24,"./utility/Debug":30,"./utility/ErrorHandler":31,"./utility/Util":33}],2:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.RE6Module=void 0;const XM_1=require("./api/XM"),Keybinds_1=require("./data/Keybinds"),Page_1=require("./data/Page"),ModuleController_1=require("./ModuleController");exports.RE6Module=class{constructor(constraint,waitForDOM=!1,waitForFocus=!1,dependencies=[],settingsTag){this.initialized=!1,this.dependencies=[],this.constraint=[],this.keybinds=[],void 0===constraint?this.constraint=[]:constraint instanceof RegExp?this.constraint.push(constraint):this.constraint=constraint,this.dependencies=dependencies,this.waitForDOM=waitForDOM,this.waitForFocus=waitForFocus,this.settingsTag=settingsTag||this.constructor.name}async prepare(){await this.loadSettingsCache(),this.enabled=this.fetchSettings("enabled")}isInitialized(){return this.initialized}canInitialize(){let depend=!0;for(const module of this.dependencies)if(!ModuleController_1.ModuleController.get(module).isEnabled()){depend=!1;break}return!this.initialized&&this.pageMatchesFilter()&&this.enabled&&depend}getSettingsTag(){return this.settingsTag}isWaitingForDOM(){return this.waitForDOM}isWaitingForFocus(){return this.waitForFocus}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 keyMeta=[],keybindObj=[],enabled=this.pageMatchesFilter();for(const keybind of this.keybinds){const meta=this.getSettingsTag()+"."+keybind.keys;keybindObj.push({keys:this.fetchSettings(keybind.keys).split("|"),fnct:keybind.fnct,bindMeta:meta,enabled:enabled,element:keybind.element,selector:keybind.selector}),keyMeta.push(meta)}Keybinds_1.KeybindManager.unregister(keyMeta),Keybinds_1.KeybindManager.register(keybindObj)}registerHotkeys(...keybinds){this.keybinds.push(...keybinds),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)}}},{"./ModuleController":1,"./api/XM":6,"./data/Keybinds":15,"./data/Page":16}],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(post_id,scoreDifference,preventUnvote){Danbooru.hasModules()?Danbooru.getModules().Post.vote(post_id,scoreDifference,preventUnvote):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","vote",[post_id,scoreDifference,preventUnvote])},initialize_all(){Danbooru.hasModules()?Danbooru.getModules().Post.initialize_all():XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","update")},update(post_id,params){Danbooru.hasModules()?Danbooru.getModules().Post.update(post_id,params):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","update",[post_id,params])},delete_with_reason(post_id,reason,reload_after_delete){Danbooru.hasModules()?Danbooru.getModules().Post.delete_with_reason(post_id,reason,reload_after_delete):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","delete_with_reason",[post_id,reason,reload_after_delete])},undelete(post_id){Danbooru.hasModules()?Danbooru.getModules().Post.undelete(post_id):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","undelete",[post_id])},approve(post_id,should_reload=!1){Danbooru.hasModules()?Danbooru.getModules().Post.approve(post_id,should_reload):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","approve",[post_id,should_reload])},disapprove(post_id,reason,should_reload=!1){Danbooru.hasModules()?Danbooru.getModules().Post.disapprove(post_id,reason,should_reload):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","disapprove",[post_id,reason,should_reload])},unapprove(post_id){Danbooru.hasModules()?Danbooru.getModules().Post.unapprove(post_id):XM_1.XM.Chrome.execInjectorRequest("Danbooru","Post","unapprove",[post_id])}},Danbooru.PostModeMenu={change(){Danbooru.hasModules()?Danbooru.getModules().PostModeMenu.change():XM_1.XM.Chrome.execInjectorRequest("Danbooru","PostModeMenu","change")},click(e){Danbooru.hasModules()?Danbooru.getModules().PostModeMenu.click(e):XM_1.XM.Chrome.execInjectorRequest("Danbooru","PostModeMenu","click",[e])}},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":6}],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){this.queue=this.queue.reverse();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":6}],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.formatParam(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.formatParam(data),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.formatParam(data),this.name,this.node,delay).then(data=>Promise.resolve(data),error=>Promise.reject(error))}async put(data,delay){return this.queue.createRequest(this.getParsedPath(),{},"PUT",this.formatParam(data),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}formatParam(input){if(Debug_1.Debug.log("input",input),null==input)return{};const response={};for(const[key,value]of Object.entries(input))if(null!=value)if(Array.isArray(value)){for(const[index,elem]of value.entries())value[index]=cleanURIComponent(elem);response[key]=value.join("+")}else if("object"==typeof value)for(const[subKey,subValue]of Object.entries(value))if(Array.isArray(subValue)){for(const[index,subElement]of subValue.entries())subValue[index]=cleanURIComponent(subElement);response[`${key}[${subKey}]`]=subValue.join("+")}else response[`${key}[${subKey}]`]=cleanURIComponent(subValue);else response[key]=cleanURIComponent(value);return Debug_1.Debug.log("output",response),response;function cleanURIComponent(value){return encodeURIComponent(decodeURIComponent(value+""))}}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"};"GET"!==method&&(this.authToken=$("meta[name=csrf-token]").attr("content"),requestBody.authenticity_token=encodeURIComponent(this.authToken),requestInfo.body=FormattedAPIQuery.stringify(requestBody)),query._client=window.re621.useragent;const entry=new Request(location.origin+"/"+path+"?"+FormattedAPIQuery.stringify(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&&error[0]?error[1]+" "+error[0].error:"unknown error"},error&&error[0]?error[1]:500,item.endpoint,item.node]),resolve()})}),await Util_1.Util.sleep(item.delay)}this.processing=!1}}}var FormattedAPIQuery;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"),function(FormattedAPIQuery){FormattedAPIQuery.stringify=function(input){const result=[];for(const[key,value]of Object.entries(input))result.push(key+"="+value);return result.join("&")}}(FormattedAPIQuery||(FormattedAPIQuery={}))},{"../utility/Debug":30,"../utility/Util":33}],6:[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":7,"./XMConnect":8,"./XMStorage":9,"./XMUtil":10}],7:[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":33}],8:[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);const btn=$("<a>").attr({href:URL.createObjectURL(event.response),download:a.name}).html("download").on("click",()=>{btn.remove()});btn[0].click()}})}}exports.XMConnect=XMConnect},{"../utility/Debug":30,"./XM":6}],9:[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)}}},{}],10:[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":6}],11:[function(require,module,exports){"use strict";var PostRating,PostRatingAliases;Object.defineProperty(exports,"__esModule",{value:!0}),exports.APIPost=exports.PostFlag=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(PostFlag){PostFlag.Pending="pending",PostFlag.Flagged="flagged",PostFlag.Deleted="deleted"}(exports.PostFlag||(exports.PostFlag={})),function(PostFlag){PostFlag.get=function(post){const flags=new Set;return post.flags.deleted&&flags.add(PostFlag.Deleted),post.flags.flagged&&flags.add(PostFlag.Flagged),post.flags.pending&&flags.add(PostFlag.Pending),flags},PostFlag.getString=function(post){return[...PostFlag.get(post)].join(" ")},PostFlag.fromSingle=function(input){switch(input=input.toLowerCase().trim()){case"pending":return PostFlag.Pending;case"flagged":return PostFlag.Flagged;case"deleted":return PostFlag.Deleted}return null},PostFlag.fromString=function(input){const parts=new Set(input.split(" ")),flags=new Set;return parts.has("deleted")&&flags.add(PostFlag.Deleted),parts.has("flagged")&&flags.add(PostFlag.Flagged),parts.has("pending")&&flags.add(PostFlag.Pending),flags}}(exports.PostFlag||(exports.PostFlag={})),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.toFullString=function(postRating){switch(postRating.toLowerCase()){case"s":return"safe";case"q":return"questionable";case"e":return"explicit"}return null}}(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.getTagSet=function(post){return new Set(APIPost.getTags(post))},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")),duration:null};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={}))},{}],12:[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":33}],13:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TagCache=void 0;const Debug_1=require("../utility/Debug"),Util_1=require("../utility/Util");class TagCache{static getCache(){return null==TagCache.cache&&TagCache.load(),TagCache.cache}static load(){TagCache.cache=new Map(JSON.parse(Util_1.Util.LS.getItem("re621.tagcache")||"[]"));const now=Util_1.Util.Time.now();let pruned=0;for(const[name,data]of TagCache.cache)data.expires<now&&(TagCache.cache.delete(name),pruned++);Debug_1.Debug.log(`TagCache loaded, ${TagCache.cache.size}, ${pruned} pruned`)}static save(){Util_1.Util.LS.setItem("re621.tagcache",JSON.stringify(Array.from(TagCache.getCache().entries()))),Debug_1.Debug.log("TagCache saved, "+TagCache.cache.size)}static clear(){TagCache.getCache().clear(),TagCache.save()}static has(tag){return TagCache.getCache().has(tag)}static get(tag){return TagCache.getCache().has(tag)?TagCache.getCache().get(tag):null}static add(tag,count,category){TagCache.getCache().set(tag,{count:count,category:category,expires:Util_1.Util.Time.now()+(count>1e5?Util_1.Util.Time.WEEK:Util_1.Util.Time.DAY)})}}exports.TagCache=TagCache},{"../utility/Debug":30,"../utility/Util":33}],14:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Blacklist=void 0;const BlacklistEnhancer_1=require("../../modules/search/BlacklistEnhancer"),ModuleController_1=require("../ModuleController"),Post_1=require("../post/Post"),PostFilter_1=require("../post/PostFilter"),Util_1=require("../utility/Util"),User_1=require("./User");class Blacklist{constructor(){this.blacklist=new Map;const filters=$("head meta[name=blacklisted-tags]").attr("content"),blacklistEnabled="1"!==Util_1.Util.LS.getItem("dab"),options=ModuleController_1.ModuleController.get(BlacklistEnhancer_1.BlacklistEnhancer).fetchSettings(["favorites","uploads","whitelist"]);if(void 0!==filters)for(const filter of JSON.parse(filters))this.createFilter(filter,blacklistEnabled,options)}static getInstance(){return null==this.instance&&(this.instance=new Blacklist),this.instance}static get(){return this.getInstance().blacklist}static getActiveFilters(){const result=new Map;for(const[tags,filter]of this.getInstance().blacklist)filter.getMatchesCount()>0&&result.set(tags,filter);return result}static addPost(...posts){let count=0;for(const filter of Blacklist.get().values())filter.update(posts)&&count++;return count}static updatePost(...posts){return Blacklist.addPost(...posts)}static checkPost(post,ignoreDisabled=!1){"number"!=typeof post&&(post=post.id);for(const filter of Blacklist.get().values())if(filter.matchesID(post,ignoreDisabled))return!0;return!1}static enableAll(){for(const filter of Blacklist.get().values())filter.setEnabled(!0)}static disableAll(){for(const filter of Blacklist.get().values())filter.setEnabled(!1)}createFilter(filter,enabled=!0,options){let postFilter=this.blacklist.get(filter);void 0===postFilter&&(postFilter=new PostFilter_1.PostFilter(filter,enabled,options),this.blacklist.set(filter,postFilter))}static createFilter(filter,enabled=!0,options){return this.getInstance().createFilter(filter,enabled,options)}deleteFilter(filter){this.blacklist.delete(filter)}static deleteFilter(filter){return this.getInstance().deleteFilter(filter)}static async toggleBlacklistTag(tagName){let currentBlacklist=(await User_1.User.getCurrentSettings()).blacklisted_tags.split("\n");return-1===currentBlacklist.indexOf(tagName)?(currentBlacklist.push(tagName),Blacklist.createFilter(tagName),Danbooru.notice(`Adding ${getTagLink(tagName)} to blacklist`)):(currentBlacklist=currentBlacklist.filter(e=>e!==tagName),Blacklist.deleteFilter(tagName),Danbooru.notice(`Removing ${getTagLink(tagName)} from blacklist`)),await User_1.User.setSettings({blacklisted_tags:currentBlacklist.join("\n")}),ModuleController_1.ModuleController.get(BlacklistEnhancer_1.BlacklistEnhancer).isInitialized()&&BlacklistEnhancer_1.BlacklistEnhancer.update(),Post_1.Post.find("all").each(post=>{post.updateVisibility()}),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>`}}}exports.Blacklist=Blacklist},{"../../modules/search/BlacklistEnhancer":57,"../ModuleController":1,"../post/Post":19,"../post/PostFilter":21,"../utility/Util":33,"./User":18}],15:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.KeybindManager=void 0;const Debug_1=require("../utility/Debug"),Util_1=require("../utility/Util"),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"],replacedKeys={enter:"return",control:"ctrl",arrow:"","!":"1","@":"2","#":"3",$:"4","%":"5","^":"6","&":"7","*":"8","(":"9",")":"0",_:"-","+":"=","<":",",">":".","?":"//",":":";",'"':"'","{":"[","}":"]"},replacedRegExp=Util_1.Util.getKeyRegex(replacedKeys);class KeybindManager{static enable(){KeybindManager.enabled=!0}static disable(){KeybindManager.enabled=!1}static register(keybind){if(Array.isArray(keybind))for(const entry of keybind)this.register(entry);else{this.refreshListener(keybind.keys,keybind.element,keybind.selector);for(const key of keybind.keys)0!=key.length&&(this.executors.get(key)[keybind.bindMeta]=keybind)}}static unregister(bindMeta){Array.isArray(bindMeta)||(bindMeta=[bindMeta]);for(const executor of this.executors.values())for(const key of Object.keys(executor))bindMeta.includes(key)&&delete executor[key]}static record(callback){KeybindManager.listening=!0;let keys=[];console.log(replacedRegExp),$(document).on("keydown.re621.record",event=>{const key=event.key.toLowerCase().replace(replacedRegExp,matched=>(console.log("replacing",matched,"with",replacedKeys[matched]),replacedKeys[matched]));console.log(key,-1==validKeys.indexOf(key)?"invalid":"valid"),-1!=validKeys.indexOf(key)&&keys.push(key)}),$(document).on("keyup.re621.record",()=>{if(0!==keys.length)return $(document).off(".re621.record"),callback(keys),void(KeybindManager.listening=!1);keys=[]})}static count(sequence){return this.executors.has(sequence)?Object.keys(this.executors.get(sequence)).length:0}static refreshListener(keys,element,selector){for(const key of keys)if(0!=key.length){if(!this.listeners.has(key)){this.listeners.set(key,event=>{if(KeybindManager.listening)return;const listenerExecutor=this.executors.get(key);Debug_1.Debug.log("["+key+"]: triggered "+Object.entries(listenerExecutor).length+" executors");for(const[bindMeta,keyObj]of Object.entries(listenerExecutor))keyObj.enabled&&keyObj.fnct(event,bindMeta)});const $element=element?$(element):$(document);selector||(selector=null);let keydown=!1;$element.on("keydown.re621.hotkey-"+key,selector,key,event=>{if(!keydown){if(keydown=!0,!KeybindManager.enabled||KeybindManager.listening)return!1;this.listeners.get(key)(event)}}),$element.on("keyup.re621.hotkey-"+key,selector,key,()=>{keydown=!1})}this.executors.has(key)||this.executors.set(key,{})}}static getData(){console.log(this.listeners),console.log(this.executors)}}exports.KeybindManager=KeybindManager,KeybindManager.listeners=new Map,KeybindManager.executors=new Map,KeybindManager.enabled=!0,KeybindManager.listening=!1},{"../utility/Debug":30,"../utility/Util":33}],16:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PageDefinition=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.PageDefinition={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\??.*/,settings:/^\/users\/\d+\/edit$/,changes:/^\/post_versions.*/}},{}],17:[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 isArtist(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"]},{}],18:[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()}static async setSettings(data){await E621_1.E621.User.id(this.getUserID()).post({user:data,_method:"patch"})}static getInstance(){return null==this.instance&&(this.instance=new this),this.instance}}},{"../api/E621":5}],19:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.LoadedFileType=exports.PostData=exports.Post=void 0;const BetterSearch_1=require("../../modules/search/BetterSearch"),CustomFlagger_1=require("../../modules/search/CustomFlagger"),APIPost_1=require("../api/responses/APIPost"),Blacklist_1=require("../data/Blacklist"),Tag_1=require("../data/Tag"),ModuleController_1=require("../ModuleController"),Debug_1=require("../utility/Debug"),Util_1=require("../utility/Util"),PostParts_1=require("./PostParts"),PostSet_1=require("./PostSet");class Post{constructor(data,$ref){for(const[key,value]of Object.entries(data))this[key]=value;this.$ref=$ref,this.$ref.data("post",this),this.updateFilters()}update(data){for(const[key,value]of Object.entries(PostData.fromAPI(data)))this[key]=value;return this.updateFilters(),this}isRendered(){return"true"==this.$ref.attr("rendered")}isBlacklisted(){return"true"==this.$ref.attr("blacklisted")}render(){const conf=ModuleController_1.ModuleController.get(BetterSearch_1.BetterSearch).fetchSettings(["imageRatioChange","clickAction","imageLoadMethod","autoPlayGIFs","hoverTags","ribbonsFlag","ribbonsRel","buttonsVote","buttonsFav"]);return this.$ref.attr({fav:1==this.is_favorited?"true":void 0,rendered:!0}).removeAttr("style").html(""),this.$ref.append(PostParts_1.PostParts.renderImage(this,conf)).append(PostParts_1.PostParts.renderRibbons(this,conf)).append(PostParts_1.PostParts.renderButtons(this,conf)).append(PostParts_1.PostParts.renderFlags(this)).append(PostParts_1.PostParts.renderInfo(this)),conf.imageRatioChange||this.$ref.css("--img-ratio",this.img.ratio),this.file.duration&&this.$ref.css("--duration",this.file.duration),this.updateVisibility(),this}reset(){return this.$ref.attr({rendered:!1,loading:!1}).html(this.id+"").children().remove(),this.$ref.off("re621:update"),this}updateFilters(){return CustomFlagger_1.CustomFlagger.addPost(this),Blacklist_1.Blacklist.addPost(this),this}updateVisibility(){return Blacklist_1.Blacklist.checkPost(this.id)?(this.$ref.attr("blacklisted","true"),this.isRendered()&&this.reset()):this.$ref.removeAttr("blacklisted"),this}static get(post){return"number"==typeof post&&0==(post=$("#entry_"+post).first()).length?null:post.data("post")}static getViewingPost(){const container=$("#image-container");return void 0!==container.data("post")?Post.get(container):new Post(PostData.fromDOM(),container)}static find(type){const result=new PostSet_1.PostSet;switch(type){case"hovering":case"blacklisted":case"rendered":for(const elem of $(`post[${type}=true]`).get())result.push(Post.get($(elem)));break;case"existant":for(const elem of $("post:not([deleted=true])").get())result.push(Post.get($(elem)));break;case"all":for(const elem of $("post").get())result.push(Post.get($(elem)))}return result}static make(data,page,imageRatioChange){const tags=APIPost_1.APIPost.getTagSet(data),flags=APIPost_1.PostFlag.get(data),animated=tags.has("animated")||"webm"==data.file.ext||"gif"==data.file.ext||"swf"==data.file.ext;null==imageRatioChange&&(imageRatioChange=ModuleController_1.ModuleController.get(BetterSearch_1.BetterSearch).fetchSettings("imageRatioChange"));const $article=$("<post>").attr({id:"entry_"+data.id,fav:1==data.is_favorited||void 0,vote:void 0,animated:animated?"true":void 0,filetype:data.file.ext,deleted:!!flags.has(APIPost_1.PostFlag.Deleted)||void 0,rendered:!1,page:page}).data({id:data.id,"large-file-url":data.sample.url,"file-ext":data.file.ext}).html(data.id+"");imageRatioChange||$article.css("--img-ratio",data.file.height/data.file.width+"");const result=new Post(PostData.fromAPI(data,page),$article);return result.file.original||result.flags.has(APIPost_1.PostFlag.Deleted)?(result.updateFilters(),result.updateVisibility(),result):(Debug_1.Debug.log(`Post #${result.id} skipped: no file`),null)}}var PostData;exports.Post=Post,function(PostData){PostData.fromAPI=function(data,page){const tags=APIPost_1.APIPost.getTagSet(data),flags=APIPost_1.PostFlag.get(data);return{id:data.id,flags:flags,score:data.score.total,user_score:void 0,favorites:data.fav_count,is_favorited:1==data.is_favorited,comments:data.comment_count,rating:APIPost_1.PostRating.fromValue(data.rating),uploader:data.uploader_id,page:page,date:{raw:null==data.created_at?data.updated_at:data.created_at,ago:Util_1.Util.Time.ago(null==data.created_at?data.updated_at:data.created_at)},tagString:[...tags].sort().join(" "),tags:{all:tags,artist:new Set(data.tags.artist),real_artist:new Set(data.tags.artist.filter(tag=>Tag_1.Tag.isArtist(tag))),copyright:new Set(data.tags.copyright),species:new Set(data.tags.species),character:new Set(data.tags.character),general:new Set(data.tags.general),invalid:new Set(data.tags.invalid),meta:new Set(data.tags.meta),lore:new Set(data.tags.lore)},file:{ext:data.file.ext,md5:data.file.md5,original:data.file.url,sample:data.sample.has?data.sample.url:data.file.url,preview:data.preview.url,size:data.file.size,duration:data.duration},loaded:void 0,img:{width:data.file.width,height:data.file.height,ratio:data.file.height/data.file.width},has:{file:null!==data.file.url,children:data.relationships.has_active_children,parent:void 0!==data.relationships.parent_id&&null!==data.relationships.parent_id},rel:{children:new Set(data.relationships.children),parent:data.relationships.parent_id}}},PostData.fromDOM=function(){const $article=$("#image-container"),id=parseInt($article.attr("data-id"))||0,timeEl=$("#post-information").find("time"),time=0!=timeEl.length?timeEl.attr("title"):"0",children=new Set;for(const post of $("div#has-children-relationship-preview").find("article").get())children.add(parseInt($(post).attr("data-id")));const tagString=$article.attr("data-tags")||"",artistTags=getTags("artist");let md5;$article.attr("data-md5")?md5=$article.attr("data-md5"):$article.attr("data-file-url")&&(md5=$article.attr("data-file-url").substring(36,68));let score=0;$article.attr("data-score")?score=parseInt($article.attr("data-score")):0!==$article.find(".post-score-score").length&&(score=parseInt($article.find(".post-score-score").first().html().substring(1)));let userScore=0;$(".post-vote-up-"+id).first().hasClass("score-positive")?userScore=1:$(".post-vote-down-"+id).first().hasClass("score-negative")&&(userScore=-1);const width=parseInt($article.attr("data-width")),height=parseInt($article.attr("data-height"));return{id:id,flags:APIPost_1.PostFlag.fromString($article.attr("data-flags")||""),score:score,user_score:userScore,favorites:parseInt($article.attr("data-fav-count"))||0,is_favorited:"true"==$article.attr("data-is-favorited"),comments:-1,rating:APIPost_1.PostRating.fromValue($article.attr("data-rating")),uploader:parseInt($article.attr("data-uploader-id"))||0,page:"-1",date:{raw:time,ago:Util_1.Util.Time.ago(time)},tagString:tagString,tags:{all:new Set(tagString.split(" ")),artist:artistTags,real_artist:new Set([...artistTags].filter(tag=>Tag_1.Tag.isArtist(tag))),copyright:getTags("copyright"),species:getTags("species"),character:getTags("character"),general:getTags("general"),invalid:getTags("invalid"),meta:getTags("meta"),lore:getTags("lore")},file:{ext:$article.attr("data-file-ext"),md5:md5,original:$article.attr("data-file-url")||null,sample:$article.attr("data-large-file-url")||null,preview:$article.attr("data-preview-file-url")||null,size:0,duration:null},loaded:void 0,img:{width:width,height:height,ratio:height/width},has:{file:void 0!==$article.attr("data-file-url"),children:"true"==$article.attr("data-has-active-children"),parent:void 0!==$article.attr("data-parent-id")},rel:{children:children,parent:parseInt($article.attr("data-parent-id"))||null}};function getTags(group){const result=new Set;for(const element of $(`#tag-list .${group}-tag-list`).children())result.add($(element).find(".search-tag").text().replace(/ /g,"_"));return result}},PostData.fromThumbnail=function($article){const id=parseInt($article.attr("data-id"))||0,children=new Set,tagString=$article.attr("data-tags")||"",width=parseInt($article.attr("data-width")),height=parseInt($article.attr("data-height")),extension=$article.attr("data-file-ext");let md5,urls={};$article.hasClass("post-preview")?($article.attr("data-md5")?md5=$article.attr("data-md5"):$article.attr("data-file-url")&&(md5=$article.attr("data-file-url").substr(36,32)),urls={preview:$article.attr("data-preview-file-url")||null,sample:$article.attr("data-large-file-url")||null,original:$article.attr("data-file-url")||null}):($article.attr("data-md5")?md5=$article.attr("data-md5"):$article.attr("data-preview-url")&&(md5=$article.attr("data-preview-url").substr(44,32)),urls=null==md5?{preview:"/images/deleted-preview.png",sample:"/images/deleted-preview.png",original:"/images/deleted-preview.png"}:{preview:$article.attr("data-preview-url")||null,sample:width<850||height<850?`https://static1.e621.net/data/${md5.substr(0,2)}/${md5.substr(2,2)}/${md5}.${extension}`:`https://static1.e621.net/data/sample/${md5.substr(0,2)}/${md5.substr(2,2)}/${md5}.jpg`,original:`https://static1.e621.net/data/${md5.substr(0,2)}/${md5.substr(2,2)}/${md5}.${extension}`});const rawDate=$article.attr("data-created-at")||"0";return{id:id,flags:APIPost_1.PostFlag.fromString($article.attr("data-flags")||""),score:parseInt($article.attr("data-score")||"0"),user_score:0,favorites:parseInt($article.attr("data-fav-count"))||0,is_favorited:"true"==$article.attr("data-is-favorited"),comments:-1,rating:APIPost_1.PostRating.fromValue($article.attr("data-rating")),uploader:parseInt($article.attr("data-uploader-id"))||0,page:"-1",date:{raw:rawDate,ago:Util_1.Util.Time.ago(rawDate)},tagString:tagString,tags:{all:new Set(tagString.split(" ")),artist:new Set,real_artist:new Set,copyright:new Set,species:new Set,character:new Set,general:new Set,invalid:new Set,meta:new Set,lore:new Set},file:{ext:extension,md5:md5,original:urls.original,sample:urls.sample,preview:urls.preview,size:0,duration:null},loaded:void 0,img:{width:width,height:height,ratio:height/width},has:{file:void 0!==$article.attr("data-file-url"),children:"true"==$article.attr("data-has-active-children"),parent:void 0!==$article.attr("data-parent-id")},rel:{children:children,parent:parseInt($article.attr("data-parent-id"))||null}}},PostData.createPreviewUrlFromMd5=function(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`}}(PostData=exports.PostData||(exports.PostData={})),function(LoadedFileType){LoadedFileType.PREVIEW="preview",LoadedFileType.SAMPLE="sample",LoadedFileType.ORIGINAL="original"}(exports.LoadedFileType||(exports.LoadedFileType={}))},{"../../modules/search/BetterSearch":56,"../../modules/search/CustomFlagger":58,"../ModuleController":1,"../api/responses/APIPost":11,"../data/Blacklist":14,"../data/Tag":17,"../utility/Debug":30,"../utility/Util":33,"./PostParts":22,"./PostSet":23}],20:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostActions=void 0;const E621_1=require("../api/E621"),Debug_1=require("../utility/Debug");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 occurred while adding the post to set: "+response[1]),Promise.resolve(!1)),response=>(Danbooru.error("Error occurred 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 occurred while removing the post from set: "+response[1]),Promise.resolve(!1)),response=>(Danbooru.error("Error occurred while removing the post from set: "+response[1]),Promise.resolve(!1)))}static vote(postID,score,preventUnvote=!1){return new Promise(resolve=>{E621_1.E621.PostVotes.id(postID).post({score:score,no_unvote:preventUnvote}).then(success=>{Debug_1.Debug.log(success),resolve({success:!0,action:success[0].our_score,score:success[0].score,up:success[0].up,down:success[0].down})},error=>{console.log(error),resolve({success:!1})})})}static addFavorite(postID){return new Promise(resolve=>{E621_1.E621.Favorites.post({post_id:postID}).then(response=>{Debug_1.Debug.log(response),resolve(!0)},error=>{console.log(error),resolve(!1)})})}static removeFavorite(postID){return new Promise(resolve=>{E621_1.E621.Favorite.id(postID).delete().then(response=>{Debug_1.Debug.log(response),resolve(!0)},error=>{console.log(error),resolve(!1)})})}}exports.PostActions=PostActions},{"../api/E621":5,"../utility/Debug":30}],21:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostFilter=void 0;const APIPost_1=require("../api/responses/APIPost"),Tag_1=require("../data/Tag"),User_1=require("../data/User"),Util_1=require("../utility/Util");exports.PostFilter=class{constructor(input,enabled=!0,options){if(this.input=input.toLowerCase().trim(),this.entries=[],this.enabled=enabled,this.matchIDs=new Set,this.optionals=0,options&&(options.favorites&&this.entries.push({type:FilterType.Fav,value:User_1.User.getUsername(),inverted:!0,optional:!1,comparison:ComparisonType.Equals}),options.uploads&&this.entries.push({type:FilterType.UserID,value:User_1.User.getUserID()+"",inverted:!0,optional:!1,comparison:ComparisonType.Equals}),options.whitelist))for(const tag of options.whitelist.split(" "))this.entries.push({type:FilterType.Tag,value:tag,inverted:!0,optional:!1,comparison:ComparisonType.Equals});for(let filter of new Set(this.input.split(" ").filter(e=>""!=e))){const optional=filter.startsWith("~");optional&&(filter=filter.substring(1),this.optionals++);const inverse=filter.startsWith("-");inverse&&(filter=filter.substring(1));const filterType=FilterType.test(filter);filterType!==FilterType.Tag&&(filter=filter.substring(filterType.length));const comparison=ComparisonType.test(filter);switch(comparison!==ComparisonType.Equals&&(filter=filter.substring(comparison.length)),filterType){case FilterType.Size:filter=Util_1.Util.unformatBytes(filter)+""}this.entries.push({type:filterType,value:filter,inverted:inverse,optional:optional,comparison:comparison})}}getName(){return this.input}update(post,shouldDecrement=!0){if(Array.isArray(post)){let result=!0;for(const entry of post)result=!!this.update(entry)&&result;return result}let result=!0,optionalHits=0;for(const filter of this.entries){const value=filter.value;switch(filter.type){case FilterType.Flag:result=post.flags.has(APIPost_1.PostFlag.fromSingle(value));break;case FilterType.Id:result=PostFilterUtils.compareNumbers(post.id,parseInt(value),filter.comparison);break;case FilterType.Rating:result=post.rating===APIPost_1.PostRating.fromValue(value);break;case FilterType.Score:result=PostFilterUtils.compareNumbers(post.score,parseInt(value),filter.comparison);break;case FilterType.FavCount:result=PostFilterUtils.compareNumbers(post.favorites,parseInt(value),filter.comparison);break;case FilterType.Tag:result=PostFilterUtils.tagsMatchesFilter(post,value);break;case FilterType.Uploader:case FilterType.UserID:result=post.uploader===parseInt(value);break;case FilterType.Fav:result=post.is_favorited;break;case FilterType.Height:result=PostFilterUtils.compareNumbers(post.img.height,parseInt(value),filter.comparison);break;case FilterType.Width:result=PostFilterUtils.compareNumbers(post.img.width,parseInt(value),filter.comparison);break;case FilterType.Size:result=PostFilterUtils.compareNumbers(post.file.size,parseInt(value),filter.comparison);break;case FilterType.Duration:result=null==post.file.duration||PostFilterUtils.compareNumbers(post.file.duration,parseFloat(value),filter.comparison)}if(filter.inverted&&(result=!result),filter.optional)optionalHits+=result?1:0;else if(!result)break}return result=result&&(0==this.optionals||optionalHits>0),!0===result?this.matchIDs.add(post.id):!1===result&&shouldDecrement&&this.matchIDs.delete(post.id),result}matches(post,ignoreDisabled=!1){return this.matchesID(post.id,ignoreDisabled)}matchesID(id,ignoreDisabled=!1){return(this.enabled||ignoreDisabled)&&this.matchIDs.has(id)}getMatches(){return this.matchIDs}getMatchesCount(){return this.matchIDs.size}toggleEnabled(){this.enabled=!this.enabled}setEnabled(enabled){this.enabled=enabled}isEnabled(){return this.enabled}};class PostFilterUtils{static compareNumbers(a,b,mode){switch(mode){case ComparisonType.Equals:return a===b;case ComparisonType.Smaller:return a<b;case ComparisonType.EqualsSmaller:return a<=b;case ComparisonType.Larger:return a>b;case ComparisonType.EqualsLarger:return a>=b}}static tagsMatchesFilter(post,filter){if(filter.includes("*")){return Tag_1.Tag.escapeSearchToRegex(filter).test(post.tagString)}return post.tags.all.has(filter)}}var FilterType,ComparisonType;!function(FilterType){FilterType.Tag="tag:",FilterType.Id="id:",FilterType.Score="score:",FilterType.FavCount="favcount:",FilterType.Rating="rating:",FilterType.Uploader="uploader:",FilterType.UserID="userid:",FilterType.Flag="status:",FilterType.Fav="fav:",FilterType.Height="height:",FilterType.Width="width:",FilterType.Size="filesize:",FilterType.Duration="duration:"}(FilterType||(FilterType={})),function(FilterType){FilterType.test=function(input){input=input.toLowerCase();for(const key of Object.keys(FilterType))if(input.startsWith(FilterType[key]))return FilterType[key];return FilterType.Tag}}(FilterType||(FilterType={})),function(ComparisonType){ComparisonType.EqualsSmaller="<=",ComparisonType.EqualsLarger=">=",ComparisonType.Equals="=",ComparisonType.Smaller="<",ComparisonType.Larger=">"}(ComparisonType||(ComparisonType={})),function(ComparisonType){ComparisonType.test=function(input){input=input.toLowerCase();for(const key of Object.keys(ComparisonType))if(input.startsWith(ComparisonType[key]))return ComparisonType[key];return ComparisonType.Equals}}(ComparisonType||(ComparisonType={}))},{"../api/responses/APIPost":11,"../data/Tag":17,"../data/User":18,"../utility/Util":33}],22:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostParts=void 0;const BetterSearch_1=require("../../modules/search/BetterSearch"),CustomFlagger_1=require("../../modules/search/CustomFlagger"),Danbooru_1=require("../api/Danbooru"),APIPost_1=require("../api/responses/APIPost"),XM_1=require("../api/XM"),Blacklist_1=require("../data/Blacklist"),Page_1=require("../data/Page"),DomUtilities_1=require("../structure/DomUtilities"),Util_1=require("../utility/Util"),Post_1=require("./Post"),PostActions_1=require("./PostActions");class PostParts{static renderImage(post,conf){const query=Page_1.Page.getQueryParameter("tags"),$link=$("<a>").attr({href:"/posts/"+post.id+(null!==query?"?q="+query:"")}).append(PostParts.renderImageElement(post,conf)).append($("<post-loading>"));return post.file.duration&&$("<span>").addClass("video-duration").html(Util_1.Util.Time.formatPlaytime(post.file.duration)).appendTo($link),conf.clickAction!==BetterSearch_1.ImageClickAction.Disabled&&PostParts.handleDoubleClick($link,post,conf),$link}static handleDoubleClick($link,post,conf){let dblclickTimer,prevent=!1;$link.on("click.re621.dbl-extra",event=>{if(!(0!==event.button||event.shiftKey||event.ctrlKey||event.altKey||event.metaKey||BetterSearch_1.BetterSearch.isPaused()||"view"!==$("#mode-box-mode").val()))return event.preventDefault(),dblclickTimer=window.setTimeout(()=>{prevent||($link.off("click.re621.dbl-extra"),$link[0].click()),prevent=!1},200),!1}),$link.on("dblclick.re621.dbl-extra",event=>{if(!(0!==event.button||event.shiftKey||event.ctrlKey||event.altKey||event.metaKey||BetterSearch_1.BetterSearch.isPaused()||"view"!==$("#mode-box-mode").val()))switch(event.preventDefault(),window.clearTimeout(dblclickTimer),prevent=!0,post.$ref.addClass("highlight"),window.setTimeout(()=>post.$ref.removeClass("highlight"),250),conf.clickAction){case BetterSearch_1.ImageClickAction.NewTab:XM_1.XM.Util.openInTab(window.location.origin+$link.attr("href"),!1);break;case BetterSearch_1.ImageClickAction.CopyID:XM_1.XM.Util.setClipboard(post.id+"","text"),Danbooru_1.Danbooru.notice(`Copied post ID to clipboard: <a href="/posts/${post.id}" target="_blank">#${post.id}</a>`);break;case BetterSearch_1.ImageClickAction.Blacklist:Blacklist_1.Blacklist.toggleBlacklistTag("id:"+post.id);break;case BetterSearch_1.ImageClickAction.AddToSet:{const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.addSet(lastSet,post.id):Danbooru_1.Danbooru.error("Error: no set selected");break}case BetterSearch_1.ImageClickAction.ToggleSet:{const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.toggleSet(lastSet,post.id):Danbooru_1.Danbooru.error("Error: no set selected");break}default:$link.off("click.re621.dbl-extra"),$link[0].click()}})}static renderImageElement(post,conf){post.$ref.attr("loading","true");const $image=$("<img>").attr("src",DomUtilities_1.DomUtilities.getPlaceholderImage()).one("load",()=>{post.$ref.removeAttr("loading")});if(conf.hoverTags&&$image.attr("title",PostParts.formatHoverText(post)),post.flags.has(APIPost_1.PostFlag.Deleted))post.img.ratio=1,post.loaded=Post_1.LoadedFileType.ORIGINAL;else if("swf"===post.file.ext)post.img.ratio=1,post.loaded=Post_1.LoadedFileType.ORIGINAL;else if("gif"!==post.file.ext||conf.imageLoadMethod!=BetterSearch_1.ImageLoadMethod.Always||conf.autoPlayGIFs){const size=function(cur,req){if(!cur)return req==BetterSearch_1.ImageLoadMethod.Always?Post_1.LoadedFileType.SAMPLE:Post_1.LoadedFileType.PREVIEW;if(req==BetterSearch_1.ImageLoadMethod.Always)return Post_1.LoadedFileType.SAMPLE;if(req==BetterSearch_1.ImageLoadMethod.Disabled)return Post_1.LoadedFileType.PREVIEW;return cur}(post.loaded,conf.imageLoadMethod);size==Post_1.LoadedFileType.SAMPLE?$image.attr("src",post.file.sample):$image.attr("src",post.file.preview),post.loaded=size}else if(post.loaded==Post_1.LoadedFileType.SAMPLE)$image.attr("src",post.file.sample);else{let timer;$image.attr("src",post.file.preview),post.loaded=Post_1.LoadedFileType.PREVIEW,$image.on("mouseenter.re621.upscale",()=>{timer=window.setTimeout(()=>{post.$ref.attr("loading","true"),post.loaded=Post_1.LoadedFileType.SAMPLE,$image.attr("src",post.file.sample).on("load",()=>{post.$ref.removeAttr("loading"),$image.off("mouseenter.re621.upscale").off("mouseleave.re621.upscale")})},200)}),$image.on("mouseleave.re621.upscale",()=>{window.clearTimeout(timer)})}if(conf.imageLoadMethod==BetterSearch_1.ImageLoadMethod.Hover&&post.loaded==Post_1.LoadedFileType.PREVIEW){let timer;$image.on("mouseenter.re621.upscale",()=>{timer=window.setTimeout(()=>{post.$ref.attr("loading","true"),post.loaded=Post_1.LoadedFileType.SAMPLE,$image.attr("src",post.file.sample).one("load",()=>{post.$ref.removeAttr("loading"),$image.off("mouseenter.re621.upscale").off("mouseleave.re621.upscale")})},200)}),$image.on("mouseleave.re621.upscale",()=>{window.clearTimeout(timer)})}return $image}static renderRibbons(post,conf){const $ribbons=$("<img-ribbons>");if(conf.ribbonsRel){const relRibbon=$("<ribbon>").addClass("left").html("<span></span>").appendTo($ribbons),relRibbonText=[];post.has.children&&(relRibbon.addClass("has-children"),relRibbonText.push("Child posts")),post.has.parent&&(relRibbon.addClass("has-parent"),relRibbonText.push("Parent posts")),relRibbonText.length>0?relRibbon.attr("title",relRibbonText.join("\n")):relRibbon.remove()}if(conf.ribbonsFlag){const flagRibbon=$("<ribbon>").addClass("right").html("<span></span>").appendTo($ribbons),flagRibbonText=[];post.flags.has(APIPost_1.PostFlag.Flagged)&&(flagRibbon.addClass("is-flagged"),flagRibbonText.push("Flagged")),post.flags.has(APIPost_1.PostFlag.Pending)&&(flagRibbon.addClass("is-pending"),flagRibbonText.push("Pending")),flagRibbonText.length>0?flagRibbon.attr("title",flagRibbonText.join("\n")):flagRibbon.remove()}if(0!=$ribbons.children().length)return $ribbons}static renderButtons(post,conf){const $voteBox=$("<post-voting>");if(conf.buttonsVote&&($("<button>").addClass("button voteButton vote score-neutral").attr("action","up").appendTo($voteBox).on("click",event=>{event.preventDefault();const firstVote=null==post.$ref.attr("vote");PostActions_1.PostActions.vote(post.id,1,firstVote).then(response=>{0==response.action?firstVote?post.$ref.attr("vote","1"):post.$ref.attr("vote","0"):post.$ref.attr("vote",response.action),post.score=response.score,post.$ref.trigger("re621:update")},error=>{Danbooru_1.Danbooru.error("An error occurred while recording the vote"),console.log(error)})}),$("<button>").addClass("button voteButton vote score-neutral").attr("action","down").appendTo($voteBox).on("click",event=>{event.preventDefault();const firstVote=null==parseInt(post.$ref.attr("vote"));PostActions_1.PostActions.vote(post.id,-1,firstVote).then(response=>{0==response.action?firstVote?post.$ref.attr("vote","-1"):post.$ref.attr("vote","0"):post.$ref.attr("vote",response.action),post.score=response.score,post.$ref.trigger("re621:update")},error=>{Danbooru_1.Danbooru.error("An error occurred while recording the vote"),console.log(error)})})),conf.buttonsFav){let favBlock=!1;const $btn=$("<button>").addClass("button voteButton fav score-neutral").appendTo($voteBox).on("click",async event=>{event.preventDefault(),favBlock||(favBlock=!0,post.is_favorited?(await PostActions_1.PostActions.removeFavorite(post.id),post.is_favorited=!1,post.$ref.removeAttr("fav"),$btn.removeClass("score-favorite")):(await PostActions_1.PostActions.addFavorite(post.id),post.is_favorited=!0,post.$ref.attr("fav","true"),$btn.addClass("score-favorite")),favBlock=!1)})}return $voteBox}static renderFlags(post){const $flagBox=$("<post-flags>");for(const flag of CustomFlagger_1.CustomFlagger.getFlags(post))$("<span>").addClass("custom-flag-thumb").css("--flag-color",flag.color).attr("title",flag.tags).html(flag.name).appendTo($flagBox);if(0!=$flagBox.children().length)return $flagBox}static renderInfo(post){const $infoBlock=$("<post-info>");return post.$ref.on("re621:update",()=>{$infoBlock.html(getPostInfo(post))}),$infoBlock.html(getPostInfo(post)),$infoBlock;function getPostInfo(post){return`\n <span class="post-info-score score-${post.score>0?"positive":post.score<0?"negative":"neutral"}">${post.score}</span>\n <span class="post-info-favorites">${post.favorites}</span>\n <span class="post-info-comments">${post.comments}</span>\n <span class="post-info-rating rating-${post.rating}">${post.rating}</span>\n `}}static formatHoverText(post,compact=!1,html=!1){const br=html?"<br>\n":"\n";return compact?[...post.tags.artist,...post.tags.copyright].join(" ")+" "+[...post.tags.character,...post.tags.species].join(" ")+" "+[...post.tags.general,...post.tags.invalid,...post.tags.lore,...post.tags.meta].join(" "):`Post #${post.id}, posted on: ${Util_1.Util.Time.format(post.date.raw)} (${post.date.ago})${br}${[...post.tags.artist,...post.tags.copyright].join(" ")}${br}${[...post.tags.character,...post.tags.species].join(" ")}${br}${[...post.tags.general,...post.tags.invalid,...post.tags.lore,...post.tags.meta].join(" ")}${br}`}}exports.PostParts=PostParts},{"../../modules/search/BetterSearch":56,"../../modules/search/CustomFlagger":58,"../api/Danbooru":3,"../api/XM":6,"../api/responses/APIPost":11,"../data/Blacklist":14,"../data/Page":16,"../structure/DomUtilities":25,"../utility/Util":33,"./Post":19,"./PostActions":20}],23:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostSortType=exports.PostSet=void 0;class PostSet{constructor(posts){this.posts=posts||[]}push(post){this.posts.push(post)}pop(){return this.posts.pop()}size(){return this.posts.length}reverse(){return new PostSet(this.posts.reverse())}values(){return this.posts.values()}entries(){return this.posts}each(fn){for(const entry of this.posts)fn(entry)}sort(type){switch(type||(type=PostSortType.ID),type){case PostSortType.Size:return this.sort(PostSortType.Size).reverse();case PostSortType.SizeAsc:return new PostSet([...this.posts.sort((a,b)=>a.file.size-b.file.size)]);case PostSortType.ID:return this.sort(PostSortType.ID).reverse();case PostSortType.IDAsc:return new PostSet([...this.posts.sort((a,b)=>a.id-b.id)])}}}var PostSortType;exports.PostSet=PostSet,function(PostSortType){PostSortType.ID="id",PostSortType.IDAsc="id_asc",PostSortType.Size="size",PostSortType.SizeAsc="size_asc"}(PostSortType=exports.PostSortType||(exports.PostSortType={}))},{}],24:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CleanSlate=void 0;const XM_1=require("../api/XM"),Keybinds_1=require("../data/Keybinds"),Page_1=require("../data/Page"),Debug_1=require("../utility/Debug"),ErrorHandler_1=require("../utility/ErrorHandler"),Util_1=require("../utility/Util"),DomUtilities_1=require("./DomUtilities");exports.CleanSlate=class{static async createDOM(){const actions=[];return actions.push({selector:"head",action:async()=>{try{const css=await XM_1.XM.Connect.getResourceText("re621_css"),stylesheet=DomUtilities_1.DomUtilities.addStyle(css);return $(()=>{stylesheet.appendTo("head")}),Promise.resolve(stylesheet)}catch(error){ErrorHandler_1.ErrorHandler.error("DOM",error.stack,"styles")}"undefined"==typeof GM&&$("<script>").attr("src",XM_1.XM.Chrome.getResourceURL("injector.js")).appendTo("head")}}),actions.push({selector:"body",action:()=>{$("body").attr({"data-th-main":window.localStorage.getItem("theme"),"data-th-extra":window.localStorage.getItem("theme-extra"),"data-th-nav":window.localStorage.getItem("theme-nav")})}}),actions.push({selector:"#page",action:()=>{$("<div>").attr("id","modal-container").prependTo("div#page")}}),actions.push({selector:"#nav",action:()=>{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}">`+Page_1.Page.getSiteName()+"</a>").prependTo($menuContainer),$menuMain.find("a[href='/']").remove(),$("<menu>").addClass("extra").insertAfter($menuMain),$menuContainer.addClass("grid")}}),Page_1.Page.matches([Page_1.PageDefinition.search,Page_1.PageDefinition.favorites])&&"true"===Util_1.Util.LS.getItem("re621.bs.enabled")&&actions.push({selector:"div.paginator menu",action:()=>{$("div.paginator menu").css("display","none").attr("id","paginator-old").appendTo("body"),$("#content").html("")}}),Page_1.Page.matches(Page_1.PageDefinition.post)&&actions.push({selector:"#image-container",action:()=>{"swf"===$("#image-container").attr("data-file-ext")&&Keybinds_1.KeybindManager.disable()}}),this.elementsReady(actions)}static async elementsReady(actions){const processed=new Map;for(const action of actions)processed.set(action.selector,action.action);let iterations=0;return new Promise(resolve=>{const observer=new MutationObserver(()=>{for(const[selector,action]of processed.entries())0!=$(selector).length&&(processed.delete(selector),action());iterations++,0==processed.size?(observer.disconnect(),resolve(!0)):iterations>100&&(observer.disconnect(),resolve(!1))});observer.observe(document,{childList:!0,subtree:!0}),$(()=>{observer.disconnect();for(const action of processed.values())action();resolve(!1)})})}static async awaitFocus(){return new Promise(resolve=>{document.hasFocus()||"visible"==document.visibilityState?resolve(!0):(Debug_1.Debug.log("CleanSlate: waiting for focus"),$(window).one("focus",()=>{Debug_1.Debug.log("CleanSlate: received focus"),resolve(!0)}))})}}},{"../api/XM":6,"../data/Keybinds":15,"../data/Page":16,"../utility/Debug":30,"../utility/ErrorHandler":31,"../utility/Util":33,"./DomUtilities":25}],25:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.DomUtilities=void 0;const Page_1=require("../data/Page"),Util_1=require("../utility/Util");exports.DomUtilities=class{static createSearchbox(){if(Page_1.Page.matches([Page_1.PageDefinition.search,Page_1.PageDefinition.post,Page_1.PageDefinition.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();$("<span>").addClass("tag-wrap").insertAfter($tagLink).append($tagLink);const $actionsBox=$("<div>").addClass("tag-actions").attr("data-tag",$container.find("a.search-tag").text().replace(/ /g,"_")).appendTo($container);$("<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 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=="}}},{"../data/Page":16,"../utility/Util":33}],26:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.FormElement=exports.Form=void 0;const XM_1=require("../api/XM"),Keybinds_1=require("../data/Keybinds"),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&&null!==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.title&&$input.attr("title",options.title),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&&null!==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 options.title&&($input.attr("title",options.title),$copyButton.attr("title",options.title)),$($copyButton).on("click",()=>{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&&null!==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)}$input.attr("key",$input.val()+"")}const $warning=$("<span>").addClass("keyinput-warning").attr("title","Duplicate Keybinding").appendTo($element);Keybinds_1.KeybindManager.count($input.val()+"")<=1&&$warning.addClass("display-none");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);options.title&&($input.attr("title",options.title),$recordButton.attr("title",options.title));let occupied=!1;return $($recordButton).on("click",()=>{if(occupied)return;occupied=!0;const duplicates=$(`.keyinput input[key="${$input.val()}"]`);duplicates.length>2?$warning.addClass("display-none"):duplicates.parent().find("span.keyinput-warning").addClass("display-none"),$input.addClass("input-info").val("Recording"),Keybinds_1.KeybindManager.record(sequence=>{if(sequence.includes("escape"))$input.removeClass("input-info").val("").attr("key",""),void 0!==changed&&changed("",$input),occupied=!1;else{const newVal=(input=(input=sequence).join("+").split("+"),(input=[...new Set(input)]).join("+"));$input.removeClass("input-info").val(newVal).attr("key",newVal);const duplicates=$(`.keyinput input[key="${newVal}"]`);duplicates.length>1&&duplicates.parent().find("span.keyinput-warning").removeClass("display-none"),void 0!==changed&&changed(newVal,$input),occupied=!1}var input})}),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 options.title&&$input.attr("title",options.title),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&&null!==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").on("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().trigger("click"):$selectContainer.find("a").first().trigger("click"),$input.on("re621:form:update",()=>{""==$input.val()?$selectContainer.find("a").first().trigger("click"):$selectContainer.find("a[data-value='"+$input.val()+"']").first().trigger("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&&null!==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 options.title&&$input.attr("title",options.title),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&&null!==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&&null!==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 options.title&&$input.attr("title",options.title),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&&null!==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)}return new FormElement($element,void 0,$label)}static text(text,width=1,wrapper){return Form.div({value:text,width:width,wrapper:wrapper})}static requiresReload(){return Form.text('<div class="text-center text-bold">Requires a page reload</div>',1,"align-middle")}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":6,"../data/Keybinds":15,"../utility/Util":33}],27:[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).on("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":33}],28:[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.trigger("focus"),this.promise=new Promise((resolve,reject)=>{this.$form.on("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":27}],29:[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":33}],30:[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":6}],31:[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.getSettingsTag()),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":6,"../structure/Modal":27,"./Patcher":32}],32:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Patcher=void 0;const HoverZoom_1=require("../../modules/search/HoverZoom"),XM_1=require("../api/XM"),Debug_1=require("./Debug"),ErrorHandler_1=require("./ErrorHandler");class Patcher{static async patchConfig(){let counter=0;Patcher.version=await XM_1.XM.Storage.getValue("re621.patchVersion",0);try{switch(Patcher.version){case 0:counter+=await this.patch1();case 1:counter+=await this.patch2();case 2:counter+=await this.patch3();case 3:counter+=await this.patch4();case 4:counter+=await this.patch5();case 5:counter+=await this.patch6();case 6:case 7:counter+=await this.patch8();case 8:counter+=await this.patch9()}}catch(error){ErrorHandler_1.ErrorHandler.error("Patcher",error.stack,"patch "+Patcher.version)}Debug_1.Debug.log(`Patcher: ${counter} records changed`),await XM_1.XM.Storage.setValue("re621.patchVersion",Patcher.version)}static async patch1(){let counter=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++)}return Patcher.version=1,counter}static async patch2(){let counter=0;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++);return await XM_1.XM.Storage.setValue("re621.Miscellaneous",miscSettings),await XM_1.XM.Storage.setValue("re621.SearchUtilities",searchUtilities),Patcher.version=2,counter}static async patch3(){let counter=0;return void 0!==await XM_1.XM.Storage.getValue("re621.report",void 0)&&(await XM_1.XM.Storage.deleteValue("re621.report"),counter++),Patcher.version=3,counter}static async patch4(){let counter=0;return window.localStorage.removeItem("re621.favorites"),window.localStorage.removeItem("re621.dnp.cache"),counter+=2,Patcher.version=4,2}static async patch5(){let counter=0;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")}return Patcher.version=5,counter}static async patch6(){let counter=0;const thumbEnhancer=await XM_1.XM.Storage.getValue("re621.ThumbnailEnhancer",void 0),infiniteScroll=await XM_1.XM.Storage.getValue("re621.InfiniteScroll",void 0),betterSearch=await XM_1.XM.Storage.getValue("re621.BetterSearch",{});return thumbEnhancer&&(betterSearch.imageLoadMethod=thumbEnhancer.upscale,betterSearch.autoPlayGIFs=thumbEnhancer.autoPlayGIFs,betterSearch.hoverTags=thumbEnhancer.preserveHoverText,"onshift"==thumbEnhancer.zoom?betterSearch.zoomMode=HoverZoom_1.ImageZoomMode.OnShift:"true"==thumbEnhancer.zoom?betterSearch.zoomMode=HoverZoom_1.ImageZoomMode.Hover:betterSearch.zoomMode=HoverZoom_1.ImageZoomMode.Disabled,betterSearch.imageSizeChange=thumbEnhancer.crop,betterSearch.imageWidth=(thumbEnhancer.cropSize||"150").replace(/px/g,""),betterSearch.imageRatioChange=!thumbEnhancer.cropPreserveRatio,betterSearch.imageRatio=thumbEnhancer.cropRatio,betterSearch.ribbonsFlag=thumbEnhancer.ribbons,betterSearch.ribbonsRel=thumbEnhancer.relRibbons,betterSearch.buttonsVote=thumbEnhancer.vote,betterSearch.buttonsFav=thumbEnhancer.fav,counter+=12,await XM_1.XM.Storage.setValue("re621.BetterSearch",betterSearch),await XM_1.XM.Storage.deleteValue("re621.ThumbnailEnhancer")),infiniteScroll&&(betterSearch.infiniteScroll=infiniteScroll.enabled,betterSearch.loadPrevPages=infiniteScroll.keepHistory,counter+=2,await XM_1.XM.Storage.setValue("re621.BetterSearch",betterSearch),await XM_1.XM.Storage.deleteValue("re621.InfiniteScroll")),window.localStorage.removeItem("re621.favcache.data"),window.localStorage.removeItem("re621.favcache.invalid"),window.localStorage.removeItem("re621.favcache.update"),counter+=3,Patcher.version=6,counter}static async patch8(){return await XM_1.XM.Storage.deleteValue("re621.sync"),Patcher.version=8,1}static async patch9(){let counter=0;const betterSearch=await XM_1.XM.Storage.getValue("re621.BetterSearch",{}),hoverZoom=await XM_1.XM.Storage.getValue("re621.HoverZoom",{});void 0!==betterSearch.zoomMode&&(hoverZoom.mode=betterSearch.zoomMode,delete betterSearch.zoomMode,counter++),void 0!==betterSearch.zoomTags&&(hoverZoom.tags=betterSearch.zoomTags,delete betterSearch.zoomTags,counter++);for(const deletedEntry of["zoomFull","zoomScale","zoomContextual"])delete betterSearch[deletedEntry],counter++;return await XM_1.XM.Storage.setValue("re621.BetterSearch",betterSearch),await XM_1.XM.Storage.setValue("re621.HoverZoom",hoverZoom),Patcher.version=9,counter}}exports.Patcher=Patcher},{"../../modules/search/HoverZoom":59,"../api/XM":6,"./Debug":30,"./ErrorHandler":31}],33:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Util=void 0;const UtilID_1=require("./UtilID"),UtilMath_1=require("./UtilMath"),UtilTime_1=require("./UtilTime");class Util{static downloadAsJSON(data,file){const tempLink=$("<a>").attr({download:file+".json",href:"data:application/json,"+encodeURIComponent(JSON.stringify(data,null,4))}).appendTo("body").on("click",()=>{tempLink.remove()});tempLink[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(/\_(.*?\S)\_/gm,"<em>$1</em>").replace(/\[(.+)\]\((.*)\)/gm,'<a href="$2">$1</a>').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))+["B","KB","MB","GB","TB","PB"][i]}static unformatBytes(input){if(Util.Math.isNumeric(input))return parseInt(input);input=input.toUpperCase();for(const[index,size]of[/\dB$/,/\dKB$/,/\dMB$/,/\dGB$/,/\dTB$/,/\dPB$/].entries())if(size.test(input))return parseInt(input)*Math.pow(1024,index);return 0}static formatK(num){return Math.abs(num)>999?(Math.sign(num)*(Math.abs(num)/1e3)).toFixed(1)+"k":Math.sign(num)*Math.abs(num)+""}static formatRatio(width,height){const d=function gcd(u,v){if(u===v)return u;if(0===u)return v;if(0===v)return u;if(1&~u)return 1&v?gcd(u>>1,v):gcd(u>>1,v>>1)<<1;return 1&~v?gcd(u,v>>1):u>v?gcd(u-v>>1,v):gcd(v-u>>1,u)}(width,height);return[width/d,height/d]}static getTagString(input){return input.val().toString().trim().toLowerCase().replace(/\r?\n|\r/g," ").replace(/(?:\s){2,}/g," ")}static getTags(input){return("string"==typeof input?input:Util.getTagString(input)).split(" ").filter(el=>null!=el&&""!=el)}static getKeyRegex(object){const result=[];for(const key of Object.keys(object))result.push(key.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));return new RegExp(result.join("|"),"gi")}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.Math=UtilMath_1.UtilMath,Util.LS=window.localStorage,Util.SS=window.sessionStorage},{"./UtilID":34,"./UtilMath":35,"./UtilTime":36}],34:[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},{}],35:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.UtilMath=void 0;exports.UtilMath=class{static clamp(value,min,max){return Math.min(Math.max(value,min),max)}static between(value,min,max){return min<=value&&max>=value}static isNumeric(value){return!isNaN(Number(value))}static round(num,decimal=2){return parseFloat(num.toFixed(decimal))}}},{}],36:[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",UtilTime[UtilTime.MONTH=2592e6]="MONTH",UtilTime[UtilTime.YEAR=31536e6]="YEAR"}(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&&"string"!=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.formatPeriod=function(input){return input<UtilTime.MINUTE?(input/UtilTime.SECOND).toFixed(1)+" seconds":input<UtilTime.HOUR?(input/UtilTime.MINUTE).toFixed(1)+" minutes":input<UtilTime.DAY?(input/UtilTime.HOUR).toFixed(1)+" hours":input<UtilTime.WEEK?(input/UtilTime.DAY).toFixed(1)+" days":input<UtilTime.MONTH?(input/UtilTime.WEEK).toFixed(1)+" weeks":input<UtilTime.YEAR?(input/UtilTime.MONTH).toFixed(1)+" months":(input/UtilTime.YEAR).toFixed(1)+" years"},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())},UtilTime.formatPlaytime=function(seconds){const remainder=(seconds=Math.ceil(seconds))%60;return Math.floor(seconds/60)+":"+(remainder<10?"0":"")+remainder}}(exports.UtilTime||(exports.UtilTime={}))},{}],37:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.VersionChecker=void 0;const XM_1=require("../api/XM"),Debug_1=require("./Debug"),Util_1=require("./Util");class VersionChecker{static async init(){const emVersion=Util_1.Util.LS.getItem("re621.version");VersionChecker.scriptBuild=emVersion||window.re621.version;const settings=await XM_1.XM.Storage.getValue("re621.VersionChecker",{});if(void 0!==settings.latestBuild&&(VersionChecker.latestBuild=settings.latestBuild),void 0!==settings.cachedBuild&&(VersionChecker.cachedBuild=settings.cachedBuild),VersionChecker.cachedBuild!==VersionChecker.scriptBuild&&(VersionChecker.wasUpdated=!0),Util_1.Util.versionCompare(VersionChecker.cachedBuild,VersionChecker.latestBuild)<0&&(VersionChecker.hasUpdate=!0),void 0!==settings.lastUpdated&&(VersionChecker.lastUpdated=settings.lastUpdated),void 0!==settings.changesText&&(VersionChecker.changesText=settings.changesText),VersionChecker.scriptBuild.includes("dev"))VersionChecker.wasUpdated=!1,VersionChecker.hasUpdate=!1;else if(VersionChecker.wasUpdated||VersionChecker.lastUpdated+Util_1.Util.Time.HOUR<Util_1.Util.Time.now()){const latestRelease=await VersionChecker.getGithubData("latest");VersionChecker.latestBuild=latestRelease.name,VersionChecker.cachedBuild=VersionChecker.scriptBuild,VersionChecker.hasUpdate=Util_1.Util.versionCompare(VersionChecker.scriptBuild,VersionChecker.latestBuild)<0,VersionChecker.lastUpdated=Util_1.Util.Time.now(),VersionChecker.changesText=latestRelease.body}VersionChecker.changesHTML=Util_1.Util.quickParseMarkdown(VersionChecker.changesText),Debug_1.Debug.log("VersionChecker",{scriptBuild:VersionChecker.scriptBuild,latestBuild:VersionChecker.latestBuild,cachedBuild:VersionChecker.cachedBuild,wasUpdated:VersionChecker.wasUpdated,hasUpdate:VersionChecker.hasUpdate,lastUpdated:VersionChecker.lastUpdated,changesText:VersionChecker.changesText,changesHTML:VersionChecker.changesHTML}),await XM_1.XM.Storage.setValue("re621.VersionChecker",{latestBuild:VersionChecker.latestBuild,cachedBuild:VersionChecker.cachedBuild,lastUpdated:VersionChecker.lastUpdated,changesText:VersionChecker.changesText})}static async 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")})}}exports.VersionChecker=VersionChecker,VersionChecker.scriptBuild="0.0.1",VersionChecker.latestBuild="0.0.1",VersionChecker.cachedBuild="0.0.1",VersionChecker.wasUpdated=!1,VersionChecker.hasUpdate=!1,VersionChecker.lastUpdated=0,VersionChecker.changesText="_~ Changelog not available ~_",VersionChecker.changesHTML=""},{"../api/XM":6,"./Debug":30,"./Util":33}],38:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const Danbooru_1=require("./components/api/Danbooru"),Page_1=require("./components/data/Page"),ModuleController_1=require("./components/ModuleController"),CleanSlate_1=require("./components/structure/CleanSlate"),DomUtilities_1=require("./components/structure/DomUtilities"),Debug_1=require("./components/utility/Debug"),Patcher_1=require("./components/utility/Patcher"),Util_1=require("./components/utility/Util"),VersionChecker_1=require("./components/utility/VersionChecker"),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"),EditTracker_1=require("./modules/misc/EditTracker"),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"),BetterSearch_1=require("./modules/search/BetterSearch"),BlacklistEnhancer_1=require("./modules/search/BlacklistEnhancer"),CustomFlagger_1=require("./modules/search/CustomFlagger"),HoverZoom_1=require("./modules/search/HoverZoom"),InstantFilters_1=require("./modules/search/InstantFilters"),PostSuggester_1=require("./modules/search/PostSuggester"),SearchUtilities_1=require("./modules/search/SearchUtilities"),ThumbnailTweaks_1=require("./modules/search/ThumbnailTweaks"),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,BlacklistEnhancer_1.BlacklistEnhancer,CustomFlagger_1.CustomFlagger,ThumbnailTweaks_1.ThumbnailTweaks,BetterSearch_1.BetterSearch,InstantFilters_1.InstantFilters,HoverZoom_1.HoverZoom,PostSuggester_1.PostSuggester,SearchUtilities_1.SearchUtilities,Miscellaneous_1.Miscellaneous,SmartAlias_1.SmartAlias,EditTracker_1.EditTracker,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.PageDefinition.title)){const page=Util_1.Util.LS.getItem("re621.mainpage");page&&"default"!==page&&window.location.replace("/"+page)}Danbooru_1.Danbooru.Utility.disableShortcuts(!0),CleanSlate_1.CleanSlate.createDOM().then(async()=>{DomUtilities_1.DomUtilities.createSearchbox(),DomUtilities_1.DomUtilities.createTagList(),await Debug_1.Debug.init(),await Patcher_1.Patcher.patchConfig(),await VersionChecker_1.VersionChecker.init(),await ModuleController_1.ModuleController.register(subscriptions),await SubscriptionManager_1.SubscriptionManager.register(subscriptions),await ModuleController_1.ModuleController.register(loadOrder)})},{"./components/ModuleController":1,"./components/api/Danbooru":3,"./components/data/Page":16,"./components/structure/CleanSlate":24,"./components/structure/DomUtilities":25,"./components/utility/Debug":30,"./components/utility/Patcher":32,"./components/utility/Util":33,"./components/utility/VersionChecker":37,"./modules/downloader/FavDownloader":39,"./modules/downloader/MassDownloader":40,"./modules/downloader/PoolDownloader":41,"./modules/general/FormattingHelper":42,"./modules/general/HeaderCustomizer":43,"./modules/general/Miscellaneous":44,"./modules/general/SettingsController":45,"./modules/general/ThemeCustomizer":46,"./modules/misc/EditTracker":47,"./modules/misc/SmartAlias":48,"./modules/misc/UploadUtilities":49,"./modules/misc/WikiEnhancer":50,"./modules/post/DownloadCustomizer":51,"./modules/post/ImageScaler":52,"./modules/post/PoolNavigator":53,"./modules/post/PostViewer":54,"./modules/post/TitleCustomizer":55,"./modules/search/BetterSearch":56,"./modules/search/BlacklistEnhancer":57,"./modules/search/CustomFlagger":58,"./modules/search/HoverZoom":59,"./modules/search/InstantFilters":60,"./modules/search/PostSuggester":61,"./modules/search/SearchUtilities":62,"./modules/search/ThumbnailTweaks":63,"./modules/subscriptions/CommentTracker":64,"./modules/subscriptions/ForumTracker":65,"./modules/subscriptions/PoolTracker":66,"./modules/subscriptions/SubscriptionManager":67,"./modules/subscriptions/TagTracker":69}],39:[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"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util"),BetterSearch_1=require("../search/BetterSearch"),MassDownloader_1=require("./MassDownloader");class FavDownloader extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefinition.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}}create(){super.create(),this.userID=parseInt(Page_1.Page.getQueryParameter("user_id")||$("meta[name=current-user-id]").attr("content")),NaN!=this.userID&&(this.section=$("<section>").attr({id:"fav-downloader-box","data-fixed":this.fetchSettings("fixedSection")+""}).html("<h1>Download</h1>").appendTo("aside#sidebar"),$("#sidebar").on("re621:reflow",()=>{this.section.css("top",$("#re621-search").outerHeight()+"px")}),$("#sidebar").trigger("re621:reflow"),this.actButton=$("<a>").html("All").addClass("pool-download-button button btn-neutral").appendTo(this.section).on("click",event=>{event.preventDefault(),this.processFiles()}),this.visButton=$("<a>").html("Page").addClass("pool-download-button button btn-neutral").appendTo(this.section).on("click",event=>{event.preventDefault(),this.processFiles(!0)}),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(visible=!1){if(this.processing)return;this.processing=!0,this.actButton.attr("disabled","disabled"),this.visButton.attr("disabled","disabled"),$("search-content").attr("data-downloading","true"),BetterSearch_1.BetterSearch.setPaused(!0),this.infoText.attr("data-state","loading").html("Indexing favorites . . ."),0==this.posts.length&&(this.infoText.attr("data-state","loading").html("Fetching API data . . ."),this.posts=visible?Post_1.Post.find("existant").reverse().entries():(await async function recursiveLookup(output,info,userID,index=1){return info.html(" request "+index+" ["+output.length+"]"),E621_1.E621.Favorites.get({user_id:userID,page:index,limit:320}).then(data=>{for(const post of data){Post_1.PostData.fromAPI(post).has.file&&output.push(Post_1.PostData.fromAPI(post))}return console.log("counting",data.length),0==data.length?Promise.resolve(output):recursiveLookup(output,info,userID,++index)})}([],this.infoFile,this.userID)).reverse());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 queuedPost,totalFileSize=0,queueSize=0;for(this.batchOverSize=!1;queuedPost=this.posts.pop();){const post=queuedPost;if(totalFileSize+=post.file.size,Debug_1.Debug.log(`adding #${post.id} (${Util_1.Util.formatBytes(post.file.size)}) to the queue: ${Util_1.Util.formatBytes(totalFileSize)} total`),totalFileSize>FavDownloader.maxBlobSize){this.batchOverSize=!0,this.downloadOverSize=!0;break}$("#entry_"+post.id).addClass("download-item").attr("data-state","preparing"),downloadQueue.add({name:this.createFilename(post),path:post.file.original,file:post.file.original.match(/.{32}\..*$/g)[0],unid:post.id,date:new Date(post.date.raw),tags:post.tagString},{onStart:(item,thread,index)=>{this.infoText.html('Downloading ... <span class="float-right">'+(queueSize-index)+" / "+queueSize+"</span>"),threadInfo[thread].html(item.file).css("--progress","0%"),$("#entry_"+post.id).attr("data-state","loading")},onFinish:()=>{$("#entry_"+post.id).attr("data-state","done")},onError:()=>{$("#entry_"+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 . . . ");const zipData=await downloadQueue.run(metadata=>{this.infoText.html("Compressing . . . "+metadata.percent.toFixed(2)+"%"),metadata.currentFile?this.infoFile.html(metadata.currentFile):this.infoFile.html("")});let filename=this.userID+"-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:URL.createObjectURL(zipData),download:filename}).html("Download Archive").appendTo(this.infoText);this.fetchSettings("autoDownloadArchive")&&$downloadLink.get(0).click(),this.downloadIndex++,this.actButton.removeAttr("disabled"),this.visButton.removeAttr("disabled"),this.processing=!1,this.batchOverSize?this.fetchSettings("autoDownloadArchive")?visible?this.visButton.get(0).click():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):BetterSearch_1.BetterSearch.setPaused(!1)}createFilename(post){return MassDownloader_1.MassDownloader.createFilenameBase(this.fetchSettings("template"),post).slice(0,128).replace(/-{2,}/g,"-").replace(/-*$/g,"")+"."+post.file.ext}}exports.FavDownloader=FavDownloader,FavDownloader.maxBlobSize=838860800},{"../../components/RE6Module":2,"../../components/api/DownloadQueue":4,"../../components/api/E621":5,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/utility/Debug":30,"../../components/utility/Util":33,"../search/BetterSearch":56,"./MassDownloader":40}],40:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MassDownloader=void 0;const DownloadQueue_1=require("../../components/api/DownloadQueue"),Page_1=require("../../components/data/Page"),Post_1=require("../../components/post/Post"),PostSet_1=require("../../components/post/PostSet"),RE6Module_1=require("../../components/RE6Module"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util"),BetterSearch_1=require("../search/BetterSearch");class MassDownloader extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefinition.search,!0,!1,[BetterSearch_1.BetterSearch]),this.showInterface=!1,this.processing=!1,this.downloadOverSize=!1,this.fileTimestamp=Util_1.Util.Time.getDatetimeShort(),this.downloadIndex=0}getDefaultSettings(){return{enabled:!0,template:"%artist%/%postid%-%copyright%-%character%-%species%",autoDownloadArchive:!0}}create(){super.create(),this.section=$("<section>").attr({id:"downloader-box","data-fixed":this.fetchSettings("fixedSection")+""}).html("<h1>Download</h1>").appendTo("aside#sidebar"),$("#sidebar").on("re621:reflow",()=>{this.section.css("top",$("#re621-search").outerHeight()+"px")}),$("#sidebar").trigger("re621:reflow"),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=$("search-content")}destroy(){super.destroy(),BetterSearch_1.BetterSearch.off("pageload.MassDownloader")}toggleInterface(){this.showInterface=!this.showInterface,BetterSearch_1.BetterSearch.setPaused(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:"post",selected:function(event,ui){$(ui.selected).toggleClass("download-item").attr("data-state","ready")}}),BetterSearch_1.BetterSearch.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"),BetterSearch_1.BetterSearch.off("pageload.MassDownloader"))}toggleFixedSection(){"true"===this.section.attr("data-fixed")?this.section.attr("data-fixed","false"):this.section.attr("data-fixed","true")}setProcessing(state){this.processing=state,BetterSearch_1.BetterSearch.setPaused(state),state?this.actButton.attr("disabled","disabled"):this.actButton.removeAttr("disabled")}async processFiles(){if(this.processing)return;this.setProcessing(!0),this.infoText.attr("data-state","loading").html("Indexing selected files . . .");const postList=new PostSet_1.PostSet;if($("post.download-item[data-state=ready]").each((index,element)=>{postList.push(Post_1.Post.get($(element)))}),0===postList.size())return this.infoText.attr("data-state","error").html("Error: No files selected!"),void this.setProcessing(!1);Debug_1.Debug.log(`downloading ${postList.size()} files`),Debug_1.Debug.log(postList);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;this.downloadOverSize=!1;for(const post of postList.sort(PostSet_1.PostSortType.SizeAsc).values())if(post.has.file){if(totalFileSize+=post.file.size,Debug_1.Debug.log(`adding #${post.id} (${Util_1.Util.formatBytes(post.file.size)}) to the queue: ${Util_1.Util.formatBytes(totalFileSize)} total`),totalFileSize>MassDownloader.maxBlobSize){this.downloadOverSize=!0,Debug_1.Debug.log("over filesize limit, aborting");break}post.$ref.attr("data-state","preparing"),downloadQueue.add({name:this.createFilename(post),path:post.file.original,file:post.file.original.match(/.{32}\..*$/g)[0],unid:post.id,date:new Date(post.date.raw),tags:post.tagString},{onStart:(item,thread,index)=>{this.infoText.html('Downloading ... <span class="float-right">'+(queueSize-index)+" / "+queueSize+"</span>"),threadInfo[thread].html(item.file).css("--progress","0%"),$("#entry_"+item.unid).attr("data-state","loading")},onFinish:item=>{$("#entry_"+item.unid).attr("data-state","done")},onError:item=>{$("#entry_"+item.unid).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 . . . ");const zipData=await downloadQueue.run(metadata=>{this.infoText.html(`Compressing . . . ${metadata.percent.toFixed(2)}%`),metadata.currentFile?this.infoFile.html(metadata.currentFile):this.infoFile.html("")});this.infoText.attr("data-state","done").html("Done! "),this.infoFile.html(""),this.downloadIndex++;const filename=`e621-${this.fileTimestamp}-${this.downloadIndex}.zip`,$downloadLink=$("<a>").attr({href:URL.createObjectURL(zipData),download:filename}).html("Download Archive").appendTo(this.infoText);if(this.fetchSettings("autoDownloadArchive")){if($downloadLink.get(0).click(),this.downloadOverSize)return this.setProcessing(!1),void this.actButton.get(0).click()}else this.downloadOverSize&&$("<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.setProcessing(!1)}createFilename(post){return MassDownloader.createFilenameBase(this.fetchSettings("template"),post).slice(0,128).replace(/-{2,}/g,"-").replace(/-*$/g,"")+"."+post.file.ext}static createFilenameBase(template,post){return template.replace(/%postid%/g,post.id+"").replace(/%artist%/g,[...post.tags.artist].join("-")).replace(/%copyright%/g,[...post.tags.copyright].join("-")).replace(/%character%/g,[...post.tags.character].join("-")).replace(/%species%/g,[...post.tags.species].join("-")).replace(/%meta%/g,[...post.tags.meta].join("-")).replace(/%md5%/g,post.file.md5)}}exports.MassDownloader=MassDownloader,MassDownloader.maxBlobSize=838860800},{"../../components/RE6Module":2,"../../components/api/DownloadQueue":4,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/post/PostSet":23,"../../components/utility/Debug":30,"../../components/utility/Util":33,"../search/BetterSearch":56}],41:[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"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util"),MassDownloader_1=require("./MassDownloader");class PoolDownloader extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefinition.pool,Page_1.PageDefinition.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=[]}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.PageDefinition.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.PageDefinition.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(" 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.PageDefinition.pool)?"pool:":"set:")+pool.id,page:i,limit:320},500);this.infoFile.html(" 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,dataChunks.forEach(chunk=>{this.batchOverSize||chunk.forEach(queuedPost=>{const post=Post_1.PostData.fromAPI(queuedPost);if(post.has.file){if(totalFileSize+=post.file.size,Debug_1.Debug.log(`adding #${post.id} (${Util_1.Util.formatBytes(post.file.size)}) to the queue: ${Util_1.Util.formatBytes(totalFileSize)} total`),totalFileSize>PoolDownloader.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.original,file:post.file.original.match(/.{32}\..*$/g)[0],unid:post.id,date:new Date(post.date.raw),tags:post.tagString},{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)}})}),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:URL.createObjectURL(zipData),download:filename}).html("Download Archive").appendTo(this.infoText);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))})}createFilename(post){return MassDownloader_1.MassDownloader.createFilenameBase(this.fetchSettings("template"),post).replace(/%pool%/g,this.poolName).replace(/%index%/g,""+(this.poolFiles.indexOf(post.id)+1)).slice(0,128).replace(/-{2,}/g,"-").replace(/-*$/g,"")+"."+post.file.ext}createPoolFilename(name){return name.slice(0,64).replace(/\s/g,"_").replace(/_{2,}/g,"_").replace(/-{2,}/g,"-").replace(/-*$/g,"")}}exports.PoolDownloader=PoolDownloader,PoolDownloader.maxBlobSize=838860800},{"../../components/RE6Module":2,"../../components/api/DownloadQueue":4,"../../components/api/E621":5,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/utility/Debug":30,"../../components/utility/Util":33,"./MassDownloader":40}],42:[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"),Page_1=require("../../components/data/Page"),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:" ",bold:"",italic:"",strikethrough:"",underscore:"",superscript:"",subscript:"",spoiler:"",color:"",code:"",heading:"",quote:"",section:"",tag:"",wiki:"",keyboard:"",link:"",unlink:"",link_prompt:"",lemon:"",pepper:"",drumstick:"",magic:"",clipboard:"",paperclip:"",fountainpen:"",comment:"",bell:"",bullhorn:"",heart:"","plus-square":"","minus-square":"",baby:"",scales:"","chart-pie":"",dice:"",hotdog:"",leaf:"","paper-plane":"",anchor:"",crown:"",crow:""};class FormattingManager extends RE6Module_1.RE6Module{constructor(){super([],!0),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(){if(super.create(),Page_1.Page.matches(Page_1.PageDefinition.upload)||Page_1.Page.matches(Page_1.PageDefinition.post)){const $textarea=$("#post_description");$("<div>").addClass("dtext-previewable").append($('<div class="dtext-preview">')).insertBefore($textarea).append($textarea)}if(Page_1.Page.matches(Page_1.PageDefinition.settings)){const $textareas=$("#user_profile_about, #user_profile_artinfo");for(const input of $textareas){const $input=$(input);$("<div>").addClass("dtext-previewable").append($('<div class="dtext-preview">')).insertBefore($input).append($input)}}$("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").on("click",event=>{event.preventDefault(),this.toggleEditing()}),this.$formatButtons=$("<div>").addClass("comment-buttons").appendTo($bar);const $drawerButtonBox=$("<li>").appendTo($("<div>").addClass("settings-buttons").appendTo($bar));$("<a>").html("").attr("title","Settings").appendTo($drawerButtonBox).on("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.on("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.on("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"),this.$textarea.trigger("focus"))}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.trigger("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.trigger("focus")})}}},{"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/api/E621":5,"../../components/data/Page":16,"../../components/structure/Form":26,"../../components/structure/Modal":27,"../../components/structure/Prompt":28}],43:[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:home"},{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":16,"../../components/data/User":18,"../../components/structure/DomUtilities":25,"../../components/structure/Form":26,"../../components/structure/Modal":27}],44:[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"),ModuleController_1=require("../../components/ModuleController"),RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),BetterSearch_1=require("../search/BetterSearch");class Miscellaneous extends RE6Module_1.RE6Module{constructor(){super(),this.registerHotkeys({keys:"hotkeyNewComment",fnct:this.openNewComment},{keys:"hotkeyEditPost",fnct:this.openEditTab},{keys:"hotkeyToggleBlacklist",fnct:this.toggleBlacklist},{keys:"hotkeySubmit",fnct:this.handleSubmitForm,element:"body",selector:"textarea, input"},{keys:"hotkeyRandomSetPost",fnct:this.randomSetPost})}getDefaultSettings(){return{enabled:!0,hotkeyNewComment:"n",hotkeyEditPost:"e",hotkeyToggleBlacklist:"",hotkeySubmit:"alt+return",hotkeyRandomSetPost:"",stickySearchbox:!0,stickyHeader:!1,stickyEditBox:!0,hideBlacklist:!1,avatarClick:!0,commitWikiLinks:!1,fixForumTitle:!0}}create(){if(super.create(),Page_1.Page.matches([Page_1.PageDefinition.post,Page_1.PageDefinition.forum])&&this.handleQuoteButton(),Page_1.Page.matches([Page_1.PageDefinition.search,Page_1.PageDefinition.post,Page_1.PageDefinition.favorites])&&this.createStickySearchbox(this.fetchSettings("stickySearchbox")),this.createStickyHeader(this.fetchSettings("stickyHeader")),Page_1.Page.matches([Page_1.PageDefinition.search,Page_1.PageDefinition.favorites])&&this.createStickyEditBox(this.fetchSettings("stickyEditBox")),this.hideBlacklist(this.fetchSettings("hideBlacklist")),this.handleAvatarClick(this.fetchSettings("avatarClick")),this.fetchSettings("fixForumTitle")&&Page_1.Page.matches(Page_1.PageDefinition.forum)){const title=/^(?:Forum - )(.+)(?: - (e621|e926))$/g.exec(document.title);title&&(document.title=`${title[1]} - Forum - ${title[2]}`)}if(Page_1.Page.matches(Page_1.PageDefinition.settings)&&this.modifyBlacklistForm(),Page_1.Page.matches(Page_1.PageDefinition.set)&&this.tweakSetPage(),Page_1.Page.matches(Page_1.PageDefinition.changes)&&this.fetchSettings("commitWikiLinks"))for(const link of $(".diff-list a").get()){const $link=$(link);$link.attr("href","/wiki_pages/show_or_new?title="+$link.text())}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.PageDefinition.post)?($("menu#post-sections > li > a[href$=comments]")[0].click(),$("a.expand-comment-response")[0].click()):Page_1.Page.matches(Page_1.PageDefinition.forum)&&$("a#new-response-link")[0].click()}openEditTab(){Page_1.Page.matches(Page_1.PageDefinition.post)&&window.setTimeout(()=>{$("#post-edit-link")[0].click()},100)}createStickySearchbox(state=!0){$("body").attr("data-sticky",state+"")}createStickyHeader(state=!0){$("body").attr("data-sticky-header",state+"")}createStickyEditBox(state=!0){$("body").attr("data-sticky-editbox",state+"")}hideBlacklist(state=!0){$("body").attr("data-hide-blacklist",state+"")}handleQuoteButton(){Page_1.Page.matches(Page_1.PageDefinition.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.PageDefinition.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.trigger("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=ModuleController_1.ModuleController.get(BetterSearch_1.BetterSearch).fetchSettings("clickAction"),avatars=$("div.avatar > div > a").get();for(const element of avatars){const $link=$(element);let dblclickTimer,prevent=!1;$link.on("click.re621.thumbnail",event=>{0!==event.button||event.shiftKey||event.ctrlKey||event.altKey||event.metaKey||(event.preventDefault(),dblclickTimer=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(dblclickTimer),prevent=!0,clickAction===BetterSearch_1.ImageClickAction.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").trigger("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.on("keyup",()=>{charCounter.html(($textarea.val()+"").length+" / 50000")})}toggleBlacklist(){$("a#disable-all-blacklists:visible, a#re-enable-all-blacklists:visible").first()[0].click()}tweakSetPage(){const wrapper=$("span.set-viewposts").first();wrapper.find("a").addClass("button btn-success"),$("<a>").addClass("button btn-neutral").html("Random Post").attr({id:"set-random-post"}).on("click",async()=>{const shortname=$("div.set-shortname a").first().text(),result=await E621_1.E621.Posts.get({tags:["set:"+shortname,"order:random"],limit:1});0!=result.length&&(location.href="/posts/"+result[0].id+"?q=set:"+shortname)}).appendTo(wrapper)}randomSetPost(){Page_1.Page.matches(Page_1.PageDefinition.set)&&$("#set-random-post")[0].click()}}exports.Miscellaneous=Miscellaneous},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/api/XM":6,"../../components/data/Page":16,"../../components/structure/DomUtilities":25,"../search/BetterSearch":56}],45:[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"),TagCache_1=require("../../components/cache/TagCache"),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"),Util_1=require("../../components/utility/Util"),VersionChecker_1=require("../../components/utility/VersionChecker"),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"),BetterSearch_1=require("../search/BetterSearch"),BlacklistEnhancer_1=require("../search/BlacklistEnhancer"),CustomFlagger_1=require("../search/CustomFlagger"),HoverZoom_1=require("../search/HoverZoom"),SearchUtilities_1=require("../search/SearchUtilities"),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,checkUpdates:!0,hotkeyOpenSettings:""}}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:"Blacklist",structure:this.createBlacklistTab()},{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:this.aboutTabButton=$("<a>").attr({"data-loading":"false","data-updates":"0",id:"conf-tab-about"}).addClass("update-notification").html("About"),structure:this.createAboutTab()}]});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"}})}pushNotificationsCount(tab,count=0){this.openSettingsButton.attr("data-updates",(parseInt(this.openSettingsButton.attr("data-updates"))||0)+count);("util"==tab?this.utilTabButton:this.aboutTabButton).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),imageScaler=ModuleController_1.ModuleController.get(ImageScaler_1.ImageScaler),headerCustomizer=ModuleController_1.ModuleController.get(HeaderCustomizer_1.HeaderCustomizer),searchUtilities=ModuleController_1.ModuleController.get(SearchUtilities_1.SearchUtilities),betterSearch=ModuleController_1.ModuleController.get(BetterSearch_1.BetterSearch),hoverZoom=ModuleController_1.ModuleController.get(HoverZoom_1.HoverZoom);return new Form_1.Form({name:"conf-general",columns:3,width:3},[Form_1.Form.accordion({name:"collapse",columns:3,width:3,active:0},[Form_1.Form.accordionTab({name:"general",label:"General",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">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:"%general%",label:"General"}),Form_1.Form.copy({value:"%meta%",label:"Meta"}),Form_1.Form.copy({value:"%all%",label:"All Tags"})]),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.accordionTab({name:"layout",label:"Page Layout",columns:3,width: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:postViewer.fetchSettings("moveChildThumbs"),label:"<b>Move Related Thumbnails</b><br />Moves the parent / child thumbnails to the sidebar",width:2},async data=>{await postViewer.pushSettings("moveChildThumbs",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:postViewer.fetchSettings("boldenTags"),label:"<b>Boldened Tags</b><br />Restore the classic boldened look on the sidebar tags",width:3},async data=>{await postViewer.pushSettings("boldenTags",data),postViewer.toggleBoldenedTags(data)}),Form_1.Form.hr(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),$("#sidebar").trigger("re621:reflow")}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:miscellaneous.fetchSettings("stickySearchbox"),label:"<b>Fixed Sidebar</b><br />Leave the sidebar controls on the screen while scrolling",width:3},async data=>{await miscellaneous.pushSettings("stickySearchbox",data),miscellaneous.createStickySearchbox(data),$("#sidebar").trigger("re621:reflow")}),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:betterSearch.fetchSettings("imageLoadMethod")},{disabled:"Disabled",hover:"On Hover",always:"Always"},async data=>{await betterSearch.pushSettings("imageLoadMethod",data),betterSearch.isInitialized()&&(betterSearch.reloadEventListeners(),betterSearch.reloadRenderedPosts())}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("autoPlayGIFs"),label:"<b>Auto-Play GIFs</b><br />If disabled, animated GIFs will only play on hover",width:3},async data=>{await betterSearch.pushSettings("autoPlayGIFs",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.subheader("Double-Click Action","Action taken when a thumbnail is double-clicked",2),Form_1.Form.select({value:betterSearch.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 betterSearch.pushSettings("clickAction",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("hoverTags"),label:"<b>Preserve Hover Text</b><br />Restores text displayed when hovering over the thumbnail",width:3},async data=>{await betterSearch.pushSettings("hoverTags",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.collapse({name:"scaling",columns:3,width:3,title:"Scaling Options",collapsed:!0},[Form_1.Form.checkbox({value:betterSearch.fetchSettings("imageSizeChange"),label:"<b>Thumbnail Rescaling</b><br />Resize thumbnail images according to settings below",width:3},async data=>{await betterSearch.pushSettings("imageSizeChange",data),betterSearch.isInitialized()&&betterSearch.updateContentHeader(),$("#conf-general-collapse-thumb-scaling-thumbsize-desc").toggleClass("input-disabled",!data),$("#conf-general-collapse-thumb-scaling-thumbsize").prop("disabled",!data).parent().toggleClass("input-disabled",!data)}),Form_1.Form.spacer(3,!0),Form_1.Form.subheader("Thumbnail Size","Thumbnail card width, in pixels",2,"thumbsize-desc",betterSearch.fetchSettings("imageSizeChange")?void 0:"input-disabled"),Form_1.Form.input({name:"thumbsize",value:betterSearch.fetchSettings("imageWidth"),title:"Number between 150 and 999",required:!0,pattern:"^(1[5-9][0-9]|[2-9][0-9][0-9])$",wrapper:betterSearch.fetchSettings("imageSizeChange")?void 0:"input-disabled",disabled:!betterSearch.fetchSettings("imageSizeChange")},async(data,input)=>{""!=input.val()&&input.get()[0].checkValidity()&&(await betterSearch.pushSettings("imageWidth",parseInt(data)),betterSearch.isInitialized()&&betterSearch.updateContentHeader())}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({name:"cropimages",value:betterSearch.fetchSettings("imageRatioChange"),label:"<b>Crop Images</b><br />Restrict image size to the specified ratio",width:3},async data=>{await betterSearch.pushSettings("imageRatioChange",data),betterSearch.isInitialized()&&(betterSearch.updateContentHeader(),betterSearch.reloadRenderedPosts()),$("#conf-general-collapse-thumb-scaling-cropratio-desc").toggleClass("input-disabled",!data),$("#conf-general-collapse-thumb-scaling-cropratio").prop("disabled",!data).parent().toggleClass("input-disabled",!data)}),Form_1.Form.spacer(3,!0),Form_1.Form.subheader("Image Ratio","Height to width ratio of the image",2,"cropratio-desc",betterSearch.fetchSettings("imageRatioChange")?void 0:"input-disabled"),Form_1.Form.input({name:"cropratio",value:betterSearch.fetchSettings("imageRatio"),title:"Number between 0.1 and 1.9",required:!0,pattern:"^([01]\\.[1-9]|1\\.0)$",wrapper:betterSearch.fetchSettings("imageRatioChange")?void 0:"input-disabled",disabled:!betterSearch.fetchSettings("imageRatioChange")},async(data,input)=>{""!=input.val()&&input.get()[0].checkValidity()&&(await betterSearch.pushSettings("imageRatio",parseFloat(data)),betterSearch.isInitialized()&&(betterSearch.updateContentHeader(),betterSearch.reloadRenderedPosts()))}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({name:"compactMode",value:betterSearch.fetchSettings("compactMode"),label:"<b>Compact Mode</b><br />Limit the image height to the same value as the width",width:3},async data=>{await betterSearch.pushSettings("compactMode",data),betterSearch.isInitialized()&&(betterSearch.updateContentHeader(),betterSearch.reloadRenderedPosts())}),Form_1.Form.spacer(3,!0),Form_1.Form.subheader("Minimum Image Width","Images narrower than this percent value will be cropped to fit",2),Form_1.Form.input({value:betterSearch.fetchSettings("imageMinWidth"),required:!0,pattern:"^([1-9][0-9]|100)$",title:"Number between 10 and 100"},async(data,input)=>{""!=input.val()&&input.get()[0].checkValidity()&&(await betterSearch.pushSettings("imageMinWidth",parseInt(data)),betterSearch.isInitialized()&&betterSearch.updateContentHeader())}),Form_1.Form.spacer(3,!0)]),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({name:"votebutton",value:betterSearch.fetchSettings("buttonsVote"),label:"<b>Voting Buttons</b><br />Adds voting buttons when hovering over a thumbnail",width:3},async data=>{await betterSearch.pushSettings("buttonsVote",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({name:"favbutton",value:betterSearch.fetchSettings("buttonsFav"),label:"<b>Favorite Button</b><br />Adds a +favorite button when hovering over a thumbnail",width:3},async data=>{await betterSearch.pushSettings("buttonsFav",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("ribbonsRel"),label:"<b>Relations Ribbons</b><br />Display ribbons for parent/child relationships",width:3},async data=>{await betterSearch.pushSettings("ribbonsRel",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("ribbonsFlag"),label:"<b>Status Ribbons</b><br />Display post status as a colored ribbon on the post",width:3},async data=>{await betterSearch.pushSettings("ribbonsFlag",data),betterSearch.isInitialized()&&betterSearch.reloadRenderedPosts()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("ribbonsAlt"),label:"<b>Alternative Ribbons</b><br />Place the ribbons on the bottom of the thumbnail",width:3},async data=>{await betterSearch.pushSettings("ribbonsAlt",data),betterSearch.isInitialized()&&betterSearch.updateContentHeader()})]),Form_1.Form.accordionTab({name:"infscroll",label:"Scrolling and Zoom",columns:3,width:3},[Form_1.Form.header("Infinite Scroll",3),Form_1.Form.checkbox({value:betterSearch.fetchSettings("infiniteScroll"),label:"<b>Enable Infinite Scroll</b><br />Append the next page of posts below the current one",width:3},async data=>{await betterSearch.pushSettings("infiniteScroll",data),betterSearch.isInitialized()&&(betterSearch.reloadEventListeners(),betterSearch.reloadPaginator())}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("loadAutomatically"),label:"<b>Auto-Load Posts</b><br />Load posts automatically as you scroll, not by clicking a button",width:3},async data=>{await betterSearch.pushSettings("loadAutomatically",data),betterSearch.isInitialized()&&betterSearch.reloadEventListeners()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("loadPrevPages"),label:"<b>Preserve Scroll History</b><br />When opening a specific result page, load several previous pages as well",width:3},async data=>{await betterSearch.pushSettings("loadPrevPages",data)}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:betterSearch.fetchSettings("hidePageBreaks"),label:"<b>Hide Page Separators</b><br />Display posts as one continuous section, instead of being separated by page",width:3},async data=>{await betterSearch.pushSettings("hidePageBreaks",data),betterSearch.isInitialized()&&betterSearch.updateContentHeader()}),Form_1.Form.hr(3),Form_1.Form.header("Hover Zoom",3),Form_1.Form.div({value:"<b>Zoom Mode</b><br />Increases the size of the thumbnail when hovering over it",width:2}),Form_1.Form.select({name:"hoverzoom",value:hoverZoom.fetchSettings("mode")},{disabled:"Disabled",hover:"On Hover",onshift:"Holding Shift"},async data=>{await hoverZoom.pushSettings("mode",data),hoverZoom.isInitialized()&&hoverZoom.reloadEventListeners()}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:hoverZoom.fetchSettings("tags"),label:"<b>Show Tags</b><br />Display the list of post's tags under the zoom-in image",width:3},async data=>{await hoverZoom.pushSettings("tags",data)}),Form_1.Form.spacer(3,!0),Form_1.Form.checkbox({value:hoverZoom.fetchSettings("time"),label:"<b>Relative Time</b><br />Display the post's upload time in a relative format",width:3},async data=>{await hoverZoom.pushSettings("time",data)}),Form_1.Form.spacer(3,!0)]),Form_1.Form.accordionTab({name:"misc",label:"Other",columns:3,width: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),imageScaler.toggleClickScale(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: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),Form_1.Form.checkbox({value:miscellaneous.fetchSettings("commitWikiLinks"),label:"<b>Wiki Links in Post History</b><br />Redirect the tag links in the post history to the wiki pages",width:2},async data=>{await miscellaneous.pushSettings("commitWikiLinks",data)}),Form_1.Form.requiresReload()])])])}createBlacklistTab(){const searchUtilities=ModuleController_1.ModuleController.get(SearchUtilities_1.SearchUtilities),miscellaneous=ModuleController_1.ModuleController.get(Miscellaneous_1.Miscellaneous),blacklistEnhancer=ModuleController_1.ModuleController.get(BlacklistEnhancer_1.BlacklistEnhancer),imageScaler=ModuleController_1.ModuleController.get(ImageScaler_1.ImageScaler);return new Form_1.Form({name:"conf-blacklist",columns:3,width:3},[Form_1.Form.header("Blacklist Settings"),Form_1.Form.checkbox({value:miscellaneous.fetchSettings("hideBlacklist"),label:'<b>Hide Blacklist</b><br />Completely remove the "Blacklisted" section in the sidebar',width:3},async data=>{await miscellaneous.pushSettings("hideBlacklist",data),miscellaneous.hideBlacklist(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:searchUtilities.fetchSettings("quickBlacklist"),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 searchUtilities.pushSettings("quickBlacklist",data),searchUtilities.initQuickBlacklist(data)}),Form_1.Form.spacer(3),Form_1.Form.checkbox({value:imageScaler.fetchSettings("clickShowFiltered"),label:"<b>Click to Show Blacklisted</b><br />Click on the blacklisted image on the post page to show it",width:2},async data=>{await imageScaler.pushSettings("clickShowFiltered",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.checkbox({value:blacklistEnhancer.fetchSettings("favorites"),label:"<b>Exclude Favorites</b><br />Prevent your favorites from being filtered out by the blacklist",width:2},async data=>{await blacklistEnhancer.pushSettings("favorites",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:blacklistEnhancer.fetchSettings("uploads"),label:"<b>Exclude Uploads</b><br />Prevent your uploads from being filtered out by the blacklist",width:2},async data=>{await blacklistEnhancer.pushSettings("uploads",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.text("<b>Whitelist</b>"),Form_1.Form.input({value:blacklistEnhancer.fetchSettings("whitelist"),width:2},async data=>{await blacklistEnhancer.pushSettings("whitelist",data)}),Form_1.Form.text("Posts with these tags will never be filtered out",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.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.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:"conf-download",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:"collapse",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.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.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:"conf-flags",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:<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).on("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).on("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:"conf-alias",columns:3,width:3},[Form_1.Form.accordion({name:"collapse",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,wrapper:"display-none"},data=>{smartAlias.pushSettings("fixCommonTypos",data)}),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.subheader("Cache Post Minimum","Tags with this amount of posts will be cached to speed up lookups",2),Form_1.Form.input({value:smartAlias.fetchSettings("minCachedTags"),width:1,pattern:"\\d{2,}"},(data,input)=>{input.get()[0].checkValidity()&&smartAlias.pushSettings("minCachedTags",data)}),Form_1.Form.hr(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,await module.pushSettings(settingsKey,bindings.join("|")),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,await module.pushSettings(settingsKey,bindings.join("|")),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:"conf-hotkeys",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 Post","hotkeyUpvoteNU"),...createInputs(postViewer,"Toggle Upvote","hotkeyUpvote"),...createInputs(postViewer,"Downvote Post","hotkeyDownvoteNU"),...createInputs(postViewer,"Toggle 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"),...createInputs(postViewer,"Post History","hotkeyOpenHistory"),...createInputs(miscellaneous,"Toggle Blacklist","hotkeyToggleBlacklist"),Form_1.Form.hr(3),Form_1.Form.header("Search Modes",3),...createInputs(searchUtilities,"View","hotkeySwitchModeView"),...createInputs(searchUtilities,"Edit","hotkeySwitchModeEdit"),...createInputs(searchUtilities,"Fullscreen","hotkeySwitchModeOpen"),...createInputs(searchUtilities,"Add Favorite","hotkeySwitchModeAddFav"),...createInputs(searchUtilities,"Remove Favorite","hotkeySwitchModeRemFav"),...createInputs(searchUtilities,"Blacklist","hotkeySwitchModeBlacklist"),...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,"Random Set Post","hotkeyRandomSetPost"),...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("BetterSearch","Improved Thumbnails","Massively overhauled thumbnail system. Many features will not work with this module disabled."),...createInput("HeaderCustomizer","Header Customizer","Add, delete, and customize header links to your heart's content."),...createInput("InstantFilters","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.")])}createMiscTab(){const modules=ModuleController_1.ModuleController.getAll(),moduleSelector={none:"------"};modules.forEach(module=>{moduleSelector[module.getSettingsTag()]=module.getSettingsTag()});let selectedModule="none",dnpcacheUpdated=!0;return new Form_1.Form({name:"conf-misc",columns:3,width:3},[Form_1.Form.header("Miscellaneous",3),Form_1.Form.accordion({name:"collapse",columns:3,width:3,active:0},[Form_1.Form.accordionTab({name:"cache",label:"Cache",columns:3,width:3},[Form_1.Form.section({name:"tagcache",columns:3,width:3},[Form_1.Form.div({value:"<b>Tag Cache</b><br />Used to speed up SmartAlias tag checking",width:2}),Form_1.Form.button({name:"reset",value:"Clear"},async(data,input)=>{TagCache_1.TagCache.clear(),input.html("Done!"),window.setTimeout(()=>{input.html("Clear")},1e3)})]),Form_1.Form.spacer(3),Form_1.Form.section({name:"dnpcache",columns:3,width:3},[Form_1.Form.div({value:"<b>Avoid Posting Cache</b><br />Used to validate the artist tags against the DNP list",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("util",-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("util",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 VersionChecker_1.VersionChecker.hasUpdate&&this.fetchSettings("checkUpdates")&&this.pushNotificationsCount("about",1),new Form_1.Form({name:"conf-about",columns:3,width:3},[Form_1.Form.div({value:`<h3 class="display-inline"><a href="${window.re621.links.website}" target="_blank">${window.re621.name} v.${VersionChecker_1.VersionChecker.scriptBuild}</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="${VersionChecker_1.VersionChecker.hasUpdate}">\n <a href="${window.re621.links.releases}" target="_blank">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.checkbox({label:"<b>Show Update Notification</b><br />Display a red dot over the settings icon if an update is available",value:this.fetchSettings("checkUpdates"),width:3},async data=>{console.log(data),await this.pushSettings("checkUpdates",data)}),Form_1.Form.spacer(3),Form_1.Form.header(`<a href="${window.re621.links.releases}" target="_blank" class="unmargin">What's new?</a>`,3),Form_1.Form.div({value:`<div id="changelog-list"><h5>Version ${VersionChecker_1.VersionChecker.latestBuild}</h5>${VersionChecker_1.VersionChecker.changesHTML}</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":6,"../../components/cache/AvoidPosting":12,"../../components/cache/TagCache":13,"../../components/data/User":18,"../../components/structure/DomUtilities":25,"../../components/structure/Form":26,"../../components/structure/Modal":27,"../../components/structure/Tabbed":29,"../../components/utility/Debug":30,"../../components/utility/Patcher":32,"../../components/utility/Util":33,"../../components/utility/VersionChecker":37,"../downloader/FavDownloader":39,"../downloader/MassDownloader":40,"../downloader/PoolDownloader":41,"../misc/SmartAlias":48,"../misc/UploadUtilities":49,"../post/DownloadCustomizer":51,"../post/ImageScaler":52,"../post/PoolNavigator":53,"../post/PostViewer":54,"../post/TitleCustomizer":55,"../search/BetterSearch":56,"../search/BlacklistEnhancer":57,"../search/CustomFlagger":58,"../search/HoverZoom":59,"../search/SearchUtilities":62,"../subscriptions/ForumTracker":65,"../subscriptions/PoolTracker":66,"../subscriptions/SubscriptionManager":67,"./HeaderCustomizer":43,"./Miscellaneous":44}],46:[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),ThemeCustomizer.trigger("switch.theme",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),ThemeCustomizer.trigger("switch.extras",data)}),Form_1.Form.select({label:"Post Navbar",value:window.localStorage.getItem("theme-nav")||"top"},{top:"Top",bottom:"Bottom",both:"Both",none:"None"},data=>{window.localStorage.setItem("theme-nav",data),$("body").attr("data-th-nav",data),ThemeCustomizer.trigger("switch.navbar",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":25,"../../components/structure/Form":26,"../../components/structure/Modal":27}],47:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.EditTracker=void 0;const Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util");class EditTracker extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefinition.post)}create(){$("#post_tag_string").is(":visible")?this.listen():$("body").one("click.re621","#post-edit-link",()=>{this.listen()})}async listen(){const input=$("#post_tag_string"),original=Util_1.Util.getTags(input),changes=$("<div>").addClass("diff-list post-changes").insertAfter("#tags-container");$("#post_tag_string").on("input",()=>{const changed=Util_1.Util.getTags(input),output=[];for(const tag of changed.filter(el=>!original.includes(el)))output.push(`<ins>+<a href="/wiki_pages/show_or_new?title=${tag}" target="_blank">${tag}</a></ins>`);for(const tag of original.filter(el=>!changed.includes(el)))output.push(`<del>-<a href="/wiki_pages/show_or_new?title=${tag}" target="_blank">${tag}</a></del>`);0!=output.length?changes.html("<label>Tag Changes</label>\n"+output.join(" ")):changes.html("")})}}exports.EditTracker=EditTracker},{"../../components/RE6Module":2,"../../components/data/Page":16,"../../components/utility/Util":33}],48:[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"),TagCache_1=require("../../components/cache/TagCache"),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.PageDefinition.upload,Page_1.PageDefinition.post,Page_1.PageDefinition.search,Page_1.PageDefinition.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,minCachedTags:1e3,data:""}}async prepare(){await super.prepare(),Page_1.Page.matches(Page_1.PageDefinition.post)&&($("#post_tag_string").is(":visible")||(SmartAlias.postPageLockout=!0,$("body").one("click.re621","#post-edit-link",()=>{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 $("#post_tags, #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.PageDefinition.search,Page_1.PageDefinition.favorites]))return;if(!this.fetchSettings("editTagsForm")&&Page_1.Page.matches(Page_1.PageDefinition.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.PageDefinition.search,Page_1.PageDefinition.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")}),$textarea.on("re621:input",()=>{this.handleTagInput($textarea,$container)}),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();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,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)}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)),TagCache_1.TagCache.load();for(const tag of lookup){const data=TagCache_1.TagCache.get(tag);null!=data&&(SmartAlias.tagData[tag]={count:data.count,category:data.category,ambiguous:!1,invalid:!1,dnp:AvoidPosting_1.AvoidPosting.has(tag),cached:!0},lookup.delete(tag))}if(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(","),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),cached:!1},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),cached:!1}}const minCachedTags=this.fetchSettings("minCachedTags");if(minCachedTags>0){for(const[name,data]of Object.entries(SmartAlias.tagData))TagCache_1.TagCache.has(name)||data.count<minCachedTags||TagCache_1.TagCache.add(name,data.count,data.category);TagCache_1.TagCache.save()}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,title;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.cached?"~"+Util_1.Util.formatK(data.count):data.count+"",title=data.cached?"cached value":void 0),displayName=displayName.replace(/_/g,"_​"),$("<smart-tag>").addClass(isLoading?"":"category-"+data.category).attr({name:tagName,symbol:symbol,color:color,title:title}).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","#re621_qedit_tags","#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":12,"../../components/cache/TagCache":13,"../../components/data/Page":16,"../../components/utility/Util":33}],49:[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.PageDefinition.upload],!0)}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();var link;($parent.find("button.source-copy").remove(),$parent.find("button.source-link").remove(),$parent.find("span.source-eval").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")}),$("<span>").addClass("source-eval").html((link=$input.val()+"",/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/.test(link)?link.startsWith("https")?"":"http":"invalid")).appendTo($parent))}),$("input.upload-source-input").trigger("input")}}exports.UploadUtilities=UploadUtilities},{"../../components/RE6Module":2,"../../components/api/E621":5,"../../components/api/XM":6,"../../components/data/Page":16,"../../components/utility/Util":33}],50:[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.PageDefinition.wiki,Page_1.PageDefinition.wikiNA,Page_1.PageDefinition.artist])}getDefaultSettings(){return{enabled:!0}}create(){super.create();const $title=Page_1.Page.matches(Page_1.PageDefinition.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":6,"../../components/data/Page":16}],51:[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/post/Post"),PostParts_1=require("../../components/post/PostParts"),RE6Module_1=require("../../components/RE6Module");class DownloadCustomizer extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefinition.post,!0)}getDefaultSettings(){return{enabled:!0,template:"%postid%-%artist%-%copyright%-%character%"}}create(){super.create(),this.post=Post_1.Post.getViewingPost();const downloadContainer=$("<div>").attr("id","image-custom-download-links").appendTo("#image-extra-controls"),link=$("<a>").attr({id:"image-custom-download-file",href:this.post.file.original,download:this.parseTemplate()}).html("Download").addClass("button btn-neutral").appendTo(downloadContainer).on("click",event=>{event.preventDefault(),event.stopImmediatePropagation(),link.attr("loading","true"),XM_1.XM.Connect.download({url:link.attr("href"),name:link.attr("download"),onload:()=>{link.removeAttr("loading")}})}),tags=$("<a>").attr({id:"image-custom-download-tags",href:this.getTagsBlock(),download:this.parseTemplate("txt")}).html("Tags").addClass("button btn-neutral").appendTo(downloadContainer).on("click",()=>{tags.attr("loading","true"),tags.attr({loading:"false",href:this.getTagsBlock()})})}refreshDownloadLink(){$("#image-custom-download-file").attr("download",this.parseTemplate())}getTagsBlock(){return URL.createObjectURL(new Blob([PostParts_1.PostParts.formatHoverText(this.post)],{type:"text/plain"}))}parseTemplate(ext){return this.fetchSettings("template").replace(/%postid%/g,this.post.id).replace(/%artist%/g,tagSetToString(this.post.tags.real_artist)).replace(/%copyright%/g,tagSetToString(this.post.tags.copyright)).replace(/%species%/g,tagSetToString(this.post.tags.species)).replace(/%character%/g,tagSetToString(this.post.tags.character)).replace(/%meta%/g,tagSetToString(this.post.tags.meta)).replace(/%md5%/g,this.post.file.md5).slice(0,128).replace(/-{2,}/g,"-").replace(/-*$/g,"")+"."+(ext||this.post.file.ext);function tagSetToString(tags){return[...tags].join("-")}}}exports.DownloadCustomizer=DownloadCustomizer},{"../../components/RE6Module":2,"../../components/api/XM":6,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/post/PostParts":22}],52:[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"),User_1=require("../../components/data/User"),ModuleController_1=require("../../components/ModuleController"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module");class ImageScaler extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefinition.post,!0),this.registerHotkeys({keys:"hotkeyScale",fnct:()=>{this.setScale()}},{keys:"hotkeyFullscreen",fnct:this.openFullscreen})}getDefaultSettings(){return{enabled:!0,hotkeyScale:"v|0",hotkeyFullscreen:"",clickScale:!0,clickShowFiltered:!1,size:ImageSize.Fill}}create(){super.create(),$("#note-preview").insertBefore("#page"),this.post=Post_1.Post.getViewingPost(),this.image=$("img#image");const resizeButtonContainer=$("#image-resize-cycle").empty();"/images/blacklisted-preview.png"!==this.image.attr("src")&&this.setImageSize(this.fetchSettings("size")),this.resizeSelector=$("<select>").html(`\n <option value="${ImageSize.Sample}">Sample</option>\n <option value="${ImageSize.Fill}">Fill Screen</option>\n <option value="${ImageSize.Fit}">Fit Horizontally</option>\n <option value="${ImageSize.Original}">Original</option>\n `).val(this.fetchSettings("size")).addClass("button btn-neutral").appendTo(resizeButtonContainer).on("change",async(event,save)=>{const size=$(event.target).val()+"";if(this.setImageSize(size),!1!==save)switch(await this.pushSettings("size",size),size){case ImageSize.Sample:await User_1.User.setSettings({default_image_size:"large"});break;case ImageSize.Fill:case ImageSize.Fit:await User_1.User.setSettings({default_image_size:"fit"});break;case ImageSize.Original:await User_1.User.setSettings({default_image_size:"original"})}}),$("#image-download-link a").html("Fullscreen"),this.image.on("click",async()=>{this.fetchSettings("clickScale")&&!await Danbooru_1.Danbooru.Note.TranslationMode.active()&&("/images/blacklisted-preview.png"!=this.image.attr("src")?this.setScale("",!1):this.fetchSettings("clickShowFiltered")&&this.setScale("current",!1))}),this.toggleClickScale(this.fetchSettings("clickScale"))}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()+""}else"current"==size&&(size=selector.find("option:selected").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 ImageSize.Sample:this.image.attr("src",this.post.file.sample);break;case ImageSize.Fill:this.image.addClass("re621-fit-vertical"),this.image.attr("src")!==this.post.file.original?this.image.attr("src",this.post.file.original):this.image.parent().removeClass("loading");break;case ImageSize.Fit:this.image.addClass("re621-fit-horizontal"),this.image.attr("src")!==this.post.file.original?this.image.attr("src",this.post.file.original):this.image.parent().removeClass("loading");break;case ImageSize.Original:this.image.attr("src")!==this.post.file.original?this.image.attr("src",this.post.file.original):this.image.parent().removeClass("loading")}Danbooru_1.Danbooru.Note.Box.scale_all()}openFullscreen(){$("#image-download-link a")[0].click()}toggleClickScale(state=!0){$("#image-container").toggleClass("click-scale",state)}}var ImageSize;exports.ImageScaler=ImageScaler,function(ImageSize){ImageSize.Sample="sample",ImageSize.Fill="fit-vertical",ImageSize.Fit="fit-horizontal",ImageSize.Original="original"}(ImageSize||(ImageSize={}))},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/data/Page":16,"../../components/data/User":18,"../../components/post/Post":19}],53:[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"),ThemeCustomizer_1=require("../general/ThemeCustomizer");class PoolNavigator extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefinition.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.createStructure(),ThemeCustomizer_1.ThemeCustomizer.on("switch.navbar",()=>{this.resetStructure(),this.createStructure()}),$("#nav-links, #nav-links-top, #nav-links-bottom").find(".first").each((index,element)=>{$(element).html("«")}),$("#nav-links, #nav-links-top, #nav-links-bottom").find(".last").each((index,element)=>{$(element).html("»")})}cycleNavbars(){const poolNavigator=ModuleController_1.ModuleController.get(PoolNavigator),navbars=poolNavigator.navbars,active=poolNavigator.activeNav;0!=navbars.length&&(active+1>=navbars.length?navbars[0].checkbox.trigger("click"):navbars[active+1].checkbox.trigger("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()}createStructure(){$(".search-seq-nav:visible").length&&this.navbars.push({type:"search",element:$(".search-seq-nav:visible > ul > li").first(),checkbox:void 0});for(const element of $(".pool-nav:visible").first().find("ul > li").get())this.navbars.push({type:"pool",element:$(element),checkbox:void 0});for(const element of $(".set-nav:visible").first().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"),$("input[type='radio'].post-nav-switch").on("change",event=>{this.activeNav=parseInt($(event.target).val()+"")})}resetStructure(){$("input[type='radio'].post-nav-switch").off("change"),$(".post-nav-switch-box, .post-nav-spacer").remove(),this.navbars=[]}}exports.PoolNavigator=PoolNavigator},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/data/Page":16,"../general/ThemeCustomizer":46}],54:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PostViewer=void 0;const Danbooru_1=require("../../components/api/Danbooru"),Page_1=require("../../components/data/Page"),ModuleController_1=require("../../components/ModuleController"),Post_1=require("../../components/post/Post"),PostActions_1=require("../../components/post/PostActions"),RE6Module_1=require("../../components/RE6Module");class PostViewer extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefinition.post,!0),this.registerHotkeys({keys:"hotkeyUpvote",fnct:this.triggerUpvote},{keys:"hotkeyUpvoteNU",fnct:this.triggerUpvoteNU},{keys:"hotkeyDownvote",fnct:this.triggerDownvote},{keys:"hotkeyDownvoteNU",fnct:this.triggerDownvoteNU},{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")}},{keys:"hotkeyOpenHistory",fnct:this.openImageHistory})}getDefaultSettings(){return{enabled:!0,hotkeyUpvote:"w",hotkeyUpvoteNU:"",hotkeyDownvote:"s",hotkeyDownvoteNU:"",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",hotkeyOpenHistory:"",upvoteOnFavorite:!0,hideNotes:!1,moveChildThumbs:!0,boldenTags:!0}}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 $noteToggleContainer=$("<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($noteToggleContainer).on("click",event=>{event.preventDefault(),this.toggleNotes()}),$("#note-container").css("display","").attr("data-hidden",this.fetchSettings("hideNotes")),this.fetchSettings("moveChildThumbs")&&$(".parent-children").addClass("children-moved").insertAfter($("#search-box")),this.toggleBoldenedTags(this.fetchSettings("boldenTags")),$("#add-fav-button, #add-to-favorites").on("click",()=>{this.fetchSettings("upvoteOnFavorite")&&Danbooru_1.Danbooru.Post.vote(this.post.id,1,!0)});for(const link of $("#post-related-images a[href^=http]").get())$(link).attr("target","_blank")}toggleBoldenedTags(state=!0){$("#tag-list").toggleClass("tags-boldened",state)}triggerUpvote(){Danbooru_1.Danbooru.Post.vote(Post_1.Post.getViewingPost().id,1)}triggerUpvoteNU(){const id=Post_1.Post.getViewingPost().id;PostActions_1.PostActions.vote(id,1,!0).then(response=>{response.success?($("span.post-vote-up-"+id).removeClass("score-neutral").addClass("score-positive"),$("span.post-vote-down-"+id).removeClass("score-negative").addClass("score-neutral"),$("span.post-score-"+id).removeClass("score-positive score-negative score-neutral").addClass(PostViewer.getScoreClass(response.score)).attr("title",response.up+" up / "+response.down+" down").html(response.score+""),response.score>0&&Danbooru_1.Danbooru.notice("Post Score Updated")):Danbooru_1.Danbooru.error("An error occurred while processing votes")})}triggerDownvote(){Danbooru_1.Danbooru.Post.vote(Post_1.Post.getViewingPost().id,-1)}triggerDownvoteNU(){const id=Post_1.Post.getViewingPost().id;PostActions_1.PostActions.vote(id,-1,!0).then(response=>{response.success?($("span.post-vote-down-"+id).addClass("score-negative").removeClass("score-neutral"),$("span.post-vote-up-"+id).removeClass("score-positive").addClass("score-neutral"),$("span.post-score-"+id).removeClass("score-positive score-negative score-neutral").addClass(PostViewer.getScoreClass(response.score)).attr("title",response.up+" up / "+response.down+" down").html(response.score+""),response.score<0&&Danbooru_1.Danbooru.notice("Post Score Updated")):Danbooru_1.Danbooru.error("An error occurred while processing votes")})}static getScoreClass(score){return score>0?"score-positive":score<0?"score-negative":"score-neutral"}toggleFavorite(){$("div.fav-buttons").hasClass("fav-buttons-false")?$("#add-fav-button")[0].click():$("#remove-fav-button")[0].click()}addFavorite(){$("div.fav-buttons").hasClass("fav-buttons-false")&&$("#add-fav-button")[0].click()}removeFavorite(){$("div.fav-buttons").hasClass("fav-buttons-false")||$("#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()}addSet(){$("a#set")[0].click()}toggleSetLatest(){const lastSet=parseInt(window.localStorage.getItem("set"));lastSet?PostActions_1.PostActions.toggleSet(lastSet,Post_1.Post.getViewingPost().id):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().id):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().id):Danbooru_1.Danbooru.error("Error: no set selected")}addSetCustom(dataKey){PostActions_1.PostActions.addSet(this.fetchSettings(dataKey),Post_1.Post.getViewingPost().id)}addPool(){$("a#pool")[0].click()}openImageHistory(){location.href="/post_versions?search[post_id]="+Post_1.Post.getViewingPost().id}}exports.PostViewer=PostViewer},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/post/PostActions":20}],55:[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/post/Post"),RE6Module_1=require("../../components/RE6Module");class TitleCustomizer extends RE6Module_1.RE6Module{constructor(){super(Page_1.PageDefinition.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.is_favorited&&(prefix+=this.fetchSettings("symbolFav")),this.post.user_score>0?prefix+=this.fetchSettings("symbolVoteUp"):this.post.user_score<0&&(prefix+=this.fetchSettings("symbolVoteDown")),prefix&&(prefix+=" ")),prefix+this.fetchSettings("template").replace(/%postid%/g,this.post.id).replace(/%artist%/g,tagSetToString(this.post.tags.real_artist)).replace(/%copyright%/g,tagSetToString(this.post.tags.copyright)).replace(/%character%/g,tagSetToString(this.post.tags.character)).replace(/%species%/g,tagSetToString(this.post.tags.species)).replace(/%general%/g,tagSetToString(this.post.tags.general)).replace(/%all%/g,this.post.tagString).replace(/%meta%/g,tagSetToString(this.post.tags.meta)).replace(/[ ]{2,}/g," ").replace(/( (?:- ){2,})/g," - ").replace(/\(\)|( - )$/g,"").replace(/^ | $/g,"")+" - "+Page_1.Page.getSiteName();function tagSetToString(tags){return[...tags].join(", ")}}}exports.TitleCustomizer=TitleCustomizer},{"../../components/RE6Module":2,"../../components/data/Page":16,"../../components/post/Post":19}],56:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ImageClickAction=exports.ImageLoadMethod=exports.BetterSearch=void 0;const Danbooru_1=require("../../components/api/Danbooru"),E621_1=require("../../components/api/E621"),APIPost_1=require("../../components/api/responses/APIPost"),XM_1=require("../../components/api/XM"),Blacklist_1=require("../../components/data/Blacklist"),Page_1=require("../../components/data/Page"),User_1=require("../../components/data/User"),Post_1=require("../../components/post/Post"),PostActions_1=require("../../components/post/PostActions"),RE6Module_1=require("../../components/RE6Module"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util"),BlacklistEnhancer_1=require("./BlacklistEnhancer");class BetterSearch extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefinition.search,Page_1.PageDefinition.favorites],!0,!0,[BlacklistEnhancer_1.BlacklistEnhancer])}getDefaultSettings(){return{enabled:!0,imageLoadMethod:ImageLoadMethod.Disabled,autoPlayGIFs:!0,imageSizeChange:!1,imageWidth:150,imageRatioChange:!1,imageRatio:.9,imageMinWidth:50,compactMode:!0,hoverTags:!1,ribbonsRel:!0,ribbonsFlag:!0,ribbonsAlt:!1,buttonsVote:!0,buttonsFav:!0,clickAction:ImageClickAction.Disabled,infiniteScroll:!0,loadAutomatically:!0,loadPrevPages:!1,hidePageBreaks:!0}}async prepare(){await super.prepare();const enabled=this.fetchSettings("enabled");Util_1.Util.LS.setItem("re621.bs.enabled",enabled+""),enabled&&this.pageMatchesFilter()&&(this.queryPage=Page_1.Page.getQueryParameter("page")||"1",this.queryTags=(Page_1.Page.getQueryParameter("tags")||"").split(" ").filter(el=>""!=el),this.queryLimit=parseInt(Page_1.Page.getQueryParameter("limit"))||void 0,this.pageResult=this.fetchPosts(),$("#content").attr("loading","true"))}create(){super.create();const paginator=$("#paginator-old, div.paginator menu").first(),curPage=parseInt(paginator.find(".current-page").text())||-1,lastPage=parseInt(paginator.find(".numbered-page").last().text())||-1;if(paginator.remove(),this.lastPage=Math.max(curPage,lastPage),Util_1.Util.Math.isNumeric(this.queryPage)){const currentPage=Util_1.Util.Math.clamp(parseInt(this.queryPage),1,750);this.queryPage=currentPage+"",this.lastPage<currentPage&&(this.lastPage=currentPage),this.hasMorePages=750==currentPage||currentPage<this.lastPage}else this.queryPage.match(/(?:a|b)\d+/g)?this.hasMorePages=!0:(this.queryPage="-1",this.hasMorePages=!1);this.createStructure(),this.updateContentHeader(),this.updatePageTitle(this.queryPage);const preloadEnabled=this.fetchSettings("loadPrevPages")&&"true"!==Page_1.Page.getQueryParameter("nopreload");let timer;Page_1.Page.removeQueryParameter("nopreload"),$(window).on("scroll.re621.gen resize.re621.gen",()=>{timer||(null==timer&&BetterSearch.trigger("scroll"),timer=window.setTimeout(()=>{timer=void 0,BetterSearch.trigger("scroll")},250))}),this.$content.on("re621:render","post",event=>{Post_1.Post.get($(event.currentTarget)).render()}).on("re621:reset","post",event=>{Post_1.Post.get($(event.currentTarget)).reset()}).on("re621:filters","post",event=>{Post_1.Post.get($(event.currentTarget)).updateFilters()}).on("re621:visibility","post",event=>{Post_1.Post.get($(event.currentTarget)).updateVisibility()}),BetterSearch.on("postcount",()=>{this.updatePostCount()}),BetterSearch.on("paginator",()=>{this.reloadPaginator()});const intersecting=new Set;let selectedPage=this.queryPage;this.observer=new IntersectionObserver(entries=>{entries.forEach(value=>{const post=Post_1.Post.get($(value.target)),has=intersecting.has(post.id);has&&!value.isIntersecting&&(intersecting.delete(post.id),post.reset()),!has&&value.isIntersecting&&(intersecting.add(post.id),window.setTimeout(()=>{intersecting.has(post.id)&&(post.render(),post.page!=selectedPage&&(selectedPage=post.page,Page_1.Page.setQueryParameter("page",selectedPage+""),this.updatePageTitle(selectedPage)))},100))})},{root:null,rootMargin:"100% 50% 100% 50%",threshold:.5}),new Promise(async resolve=>{let pagesLoaded=0;const pageResult=await this.pageResult,stats=$("<search-stats>").appendTo(this.$content);Util_1.Util.Math.isNumeric(this.queryPage)&&$("<span>").attr({id:"search-stats-count",title:"Approximate number of posts found"}).html((this.lastPage>1?"~":"")+Util_1.Util.formatK(pageResult.length*this.lastPage)+" Posts").appendTo(stats);const order=this.queryTags.find(el=>el.includes("order:"));if(Page_1.Page.matches(Page_1.PageDefinition.search)&&pageResult.length>1&&(!order||"order:id_desc"==order)){const diffData=BetterSearch.getPostDiffs(pageResult);$("<span>").attr({id:"search-stats-frequency",title:`Page refresh frequency\nNew page every ${(diffData.refresh/Util_1.Util.Time.DAY).toFixed(1)} days`}).html(Util_1.Util.Time.formatPeriod(diffData.refresh)).appendTo(stats);const graphContainer=$("<span>");graphContainer.attr({id:"search-stats-graph",title:`Post upload frequency\nNew post every ${Util_1.Util.Time.formatPeriod(diffData.average)}\nAt most every `+Util_1.Util.Time.formatPeriod(diffData.largest)}).html("").appendTo(stats);for(const point of diffData.data)$("<span>").css("height",(.9*(.5+point)).toFixed(2)+"em").appendTo(graphContainer)}if(pageResult.length>0){const imageRatioChange=this.fetchSettings("imageRatioChange");if(Util_1.Util.Math.isNumeric(this.queryPage)){const currentPage=parseInt(this.queryPage);let result=[];for(let i=preloadEnabled?Math.max(currentPage-BetterSearch.PAGES_PRELOAD,1):currentPage;i<currentPage;i++){result=await this.fetchPosts(i);for(const post of result){const postData=Post_1.Post.make(post,i+"",imageRatioChange);null!==postData&&(this.$content.append(postData.$ref),this.observer.observe(postData.$ref[0]))}$("<post-break>").attr("id","page-"+(i+1)).html("Page "+(i+1)).appendTo(this.$content),pagesLoaded++}}for(const post of pageResult){const postData=Post_1.Post.make(post,this.queryPage,imageRatioChange);null!==postData&&(this.$content.append(postData.$ref),this.observer.observe(postData.$ref[0]))}pagesLoaded++}this.$wrapper.removeAttr("loading").attr("infscroll","ready"),resolve(pagesLoaded)}).then(pagesLoaded=>{this.reloadPaginator(),this.reloadEventListeners();const scrollTo=$(`[page=${this.queryPage}]:visible:first`);preloadEnabled&&pagesLoaded>1&&0!==scrollTo.length&&$([document.documentElement,document.body]).animate({scrollTop:scrollTo.offset().top-30},200),BlacklistEnhancer_1.BlacklistEnhancer.update(),this.updatePostCount()})}static isPaused(){return BetterSearch.paused}static setPaused(state){BetterSearch.paused=state,BetterSearch.trigger("paginator")}updatePageTitle(page){document.title=(0==this.queryTags.length?"Posts":this.queryTags.join(" ").replace(/_/g," "))+("1"!=page?" - Page "+page:"")+" - "+Page_1.Page.getSiteName()}createStructure(){this.$wrapper=$("#content").attr("loading","true"),$("<search-loading>").html('<span><div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div></span>').appendTo(this.$wrapper),$('<option value="open">Fullscreen</option>').insertAfter("#mode-box-mode option[value=edit]"),$('<option value="blacklist">Blacklist</option>').insertAfter("#mode-box-mode option[value=remove-fav]"),this.$quickEdit=$("<form>").attr({id:"re621-quick-tags",postid:"invalid"}).addClass("simple_form").html('<input type="hidden" name="_method" value="put"><div class="quick-tags-container"> <textarea name="post[tag_string]" id="re621_qedit_tags" data-autocomplete="tag-edit" class="ui-autocomplete-input" autocomplete="off"></textarea></div><div class="quick-tags-toolbar"> <input type="submit" name="submit" value="Submit"> <input type="button" name="cancel" value="Cancel"> <input type="text" name="reason" placeholder="Edit Reason" title="Edit Reason" id="re621_qedit_reason"> <input type="text" name="parent" placeholder="Parent ID" title="Parent ID" id="re621_qedit_parent"> <select name="post[rating]" title="Rating" id="re621_qedit_rating">\n <option value="s">Safe</option>\n <option value="q">Questionable</option>\n <option value="e">Explicit</option>\n </select><div class="quick-tags-info"> <span id="re621-qedit-dimensions"></span> <span id="re621-qedit-flags" class="display-none-important"></span> <a id="re621-qedit-history" href="404">history</a></div></div>').appendTo(this.$wrapper).hide(),this.$quickEdit.data({token:$("#re621_qedit_token"),info:$("#re621-qedit-dimensions"),flags:$("#re621-qedit-flags"),history:$("#re621-qedit-history"),tags:$("#re621_qedit_tags"),reason:$("#re621_qedit_reason"),parent:$("#re621_qedit_parent"),rating:$("#re621_qedit_rating")}),this.$quickEdit.find("input[name=cancel]").on("click",()=>{this.$quickEdit.hide("fast")}),Danbooru_1.Danbooru.Autocomplete.initialize_all(),this.$quickEdit.on("submit",event=>{event.preventDefault();const postID=parseInt(this.$quickEdit.attr("postid"));E621_1.E621.Post.id(postID).put({post:{tag_string:this.$quickEdit.data("tags").val()+"",edit_reason:this.$quickEdit.data("reason").val()+"",parent_id:this.$quickEdit.data("parent").val()+"",rating:APIPost_1.PostRating.fromValue(this.$quickEdit.data("rating").val()+"")}}).then(response=>{Debug_1.Debug.log(response),Post_1.Post.get(postID).update(response[0].post).render(),Danbooru_1.Danbooru.notice(`Post <a href="/posts/${postID}" target="_blank">#${postID}</a> updated (<a href="/post_versions?search[post_id]=${postID}">history</a>)`),this.$quickEdit.hide("fast")},error=>{Danbooru_1.Danbooru.error("An error occurred while updating a post"),console.log(error),this.$quickEdit.hide("fast")})}),this.$content=$("<search-content>").appendTo(this.$wrapper);const infscroll=$("<paginator-container>").appendTo(this.$wrapper);$("<span>").addClass("paginator-loading").html('<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>').appendTo(infscroll),this.$paginator=$("<paginator>").html("").appendTo(infscroll)}updatePostCount(){this.$content.attr("posts",$("post:visible").length)}reloadRenderedPosts(){Post_1.Post.find("rendered").each(post=>post.render())}updateContentHeader(){const conf=this.fetchSettings(["imageSizeChange","imageWidth","imageRatioChange","imageRatio","imageMinWidth","compactMode","ribbonsAlt","hidePageBreaks"]);this.$content.removeAttr("style"),conf.imageSizeChange&&this.$content.css("--img-width",conf.imageWidth+"px"),conf.imageRatioChange?this.$content.css("--img-ratio",conf.imageRatio):this.$content.css("--img-fit",conf.imageMinWidth+"%"),conf.compactMode&&this.$content.css("--img-maxheight",(conf.imageSizeChange?conf.imageWidth:150)+"px"),conf.ribbonsAlt?this.$content.attr("ribbons-alt","true"):this.$content.removeAttr("ribbons-alt"),conf.hidePageBreaks?this.$content.attr("hide-page-breaks","true"):this.$content.removeAttr("hide-page-breaks")}reloadEventListeners(){this.reloadModeSwitchListener(),this.reloadInfScrollListeners()}reloadModeSwitchListener(){this.$content.on("click","post a",event=>{const mode=$("#mode-box-mode").val();if("view"==mode)return;event.preventDefault();const $article=$(event.currentTarget).parent(),post=Post_1.Post.get($article);switch(mode){case"rating-q":case"rating-s":case"rating-e":case"lock-rating":case"lock-note":case"delete":case"undelete":case"approve":case"remove-parent":case"tag-script":case"add-to-set":case"remove-from-set":case"fake-click":{const $tempArticle=$("<article>").addClass("post-preview display-none-important").attr({id:"post_"+post.id,"data-id":post.id,"data-tags":post.tagString}).appendTo("body");$("<a>").appendTo($tempArticle).one("click",event=>{Danbooru_1.Danbooru.PostModeMenu.click(event),window.setTimeout(()=>{$tempArticle.remove()},500)})[0].click();break}case"open":XM_1.XM.Util.openInTab(post.file.original,!1);break;case"blacklist":Blacklist_1.Blacklist.toggleBlacklistTag("id:"+post.id);break;case"vote-up":{const firstVote=null==post.$ref.attr("vote");PostActions_1.PostActions.vote(post.id,1,firstVote).then(response=>{Debug_1.Debug.log(response),0==response.action?firstVote?post.$ref.attr("vote","1"):post.$ref.attr("vote","0"):post.$ref.attr("vote",response.action),post.score=response.score,post.$ref.trigger("re621:update")},error=>{Danbooru_1.Danbooru.error("An error occurred while recording the vote"),console.log(error)});break}case"vote-down":{const firstVote=null==post.$ref.attr("vote");PostActions_1.PostActions.vote(post.id,-1,!1).then(response=>{Debug_1.Debug.log(response),0==response.action?firstVote?post.$ref.attr("vote","1"):post.$ref.attr("vote","0"):post.$ref.attr("vote",response.action),post.score=response.score,post.$ref.trigger("re621:update")},error=>{Danbooru_1.Danbooru.error("An error occurred while recording the vote"),console.log(error)});break}case"add-fav":E621_1.E621.Favorites.post({post_id:post.id}),post.is_favorited=!0,post.$ref.attr("fav","true");break;case"remove-fav":E621_1.E621.Favorite.id(post.id).delete(),post.is_favorited=!1,post.$ref.removeAttr("fav");break;case"edit":{"true"==$("body").attr("data-sticky-header")?this.$quickEdit.css("top",$("#top").height()+"px"):this.$quickEdit.css("top",""),this.$quickEdit.show("fast"),this.$quickEdit.attr("postid",post.id);const ratio=Util_1.Util.formatRatio(post.img.width,post.img.height);this.$quickEdit.data("info").html(`${post.img.width} x ${post.img.height} (${ratio[0]}:${ratio[1]}), ${Util_1.Util.formatBytes(post.file.size)}`),this.$quickEdit.data("flags").toggleClass("display-none-important",0==post.flags.size).html(post.flags.size>0?[...post.flags].join(", "):""),this.$quickEdit.data("history").attr("href","https://e621.net/post_versions?search[post_id]="+post.id),this.$quickEdit.data("tags").val(post.tagString+" ").trigger("re621:input").focus(),this.$quickEdit.data("reason").val(""),this.$quickEdit.data("parent").val(post.rel.parent),this.$quickEdit.data("rating").val(post.rating);break}default:Danbooru_1.Danbooru.error("Unknown mode")}})}reloadInfScrollListeners(){const fullpage=$(document),viewport=$(window);BetterSearch.off("scroll.infscroll"),this.fetchSettings("infiniteScroll")&&this.fetchSettings("loadAutomatically")&&void 0===this.queryLimit&&BetterSearch.on("scroll.infscroll",()=>{if(!this.hasMorePages)return void BetterSearch.off("scroll.infscroll");if(BetterSearch.paused)return;if(this.loadingPosts)return;const pageHeight=fullpage.height(),viewHeight=viewport.height();viewport.scrollTop()+viewHeight<Math.max(pageHeight-viewHeight,.9*fullpage.height())||$("#infscroll-next")[0].click()})}async fetchPosts(page){if(Page_1.Page.matches(Page_1.PageDefinition.favorites)){const userID=Page_1.Page.getQueryParameter("user_id")||User_1.User.getUserID();return E621_1.E621.Favorites.get({user_id:userID,page:page||this.queryPage,limit:this.queryLimit},500)}const parsedTags=[];for(const tag of this.queryTags)parsedTags.push(decodeURIComponent(tag));return E621_1.E621.Posts.get({tags:parsedTags,page:page||this.queryPage,limit:this.queryLimit},500)}async loadNextPage(){this.queryPage=Util_1.Util.Math.isNumeric(this.queryPage)?this.queryPage=parseInt(this.queryPage)+1+"":this.queryPage="b"+Post_1.Post.get($("post:last")).id;const search=await this.fetchPosts(this.queryPage);if(0==search.length)return Promise.resolve(!1);const imageRatioChange=this.fetchSettings("imageRatioChange");$("<post-break>").attr("id","page-"+this.queryPage).html("Page "+this.queryPage).appendTo(this.$content);for(const post of search){if(null!==Post_1.Post.get(post.id))continue;const postData=Post_1.Post.make(post,this.queryPage,imageRatioChange);null!==postData&&(this.$content.append(postData.$ref),this.observer.observe(postData.$ref[0]))}return Page_1.Page.setQueryParameter("page",this.queryPage+""),BetterSearch.trigger("tracker.update"),BlacklistEnhancer_1.BlacklistEnhancer.update(),this.updatePostCount(),BetterSearch.trigger("pageload"),Util_1.Util.Math.isNumeric(this.queryPage)?Promise.resolve(parseInt(this.queryPage)<this.lastPage):Promise.resolve(!0)}reloadPaginator(){if(this.$paginator.html(""),"1"==this.queryPage?$("<span>").html('<i class="fas fa-angle-double-left"></i> Previous').addClass("paginator-prev").appendTo(this.$paginator):$("<a>").attr("href",function(page){if(Util_1.Util.Math.isNumeric(page))return getPageURL(parseInt(page)-1);const lookup=$("post:first");return 0==lookup.length?null:getPageURL("a"+Post_1.Post.get(lookup).id)}(this.queryPage)).html('<i class="fas fa-angle-double-left"></i> Previous').addClass("paginator-prev").appendTo(this.$paginator),this.fetchSettings("infiniteScroll")){const loadMoreWrap=$("<span>").addClass("infscroll-next-wrap").appendTo(this.$paginator),loadMoreCont=$("<span>").addClass("infscroll-next-cont").appendTo(loadMoreWrap);this.hasMorePages?($("<a>").html("Load More").attr("id","infscroll-next").appendTo(loadMoreCont).one("click",event=>{event.preventDefault(),this.loadingPosts=!0,this.$wrapper.attr("infscroll","loading"),this.loadNextPage().then(result=>{this.hasMorePages=result,this.$wrapper.attr("infscroll","ready"),this.reloadPaginator(),this.loadingPosts=!1})}),$("<span>").addClass("infscroll-manual").html(BetterSearch.paused||!this.fetchSettings("loadAutomatically")?"Manual Mode":" ").appendTo(loadMoreCont)):$("<span>").html("No More Posts").attr("id","infscroll-next").appendTo(loadMoreCont)}else $("<span>").appendTo(this.$paginator);this.hasMorePages?$("<a>").attr("href",function(page){if(Util_1.Util.Math.isNumeric(page)){if(parseInt(page)<750)return getPageURL(parseInt(page)+1)}const lookup=$("post:last");return 0==lookup.length?null:getPageURL("b"+Post_1.Post.get(lookup).id)}(this.queryPage)).html('Next <i class="fas fa-angle-double-right"></i>').addClass("paginator-next").appendTo(this.$paginator):$("<span>").html('Next <i class="fas fa-angle-double-right"></i>').addClass("paginator-next").appendTo(this.$paginator);const pages=$("<div>").addClass("paginator-numbers").appendTo(this.$paginator);if(Util_1.Util.Math.isNumeric(this.queryPage)){const currentPage=parseInt(this.queryPage),pageNum=[];let count=0;for(let i=1;i<=this.lastPage;i++)Util_1.Util.Math.between(i,0,currentPage<5?5:3)||Util_1.Util.Math.between(i,currentPage-2,currentPage+2)||Util_1.Util.Math.between(i,currentPage<5?this.lastPage-5:this.lastPage-3,this.lastPage)?(pageNum.push(i),count++):null!==pageNum[count-1]&&(pageNum.push(null),count++);for(const page of pageNum)null==page?$("<span>").html(". . .").appendTo(pages):page==currentPage?$("<span>").html(`<b>${page}</b>`).appendTo(pages):$("<a>").attr("href",getPageURL(page)).html(""+page).appendTo(pages)}function getPageURL(page){const url=new URL(window.location.toString());return url.searchParams.set("page",page+""),url.searchParams.set("nopreload","true"),url.pathname+url.search}}static getPostDiffs(posts,chunks=10){const response={refresh:getDiff(posts[0],posts[posts.length-1]),largest:1,average:1,data:[]},period=Math.ceil(posts.length/chunks),intervals=[];let largest=1,smallest=1,average=0;for(let i=0;i<posts.length-period;i+=period){const diff=getDiff(posts[i],posts[i+period]);intervals.push(diff),diff>largest&&(largest=diff),(diff<smallest||1==smallest)&&(smallest=diff),average+=diff}average/=posts.length;const range=largest-smallest,intervalData=[];for(const entry of intervals)intervalData.push(Util_1.Util.Math.round((entry-smallest)/range*-1+.5));return response.largest=largest,response.average=average,response.data=intervalData,response;function getDiff(one,two){return new Date(one.created_at).getTime()-new Date(two.created_at).getTime()}}}var ImageLoadMethod,ImageClickAction;exports.BetterSearch=BetterSearch,BetterSearch.PAGES_PRELOAD=3,BetterSearch.CLICK_DELAY=200,BetterSearch.paused=!1,function(ImageLoadMethod){ImageLoadMethod.Disabled="disabled",ImageLoadMethod.Hover="hover",ImageLoadMethod.Always="always"}(ImageLoadMethod=exports.ImageLoadMethod||(exports.ImageLoadMethod={})),function(ImageClickAction){ImageClickAction.Disabled="disabled",ImageClickAction.NewTab="newtab",ImageClickAction.CopyID="copyid",ImageClickAction.Blacklist="blacklist",ImageClickAction.AddToSet="addtoset",ImageClickAction.ToggleSet="toggleset"}(ImageClickAction=exports.ImageClickAction||(exports.ImageClickAction={}))},{"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/api/E621":5,"../../components/api/XM":6,"../../components/api/responses/APIPost":11,"../../components/data/Blacklist":14,"../../components/data/Page":16,"../../components/data/User":18,"../../components/post/Post":19,"../../components/post/PostActions":20,"../../components/utility/Debug":30,"../../components/utility/Util":33,"./BlacklistEnhancer":57}],57:[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/post/Post"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),BetterSearch_1=require("./BetterSearch");class BlacklistEnhancer extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefinition.search,Page_1.PageDefinition.favorites],!0,!1,[BetterSearch_1.BetterSearch])}getDefaultSettings(){return{enabled:!0,favorites:!1,uploads:!1,whitelist:""}}create(){super.create(),Danbooru_1.Danbooru.Blacklist.stub_vanilla_functions(),Danbooru_1.Danbooru.Blacklist.initialize_disable_all_blacklists(),$("#blacklisted-hider").remove(),BlacklistEnhancer.$wrapper=$("#blacklist-box").attr({open:!1,count:0,discount:0,collapsed:"1"==Util_1.Util.LS.getItem("bc")}).removeAttr("style").removeAttr("class").appendTo("#re621-search").html(""),BlacklistEnhancer.$header=$("<blacklist-header>").html("Blacklisted").appendTo(BlacklistEnhancer.$wrapper).on("click.re621",()=>{const collapsed=!("true"==BlacklistEnhancer.$wrapper.attr("collapsed"));BlacklistEnhancer.$wrapper.attr("collapsed",collapsed+""),Util_1.Util.LS.setItem("bc",collapsed?"1":"0"),$("#sidebar").trigger("re621:reflow")}),BlacklistEnhancer.$content=$("<blacklist-content>").appendTo(BlacklistEnhancer.$wrapper),BlacklistEnhancer.$content.on("click.re621","a",event=>{event.preventDefault();const $target=$(event.currentTarget).parent(),enabled=!("true"==$target.attr("enabled")),filter=$target.data("filter");filter.setEnabled(enabled),$target.attr("enabled",enabled+""),BlacklistEnhancer.updateHeader(),BlacklistEnhancer.updateToggleSwitch();for(const match of filter.getMatches())$("#entry_"+match).trigger("re621:visibility");BetterSearch_1.BetterSearch.trigger("postcount")});const toggleContainer=$("<blacklist-toggle>").appendTo(BlacklistEnhancer.$wrapper);BlacklistEnhancer.$toggle=$("<a>").attr("id","disable-all-blacklists").html("Disable All Filters").appendTo(toggleContainer).on("click.re621",()=>{"re-enable-all-blacklists"==BlacklistEnhancer.$toggle.attr("id")?(Blacklist_1.Blacklist.enableAll(),BlacklistEnhancer.$toggle.attr("id","disable-all-blacklists"),Post_1.Post.find("all").each(post=>post.updateVisibility())):(Blacklist_1.Blacklist.disableAll(),Post_1.Post.find("blacklisted").each(post=>post.updateVisibility()),BlacklistEnhancer.$toggle.attr("id","re-enable-all-blacklists"),BlacklistEnhancer.$wrapper.attr("collapsed","false"),Util_1.Util.LS.setItem("bc","0"),$("#sidebar").trigger("re621:reflow")),BlacklistEnhancer.update(),BetterSearch_1.BetterSearch.trigger("postcount")})}static update(){BlacklistEnhancer.updateFilterList(),BlacklistEnhancer.updateHeader(),BlacklistEnhancer.updateToggleSwitch(),$("#sidebar").trigger("re621:reflow")}static updateHeader(){let enabled=0,disabled=0;for(const entry of BlacklistEnhancer.$content.find("filter")){const filter=$(entry);"true"==filter.attr("enabled")?enabled+=parseInt(filter.attr("count"))||0:disabled+=parseInt(filter.attr("count"))||0}BlacklistEnhancer.$header.html(`Blacklisted (${enabled})`),BlacklistEnhancer.$wrapper.attr({count:enabled,discount:disabled})}static updateFilterList(){BlacklistEnhancer.$content.html("");for(const[tags,filter]of Blacklist_1.Blacklist.getActiveFilters()){const count=filter.getMatchesCount(),entry=$("<filter>").attr({count:count,enabled:filter.isEnabled()}).data("filter",filter).appendTo(BlacklistEnhancer.$content);$("<a>").attr("href","/posts?tags="+tags.replace(" ","+")).html(tags.replace(/_/g,"​_")).appendTo(entry),$("<span>").html(count+"").appendTo(entry)}$("#sidebar").trigger("re621:reflow")}static updateToggleSwitch(){BlacklistEnhancer.$content.find("filter[enabled=false]").length>0?(BlacklistEnhancer.$toggle.html("Enable All Filters").attr("id","re-enable-all-blacklists"),Util_1.Util.LS.setItem("dab","1")):(BlacklistEnhancer.$toggle.html("Disable All Filters").attr("id","disable-all-blacklists"),Util_1.Util.LS.setItem("dab","0"))}}exports.BlacklistEnhancer=BlacklistEnhancer},{"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/data/Blacklist":14,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/utility/Util":33,"./BetterSearch":56}],58:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CustomFlagger=void 0;const Page_1=require("../../components/data/Page"),ModuleController_1=require("../../components/ModuleController"),Post_1=require("../../components/post/Post"),PostFilter_1=require("../../components/post/PostFilter"),RE6Module_1=require("../../components/RE6Module"),BetterSearch_1=require("./BetterSearch");class CustomFlagger extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefinition.post,Page_1.PageDefinition.search,Page_1.PageDefinition.favorites,Page_1.PageDefinition.popular],!0,!1,[BetterSearch_1.BetterSearch])}getDefaultSettings(){return{enabled:!1,flags:[]}}create(){Page_1.Page.matches(Page_1.PageDefinition.post)&&this.createPostPage()}static get(){if(null==CustomFlagger.filters){CustomFlagger.filters=new Map;for(const flag of ModuleController_1.ModuleController.get(CustomFlagger).fetchSettings("flags"))CustomFlagger.filters.get(flag.tags)||CustomFlagger.filters.set(flag.tags,{data:flag,filter:new PostFilter_1.PostFilter(flag.tags,!0)})}return CustomFlagger.filters}static addPost(...posts){let count=0;for(const filterPair of CustomFlagger.get().values())filterPair.filter.update(posts)&&count++;return count}static updatePost(...posts){return CustomFlagger.addPost(...posts)}static getFlags(post){"number"!=typeof post&&(post=post.id);const output=[];for(const filterPair of CustomFlagger.get().values())filterPair.filter.matchesID(post)&&output.push(filterPair.data);return output}createPostPage(){const post=Post_1.Post.getViewingPost();CustomFlagger.addPost(post);const flagContainer=$("<div>").insertBefore("div.input#tags-container");let activeFlags=0;for(const flag of CustomFlagger.getFlags(post))$("<div>").addClass("custom-flag").html(`<span class="custom-flag-title" style="--flag-color: ${flag.color}">${flag.name}</span> ${flag.tags}`).appendTo(flagContainer),activeFlags++;activeFlags>0&&$("<b>").html("Flags").addClass("display-block").prependTo(flagContainer)}}exports.CustomFlagger=CustomFlagger},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/post/PostFilter":21,"./BetterSearch":56}],59:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ImageZoomMode=exports.HoverZoom=void 0;const APIPost_1=require("../../components/api/responses/APIPost"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module"),DomUtilities_1=require("../../components/structure/DomUtilities"),Debug_1=require("../../components/utility/Debug"),Util_1=require("../../components/utility/Util");class HoverZoom extends RE6Module_1.RE6Module{constructor(){super([],!0),this.shiftPressed=!1}getDefaultSettings(){return{enabled:!0,mode:ImageZoomMode.OnShift,tags:!0,time:!0}}create(){super.create(),this.createStructure(),this.reloadEventListeners(),this.initFunctionality()}createStructure(){this.$zoomBlock=$("<zoom-container>").attr("status","waiting").appendTo("body"),this.$zoomInfo=$("<div>").attr("id","zoom-info").appendTo(this.$zoomBlock),this.$zoomImage=$("<img>").attr("src",DomUtilities_1.DomUtilities.getPlaceholderImage()).addClass("display-none").appendTo(this.$zoomBlock),this.$zoomVideo=$("<video controls autoplay loop muted></video>").attr({poster:"",src:"",muted:"muted"}).addClass("display-none").appendTo(this.$zoomBlock),this.$zoomTags=$("<div>").attr("id","zoom-tags").appendTo(this.$zoomBlock)}reloadEventListeners(){const zoomMode=this.fetchSettings("mode");$(document).off("keydown.re621.zoom").off("keyup.re621.zoom"),$("#page").off("mouseenter.re621.zoom","post, .post-preview, div.post-thumbnail").off("mouseleave.re621.zoom","post, .post-preview, div.post-thumbnail"),zoomMode!=ImageZoomMode.Disabled&&($("#page").on("mouseenter.re621.zoom","post, .post-preview, div.post-thumbnail",event=>{const $ref=$(event.currentTarget);$ref.attr("hovering","true"),HoverZoom.trigger("zoom.start",{post:$ref.data("id"),pageX:event.pageX,pageY:event.pageY})}).on("mouseleave.re621.zoom","post, .post-preview, div.post-thumbnail",event=>{const $ref=$(event.currentTarget);$ref.removeAttr("hovering"),HoverZoom.trigger("zoom.stop",{post:$ref.data("id"),pageX:event.pageX,pageY:event.pageY})}),zoomMode===ImageZoomMode.OnShift&&$(document).on("keydown.re621.zoom",event=>{if(this.shiftPressed||"Shift"!==event.originalEvent.key)return;this.shiftPressed=!0;let count=0;for(const el of $("[hovering=true]"))$(el).trigger("mouseenter.re621.zoom"),count++;Debug_1.Debug.log("hovering total",count)}).on("keyup.re621.zoom",event=>{this.shiftPressed&&"Shift"===event.originalEvent.key&&(this.shiftPressed=!1)}))}initFunctionality(){let videoTimeout;const viewport=$(window);HoverZoom.on("zoom.start",(event,data)=>{if(HoverZoom.paused||this.fetchSettings("mode")==ImageZoomMode.OnShift&&!this.shiftPressed)return;const $ref=$(`#entry_${data.post}, #post_${data.post}, div.post-thumbnail[data-id=${data.post}]`).first(),post=$ref.is("post")?Post_1.Post.get($ref):Post_1.PostData.fromThumbnail($ref);if(post.flags.has(APIPost_1.PostFlag.Deleted)||"swf"==post.file.ext)return;const $img=$ref.find("img").first();$ref.data("stored-title",$img.attr("title")||""),$img.removeAttr("title"),this.$zoomBlock.attr("status","loading");let width=Math.min(post.img.width,.5*viewport.width()-50),height=width*post.img.ratio;height>.75*viewport.height()&&(height=.75*viewport.height(),width=height/post.img.ratio),this.$zoomImage.css({width:width+"px",height:height+"px"}),"webm"==post.file.ext?(this.$zoomVideo.removeClass("display-none").css("background-image",`url("${post.file.sample}")`).attr({src:post.file.original,poster:post.file.sample}),videoTimeout=window.setTimeout(()=>{this.$zoomVideo.attr("muted","false")},500),this.$zoomBlock.attr("status","ready")):this.$zoomImage.removeClass("display-none").css("background-image",`url("${post.file.preview}")`).attr("src",post.file.sample).one("load",()=>{this.$zoomBlock.attr("status","ready")}),this.$zoomInfo.html(`${post.img.width} x ${post.img.height}`+(post.file.size>0?", "+Util_1.Util.formatBytes(post.file.size):"")+` | <span class="post-info-rating rating-${post.rating}">${post.rating}</span>`+("0"!==post.date.raw?" | "+(this.fetchSettings("time")?post.date.ago:Util_1.Util.Time.format(post.date.raw)):"")),this.fetchSettings("tags")&&this.$zoomTags.html(post.tagString).css({"max-width":width+"px"});let throttled=!1;$(document).on("mousemove.re621.zoom",event=>{if(throttled)return;throttled=!0,window.setTimeout(()=>{throttled=!1},25);const imgHeight=this.$zoomBlock.height(),imgWidth=this.$zoomBlock.width(),cursorX=event.pageX,cursorY=event.pageY-viewport.scrollTop(),left=cursorX<viewport.width()/2?cursorX+50:cursorX-imgWidth-50,top=Util_1.Util.Math.clamp(cursorY-imgHeight/2,10,viewport.height()-imgHeight-10);this.$zoomBlock.css({left:left+"px",top:top+"px"})});const offset=$ref.offset(),e=$.Event("mousemove.re621.zoom"),centerX=offset.left+$ref.width()/2,centerY=offset.top+$ref.height()/2;e.pageX=data.pageX?data.pageX:centerX,e.pageY=data.pageY?data.pageY:centerY,$(document).trigger(e)}),HoverZoom.on("zoom.stop",(event,data)=>{$(document).off("mousemove.re621.zoom");const $ref=$(`#entry_${data.post}, #post_${data.post}, div.post-thumbnail[data-id=${data.post}]`).first(),$img=$ref.find("img").first();$ref.data("stored-title")&&$img.attr("title",$ref.data("stored-title")),this.$zoomBlock.attr("status","waiting").css({left:0,top:"100vh"}),this.$zoomInfo.html(""),this.$zoomImage.addClass("display-none").removeAttr("style").attr("src",DomUtilities_1.DomUtilities.getPlaceholderImage()),this.$zoomVideo.addClass("display-none").attr({muted:""}),""!==this.$zoomVideo.attr("src")&&this.$zoomVideo.attr({poster:"",src:""}),window.clearTimeout(videoTimeout),this.$zoomTags.removeAttr("style").html("")})}}var ImageZoomMode;exports.HoverZoom=HoverZoom,HoverZoom.paused=!1,function(ImageZoomMode){ImageZoomMode.Disabled="disabled",ImageZoomMode.Hover="hover",ImageZoomMode.OnShift="onshift"}(ImageZoomMode=exports.ImageZoomMode||(exports.ImageZoomMode={}))},{"../../components/RE6Module":2,"../../components/api/responses/APIPost":11,"../../components/post/Post":19,"../../components/structure/DomUtilities":25,"../../components/utility/Debug":30,"../../components/utility/Util":33}],60:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.InstantFilters=void 0;const Page_1=require("../../components/data/Page"),Post_1=require("../../components/post/Post"),PostFilter_1=require("../../components/post/PostFilter"),RE6Module_1=require("../../components/RE6Module"),Util_1=require("../../components/utility/Util"),BetterSearch_1=require("./BetterSearch");class InstantFilters extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefinition.search,Page_1.PageDefinition.favorites],!0,!1,[BetterSearch_1.BetterSearch])}getDefaultSettings(){return{enabled:!1}}create(){super.create(),$("search-content").on("re621:insearch","post",event=>{const $article=$(event.currentTarget),post=Post_1.Post.get($article);null==InstantFilters.filter?$article.removeAttr("filtered"):(InstantFilters.filter.update(post),InstantFilters.filter.matches(post)?$article.removeAttr("filtered"):$article.attr("filtered","true"))});const $section=$("<section>").attr("id","re621-insearch").html("<h1>Filter</h1>").insertAfter("#search-box"),$searchForm=$("<form>").appendTo($section).on("submit",event=>{event.preventDefault()});let typingTimeout;this.$searchbox=$("<input>").attr("id","re621-insearch-input").attr("type","text").val(Page_1.Page.getQueryParameter("insearch")||"").appendTo($searchForm).on("input",()=>{clearTimeout(typingTimeout),typingTimeout=window.setTimeout(()=>{this.applyFilter()},500)}),this.$searchbox.trigger("input"),$("<button>").attr("type","submit").html('<i class="fas fa-search"></i>').appendTo($searchForm),$("#sidebar").trigger("re621:reflow")}destroy(){super.destroy(),this.$searchbox.val(""),this.applyFilter(),$("#re621-insearch").remove(),$("search-content").off("re621:insearch","post"),$("#sidebar").trigger("re621:reflow")}static get(){return InstantFilters.filter}static addPost(...posts){const filter=InstantFilters.get();return!!filter&&filter.update(posts)}applyFilter(){const filterText=Util_1.Util.getTagString(this.$searchbox);0==filterText.length?InstantFilters.filter=void 0:InstantFilters.filter=new PostFilter_1.PostFilter(filterText),$("post").trigger("re621:insearch")}}exports.InstantFilters=InstantFilters},{"../../components/RE6Module":2,"../../components/data/Page":16,"../../components/post/Post":19,"../../components/post/PostFilter":21,"../../components/utility/Util":33,"./BetterSearch":56}],61:[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.PageDefinition.search)}getDefaultSettings(){return{enabled:!0}}create(){if(super.create(),!User_1.User.isLoggedIn())return;const listItem=$("<li>").appendTo("ul#related-list"),button=$("<a>").attr({id:"recommended-posts",title:"Show posts similar to your favorites"}).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 [ page ${i} ]`),result=await E621_1.E621.Favorites.get({user_id:User_1.User.getUserID(),page:i},500),result.forEach(post=>{APIPost_1.APIPost.getTags(post).forEach(tag=>{data[tag]?data[tag]=data[tag]+1:data[tag]=1})}),100===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).on("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.length=Math.min(query.length,37),query.push(encodeURIComponent("-fav:"+User_1.User.getUsername()),encodeURIComponent("order:random"),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":11,"../../components/data/Page":16,"../../components/data/User":18,"../../components/structure/Modal":27}],62:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SearchUtilities=void 0;const Danbooru_1=require("../../components/api/Danbooru"),Blacklist_1=require("../../components/data/Blacklist"),Page_1=require("../../components/data/Page"),RE6Module_1=require("../../components/RE6Module");class SearchUtilities extends RE6Module_1.RE6Module{constructor(){super([Page_1.PageDefinition.search,Page_1.PageDefinition.post,Page_1.PageDefinition.favorites]),this.registerHotkeys({keys:"hotkeyFocusSearch",fnct:this.focusSearchbar},{keys:"hotkeyRandomPost",fnct:this.randomPost},{keys:"hotkeySwitchModeView",fnct:this.switchModeView},{keys:"hotkeySwitchModeEdit",fnct:this.switchModeEdit},{keys:"hotkeySwitchModeOpen",fnct:this.switchModeOpen},{keys:"hotkeySwitchModeAddFav",fnct:this.switchModeAddFav},{keys:"hotkeySwitchModeRemFav",fnct:this.switchModeRemFav},{keys:"hotkeySwitchModeBlacklist",fnct:this.switchModeBlacklist},{keys:"hotkeySwitchModeAddSet",fnct:this.switchModeAddSet},{keys:"hotkeySwitchModeRemSet",fnct:this.switchModeRemSet})}getDefaultSettings(){return{enabled:!0,improveTagCount:!0,shortenTagNames:!0,hidePlusMinusIcons:!1,collapseCategories:!0,categoryData:[],persistentTags:"",quickBlacklist:!0,hotkeyFocusSearch:"q",hotkeyRandomPost:"r",hotkeySwitchModeView:"",hotkeySwitchModeEdit:"",hotkeySwitchModeOpen:"",hotkeySwitchModeAddFav:"",hotkeySwitchModeRemFav:"",hotkeySwitchModeAddSet:"",hotkeySwitchModeRemSet:"",hotkeySwitchModeBlacklist:""}}create(){if(super.create(),Page_1.Page.matches(Page_1.PageDefinition.search)){const searchbox=$("section#search-box input");""==searchbox.val()&&searchbox.trigger("focus")}Page_1.Page.matches(Page_1.PageDefinition.post)&&Page_1.Page.removeQueryParameter("q"),Page_1.Page.matches([Page_1.PageDefinition.search,Page_1.PageDefinition.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.PageDefinition.post)&&this.collapseTagCategories();const persistentTags=this.fetchSettings("persistentTags").trim().toLowerCase();if(""!==persistentTags&&Page_1.Page.matches([Page_1.PageDefinition.search,Page_1.PageDefinition.post,Page_1.PageDefinition.favorites])){const $tagInput=$("input#tags");$tagInput.val(($tagInput.val()+"").replace(persistentTags,"")),$("section#search-box form").on("submit",()=>($tagInput.val($tagInput.val()+" "+persistentTags),!0))}this.initQuickBlacklist(this.fetchSettings("quickBlacklist")),Page_1.Page.matches(Page_1.PageDefinition.search)&&this.handleSidebarCollapse()}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").trigger("focus")}randomPost(){location.pathname="/posts/random"}switchModeView(){SearchUtilities.switchMode("view")}switchModeEdit(){SearchUtilities.switchMode("edit")}switchModeOpen(){SearchUtilities.switchMode("open")}switchModeAddFav(){SearchUtilities.switchMode("add-fav")}switchModeRemFav(){SearchUtilities.switchMode("remove-fav")}switchModeBlacklist(){SearchUtilities.switchMode("blacklist")}switchModeAddSet(){SearchUtilities.switchMode("add-to-set"),$("#set-id").trigger("focus")}switchModeRemSet(){SearchUtilities.switchMode("remove-from-set"),$("#set-id").trigger("focus")}static switchMode(mode){$("select#mode-box-mode").val(mode),Danbooru_1.Danbooru.PostModeMenu.change()}initQuickBlacklist(state=!0){if(state)for(const element of $("div.tag-actions span.tag-action-blacklist").get()){const $container=$(element);$("<a>").attr({href:"#",title:"Blacklist Tag"}).addClass("blacklist-tag-toggle").html('<i class="fas fa-times"></i>').prependTo($container).on("click",event=>{event.preventDefault(),Blacklist_1.Blacklist.toggleBlacklistTag($container.parent().attr("data-tag"))})}else $("div.tag-actions span.tag-action-blacklist").html("")}handleSidebarCollapse(){const sidebar=$("#sidebar"),button=$("<a>").attr({id:"sidebar-collapse"}).insertBefore(sidebar).on("click",()=>{sidebar.toggleClass("collapsed"),button.toggleClass("collapsed")})}}exports.SearchUtilities=SearchUtilities},{"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/data/Blacklist":14,"../../components/data/Page":16}],63:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ThumbnailTweaks=void 0;const ModuleController_1=require("../../components/ModuleController"),Post_1=require("../../components/post/Post"),RE6Module_1=require("../../components/RE6Module"),BetterSearch_1=require("./BetterSearch"),CustomFlagger_1=require("./CustomFlagger");class ThumbnailTweaks extends RE6Module_1.RE6Module{constructor(){super()}getDefaultSettings(){return{enabled:!0}}create(){super.create();const conf=ModuleController_1.ModuleController.get(BetterSearch_1.BetterSearch).fetchSettings(["ribbonsRel","ribbonsFlag"]);for(const element of $(".post-preview").get())ThumbnailTweaks.modify($(element),conf.ribbonsRel,conf.ribbonsFlag)}static modify($article,ribbonsRel,ribbonsFlag){const post=Post_1.PostData.fromThumbnail($article);CustomFlagger_1.CustomFlagger.addPost(post);let $picture=$article.find("picture");if(0==$picture.length){const $img=$article.find("img");$picture=$("<picture>").insertAfter($img).append($img)}$picture.addClass("picture-container");const $ribbons=$("<img-ribbons>").appendTo($picture);if(ribbonsRel){const relRibbon=$("<ribbon>").addClass("left").html("<span></span>").appendTo($ribbons),relRibbonText=[];"true"==$article.attr("data-has-children")&&(relRibbon.addClass("has-children"),relRibbonText.push("Child posts")),void 0!==$article.attr("data-parent-id")&&(relRibbon.addClass("has-parent"),relRibbonText.push("Parent posts")),relRibbonText.length>0?relRibbon.attr("title",relRibbonText.join("\n")):relRibbon.remove()}if(ribbonsFlag){const flags=new Set(($article.attr("data-flags")||"").split(" ")),flagRibbon=$("<ribbon>").addClass("right").html("<span></span>").appendTo($ribbons),flagRibbonText=[];flags.has("flagged")&&(flagRibbon.addClass("is-flagged"),flagRibbonText.push("Flagged")),flags.has("pending")&&(flagRibbon.addClass("is-pending"),flagRibbonText.push("Pending")),flagRibbonText.length>0?flagRibbon.attr("title",flagRibbonText.join("\n")):flagRibbon.remove()}0==$ribbons.children().length&&$ribbons.remove();const $flagBox=$("<post-flags>").appendTo($picture);for(const flag of CustomFlagger_1.CustomFlagger.getFlags(post))$("<span>").addClass("custom-flag-thumb").css("--flag-color",flag.color).attr("title",flag.tags).html(flag.name).appendTo($flagBox)}}exports.ThumbnailTweaks=ThumbnailTweaks},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/post/Post":19,"./BetterSearch":56,"./CustomFlagger":58}],64:[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"),User_1=require("../../components/data/User"),Post_1=require("../../components/post/Post"),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.PostData.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.PageDefinition.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> 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> - processing batch #${index}</div>`),postsJSON.push(...await E621_1.E621.Posts.get({tags:"id:"+chunk.join(",")},500));status.append("<div> fetching comments</div>");const commentsJSON=[];for(const[index,chunk]of storedSubChunks.entries())storedSubChunks.length>1&&status.append(`<div> - 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)+"…":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":16,"../../components/data/User":18,"../../components/post/Post":19,"../../components/utility/Util":33,"./SubscriptionTracker":68}],65:[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.PageDefinition.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> - 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":16,"../../components/data/User":18,"../../components/utility/Util":33,"./SubscriptionTracker":68}],66:[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/post/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.PostData.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> - 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":16,"../../components/post/Post":19,"../../components/utility/Util":33,"./SubscriptionTracker":68}],67:[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"),Util_1=require("../../components/utility/Util"),BetterSearch_1=require("../search/BetterSearch");class SubscriptionManager extends RE6Module_1.RE6Module{constructor(){super([],!1,!0),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)return;if(this.notificationsAlreadyOpened){const activeTab=this.tabs.tabs("option","active");return void window.setTimeout(()=>{this.clearTabNotification(activeTab)},1e3)}this.notificationsAlreadyOpened=!0,this.trackers.forEach(trackerData=>{this.executeReloadEvent(trackerData)});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.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(){let updateInterval=this.fetchSettings("updateInterval");return(updateInterval>24*Util_1.Util.Time.HOUR||updateInterval<Util_1.Util.Time.HOUR&&-1!=updateInterval)&&(updateInterval=Util_1.Util.Time.HOUR,this.pushSettings("updateInterval",updateInterval)),-1!==updateInterval&&(updateInterval/=Util_1.Util.Time.HOUR),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:updateInterval+""},{"-1":"Manually",1:"1 hour",6:"6 hours",12:"12 hours",24:"24 hours"},async data=>{(data=Math.max(parseFloat(data)*Util_1.Util.Time.HOUR,-1))<Util_1.Util.Time.HOUR&&-1!=data&&(data=Util_1.Util.Time.HOUR),await this.pushSettings("updateInterval",data),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&&-1!==time.updateInterval&&(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"),!navigator.onLine)return SubscriptionManager.updateInProgress=!1,void SubscriptionManager.trigger("timerRefresh");this.$openSubsButton.attr({"data-loading":"true","data-updates":"0"});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);try{const cache=trackerData.instance.getCache();await cache.load(),await cache.update(prevUpdate,status)}catch(error){SubscriptionManager.updateInProgress=!1,SubscriptionManager.trigger("timerRefresh")}trackerData.tabElement.attr("data-loading","false"),await this.executeReloadEvent(trackerData),resolve()}));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()}async executeReloadEvent(trackerData){const cache=trackerData.instance.getCache();if(await cache.load(),this.refreshTabNotifications(trackerData),this.refreshHeaderNotifications(),!this.notificationsAlreadyOpened&&!this.modal.isOpen())return void Debug_1.Debug.log(`SubM${trackerData.tabIndex}: [${cache.getSize()}] idle`);Debug_1.Debug.log(`SubM${trackerData.tabIndex}: [${cache.getSize()}] draw`),trackerData.content[0].innerHTML="",cache.getSize()>0&&trackerData.content.append(this.createCacheDivider());const clickAction=ModuleController_1.ModuleController.get(BetterSearch_1.BetterSearch).fetchSettings("clickAction");cache.forEach((content,timestamp)=>{trackerData.content.append(this.createUpdateEntry(timestamp,content,trackerData,clickAction))});const activeTab=this.tabs.tabs("option","active");this.modal.isOpen()&&trackerData.tabIndex==activeTab&&window.setTimeout(()=>{this.clearTabNotification(activeTab)},1e3)}async executeTimerRefreshEvent(){this.refreshSettings();const time=await this.fetchSettings(["lastUpdate","updateInterval","updateStarted"],!0);var lastUpdate,updateStarted,updateInterval;$("span#subscriptions-lastupdate").attr("title",(lastUpdate=time.lastUpdate,updateStarted=time.updateStarted,updateInterval=time.updateInterval,SubscriptionManager.updateInProgress?"":-1==updateInterval?"Never":0!==updateStarted?Util_1.Util.Time.format(updateStarted):0===lastUpdate?"":Util_1.Util.Time.format(lastUpdate))).html(function(lastUpdate,updateStarted,updateInterval){return SubscriptionManager.updateInProgress?"In progress . . .":-1==updateInterval?"Never":0!==updateStarted?Util_1.Util.Time.ago(updateStarted)+" (interrupted)":0===lastUpdate?"Never":Util_1.Util.Time.ago(lastUpdate)}(time.lastUpdate,time.updateStarted,time.updateInterval)),$("span#subscriptions-nextupdate").attr("title",function(lastUpdate,updateInterval,updateStarted){const now=Util_1.Util.Time.now();return SubscriptionManager.updateInProgress?"":-1==updateInterval?"Never":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();return SubscriptionManager.updateInProgress?"In progress . . .":-1==updateInterval?"Never":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.instance.getCache().getNewCount();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");const cache=subscription.instance.getCache();let cleared=0;cache.forEach(entry=>(entry.new&&cleared++,delete entry.new,entry)),this.refreshTabNotifications(subscription),this.refreshHeaderNotifications(),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.on("click",async event=>{event.preventDefault(),processing||(processing=!0,execSubscribe(id,$subscribeButton,$unsubscribeButton,$element).then(()=>{processing=!1}))}),$unsubscribeButton.on("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"),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"),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:actions.imageSrc(data),title:actions.updateText(data)+"\n"+timeAgo+"\n"+timeString}).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 dblclickTimer,prevent=!1;$link.on("click.re621.thumbnail",event=>{0!==event.button||event.shiftKey||event.ctrlKey||event.altKey||event.metaKey||(event.preventDefault(),dblclickTimer=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(dblclickTimer),prevent=!0,clickAction===BetterSearch_1.ImageClickAction.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).on("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=2,SubscriptionManager.updateInProgress=!1,SubscriptionManager.updateTimeout=5*Util_1.Util.Time.MINUTE},{"../../components/ModuleController":1,"../../components/RE6Module":2,"../../components/api/Danbooru":3,"../../components/api/XM":6,"../../components/structure/DomUtilities":25,"../../components/structure/Form":26,"../../components/structure/Modal":27,"../../components/structure/Tabbed":29,"../../components/utility/Debug":30,"../../components/utility/Util":33,"../search/BetterSearch":56}],68:[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(){try{this.data=JSON.parse(Util_1.Util.LS.getItem(this.getStorageTag())||"{}")}catch(error){this.data={},this.save()}return 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 Util_1.Util.LS.setItem(this.getStorageTag(),JSON.stringify(this.data)),XM_1.XM.Storage.setValue(this.getStorageTag(),Util_1.Util.Time.now())}async clear(){return this.data={},this.updateIndex(),this.save()}getIndex(){return this.index}getSize(){return this.index.length}getNewCount(){let count=0;return this.forEach(data=>{data.new&&count++}),count}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":6,"../../components/utility/Util":33,"./SubscriptionManager":67}],69:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.TagTracker=void 0;const E621_1=require("../../components/api/E621"),Blacklist_1=require("../../components/data/Blacklist"),ModuleController_1=require("../../components/ModuleController"),Post_1=require("../../components/post/Post"),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.PostData.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> - 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),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: post limit");break}const post=Post_1.PostData.fromAPI(apiResult[key]);Debug_1.Debug.log(`TgT: ${post.id} ${Util_1.Util.Time.format(new Date(post.date.raw))}`),Blacklist_1.Blacklist.addPost(post),Blacklist_1.Blacklist.checkPost(post.id,!0)?Debug_1.Debug.log("TgT: blacklist"):results[new Date(post.date.raw).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/Blacklist":14,"../../components/post/Post":19,"../../components/utility/Debug":30,"../../components/utility/Util":33,"./SubscriptionManager":67,"./SubscriptionTracker":68}]},{},[38]);