From 3e3878b93cdd8f9bf8eb3e3cc322d5eaaa8cd4ca Mon Sep 17 00:00:00 2001 From: Bobby Wibowo Date: Sun, 19 Apr 2020 02:52:11 +0700 Subject: [PATCH] Massively overhauled uploads filtering endpoint Please consult the Help? button again to learn all the syntax changes! The prompt will now also have its width expanded! Updated dependency, knex: 0.20.13 -> 0.20.15. Added new dependency: search-query-parser. Updated all sub-dependencies. Critical? Admins-only API /users/edit will no longer return NEW password salt of the user when randomizing their password. Added page.escape() function to js/misc/utils.js. This will be used to escape input in upload filters input box. The same function used in utilsController.js. Pretty dates will now use / instead of - for date separator. This is due to the fact that date range key for filtering uploads can not accepts dates with - separator. To avoid inconsistency, we will now use / separator. Caching system of album public pages will now be disabled during development (yarn develop). Cleaned up domClick() function in js/dashboard.js. If using date or expiry range keys when filtering uploads, attach client's timezone offset to the API requets. This will be used by the server to calculate timezone differences. Success prompt when changing token will now auto-close. Removed ID column from Manage Users. Improved success prompt when editing users. This will properly list all of the edited fields at once, excluding user group change. Success message for user group change will require a bit more changes on the API endpoint, which is a bit annoying. Rebuilt client-side assets and bumped v1 version string. --- controllers/authController.js | 2 +- controllers/uploadController.js | 293 ++++++++++++++++++++++---------- controllers/utilsController.js | 5 +- dist/js/dashboard.js | 2 +- dist/js/dashboard.js.map | 2 +- dist/js/misc/utils.js | 2 +- dist/js/misc/utils.js.map | 2 +- package.json | 3 +- routes/album.js | 54 +++--- src/js/dashboard.js | 190 ++++++++++++++------- src/js/misc/utils.js | 57 ++++++- src/versions.json | 2 +- yarn.lock | 93 +++++----- 13 files changed, 472 insertions(+), 235 deletions(-) diff --git a/controllers/authController.js b/controllers/authController.js index 4df1bf1..7d1e440 100644 --- a/controllers/authController.js +++ b/controllers/authController.js @@ -259,7 +259,7 @@ self.editUser = async (req, res, next) => { utils.invalidateStatsCache('users') const response = { success: true, update } - if (password) response.password = password + if (password) response.update.password = password return res.json(response) } catch (error) { logger.error(error) diff --git a/controllers/uploadController.js b/controllers/uploadController.js index e9e0e89..516decf 100644 --- a/controllers/uploadController.js +++ b/controllers/uploadController.js @@ -4,6 +4,7 @@ const fs = require('fs') const multer = require('multer') const path = require('path') const randomstring = require('randomstring') +const searchQuery = require('search-query-parser') const paths = require('./pathsController') const perms = require('./permissionController') const utils = require('./utilsController') @@ -758,94 +759,172 @@ self.list = async (req, res) => { const all = Boolean(req.headers.all) const filters = req.headers.filters + const minoffset = req.headers.minoffset const ismoderator = perms.is(user, 'moderator') if ((all || filters) && !ismoderator) return res.status(403).end() const basedomain = config.domain - // For filtering uploads - const _filters = { + const filterObj = { uploaders: [], - names: [], - ips: [], - flags: { - nouser: false, - noip: false + excludeUploaders: [], + queries: { + exclude: {} }, - keywords: [] + flags: {} } - // Cast column(s) to specific type if they're stored differently - const _orderByCasts = { - size: 'integer' + const orderByObj = { + // Cast columns to specific type if they are stored differently + casts: { + size: 'integer' + }, + // Columns mapping + maps: { + date: 'timestamp', + expiry: 'expirydate' + }, + // Columns with which to use SQLite's NULLS LAST option + nullsLast: [ + 'userid', + 'expirydate', + 'ip' + ], + parsed: [] } - // Columns with which to use SQLite's NULLS LAST option - const _orderByNullsLast = [ - 'userid', - 'expirydate', - 'ip' - ] - const _orderBy = [] - // Perhaps this can be simplified even further? if (filters) { - const usernames = [] - filters - .split(' ') - .map((v, i, a) => { - if (/[^\\]\\$/.test(v) && a[i + 1]) { - const tmp = `${v.slice(0, -1)} ${a[i + 1]}` - a[i + 1] = '' - return tmp - } - return v.replace(/\\\\/, '\\') - }) - .map((v, i) => { - const x = v.indexOf(':') - if (x >= 0 && v.substring(x + 1)) - return [v.substring(0, x), v.substring(x + 1)] - else - return v - }) - .forEach(v => { - if (Array.isArray(v)) { - if (v[0] === 'user') { - usernames.push(v[1]) - } else if (v[0] === 'name') { - _filters.names.push(v[1]) - } else if (v[0] === 'ip') { - _filters.ips.push(v[1]) - } else if (v[0] === 'orderby') { - const tmp = v[1].split(':') - let col = tmp[0] - let dir = 'asc' - if (_orderByCasts[col]) - col = `cast (\`${col}\` as ${_orderByCasts[col]})` - if (tmp[1] && /^d/i.test(tmp[1])) - dir = 'desc' - _orderBy.push(`${col} ${dir}${_orderByNullsLast.includes(col) ? ' nulls last' : ''}`) - } - } else { - if (v === '-user') - _filters.flags.nouser = true - else if (v === '-ip') - _filters.flags.noip = true - else - _filters.keywords.push(v[0]) - } - }) - _filters.uploaders = await db.table('users') - .whereIn('username', usernames) - .select('id', 'username') - } + const keywords = [ + 'ip', + 'user' + ] + const ranges = [ + 'date', + 'expiry' + ] + filterObj.queries = searchQuery.parse(filters, { + keywords: keywords.concat([ + 'orderby' + ]), + ranges, + tokenize: true, + alwaysArray: true, + offsets: false + }) - if (filters && !(_filters.uploaders.length || _filters.names.length || _filters.ips.length || _filters.flags.nouser || _filters.flags.noip || _orderBy.length)) - if (_filters.keywords.length) - // TODO: Support filtering using keywords only - return res.json({ success: false, description: 'Filtering using keywords only is still work in progress. Please confirm valid filtering keys through the Help? button!' }) - else - return res.json({ success: false, description: 'No valid filter or sort keys were used. Please confirm the valid keys through the Help? button!' }) + for (const key of keywords) + if (filterObj.queries[key]) { + // Make sure keyword arrays only contain unique values + filterObj.queries[key] = filterObj.queries[key].filter((v, i, a) => a.indexOf(v) === i) + + // Flag to match NULL values + const index = filterObj.queries[key].indexOf('-') + if (index !== -1) { + filterObj.flags[`no${key}`] = true + filterObj.queries[key].splice(index, 1) + } + } + + const parseDate = (date, minoffset, resetMs) => { + // [YYYY][/MM][/DD] [HH][:MM][:SS] + // e.g. 2020/01/01 00:00:00, 2018/01/01 06, 2019/11, 12:34:00 + const match = date.match(/^(\d{4})?(\/\d{2})?(\/\d{2})?\s?(\d{2})?(:\d{2})?(:\d{2})?$/) + + if (match) { + const offset = 60000 * (utils.timezoneOffset - minoffset) + const dateObj = new Date(Date.now() + offset) + + if (match[1] !== undefined) + dateObj.setFullYear(Number(match[1]), // full year + match[2] !== undefined ? (Number(match[2].slice(1)) - 1) : 0, // month, zero-based + match[3] !== undefined ? Number(match[3].slice(1)) : 1) // date + + if (match[4] !== undefined) + dateObj.setHours(Number(match[4]), // hours + match[5] !== undefined ? Number(match[5].slice(1)) : 0, // minutes + match[6] !== undefined ? Number(match[6].slice(1)) : 0) // seconds + + if (resetMs) + dateObj.setMilliseconds(0) + + // Calculate timezone differences + const newDateObj = new Date(dateObj.getTime() - offset) + return newDateObj + } else { + return null + } + } + + // Parse dates to timestamps + for (const range of ranges) + if (filterObj.queries[range]) { + if (filterObj.queries[range].from) { + const parsed = parseDate(filterObj.queries[range].from, minoffset, true) + filterObj.queries[range].from = parsed ? Math.floor(parsed / 1000) : null + } + if (filterObj.queries[range].to) { + const parsed = parseDate(filterObj.queries[range].to, minoffset, true) + filterObj.queries[range].to = parsed ? Math.ceil(parsed / 1000) : null + } + } + + // Query users table for user IDs + if (filterObj.queries.user || filterObj.queries.exclude.user) { + const usernames = [] + .concat(filterObj.queries.user || []) + .concat(filterObj.queries.exclude.user || []) + + const uploaders = await db.table('users') + .whereIn('username', usernames) + .select('id', 'username') + + // If no matches, or mismatched results + if (!uploaders || (uploaders.length !== usernames.length)) { + const notFound = usernames.filter(username => { + return !uploaders.find(uploader => uploader.username === username) + }) + if (notFound) + return res.json({ + success: false, + description: `User${notFound.length === 1 ? '' : 's'} not found: ${notFound.join(', ')}.` + }) + } + + for (const uploader of uploaders) + if (filterObj.queries.user && filterObj.queries.user.includes(uploader.username)) + filterObj.uploaders.push(uploader) + else + filterObj.excludeUploaders.push(uploader) + + delete filterObj.queries.user + delete filterObj.queries.exclude.user + } + + // Parse orderby keys + if (filterObj.queries.orderby) { + for (const obQuery of filterObj.queries.orderby) { + const tmp = obQuery.toLowerCase().split(':') + + let column = orderByObj.maps[tmp[0]] || tmp[0] + let direction = 'asc' + + if (orderByObj.casts[column]) + column = `cast (\`${column}\` as ${orderByObj.casts[column]})` + if (tmp[1] && /^d/.test(tmp[1])) + direction = 'desc' + + const suffix = orderByObj.nullsLast.includes(column) ? ' nulls last' : '' + orderByObj.parsed.push(`${column} ${direction}${suffix}`) + } + + delete filterObj.queries.orderby + } + + // For some reason, single value won't be in Array even with 'alwaysArray' option + if (typeof filterObj.queries.exclude.text === 'string') + filterObj.queries.exclude.text = [filterObj.queries.exclude.text] + } function filter () { if (req.params.id !== undefined) @@ -853,23 +932,53 @@ self.list = async (req, res) => { else if (!all) this.where('userid', user.id) else - // Fisrt, look for uploads matching ANY of the supplied 'user' OR 'ip' filters - // Then, refine the matches using the supplied 'name' filters + // Sheesh, these look too overbearing... this.where(function () { - if (_filters.uploaders.length) - this.orWhereIn('userid', _filters.uploaders.map(v => v.id)) - if (_filters.ips.length) - this.orWhereIn('ip', _filters.ips) - if (_filters.flags.nouser) + // Filter uploads matching any of the supplied 'user' keys and/or NULL flag + if (filterObj.uploaders.length) + this.orWhereIn('userid', filterObj.uploaders.map(v => v.id)) + if (filterObj.excludeUploaders.length) + this.orWhereNotIn('userid', filterObj.excludeUploaders.map(v => v.id)) + if (filterObj.flags.nouser) this.orWhereNull('userid') - if (_filters.flags.noip) + }).orWhere(function () { + // Filter uploads matching any of the supplied 'ip' keys and/or NULL flag + if (filterObj.queries.ip) + this.orWhereIn('ip', filterObj.queries.ip) + if (filterObj.queries.exclude.ip) + this.orWhereNotIn('ip', filterObj.queries.exclude.ip) + if (filterObj.flags.noip) this.orWhereNull('ip') }).andWhere(function () { - for (const name of _filters.names) + // Then, refine using the supplied 'date' and/or 'expiry' ranges + if (filterObj.queries.date) + if (typeof filterObj.queries.date.to === 'number') + this.andWhereBetween('timestamp', [filterObj.queries.date.from, filterObj.queries.date.to]) + else + this.andWhere('timestamp', '>=', filterObj.queries.date.from) + if (filterObj.queries.expiry) + if (typeof filterObj.queries.expiry.to === 'number') + this.andWhereBetween('expirydate', [filterObj.queries.expiry.from, filterObj.queries.expiry.to]) + else + this.andWhere('expirydate', '>=', filterObj.queries.date.from) + }).andWhere(function () { + // Then, refine using the supplied keywords against their file names + if (!filterObj.queries.text) return + for (const name of filterObj.queries.text) if (name.includes('*')) this.orWhere('name', 'like', name.replace(/\*/g, '%')) else - this.orWhere('name', name) + // If no asterisks, assume partial + this.orWhere('name', 'like', `%${name}%`) + }).andWhere(function () { + // Finally, refine using the supplied exclusions against their file names + if (!filterObj.queries.exclude.text) return + for (const exclude of filterObj.queries.exclude.text) + if (exclude.includes('*')) + this.orWhere('name', 'not like', exclude.replace(/\*/g, '%')) + else + // If no asterisks, assume partial + this.orWhere('name', 'not like', `%${exclude}%`) }) } @@ -886,16 +995,18 @@ self.list = async (req, res) => { if (offset === undefined) offset = 0 const columns = ['id', 'name', 'userid', 'size', 'timestamp'] - if (temporaryUploads) columns.push('expirydate') // Only select IPs if we are listing all uploads columns.push(all ? 'ip' : 'albumid') + const orderByRaw = orderByObj.parsed.length + ? orderByObj.parsed.join(', ') + : '`id` desc' const files = await db.table('files') .where(filter) - .orderByRaw(_orderBy.length ? _orderBy.join(', ') : '`id` desc') + .orderByRaw(orderByRaw) .limit(25) .offset(25 * offset) .select(columns) @@ -923,7 +1034,7 @@ self.list = async (req, res) => { .where('userid', user.id) .select('id', 'name') .then(rows => { - // Build Object indexed by their IDs + // Build Object indexed by their IDs const obj = {} for (const row of rows) obj[row.id] = row.name @@ -936,8 +1047,8 @@ self.list = async (req, res) => { return res.json({ success: true, files, count, albums, basedomain }) // Otherwise proceed to querying usernames - let _users = _filters.uploaders - if (!_users.length) { + let usersTable = filterObj.uploaders + if (!usersTable.length) { const userids = files .map(file => file.userid) .filter((v, i, a) => { @@ -949,13 +1060,13 @@ self.list = async (req, res) => { return res.json({ success: true, files, count, basedomain }) // Query usernames of user IDs from currently selected files - _users = await db.table('users') + usersTable = await db.table('users') .whereIn('id', userids) .select('id', 'username') } const users = {} - for (const user of _users) + for (const user of usersTable) users[user.id] = user.username return res.json({ success: true, files, count, users, basedomain }) diff --git a/controllers/utilsController.js b/controllers/utilsController.js index 0e9a760..be4fd03 100644 --- a/controllers/utilsController.js +++ b/controllers/utilsController.js @@ -31,7 +31,8 @@ const self = { ffprobe: promisify(ffmpeg.ffprobe), - albumsCache: {} + albumsCache: {}, + timezoneOffset: new Date().getTimezoneOffset() } const statsCache = { @@ -106,7 +107,7 @@ self.extname = filename => { return extname + multi } -self.escape = (string) => { +self.escape = string => { // MIT License // Copyright(c) 2012-2013 TJ Holowaychuk // Copyright(c) 2015 Andreas Lubbe diff --git a/dist/js/dashboard.js b/dist/js/dashboard.js index 634e610..bdb32ea 100644 --- a/dist/js/dashboard.js +++ b/dist/js/dashboard.js @@ -1,2 +1,2 @@ -var lsKeys={token:"token",viewType:{uploads:"viewTypeUploads",uploadsAll:"viewTypeUploadsAll"},selected:{uploads:"selectedUploads",uploadsAll:"selectedUploadsAll",users:"selectedUsers"}},page={dom:null,token:localStorage[lsKeys.token],username:null,permissions:null,menusContainer:null,menus:[],currentView:null,views:{uploads:{type:localStorage[lsKeys.viewType.uploads],album:null,pageNum:null},uploadsAll:{type:localStorage[lsKeys.viewType.uploadsAll],filters:null,pageNum:null,all:!0},users:{filters:null,pageNum:null}},selected:{uploads:[],uploadsAll:[],users:[]},checkboxes:{uploads:[],uploadsAll:[],users:[]},lastSelected:{upload:null,uploadsAll:null,user:null},selectAlbumContainer:null,cache:{uploads:{},albums:{},users:{}},clipboardJS:null,lazyLoad:null,imageExts:[".webp",".jpg",".jpeg",".gif",".png",".tiff",".tif",".svg"],videoExts:[".webm",".mp4",".wmv",".avi",".mov",".mkv"],isTriggerLoading:null,fadingIn:null,albumTitleMaxLength:70,albumDescMaxLength:4e3,unhide:function(){document.querySelector("#loader").classList.add("is-hidden"),document.querySelector("#dashboard").classList.remove("is-hidden")},onError:function(e){console.error(e);var a=document.createElement("div");return a.innerHTML=""+e.toString()+"",swal({title:"An error occurred!",icon:"error",content:a})},onAxiosError:function(e){console.error(e);var a={520:"Unknown Error",521:"Web Server Is Down",522:"Connection Timed Out",523:"Origin Is Unreachable",524:"A Timeout Occurred",525:"SSL Handshake Failed",526:"Invalid SSL Certificate",527:"Railgun Error",530:"Origin DNS Error"}[e.response.status]||e.response.statusText,t=e.response.data&&e.response.data.description?e.response.data.description:"There was an error with the request, please check the console for more information.";return swal(e.response.status+" "+a,t,"error")},preparePage:function(){page.token?page.verifyToken(page.token,!0):window.location="auth"},verifyToken:function(e,a){axios.post("api/tokens/verify",{token:e}).then((function(t){if(!1===t.data.success)return swal({title:"An error occurred!",text:t.data.description,icon:"error"}).then((function(){a&&(localStorage.removeItem(lsKeys.token),window.location="auth")}));axios.defaults.headers.common.token=e,localStorage[lsKeys.token]=e,page.token=e,page.username=t.data.username,page.permissions=t.data.permissions,page.prepareDashboard()})).catch(page.onAxiosError)},prepareDashboard:function(){page.dom=document.querySelector("#page"),page.dom.addEventListener("click",page.domClick,!0),page.dom.addEventListener("submit",(function(e){if(e.target&&e.target.classList.contains("prevent-default"))return e.preventDefault()}),!0),page.menusContainer=document.querySelector("#menu");for(var e=[{selector:"#itemUploads",onclick:page.getUploads},{selector:"#itemDeleteUploadsByNames",onclick:page.deleteUploadsByNames},{selector:"#itemManageAlbums",onclick:page.getAlbums},{selector:"#itemManageToken",onclick:page.changeToken},{selector:"#itemChangePassword",onclick:page.changePassword},{selector:"#itemLogout",onclick:page.logout},{selector:"#itemManageUploads",onclick:page.getUploads,params:{all:!0},group:"moderator"},{selector:"#itemStatistics",onclick:page.getStatistics,group:"admin"},{selector:"#itemManageUsers",onclick:page.getUsers,group:"admin"}],a=function(a){if(!e[a].group||page.permissions[e[a].group]){var t=document.querySelector(e[a].selector);t.addEventListener("click",(function(t){page.menusContainer.classList.contains("is-loading")||e[a].onclick.call(null,Object.assign({trigger:t.currentTarget},e[a].params||{}))})),t.classList.remove("is-hidden"),page.menus.push(t)}},t=0;t';e.all&&(o='\n
\n
\n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n
\n
\n ');for(var c='\n
\n '+o+'\n
\n
\n
\n
\n \n
\n
\n \n
\n
\n
\n
\n
\n ',d='\n
\n
\n \n \n
\n ',u=!1,p=n.some((function(e){return void 0!==e.expirydate})),g=0;g\n \n '+r+"\n ";for(var h=document.querySelector("#table"),v=0;v'+f.name+'':w.innerHTML='

'+(f.extname||"N/A")+"

",w.innerHTML+='\n \n
\n '+(f.thumb?'\n \n \n \n \n ':"")+'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n
\n

'+f.name+"

\n

"+(f.appendix?""+f.appendix+" – ":"")+f.prettyBytes+"

\n "+(p&&f.prettyExpiryDate?'\n

EXP: '+f.prettyExpiryDate+"

":"")+"\n
\n ",h.appendChild(w),page.checkboxes[page.currentView]=h.querySelectorAll('.checkbox[data-action="select"]')}}else{page.dom.innerHTML="\n "+r+"\n "+c+"\n "+d+'\n
\n \n \n \n \n \n '+(void 0===e.album?"":"")+"\n \n "+(e.all?"":"")+"\n \n "+(p?"":"")+'\n \n \n \n \n \n
File"+(e.all?"User":"Album")+"SizeIPDateExpiry date
\n
\n '+r+"\n ";for(var y=document.querySelector("#table"),k=0;k\n '+x.name+"\n "+(void 0===e.album?""+x.appendix+"":"")+"\n "+x.prettyBytes+"\n "+(e.all?""+(x.ip||"")+"":"")+"\n "+x.prettyDate+"\n "+(p?""+(x.prettyExpiryDate||"-")+"":"")+'\n \n \n \n \n \n \n \n \n \n \n \n '+(e.all?"":'\n \n \n \n \n ')+'\n \n \n \n \n \n \n ',y.appendChild(T),page.checkboxes[page.currentView]=y.querySelectorAll('.checkbox[data-action="select"]')}}var A=document.querySelector("#selectAll");A&&!u&&n.length&&(A.checked=!0,A.title="Unselect all"),"thumbs"===page.views[page.currentView].type?(page.fadeAndScroll(!0),page.lazyLoad.update()):page.fadeAndScroll(),page.updateTrigger(e.trigger,"active"),"uploads"===page.currentView&&(page.views.uploads.album=e.album),"uploadsAll"===page.currentView&&(page.views.uploadsAll.filters=e.filters),page.views[page.currentView].pageNum=n.length?e.pageNum:0})).catch((function(a){page.updateTrigger(e.trigger),page.onAxiosError(a)}))},setUploadsView:function(e,a){localStorage[lsKeys.viewType[page.currentView]]=e,page.views[page.currentView].type=e,page.getUploads(Object.assign({trigger:a},page.views[page.currentView]))},displayPreview:function(e){var a=page.cache.uploads[e];if(a.thumb){var t=document.createElement("div");if(t.innerHTML='\n
\n \n
\n \n
\n
\n ',a.original){var n=/.[\w]+(\?|$)/.exec(a.original),s=n&&n[0]?n[0].toLowerCase():null,i=page.imageExts.includes(s),l=!i&&page.videoExts.includes(s);(i||l)&&(t.innerHTML+='\n \n ',t.querySelector("#swalOriginal").addEventListener("click",(function(e){var n=e.currentTarget;if(!n.classList.contains("is-danger")){n.classList.add("is-loading");var s=t.querySelector("#swalThumb");if(i)s.src=a.original,s.onload=function(){n.classList.add("is-hidden"),document.body.querySelector(".swal-overlay .swal-modal:not(.is-expanded)").classList.add("is-expanded")},s.onerror=function(e){e.currentTarget.classList.add("is-hidden"),n.className="button is-danger is-fullwidth",n.innerHTML='\n \n \n \n Unable to load original\n '};else if(l){s.classList.add("is-hidden");var r=document.createElement("video");r.id="swalVideo",r.controls=!0,r.autoplay=!0,r.src=a.original,s.insertAdjacentElement("afterend",r),n.classList.add("is-hidden"),document.body.querySelector(".swal-overlay .swal-modal:not(.is-expanded)").classList.add("is-expanded")}}})))}return swal({content:t,buttons:!1}).then((function(){var e=t.querySelector("#swalVideo");e&&e.remove(),document.body.querySelector(".swal-overlay .swal-modal").classList.remove("is-expanded")}))}},selectAll:function(e){for(var a=0;an&&s>n&&st&&s"),swal({content:a})},filterUploads:function(e){var a=document.querySelector("#filters").value.trim();page.getUploads({all:!0,filters:a},e)},viewUserUploads:function(e,a){var t=page.cache.users[e];t&&(a.classList.add("is-loading"),page.getUploads({all:!0,filters:"user:"+t.username.replace(/ /g,"\\ "),trigger:document.querySelector("#itemManageUploads")}))},deleteUpload:function(e){page.postBulkDeleteUploads({all:"uploadsAll"===page.currentView,field:"id",values:[e],cb:function(a){!a.length&&page.selected[page.currentView].includes(e)&&page.selected[page.currentView].splice(page.selected[page.currentView].indexOf(e),1),page.selected[page.currentView].length?localStorage[lsKeys.selected[page.currentView]]=JSON.stringify(page.selected[page.currentView]):delete localStorage[lsKeys.selected[page.currentView]],page.getUploads(Object.assign({autoPage:!0},page.views[page.currentView]))}})},bulkDeleteUploads:function(){if(!page.selected[page.currentView].length)return swal("An error occurred!","You have not selected any uploads.","error");page.postBulkDeleteUploads({all:"uploadsAll"===page.currentView,field:"id",values:page.selected[page.currentView],cb:function(e){e.length?page.selected[page.currentView]=page.selected[page.currentView].filter((function(a){return e.includes(a)})):page.selected[page.currentView]=[],page.selected[page.currentView].length?localStorage[lsKeys.selected[page.currentView]]=JSON.stringify(page.selected[page.currentView]):delete localStorage[lsKeys.selected[page.currentView]],page.getUploads(Object.assign({autoPage:!0},page.views[page.currentView]))}})},deleteUploadsByNames:function(e){void 0===e&&(e={});var a="";page.permissions.moderator&&(a="
Hint: You can use this feature to delete uploads by other users."),page.dom.innerHTML='\n
\n
\n \n
\n \n
\n

Separate each entry with a new line.'+a+'

\n
\n
\n
\n \n
\n
\n
\n ',page.fadeAndScroll(),page.updateTrigger(e.trigger,"active"),document.querySelector("#submitBulkDelete").addEventListener("click",(function(){var e=document.querySelector("#bulkDeleteNames"),a={},t=e.value.split(/\r?\n/).map((function(e){var a=e.trim();return/^[^\s]+$/.test(a)?a:""})).filter((function(e){return!(!e||Object.prototype.hasOwnProperty.call(a,e))&&(a[e]=!0)}));if(e.value=t.join("\n"),!t.length)return swal("An error occurred!","You have not entered any upload names.","error");page.postBulkDeleteUploads({all:!0,field:"name",values:t,cb:function(a){e.value=a.join("\n")}})}))},postBulkDeleteUploads:function(e){void 0===e&&(e={});var a=e.values.length,t=e.values.length+" upload"+(1===a?"":"s"),n="

You won't be able to recover "+t.replace(/^(\d*)(.*)/,"$1$2")+"!

";e.all&&(n+="\n

Warning: You may be nuking "+(1===a?"an upload":"some uploads")+" by "+(1===a?"another user":"other users")+"!

");var s=document.createElement("div");s.innerHTML=n,swal({title:"Are you sure?",content:s,icon:"warning",dangerMode:!0,buttons:{cancel:!0,confirm:{text:"Yes, nuke "+(1===e.values.length?"it":"them")+"!",closeModal:!1}}}).then((function(n){n&&axios.post("api/upload/bulkdelete",{field:e.fields,values:e.values}).then((function(n){if(n){if(!1===n.data.success)return"No token provided"===n.data.description?page.verifyToken(page.token):swal("An error occurred!",n.data.description,"error");var s=Array.isArray(n.data.failed)?n.data.failed:[];s.length===e.values.length?swal("An error occurred!","Unable to delete any of the "+t+".","error"):s.length&&s.length\n

You are about to add '+t+" upload"+(1===t?"":"s")+' to an album.

\n

If an upload is already in an album, it will be moved.

\n \n
\n
\n
\n \n
\n
\n
\n ',swal({icon:"warning",content:n,buttons:{cancel:!0,confirm:{text:"OK",closeModal:!1}}}).then((function(t){if(t){var n=parseInt(document.querySelector("#swalAlbum").value);if(isNaN(n))return swal("An error occurred!","You did not choose an album.","error");axios.post("api/albums/addfiles",{ids:e,albumid:n}).then((function(t){if(t)if(!1!==t.data.success){var s=e.length;t.data.failed&&t.data.failed.length&&(s-=t.data.failed.length);var i="upload"+(1===e.length?"":"s");if(!s)return swal("An error occurred!","Could not add the "+i+" to the album.","error");swal("Woohoo!","Successfully "+(n<0?"removed":"added")+" "+s+" "+i+" "+(n<0?"from":"to")+" the album.","success",{buttons:!1,timer:1500}),a(t.data.failed)}else"No token provided"===t.data.description?page.verifyToken(page.token):swal("An error occurred!",t.data.description,"error")})).catch(page.onAxiosError)}})),axios.get("api/albums").then((function(e){if(!1!==e.data.success){var a=document.querySelector("#swalAlbum");a&&(a.innerHTML+=e.data.albums.map((function(e){return'"})).join("\n"),a.getElementsByTagName("option")[1].innerHTML="Choose an album",a.removeAttribute("disabled"))}else"No token provided"===e.data.description?page.verifyToken(page.token):swal("An error occurred!",e.data.description,"error")})).catch(page.onAxiosError)},getAlbums:function(e){void 0===e&&(e={}),page.updateTrigger(e.trigger,"loading"),axios.get("api/albums").then((function(a){if(a){if(!1===a.data.success)return"No token provided"===a.data.description?page.verifyToken(page.token):(page.updateTrigger(e.trigger),swal("An error occurred!",a.data.description,"error"));page.cache.albums={},page.dom.innerHTML='\n

Create new album

\n
\n
\n
\n \n
\n

Max length is '+page.albumTitleMaxLength+' characters.

\n
\n
\n
\n \n
\n

Max length is '+page.albumDescMaxLength+' characters.

\n
\n
\n
\n \n
\n
\n
\n
\n

List of albums

\n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n
IDNameFilesCreated atPublic link
\n
\n ';for(var t=a.data.homeDomain,n=document.querySelector("#table"),s=0;s"+i.id+"\n "+i.name+"\n "+i.files+"\n "+i.prettyDate+"\n '+l+'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ',n.appendChild(r)}page.fadeAndScroll(),page.updateTrigger(e.trigger,"active")}})).catch((function(a){page.updateTrigger(e.trigger),page.onAxiosError(a)}))},editAlbum:function(e){var a=page.cache.albums[e];if(a){var t=document.createElement("div");t.innerHTML='\n
\n
\n \n
\n

Max length is '+page.albumTitleMaxLength+' characters.

\n
\n
\n
\n \n
\n

Max length is '+page.albumDescMaxLength+' characters.

\n
\n
\n
\n \n
\n
\n
\n
\n \n
\n
\n
\n
\n \n
\n
\n ',swal({title:"Edit album",icon:"info",content:t,buttons:{cancel:!0,confirm:{closeModal:!1}}}).then((function(t){t&&axios.post("api/albums/edit",{id:e,name:document.querySelector("#swalName").value.trim(),description:document.querySelector("#swalDescription").value.trim(),download:document.querySelector("#swalDownload").checked,public:document.querySelector("#swalPublic").checked,requestLink:document.querySelector("#swalRequestLink").checked}).then((function(e){if(e){if(!1===e.data.success)return"No token provided"===e.data.description?page.verifyToken(page.token):swal("An error occurred!",e.data.description,"error");e.data.identifier?swal("Success!","Your album's new identifier is: "+e.data.identifier+".","success"):e.data.name!==a.name?swal("Success!","Your album was renamed to: "+e.data.name+".","success"):swal("Success!","Your album was edited!","success",{buttons:!1,timer:1500}),page.getAlbumsSidebar(),page.getAlbums()}})).catch(page.onAxiosError)}))}},deleteAlbum:function(e){swal({title:"Are you sure?",text:"This won't delete your uploads, only the album!",icon:"warning",dangerMode:!0,buttons:{cancel:!0,confirm:{text:"Yes, delete it!",closeModal:!1},purge:{text:"Umm, delete the uploads too please?",value:"purge",className:"swal-button--danger",closeModal:!1}}}).then((function(a){a&&axios.post("api/albums/delete",{id:e,purge:"purge"===a}).then((function(e){if(!1===e.data.success){var a=Array.isArray(e.data.failed)?e.data.failed:[];return"No token provided"===e.data.description?page.verifyToken(page.token):a.length?swal("An error occurred!","Unable to delete "+a.length+" of the album's upload"+(1===a.length?"":"s")+".","error"):swal("An error occurred!",e.data.description,"error")}swal("Deleted!","Your album has been deleted.","success",{buttons:!1,timer:1500}),page.getAlbumsSidebar(),page.getAlbums()})).catch(page.onAxiosError)}))},submitAlbum:function(e){page.updateTrigger(e,"loading"),axios.post("api/albums",{name:document.querySelector("#albumName").value.trim(),description:document.querySelector("#albumDescription").value.trim()}).then((function(a){if(a){if(page.updateTrigger(e),!1===a.data.success)return"No token provided"===a.data.description?page.verifyToken(page.token):swal("An error occurred!",a.data.description,"error");swal("Woohoo!","Album was created successfully.","success",{buttons:!1,timer:1500}),page.getAlbumsSidebar(),page.getAlbums()}})).catch((function(a){page.updateTrigger(e),page.onAxiosError(a)}))},getAlbumsSidebar:function(){axios.get("api/albums/sidebar").then((function(e){if(e){if(!1===e.data.success)return"No token provided"===e.data.description?page.verifyToken(page.token):swal("An error occurred!",e.data.description,"error");var a=document.querySelector("#albumsContainer"),t=a.querySelectorAll("li > a");if(t.length){for(var n=0;n\n \n
\n
\n \n
\n
\n \n \n ',page.fadeAndScroll(),page.updateTrigger(e.trigger,"active"),document.querySelector("#getNewToken").addEventListener("click",(function(e){var a=e.currentTarget;page.updateTrigger(a,"loading"),axios.post("api/tokens/change").then((function(e){if(!1===e.data.success)return"No token provided"===e.data.description?page.verifyToken(page.token):(page.updateTrigger(a),swal("An error occurred!",e.data.description,"error"));page.updateTrigger(a),swal({title:"Woohoo!",text:"Your token was successfully changed.",icon:"success"}).then((function(){axios.defaults.headers.common.token=e.data.token,localStorage[lsKeys.token]=e.data.token,page.token=e.data.token,page.changeToken()}))})).catch((function(e){page.updateTrigger(a),page.onAxiosError(e)}))}))},changePassword:function(e){void 0===e&&(e={}),page.dom.innerHTML='\n
\n
\n \n
\n \n
\n
\n
\n \n
\n \n
\n
\n
\n
\n \n
\n
\n
\n ',page.fadeAndScroll(),page.updateTrigger(e.trigger,"active"),document.querySelector("#sendChangePassword").addEventListener("click",(function(e){page.dom.querySelector("form").checkValidity()&&(document.querySelector("#password").value===document.querySelector("#passwordConfirm").value?page.sendNewPassword(document.querySelector("#password").value,e.currentTarget):swal({title:"Password mismatch!",text:"Your passwords do not match, please try again.",icon:"error"}))}))},sendNewPassword:function(e,a){page.updateTrigger(a,"loading"),axios.post("api/password/change",{password:e}).then((function(e){if(!1===e.data.success)return"No token provided"===e.data.description?page.verifyToken(page.token):(page.updateTrigger(a),swal("An error occurred!",e.data.description,"error"));page.updateTrigger(a),swal({title:"Woohoo!",text:"Your password was successfully changed.",icon:"success",buttons:!1,timer:1500}).then((function(){page.changePassword()}))})).catch((function(e){page.updateTrigger(a),page.onAxiosError(e)}))},getUsers:function(e){if(void 0===e&&(e={}),page.updateTrigger(e.trigger,"loading"),void 0===e.pageNum&&(e.pageNum=0),!page.permissions.admin)return swal("An error occurred!","You can not do this!","error");var a="api/users/"+e.pageNum;axios.get(a).then((function(a){if(!1===a.data.success)return"No token provided"===a.data.description?page.verifyToken(page.token):(page.updateTrigger(e.trigger),swal("An error occurred!",a.data.description,"error"));var t=Math.ceil(a.data.count/25);if(e.pageNum&&0===a.data.users.length)return e.autoPage?(e.pageNum=t-1,page.getUsers(e)):(page.updateTrigger(e.trigger),swal("An error occurred!","There are no more users to populate page "+(e.pageNum+1)+".","error"));page.currentView="users",page.cache.users={};var n=page.paginate(a.data.count,25,e.pageNum),s='\n
\n '+('\n
\n
\n
\n
\n \n
\n
\n \n
\n
\n \n
\n
\n
\n
\n ')+'\n
\n
\n
\n
\n \n
\n
\n \n
\n
\n
\n
\n
\n ',i=!1;page.dom.innerHTML="\n "+n+"\n "+s+'\n \n \n \n
\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
IDUsernameUploadsUsageGroup
\n
\n '+n+"\n ";for(var l=document.querySelector("#table"),r=0;r\n "+o.id+"\n "+o.username+"\n "+o.uploads+"\n "+page.getPrettyBytes(o.usage)+"\n "+d+'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ',l.appendChild(m),page.checkboxes.users=l.querySelectorAll('.checkbox[data-action="select"]')}var b=document.querySelector("#selectAll");b&&!i&&(b.checked=!0,b.title="Unselect all"),page.fadeAndScroll(),page.updateTrigger(e.trigger,"active"),page.views.users.pageNum=a.data.users.length?e.pageNum:0})).catch((function(a){page.updateTrigger(e.trigger),page.onAxiosError(a)}))},createUser:function(){var e=Object.keys(page.permissions).map((function(e,a,t){return'"})).join("\n"),a=document.createElement("div");a.innerHTML='\n
\n \n
\n \n
\n
\n
\n \n
\n \n
\n
\n
\n \n
\n
\n \n
\n
\n
\n ",swal({title:"Create new user",icon:"info",content:a,buttons:{cancel:!0,confirm:{closeModal:!1}}}).then((function(e){e&&axios.post("api/users/create",{username:document.querySelector("#swalUsername").value,password:document.querySelector("#swalPassword").value,group:document.querySelector("#swalGroup").value}).then((function(e){if(e){if(!1===e.data.success)return"No token provided"===e.data.description?page.verifyToken(page.token):swal("An error occurred!",e.data.description,"error");var a=document.createElement("div");a.innerHTML="\n

Username: "+e.data.username+"

\n

Password: "+e.data.password+"

\n

User group: "+e.data.group+"

\n ",swal({title:"Created a new user!",icon:"success",content:a}),page.getUsers(page.views.users)}})).catch(page.onAxiosError)}))},editUser:function(e){var a=page.cache.users[e];if(a){var t=Object.keys(page.permissions).map((function(e,t,n){return'"})).join("\n"),n=document.createElement("div");n.innerHTML='\n
\n \n
\n \n
\n
\n
\n \n
\n
\n \n
\n
\n
\n
\n
\n \n
\n
\n
\n
\n \n
\n
\n ',swal({title:"Edit user",icon:"info",content:n,buttons:{cancel:!0,confirm:{closeModal:!1}}}).then((function(t){t&&axios.post("api/users/edit",{id:e,username:document.querySelector("#swalUsername").value,group:document.querySelector("#swalGroup").value,enabled:document.querySelector("#swalEnabled").checked,resetPassword:document.querySelector("#swalResetPassword").checked}).then((function(e){if(e){if(!1===e.data.success)return"No token provided"===e.data.description?page.verifyToken(page.token):swal("An error occurred!",e.data.description,"error");if(e.data.password){var t=document.createElement("div");t.innerHTML="\n

