filesafe/public/js/home.js

504 lines
16 KiB
JavaScript
Raw Normal View History

/* global swal, axios, Dropzone, ClipboardJS, LazyLoad */
2017-01-14 09:16:47 +00:00
2018-10-09 19:52:41 +00:00
const page = {
// user token
token: localStorage.token,
// configs from api/check
private: null,
enableUserAccounts: null,
maxFileSize: null,
chunkSize: null,
// store album id that will be used with upload requests
album: null,
albumSelect: null,
previewTemplate: null,
dropzone: null,
clipboardJS: null,
lazyLoad: null,
imageExtensions: ['.webp', '.jpg', '.jpeg', '.bmp', '.gif', '.png', '.svg']
}
page.checkIfPublic = function () {
2018-10-09 19:52:41 +00:00
axios.get('api/check').then(function (response) {
page.private = response.data.private
page.enableUserAccounts = response.data.enableUserAccounts
page.maxFileSize = response.data.maxFileSize
page.chunkSize = response.data.chunkSize
page.preparePage()
}).catch(function (error) {
console.log(error)
const button = document.getElementById('loginToUpload')
button.classList.remove('is-loading')
button.innerText = 'Error occurred. Reload the page?'
return swal('An error occurred!', 'There was an error with the request, please check the console for more information.', 'error')
})
}
page.preparePage = function () {
if (page.private)
if (page.token) {
return page.verifyToken(page.token, true)
} else {
2018-10-09 19:52:41 +00:00
const button = document.getElementById('loginToUpload')
button.href = 'auth'
button.classList.remove('is-loading')
if (page.enableUserAccounts)
button.innerText = 'Anonymous upload is disabled. Log in to page.'
else
button.innerText = 'Running in private mode. Log in to page.'
}
else
return page.prepareUpload()
}
page.verifyToken = function (token, reloadOnError) {
if (reloadOnError === undefined) reloadOnError = false
2018-10-09 19:52:41 +00:00
axios.post('api/tokens/verify', { token }).then(function (response) {
if (response.data.success === false)
2018-10-09 19:52:41 +00:00
return swal({
title: 'An error occurred!',
text: response.data.description,
icon: 'error'
}).then(function () {
if (!reloadOnError) return
2018-10-09 19:52:41 +00:00
localStorage.removeItem('token')
location.reload()
})
2018-10-09 19:52:41 +00:00
localStorage.token = token
page.token = token
return page.prepareUpload()
}).catch(function (error) {
console.log(error)
return swal('An error occurred!', 'There was an error with the request, please check the console for more information.', 'error')
})
}
page.prepareUpload = function () {
// I think this fits best here because we need to check for a valid token before we can get the albums
if (page.token) {
page.albumSelect = document.getElementById('albumSelect')
page.albumSelect.addEventListener('change', function () {
page.album = parseInt(page.albumSelect.value)
})
page.prepareAlbums()
// Display the album selection
document.getElementById('albumDiv').style.display = 'flex'
}
2018-10-09 19:52:41 +00:00
document.getElementById('maxFileSize').innerHTML = `Maximum upload size per file is ${page.maxFileSize}`
document.getElementById('loginToUpload').style.display = 'none'
if (!page.token && page.enableUserAccounts)
document.getElementById('loginLinkText').innerHTML = 'Create an account and keep track of your uploads'
2018-10-09 19:52:41 +00:00
const previewNode = document.querySelector('#tpl')
page.previewTemplate = previewNode.innerHTML
previewNode.parentNode.removeChild(previewNode)
page.prepareDropzone()
2018-10-09 19:52:41 +00:00
const tabs = document.getElementById('tabs')
if (tabs) {
tabs.style.display = 'flex'
2018-10-09 19:52:41 +00:00
const items = tabs.getElementsByTagName('li')
for (let i = 0; i < items.length; i++)
items[i].addEventListener('click', function () {
page.setActiveTab(this.dataset.id)
})
document.getElementById('uploadUrls').addEventListener('click', function () {
page.uploadUrls(this)
})
page.setActiveTab('tab-files')
} else {
document.getElementById('tab-files').style.display = 'block'
}
}
page.prepareAlbums = function () {
2018-10-09 19:52:41 +00:00
const option = document.createElement('option')
option.value = ''
option.innerHTML = 'Upload to album'
option.disabled = true
option.selected = true
page.albumSelect.appendChild(option)
2018-10-09 19:52:41 +00:00
axios.get('api/albums', {
headers: {
token: page.token
}
}).then(function (response) {
if (response.data.success === false)
2018-10-09 19:52:41 +00:00
return swal('An error occurred!', response.data.description, 'error')
2018-10-09 19:52:41 +00:00
// If the user doesn't have any albums we don't really need to display
// an album selection
if (!response.data.albums.length) return
2018-10-09 19:52:41 +00:00
// Loop through the albums and create an option for each album
for (let i = 0; i < response.data.albums.length; i++) {
const album = response.data.albums[i]
const option = document.createElement('option')
option.value = album.id
option.innerHTML = album.name
page.albumSelect.appendChild(option)
}
}).catch(function (error) {
console.log(error)
const description = error.response.data && error.response.data.description
? error.response.data.description
: 'There was an error with the request, please check the console for more information.'
return swal(`${error.response.status} ${error.response.statusText}`, description, 'error')
2018-10-09 19:52:41 +00:00
})
}
page.setActiveTab = function (activeId) {
2018-10-09 19:52:41 +00:00
const items = document.getElementById('tabs').getElementsByTagName('li')
for (let i = 0; i < items.length; i++) {
const tabId = items[i].dataset.id
if (tabId === activeId) {
items[i].classList.add('is-active')
document.getElementById(tabId).style.display = 'block'
} else {
items[i].classList.remove('is-active')
document.getElementById(tabId).style.display = 'none'
}
}
}
page.prepareDropzone = function () {
2018-10-09 19:52:41 +00:00
const tabDiv = document.getElementById('tab-files')
const div = document.createElement('div')
div.className = 'control is-expanded'
2018-10-09 19:52:41 +00:00
div.innerHTML = `
<div id="dropzone" class="button is-danger is-fullwidth is-unselectable">
<span class="icon">
<i class="icon-upload-cloud"></i>
</span>
<span>Click here or drag and drop files</span>
</div>
`
tabDiv.querySelector('.dz-container').appendChild(div)
const previewsContainer = tabDiv.querySelector('#tab-files .field.uploads')
page.dropzone = new Dropzone('#dropzone', {
url: 'api/upload',
paramName: 'files[]',
maxFilesize: parseInt(page.maxFileSize),
parallelUploads: 2,
uploadMultiple: false,
2018-10-09 19:52:41 +00:00
previewsContainer,
previewTemplate: page.previewTemplate,
createImageThumbnails: false,
maxFiles: 1000,
autoProcessQueue: true,
headers: { token: page.token },
chunking: Boolean(page.chunkSize),
chunkSize: parseInt(page.chunkSize) * 1000000, // 1000000 B = 1 MB,
parallelChunkUploads: false, // when set to true, sometimes it often hangs with hundreds of parallel uploads
2018-10-09 19:52:41 +00:00
chunksUploaded (file, done) {
file.previewElement.querySelector('.progress').setAttribute('value', 100)
file.previewElement.querySelector('.progress').innerHTML = '100%'
2018-10-09 19:52:41 +00:00
return axios.post('api/upload/finishchunks', {
// The API supports an array of multiple files
files: [{
uuid: file.upload.uuid,
original: file.name,
size: file.size,
type: file.type,
count: file.upload.totalChunkCount,
albumid: page.album
}]
}, {
headers: {
token: page.token
}
}).then(function (response) {
file.previewElement.querySelector('.progress').style.display = 'none'
if (response.data.success === false)
2018-10-09 19:52:41 +00:00
file.previewElement.querySelector('.error').innerHTML = response.data.description
if (response.data.files && response.data.files[0])
2018-10-09 19:52:41 +00:00
page.updateTemplate(file, response.data.files[0])
2018-10-09 19:52:41 +00:00
return done()
}).catch(function (error) {
return {
success: false,
description: error.toString()
}
})
}
})
page.dropzone.on('addedfile', function (file) {
tabDiv.getElementsByClassName('uploads')[0].style.display = 'block'
file.previewElement.querySelector('.name').innerHTML = file.name
})
// Add the selected albumid, if an album is selected, as a header
page.dropzone.on('sending', function (file, xhr) {
if (file.upload.chunked) return
if (page.album) xhr.setRequestHeader('albumid', page.album)
})
// Update the total progress bar
page.dropzone.on('uploadprogress', function (file, progress) {
if (file.upload.chunked && progress === 100) return
file.previewElement.querySelector('.progress').setAttribute('value', progress)
2018-10-09 19:52:41 +00:00
file.previewElement.querySelector('.progress').innerHTML = `${progress}%`
})
page.dropzone.on('success', function (file, response) {
if (!response) return
file.previewElement.querySelector('.progress').style.display = 'none'
// file.previewElement.querySelector('.name').innerHTML = file.name
if (response.success === false)
file.previewElement.querySelector('.error').innerHTML = response.description
if (response.files && response.files[0])
page.updateTemplate(file, response.files[0])
})
page.dropzone.on('error', function (file, error) {
page.updateTemplateIcon(file.previewElement, 'icon-block')
file.previewElement.querySelector('.progress').style.display = 'none'
file.previewElement.querySelector('.name').innerHTML = file.name
Updates Reworked unique name generator to prevent the same unique identifier from being used if it was already used with a different extension (e.i. If a file named aBcD.jpg already exists, then files such as aBcD.png or aBcD.txt may not exist). This is mainly to deal with the fact that thumbnails are only being saved as PNG, so if the same unique name is being used by multiple image/video extensions, then only one of them will have the proper thumbnail. If you already have existing files with matching unique name but varying extensions, unfortunately you can only deal with them manually for now (either allocating new unique names or deleting them altogether). Added a new config option to filter files with no extension. Files with no extensions will no longer have their original name appended to the allocated random name (e.i. A file named "textfile" used to become something like "aBcDtextfile", where "aBcD" was the allocated random name. Now it will only just become "aBcD"). In relation to that, utils.extname() function will now always return blank string if the file name does not seem to have any extension. Though files such as '.DS_Store' (basically anything that starts with a dot) will still be accepted. Examples: .hiddenfile => .hiddenfile .hiddenfile.sh => .sh .hiddenfile.001 => .hiddenfile.001 .hiddenfile.sh.001 => .sh.001 Simplified error messages of /api/upload/finishchunks. Most, if not all, of the error responses for /api/upload* will now have HTTP status code 400 (bad request) instead of 200 (ok). I plan to generalize this for the other API routes in the future. Updated home.js to properly handle formatted error message when the response's status code is not 200 (ok). Bumped v1 version string (due to home.js).
2018-11-28 17:52:12 +00:00
file.previewElement.querySelector('.error').innerHTML = error.description || error
})
if (typeof page.prepareShareX === 'function') page.prepareShareX()
}
page.uploadUrls = function (button) {
2018-10-09 19:52:41 +00:00
const tabDiv = document.getElementById('tab-urls')
if (!tabDiv) return
if (button.classList.contains('is-loading')) return
button.classList.add('is-loading')
function done (error) {
if (error) swal('An error occurred!', error, 'error')
button.classList.remove('is-loading')
}
function run () {
2018-10-09 19:52:41 +00:00
const albumid = page.album
const previewsContainer = tabDiv.getElementsByClassName('uploads')[0]
const urls = document.getElementById('urls').value
.split(/\r?\n/)
.filter(function (url) {
return url.trim().length
})
document.getElementById('urls').value = urls.join('\n')
if (!urls.length)
// eslint-disable-next-line prefer-promise-reject-errors
return done('You have not entered any URLs.')
tabDiv.getElementsByClassName('uploads')[0].style.display = 'block'
2018-10-09 19:52:41 +00:00
const files = urls.map(function (url) {
const previewTemplate = document.createElement('template')
previewTemplate.innerHTML = page.previewTemplate.trim()
2018-10-09 19:52:41 +00:00
const previewElement = previewTemplate.content.firstChild
previewElement.querySelector('.name').innerHTML = url
previewElement.querySelector('.progress').removeAttribute('value')
previewsContainer.appendChild(previewElement)
return {
2018-10-09 19:52:41 +00:00
url,
previewElement
}
})
function post (i) {
if (i === files.length) return done()
2018-10-09 19:52:41 +00:00
const file = files[i]
function posted (result) {
file.previewElement.querySelector('.progress').style.display = 'none'
if (result.success) {
page.updateTemplate(file, result.files[0])
} else {
page.updateTemplateIcon(file.previewElement, 'icon-block')
file.previewElement.querySelector('.error').innerHTML = result.description
}
return post(i + 1)
}
2018-10-09 19:52:41 +00:00
axios.post('api/upload', {
urls: [file.url]
}, {
headers: {
token: page.token,
albumid
}
}).then(function (response) {
return posted(response.data)
}).catch(function (error) {
return posted({
success: false,
description: error.response ? error.response.data.description : error.toString()
})
2018-10-09 19:52:41 +00:00
})
}
return post(0)
}
return run()
}
page.updateTemplateIcon = function (templateElement, iconClass) {
const iconElement = templateElement.querySelector('.icon')
if (!iconElement) return
iconElement.classList.add(iconClass)
iconElement.style.display = ''
}
page.updateTemplate = function (file, response) {
if (!response.url) return
2018-10-09 19:52:41 +00:00
const a = file.previewElement.querySelector('.link > a')
const clipboard = file.previewElement.querySelector('.clipboard-mobile > .clipboard-js')
a.href = a.innerHTML = clipboard.dataset['clipboardText'] = response.url
clipboard.parentElement.style.display = 'block'
2018-10-09 19:52:41 +00:00
const exec = /.[\w]+(\?|$)/.exec(response.url)
if (exec && exec[0] && page.imageExtensions.includes(exec[0].toLowerCase())) {
2018-10-09 19:52:41 +00:00
const img = file.previewElement.querySelector('img')
img.setAttribute('alt', response.name || '')
img.dataset['src'] = response.url
img.style.display = ''
img.onerror = function () {
// Hide image elements that fail to load
// Consequently include WEBP in browsers that do not have WEBP support (Firefox/IE)
this.style.display = 'none'
file.previewElement.querySelector('.icon').style.display = ''
}
page.lazyLoad.update(file.previewElement.querySelectorAll('img'))
} else {
page.updateTemplateIcon(file.previewElement, 'icon-doc-inv')
}
}
page.createAlbum = function () {
2018-10-09 19:52:41 +00:00
const div = document.createElement('div')
div.innerHTML = `
<div class="field">
<div class="controls">
<input id="swalName" class="input" type="text" placeholder="Name">
</div>
</div>
<div class="field">
<div class="control">
<textarea id="swalDescription" class="textarea" placeholder="Description" rows="2"></textarea>
2018-10-09 19:52:41 +00:00
</div>
</div>
<div class="field">
<div class="control">
<label class="checkbox">
<input id="swalDownload" type="checkbox" checked>
Enable download
</label>
</div>
</div>
<div class="field">
<div class="control">
<label class="checkbox">
<input id="swalPublic" type="checkbox" checked>
Enable public link
</label>
</div>
</div>
`
swal({
title: 'Create new album',
icon: 'info',
content: div,
buttons: {
cancel: true,
confirm: {
closeModal: false
}
}
2018-10-09 19:52:41 +00:00
}).then(function (value) {
if (!value) return
2018-10-09 19:52:41 +00:00
const name = document.getElementById('swalName').value
axios.post('api/albums', {
name,
description: document.getElementById('swalDescription').value,
2018-10-09 19:52:41 +00:00
download: document.getElementById('swalDownload').checked,
public: document.getElementById('swalPublic').checked
}, {
headers: {
token: page.token
}
}).then(function (response) {
if (response.data.success === false)
2018-10-09 19:52:41 +00:00
return swal('An error occurred!', response.data.description, 'error')
const option = document.createElement('option')
option.value = response.data.id
option.innerHTML = name
page.albumSelect.appendChild(option)
swal('Woohoo!', 'Album was created successfully', 'success')
}).catch(function (error) {
console.log(error)
return swal('An error occurred!', 'There was an error with the request, please check the console for more information.', 'error')
})
2018-10-09 19:52:41 +00:00
})
}
// Handle image paste event
window.addEventListener('paste', function (event) {
2018-10-09 19:52:41 +00:00
const items = (event.clipboardData || event.originalEvent.clipboardData).items
for (const index in items) {
const item = items[index]
if (item.kind === 'file') {
2018-10-09 19:52:41 +00:00
const blob = item.getAsFile()
const file = new File([blob], `pasted-image.${blob.type.match(/(?:[^/]*\/)([^;]*)/)[1]}`)
file.type = blob.type
page.dropzone.addFile(file)
}
}
})
window.onload = function () {
page.checkIfPublic()
page.clipboardJS = new ClipboardJS('.clipboard-js')
page.clipboardJS.on('success', function () {
return swal('Copied!', 'The link has been copied to clipboard.', 'success')
})
page.clipboardJS.on('error', function (event) {
console.error(event)
return swal('An error occurred!', 'There was an error when trying to copy the link to clipboard, please check the console for more information.', 'error')
})
page.lazyLoad = new LazyLoad({
elements_selector: '.field.uploads img'
})
document.getElementById('createAlbum').addEventListener('click', function () {
page.createAlbum()
})
}