filesafe/dist/js/home.js
Bobby Wibowo 456f63d0d8
Updated home.js
Make sure album newly created on the homepage is properly selected
2020-04-08 00:54:00 +07:00

3 lines
22 KiB
JavaScript

var lsKeys={token:"token",chunkSize:"chunkSize",parallelUploads:"parallelUploads",uploadsHistoryOrder:"uploadsHistoryOrder",previewImages:"previewImages",fileLength:"fileLength",uploadAge:"uploadAge",stripTags:"stripTags"},page={token:localStorage[lsKeys.token],private:null,enableUserAccounts:null,maxSize:null,chunkSize:null,temporaryUploadAges:null,fileIdentifierLength:null,stripTagsConfig:null,album:null,parallelUploads:2,previewImages:null,fileLength:null,uploadAge:null,maxSizeBytes:null,urlMaxSize:null,urlMaxSizeBytes:null,tabs:[],activeTab:null,albumSelect:null,albumSelectOnChange:null,previewTemplate:null,dropzone:null,clipboardJS:null,lazyLoad:null,urlsQueue:[],activeUrlsQueue:0,imageExts:[".webp",".jpg",".jpeg",".bmp",".gif",".png",".tiff",".tif",".svg"],videoExts:[".webm",".mp4",".wmv",".avi",".mov",".mkv"],albumTitleMaxLength:70,albumDescMaxLength:4e3,onInitError:function(e){document.querySelector("#albumDiv").classList.add("is-hidden"),document.querySelector("#tabs").classList.add("is-hidden"),document.querySelectorAll(".tab-content").forEach((function(e){return e.classList.add("is-hidden")}));var a=document.querySelector("#loginToUpload");a.innerText="An error occurred. Try to reload?",a.classList.remove("is-loading"),a.classList.remove("is-hidden"),a.addEventListener("click",(function(){location.reload()})),e.response?page.onAxiosError(e):page.onError(e)},onError:function(e){console.error(e);var a=document.createElement("div");return a.innerHTML="<code>"+e.toString()+"</code>",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")},checkIfPublic:function(){var e=!1;return axios.get("api/check",{onDownloadProgress:function(){e||"function"!=typeof page.doRender||(page.doRender(),e=!0)}}).then((function(e){return page.private=e.data.private,page.enableUserAccounts=e.data.enableUserAccounts,page.maxSize=parseInt(e.data.maxSize),page.maxSizeBytes=1e6*page.maxSize,page.chunkSize=parseInt(e.data.chunkSize),page.temporaryUploadAges=e.data.temporaryUploadAges,page.fileIdentifierLength=e.data.fileIdentifierLength,page.stripTagsConfig=e.data.stripTags,page.preparePage()})).catch(page.onInitError)},preparePage:function(){if(!page.private)return page.prepareUpload();if(page.token)return page.verifyToken(page.token,!0);var e=document.querySelector("#loginToUpload");e.href="auth",e.classList.remove("is-loading"),page.enableUserAccounts?e.innerText="Anonymous upload is disabled. Log in to upload.":e.innerText="Running in private mode. Log in to upload."},verifyToken:function(e,a){return axios.post("api/tokens/verify",{token:e}).then((function(t){return!1===t.data.success?swal({title:"An error occurred!",text:t.data.description,icon:"error"}).then((function(){a&&(localStorage.removeItem("token"),location.reload())})):(localStorage[lsKeys.token]=e,page.token=e,page.prepareUpload())})).catch(page.onInitError)},prepareUpload:function(){page.token&&(document.querySelector("#albumDiv").classList.remove("is-hidden"),page.albumSelect=document.querySelector("#albumSelect"),page.albumSelectOnChange=function(){page.album=parseInt(page.albumSelect.value),"function"==typeof page.prepareShareX&&page.prepareShareX()},page.albumSelect.addEventListener("change",page.albumSelectOnChange),page.fetchAlbums()),page.prepareUploadConfig(),document.querySelector("#maxSize > span").innerHTML=page.getPrettyBytes(page.maxSizeBytes),document.querySelector("#loginToUpload").classList.add("is-hidden"),!page.token&&page.enableUserAccounts&&(document.querySelector("#loginLinkText").innerHTML="Create an account and keep track of your uploads"),page.prepareDropzone(),"function"==typeof page.prepareShareX&&page.prepareShareX();var e=document.querySelector("#urlMaxSize");e&&(page.urlMaxSize=parseInt(e.innerHTML),page.urlMaxSizeBytes=1e6*page.urlMaxSize,e.innerHTML=page.getPrettyBytes(page.urlMaxSizeBytes),document.querySelector("#uploadUrls").addEventListener("click",(function(e){page.addUrlsToQueue()})));for(var a=document.querySelector("#tabs"),t=a.querySelectorAll("li"),r=function(e){var a=t[e].dataset.id,r=document.querySelector("#"+a);r&&(t[e].addEventListener("click",(function(){page.setActiveTab(e)})),page.tabs.push({tab:t[e],content:r}))},n=0;n<t.length;n++)r(n);page.tabs.length&&(page.setActiveTab(0),a.classList.remove("is-hidden"))},setActiveTab:function(e){for(var a=0;a<page.tabs.length;a++)a===e?(page.tabs[a].tab.classList.add("is-active"),page.tabs[a].content.classList.remove("is-hidden"),page.activeTab=e):(page.tabs[a].tab.classList.remove("is-active"),page.tabs[a].content.classList.add("is-hidden"))},fetchAlbums:function(){return axios.get("api/albums",{headers:{token:page.token}}).then((function(e){if(!1===e.data.success)return swal("An error occurred!",e.data.description,"error");if(Array.isArray(e.data.albums)&&e.data.albums.length)for(var a=0;a<e.data.albums.length;a++){var t=e.data.albums[a],r=document.createElement("option");r.value=t.id,r.innerHTML=t.name,page.albumSelect.appendChild(r)}})).catch(page.onInitError)},prepareDropzone:function(){var e=document.querySelector("#tpl");page.previewTemplate=e.innerHTML,e.parentNode.removeChild(e);var a=document.querySelector("#tab-files"),t=document.createElement("div");t.className="control is-expanded",t.innerHTML='\n <div id="dropzone" class="button is-danger is-outlined is-fullwidth is-unselectable">\n <span class="icon">\n <i class="icon-upload-cloud"></i>\n </span>\n <span>Click here or drag & drop files</span>\n </div>\n ',a.querySelector(".dz-container").appendChild(t);var r=a.querySelector("#tab-files .field.uploads");page.dropzone=new Dropzone(document.body,{url:"api/upload",paramName:"files[]",clickable:a.querySelector("#dropzone"),maxFilesize:page.maxSizeBytes/1024/1024,parallelUploads:page.parallelUploads,uploadMultiple:!1,previewsContainer:r,previewTemplate:page.previewTemplate,createImageThumbnails:!1,autoProcessQueue:!0,headers:{token:page.token},chunking:Boolean(page.chunkSize),chunkSize:1e6*page.chunkSize,parallelChunkUploads:!1,timeout:0,init:function(){this.on("addedfile",(function(e){0!==page.activeTab&&page.setActiveTab(0),a.querySelector(".uploads").classList.remove("is-hidden"),e.previewElement.querySelector(".name").innerHTML=e.name,e.previewElement.querySelector(".descriptive-progress").innerHTML="Waiting in queue…"})),this.on("sending",(function(e,a){a.ontimeout||(a.ontimeout=function(){var e=page.dropzone.getUploadingFiles().filter((function(e){return e.xhr===a}));page.dropzone._handleUploadError(e,a,"Connection timed out. Try to reduce upload chunk size.")}),void 0===a._start&&(a._start=Date.now()),e.upload.chunked||(null!==page.album&&a.setRequestHeader("albumid",page.album),null!==page.fileLength&&a.setRequestHeader("filelength",page.fileLength),null!==page.uploadAge&&a.setRequestHeader("age",page.uploadAge),null!==page.stripTags&&a.setRequestHeader("striptags",page.stripTags)),e.upload.chunked?1===e.upload.chunks.length&&(e.previewElement.querySelector(".descriptive-progress").innerHTML="Uploading chunk 1/"+e.upload.totalChunkCount+"…"):e.previewElement.querySelector(".descriptive-progress").innerHTML="Uploading…"})),this.on("uploadprogress",(function(e,a){var t,r=Math.max(e.size,e.upload.total),n=(e.upload.bytesSent/r*100).toFixed(0),l=e.upload.chunked?e.upload.chunks[e.upload.chunks.length-1]:e.upload,i=l.xhr||e.xhr,o="Uploading…",s=!1;if(e.upload.chunked){var p=l.bytesSent===l.total,u=e.upload.chunks.length===e.upload.totalChunkCount,d=e.upload.chunks.length;p&&!u&&(d++,s=!0),o="Uploading chunk "+d+"/"+e.upload.totalChunkCount+"…"}if(!s){var c=(Date.now()-i._start)/1e3,g=c?l.bytesSent/c:0;t=page.getPrettyBytes(g)}e.previewElement.querySelector(".descriptive-progress").innerHTML=o+" "+n+"%"+(t?" at ~"+t+"/s":"")})),this.on("success",(function(e,a){a&&(e.previewElement.querySelector(".descriptive-progress").classList.add("is-hidden"),!1===a.success&&(e.previewElement.querySelector(".error").innerHTML=a.description,e.previewElement.querySelector(".error").classList.remove("is-hidden")),Array.isArray(a.files)&&a.files[0]&&page.updateTemplate(e,a.files[0]))})),this.on("error",(function(e,a){("string"==typeof a&&/^File is too big/.test(a)||"object"==typeof a&&/File too large/.test(a.description))&&(a="File too large ("+page.getPrettyBytes(e.size)+")."),page.updateTemplateIcon(e.previewElement,"icon-block"),e.previewElement.querySelector(".descriptive-progress").classList.add("is-hidden"),e.previewElement.querySelector(".error").innerHTML=a.description||a,e.previewElement.querySelector(".error").classList.remove("is-hidden")}))},chunksUploaded:function(e,a){return e.previewElement.querySelector(".descriptive-progress").innerHTML="Rebuilding "+e.upload.totalChunkCount+" chunks…",axios.post("api/upload/finishchunks",{files:[{uuid:e.upload.uuid,original:e.name,type:e.type,albumid:page.album,filelength:page.fileLength,age:page.uploadAge}]},{headers:{token:page.token,striptags:page.stripTags}}).catch((function(e){return e.response.data?e.response:{data:{success:!1,description:e.toString()}}})).then((function(t){return e.previewElement.querySelector(".descriptive-progress").classList.add("is-hidden"),!1===t.data.success&&(e.previewElement.querySelector(".error").innerHTML=t.data.description,e.previewElement.querySelector(".error").classList.remove("is-hidden")),t.data.files&&t.data.files[0]&&page.updateTemplate(e,t.data.files[0]),a()}))}})},addUrlsToQueue:function(){var e=document.querySelector("#urls").value.split(/\r?\n/).filter((function(e){return e.trim().length}));if(!e.length)return swal("An error occurred!","You have not entered any URLs.","error");var a=document.querySelector("#tab-urls");a.querySelector(".uploads").classList.remove("is-hidden");for(var t=0;t<e.length;t++){var r=document.createElement("template");r.innerHTML=page.previewTemplate.trim();var n=r.content.firstChild;n.querySelector(".name").innerHTML=e[t],n.querySelector(".descriptive-progress").innerHTML="Waiting in queue…",a.querySelector(".uploads").appendChild(n),page.urlsQueue.push({url:e[t],previewElement:n})}page.processUrlsQueue(),document.querySelector("#urls").value=""}};page.processUrlsQueue=function(){if(page.urlsQueue.length)return a();function e(e){return e.previewElement.querySelector(".descriptive-progress").innerHTML="Waiting for server to fetch URL…",axios.post("api/upload",{urls:[e.url]},{headers:{token:page.token,albumid:page.album,age:page.uploadAge,filelength:page.fileLength}}).catch((function(e){return e.response.data?e.response:{data:{success:!1,description:e.toString()}}})).then((function(t){return function(e,t){if(e.previewElement.querySelector(".descriptive-progress").classList.add("is-hidden"),!1===t.success){var r=t.description.match(/ over limit: (\d+)$/);r&&r[1]&&(t.description="File exceeded limit of "+page.getPrettyBytes(r[1])+"."),e.previewElement.querySelector(".error").innerHTML=t.description,e.previewElement.querySelector(".error").classList.remove("is-hidden")}return Array.isArray(t.files)&&t.files[0]&&page.updateTemplate(e,t.files[0]),page.activeUrlsQueue--,a()}(e,t.data)}))}function a(){for(;page.urlsQueue.length&&page.activeUrlsQueue<page.parallelUploads;)page.activeUrlsQueue++,e(page.urlsQueue.shift())}},page.updateTemplateIcon=function(e,a){var t=e.querySelector(".icon");t&&(t.classList.add(a),t.classList.remove("is-hidden"))},page.updateTemplate=function(e,a){if(a.url){var t=e.previewElement.querySelector(".link"),r=t.querySelector("a"),n=e.previewElement.querySelector(".clipboard-mobile > .clipboard-js");r.href=r.innerHTML=n.dataset.clipboardText=a.url,t.classList.remove("is-hidden"),n.parentElement.classList.remove("is-hidden");var l=/.[\w]+(\?|$)/.exec(a.url),i=l&&l[0]?l[0].toLowerCase():null;if(page.imageExts.includes(i))if(page.previewImages){var o=e.previewElement.querySelector("img");o.setAttribute("alt",a.name||""),o.dataset.src=a.url,o.classList.remove("is-hidden"),o.onerror=function(a){a.currentTarget.classList.add("is-hidden"),page.updateTemplateIcon(e.previewElement,"icon-picture")},page.lazyLoad.update(e.previewElement.querySelectorAll("img"))}else page.updateTemplateIcon(e.previewElement,"icon-picture");else page.videoExts.includes(i)?page.updateTemplateIcon(e.previewElement,"icon-video"):page.updateTemplateIcon(e.previewElement,"icon-doc-inv");if(a.expirydate){var s=e.previewElement.querySelector(".expiry-date");s.innerHTML="EXP: "+page.getPrettyDate(new Date(1e3*a.expirydate)),s.classList.remove("is-hidden")}}},page.createAlbum=function(){var e=document.createElement("div");e.innerHTML='\n <div class="field">\n <div class="controls">\n <input id="swalName" class="input" type="text" placeholder="Name" maxlength="'+page.albumTitleMaxLength+'">\n </div>\n <p class="help">Max length is '+page.albumTitleMaxLength+' characters.</p>\n </div>\n <div class="field">\n <div class="control">\n <textarea id="swalDescription" class="textarea" placeholder="Description" rows="2" maxlength="'+page.albumDescMaxLength+'"></textarea>\n </div>\n <p class="help">Max length is '+page.albumDescMaxLength+' characters.</p>\n </div>\n <div class="field">\n <div class="control">\n <label class="checkbox">\n <input id="swalDownload" type="checkbox" checked>\n Enable download\n </label>\n </div>\n </div>\n <div class="field">\n <div class="control">\n <label class="checkbox">\n <input id="swalPublic" type="checkbox" checked>\n Enable public link\n </label>\n </div>\n </div>\n ',swal({title:"Create new album",icon:"info",content:e,buttons:{cancel:!0,confirm:{closeModal:!1}}}).then((function(e){if(e){var a=document.querySelector("#swalName").value.trim();axios.post("api/albums",{name:a,description:document.querySelector("#swalDescription").value.trim(),download:document.querySelector("#swalDownload").checked,public:document.querySelector("#swalPublic").checked},{headers:{token:page.token}}).then((function(e){if(!1===e.data.success)return swal("An error occurred!",e.data.description,"error");var t=document.createElement("option");page.albumSelect.appendChild(t),t.value=e.data.id,t.innerHTML=a,t.selected=!0,page.albumSelectOnChange(),swal("Woohoo!","Album was created successfully.","success")})).catch(page.onError)}}))},page.prepareUploadConfig=function(){var e={chunkSize:page.chunkSize,parallelUploads:page.parallelUploads},a=Array.isArray(page.temporaryUploadAges)&&page.temporaryUploadAges.length,t=page.fileIdentifierLength&&"number"==typeof page.fileIdentifierLength.min&&"number"==typeof page.fileIdentifierLength.max,r={siBytes:{label:"File size display",select:[{value:"default",text:"1000 B = 1 kB = 1 Kilobyte"},{value:"0",text:"1024 B = 1 KiB = 1 Kibibyte"}],help:"This will be used in our homepage, dashboard, and album public pages.",valueHandler:function(){}},fileLength:{display:t,label:"File identifier length",number:t?{min:page.fileIdentifierLength.min,max:page.fileIdentifierLength.max,round:!0}:void 0,help:!0,disabled:t&&page.fileIdentifierLength.force},uploadAge:{display:a,label:"Upload age",select:[],help:"Whether to automatically delete your uploads after a certain amount of time."},stripTags:{display:page.stripTagsConfig,label:"Strip tags",select:page.stripTagsConfig?[{value:page.stripTagsConfig.default?"default":"1",text:"Yes"},{value:page.stripTagsConfig.default?"0":"default",text:"No"}]:null,help:"Whether to strip tags (e.g. EXIF) from your uploads.<br>\n This only applies to regular image"+(page.stripTagsConfig&&page.stripTagsConfig.video?" and video":"")+" uploads (i.e. not URL uploads).",disabled:page.stripTagsConfig&&page.stripTagsConfig.force},chunkSize:{display:!isNaN(page.chunkSize),label:"Upload chunk size (MB)",number:{min:1,max:95,suffix:" MB",round:!0},help:!0},parallelUploads:{label:"Parallel uploads",number:{min:1,max:10,round:!0},help:!0},uploadsHistoryOrder:{label:"Uploads history order",select:[{value:"default",text:"Older files on top"},{value:"0",text:"Newer files on top"}],help:'"Newer files on top" will use a CSS technique, which unfortunately come with <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/flex-direction#Accessibility_Concerns" target="_blank" rel="noopener">some undesirable side effects</a>.<br>\n This also affects text selection, such as when trying to select text from top to bottom will result in them being selected from bottom to top instead, and vice versa.',valueHandler:function(e){if("0"===e)for(var a=document.querySelectorAll(".tab-content > .uploads"),t=0;t<a.length;t++)a[t].classList.add("is-reversed")}},previewImages:{label:"Load images for preview",select:[{value:"default",text:"Yes"},{value:"0",text:"No"}],help:"By default, uploaded images will be loaded as their previews.",valueHandler:function(e){page.previewImages="0"!==e}}};if(a)for(var n=parseFloat(localStorage[lsKeys.uploadAge]),l=0;l<page.temporaryUploadAges.length;l++){var i=page.temporaryUploadAges[l];r.uploadAge.select.push({value:0===l?"default":String(i),text:page.getPrettyUploadAge(i)}),i===n&&(r.uploadAge.value=n)}if(t){e.fileLength=page.fileIdentifierLength.default||void 0;var o=parseInt(localStorage[lsKeys.fileLength]);!page.fileIdentifierLength.force&&!isNaN(o)&&o>=page.fileIdentifierLength.min&&o<=page.fileIdentifierLength.max&&(r.fileLength.value=o)}var s=document.querySelector("#tab-config"),p=document.createElement("form");p.addEventListener("submit",(function(e){return e.preventDefault()}));for(var u=Object.keys(r),d=0;d<u.length;d++){var c=u[d],g=r[c];if(!1!==g.display){var m=document.createElement("div");m.className="field";var f=void 0;if(!g.disabled){if(void 0!==g.value)f=g.value;else if(void 0!==g.number){var v=parseInt(localStorage[lsKeys[c]]);isNaN(v)||(f=v)}else{var h=localStorage[lsKeys[c]];f=Array.isArray(g.select)?g.select.find((function(e){return e.value===h}))?h:void 0:h}"function"==typeof g.valueHandler?g.valueHandler(f):void 0!==f&&(page[c]=f)}var b=void 0;if(Array.isArray(g.select)){(b=document.createElement("div")).className="select is-fullwidth";for(var y=[],S=0;S<g.select.length;S++){var L=g.select[S],w=f&&L.value===String(f)||void 0===f&&"default"===L.value;y.push('\n <option value="'+L.value+'"'+(w?" selected":"")+">\n "+L.text+("default"===L.value?" (default)":"")+"\n </option>\n ")}b.innerHTML='\n <select id="'+c+'">\n '+y.join("\n")+"\n </select>\n "}else void 0!==g.number&&((b=document.createElement("input")).id=b.name=c,b.className="input is-fullwidth",b.type="number",void 0!==g.number.min&&(b.min=g.number.min),void 0!==g.number.max&&(b.max=g.number.max),"number"==typeof f?b.value=f:void 0!==e[c]&&(b.value=e[c]));var x=void 0;if(g.disabled)Array.isArray(g.select)?b.querySelector("select").disabled=g.disabled:b.disabled=g.disabled,x="This option is currently not configurable.";else if("string"==typeof g.help)x=g.help;else if(!0===g.help&&void 0!==g.number){var T=[];void 0!==e[c]&&T.push("Default is "+e[c]+(g.number.suffix||"")+"."),void 0!==g.number.min&&T.push("Min is "+g.number.min+(g.number.suffix||"")+"."),void 0!==g.number.max&&T.push("Max is "+g.number.max+(g.number.suffix||"")+"."),x=T.join(" ")}m.innerHTML='\n <label class="label">'+g.label+'</label>\n <div class="control"></div>\n '+(x?'<p class="help">'+x+"</p>":"")+"\n ",m.querySelector("div.control").appendChild(b),p.appendChild(m)}}var k=document.createElement("div");k.className="field",k.innerHTML='\n <p class="control">\n <button id="saveConfig" type="submit" class="button is-danger is-outlined is-fullwidth">\n <span class="icon">\n <i class="icon-floppy"></i>\n </span>\n <span>Save & reload</span>\n </button>\n </p>\n <p class="help">\n This configuration will only be used in this browser.<br>\n After reloading the page, some of them will also be applied to the ShareX config that you can download by clicking on the ShareX icon below.\n </p>\n ',p.appendChild(k),p.querySelector("#saveConfig").addEventListener("click",(function(){if(p.checkValidity()){for(var a=Object.keys(r).filter((function(e){return!1!==r[e].display&&!0!==r[e].disabled})),t=0;t<a.length;t++){var n=a[t],l=void 0;if(void 0!==r[n].select)"default"!==p.elements[n].value&&(l=p.elements[n].value);else if(void 0!==r[n].number){var i=parseInt(p.elements[n].value);isNaN(i)||(l=Math.min(Math.max(i,r[n].number.min),r[n].number.max))}void 0!==l&&l!==e[n]?localStorage[lsKeys[n]]=l:localStorage.removeItem(lsKeys[n])}swal({title:"Woohoo!",text:"Configuration saved into this browser.",icon:"success"}).then((function(){location.reload()}))}})),s.appendChild(p)},page.getPrettyUploadAge=function(e){if(0===e)return"Permanent";if(e<1){var a=60*e;return a+" minute"+(1===a?"":"s")}if(e>=24){var t=e/24;return t+" day"+(1===t?"":"s")}return e+" hour"+(1===e?"":"s")},window.addEventListener("paste",(function(e){for(var a=(e.clipboardData||e.originalEvent.clipboardData).items,t=Object.keys(a),r=0;r<t.length;r++){var n=a[t[r]];if("file"===n.kind){var l=n.getAsFile(),i=new File([l],"pasted-image."+l.type.match(/(?:[^/]*\/)([^;]*)/)[1],{type:l.type});page.dropzone.addFile(i)}}})),window.onload=function(){page.checkIfPublic(),page.clipboardJS=new ClipboardJS(".clipboard-js"),page.clipboardJS.on("success",(function(){return swal("","The link has been copied to clipboard.","success",{buttons:!1,timer:1500})})),page.clipboardJS.on("error",page.onError),page.lazyLoad=new LazyLoad({elements_selector:".field.uploads img"}),document.querySelector("#createAlbum").addEventListener("click",(function(){page.createAlbum()}))};
//# sourceMappingURL=home.js.map