"+a.username+"'s new password is:

\n

"+e.data.password+"

\n ",swal({title:"Success!",icon:"success",content:t})}else e.data.update&&e.data.update.username!==a.username?swal("Success!",a.username+" was renamed into: "+e.data.update.username+".","success"):swal("Success!","The user was edited!","success",{buttons:!1,timer:1500});page.getUsers(page.views.users)}})).catch(page.onAxiosError)}))}},disableUser:function(e){var a=page.cache.users[e];if(a&&a.enabled){var t=document.createElement("div");t.innerHTML="\n

You will be disabling a user named "+page.cache.users[e].username+".

\n

Their files will remain.

\n ",swal({title:"Are you sure?",icon:"warning",content:t,dangerMode:!0,buttons:{cancel:!0,confirm:{text:"Yes, disable them!",closeModal:!1}}}).then((function(a){a&&axios.post("api/users/disable",{id:e}).then((function(a){if(a){if(!1===a.data.success)return"No token provided"===a.data.description?page.verifyToken(page.token):swal("An error occurred!",a.data.description,"error");swal("Success!",page.cache.users[e].username+" has been disabled.","success",{buttons:!1,timer:1500}),page.getUsers(page.views.users)}})).catch(page.onAxiosError)}))}},deleteUser:function(e){if(page.cache.users[e]){var a=document.createElement("div");a.innerHTML="\n

You will be deleting a user named "+page.cache.users[e].username+".

\n

Their files will remain, unless you choose otherwise.

\n ",swal({title:"Are you sure?",icon:"warning",content:a,dangerMode:!0,buttons:{cancel:!0,confirm:{text:"Yes, delete it!",closeModal:!1},purge:{text:"Yes, and the uploads too!",value:"purge",className:"swal-button--danger",closeModal:!1}}}).then((function(a){a&&axios.post("api/users/delete",{id:e,purge:"purge"===a}).then((function(a){if(a){if(!1===a.data.success){var t=Array.isArray(a.data.failed)?a.data.failed:[];return"No token provided"===a.data.description?page.verifyToken(page.token):t.length?swal("An error occurred!","Unable to delete "+t.length+" of the user's upload"+(1===t.length?"":"s")+".","error"):swal("An error occurred!",a.data.description,"error")}swal("Success!",page.cache.users[e].username+" has been deleted.","success",{buttons:!1,timer:1500}),page.getUsers(Object.assign({autoPage:!0},page.views.users))}})).catch(page.onAxiosError)}))}},paginate:function(e,a,t){t+=1;var n=Math.ceil(e/a),s="",i=function(e,a){for(var n=e;n<=a;++n)s+='
  • '+n+"
  • "},l=function(){s+='\n
  • 1
  • \n
  • \n '},r=function(){s+='\n
  • \n
  • '+n+"
  • \n "};return 7>=n?i(1,n):t<6?(i(1,6),r()):t>n-6+1?(l(),i(n-6+1,n)):(l(),i(t-3+1,t+3-1),r()),'\n \n "},getStatistics:function(e){if(void 0===e&&(e={}),!page.permissions.admin)return swal("An error occurred!","You can not do this!","error");page.updateTrigger(e.trigger,"loading");axios.get("api/stats").then((function(a){if(!1===a.data.success)return"No token provided"===a.data.description?page.verifyToken(page.token):(page.updateTrigger(e.trigger),swal("An error occurred!",a.data.description,"error"));for(var t="",n=Object.keys(a.data.stats),s=0;s\n "+d+"\n \n "}}catch(e){i="\n \n Error parsing response. Try again?\n \n \n ",page.onError(e)}else i+="\n \n Generating, please try again later…\n \n \n ";t+='\n
    \n \n \n \n \n \n \n \n \n "+i+"\n \n
    '+n[s].toUpperCase()+"
    \n
    \n "}page.dom.innerHTML=t,page.fadeAndScroll(),page.updateTrigger(e.trigger,"active")})).catch((function(a){page.updateTrigger(e.trigger),page.onAxiosError(a)}))}};window.onload=function(){"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,a){"use strict";var t=arguments;if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var n=Object(e),s=1;s",swal({title:"An error occurred!",icon:"error",content:a})},onAxiosError:function(e){console.error(e);var a={520:"Unknown Error",521:"Web Server Is Down",522:"Connection Timed Out",523:"Origin Is Unreachable",524:"A Timeout Occurred",525:"SSL Handshake Failed",526:"Invalid SSL Certificate",527:"Railgun Error",530:"Origin DNS Error"}[e.response.status]||e.response.statusText,n=e.response.data&&e.response.data.description?e.response.data.description:"There was an error with the request, please check the console for more information.";return swal(e.response.status+" "+a,n,"error")},preparePage:function(){page.token?page.verifyToken(page.token,!0):window.location="auth"},verifyToken:function(e,a){axios.post("api/tokens/verify",{token:e}).then((function(n){if(!1===n.data.success)return swal({title:"An error occurred!",text:n.data.description,icon:"error"}).then((function(){a&&(localStorage.removeItem(lsKeys.token),window.location="auth")}));axios.defaults.headers.common.token=e,localStorage[lsKeys.token]=e,page.token=e,page.username=n.data.username,page.permissions=n.data.permissions,page.prepareDashboard()})).catch(page.onAxiosError)},prepareDashboard:function(){page.dom=document.querySelector("#page"),page.dom.addEventListener("click",page.domClick,!0),page.dom.addEventListener("submit",(function(e){if(e.target&&e.target.classList.contains("prevent-default"))return e.preventDefault()}),!0),page.menusContainer=document.querySelector("#menu");for(var e=[{selector:"#itemUploads",onclick:page.getUploads},{selector:"#itemDeleteUploadsByNames",onclick:page.deleteUploadsByNames},{selector:"#itemManageAlbums",onclick:page.getAlbums},{selector:"#itemManageToken",onclick:page.changeToken},{selector:"#itemChangePassword",onclick:page.changePassword},{selector:"#itemLogout",onclick:page.logout},{selector:"#itemManageUploads",onclick:page.getUploads,params:{all:!0},group:"moderator"},{selector:"#itemStatistics",onclick:page.getStatistics,group:"admin"},{selector:"#itemManageUsers",onclick:page.getUsers,group:"admin"}],a=function(a){if(!e[a].group||page.permissions[e[a].group]){var n=document.querySelector(e[a].selector);n.addEventListener("click",(function(n){page.menusContainer.classList.contains("is-loading")||e[a].onclick.call(null,Object.assign({trigger:n.currentTarget},e[a].params||{}))})),n.classList.remove("is-hidden"),page.menus.push(n)}},n=0;n';e.all&&(o='\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n ');for(var c='\n
    \n '+o+'\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n ',d='\n
    \n
    \n \n \n
    \n ',u=!1,p=t.some((function(e){return void 0!==e.expirydate})),g=0;g\n \n '+r+"\n ";for(var h=document.querySelector("#table"),v=0;v'+f.name+'':w.innerHTML='

    '+(f.extname||"N/A")+"

    ",w.innerHTML+='\n \n
    \n '+(f.thumb?'\n \n \n \n \n ':"")+'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    \n
    \n

    '+f.name+"

    \n

    "+(f.appendix?""+f.appendix+" – ":"")+f.prettyBytes+"

    \n "+(p&&f.prettyExpiryDate?'\n

    EXP: '+f.prettyExpiryDate+"

    ":"")+"\n
    \n ",h.appendChild(w),page.checkboxes[page.currentView]=h.querySelectorAll('.checkbox[data-action="select"]')}}else{page.dom.innerHTML="\n "+r+"\n "+c+"\n "+d+'\n
    \n \n \n \n \n \n '+(void 0===e.album?"":"")+"\n \n "+(e.all?"":"")+"\n \n "+(p?"":"")+'\n \n \n \n \n \n
    File name"+(e.all?"User":"Album")+"SizeIPDateExpiry date
    \n
    \n '+r+"\n ";for(var y=document.querySelector("#table"),k=0;k\n '+x.name+"\n "+(void 0===e.album?""+x.appendix+"":"")+"\n "+x.prettyBytes+"\n "+(e.all?""+(x.ip||"")+"":"")+"\n "+x.prettyDate+"\n "+(p?""+(x.prettyExpiryDate||"-")+"":"")+'\n \n \n \n \n \n \n \n \n \n \n \n '+(e.all?"":'\n \n \n \n \n ')+'\n \n \n \n \n \n \n ',y.appendChild(T),page.checkboxes[page.currentView]=y.querySelectorAll('.checkbox[data-action="select"]')}}var A=document.querySelector("#selectAll");A&&!u&&t.length&&(A.checked=!0,A.title="Unselect all"),"thumbs"===page.views[page.currentView].type?(page.fadeAndScroll(!0),page.lazyLoad.update()):page.fadeAndScroll(),page.updateTrigger(e.trigger,"active"),"uploads"===page.currentView&&(page.views.uploads.album=e.album),"uploadsAll"===page.currentView&&(page.views.uploadsAll.filters=e.filters),page.views[page.currentView].pageNum=t.length?e.pageNum:0})).catch((function(a){page.updateTrigger(e.trigger),page.onAxiosError(a)}))},setUploadsView:function(e,a){localStorage[lsKeys.viewType[page.currentView]]=e,page.views[page.currentView].type=e,page.getUploads(Object.assign({trigger:a},page.views[page.currentView]))},displayPreview:function(e){var a=page.cache.uploads[e];if(a.thumb){var n=document.createElement("div");if(n.innerHTML='\n
    \n \n
    \n \n
    \n
    \n ',a.original){var t=/.[\w]+(\?|$)/.exec(a.original),s=t&&t[0]?t[0].toLowerCase():null,i=page.imageExts.includes(s),l=!i&&page.videoExts.includes(s);(i||l)&&(n.innerHTML+='\n \n ',n.querySelector("#swalOriginal").addEventListener("click",(function(e){var t=e.currentTarget;if(!t.classList.contains("is-danger")){t.classList.add("is-loading");var s=n.querySelector("#swalThumb");if(i)s.src=a.original,s.onload=function(){t.classList.add("is-hidden"),document.body.querySelector(".swal-overlay .swal-modal:not(.is-expanded)").classList.add("is-expanded")},s.onerror=function(e){e.currentTarget.classList.add("is-hidden"),t.className="button is-danger is-fullwidth",t.innerHTML='\n \n \n \n Unable to load original\n '};else if(l){s.classList.add("is-hidden");var r=document.createElement("video");r.id="swalVideo",r.controls=!0,r.autoplay=!0,r.src=a.original,s.insertAdjacentElement("afterend",r),t.classList.add("is-hidden"),document.body.querySelector(".swal-overlay .swal-modal:not(.is-expanded)").classList.add("is-expanded")}}})))}return swal({content:n,buttons:!1}).then((function(){var e=n.querySelector("#swalVideo");e&&e.remove(),document.body.querySelector(".swal-overlay .swal-modal").classList.remove("is-expanded")}))}},selectAll:function(e){for(var a=0;at&&s>t&&sn&&s2020/01/01 01:23, 2018/01/01 06, 2019/11, 12:34:56.\n These keys can only be specified once each.\n\n Matches can also be sorted with orderby:columnName[:d[escending]] keys.\n This key require internal column names used in the database (id, userid, and so on), but there are 2 shortcuts, namely date for timestamp column and expiry for expirydate column.\n This key can also be specified more than once, where their order will decide the sorting steps.\n\n Any leftover keywords which do not use keys will be matched against the matches\' file names.\n Excluding certain keywords is also supported by adding negation sign (-) before the keywords.\n\n Internals:\n First, it will filter uploads matching ANY of the supplied filter keys AND/OR special filter keys, if any.\n Second, it will refine the matches using the supplied date AND/OR expiry range keys, if any.\n Third, it will refine the matches using the leftover non-keyed keywords, if any.\n Finally, it will sort the matches using the supplied orderby keys, if any.\n\n Examples:\n Uploads from user named "demo":\n user:demo\n Uploads from users named "demo" AND/OR "John Doe" AND/OR non-registered users:\n user:demo user:"John Doe" user:-\n ALL uploads, including from non-registered users, but NOT the ones from user named "demo":\n -user:demo user:-\n Uploads from IP "127.0.0.1" AND which file names match "*.rar" OR "*.zip":\n ip:127.0.0.1 *.rar *.zip\n Uploads uploaded since "1 June 2019 00:00:00":\n date:2019/06\n Uploads uploaded between "7 April 2020 00:00:00" and "7 April 2020 23:59:59":\n date:2020/04/07-2020/04/07 23:59:59\n Uploads which file names match "*.gz" but NOT "*.tar.gz":\n *.gz -*.tar.gz\n Sort matches by "size" column in ascending and descending order respectively:\n user:"John Doe" orderby:size\n *.mp4 user:- orderby:size:d\n\n Friendly reminder: This window can be scrolled up!\n '.trim().replace(/^ {6}/gm,"").replace(/\n/g,"
    "),swal({content:a}).then((function(){document.body.querySelector(".swal-overlay .swal-modal").classList.remove("is-expanded")})),document.body.querySelector(".swal-overlay .swal-modal:not(.is-expanded)").classList.add("is-expanded")},filterUploads:function(e){var a=document.querySelector("#filters").value.trim();page.getUploads({all:!0,filters:a},e)},viewUserUploads:function(e,a){var n=page.cache.users[e];if(n){a.classList.add("is-loading");var t=n.username.includes(" ")?'"'+n.username+'"':n.username;page.getUploads({all:!0,filters:"user:"+t,trigger:document.querySelector("#itemManageUploads")})}},deleteUpload:function(e){page.postBulkDeleteUploads({all:"uploadsAll"===page.currentView,field:"id",values:[e],cb:function(a){!a.length&&page.selected[page.currentView].includes(e)&&page.selected[page.currentView].splice(page.selected[page.currentView].indexOf(e),1),page.selected[page.currentView].length?localStorage[lsKeys.selected[page.currentView]]=JSON.stringify(page.selected[page.currentView]):delete localStorage[lsKeys.selected[page.currentView]],page.getUploads(Object.assign({autoPage:!0},page.views[page.currentView]))}})},bulkDeleteUploads:function(){if(!page.selected[page.currentView].length)return swal("An error occurred!","You have not selected any uploads.","error");page.postBulkDeleteUploads({all:"uploadsAll"===page.currentView,field:"id",values:page.selected[page.currentView],cb:function(e){e.length?page.selected[page.currentView]=page.selected[page.currentView].filter((function(a){return e.includes(a)})):page.selected[page.currentView]=[],page.selected[page.currentView].length?localStorage[lsKeys.selected[page.currentView]]=JSON.stringify(page.selected[page.currentView]):delete localStorage[lsKeys.selected[page.currentView]],page.getUploads(Object.assign({autoPage:!0},page.views[page.currentView]))}})},deleteUploadsByNames:function(e){void 0===e&&(e={});var a="";page.permissions.moderator&&(a="
    Hint: You can use this feature to delete uploads by other users."),page.dom.innerHTML='\n
    \n
    \n \n
    \n \n
    \n

    Separate each entry with a new line.'+a+'

    \n
    \n
    \n
    \n \n
    \n
    \n
    \n ',page.fadeAndScroll(),page.updateTrigger(e.trigger,"active"),document.querySelector("#submitBulkDelete").addEventListener("click",(function(){var e=document.querySelector("#bulkDeleteNames"),a={},n=e.value.split(/\r?\n/).map((function(e){var a=e.trim();return/^[^\s]+$/.test(a)?a:""})).filter((function(e){return!(!e||Object.prototype.hasOwnProperty.call(a,e))&&(a[e]=!0)}));if(e.value=n.join("\n"),!n.length)return swal("An error occurred!","You have not entered any upload names.","error");page.postBulkDeleteUploads({all:!0,field:"name",values:n,cb:function(a){e.value=a.join("\n")}})}))},postBulkDeleteUploads:function(e){void 0===e&&(e={});var a=e.values.length,n=e.values.length+" upload"+(1===a?"":"s"),t="

    You won't be able to recover "+n.replace(/^(\d*)(.*)/,"$1$2")+"!

    ";e.all&&(t+="\n

    Warning: You may be nuking "+(1===a?"an upload":"some uploads")+" by "+(1===a?"another user":"other users")+"!

    ");var s=document.createElement("div");s.innerHTML=t,swal({title:"Are you sure?",content:s,icon:"warning",dangerMode:!0,buttons:{cancel:!0,confirm:{text:"Yes, nuke "+(1===e.values.length?"it":"them")+"!",closeModal:!1}}}).then((function(t){t&&axios.post("api/upload/bulkdelete",{field:e.fields,values:e.values}).then((function(t){if(t){if(!1===t.data.success)return"No token provided"===t.data.description?page.verifyToken(page.token):swal("An error occurred!",t.data.description,"error");var s=Array.isArray(t.data.failed)?t.data.failed:[];s.length===e.values.length?swal("An error occurred!","Unable to delete any of the "+n+".","error"):s.length&&s.length\n

    You are about to add '+n+" upload"+(1===n?"":"s")+' to an album.

    \n

    If an upload is already in an album, it will be moved.

    \n \n
    \n
    \n
    \n \n
    \n
    \n
    \n ',swal({icon:"warning",content:t,buttons:{cancel:!0,confirm:{text:"OK",closeModal:!1}}}).then((function(n){if(n){var t=parseInt(document.querySelector("#swalAlbum").value);if(isNaN(t))return swal("An error occurred!","You did not choose an album.","error");axios.post("api/albums/addfiles",{ids:e,albumid:t}).then((function(n){if(n)if(!1!==n.data.success){var s=e.length;n.data.failed&&n.data.failed.length&&(s-=n.data.failed.length);var i="upload"+(1===e.length?"":"s");if(!s)return swal("An error occurred!","Could not add the "+i+" to the album.","error");swal("Woohoo!","Successfully "+(t<0?"removed":"added")+" "+s+" "+i+" "+(t<0?"from":"to")+" the album.","success",{buttons:!1,timer:1500}),a(n.data.failed)}else"No token provided"===n.data.description?page.verifyToken(page.token):swal("An error occurred!",n.data.description,"error")})).catch(page.onAxiosError)}})),axios.get("api/albums").then((function(e){if(!1!==e.data.success){var a=document.querySelector("#swalAlbum");a&&(a.innerHTML+=e.data.albums.map((function(e){return'"})).join("\n"),a.getElementsByTagName("option")[1].innerHTML="Choose an album",a.removeAttribute("disabled"))}else"No token provided"===e.data.description?page.verifyToken(page.token):swal("An error occurred!",e.data.description,"error")})).catch(page.onAxiosError)},getAlbums:function(e){void 0===e&&(e={}),page.updateTrigger(e.trigger,"loading"),axios.get("api/albums").then((function(a){if(a){if(!1===a.data.success)return"No token provided"===a.data.description?page.verifyToken(page.token):(page.updateTrigger(e.trigger),swal("An error occurred!",a.data.description,"error"));page.cache.albums={},page.dom.innerHTML='\n

    Create new album

    \n
    \n
    \n
    \n \n
    \n

    Max length is '+page.albumTitleMaxLength+' characters.

    \n
    \n
    \n
    \n \n
    \n

    Max length is '+page.albumDescMaxLength+' characters.

    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n

    List of albums

    \n
    \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    IDNameFilesCreated atPublic link
    \n
    \n ';for(var n=a.data.homeDomain,t=document.querySelector("#table"),s=0;s"+i.id+"\n "+i.name+"\n "+i.files+"\n "+i.prettyDate+"\n '+l+'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ',t.appendChild(r)}page.fadeAndScroll(),page.updateTrigger(e.trigger,"active")}})).catch((function(a){page.updateTrigger(e.trigger),page.onAxiosError(a)}))},editAlbum:function(e){var a=page.cache.albums[e];if(a){var n=document.createElement("div");n.innerHTML='\n
    \n
    \n \n
    \n

    Max length is '+page.albumTitleMaxLength+' characters.

    \n
    \n
    \n
    \n \n
    \n

    Max length is '+page.albumDescMaxLength+' characters.

    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n ',swal({title:"Edit album",icon:"info",content:n,buttons:{cancel:!0,confirm:{closeModal:!1}}}).then((function(n){n&&axios.post("api/albums/edit",{id:e,name:document.querySelector("#swalName").value.trim(),description:document.querySelector("#swalDescription").value.trim(),download:document.querySelector("#swalDownload").checked,public:document.querySelector("#swalPublic").checked,requestLink:document.querySelector("#swalRequestLink").checked}).then((function(e){if(e){if(!1===e.data.success)return"No token provided"===e.data.description?page.verifyToken(page.token):swal("An error occurred!",e.data.description,"error");e.data.identifier?swal("Success!","Your album's new identifier is: "+e.data.identifier+".","success"):e.data.name!==a.name?swal("Success!","Your album was renamed to: "+e.data.name+".","success"):swal("Success!","Your album was edited!","success",{buttons:!1,timer:1500}),page.getAlbumsSidebar(),page.getAlbums()}})).catch(page.onAxiosError)}))}},deleteAlbum:function(e){swal({title:"Are you sure?",text:"This won't delete your uploads, only the album!",icon:"warning",dangerMode:!0,buttons:{cancel:!0,confirm:{text:"Yes, delete it!",closeModal:!1},purge:{text:"Umm, delete the uploads too please?",value:"purge",className:"swal-button--danger",closeModal:!1}}}).then((function(a){a&&axios.post("api/albums/delete",{id:e,purge:"purge"===a}).then((function(e){if(!1===e.data.success){var a=Array.isArray(e.data.failed)?e.data.failed:[];return"No token provided"===e.data.description?page.verifyToken(page.token):a.length?swal("An error occurred!","Unable to delete "+a.length+" of the album's upload"+(1===a.length?"":"s")+".","error"):swal("An error occurred!",e.data.description,"error")}swal("Deleted!","Your album has been deleted.","success",{buttons:!1,timer:1500}),page.getAlbumsSidebar(),page.getAlbums()})).catch(page.onAxiosError)}))},submitAlbum:function(e){page.updateTrigger(e,"loading"),axios.post("api/albums",{name:document.querySelector("#albumName").value.trim(),description:document.querySelector("#albumDescription").value.trim()}).then((function(a){if(a){if(page.updateTrigger(e),!1===a.data.success)return"No token provided"===a.data.description?page.verifyToken(page.token):swal("An error occurred!",a.data.description,"error");swal("Woohoo!","Album was created successfully.","success",{buttons:!1,timer:1500}),page.getAlbumsSidebar(),page.getAlbums()}})).catch((function(a){page.updateTrigger(e),page.onAxiosError(a)}))},getAlbumsSidebar:function(){axios.get("api/albums/sidebar").then((function(e){if(e){if(!1===e.data.success)return"No token provided"===e.data.description?page.verifyToken(page.token):swal("An error occurred!",e.data.description,"error");var a=document.querySelector("#albumsContainer"),n=a.querySelectorAll("li > a");if(n.length){for(var t=0;t\n \n
    \n
    \n \n
    \n
    \n \n \n ',page.fadeAndScroll(),page.updateTrigger(e.trigger,"active"),document.querySelector("#getNewToken").addEventListener("click",(function(e){var a=e.currentTarget;page.updateTrigger(a,"loading"),axios.post("api/tokens/change").then((function(e){if(!1===e.data.success)return"No token provided"===e.data.description?page.verifyToken(page.token):(page.updateTrigger(a),swal("An error occurred!",e.data.description,"error"));page.updateTrigger(a),swal({title:"Woohoo!",text:"Your token was successfully changed.",icon:"success",buttons:!1,timer:1500}).then((function(){axios.defaults.headers.common.token=e.data.token,localStorage[lsKeys.token]=e.data.token,page.token=e.data.token,page.changeToken()}))})).catch((function(e){page.updateTrigger(a),page.onAxiosError(e)}))}))},changePassword:function(e){void 0===e&&(e={}),page.dom.innerHTML='\n
    \n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n ',page.fadeAndScroll(),page.updateTrigger(e.trigger,"active"),document.querySelector("#sendChangePassword").addEventListener("click",(function(e){page.dom.querySelector("form").checkValidity()&&(document.querySelector("#password").value===document.querySelector("#passwordConfirm").value?page.sendNewPassword(document.querySelector("#password").value,e.currentTarget):swal({title:"Password mismatch!",text:"Your passwords do not match, please try again.",icon:"error"}))}))},sendNewPassword:function(e,a){page.updateTrigger(a,"loading"),axios.post("api/password/change",{password:e}).then((function(e){if(!1===e.data.success)return"No token provided"===e.data.description?page.verifyToken(page.token):(page.updateTrigger(a),swal("An error occurred!",e.data.description,"error"));page.updateTrigger(a),swal({title:"Woohoo!",text:"Your password was successfully changed.",icon:"success",buttons:!1,timer:1500}).then((function(){page.changePassword()}))})).catch((function(e){page.updateTrigger(a),page.onAxiosError(e)}))},getUsers:function(e){if(void 0===e&&(e={}),page.updateTrigger(e.trigger,"loading"),void 0===e.pageNum&&(e.pageNum=0),!page.permissions.admin)return swal("An error occurred!","You can not do this!","error");var a="api/users/"+e.pageNum;axios.get(a).then((function(a){if(!1===a.data.success)return"No token provided"===a.data.description?page.verifyToken(page.token):(page.updateTrigger(e.trigger),swal("An error occurred!",a.data.description,"error"));var n=Math.ceil(a.data.count/25);if(e.pageNum&&0===a.data.users.length)return e.autoPage?(e.pageNum=n-1,page.getUsers(e)):(page.updateTrigger(e.trigger),swal("An error occurred!","There are no more users to populate page "+(e.pageNum+1)+".","error"));page.currentView="users",page.cache.users={};var t=page.paginate(a.data.count,25,e.pageNum),s='\n
    \n '+('\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n ')+'\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n ',i=!1;page.dom.innerHTML="\n "+t+"\n "+s+'\n \n \n \n
    \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    UsernameUploadsUsageGroup
    \n
    \n '+t+"\n ";for(var l=document.querySelector("#table"),r=0;r\n "+o.username+"\n "+o.uploads+"\n "+page.getPrettyBytes(o.usage)+"\n "+d+'\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ',l.appendChild(m),page.checkboxes.users=l.querySelectorAll('.checkbox[data-action="select"]')}var b=document.querySelector("#selectAll");b&&!i&&(b.checked=!0,b.title="Unselect all"),page.fadeAndScroll(),page.updateTrigger(e.trigger,"active"),page.views.users.pageNum=a.data.users.length?e.pageNum:0})).catch((function(a){page.updateTrigger(e.trigger),page.onAxiosError(a)}))},createUser:function(){var e=Object.keys(page.permissions).map((function(e,a,n){return'"})).join("\n"),a=document.createElement("div");a.innerHTML='\n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n ",swal({title:"Create new user",icon:"info",content:a,buttons:{cancel:!0,confirm:{closeModal:!1}}}).then((function(e){e&&axios.post("api/users/create",{username:document.querySelector("#swalUsername").value,password:document.querySelector("#swalPassword").value,group:document.querySelector("#swalGroup").value}).then((function(e){if(e){if(!1===e.data.success)return"No token provided"===e.data.description?page.verifyToken(page.token):swal("An error occurred!",e.data.description,"error");var a=document.createElement("div");a.innerHTML="\n

    Username: "+e.data.username+"

    \n

    Password: "+e.data.password+"

    \n

    User group: "+e.data.group+"

    \n ",swal({title:"Created a new user!",icon:"success",content:a}),page.getUsers(page.views.users)}})).catch(page.onAxiosError)}))},editUser:function(e){var a=page.cache.users[e];if(a){var n=Object.keys(page.permissions).map((function(e,n,t){return'"})).join("\n"),t=document.createElement("div");t.innerHTML='\n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n ',swal({title:"Edit user",icon:"info",content:t,buttons:{cancel:!0,confirm:{closeModal:!1}}}).then((function(n){n&&axios.post("api/users/edit",{id:e,username:document.querySelector("#swalUsername").value,group:document.querySelector("#swalGroup").value,enabled:document.querySelector("#swalEnabled").checked,resetPassword:document.querySelector("#swalResetPassword").checked}).then((function(e){if(e){if(!1===e.data.success)return"No token provided"===e.data.description?page.verifyToken(page.token):swal("An error occurred!",e.data.description,"error");var n=!0,t=document.createElement("div"),s=a.username;e.data.update.username!==a.username&&(t.innerHTML+="

    "+a.username+" was renamed into: "+e.data.update.username+".

    ",n=!1,s=e.data.update.username),e.data.update.password&&(t.innerHTML+="\n

    "+s+"'s new password is:

    \n

    "+e.data.update.password+"

    \n ",n=!1),e.data.update.enabled!==a.enabled&&(t.innerHTML+="

    "+s+" has been "+(e.data.update.enabled?"enabled":"disabled")+"!

    "),t.innerHTML||(t.innerHTML="

    "+s+" was edited!

    "),swal({title:"Success!",icon:"success",content:t,buttons:!n,timer:n?1500:null}),page.getUsers(page.views.users)}})).catch(page.onAxiosError)}))}},disableUser:function(e){var a=page.cache.users[e];if(a&&a.enabled){var n=document.createElement("div");n.innerHTML="\n

    You will be disabling a user named "+page.cache.users[e].username+".

    \n

    Their files will remain.

    \n ",swal({title:"Are you sure?",icon:"warning",content:n,dangerMode:!0,buttons:{cancel:!0,confirm:{text:"Yes, disable them!",closeModal:!1}}}).then((function(a){a&&axios.post("api/users/disable",{id:e}).then((function(a){if(a){if(!1===a.data.success)return"No token provided"===a.data.description?page.verifyToken(page.token):swal("An error occurred!",a.data.description,"error");swal("Success!",page.cache.users[e].username+" has been disabled.","success",{buttons:!1,timer:1500}),page.getUsers(page.views.users)}})).catch(page.onAxiosError)}))}},deleteUser:function(e){if(page.cache.users[e]){var a=document.createElement("div");a.innerHTML="\n

    You will be deleting a user named "+page.cache.users[e].username+".

    \n

    Their files will remain, unless you choose otherwise.

    \n ",swal({title:"Are you sure?",icon:"warning",content:a,dangerMode:!0,buttons:{cancel:!0,confirm:{text:"Yes, delete it!",closeModal:!1},purge:{text:"Yes, and the uploads too!",value:"purge",className:"swal-button--danger",closeModal:!1}}}).then((function(a){a&&axios.post("api/users/delete",{id:e,purge:"purge"===a}).then((function(a){if(a){if(!1===a.data.success){var n=Array.isArray(a.data.failed)?a.data.failed:[];return"No token provided"===a.data.description?page.verifyToken(page.token):n.length?swal("An error occurred!","Unable to delete "+n.length+" of the user's upload"+(1===n.length?"":"s")+".","error"):swal("An error occurred!",a.data.description,"error")}swal("Success!",page.cache.users[e].username+" has been deleted.","success",{buttons:!1,timer:1500}),page.getUsers(Object.assign({autoPage:!0},page.views.users))}})).catch(page.onAxiosError)}))}},paginate:function(e,a,n){n+=1;var t=Math.ceil(e/a),s="",i=function(e,a){for(var t=e;t<=a;++t)s+='
  • '+t+"
  • "},l=function(){s+='\n
  • 1
  • \n
  • \n '},r=function(){s+='\n
  • \n
  • '+t+"
  • \n "};return 7>=t?i(1,t):n<6?(i(1,6),r()):n>t-6+1?(l(),i(t-6+1,t)):(l(),i(n-3+1,n+3-1),r()),'\n \n "},getStatistics:function(e){if(void 0===e&&(e={}),!page.permissions.admin)return swal("An error occurred!","You can not do this!","error");page.updateTrigger(e.trigger,"loading");axios.get("api/stats").then((function(a){if(!1===a.data.success)return"No token provided"===a.data.description?page.verifyToken(page.token):(page.updateTrigger(e.trigger),swal("An error occurred!",a.data.description,"error"));for(var n="",t=Object.keys(a.data.stats),s=0;s\n "+d+"\n \n "}}catch(e){i="\n \n Error parsing response. Try again?\n \n \n ",page.onError(e)}else i+="\n \n Generating, please try again later…\n \n \n ";n+='\n
    \n \n \n \n \n \n \n \n \n "+i+"\n \n
    '+t[s].toUpperCase()+"
    \n
    \n "}page.dom.innerHTML=n,page.fadeAndScroll(),page.updateTrigger(e.trigger,"active")})).catch((function(a){page.updateTrigger(e.trigger),page.onAxiosError(a)}))}};window.onload=function(){"function"!=typeof Object.assign&&Object.defineProperty(Object,"assign",{value:function(e,a){"use strict";var n=arguments;if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var t=Object(e),s=1;s {\n document.querySelector('#loader').classList.add('is-hidden')\n document.querySelector('#dashboard').classList.remove('is-hidden')\n}\n\n// Handler for regular JS errors\npage.onError = error => {\n console.error(error)\n\n const content = document.createElement('div')\n content.innerHTML = `${error.toString()}`\n return swal({\n title: 'An error occurred!',\n icon: 'error',\n content\n })\n}\n\n// Handler for Axios errors\npage.onAxiosError = error => {\n console.error(error)\n\n // Better Cloudflare errors\n const cloudflareErrors = {\n 520: 'Unknown Error',\n 521: 'Web Server Is Down',\n 522: 'Connection Timed Out',\n 523: 'Origin Is Unreachable',\n 524: 'A Timeout Occurred',\n 525: 'SSL Handshake Failed',\n 526: 'Invalid SSL Certificate',\n 527: 'Railgun Error',\n 530: 'Origin DNS Error'\n }\n\n const statusText = cloudflareErrors[error.response.status] || error.response.statusText\n const description = error.response.data && error.response.data.description\n ? error.response.data.description\n : 'There was an error with the request, please check the console for more information.'\n\n return swal(`${error.response.status} ${statusText}`, description, 'error')\n}\n\npage.preparePage = () => {\n if (page.token)\n page.verifyToken(page.token, true)\n else\n window.location = 'auth'\n}\n\npage.verifyToken = (token, reloadOnError) => {\n axios.post('api/tokens/verify', { token }).then(response => {\n if (response.data.success === false)\n return swal({\n title: 'An error occurred!',\n text: response.data.description,\n icon: 'error'\n }).then(() => {\n if (!reloadOnError) return\n localStorage.removeItem(lsKeys.token)\n window.location = 'auth'\n })\n\n axios.defaults.headers.common.token = token\n localStorage[lsKeys.token] = token\n\n page.token = token\n page.username = response.data.username\n page.permissions = response.data.permissions\n page.prepareDashboard()\n }).catch(page.onAxiosError)\n}\n\npage.prepareDashboard = () => {\n page.dom = document.querySelector('#page')\n\n // Capture all click events\n page.dom.addEventListener('click', page.domClick, true)\n\n // Capture all submit events\n page.dom.addEventListener('submit', event => {\n // Prevent default if necessary\n if (event.target && event.target.classList.contains('prevent-default'))\n return event.preventDefault()\n }, true)\n\n page.menusContainer = document.querySelector('#menu')\n\n // All item menus in the sidebar\n const itemMenus = [\n { selector: '#itemUploads', onclick: page.getUploads },\n { selector: '#itemDeleteUploadsByNames', onclick: page.deleteUploadsByNames },\n { selector: '#itemManageAlbums', onclick: page.getAlbums },\n { selector: '#itemManageToken', onclick: page.changeToken },\n { selector: '#itemChangePassword', onclick: page.changePassword },\n { selector: '#itemLogout', onclick: page.logout },\n { selector: '#itemManageUploads', onclick: page.getUploads, params: { all: true }, group: 'moderator' },\n { selector: '#itemStatistics', onclick: page.getStatistics, group: 'admin' },\n { selector: '#itemManageUsers', onclick: page.getUsers, group: 'admin' }\n ]\n\n for (let i = 0; i < itemMenus.length; i++) {\n // Skip item menu if not enough permission\n if (itemMenus[i].group && !page.permissions[itemMenus[i].group])\n continue\n\n // Add onclick event listener\n const item = document.querySelector(itemMenus[i].selector)\n item.addEventListener('click', event => {\n // This class name isn't actually being applied fast enough\n if (page.menusContainer.classList.contains('is-loading'))\n return\n\n // eslint-disable-next-line compat/compat\n itemMenus[i].onclick.call(null, Object.assign({\n trigger: event.currentTarget\n }, itemMenus[i].params || {}))\n })\n\n item.classList.remove('is-hidden')\n page.menus.push(item)\n }\n\n // If at least a moderator, show administration section\n if (page.permissions.moderator) {\n document.querySelector('#itemLabelAdmin').classList.remove('is-hidden')\n document.querySelector('#itemListAdmin').classList.remove('is-hidden')\n }\n\n // Update text of logout button\n document.querySelector('#itemLogout').innerHTML = `Logout ( ${page.username} )`\n\n // Finally display dashboard\n page.unhide()\n\n // Load albums sidebar\n page.getAlbumsSidebar()\n\n if (typeof page.prepareShareX === 'function')\n page.prepareShareX()\n}\n\npage.logout = params => {\n page.updateTrigger(params.trigger, 'active')\n localStorage.removeItem(lsKeys.token)\n window.location = 'auth'\n}\n\npage.updateTrigger = (trigger, newState) => {\n if (!trigger) return\n\n // Disable menus container when loading\n if (newState === 'loading')\n page.menusContainer.classList.add('is-loading')\n else\n page.menusContainer.classList.remove('is-loading')\n\n if (newState === 'loading') {\n trigger.classList.add('is-loading')\n } else if (newState === 'active') {\n if (trigger.parentNode.tagName !== 'LI')\n return\n for (let i = 0; i < page.menus.length; i++)\n page.menus[i].classList.remove('is-active')\n trigger.classList.remove('is-loading')\n trigger.classList.add('is-active')\n } else {\n trigger.classList.remove('is-loading')\n trigger.classList.remove('is-active')\n }\n}\n\npage.getItemID = element => {\n // This expects the item's parent to have the item's ID\n let parent = element.parentNode\n // If the element is part of a set of controls, use the container's parent instead\n if (element.parentNode.classList.contains('controls')) parent = parent.parentNode\n return parseInt(parent.dataset.id)\n}\n\npage.domClick = event => {\n // We are processing clicks this way to avoid using \"onclick\" attribute\n // Apparently we will need to use \"unsafe-inline\" for \"script-src\" directive\n // of Content Security Policy (CSP), if we want to use \"onclick\" attribute\n // Though I think that only applies to some browsers (?)\n // Of course it wouldn't have mattered if we didn't use CSP to begin with\n // Anyway, I personally would rather not use \"onclick\" attribute\n let element = event.target\n if (!element) return\n\n // Delegate click events to their A or BUTTON parents\n if (['I'].includes(element.tagName) && ['SPAN'].includes(element.parentNode.tagName))\n element = element.parentNode\n if (['SPAN'].includes(element.tagName) && ['A', 'BUTTON'].includes(element.parentNode.tagName))\n element = element.parentNode\n\n // Skip elements that have no action data\n if (!element.dataset || !element.dataset.action) return\n\n // Skip disabled elements\n if (element.hasAttribute('disabled')) return\n\n event.stopPropagation() // maybe necessary\n const id = page.getItemID(element)\n const action = element.dataset.action\n\n switch (action) {\n case 'view-list':\n return page.setUploadsView('list', element)\n case 'view-thumbs':\n return page.setUploadsView('thumbs', element)\n case 'clear-selection':\n return page.clearSelection()\n case 'add-selected-uploads-to-album':\n return page.addSelectedUploadsToAlbum()\n case 'select':\n return page.select(element, event)\n case 'select-all':\n return page.selectAll(element)\n case 'add-to-album':\n return page.addToAlbum(id)\n case 'delete-upload':\n return page.deleteUpload(id)\n case 'bulk-delete-uploads':\n return page.bulkDeleteUploads()\n case 'display-preview':\n return page.displayPreview(id)\n case 'submit-album':\n return page.submitAlbum(element)\n case 'edit-album':\n return page.editAlbum(id)\n case 'delete-album':\n return page.deleteAlbum(id)\n case 'get-new-token':\n return page.getNewToken(element)\n case 'create-user':\n return page.createUser()\n case 'edit-user':\n return page.editUser(id)\n case 'disable-user':\n return page.disableUser(id)\n case 'delete-user':\n return page.deleteUser(id)\n case 'user-filters-help':\n return page.userFiltersHelp(element)\n case 'filter-uploads':\n return page.filterUploads(element)\n case 'view-user-uploads':\n return page.viewUserUploads(id, element)\n case 'page-ellipsis':\n return page.focusJumpToPage()\n case 'page-prev':\n case 'page-next':\n case 'page-goto':\n case 'jump-to-page':\n return page.switchPage(action, element)\n }\n}\n\npage.fadeAndScroll = disableFading => {\n if (page.fadingIn) {\n clearTimeout(page.fadingIn)\n page.dom.classList.remove('fade-in')\n }\n\n if (!disableFading) {\n page.dom.classList.add('fade-in')\n page.fadingIn = setTimeout(() => {\n page.dom.classList.remove('fade-in')\n }, 500)\n }\n\n page.dom.scrollIntoView({\n behavior: disableFading ? 'auto' : 'smooth',\n block: 'start',\n inline: 'nearest'\n })\n}\n\npage.switchPage = (action, element) => {\n // eslint-disable-next-line compat/compat\n const params = Object.assign({\n trigger: element\n }, page.views[page.currentView])\n\n const func = page.currentView === 'users' ? page.getUsers : page.getUploads\n\n switch (action) {\n case 'page-prev':\n params.pageNum = page.views[page.currentView].pageNum - 1\n if (params.pageNum < 0)\n return swal('An error occurred!', 'This is already the first page.', 'error')\n return func(params)\n case 'page-next':\n params.pageNum = page.views[page.currentView].pageNum + 1\n return func(params)\n case 'page-goto':\n params.pageNum = parseInt(element.dataset.goto)\n return func(params)\n case 'jump-to-page': {\n const jumpToPage = document.querySelector('#jumpToPage')\n if (!jumpToPage.checkValidity()) return\n const parsed = parseInt(jumpToPage.value)\n params.pageNum = isNaN(parsed) ? 0 : (parsed - 1)\n if (params.pageNum < 0) params.pageNum = 0\n return func(params)\n }\n }\n}\n\npage.focusJumpToPage = () => {\n const element = document.querySelector('#jumpToPage')\n if (!element) return\n element.focus()\n element.select()\n}\n\npage.getUploads = (params = {}) => {\n if (params === undefined)\n params = {}\n\n if ((params.all || params.filters) && !page.permissions.moderator)\n return swal('An error occurred!', 'You can not do this!', 'error')\n\n page.updateTrigger(params.trigger, 'loading')\n\n if (typeof params.pageNum !== 'number' || params.pageNum < 0)\n params.pageNum = 0\n\n const url = params.album !== undefined\n ? `api/album/${params.album}/${params.pageNum}`\n : `api/uploads/${params.pageNum}`\n\n const headers = {\n all: params.all ? '1' : '',\n filters: params.filters || ''\n }\n\n axios.get(url, { headers }).then(response => {\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n page.updateTrigger(params.trigger)\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n const pages = Math.ceil(response.data.count / 25)\n const files = response.data.files\n if (params.pageNum && (files.length === 0))\n if (params.autoPage) {\n params.pageNum = pages - 1\n return page.getUploads(params)\n } else {\n page.updateTrigger(params.trigger)\n return swal('An error occurred!', `There are no more uploads to populate page ${params.pageNum + 1}.`, 'error')\n }\n\n page.currentView = params.all ? 'uploadsAll' : 'uploads'\n page.cache.uploads = {}\n\n const albums = response.data.albums\n const users = response.data.users\n const basedomain = response.data.basedomain\n const pagination = page.paginate(response.data.count, 25, params.pageNum)\n\n let filter = '
    '\n if (params.all)\n filter = `\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n `\n const extraControls = `\n
    \n ${filter}\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n `\n\n const controls = `\n
    \n
    \n \n
    \n \n \n \n \n \n ${params.all ? '' : `\n \n \n \n \n `}\n \n \n \n \n Bulk delete\n \n
    \n
    \n `\n\n // Whether there are any unselected items\n let unselected = false\n\n const hasExpiryDateColumn = files.some(file => {\n return file.expirydate !== undefined\n })\n\n for (let i = 0; i < files.length; i++) {\n // Build full URLs\n files[i].file = `${basedomain}/${files[i].name}`\n if (files[i].thumb)\n files[i].thumb = `${basedomain}/${files[i].thumb}`\n\n // Determine types\n files[i].type = 'other'\n const exec = /.[\\w]+(\\?|$)/.exec(files[i].file)\n const extname = exec && exec[0] ? exec[0].toLowerCase() : null\n if (page.imageExts.includes(extname))\n files[i].type = 'picture'\n else if (page.videoExts.includes(extname))\n files[i].type = 'video'\n\n // Cache bare minimum data for thumbnails viewer\n page.cache.uploads[files[i].id] = {\n name: files[i].name,\n thumb: files[i].thumb,\n original: files[i].file,\n type: files[i].type\n }\n\n // Prettify\n files[i].prettyBytes = page.getPrettyBytes(parseInt(files[i].size))\n files[i].prettyDate = page.getPrettyDate(new Date(files[i].timestamp * 1000))\n\n if (hasExpiryDateColumn)\n files[i].prettyExpiryDate = files[i].expirydate\n ? page.getPrettyDate(new Date(files[i].expirydate * 1000))\n : null\n\n // Update selected status\n files[i].selected = page.selected[page.currentView].includes(files[i].id)\n if (!files[i].selected) unselected = true\n\n // Appendix (display album or user)\n if (params.all)\n files[i].appendix = files[i].userid\n ? users[files[i].userid] || ''\n : ''\n else if (params.album === undefined)\n files[i].appendix = files[i].albumid\n ? albums[files[i].albumid] || ''\n : ''\n }\n\n if (page.views[page.currentView].type === 'thumbs') {\n page.dom.innerHTML = `\n ${pagination}\n ${extraControls}\n ${controls}\n
    \n
    \n ${pagination}\n `\n\n const table = document.querySelector('#table')\n\n for (let i = 0; i < files.length; i++) {\n const upload = files[i]\n const div = document.createElement('div')\n div.className = 'image-container column'\n div.dataset.id = upload.id\n\n if (upload.thumb !== undefined)\n div.innerHTML = `\"${upload.name}\"`\n else\n div.innerHTML = `

    ${upload.extname || 'N/A'}

    `\n\n div.innerHTML += `\n \n
    \n ${upload.thumb ? `\n \n \n \n \n ` : ''}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    \n
    \n

    ${upload.name}

    \n

    ${upload.appendix ? `${upload.appendix} – ` : ''}${upload.prettyBytes}

    \n ${hasExpiryDateColumn && upload.prettyExpiryDate ? `\n

    EXP: ${upload.prettyExpiryDate}

    ` : ''}\n
    \n `\n\n table.appendChild(div)\n page.checkboxes[page.currentView] = table.querySelectorAll('.checkbox[data-action=\"select\"]')\n }\n } else {\n page.dom.innerHTML = `\n ${pagination}\n ${extraControls}\n ${controls}\n
    \n \n \n \n \n \n ${params.album === undefined ? `` : ''}\n \n ${params.all ? '' : ''}\n \n ${hasExpiryDateColumn ? '' : ''}\n \n \n \n \n \n
    File${params.all ? 'User' : 'Album'}SizeIPDateExpiry date
    \n
    \n ${pagination}\n `\n\n const table = document.querySelector('#table')\n\n for (let i = 0; i < files.length; i++) {\n const upload = files[i]\n const tr = document.createElement('tr')\n tr.dataset.id = upload.id\n tr.innerHTML = `\n \n ${upload.name}\n ${params.album === undefined ? `${upload.appendix}` : ''}\n ${upload.prettyBytes}\n ${params.all ? `${upload.ip || ''}` : ''}\n ${upload.prettyDate}\n ${hasExpiryDateColumn ? `${upload.prettyExpiryDate || '-'}` : ''}\n \n \n \n \n \n \n \n \n \n \n \n ${params.all ? '' : `\n \n \n \n \n `}\n \n \n \n \n \n \n `\n\n table.appendChild(tr)\n page.checkboxes[page.currentView] = table.querySelectorAll('.checkbox[data-action=\"select\"]')\n }\n }\n\n const selectAll = document.querySelector('#selectAll')\n if (selectAll && !unselected && files.length) {\n selectAll.checked = true\n selectAll.title = 'Unselect all'\n }\n\n if (page.views[page.currentView].type === 'thumbs') {\n page.fadeAndScroll(true)\n page.lazyLoad.update()\n } else {\n page.fadeAndScroll()\n }\n\n page.updateTrigger(params.trigger, 'active')\n\n if (page.currentView === 'uploads')\n page.views.uploads.album = params.album\n if (page.currentView === 'uploadsAll')\n page.views.uploadsAll.filters = params.filters\n page.views[page.currentView].pageNum = files.length ? params.pageNum : 0\n }).catch(error => {\n page.updateTrigger(params.trigger)\n page.onAxiosError(error)\n })\n}\n\npage.setUploadsView = (view, element) => {\n localStorage[lsKeys.viewType[page.currentView]] = view\n page.views[page.currentView].type = view\n\n // eslint-disable-next-line compat/compat\n page.getUploads(Object.assign({\n trigger: element\n }, page.views[page.currentView]))\n}\n\npage.displayPreview = id => {\n const file = page.cache.uploads[id]\n if (!file.thumb) return\n\n const div = document.createElement('div')\n div.innerHTML = `\n
    \n \n
    \n \n
    \n
    \n `\n\n if (file.original) {\n const exec = /.[\\w]+(\\?|$)/.exec(file.original)\n const extname = exec && exec[0] ? exec[0].toLowerCase() : null\n const isimage = page.imageExts.includes(extname)\n const isvideo = !isimage && page.videoExts.includes(extname)\n\n if (isimage || isvideo) {\n div.innerHTML += `\n \n `\n\n div.querySelector('#swalOriginal').addEventListener('click', event => {\n const trigger = event.currentTarget\n if (trigger.classList.contains('is-danger'))\n return\n\n trigger.classList.add('is-loading')\n const thumb = div.querySelector('#swalThumb')\n\n if (isimage) {\n thumb.src = file.original\n thumb.onload = () => {\n trigger.classList.add('is-hidden')\n document.body.querySelector('.swal-overlay .swal-modal:not(.is-expanded)').classList.add('is-expanded')\n }\n thumb.onerror = event => {\n event.currentTarget.classList.add('is-hidden')\n trigger.className = 'button is-danger is-fullwidth'\n trigger.innerHTML = `\n \n \n \n Unable to load original\n `\n }\n } else if (isvideo) {\n thumb.classList.add('is-hidden')\n const video = document.createElement('video')\n video.id = 'swalVideo'\n video.controls = true\n video.autoplay = true\n video.src = file.original\n thumb.insertAdjacentElement('afterend', video)\n\n trigger.classList.add('is-hidden')\n document.body.querySelector('.swal-overlay .swal-modal:not(.is-expanded)').classList.add('is-expanded')\n }\n })\n }\n }\n\n return swal({\n content: div,\n buttons: false\n }).then(() => {\n // Destroy video, if necessary\n const video = div.querySelector('#swalVideo')\n if (video) video.remove()\n\n // Restore modal size\n document.body.querySelector('.swal-overlay .swal-modal').classList.remove('is-expanded')\n })\n}\n\npage.selectAll = element => {\n for (let i = 0; i < page.checkboxes[page.currentView].length; i++) {\n const id = page.getItemID(page.checkboxes[page.currentView][i])\n if (isNaN(id)) continue\n if (page.checkboxes[page.currentView][i].checked !== element.checked) {\n page.checkboxes[page.currentView][i].checked = element.checked\n if (page.checkboxes[page.currentView][i].checked)\n page.selected[page.currentView].push(id)\n else\n page.selected[page.currentView].splice(page.selected[page.currentView].indexOf(id), 1)\n }\n }\n\n if (page.selected[page.currentView].length)\n localStorage[lsKeys.selected[page.currentView]] = JSON.stringify(page.selected[page.currentView])\n else\n delete localStorage[lsKeys.selected[page.currentView]]\n\n element.title = element.checked ? 'Unselect all' : 'Select all'\n}\n\npage.selectInBetween = (element, lastElement) => {\n const thisIndex = parseInt(element.dataset.index)\n const lastIndex = parseInt(lastElement.dataset.index)\n\n const distance = Math.abs(thisIndex - lastIndex)\n if (distance < 2)\n return\n\n for (let i = 0; i < page.checkboxes[page.currentView].length; i++)\n if ((thisIndex > lastIndex && i > lastIndex && i < thisIndex) ||\n (thisIndex < lastIndex && i > thisIndex && i < lastIndex)) {\n // Check or uncheck depending on the state of the initial checkbox\n const checked = page.checkboxes[page.currentView][i].checked = lastElement.checked\n const id = page.getItemID(page.checkboxes[page.currentView][i])\n if (!page.selected[page.currentView].includes(id) && checked)\n page.selected[page.currentView].push(id)\n else if (page.selected[page.currentView].includes(id) && !checked)\n page.selected[page.currentView].splice(page.selected[page.currentView].indexOf(id), 1)\n }\n}\n\npage.select = (element, event) => {\n const id = page.getItemID(element)\n if (isNaN(id)) return\n\n const lastSelected = page.lastSelected[page.currentView]\n if (event.shiftKey && lastSelected) {\n page.selectInBetween(element, lastSelected)\n // Check or uncheck depending on the state of the initial checkbox\n element.checked = lastSelected.checked\n } else {\n page.lastSelected[page.currentView] = element\n }\n\n if (!page.selected[page.currentView].includes(id) && element.checked)\n page.selected[page.currentView].push(id)\n else if (page.selected[page.currentView].includes(id) && !element.checked)\n page.selected[page.currentView].splice(page.selected[page.currentView].indexOf(id), 1)\n\n // Update local storage\n if (page.selected[page.currentView].length)\n localStorage[lsKeys.selected[page.currentView]] = JSON.stringify(page.selected[page.currentView])\n else\n delete localStorage[lsKeys.selected[page.currentView]]\n}\n\npage.clearSelection = () => {\n const selected = page.selected[page.currentView]\n const type = page.currentView === 'users' ? 'users' : 'uploads'\n const count = selected.length\n if (!count)\n return swal('An error occurred!', `You have not selected any ${type}.`, 'error')\n\n const suffix = count === 1 ? type.substring(0, type.length - 1) : type\n return swal({\n title: 'Are you sure?',\n text: `You are going to unselect ${count} ${suffix}.`,\n buttons: true\n }).then(proceed => {\n if (!proceed) return\n\n const checkboxes = page.checkboxes[page.currentView]\n for (let i = 0; i < checkboxes.length; i++)\n if (checkboxes[i].checked)\n checkboxes[i].checked = false\n\n page.selected[page.currentView] = []\n delete localStorage[lsKeys.selected[page.currentView]]\n\n const selectAll = document.querySelector('#selectAll')\n if (selectAll) selectAll.checked = false\n\n return swal('Cleared selection!', `Unselected ${count} ${suffix}.`, 'success')\n })\n}\n\npage.userFiltersHelp = element => {\n const content = document.createElement('div')\n content.style = 'text-align: left'\n content.innerHTML = `\n This supports 3 filter keys, namely user (username), ip and name (upload name).\n Each key can be specified more than once.\n Backslashes should be used if the username contain whitespaces.\n\n There are 2 special flags, namely -user and -ip, which will match uploads by non-registered users and have no IPs respectively.\n\n Matches can also be sorted with orderby:columnName[:direction] key.\n This key requires using the internal column names used in the database (size, timestamp, expirydate, and so on).\n This key can also be specified more than once, where their order will decide the sorting steps.\n\n Internals:\n First, it will filter uploads matching ANY of the supplied filter keys AND/OR special flags, if any.\n Second, it will refine the matches using the supplied name keys, if any.\n Third, it will sort the matches using the supplied orderby keys, if any.\n\n Examples:\n Uploads from user with username \"demo\":\n user:demo\n Uploads from users with username \"John Doe\" AND/OR \"demo\":\n user:John\\\\ Doe user:demo\n Uploads from IP \"127.0.0.1\" AND which upload names match \"*.rar\" OR \"*.zip\":\n ip:127.0.0.1 name:*.rar name:*.zip\n Uploads from user with username \"test\" AND/OR from non-registered users:\n user:test -user\n Sort results by \"size\" column in ascending and descending order respectively:\n orderby:expirydate\n user:demo orderby:size\n -user name:*.mp4 orderby:size:desc\n `.trim().replace(/^ {6}/gm, '').replace(/\\n/g, '
    ')\n swal({ content })\n}\n\npage.filterUploads = element => {\n const filters = document.querySelector('#filters').value.trim()\n page.getUploads({ all: true, filters }, element)\n}\n\npage.viewUserUploads = (id, element) => {\n const user = page.cache.users[id]\n if (!user) return\n element.classList.add('is-loading')\n page.getUploads({\n all: true,\n filters: `user:${user.username.replace(/ /g, '\\\\ ')}`,\n trigger: document.querySelector('#itemManageUploads')\n })\n}\n\npage.deleteUpload = id => {\n page.postBulkDeleteUploads({\n all: page.currentView === 'uploadsAll',\n field: 'id',\n values: [id],\n cb (failed) {\n // Remove from remembered checkboxes if necessary\n if (!failed.length && page.selected[page.currentView].includes(id))\n page.selected[page.currentView].splice(page.selected[page.currentView].indexOf(id), 1)\n\n // Update local storage\n if (page.selected[page.currentView].length)\n localStorage[lsKeys.selected[page.currentView]] = JSON.stringify(page.selected[page.currentView])\n else\n delete localStorage[lsKeys.selected[page.currentView]]\n\n // Reload upload list\n // eslint-disable-next-line compat/compat\n page.getUploads(Object.assign({\n autoPage: true\n }, page.views[page.currentView]))\n }\n })\n}\n\npage.bulkDeleteUploads = () => {\n const count = page.selected[page.currentView].length\n if (!count)\n return swal('An error occurred!', 'You have not selected any uploads.', 'error')\n\n page.postBulkDeleteUploads({\n all: page.currentView === 'uploadsAll',\n field: 'id',\n values: page.selected[page.currentView],\n cb (failed) {\n // Update state of checkboxes\n if (failed.length)\n page.selected[page.currentView] = page.selected[page.currentView]\n .filter(id => {\n return failed.includes(id)\n })\n else\n page.selected[page.currentView] = []\n\n // Update local storage\n if (page.selected[page.currentView].length)\n localStorage[lsKeys.selected[page.currentView]] = JSON.stringify(page.selected[page.currentView])\n else\n delete localStorage[lsKeys.selected[page.currentView]]\n\n // Reload uploads list\n // eslint-disable-next-line compat/compat\n page.getUploads(Object.assign({\n autoPage: true\n }, page.views[page.currentView]))\n }\n })\n}\n\npage.deleteUploadsByNames = (params = {}) => {\n let appendix = ''\n if (page.permissions.moderator)\n appendix = '
    Hint: You can use this feature to delete uploads by other users.'\n\n page.dom.innerHTML = `\n
    \n
    \n \n
    \n \n
    \n

    Separate each entry with a new line.${appendix}

    \n
    \n
    \n
    \n \n
    \n
    \n
    \n `\n page.fadeAndScroll()\n page.updateTrigger(params.trigger, 'active')\n\n document.querySelector('#submitBulkDelete').addEventListener('click', () => {\n const textArea = document.querySelector('#bulkDeleteNames')\n\n // Clean up\n const seen = {}\n const names = textArea.value\n .split(/\\r?\\n/)\n .map(name => {\n const trimmed = name.trim()\n return /^[^\\s]+$/.test(trimmed)\n ? trimmed\n : ''\n })\n .filter(name => {\n // Filter out invalid and duplicate names\n return (!name || Object.prototype.hasOwnProperty.call(seen, name))\n ? false\n : (seen[name] = true)\n })\n\n // Update textarea with cleaned names\n textArea.value = names.join('\\n')\n\n if (!names.length)\n return swal('An error occurred!', 'You have not entered any upload names.', 'error')\n\n page.postBulkDeleteUploads({\n all: true,\n field: 'name',\n values: names,\n cb (failed) {\n textArea.value = failed.join('\\n')\n }\n })\n })\n}\n\npage.postBulkDeleteUploads = (params = {}) => {\n const count = params.values.length\n\n const objective = `${params.values.length} upload${count === 1 ? '' : 's'}`\n const boldObjective = objective.replace(/^(\\d*)(.*)/, '$1$2')\n let text = `

    You won't be able to recover ${boldObjective}!

    `\n\n if (params.all) {\n const obj1 = count === 1 ? 'an upload' : 'some uploads'\n const obj2 = count === 1 ? 'another user' : 'other users'\n text += `\\n

    Warning: You may be nuking ${obj1} by ${obj2}!

    `\n }\n\n const content = document.createElement('div')\n content.innerHTML = text\n\n swal({\n title: 'Are you sure?',\n content,\n icon: 'warning',\n dangerMode: true,\n buttons: {\n cancel: true,\n confirm: {\n text: `Yes, nuke ${params.values.length === 1 ? 'it' : 'them'}!`,\n closeModal: false\n }\n }\n }).then(proceed => {\n if (!proceed) return\n\n axios.post('api/upload/bulkdelete', {\n field: params.fields,\n values: params.values\n }).then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n const failed = Array.isArray(response.data.failed) ? response.data.failed : []\n if (failed.length === params.values.length)\n swal('An error occurred!', `Unable to delete any of the ${objective}.`, 'error')\n else if (failed.length && failed.length < params.values.length)\n swal('Warning!', `From ${objective}, unable to delete ${failed.length} of them.`, 'warning')\n else\n swal('Deleted!', `${objective} ${count === 1 ? 'has' : 'have'} been deleted.`, 'success', {\n buttons: false,\n timer: 1500\n })\n\n if (typeof params.cb === 'function')\n params.cb(failed)\n }).catch(page.onAxiosError)\n })\n}\n\npage.addSelectedUploadsToAlbum = () => {\n if (page.currentView !== 'uploads')\n return\n\n const count = page.selected[page.currentView].length\n if (!count)\n return swal('An error occurred!', 'You have not selected any uploads.', 'error')\n\n page.addUploadsToAlbum(page.selected[page.currentView], failed => {\n if (!failed) return\n if (failed.length)\n page.selected[page.currentView] = page.selected[page.currentView].filter(id => {\n return failed.includes(id)\n })\n else\n page.selected[page.currentView] = []\n\n localStorage[lsKeys.selected[page.currentView]] = JSON.stringify(page.selected[page.currentView])\n page.getUploads(page.views[page.currentView])\n })\n}\n\npage.addToAlbum = id => {\n page.addUploadsToAlbum([id], failed => {\n if (!failed) return\n page.getUploads(page.views[page.currentView])\n })\n}\n\npage.addUploadsToAlbum = (ids, callback) => {\n const count = ids.length\n\n const content = document.createElement('div')\n content.innerHTML = `\n
    \n

    You are about to add ${count} upload${count === 1 ? '' : 's'} to an album.

    \n

    If an upload is already in an album, it will be moved.

    \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n `\n\n swal({\n icon: 'warning',\n content,\n buttons: {\n cancel: true,\n confirm: {\n text: 'OK',\n closeModal: false\n }\n }\n }).then(choose => {\n if (!choose) return\n\n const albumid = parseInt(document.querySelector('#swalAlbum').value)\n if (isNaN(albumid))\n return swal('An error occurred!', 'You did not choose an album.', 'error')\n\n axios.post('api/albums/addfiles', {\n ids,\n albumid\n }).then(add => {\n if (!add) return\n\n if (add.data.success === false) {\n if (add.data.description === 'No token provided')\n page.verifyToken(page.token)\n else\n swal('An error occurred!', add.data.description, 'error')\n\n return\n }\n\n let added = ids.length\n if (add.data.failed && add.data.failed.length)\n added -= add.data.failed.length\n\n const suffix = `upload${ids.length === 1 ? '' : 's'}`\n if (!added)\n return swal('An error occurred!', `Could not add the ${suffix} to the album.`, 'error')\n\n swal('Woohoo!', `Successfully ${albumid < 0 ? 'removed' : 'added'} ${added} ${suffix} ${albumid < 0 ? 'from' : 'to'} the album.`, 'success', {\n buttons: false,\n timer: 1500\n })\n callback(add.data.failed)\n }).catch(page.onAxiosError)\n })\n\n // Get albums list then update content of swal\n axios.get('api/albums').then(list => {\n if (list.data.success === false) {\n if (list.data.description === 'No token provided')\n page.verifyToken(page.token)\n else\n swal('An error occurred!', list.data.description, 'error')\n\n return\n }\n\n // If the prompt was replaced, the container would be missing\n const select = document.querySelector('#swalAlbum')\n if (!select) return\n\n select.innerHTML += list.data.albums\n .map(album => {\n return ``\n })\n .join('\\n')\n\n select.getElementsByTagName('option')[1].innerHTML = 'Choose an album'\n select.removeAttribute('disabled')\n }).catch(page.onAxiosError)\n}\n\npage.getAlbums = (params = {}) => {\n page.updateTrigger(params.trigger, 'loading')\n\n axios.get('api/albums').then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n page.updateTrigger(params.trigger)\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n page.cache.albums = {}\n\n page.dom.innerHTML = `\n

    Create new album

    \n
    \n
    \n
    \n \n
    \n

    Max length is ${page.albumTitleMaxLength} characters.

    \n
    \n
    \n
    \n \n
    \n

    Max length is ${page.albumDescMaxLength} characters.

    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n

    List of albums

    \n
    \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    IDNameFilesCreated atPublic link
    \n
    \n `\n\n const homeDomain = response.data.homeDomain\n const table = document.querySelector('#table')\n\n for (let i = 0; i < response.data.albums.length; i++) {\n const album = response.data.albums[i]\n const albumUrl = `${homeDomain}/a/${album.identifier}`\n\n // Prettify\n album.prettyDate = page.getPrettyDate(new Date(album.timestamp * 1000))\n\n page.cache.albums[album.id] = {\n name: album.name,\n download: album.download,\n public: album.public,\n description: album.description\n }\n\n const tr = document.createElement('tr')\n tr.innerHTML = `\n ${album.id}\n ${album.name}\n ${album.files}\n ${album.prettyDate}\n ${albumUrl}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n `\n\n table.appendChild(tr)\n }\n page.fadeAndScroll()\n page.updateTrigger(params.trigger, 'active')\n }).catch(error => {\n page.updateTrigger(params.trigger)\n page.onAxiosError(error)\n })\n}\n\npage.editAlbum = id => {\n const album = page.cache.albums[id]\n if (!album) return\n\n const div = document.createElement('div')\n div.innerHTML = `\n
    \n
    \n \n
    \n

    Max length is ${page.albumTitleMaxLength} characters.

    \n
    \n
    \n
    \n \n
    \n

    Max length is ${page.albumDescMaxLength} characters.

    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n `\n\n swal({\n title: 'Edit album',\n icon: 'info',\n content: div,\n buttons: {\n cancel: true,\n confirm: {\n closeModal: false\n }\n }\n }).then(value => {\n if (!value) return\n\n axios.post('api/albums/edit', {\n id,\n name: document.querySelector('#swalName').value.trim(),\n description: document.querySelector('#swalDescription').value.trim(),\n download: document.querySelector('#swalDownload').checked,\n public: document.querySelector('#swalPublic').checked,\n requestLink: document.querySelector('#swalRequestLink').checked\n }).then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n if (response.data.identifier)\n swal('Success!', `Your album's new identifier is: ${response.data.identifier}.`, 'success')\n else if (response.data.name !== album.name)\n swal('Success!', `Your album was renamed to: ${response.data.name}.`, 'success')\n else\n swal('Success!', 'Your album was edited!', 'success', {\n buttons: false,\n timer: 1500\n })\n\n page.getAlbumsSidebar()\n page.getAlbums()\n }).catch(page.onAxiosError)\n })\n}\n\npage.deleteAlbum = id => {\n swal({\n title: 'Are you sure?',\n text: 'This won\\'t delete your uploads, only the album!',\n icon: 'warning',\n dangerMode: true,\n buttons: {\n cancel: true,\n confirm: {\n text: 'Yes, delete it!',\n closeModal: false\n },\n purge: {\n text: 'Umm, delete the uploads too please?',\n value: 'purge',\n className: 'swal-button--danger',\n closeModal: false\n }\n }\n }).then(proceed => {\n if (!proceed) return\n\n axios.post('api/albums/delete', {\n id,\n purge: proceed === 'purge'\n }).then(response => {\n if (response.data.success === false) {\n const failed = Array.isArray(response.data.failed)\n ? response.data.failed\n : []\n\n if (response.data.description === 'No token provided')\n return page.verifyToken(page.token)\n else if (failed.length)\n return swal('An error occurred!', `Unable to delete ${failed.length} of the album's upload${failed.length === 1 ? '' : 's'}.`, 'error')\n else\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n swal('Deleted!', 'Your album has been deleted.', 'success', {\n buttons: false,\n timer: 1500\n })\n page.getAlbumsSidebar()\n page.getAlbums()\n }).catch(page.onAxiosError)\n })\n}\n\npage.submitAlbum = element => {\n page.updateTrigger(element, 'loading')\n\n axios.post('api/albums', {\n name: document.querySelector('#albumName').value.trim(),\n description: document.querySelector('#albumDescription').value.trim()\n }).then(response => {\n if (!response) return\n\n page.updateTrigger(element)\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n swal('Woohoo!', 'Album was created successfully.', 'success', {\n buttons: false,\n timer: 1500\n })\n page.getAlbumsSidebar()\n page.getAlbums()\n }).catch(error => {\n page.updateTrigger(element)\n page.onAxiosError(error)\n })\n}\n\npage.getAlbumsSidebar = () => {\n axios.get('api/albums/sidebar').then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n const albumsContainer = document.querySelector('#albumsContainer')\n\n // Clear albums sidebar if necessary\n const oldAlbums = albumsContainer.querySelectorAll('li > a')\n if (oldAlbums.length) {\n for (let i = 0; i < oldAlbums.length; i++)\n page.menus.splice(page.menus.indexOf(oldAlbums[i]), 1)\n albumsContainer.innerHTML = ''\n }\n\n if (response.data.albums === undefined)\n return\n\n for (let i = 0; i < response.data.albums.length; i++) {\n const album = response.data.albums[i]\n const li = document.createElement('li')\n const a = document.createElement('a')\n a.id = album.id\n a.innerHTML = album.name\n a.className = 'is-relative'\n\n a.addEventListener('click', event => {\n page.getUploads({\n album: parseInt(event.currentTarget.id),\n trigger: event.currentTarget\n })\n })\n page.menus.push(a)\n\n li.appendChild(a)\n albumsContainer.appendChild(li)\n }\n }).catch(page.onAxiosError)\n}\n\npage.changeToken = (params = {}) => {\n page.dom.innerHTML = `\n
    \n \n
    \n
    \n \n
    \n
    \n
    \n \n `\n page.fadeAndScroll()\n page.updateTrigger(params.trigger, 'active')\n\n document.querySelector('#getNewToken').addEventListener('click', event => {\n const trigger = event.currentTarget\n page.updateTrigger(trigger, 'loading')\n axios.post('api/tokens/change').then(response => {\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n page.updateTrigger(trigger)\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n page.updateTrigger(trigger)\n swal({\n title: 'Woohoo!',\n text: 'Your token was successfully changed.',\n icon: 'success'\n }).then(() => {\n axios.defaults.headers.common.token = response.data.token\n localStorage[lsKeys.token] = response.data.token\n page.token = response.data.token\n page.changeToken()\n })\n }).catch(error => {\n page.updateTrigger(trigger)\n page.onAxiosError(error)\n })\n })\n}\n\npage.changePassword = (params = {}) => {\n page.dom.innerHTML = `\n
    \n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n `\n page.fadeAndScroll()\n page.updateTrigger(params.trigger, 'active')\n\n document.querySelector('#sendChangePassword').addEventListener('click', event => {\n if (!page.dom.querySelector('form').checkValidity()) return\n if (document.querySelector('#password').value === document.querySelector('#passwordConfirm').value)\n page.sendNewPassword(document.querySelector('#password').value, event.currentTarget)\n else\n swal({\n title: 'Password mismatch!',\n text: 'Your passwords do not match, please try again.',\n icon: 'error'\n })\n })\n}\n\npage.sendNewPassword = (pass, element) => {\n page.updateTrigger(element, 'loading')\n\n axios.post('api/password/change', { password: pass }).then(response => {\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n page.updateTrigger(element)\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n page.updateTrigger(element)\n swal({\n title: 'Woohoo!',\n text: 'Your password was successfully changed.',\n icon: 'success',\n buttons: false,\n timer: 1500\n }).then(() => {\n page.changePassword()\n })\n }).catch(error => {\n page.updateTrigger(element)\n page.onAxiosError(error)\n })\n}\n\npage.getUsers = (params = {}) => {\n page.updateTrigger(params.trigger, 'loading')\n\n if (params.pageNum === undefined)\n params.pageNum = 0\n\n if (!page.permissions.admin)\n return swal('An error occurred!', 'You can not do this!', 'error')\n\n const url = `api/users/${params.pageNum}`\n axios.get(url).then(response => {\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n page.updateTrigger(params.trigger)\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n const pages = Math.ceil(response.data.count / 25)\n if (params.pageNum && (response.data.users.length === 0))\n if (params.autoPage) {\n params.pageNum = pages - 1\n return page.getUsers(params)\n } else {\n page.updateTrigger(params.trigger)\n return swal('An error occurred!', `There are no more users to populate page ${params.pageNum + 1}.`, 'error')\n }\n\n page.currentView = 'users'\n page.cache.users = {}\n\n const pagination = page.paginate(response.data.count, 25, params.pageNum)\n\n const filter = `\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n `\n const extraControls = `\n
    \n ${filter}\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n `\n\n const controls = `\n \n `\n\n // Whether there are any unselected items\n let unselected = false\n\n page.dom.innerHTML = `\n ${pagination}\n ${extraControls}\n ${controls}\n
    \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    IDUsernameUploadsUsageGroup
    \n
    \n ${pagination}\n `\n\n const table = document.querySelector('#table')\n\n for (let i = 0; i < response.data.users.length; i++) {\n const user = response.data.users[i]\n const selected = page.selected.users.includes(user.id)\n if (!selected) unselected = true\n\n let displayGroup = null\n const groups = Object.keys(user.groups)\n for (let i = 0; i < groups.length; i++) {\n if (!user.groups[groups[i]]) break\n displayGroup = groups[i]\n }\n\n // Server-side explicitly expects either of these two values to consider a user as disabled\n const enabled = user.enabled !== false && user.enabled !== 0\n page.cache.users[user.id] = {\n username: user.username,\n groups: user.groups,\n enabled,\n displayGroup\n }\n\n const tr = document.createElement('tr')\n tr.dataset.id = user.id\n tr.innerHTML = `\n \n ${user.id}\n ${user.username}\n ${user.uploads}\n ${page.getPrettyBytes(user.usage)}\n ${displayGroup}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n `\n\n table.appendChild(tr)\n page.checkboxes.users = table.querySelectorAll('.checkbox[data-action=\"select\"]')\n }\n\n const selectAll = document.querySelector('#selectAll')\n if (selectAll && !unselected) {\n selectAll.checked = true\n selectAll.title = 'Unselect all'\n }\n\n page.fadeAndScroll()\n page.updateTrigger(params.trigger, 'active')\n\n page.views.users.pageNum = response.data.users.length ? params.pageNum : 0\n }).catch(error => {\n page.updateTrigger(params.trigger)\n page.onAxiosError(error)\n })\n}\n\npage.createUser = () => {\n const groupOptions = Object.keys(page.permissions).map((g, i, a) => {\n const disabled = !(a[i + 1] && page.permissions[a[i + 1]])\n return ``\n }).join('\\n')\n\n const div = document.createElement('div')\n div.innerHTML = `\n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n `\n\n swal({\n title: 'Create new user',\n icon: 'info',\n content: div,\n buttons: {\n cancel: true,\n confirm: {\n closeModal: false\n }\n }\n }).then(proceed => {\n if (!proceed) return\n\n axios.post('api/users/create', {\n username: document.querySelector('#swalUsername').value,\n password: document.querySelector('#swalPassword').value,\n group: document.querySelector('#swalGroup').value\n }).then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n const div = document.createElement('div')\n div.innerHTML = `\n

    Username: ${response.data.username}

    \n

    Password: ${response.data.password}

    \n

    User group: ${response.data.group}

    \n `\n swal({\n title: 'Created a new user!',\n icon: 'success',\n content: div\n })\n\n page.getUsers(page.views.users)\n }).catch(page.onAxiosError)\n })\n}\n\npage.editUser = id => {\n const user = page.cache.users[id]\n if (!user) return\n\n const groupOptions = Object.keys(page.permissions).map((g, i, a) => {\n const selected = g === user.displayGroup\n const disabled = !(a[i + 1] && page.permissions[a[i + 1]])\n return ``\n }).join('\\n')\n\n const div = document.createElement('div')\n div.innerHTML = `\n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n `\n\n swal({\n title: 'Edit user',\n icon: 'info',\n content: div,\n buttons: {\n cancel: true,\n confirm: {\n closeModal: false\n }\n }\n }).then(proceed => {\n if (!proceed) return\n\n axios.post('api/users/edit', {\n id,\n username: document.querySelector('#swalUsername').value,\n group: document.querySelector('#swalGroup').value,\n enabled: document.querySelector('#swalEnabled').checked,\n resetPassword: document.querySelector('#swalResetPassword').checked\n }).then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n if (response.data.password) {\n const div = document.createElement('div')\n div.innerHTML = `\n

    ${user.username}'s new password is:

    \n

    ${response.data.password}

    \n `\n swal({\n title: 'Success!',\n icon: 'success',\n content: div\n })\n } else if (response.data.update && response.data.update.username !== user.username) {\n swal('Success!', `${user.username} was renamed into: ${response.data.update.username}.`, 'success')\n } else {\n swal('Success!', 'The user was edited!', 'success', {\n buttons: false,\n timer: 1500\n })\n }\n\n page.getUsers(page.views.users)\n }).catch(page.onAxiosError)\n })\n}\n\npage.disableUser = id => {\n const user = page.cache.users[id]\n if (!user || !user.enabled) return\n\n const content = document.createElement('div')\n content.innerHTML = `\n

    You will be disabling a user named ${page.cache.users[id].username}.

    \n

    Their files will remain.

    \n `\n\n swal({\n title: 'Are you sure?',\n icon: 'warning',\n content,\n dangerMode: true,\n buttons: {\n cancel: true,\n confirm: {\n text: 'Yes, disable them!',\n closeModal: false\n }\n }\n }).then(proceed => {\n if (!proceed) return\n\n axios.post('api/users/disable', { id }).then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided')\n return page.verifyToken(page.token)\n else\n return swal('An error occurred!', response.data.description, 'error')\n\n swal('Success!', `${page.cache.users[id].username} has been disabled.`, 'success', {\n buttons: false,\n timer: 1500\n })\n page.getUsers(page.views.users)\n }).catch(page.onAxiosError)\n })\n}\n\npage.deleteUser = id => {\n const user = page.cache.users[id]\n if (!user) return\n\n const content = document.createElement('div')\n content.innerHTML = `\n

    You will be deleting a user named ${page.cache.users[id].username}.

    \n

    Their files will remain, unless you choose otherwise.

    \n `\n\n swal({\n title: 'Are you sure?',\n icon: 'warning',\n content,\n dangerMode: true,\n buttons: {\n cancel: true,\n confirm: {\n text: 'Yes, delete it!',\n closeModal: false\n },\n purge: {\n text: 'Yes, and the uploads too!',\n value: 'purge',\n className: 'swal-button--danger',\n closeModal: false\n }\n }\n }).then(proceed => {\n if (!proceed) return\n\n axios.post('api/users/delete', {\n id,\n purge: proceed === 'purge'\n }).then(response => {\n if (!response) return\n\n if (response.data.success === false) {\n const failed = Array.isArray(response.data.failed)\n ? response.data.failed\n : []\n\n if (response.data.description === 'No token provided')\n return page.verifyToken(page.token)\n else if (failed.length)\n return swal('An error occurred!', `Unable to delete ${failed.length} of the user's upload${failed.length === 1 ? '' : 's'}.`, 'error')\n else\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n swal('Success!', `${page.cache.users[id].username} has been deleted.`, 'success', {\n buttons: false,\n timer: 1500\n })\n\n // Reload users list\n // eslint-disable-next-line compat/compat\n page.getUsers(Object.assign({\n autoPage: true\n }, page.views.users))\n }).catch(page.onAxiosError)\n })\n}\n\n// Roughly based on https://github.com/mayuska/pagination/blob/master/index.js\npage.paginate = (totalItems, itemsPerPage, currentPage) => {\n currentPage = currentPage + 1\n const step = 3\n const numPages = Math.ceil(totalItems / itemsPerPage)\n\n let template = ''\n const elementsToShow = step * 2\n const add = {\n pageNum (start, end) {\n for (let i = start; i <= end; ++i)\n template += `
  • ${i}
  • `\n },\n startDots () {\n template += `\n
  • 1
  • \n
  • \n `\n },\n endDots () {\n template += `\n
  • \n
  • ${numPages}
  • \n `\n }\n }\n\n if (elementsToShow + 1 >= numPages) {\n add.pageNum(1, numPages)\n } else if (currentPage < elementsToShow) {\n add.pageNum(1, elementsToShow)\n add.endDots()\n } else if (currentPage > numPages - elementsToShow + 1) {\n add.startDots()\n add.pageNum(numPages - elementsToShow + 1, numPages)\n } else {\n add.startDots()\n add.pageNum(currentPage - step + 1, currentPage + step - 1)\n add.endDots()\n }\n\n return `\n \n `\n}\n\npage.getStatistics = (params = {}) => {\n if (!page.permissions.admin)\n return swal('An error occurred!', 'You can not do this!', 'error')\n\n page.updateTrigger(params.trigger, 'loading')\n\n const url = 'api/stats'\n axios.get(url).then(response => {\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n page.updateTrigger(params.trigger)\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n let content = ''\n const keys = Object.keys(response.data.stats)\n for (let i = 0; i < keys.length; i++) {\n let rows = ''\n if (!response.data.stats[keys[i]])\n rows += `\n \n Generating, please try again later\\u2026\n \n \n `\n else\n try {\n const types = response.data.stats[keys[i]]._types || {}\n const valKeys = Object.keys(response.data.stats[keys[i]])\n for (let j = 0; j < valKeys.length; j++) {\n // Skip keys that starts with an underscore\n if (/^_/.test(valKeys[j]))\n continue\n\n const value = response.data.stats[keys[i]][valKeys[j]]\n let parsed = value\n\n // Parse values with some preset formatting\n if ((types.number || []).includes(valKeys[j]))\n parsed = value.toLocaleString()\n if ((types.byte || []).includes(valKeys[j]))\n parsed = page.getPrettyBytes(value)\n if ((types.byteUsage || []).includes(valKeys[j]))\n parsed = `${page.getPrettyBytes(value.used)} / ${page.getPrettyBytes(value.total)} (${Math.round(value.used / value.total * 100)}%)`\n\n const string = valKeys[j]\n .replace(/([A-Z])/g, ' $1')\n .toUpperCase()\n rows += `\n \n ${string}\n ${parsed}\n \n `\n }\n } catch (error) {\n rows = `\n \n Error parsing response. Try again?\n \n \n `\n page.onError(error)\n }\n\n content += `\n
    \n \n \n \n \n \n \n \n \n ${rows}\n \n
    ${keys[i].toUpperCase()}
    \n
    \n `\n }\n\n page.dom.innerHTML = content\n page.fadeAndScroll()\n page.updateTrigger(params.trigger, 'active')\n }).catch(error => {\n page.updateTrigger(params.trigger)\n page.onAxiosError(error)\n })\n}\n\nwindow.onload = () => {\n // Polyfill Object.assign()\n // eslint-disable-next-line compat/compat\n if (typeof Object.assign !== 'function')\n // Must be writable: true, enumerable: false, configurable: true\n Object.defineProperty(Object, 'assign', {\n value: function assign (target, varArgs) { // .length of function is 2\n 'use strict'\n if (target === null || target === undefined)\n throw new TypeError('Cannot convert undefined or null to object')\n const to = Object(target)\n for (let i = 1; i < arguments.length; i++) {\n const nextSource = arguments[i]\n if (nextSource !== null && nextSource !== undefined)\n for (const nextKey in nextSource)\n // Avoid bugs when hasOwnProperty is shadowed\n if (Object.prototype.hasOwnProperty.call(nextSource, nextKey))\n to[nextKey] = nextSource[nextKey]\n }\n return to\n },\n writable: true,\n configurable: true\n })\n\n // Add 'no-touch' class to non-touch devices\n if (!('ontouchstart' in document.documentElement))\n document.documentElement.classList.add('no-touch')\n\n const selectedKeys = ['uploads', 'uploadsAll', 'users']\n for (let i = 0; i < selectedKeys.length; i++) {\n const ls = localStorage[lsKeys.selected[selectedKeys[i]]]\n if (ls) page.selected[selectedKeys[i]] = JSON.parse(ls)\n }\n\n page.preparePage()\n\n page.clipboardJS = new ClipboardJS('.clipboard-js')\n\n page.clipboardJS.on('success', () => {\n return swal('', 'The link has been copied to clipboard.', 'success', {\n buttons: false,\n timer: 1500\n })\n })\n\n page.clipboardJS.on('error', page.onError)\n\n page.lazyLoad = new LazyLoad()\n}\n"]} \ No newline at end of file +{"version":3,"sources":["dashboard.js"],"names":["const","lsKeys","token","viewType","uploads","uploadsAll","selected","users","page","dom","localStorage","username","permissions","menusContainer","menus","currentView","views","type","album","pageNum","filters","all","checkboxes","lastSelected","upload","user","selectAlbumContainer","cache","albums","clipboardJS","lazyLoad","imageExts","videoExts","isTriggerLoading","fadingIn","albumTitleMaxLength","albumDescMaxLength","unhide","document","querySelector","classList","add","remove","onError","error","console","content","createElement","innerHTML","toString","swal","title","icon","onAxiosError","statusText","520","521","522","523","524","525","526","527","530","response","status","description","data","preparePage","verifyToken","window","location","reloadOnError","axios","post","then","success","text","removeItem","defaults","headers","common","prepareDashboard","catch","addEventListener","domClick","event","target","contains","preventDefault","itemMenus","selector","onclick","getUploads","deleteUploadsByNames","getAlbums","changeToken","changePassword","logout","params","group","getStatistics","getUsers","loop","i","item","call","Object","assign","trigger","currentTarget","push","length","moderator","getAlbumsSidebar","prepareShareX","updateTrigger","newState","parentNode","tagName","let","getItemID","element","parent","parseInt","dataset","id","includes","action","hasAttribute","stopPropagation","setUploadsView","addToAlbum","deleteUpload","addSelectedUploadsToAlbum","bulkDeleteUploads","displayPreview","uploadFiltersHelp","filterUploads","submitAlbum","editAlbum","deleteAlbum","createUser","editUser","disableUser","deleteUser","viewUserUploads","getNewToken","clearSelection","select","selectAll","focusJumpToPage","switchPage","fadeAndScroll","disableFading","clearTimeout","setTimeout","scrollIntoView","behavior","block","inline","func","goto","jumpToPage","checkValidity","parsed","value","isNaN","focus","undefined","url","minOffset","Date","getTimezoneOffset","get","pages","Math","ceil","count","files","autoPage","basedomain","pagination","paginate","filter","escape","extraControls","controls","unselected","hasExpiryDateColumn","some","file","expirydate","thumb","exec","extname","toLowerCase","name","original","prettyBytes","getPrettyBytes","size","prettyDate","getPrettyDate","timestamp","prettyExpiryDate","appendix","userid","albumid","table","div","className","appendChild","querySelectorAll","tr","ip","checked","update","view","isimage","isvideo","src","onload","body","onerror","video","autoplay","insertAdjacentElement","buttons","splice","indexOf","JSON","stringify","selectInBetween","lastElement","thisIndex","index","lastIndex","abs","shiftKey","suffix","substring","proceed","style","trim","replace","postBulkDeleteUploads","field","values","cb","failed","textArea","seen","names","split","map","trimmed","test","prototype","hasOwnProperty","join","objective","dangerMode","cancel","confirm","closeModal","fields","Array","isArray","timer","addUploadsToAlbum","ids","callback","choose","added","list","getElementsByTagName","removeAttribute","homeDomain","albumUrl","download","public","requestLink","identifier","purge","albumsContainer","oldAlbums","li","a","sendNewPassword","pass","password","admin","displayGroup","groups","keys","enabled","usage","groupOptions","g","resetPassword","autoClose","displayName","totalItems","itemsPerPage","currentPage","numPages","template","start","end","elementsToShow","step","stats","rows","types","_types","valKeys","j","number","toLocaleString","byte","byteUsage","used","total","round","toUpperCase","defineProperty","varArgs","arguments$1","arguments","TypeError","to","nextSource","nextKey","writable","configurable","documentElement","selectedKeys","ls","parse","ClipboardJS","on","LazyLoad"],"mappings":"AAEAA,IAAMC,OAAS,CACbC,MAAO,QACPC,SAAU,CACRC,QAAS,kBACTC,WAAY,sBAEdC,SAAU,CACRF,QAAS,kBACTC,WAAY,qBACZE,MAAO,kBAILC,KAAO,CAEXC,IAAK,KAGLP,MAAOQ,aAAaT,OAAOC,OAG3BS,SAAU,KACVC,YAAa,KAGbC,eAAgB,KAChBC,MAAO,GAEPC,YAAa,KACbC,MAAO,CAELZ,QAAS,CACPa,KAAMP,a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I1U,KAAKF,SAAS2U,EAAazO,IAAM+H,KAAK4G,MAAMD,IAGtD1U,KAAK4D,cAEL5D,KAAKqB,YAAc,IAAIuT,YAAY,iBAEnC5U,KAAKqB,YAAYwT,GAAG,WAAS,WAC3B,OAAOnS,KAAK,GAAI,yCAA0C,UAAW,CACnEkL,SAAS,EACTyC,MAAO,UAIXrQ,KAAKqB,YAAYwT,GAAG,QAAS7U,KAAKmC,SAElCnC,KAAKsB,SAAW,IAAIwT","file":"dashboard.js","sourcesContent":["/* global swal, axios, ClipboardJS, LazyLoad */\n\nconst lsKeys = {\n token: 'token',\n viewType: {\n uploads: 'viewTypeUploads',\n uploadsAll: 'viewTypeUploadsAll'\n },\n selected: {\n uploads: 'selectedUploads',\n uploadsAll: 'selectedUploadsAll',\n users: 'selectedUsers'\n }\n}\n\nconst page = {\n // #page\n dom: null,\n\n // user token\n token: localStorage[lsKeys.token],\n\n // from api/tokens/verify\n username: null,\n permissions: null,\n\n // sidebar menus\n menusContainer: null,\n menus: [],\n\n currentView: null,\n views: {\n // config of uploads view\n uploads: {\n type: localStorage[lsKeys.viewType.uploads],\n album: null, // album's id\n pageNum: null // page num\n },\n // config of uploads view (all)\n uploadsAll: {\n type: localStorage[lsKeys.viewType.uploadsAll],\n filters: null, // uploads' filters\n pageNum: null, // page num\n all: true\n },\n // config of users view\n users: {\n filters: null, // users' filters\n pageNum: null\n }\n },\n\n // id of selected items (shared across pages and will be synced with localStorage)\n selected: {\n uploads: [],\n uploadsAll: [],\n users: []\n },\n checkboxes: {\n uploads: [],\n uploadsAll: [],\n users: []\n },\n lastSelected: {\n upload: null,\n uploadsAll: null,\n user: null\n },\n\n // select album dom for dialogs/modals\n selectAlbumContainer: null,\n\n // cache for dialogs/modals\n cache: {\n uploads: {},\n albums: {},\n users: {}\n },\n\n clipboardJS: null,\n lazyLoad: null,\n\n imageExts: ['.webp', '.jpg', '.jpeg', '.gif', '.png', '.tiff', '.tif', '.svg'],\n // some of these extensions can not be played directly in browsers\n videoExts: ['.webm', '.mp4', '.wmv', '.avi', '.mov', '.mkv'],\n\n isTriggerLoading: null,\n fadingIn: null,\n\n albumTitleMaxLength: 70,\n albumDescMaxLength: 4000\n}\n\npage.unhide = () => {\n document.querySelector('#loader').classList.add('is-hidden')\n document.querySelector('#dashboard').classList.remove('is-hidden')\n}\n\n// Handler for regular JS errors\npage.onError = error => {\n console.error(error)\n\n const content = document.createElement('div')\n content.innerHTML = `${error.toString()}`\n return swal({\n title: 'An error occurred!',\n icon: 'error',\n content\n })\n}\n\n// Handler for Axios errors\npage.onAxiosError = error => {\n console.error(error)\n\n // Better Cloudflare errors\n const cloudflareErrors = {\n 520: 'Unknown Error',\n 521: 'Web Server Is Down',\n 522: 'Connection Timed Out',\n 523: 'Origin Is Unreachable',\n 524: 'A Timeout Occurred',\n 525: 'SSL Handshake Failed',\n 526: 'Invalid SSL Certificate',\n 527: 'Railgun Error',\n 530: 'Origin DNS Error'\n }\n\n const statusText = cloudflareErrors[error.response.status] || error.response.statusText\n const description = error.response.data && error.response.data.description\n ? error.response.data.description\n : 'There was an error with the request, please check the console for more information.'\n\n return swal(`${error.response.status} ${statusText}`, description, 'error')\n}\n\npage.preparePage = () => {\n if (page.token)\n page.verifyToken(page.token, true)\n else\n window.location = 'auth'\n}\n\npage.verifyToken = (token, reloadOnError) => {\n axios.post('api/tokens/verify', { token }).then(response => {\n if (response.data.success === false)\n return swal({\n title: 'An error occurred!',\n text: response.data.description,\n icon: 'error'\n }).then(() => {\n if (!reloadOnError) return\n localStorage.removeItem(lsKeys.token)\n window.location = 'auth'\n })\n\n axios.defaults.headers.common.token = token\n localStorage[lsKeys.token] = token\n\n page.token = token\n page.username = response.data.username\n page.permissions = response.data.permissions\n page.prepareDashboard()\n }).catch(page.onAxiosError)\n}\n\npage.prepareDashboard = () => {\n page.dom = document.querySelector('#page')\n\n // Capture all click events\n page.dom.addEventListener('click', page.domClick, true)\n\n // Capture all submit events\n page.dom.addEventListener('submit', event => {\n // Prevent default if necessary\n if (event.target && event.target.classList.contains('prevent-default'))\n return event.preventDefault()\n }, true)\n\n page.menusContainer = document.querySelector('#menu')\n\n // All item menus in the sidebar\n const itemMenus = [\n { selector: '#itemUploads', onclick: page.getUploads },\n { selector: '#itemDeleteUploadsByNames', onclick: page.deleteUploadsByNames },\n { selector: '#itemManageAlbums', onclick: page.getAlbums },\n { selector: '#itemManageToken', onclick: page.changeToken },\n { selector: '#itemChangePassword', onclick: page.changePassword },\n { selector: '#itemLogout', onclick: page.logout },\n { selector: '#itemManageUploads', onclick: page.getUploads, params: { all: true }, group: 'moderator' },\n { selector: '#itemStatistics', onclick: page.getStatistics, group: 'admin' },\n { selector: '#itemManageUsers', onclick: page.getUsers, group: 'admin' }\n ]\n\n for (let i = 0; i < itemMenus.length; i++) {\n // Skip item menu if not enough permission\n if (itemMenus[i].group && !page.permissions[itemMenus[i].group])\n continue\n\n // Add onclick event listener\n const item = document.querySelector(itemMenus[i].selector)\n item.addEventListener('click', event => {\n // This class name isn't actually being applied fast enough\n if (page.menusContainer.classList.contains('is-loading'))\n return\n\n // eslint-disable-next-line compat/compat\n itemMenus[i].onclick.call(null, Object.assign({\n trigger: event.currentTarget\n }, itemMenus[i].params || {}))\n })\n\n item.classList.remove('is-hidden')\n page.menus.push(item)\n }\n\n // If at least a moderator, show administration section\n if (page.permissions.moderator) {\n document.querySelector('#itemLabelAdmin').classList.remove('is-hidden')\n document.querySelector('#itemListAdmin').classList.remove('is-hidden')\n }\n\n // Update text of logout button\n document.querySelector('#itemLogout').innerHTML = `Logout ( ${page.username} )`\n\n // Finally display dashboard\n page.unhide()\n\n // Load albums sidebar\n page.getAlbumsSidebar()\n\n if (typeof page.prepareShareX === 'function')\n page.prepareShareX()\n}\n\npage.logout = params => {\n page.updateTrigger(params.trigger, 'active')\n localStorage.removeItem(lsKeys.token)\n window.location = 'auth'\n}\n\npage.updateTrigger = (trigger, newState) => {\n if (!trigger) return\n\n // Disable menus container when loading\n if (newState === 'loading')\n page.menusContainer.classList.add('is-loading')\n else\n page.menusContainer.classList.remove('is-loading')\n\n if (newState === 'loading') {\n trigger.classList.add('is-loading')\n } else if (newState === 'active') {\n if (trigger.parentNode.tagName !== 'LI')\n return\n for (let i = 0; i < page.menus.length; i++)\n page.menus[i].classList.remove('is-active')\n trigger.classList.remove('is-loading')\n trigger.classList.add('is-active')\n } else {\n trigger.classList.remove('is-loading')\n trigger.classList.remove('is-active')\n }\n}\n\npage.getItemID = element => {\n // This expects the item's parent to have the item's ID\n let parent = element.parentNode\n // If the element is part of a set of controls, use the container's parent instead\n if (element.parentNode.classList.contains('controls')) parent = parent.parentNode\n return parseInt(parent.dataset.id)\n}\n\npage.domClick = event => {\n // We are processing clicks this way to avoid using \"onclick\" attribute\n // Apparently we will need to use \"unsafe-inline\" for \"script-src\" directive\n // of Content Security Policy (CSP), if we want to use \"onclick\" attribute\n // Though I think that only applies to some browsers (?)\n // Of course it wouldn't have mattered if we didn't use CSP to begin with\n // Anyway, I personally would rather not use \"onclick\" attribute\n let element = event.target\n if (!element) return\n\n // Delegate click events to their A or BUTTON parents\n if (['I'].includes(element.tagName) && ['SPAN'].includes(element.parentNode.tagName))\n element = element.parentNode\n if (['SPAN'].includes(element.tagName) && ['A', 'BUTTON'].includes(element.parentNode.tagName))\n element = element.parentNode\n\n // Skip elements that have no action data\n if (!element.dataset || !element.dataset.action) return\n\n // Skip disabled elements\n if (element.hasAttribute('disabled')) return\n\n event.stopPropagation() // maybe necessary\n const id = page.getItemID(element)\n const action = element.dataset.action\n\n switch (action) {\n // Uploads\n case 'view-list':\n return page.setUploadsView('list', element)\n case 'view-thumbs':\n return page.setUploadsView('thumbs', element)\n case 'add-to-album':\n return page.addToAlbum(id)\n case 'delete-upload':\n return page.deleteUpload(id)\n case 'add-selected-uploads-to-album':\n return page.addSelectedUploadsToAlbum()\n case 'bulk-delete-uploads':\n return page.bulkDeleteUploads()\n case 'display-preview':\n return page.displayPreview(id)\n // Manage uploads\n case 'upload-filters-help':\n return page.uploadFiltersHelp(element)\n case 'filter-uploads':\n return page.filterUploads(element)\n // Manage your albums\n case 'submit-album':\n return page.submitAlbum(element)\n case 'edit-album':\n return page.editAlbum(id)\n case 'delete-album':\n return page.deleteAlbum(id)\n // Manage users\n case 'create-user':\n return page.createUser()\n case 'edit-user':\n return page.editUser(id)\n case 'disable-user':\n return page.disableUser(id)\n case 'delete-user':\n return page.deleteUser(id)\n case 'view-user-uploads':\n return page.viewUserUploads(id, element)\n /* // WIP\n case 'user-filters-help':\n return page.userFiltersHelp(element)\n case 'filter-users':\n return page.filterUsers(element)\n */\n // Others\n case 'get-new-token':\n return page.getNewToken(element)\n // Uploads & Users\n case 'clear-selection':\n return page.clearSelection()\n case 'select':\n return page.select(element, event)\n case 'select-all':\n return page.selectAll(element)\n case 'page-ellipsis':\n return page.focusJumpToPage()\n case 'page-prev':\n case 'page-next':\n case 'page-goto':\n case 'jump-to-page':\n return page.switchPage(action, element)\n }\n}\n\npage.fadeAndScroll = disableFading => {\n if (page.fadingIn) {\n clearTimeout(page.fadingIn)\n page.dom.classList.remove('fade-in')\n }\n\n if (!disableFading) {\n page.dom.classList.add('fade-in')\n page.fadingIn = setTimeout(() => {\n page.dom.classList.remove('fade-in')\n }, 500)\n }\n\n page.dom.scrollIntoView({\n behavior: disableFading ? 'auto' : 'smooth',\n block: 'start',\n inline: 'nearest'\n })\n}\n\npage.switchPage = (action, element) => {\n // eslint-disable-next-line compat/compat\n const params = Object.assign({\n trigger: element\n }, page.views[page.currentView])\n\n const func = page.currentView === 'users' ? page.getUsers : page.getUploads\n\n switch (action) {\n case 'page-prev':\n params.pageNum = page.views[page.currentView].pageNum - 1\n if (params.pageNum < 0)\n return swal('An error occurred!', 'This is already the first page.', 'error')\n return func(params)\n case 'page-next':\n params.pageNum = page.views[page.currentView].pageNum + 1\n return func(params)\n case 'page-goto':\n params.pageNum = parseInt(element.dataset.goto)\n return func(params)\n case 'jump-to-page': {\n const jumpToPage = document.querySelector('#jumpToPage')\n if (!jumpToPage.checkValidity()) return\n const parsed = parseInt(jumpToPage.value)\n params.pageNum = isNaN(parsed) ? 0 : (parsed - 1)\n if (params.pageNum < 0) params.pageNum = 0\n return func(params)\n }\n }\n}\n\npage.focusJumpToPage = () => {\n const element = document.querySelector('#jumpToPage')\n if (!element) return\n element.focus()\n element.select()\n}\n\npage.getUploads = (params = {}) => {\n if (params === undefined)\n params = {}\n\n if ((params.all || params.filters) && !page.permissions.moderator)\n return swal('An error occurred!', 'You can not do this!', 'error')\n\n page.updateTrigger(params.trigger, 'loading')\n\n if (typeof params.pageNum !== 'number' || params.pageNum < 0)\n params.pageNum = 0\n\n const url = params.album !== undefined\n ? `api/album/${params.album}/${params.pageNum}`\n : `api/uploads/${params.pageNum}`\n\n const headers = {\n all: params.all ? '1' : '',\n filters: params.filters || ''\n }\n\n // Send client timezone offset if using date filter\n // Server will pretend client is on UTC if missing\n if (headers.filters.includes('date:') || headers.filters.includes('expiry:'))\n headers.minOffset = new Date().getTimezoneOffset()\n\n axios.get(url, { headers }).then(response => {\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n page.updateTrigger(params.trigger)\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n const pages = Math.ceil(response.data.count / 25)\n const files = response.data.files\n if (params.pageNum && (files.length === 0))\n if (params.autoPage) {\n params.pageNum = pages - 1\n return page.getUploads(params)\n } else {\n page.updateTrigger(params.trigger)\n return swal('An error occurred!', `There are no more uploads to populate page ${params.pageNum + 1}.`, 'error')\n }\n\n page.currentView = params.all ? 'uploadsAll' : 'uploads'\n page.cache.uploads = {}\n\n const albums = response.data.albums\n const users = response.data.users\n const basedomain = response.data.basedomain\n const pagination = page.paginate(response.data.count, 25, params.pageNum)\n\n let filter = '
    '\n if (params.all)\n filter = `\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n `\n const extraControls = `\n
    \n ${filter}\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n `\n\n const controls = `\n
    \n
    \n \n
    \n \n \n \n \n \n ${params.all ? '' : `\n \n \n \n \n `}\n \n \n \n \n Bulk delete\n \n
    \n
    \n `\n\n // Whether there are any unselected items\n let unselected = false\n\n const hasExpiryDateColumn = files.some(file => {\n return file.expirydate !== undefined\n })\n\n for (let i = 0; i < files.length; i++) {\n // Build full URLs\n files[i].file = `${basedomain}/${files[i].name}`\n if (files[i].thumb)\n files[i].thumb = `${basedomain}/${files[i].thumb}`\n\n // Determine types\n files[i].type = 'other'\n const exec = /.[\\w]+(\\?|$)/.exec(files[i].file)\n const extname = exec && exec[0] ? exec[0].toLowerCase() : null\n if (page.imageExts.includes(extname))\n files[i].type = 'picture'\n else if (page.videoExts.includes(extname))\n files[i].type = 'video'\n\n // Cache bare minimum data for thumbnails viewer\n page.cache.uploads[files[i].id] = {\n name: files[i].name,\n thumb: files[i].thumb,\n original: files[i].file,\n type: files[i].type\n }\n\n // Prettify\n files[i].prettyBytes = page.getPrettyBytes(parseInt(files[i].size))\n files[i].prettyDate = page.getPrettyDate(new Date(files[i].timestamp * 1000))\n\n if (hasExpiryDateColumn)\n files[i].prettyExpiryDate = files[i].expirydate\n ? page.getPrettyDate(new Date(files[i].expirydate * 1000))\n : null\n\n // Update selected status\n files[i].selected = page.selected[page.currentView].includes(files[i].id)\n if (!files[i].selected) unselected = true\n\n // Appendix (display album or user)\n if (params.all)\n files[i].appendix = files[i].userid\n ? users[files[i].userid] || ''\n : ''\n else if (params.album === undefined)\n files[i].appendix = files[i].albumid\n ? albums[files[i].albumid] || ''\n : ''\n }\n\n if (page.views[page.currentView].type === 'thumbs') {\n page.dom.innerHTML = `\n ${pagination}\n ${extraControls}\n ${controls}\n
    \n
    \n ${pagination}\n `\n\n const table = document.querySelector('#table')\n\n for (let i = 0; i < files.length; i++) {\n const upload = files[i]\n const div = document.createElement('div')\n div.className = 'image-container column'\n div.dataset.id = upload.id\n\n if (upload.thumb !== undefined)\n div.innerHTML = `\"${upload.name}\"`\n else\n div.innerHTML = `

    ${upload.extname || 'N/A'}

    `\n\n div.innerHTML += `\n \n
    \n ${upload.thumb ? `\n \n \n \n \n ` : ''}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    \n
    \n

    ${upload.name}

    \n

    ${upload.appendix ? `${upload.appendix} – ` : ''}${upload.prettyBytes}

    \n ${hasExpiryDateColumn && upload.prettyExpiryDate ? `\n

    EXP: ${upload.prettyExpiryDate}

    ` : ''}\n
    \n `\n\n table.appendChild(div)\n page.checkboxes[page.currentView] = table.querySelectorAll('.checkbox[data-action=\"select\"]')\n }\n } else {\n page.dom.innerHTML = `\n ${pagination}\n ${extraControls}\n ${controls}\n
    \n \n \n \n \n \n ${params.album === undefined ? `` : ''}\n \n ${params.all ? '' : ''}\n \n ${hasExpiryDateColumn ? '' : ''}\n \n \n \n \n \n
    File name${params.all ? 'User' : 'Album'}SizeIPDateExpiry date
    \n
    \n ${pagination}\n `\n\n const table = document.querySelector('#table')\n\n for (let i = 0; i < files.length; i++) {\n const upload = files[i]\n const tr = document.createElement('tr')\n tr.dataset.id = upload.id\n tr.innerHTML = `\n \n ${upload.name}\n ${params.album === undefined ? `${upload.appendix}` : ''}\n ${upload.prettyBytes}\n ${params.all ? `${upload.ip || ''}` : ''}\n ${upload.prettyDate}\n ${hasExpiryDateColumn ? `${upload.prettyExpiryDate || '-'}` : ''}\n \n \n \n \n \n \n \n \n \n \n \n ${params.all ? '' : `\n \n \n \n \n `}\n \n \n \n \n \n \n `\n\n table.appendChild(tr)\n page.checkboxes[page.currentView] = table.querySelectorAll('.checkbox[data-action=\"select\"]')\n }\n }\n\n const selectAll = document.querySelector('#selectAll')\n if (selectAll && !unselected && files.length) {\n selectAll.checked = true\n selectAll.title = 'Unselect all'\n }\n\n if (page.views[page.currentView].type === 'thumbs') {\n page.fadeAndScroll(true)\n page.lazyLoad.update()\n } else {\n page.fadeAndScroll()\n }\n\n page.updateTrigger(params.trigger, 'active')\n\n if (page.currentView === 'uploads')\n page.views.uploads.album = params.album\n if (page.currentView === 'uploadsAll')\n page.views.uploadsAll.filters = params.filters\n page.views[page.currentView].pageNum = files.length ? params.pageNum : 0\n }).catch(error => {\n page.updateTrigger(params.trigger)\n page.onAxiosError(error)\n })\n}\n\npage.setUploadsView = (view, element) => {\n localStorage[lsKeys.viewType[page.currentView]] = view\n page.views[page.currentView].type = view\n\n // eslint-disable-next-line compat/compat\n page.getUploads(Object.assign({\n trigger: element\n }, page.views[page.currentView]))\n}\n\npage.displayPreview = id => {\n const file = page.cache.uploads[id]\n if (!file.thumb) return\n\n const div = document.createElement('div')\n div.innerHTML = `\n
    \n \n
    \n \n
    \n
    \n `\n\n if (file.original) {\n const exec = /.[\\w]+(\\?|$)/.exec(file.original)\n const extname = exec && exec[0] ? exec[0].toLowerCase() : null\n const isimage = page.imageExts.includes(extname)\n const isvideo = !isimage && page.videoExts.includes(extname)\n\n if (isimage || isvideo) {\n div.innerHTML += `\n \n `\n\n div.querySelector('#swalOriginal').addEventListener('click', event => {\n const trigger = event.currentTarget\n if (trigger.classList.contains('is-danger'))\n return\n\n trigger.classList.add('is-loading')\n const thumb = div.querySelector('#swalThumb')\n\n if (isimage) {\n thumb.src = file.original\n thumb.onload = () => {\n trigger.classList.add('is-hidden')\n document.body.querySelector('.swal-overlay .swal-modal:not(.is-expanded)').classList.add('is-expanded')\n }\n thumb.onerror = event => {\n event.currentTarget.classList.add('is-hidden')\n trigger.className = 'button is-danger is-fullwidth'\n trigger.innerHTML = `\n \n \n \n Unable to load original\n `\n }\n } else if (isvideo) {\n thumb.classList.add('is-hidden')\n const video = document.createElement('video')\n video.id = 'swalVideo'\n video.controls = true\n video.autoplay = true\n video.src = file.original\n thumb.insertAdjacentElement('afterend', video)\n\n trigger.classList.add('is-hidden')\n document.body.querySelector('.swal-overlay .swal-modal:not(.is-expanded)').classList.add('is-expanded')\n }\n })\n }\n }\n\n return swal({\n content: div,\n buttons: false\n }).then(() => {\n // Destroy video, if necessary\n const video = div.querySelector('#swalVideo')\n if (video) video.remove()\n\n // Restore modal size\n document.body.querySelector('.swal-overlay .swal-modal').classList.remove('is-expanded')\n })\n}\n\npage.selectAll = element => {\n for (let i = 0; i < page.checkboxes[page.currentView].length; i++) {\n const id = page.getItemID(page.checkboxes[page.currentView][i])\n if (isNaN(id)) continue\n if (page.checkboxes[page.currentView][i].checked !== element.checked) {\n page.checkboxes[page.currentView][i].checked = element.checked\n if (page.checkboxes[page.currentView][i].checked)\n page.selected[page.currentView].push(id)\n else\n page.selected[page.currentView].splice(page.selected[page.currentView].indexOf(id), 1)\n }\n }\n\n if (page.selected[page.currentView].length)\n localStorage[lsKeys.selected[page.currentView]] = JSON.stringify(page.selected[page.currentView])\n else\n delete localStorage[lsKeys.selected[page.currentView]]\n\n element.title = element.checked ? 'Unselect all' : 'Select all'\n}\n\npage.selectInBetween = (element, lastElement) => {\n const thisIndex = parseInt(element.dataset.index)\n const lastIndex = parseInt(lastElement.dataset.index)\n\n const distance = Math.abs(thisIndex - lastIndex)\n if (distance < 2)\n return\n\n for (let i = 0; i < page.checkboxes[page.currentView].length; i++)\n if ((thisIndex > lastIndex && i > lastIndex && i < thisIndex) ||\n (thisIndex < lastIndex && i > thisIndex && i < lastIndex)) {\n // Check or uncheck depending on the state of the initial checkbox\n const checked = page.checkboxes[page.currentView][i].checked = lastElement.checked\n const id = page.getItemID(page.checkboxes[page.currentView][i])\n if (!page.selected[page.currentView].includes(id) && checked)\n page.selected[page.currentView].push(id)\n else if (page.selected[page.currentView].includes(id) && !checked)\n page.selected[page.currentView].splice(page.selected[page.currentView].indexOf(id), 1)\n }\n}\n\npage.select = (element, event) => {\n const id = page.getItemID(element)\n if (isNaN(id)) return\n\n const lastSelected = page.lastSelected[page.currentView]\n if (event.shiftKey && lastSelected) {\n page.selectInBetween(element, lastSelected)\n // Check or uncheck depending on the state of the initial checkbox\n element.checked = lastSelected.checked\n } else {\n page.lastSelected[page.currentView] = element\n }\n\n if (!page.selected[page.currentView].includes(id) && element.checked)\n page.selected[page.currentView].push(id)\n else if (page.selected[page.currentView].includes(id) && !element.checked)\n page.selected[page.currentView].splice(page.selected[page.currentView].indexOf(id), 1)\n\n // Update local storage\n if (page.selected[page.currentView].length)\n localStorage[lsKeys.selected[page.currentView]] = JSON.stringify(page.selected[page.currentView])\n else\n delete localStorage[lsKeys.selected[page.currentView]]\n}\n\npage.clearSelection = () => {\n const selected = page.selected[page.currentView]\n const type = page.currentView === 'users' ? 'users' : 'uploads'\n const count = selected.length\n if (!count)\n return swal('An error occurred!', `You have not selected any ${type}.`, 'error')\n\n const suffix = count === 1 ? type.substring(0, type.length - 1) : type\n return swal({\n title: 'Are you sure?',\n text: `You are going to unselect ${count} ${suffix}.`,\n buttons: true\n }).then(proceed => {\n if (!proceed) return\n\n const checkboxes = page.checkboxes[page.currentView]\n for (let i = 0; i < checkboxes.length; i++)\n if (checkboxes[i].checked)\n checkboxes[i].checked = false\n\n page.selected[page.currentView] = []\n delete localStorage[lsKeys.selected[page.currentView]]\n\n const selectAll = document.querySelector('#selectAll')\n if (selectAll) selectAll.checked = false\n\n return swal('Cleared selection!', `Unselected ${count} ${suffix}.`, 'success')\n })\n}\n\npage.uploadFiltersHelp = element => {\n const content = document.createElement('div')\n content.style = 'text-align: left'\n content.innerHTML = `\n There are 2 filter keys, namely user (username) and ip.\n These keys can be specified more than once.\n For usernames with whitespaces, wrap them with double quotes (\").\n\n There are 2 special filter keys, namely user:- and ip:-, to match uploads by non-registered users and have no IPs respectively.\n\n To exclude certain users/ips while still listing every other uploads, add negation sign (-) before the keys.\n Unfortunately, this will not show uploads by non-registered users or have no IPs as well, instead you need to also use the special filter keys if you want to include them.\n\n There are 2 range keys: date (upload date) and expiry (expiry date).\n Their format is: YYYY/MM/DD HH:MM:SS-YYYY/MM/DD HH:MM:SS (\"to\" date is optional).\n If any of the subsequent date or time units are not specified, their first value will be used (e.g. January for month, 1 for day, and so on).\n If only time is specified, today's date will be used.\n Meaning the following can be accepted: 2020/01/01 01:23, 2018/01/01 06, 2019/11, 12:34:56.\n These keys can only be specified once each.\n\n Matches can also be sorted with orderby:columnName[:d[escending]] keys.\n This key require internal column names used in the database (id, userid, and so on), but there are 2 shortcuts, namely date for timestamp column and expiry for expirydate column.\n This key can also be specified more than once, where their order will decide the sorting steps.\n\n Any leftover keywords which do not use keys will be matched against the matches' file names.\n Excluding certain keywords is also supported by adding negation sign (-) before the keywords.\n\n Internals:\n First, it will filter uploads matching ANY of the supplied filter keys AND/OR special filter keys, if any.\n Second, it will refine the matches using the supplied date AND/OR expiry range keys, if any.\n Third, it will refine the matches using the leftover non-keyed keywords, if any.\n Finally, it will sort the matches using the supplied orderby keys, if any.\n\n Examples:\n Uploads from user named \"demo\":\n user:demo\n Uploads from users named \"demo\" AND/OR \"John Doe\" AND/OR non-registered users:\n user:demo user:\"John Doe\" user:-\n ALL uploads, including from non-registered users, but NOT the ones from user named \"demo\":\n -user:demo user:-\n Uploads from IP \"127.0.0.1\" AND which file names match \"*.rar\" OR \"*.zip\":\n ip:127.0.0.1 *.rar *.zip\n Uploads uploaded since \"1 June 2019 00:00:00\":\n date:2019/06\n Uploads uploaded between \"7 April 2020 00:00:00\" and \"7 April 2020 23:59:59\":\n date:2020/04/07-2020/04/07 23:59:59\n Uploads which file names match \"*.gz\" but NOT \"*.tar.gz\":\n *.gz -*.tar.gz\n Sort matches by \"size\" column in ascending and descending order respectively:\n user:\"John Doe\" orderby:size\n *.mp4 user:- orderby:size:d\n\n Friendly reminder: This window can be scrolled up!\n `.trim().replace(/^ {6}/gm, '').replace(/\\n/g, '
    ')\n\n swal({ content }).then(() => {\n // Restore modal size\n document.body.querySelector('.swal-overlay .swal-modal').classList.remove('is-expanded')\n })\n\n // Expand modal size\n document.body.querySelector('.swal-overlay .swal-modal:not(.is-expanded)').classList.add('is-expanded')\n}\n\npage.filterUploads = element => {\n const filters = document.querySelector('#filters').value.trim()\n page.getUploads({ all: true, filters }, element)\n}\n\npage.viewUserUploads = (id, element) => {\n const user = page.cache.users[id]\n if (!user) return\n element.classList.add('is-loading')\n // Wrap username in quotes if it contains whitespaces\n const username = user.username.includes(' ')\n ? `\"${user.username}\"`\n : user.username\n page.getUploads({\n all: true,\n filters: `user:${username}`,\n trigger: document.querySelector('#itemManageUploads')\n })\n}\n\npage.deleteUpload = id => {\n page.postBulkDeleteUploads({\n all: page.currentView === 'uploadsAll',\n field: 'id',\n values: [id],\n cb (failed) {\n // Remove from remembered checkboxes if necessary\n if (!failed.length && page.selected[page.currentView].includes(id))\n page.selected[page.currentView].splice(page.selected[page.currentView].indexOf(id), 1)\n\n // Update local storage\n if (page.selected[page.currentView].length)\n localStorage[lsKeys.selected[page.currentView]] = JSON.stringify(page.selected[page.currentView])\n else\n delete localStorage[lsKeys.selected[page.currentView]]\n\n // Reload upload list\n // eslint-disable-next-line compat/compat\n page.getUploads(Object.assign({\n autoPage: true\n }, page.views[page.currentView]))\n }\n })\n}\n\npage.bulkDeleteUploads = () => {\n const count = page.selected[page.currentView].length\n if (!count)\n return swal('An error occurred!', 'You have not selected any uploads.', 'error')\n\n page.postBulkDeleteUploads({\n all: page.currentView === 'uploadsAll',\n field: 'id',\n values: page.selected[page.currentView],\n cb (failed) {\n // Update state of checkboxes\n if (failed.length)\n page.selected[page.currentView] = page.selected[page.currentView]\n .filter(id => {\n return failed.includes(id)\n })\n else\n page.selected[page.currentView] = []\n\n // Update local storage\n if (page.selected[page.currentView].length)\n localStorage[lsKeys.selected[page.currentView]] = JSON.stringify(page.selected[page.currentView])\n else\n delete localStorage[lsKeys.selected[page.currentView]]\n\n // Reload uploads list\n // eslint-disable-next-line compat/compat\n page.getUploads(Object.assign({\n autoPage: true\n }, page.views[page.currentView]))\n }\n })\n}\n\npage.deleteUploadsByNames = (params = {}) => {\n let appendix = ''\n if (page.permissions.moderator)\n appendix = '
    Hint: You can use this feature to delete uploads by other users.'\n\n page.dom.innerHTML = `\n
    \n
    \n \n
    \n \n
    \n

    Separate each entry with a new line.${appendix}

    \n
    \n
    \n
    \n \n
    \n
    \n
    \n `\n page.fadeAndScroll()\n page.updateTrigger(params.trigger, 'active')\n\n document.querySelector('#submitBulkDelete').addEventListener('click', () => {\n const textArea = document.querySelector('#bulkDeleteNames')\n\n // Clean up\n const seen = {}\n const names = textArea.value\n .split(/\\r?\\n/)\n .map(name => {\n const trimmed = name.trim()\n return /^[^\\s]+$/.test(trimmed)\n ? trimmed\n : ''\n })\n .filter(name => {\n // Filter out invalid and duplicate names\n return (!name || Object.prototype.hasOwnProperty.call(seen, name))\n ? false\n : (seen[name] = true)\n })\n\n // Update textarea with cleaned names\n textArea.value = names.join('\\n')\n\n if (!names.length)\n return swal('An error occurred!', 'You have not entered any upload names.', 'error')\n\n page.postBulkDeleteUploads({\n all: true,\n field: 'name',\n values: names,\n cb (failed) {\n textArea.value = failed.join('\\n')\n }\n })\n })\n}\n\npage.postBulkDeleteUploads = (params = {}) => {\n const count = params.values.length\n\n const objective = `${params.values.length} upload${count === 1 ? '' : 's'}`\n const boldObjective = objective.replace(/^(\\d*)(.*)/, '$1$2')\n let text = `

    You won't be able to recover ${boldObjective}!

    `\n\n if (params.all) {\n const obj1 = count === 1 ? 'an upload' : 'some uploads'\n const obj2 = count === 1 ? 'another user' : 'other users'\n text += `\\n

    Warning: You may be nuking ${obj1} by ${obj2}!

    `\n }\n\n const content = document.createElement('div')\n content.innerHTML = text\n\n swal({\n title: 'Are you sure?',\n content,\n icon: 'warning',\n dangerMode: true,\n buttons: {\n cancel: true,\n confirm: {\n text: `Yes, nuke ${params.values.length === 1 ? 'it' : 'them'}!`,\n closeModal: false\n }\n }\n }).then(proceed => {\n if (!proceed) return\n\n axios.post('api/upload/bulkdelete', {\n field: params.fields,\n values: params.values\n }).then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n const failed = Array.isArray(response.data.failed) ? response.data.failed : []\n if (failed.length === params.values.length)\n swal('An error occurred!', `Unable to delete any of the ${objective}.`, 'error')\n else if (failed.length && failed.length < params.values.length)\n swal('Warning!', `From ${objective}, unable to delete ${failed.length} of them.`, 'warning')\n else\n swal('Deleted!', `${objective} ${count === 1 ? 'has' : 'have'} been deleted.`, 'success', {\n buttons: false,\n timer: 1500\n })\n\n if (typeof params.cb === 'function')\n params.cb(failed)\n }).catch(page.onAxiosError)\n })\n}\n\npage.addSelectedUploadsToAlbum = () => {\n if (page.currentView !== 'uploads')\n return\n\n const count = page.selected[page.currentView].length\n if (!count)\n return swal('An error occurred!', 'You have not selected any uploads.', 'error')\n\n page.addUploadsToAlbum(page.selected[page.currentView], failed => {\n if (!failed) return\n if (failed.length)\n page.selected[page.currentView] = page.selected[page.currentView].filter(id => {\n return failed.includes(id)\n })\n else\n page.selected[page.currentView] = []\n\n localStorage[lsKeys.selected[page.currentView]] = JSON.stringify(page.selected[page.currentView])\n page.getUploads(page.views[page.currentView])\n })\n}\n\npage.addToAlbum = id => {\n page.addUploadsToAlbum([id], failed => {\n if (!failed) return\n page.getUploads(page.views[page.currentView])\n })\n}\n\npage.addUploadsToAlbum = (ids, callback) => {\n const count = ids.length\n\n const content = document.createElement('div')\n content.innerHTML = `\n
    \n

    You are about to add ${count} upload${count === 1 ? '' : 's'} to an album.

    \n

    If an upload is already in an album, it will be moved.

    \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n `\n\n swal({\n icon: 'warning',\n content,\n buttons: {\n cancel: true,\n confirm: {\n text: 'OK',\n closeModal: false\n }\n }\n }).then(choose => {\n if (!choose) return\n\n const albumid = parseInt(document.querySelector('#swalAlbum').value)\n if (isNaN(albumid))\n return swal('An error occurred!', 'You did not choose an album.', 'error')\n\n axios.post('api/albums/addfiles', {\n ids,\n albumid\n }).then(add => {\n if (!add) return\n\n if (add.data.success === false) {\n if (add.data.description === 'No token provided')\n page.verifyToken(page.token)\n else\n swal('An error occurred!', add.data.description, 'error')\n\n return\n }\n\n let added = ids.length\n if (add.data.failed && add.data.failed.length)\n added -= add.data.failed.length\n\n const suffix = `upload${ids.length === 1 ? '' : 's'}`\n if (!added)\n return swal('An error occurred!', `Could not add the ${suffix} to the album.`, 'error')\n\n swal('Woohoo!', `Successfully ${albumid < 0 ? 'removed' : 'added'} ${added} ${suffix} ${albumid < 0 ? 'from' : 'to'} the album.`, 'success', {\n buttons: false,\n timer: 1500\n })\n callback(add.data.failed)\n }).catch(page.onAxiosError)\n })\n\n // Get albums list then update content of swal\n axios.get('api/albums').then(list => {\n if (list.data.success === false) {\n if (list.data.description === 'No token provided')\n page.verifyToken(page.token)\n else\n swal('An error occurred!', list.data.description, 'error')\n\n return\n }\n\n // If the prompt was replaced, the container would be missing\n const select = document.querySelector('#swalAlbum')\n if (!select) return\n\n select.innerHTML += list.data.albums\n .map(album => {\n return ``\n })\n .join('\\n')\n\n select.getElementsByTagName('option')[1].innerHTML = 'Choose an album'\n select.removeAttribute('disabled')\n }).catch(page.onAxiosError)\n}\n\npage.getAlbums = (params = {}) => {\n page.updateTrigger(params.trigger, 'loading')\n\n axios.get('api/albums').then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n page.updateTrigger(params.trigger)\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n page.cache.albums = {}\n\n page.dom.innerHTML = `\n

    Create new album

    \n
    \n
    \n
    \n \n
    \n

    Max length is ${page.albumTitleMaxLength} characters.

    \n
    \n
    \n
    \n \n
    \n

    Max length is ${page.albumDescMaxLength} characters.

    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n

    List of albums

    \n
    \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    IDNameFilesCreated atPublic link
    \n
    \n `\n\n const homeDomain = response.data.homeDomain\n const table = document.querySelector('#table')\n\n for (let i = 0; i < response.data.albums.length; i++) {\n const album = response.data.albums[i]\n const albumUrl = `${homeDomain}/a/${album.identifier}`\n\n // Prettify\n album.prettyDate = page.getPrettyDate(new Date(album.timestamp * 1000))\n\n page.cache.albums[album.id] = {\n name: album.name,\n download: album.download,\n public: album.public,\n description: album.description\n }\n\n const tr = document.createElement('tr')\n tr.innerHTML = `\n ${album.id}\n ${album.name}\n ${album.files}\n ${album.prettyDate}\n ${albumUrl}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n `\n\n table.appendChild(tr)\n }\n page.fadeAndScroll()\n page.updateTrigger(params.trigger, 'active')\n }).catch(error => {\n page.updateTrigger(params.trigger)\n page.onAxiosError(error)\n })\n}\n\npage.editAlbum = id => {\n const album = page.cache.albums[id]\n if (!album) return\n\n const div = document.createElement('div')\n div.innerHTML = `\n
    \n
    \n \n
    \n

    Max length is ${page.albumTitleMaxLength} characters.

    \n
    \n
    \n
    \n \n
    \n

    Max length is ${page.albumDescMaxLength} characters.

    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n `\n\n swal({\n title: 'Edit album',\n icon: 'info',\n content: div,\n buttons: {\n cancel: true,\n confirm: {\n closeModal: false\n }\n }\n }).then(value => {\n if (!value) return\n\n axios.post('api/albums/edit', {\n id,\n name: document.querySelector('#swalName').value.trim(),\n description: document.querySelector('#swalDescription').value.trim(),\n download: document.querySelector('#swalDownload').checked,\n public: document.querySelector('#swalPublic').checked,\n requestLink: document.querySelector('#swalRequestLink').checked\n }).then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n if (response.data.identifier)\n swal('Success!', `Your album's new identifier is: ${response.data.identifier}.`, 'success')\n else if (response.data.name !== album.name)\n swal('Success!', `Your album was renamed to: ${response.data.name}.`, 'success')\n else\n swal('Success!', 'Your album was edited!', 'success', {\n buttons: false,\n timer: 1500\n })\n\n page.getAlbumsSidebar()\n page.getAlbums()\n }).catch(page.onAxiosError)\n })\n}\n\npage.deleteAlbum = id => {\n swal({\n title: 'Are you sure?',\n text: 'This won\\'t delete your uploads, only the album!',\n icon: 'warning',\n dangerMode: true,\n buttons: {\n cancel: true,\n confirm: {\n text: 'Yes, delete it!',\n closeModal: false\n },\n purge: {\n text: 'Umm, delete the uploads too please?',\n value: 'purge',\n className: 'swal-button--danger',\n closeModal: false\n }\n }\n }).then(proceed => {\n if (!proceed) return\n\n axios.post('api/albums/delete', {\n id,\n purge: proceed === 'purge'\n }).then(response => {\n if (response.data.success === false) {\n const failed = Array.isArray(response.data.failed)\n ? response.data.failed\n : []\n\n if (response.data.description === 'No token provided')\n return page.verifyToken(page.token)\n else if (failed.length)\n return swal('An error occurred!', `Unable to delete ${failed.length} of the album's upload${failed.length === 1 ? '' : 's'}.`, 'error')\n else\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n swal('Deleted!', 'Your album has been deleted.', 'success', {\n buttons: false,\n timer: 1500\n })\n page.getAlbumsSidebar()\n page.getAlbums()\n }).catch(page.onAxiosError)\n })\n}\n\npage.submitAlbum = element => {\n page.updateTrigger(element, 'loading')\n\n axios.post('api/albums', {\n name: document.querySelector('#albumName').value.trim(),\n description: document.querySelector('#albumDescription').value.trim()\n }).then(response => {\n if (!response) return\n\n page.updateTrigger(element)\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n swal('Woohoo!', 'Album was created successfully.', 'success', {\n buttons: false,\n timer: 1500\n })\n page.getAlbumsSidebar()\n page.getAlbums()\n }).catch(error => {\n page.updateTrigger(element)\n page.onAxiosError(error)\n })\n}\n\npage.getAlbumsSidebar = () => {\n axios.get('api/albums/sidebar').then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n const albumsContainer = document.querySelector('#albumsContainer')\n\n // Clear albums sidebar if necessary\n const oldAlbums = albumsContainer.querySelectorAll('li > a')\n if (oldAlbums.length) {\n for (let i = 0; i < oldAlbums.length; i++)\n page.menus.splice(page.menus.indexOf(oldAlbums[i]), 1)\n albumsContainer.innerHTML = ''\n }\n\n if (response.data.albums === undefined)\n return\n\n for (let i = 0; i < response.data.albums.length; i++) {\n const album = response.data.albums[i]\n const li = document.createElement('li')\n const a = document.createElement('a')\n a.id = album.id\n a.innerHTML = album.name\n a.className = 'is-relative'\n\n a.addEventListener('click', event => {\n page.getUploads({\n album: parseInt(event.currentTarget.id),\n trigger: event.currentTarget\n })\n })\n page.menus.push(a)\n\n li.appendChild(a)\n albumsContainer.appendChild(li)\n }\n }).catch(page.onAxiosError)\n}\n\npage.changeToken = (params = {}) => {\n page.dom.innerHTML = `\n
    \n \n
    \n
    \n \n
    \n
    \n
    \n \n `\n page.fadeAndScroll()\n page.updateTrigger(params.trigger, 'active')\n\n document.querySelector('#getNewToken').addEventListener('click', event => {\n const trigger = event.currentTarget\n page.updateTrigger(trigger, 'loading')\n axios.post('api/tokens/change').then(response => {\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n page.updateTrigger(trigger)\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n page.updateTrigger(trigger)\n swal({\n title: 'Woohoo!',\n text: 'Your token was successfully changed.',\n icon: 'success',\n buttons: false,\n timer: 1500\n }).then(() => {\n axios.defaults.headers.common.token = response.data.token\n localStorage[lsKeys.token] = response.data.token\n page.token = response.data.token\n page.changeToken()\n })\n }).catch(error => {\n page.updateTrigger(trigger)\n page.onAxiosError(error)\n })\n })\n}\n\npage.changePassword = (params = {}) => {\n page.dom.innerHTML = `\n
    \n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n `\n page.fadeAndScroll()\n page.updateTrigger(params.trigger, 'active')\n\n document.querySelector('#sendChangePassword').addEventListener('click', event => {\n if (!page.dom.querySelector('form').checkValidity()) return\n if (document.querySelector('#password').value === document.querySelector('#passwordConfirm').value)\n page.sendNewPassword(document.querySelector('#password').value, event.currentTarget)\n else\n swal({\n title: 'Password mismatch!',\n text: 'Your passwords do not match, please try again.',\n icon: 'error'\n })\n })\n}\n\npage.sendNewPassword = (pass, element) => {\n page.updateTrigger(element, 'loading')\n\n axios.post('api/password/change', { password: pass }).then(response => {\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n page.updateTrigger(element)\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n page.updateTrigger(element)\n swal({\n title: 'Woohoo!',\n text: 'Your password was successfully changed.',\n icon: 'success',\n buttons: false,\n timer: 1500\n }).then(() => {\n page.changePassword()\n })\n }).catch(error => {\n page.updateTrigger(element)\n page.onAxiosError(error)\n })\n}\n\npage.getUsers = (params = {}) => {\n page.updateTrigger(params.trigger, 'loading')\n\n if (params.pageNum === undefined)\n params.pageNum = 0\n\n if (!page.permissions.admin)\n return swal('An error occurred!', 'You can not do this!', 'error')\n\n const url = `api/users/${params.pageNum}`\n axios.get(url).then(response => {\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n page.updateTrigger(params.trigger)\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n const pages = Math.ceil(response.data.count / 25)\n if (params.pageNum && (response.data.users.length === 0))\n if (params.autoPage) {\n params.pageNum = pages - 1\n return page.getUsers(params)\n } else {\n page.updateTrigger(params.trigger)\n return swal('An error occurred!', `There are no more users to populate page ${params.pageNum + 1}.`, 'error')\n }\n\n page.currentView = 'users'\n page.cache.users = {}\n\n const pagination = page.paginate(response.data.count, 25, params.pageNum)\n\n const filter = `\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n `\n const extraControls = `\n
    \n ${filter}\n
    \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n `\n\n const controls = `\n \n `\n\n // Whether there are any unselected items\n let unselected = false\n\n page.dom.innerHTML = `\n ${pagination}\n ${extraControls}\n ${controls}\n
    \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    UsernameUploadsUsageGroup
    \n
    \n ${pagination}\n `\n\n const table = document.querySelector('#table')\n\n for (let i = 0; i < response.data.users.length; i++) {\n const user = response.data.users[i]\n const selected = page.selected.users.includes(user.id)\n if (!selected) unselected = true\n\n let displayGroup = null\n const groups = Object.keys(user.groups)\n for (let i = 0; i < groups.length; i++) {\n if (!user.groups[groups[i]]) break\n displayGroup = groups[i]\n }\n\n // Server-side explicitly expects either of these two values to consider a user as disabled\n const enabled = user.enabled !== false && user.enabled !== 0\n page.cache.users[user.id] = {\n username: user.username,\n groups: user.groups,\n enabled,\n displayGroup\n }\n\n const tr = document.createElement('tr')\n tr.dataset.id = user.id\n tr.innerHTML = `\n \n ${user.username}\n ${user.uploads}\n ${page.getPrettyBytes(user.usage)}\n ${displayGroup}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n `\n\n table.appendChild(tr)\n page.checkboxes.users = table.querySelectorAll('.checkbox[data-action=\"select\"]')\n }\n\n const selectAll = document.querySelector('#selectAll')\n if (selectAll && !unselected) {\n selectAll.checked = true\n selectAll.title = 'Unselect all'\n }\n\n page.fadeAndScroll()\n page.updateTrigger(params.trigger, 'active')\n\n page.views.users.pageNum = response.data.users.length ? params.pageNum : 0\n }).catch(error => {\n page.updateTrigger(params.trigger)\n page.onAxiosError(error)\n })\n}\n\npage.createUser = () => {\n const groupOptions = Object.keys(page.permissions).map((g, i, a) => {\n const disabled = !(a[i + 1] && page.permissions[a[i + 1]])\n return ``\n }).join('\\n')\n\n const div = document.createElement('div')\n div.innerHTML = `\n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n `\n\n swal({\n title: 'Create new user',\n icon: 'info',\n content: div,\n buttons: {\n cancel: true,\n confirm: {\n closeModal: false\n }\n }\n }).then(proceed => {\n if (!proceed) return\n\n axios.post('api/users/create', {\n username: document.querySelector('#swalUsername').value,\n password: document.querySelector('#swalPassword').value,\n group: document.querySelector('#swalGroup').value\n }).then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n const div = document.createElement('div')\n div.innerHTML = `\n

    Username: ${response.data.username}

    \n

    Password: ${response.data.password}

    \n

    User group: ${response.data.group}

    \n `\n swal({\n title: 'Created a new user!',\n icon: 'success',\n content: div\n })\n\n page.getUsers(page.views.users)\n }).catch(page.onAxiosError)\n })\n}\n\npage.editUser = id => {\n const user = page.cache.users[id]\n if (!user) return\n\n const groupOptions = Object.keys(page.permissions).map((g, i, a) => {\n const selected = g === user.displayGroup\n const disabled = !(a[i + 1] && page.permissions[a[i + 1]])\n return ``\n }).join('\\n')\n\n const div = document.createElement('div')\n div.innerHTML = `\n
    \n \n
    \n \n
    \n
    \n
    \n \n
    \n
    \n \n
    \n
    \n
    \n
    \n
    \n \n
    \n
    \n
    \n
    \n \n
    \n
    \n `\n\n swal({\n title: 'Edit user',\n icon: 'info',\n content: div,\n buttons: {\n cancel: true,\n confirm: {\n closeModal: false\n }\n }\n }).then(proceed => {\n if (!proceed) return\n\n axios.post('api/users/edit', {\n id,\n username: document.querySelector('#swalUsername').value,\n group: document.querySelector('#swalGroup').value,\n enabled: document.querySelector('#swalEnabled').checked,\n resetPassword: document.querySelector('#swalResetPassword').checked\n }).then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n let autoClose = true\n const div = document.createElement('div')\n\n let displayName = user.username\n if (response.data.update.username !== user.username) {\n div.innerHTML += `

    ${user.username} was renamed into: ${response.data.update.username}.

    `\n autoClose = false\n displayName = response.data.update.username\n }\n\n if (response.data.update.password) {\n div.innerHTML += `\n

    ${displayName}'s new password is:

    \n

    ${response.data.update.password}

    \n `\n autoClose = false\n }\n\n if (response.data.update.enabled !== user.enabled)\n div.innerHTML += `

    ${displayName} has been ${response.data.update.enabled ? 'enabled' : 'disabled'}!

    `\n\n if (!div.innerHTML)\n div.innerHTML = `

    ${displayName} was edited!

    `\n\n swal({\n title: 'Success!',\n icon: 'success',\n content: div,\n buttons: !autoClose,\n timer: autoClose ? 1500 : null\n })\n page.getUsers(page.views.users)\n }).catch(page.onAxiosError)\n })\n}\n\npage.disableUser = id => {\n const user = page.cache.users[id]\n if (!user || !user.enabled) return\n\n const content = document.createElement('div')\n content.innerHTML = `\n

    You will be disabling a user named ${page.cache.users[id].username}.

    \n

    Their files will remain.

    \n `\n\n swal({\n title: 'Are you sure?',\n icon: 'warning',\n content,\n dangerMode: true,\n buttons: {\n cancel: true,\n confirm: {\n text: 'Yes, disable them!',\n closeModal: false\n }\n }\n }).then(proceed => {\n if (!proceed) return\n\n axios.post('api/users/disable', { id }).then(response => {\n if (!response) return\n\n if (response.data.success === false)\n if (response.data.description === 'No token provided')\n return page.verifyToken(page.token)\n else\n return swal('An error occurred!', response.data.description, 'error')\n\n swal('Success!', `${page.cache.users[id].username} has been disabled.`, 'success', {\n buttons: false,\n timer: 1500\n })\n page.getUsers(page.views.users)\n }).catch(page.onAxiosError)\n })\n}\n\npage.deleteUser = id => {\n const user = page.cache.users[id]\n if (!user) return\n\n const content = document.createElement('div')\n content.innerHTML = `\n

    You will be deleting a user named ${page.cache.users[id].username}.

    \n

    Their files will remain, unless you choose otherwise.

    \n `\n\n swal({\n title: 'Are you sure?',\n icon: 'warning',\n content,\n dangerMode: true,\n buttons: {\n cancel: true,\n confirm: {\n text: 'Yes, delete it!',\n closeModal: false\n },\n purge: {\n text: 'Yes, and the uploads too!',\n value: 'purge',\n className: 'swal-button--danger',\n closeModal: false\n }\n }\n }).then(proceed => {\n if (!proceed) return\n\n axios.post('api/users/delete', {\n id,\n purge: proceed === 'purge'\n }).then(response => {\n if (!response) return\n\n if (response.data.success === false) {\n const failed = Array.isArray(response.data.failed)\n ? response.data.failed\n : []\n\n if (response.data.description === 'No token provided')\n return page.verifyToken(page.token)\n else if (failed.length)\n return swal('An error occurred!', `Unable to delete ${failed.length} of the user's upload${failed.length === 1 ? '' : 's'}.`, 'error')\n else\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n swal('Success!', `${page.cache.users[id].username} has been deleted.`, 'success', {\n buttons: false,\n timer: 1500\n })\n\n // Reload users list\n // eslint-disable-next-line compat/compat\n page.getUsers(Object.assign({\n autoPage: true\n }, page.views.users))\n }).catch(page.onAxiosError)\n })\n}\n\n// Roughly based on https://github.com/mayuska/pagination/blob/master/index.js\npage.paginate = (totalItems, itemsPerPage, currentPage) => {\n currentPage = currentPage + 1\n const step = 3\n const numPages = Math.ceil(totalItems / itemsPerPage)\n\n let template = ''\n const elementsToShow = step * 2\n const add = {\n pageNum (start, end) {\n for (let i = start; i <= end; ++i)\n template += `
  • ${i}
  • `\n },\n startDots () {\n template += `\n
  • 1
  • \n
  • \n `\n },\n endDots () {\n template += `\n
  • \n
  • ${numPages}
  • \n `\n }\n }\n\n if (elementsToShow + 1 >= numPages) {\n add.pageNum(1, numPages)\n } else if (currentPage < elementsToShow) {\n add.pageNum(1, elementsToShow)\n add.endDots()\n } else if (currentPage > numPages - elementsToShow + 1) {\n add.startDots()\n add.pageNum(numPages - elementsToShow + 1, numPages)\n } else {\n add.startDots()\n add.pageNum(currentPage - step + 1, currentPage + step - 1)\n add.endDots()\n }\n\n return `\n \n `\n}\n\npage.getStatistics = (params = {}) => {\n if (!page.permissions.admin)\n return swal('An error occurred!', 'You can not do this!', 'error')\n\n page.updateTrigger(params.trigger, 'loading')\n\n const url = 'api/stats'\n axios.get(url).then(response => {\n if (response.data.success === false)\n if (response.data.description === 'No token provided') {\n return page.verifyToken(page.token)\n } else {\n page.updateTrigger(params.trigger)\n return swal('An error occurred!', response.data.description, 'error')\n }\n\n let content = ''\n const keys = Object.keys(response.data.stats)\n for (let i = 0; i < keys.length; i++) {\n let rows = ''\n if (!response.data.stats[keys[i]])\n rows += `\n \n Generating, please try again later\\u2026\n \n \n `\n else\n try {\n const types = response.data.stats[keys[i]]._types || {}\n const valKeys = Object.keys(response.data.stats[keys[i]])\n for (let j = 0; j < valKeys.length; j++) {\n // Skip keys that starts with an underscore\n if (/^_/.test(valKeys[j]))\n continue\n\n const value = response.data.stats[keys[i]][valKeys[j]]\n let parsed = value\n\n // Parse values with some preset formatting\n if ((types.number || []).includes(valKeys[j]))\n parsed = value.toLocaleString()\n if ((types.byte || []).includes(valKeys[j]))\n parsed = page.getPrettyBytes(value)\n if ((types.byteUsage || []).includes(valKeys[j]))\n parsed = `${page.getPrettyBytes(value.used)} / ${page.getPrettyBytes(value.total)} (${Math.round(value.used / value.total * 100)}%)`\n\n const string = valKeys[j]\n .replace(/([A-Z])/g, ' $1')\n .toUpperCase()\n rows += `\n \n ${string}\n ${parsed}\n \n `\n }\n } catch (error) {\n rows = `\n \n Error parsing response. Try again?\n \n \n `\n page.onError(error)\n }\n\n content += `\n
    \n \n \n \n \n \n \n \n \n ${rows}\n \n
    ${keys[i].toUpperCase()}
    \n
    \n `\n }\n\n page.dom.innerHTML = content\n page.fadeAndScroll()\n page.updateTrigger(params.trigger, 'active')\n }).catch(error => {\n page.updateTrigger(params.trigger)\n page.onAxiosError(error)\n })\n}\n\nwindow.onload = () => {\n // Polyfill Object.assign()\n // eslint-disable-next-line compat/compat\n if (typeof Object.assign !== 'function')\n // Must be writable: true, enumerable: false, configurable: true\n Object.defineProperty(Object, 'assign', {\n value: function assign (target, varArgs) { // .length of function is 2\n 'use strict'\n if (target === null || target === undefined)\n throw new TypeError('Cannot convert undefined or null to object')\n const to = Object(target)\n for (let i = 1; i < arguments.length; i++) {\n const nextSource = arguments[i]\n if (nextSource !== null && nextSource !== undefined)\n for (const nextKey in nextSource)\n // Avoid bugs when hasOwnProperty is shadowed\n if (Object.prototype.hasOwnProperty.call(nextSource, nextKey))\n to[nextKey] = nextSource[nextKey]\n }\n return to\n },\n writable: true,\n configurable: true\n })\n\n // Add 'no-touch' class to non-touch devices\n if (!('ontouchstart' in document.documentElement))\n document.documentElement.classList.add('no-touch')\n\n const selectedKeys = ['uploads', 'uploadsAll', 'users']\n for (let i = 0; i < selectedKeys.length; i++) {\n const ls = localStorage[lsKeys.selected[selectedKeys[i]]]\n if (ls) page.selected[selectedKeys[i]] = JSON.parse(ls)\n }\n\n page.preparePage()\n\n page.clipboardJS = new ClipboardJS('.clipboard-js')\n\n page.clipboardJS.on('success', () => {\n return swal('', 'The link has been copied to clipboard.', 'success', {\n buttons: false,\n timer: 1500\n })\n })\n\n page.clipboardJS.on('error', page.onError)\n\n page.lazyLoad = new LazyLoad()\n}\n"]} \ No newline at end of file diff --git a/dist/js/misc/utils.js b/dist/js/misc/utils.js index 42357a5..cf8295e 100644 --- a/dist/js/misc/utils.js +++ b/dist/js/misc/utils.js @@ -1,2 +1,2 @@ -lsKeys.siBytes="siBytes",page.prepareShareX=function(){var e=page.token?{token:page.token||"",albumid:page.album||""}:{};e.filelength=page.fileLength||"",e.age=page.uploadAge||"",e.striptags=page.stripTags||"";for(var t=[],a=Object.keys(e),n=0;n]/.exec(a);if(!r)return a;var n="",o=0,i=0;for(o=r.index;o {\n const values = page.token ? {\n token: page.token || '',\n albumid: page.album || ''\n } : {}\n values.filelength = page.fileLength || ''\n values.age = page.uploadAge || ''\n values.striptags = page.stripTags || ''\n\n const headers = []\n const keys = Object.keys(values)\n for (let i = 0; i < keys.length; i++)\n // Pad by 4 space\n headers.push(` \"${keys[i]}\": \"${values[keys[i]]}\"`)\n\n const origin = (location.hostname + location.pathname).replace(/\\/(dashboard)?$/, '')\n const originClean = origin.replace(/\\//g, '_')\n\n const sharexElement = document.querySelector('#ShareX')\n const sharexFile = `{\n \"Name\": \"${originClean}\",\n \"DestinationType\": \"ImageUploader, FileUploader\",\n \"RequestMethod\": \"POST\",\n \"RequestURL\": \"${location.protocol}//${origin}/api/upload\",\n \"Headers\": {\n${headers.join(',\\n')}\n },\n \"Body\": \"MultipartFormData\",\n \"FileFormName\": \"files[]\",\n \"URL\": \"$json:files[0].url$\",\n \"ThumbnailURL\": \"$json:files[0].url$\"\n}`\n\n const sharexBlob = new Blob([sharexFile], { type: 'application/octet-binary' })\n /* eslint-disable-next-line compat/compat */\n sharexElement.setAttribute('href', URL.createObjectURL(sharexBlob))\n sharexElement.setAttribute('download', `${originClean}.sxcu`)\n}\n\npage.getPrettyDate = date => {\n return date.getFullYear() + '-' +\n (date.getMonth() < 9 ? '0' : '') + // month's index starts from zero\n (date.getMonth() + 1) + '-' +\n (date.getDate() < 10 ? '0' : '') +\n date.getDate() + ' ' +\n (date.getHours() < 10 ? '0' : '') +\n date.getHours() + ':' +\n (date.getMinutes() < 10 ? '0' : '') +\n date.getMinutes() + ':' +\n (date.getSeconds() < 10 ? '0' : '') +\n date.getSeconds()\n}\n\npage.getPrettyBytes = num => {\n // MIT License\n // Copyright (c) Sindre Sorhus (sindresorhus.com)\n if (typeof num !== 'number' && !isFinite(num)) return num\n\n const si = localStorage[lsKeys.siBytes] !== '0'\n const neg = num < 0 ? '-' : ''\n const scale = si ? 1000 : 1024\n if (neg) num = -num\n if (num < scale) return `${neg}${num} B`\n\n const exponent = Math.min(Math.floor((Math.log(num) * Math.LOG10E) / 3), 8) // 8 is count of KMGTPEZY\n const numStr = Number((num / Math.pow(scale, exponent)).toPrecision(3))\n const pre = (si ? 'kMGTPEZY' : 'KMGTPEZY').charAt(exponent - 1) + (si ? '' : 'i')\n return `${neg}${numStr} ${pre}B`\n}\n"]} \ No newline at end of file +{"version":3,"sources":["utils.js"],"names":["lsKeys","siBytes","page","prepareShareX","const","values","token","albumid","album","filelength","fileLength","age","uploadAge","striptags","stripTags","headers","keys","Object","i","length","push","origin","location","hostname","pathname","replace","originClean","sharexElement","document","querySelector","sharexFile","join","sharexBlob","Blob","type","setAttribute","URL","createObjectURL","getPrettyDate","date","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","getPrettyBytes","num","isFinite","si","localStorage","neg","scale","exponent","Math","min","floor","log","LOG10E","Number","pow","toPrecision","charAt","escape","string","str","String","match","exec","let","html","index","lastIndex","charCodeAt","substring"],"mappings":"AAGAA,OAAOC,QAAU,UAEjBC,KAAKC,cAAa,WAChBC,IAAMC,EAASH,KAAKI,MAAQ,CAC1BA,MAAOJ,KAAKI,OAAS,GACrBC,QAASL,KAAKM,OAAS,IACrB,GACJH,EAAOI,WAAaP,KAAKQ,YAAc,GACvCL,EAAOM,IAAMT,KAAKU,WAAa,GAC/BP,EAAOQ,UAAYX,KAAKY,WAAa,GAIrC,IAFAV,IAAMW,EAAU,GACVC,EAAOC,OAAOD,KAAKX,GAChBa,EAAI,EAAGA,EAAIF,EAAKG,OAAQD,IAE/BH,EAAQK,KAAK,QAAQJ,EAAKE,GAAE,OAAOb,EAAOW,EAAKE,IAAG,KAEpDd,IAAMiB,GAAUC,SAASC,SAAWD,SAASE,UAAUC,QAAQ,kBAAmB,IAC5EC,EAAcL,EAAOI,QAAQ,MAAO,KAEpCE,EAAgBC,SAASC,cAAc,WACvCC,EAAa,iBACRJ,EAAW,yGAGLJ,SAAS,SAAQ,KAAKD,EAAM,kCAE7CN,EAAQgB,KAAK,OAAM,oJAQbC,EAAa,IAAIC,KAAK,CAACH,GAAa,CAAEI,KAAM,6BAElDP,EAAcQ,aAAa,OAAQC,IAAIC,gBAAgBL,IACvDL,EAAcQ,aAAa,WAAeT,EAAW,UAGvDxB,KAAKoC,cAAa,SAAGC,GACnB,OAAOA,EAAKC,cAAgB,KACzBD,EAAKE,WAAa,EAAI,IAAM,KAC5BF,EAAKE,WAAa,GAAK,KACvBF,EAAKG,UAAY,GAAK,IAAM,IAC7BH,EAAKG,UAAY,KAChBH,EAAKI,WAAa,GAAK,IAAM,IAC9BJ,EAAKI,WAAa,KACjBJ,EAAKK,aAAe,GAAK,I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siBytes = 'siBytes'\n\npage.prepareShareX = () => {\n const values = page.token ? {\n token: page.token || '',\n albumid: page.album || ''\n } : {}\n values.filelength = page.fileLength || ''\n values.age = page.uploadAge || ''\n values.striptags = page.stripTags || ''\n\n const headers = []\n const keys = Object.keys(values)\n for (let i = 0; i < keys.length; i++)\n // Pad by 4 space\n headers.push(` \"${keys[i]}\": \"${values[keys[i]]}\"`)\n\n const origin = (location.hostname + location.pathname).replace(/\\/(dashboard)?$/, '')\n const originClean = origin.replace(/\\//g, '_')\n\n const sharexElement = document.querySelector('#ShareX')\n const sharexFile = `{\n \"Name\": \"${originClean}\",\n \"DestinationType\": \"ImageUploader, FileUploader\",\n \"RequestMethod\": \"POST\",\n \"RequestURL\": \"${location.protocol}//${origin}/api/upload\",\n \"Headers\": {\n${headers.join(',\\n')}\n },\n \"Body\": \"MultipartFormData\",\n \"FileFormName\": \"files[]\",\n \"URL\": \"$json:files[0].url$\",\n \"ThumbnailURL\": \"$json:files[0].url$\"\n}`\n\n const sharexBlob = new Blob([sharexFile], { type: 'application/octet-binary' })\n /* eslint-disable-next-line compat/compat */\n sharexElement.setAttribute('href', URL.createObjectURL(sharexBlob))\n sharexElement.setAttribute('download', `${originClean}.sxcu`)\n}\n\npage.getPrettyDate = date => {\n return date.getFullYear() + '/' +\n (date.getMonth() < 9 ? '0' : '') + // month's index starts from zero\n (date.getMonth() + 1) + '/' +\n (date.getDate() < 10 ? '0' : '') +\n date.getDate() + ' ' +\n (date.getHours() < 10 ? '0' : '') +\n date.getHours() + ':' +\n (date.getMinutes() < 10 ? '0' : '') +\n date.getMinutes() + ':' +\n (date.getSeconds() < 10 ? '0' : '') +\n date.getSeconds()\n}\n\npage.getPrettyBytes = num => {\n // MIT License\n // Copyright (c) Sindre Sorhus (sindresorhus.com)\n if (typeof num !== 'number' && !isFinite(num)) return num\n\n const si = localStorage[lsKeys.siBytes] !== '0'\n const neg = num < 0 ? '-' : ''\n const scale = si ? 1000 : 1024\n if (neg) num = -num\n if (num < scale) return `${neg}${num} B`\n\n const exponent = Math.min(Math.floor((Math.log(num) * Math.LOG10E) / 3), 8) // 8 is count of KMGTPEZY\n const numStr = Number((num / Math.pow(scale, exponent)).toPrecision(3))\n const pre = (si ? 'kMGTPEZY' : 'KMGTPEZY').charAt(exponent - 1) + (si ? '' : 'i')\n return `${neg}${numStr} ${pre}B`\n}\n\npage.escape = string => {\n // MIT License\n // Copyright(c) 2012-2013 TJ Holowaychuk\n // Copyright(c) 2015 Andreas Lubbe\n // Copyright(c) 2015 Tiancheng \"Timothy\" Gu\n\n if (!string)\n return string\n\n const str = String(string)\n const match = /[\"'&<>]/.exec(str)\n\n if (!match)\n return str\n\n let escape\n let html = ''\n let index = 0\n let lastIndex = 0\n\n for (index = match.index; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34: // \"\n escape = '"'\n break\n case 38: // &\n escape = '&'\n break\n case 39: // '\n escape = '''\n break\n case 60: // <\n escape = '<'\n break\n case 62: // >\n escape = '>'\n break\n default:\n continue\n }\n\n if (lastIndex !== index)\n html += str.substring(lastIndex, index)\n\n lastIndex = index + 1\n html += escape\n }\n\n return lastIndex !== index\n ? html + str.substring(lastIndex, index)\n : html\n}\n"]} \ No newline at end of file diff --git a/package.json b/package.json index c5ece87..09f80e0 100644 --- a/package.json +++ b/package.json @@ -37,12 +37,13 @@ "fluent-ffmpeg": "^2.1.2", "helmet": "^3.22.0", "jszip": "^3.3.0", - "knex": "^0.20.13", + "knex": "^0.20.15", "multer": "^1.4.2", "node-fetch": "^2.6.0", "nunjucks": "^3.2.1", "randomstring": "^1.1.5", "readline": "^1.3.0", + "search-query-parser": "^1.5.5", "sharp": "^0.25.2", "sqlite3": "^4.1.1", "systeminformation": "^4.23.3" diff --git a/routes/album.js b/routes/album.js index 0f493b6..6e078cb 100644 --- a/routes/album.js +++ b/routes/album.js @@ -31,30 +31,33 @@ routes.get('/a/:identifier', async (req, res, next) => { const nojs = req.query.nojs !== undefined - // Cache ID - we initialize a separate cache for No-JS version - const cacheid = nojs ? `${album.id}-nojs` : album.id + let cacheid + if (process.env.NODE_ENV !== 'development') { + // Cache ID - we initialize a separate cache for No-JS version + cacheid = nojs ? `${album.id}-nojs` : album.id - if (!utils.albumsCache[cacheid]) - utils.albumsCache[cacheid] = { - cache: null, - generating: false, - // Cache will actually be deleted after the album has been updated, - // so storing this timestamp may be redundant, but just in case. - generatedAt: 0 - } + if (!utils.albumsCache[cacheid]) + utils.albumsCache[cacheid] = { + cache: null, + generating: false, + // Cache will actually be deleted after the album has been updated, + // so storing this timestamp may be redundant, but just in case. + generatedAt: 0 + } - if (!utils.albumsCache[cacheid].cache && utils.albumsCache[cacheid].generating) - return res.json({ - success: false, - description: 'This album is still generating its public page.' - }) - else if ((album.editedAt < utils.albumsCache[cacheid].generatedAt) || utils.albumsCache[cacheid].generating) - return res.send(utils.albumsCache[cacheid].cache) + if (!utils.albumsCache[cacheid].cache && utils.albumsCache[cacheid].generating) + return res.json({ + success: false, + description: 'This album is still generating its public page.' + }) + else if ((album.editedAt < utils.albumsCache[cacheid].generatedAt) || utils.albumsCache[cacheid].generating) + return res.send(utils.albumsCache[cacheid].cache) - // Use current timestamp to make sure cache is invalidated - // when an album is edited during this generation process. - utils.albumsCache[cacheid].generating = true - utils.albumsCache[cacheid].generatedAt = Math.floor(Date.now() / 1000) + // Use current timestamp to make sure cache is invalidated + // when an album is edited during this generation process. + utils.albumsCache[cacheid].generating = true + utils.albumsCache[cacheid].generatedAt = Math.floor(Date.now() / 1000) + } const files = await db.table('files') .select('name', 'size') @@ -89,12 +92,15 @@ routes.get('/a/:identifier', async (req, res, next) => { files, nojs }, (error, html) => { - utils.albumsCache[cacheid].cache = error ? null : html - utils.albumsCache[cacheid].generating = false + const data = error ? null : html + if (cacheid) { + utils.albumsCache[cacheid].cache = data + utils.albumsCache[cacheid].generating = false + } // Express should already send error to the next handler if (error) return - return res.send(utils.albumsCache[cacheid].cache) + return res.send(data) }) }) diff --git a/src/js/dashboard.js b/src/js/dashboard.js index a7c6cb0..afda840 100644 --- a/src/js/dashboard.js +++ b/src/js/dashboard.js @@ -298,34 +298,34 @@ page.domClick = event => { const action = element.dataset.action switch (action) { + // Uploads case 'view-list': return page.setUploadsView('list', element) case 'view-thumbs': return page.setUploadsView('thumbs', element) - case 'clear-selection': - return page.clearSelection() - case 'add-selected-uploads-to-album': - return page.addSelectedUploadsToAlbum() - case 'select': - return page.select(element, event) - case 'select-all': - return page.selectAll(element) case 'add-to-album': return page.addToAlbum(id) case 'delete-upload': return page.deleteUpload(id) + case 'add-selected-uploads-to-album': + return page.addSelectedUploadsToAlbum() case 'bulk-delete-uploads': return page.bulkDeleteUploads() case 'display-preview': return page.displayPreview(id) + // Manage uploads + case 'upload-filters-help': + return page.uploadFiltersHelp(element) + case 'filter-uploads': + return page.filterUploads(element) + // Manage your albums case 'submit-album': return page.submitAlbum(element) case 'edit-album': return page.editAlbum(id) case 'delete-album': return page.deleteAlbum(id) - case 'get-new-token': - return page.getNewToken(element) + // Manage users case 'create-user': return page.createUser() case 'edit-user': @@ -334,12 +334,24 @@ page.domClick = event => { return page.disableUser(id) case 'delete-user': return page.deleteUser(id) - case 'user-filters-help': - return page.userFiltersHelp(element) - case 'filter-uploads': - return page.filterUploads(element) case 'view-user-uploads': return page.viewUserUploads(id, element) + /* // WIP + case 'user-filters-help': + return page.userFiltersHelp(element) + case 'filter-users': + return page.filterUsers(element) + */ + // Others + case 'get-new-token': + return page.getNewToken(element) + // Uploads & Users + case 'clear-selection': + return page.clearSelection() + case 'select': + return page.select(element, event) + case 'select-all': + return page.selectAll(element) case 'page-ellipsis': return page.focusJumpToPage() case 'page-prev': @@ -429,6 +441,11 @@ page.getUploads = (params = {}) => { filters: params.filters || '' } + // Send client timezone offset if using date filter + // Server will pretend client is on UTC if missing + if (headers.filters.includes('date:') || headers.filters.includes('expiry:')) + headers.minOffset = new Date().getTimezoneOffset() + axios.get(url, { headers }).then(response => { if (response.data.success === false) if (response.data.description === 'No token provided') { @@ -464,10 +481,10 @@ page.getUploads = (params = {}) => {
    - +
    -