Merge branch 'feature/file-size-checking' into 'develop'

[pleroma#36] Add errors when file uploading fails

See merge request pleroma/pleroma-fe!405
This commit is contained in:
HJ 2018-12-13 21:02:17 +00:00
commit 99b2b7a203
9 changed files with 153 additions and 37 deletions

View File

@ -21,11 +21,15 @@ const afterStoreSetup = ({ store, i18n }) => {
window.fetch('/api/statusnet/config.json') window.fetch('/api/statusnet/config.json')
.then((res) => res.json()) .then((res) => res.json())
.then((data) => { .then((data) => {
const { name, closed: registrationClosed, textlimit, server, vapidPublicKey } = data.site const { name, closed: registrationClosed, textlimit, uploadlimit, server, vapidPublicKey } = data.site
store.dispatch('setInstanceOption', { name: 'name', value: name }) store.dispatch('setInstanceOption', { name: 'name', value: name })
store.dispatch('setInstanceOption', { name: 'registrationOpen', value: (registrationClosed === '0') }) store.dispatch('setInstanceOption', { name: 'registrationOpen', value: (registrationClosed === '0') })
store.dispatch('setInstanceOption', { name: 'textlimit', value: parseInt(textlimit) }) store.dispatch('setInstanceOption', { name: 'textlimit', value: parseInt(textlimit) })
store.dispatch('setInstanceOption', { name: 'uploadlimit', value: parseInt(uploadlimit.uploadlimit) })
store.dispatch('setInstanceOption', { name: 'avatarlimit', value: parseInt(uploadlimit.avatarlimit) })
store.dispatch('setInstanceOption', { name: 'backgroundlimit', value: parseInt(uploadlimit.backgroundlimit) })
store.dispatch('setInstanceOption', { name: 'bannerlimit', value: parseInt(uploadlimit.bannerlimit) })
store.dispatch('setInstanceOption', { name: 'server', value: server }) store.dispatch('setInstanceOption', { name: 'server', value: server })
if (data.nsfwCensorImage) { if (data.nsfwCensorImage) {

View File

@ -1,5 +1,6 @@
/* eslint-env browser */ /* eslint-env browser */
import statusPosterService from '../../services/status_poster/status_poster.service.js' import statusPosterService from '../../services/status_poster/status_poster.service.js'
import fileSizeFormatService from '../../services/file_size_format/file_size_format.js'
const mediaUpload = { const mediaUpload = {
mounted () { mounted () {
@ -21,6 +22,12 @@ const mediaUpload = {
uploadFile (file) { uploadFile (file) {
const self = this const self = this
const store = this.$store const store = this.$store
if (file.size > store.state.instance.uploadlimit) {
const filesize = fileSizeFormatService.fileSizeFormat(file.size)
const allowedsize = fileSizeFormatService.fileSizeFormat(store.state.instance.uploadlimit)
self.$emit('upload-failed', 'file_too_big', {filesize: filesize.num, filesizeunit: filesize.unit, allowedsize: allowedsize.num, allowedsizeunit: allowedsize.unit})
return
}
const formData = new FormData() const formData = new FormData()
formData.append('media', file) formData.append('media', file)
@ -32,7 +39,7 @@ const mediaUpload = {
self.$emit('uploaded', fileData) self.$emit('uploaded', fileData)
self.uploading = false self.uploading = false
}, (error) => { // eslint-disable-line handle-callback-err }, (error) => { // eslint-disable-line handle-callback-err
self.$emit('upload-failed') self.$emit('upload-failed', 'default')
self.uploading = false self.uploading = false
}) })
}, },

View File

@ -262,6 +262,11 @@ const PostStatusForm = {
let index = this.newStatus.files.indexOf(fileInfo) let index = this.newStatus.files.indexOf(fileInfo)
this.newStatus.files.splice(index, 1) this.newStatus.files.splice(index, 1)
}, },
uploadFailed (errString, templateArgs) {
templateArgs = templateArgs || {}
this.error = this.$t('upload.error.base') + ' ' + this.$t('upload.error.' + errString, templateArgs)
this.enableSubmit()
},
disableSubmit () { disableSubmit () {
this.submitDisabled = true this.submitDisabled = true
}, },

View File

@ -64,7 +64,7 @@
</div> </div>
</div> </div>
<div class='form-bottom'> <div class='form-bottom'>
<media-upload @uploading="disableSubmit" @uploaded="addMediaFile" @upload-failed="enableSubmit" :drop-files="dropFiles"></media-upload> <media-upload @uploading="disableSubmit" @uploaded="addMediaFile" @upload-failed="uploadFailed" :drop-files="dropFiles"></media-upload>
<p v-if="isOverLengthLimit" class="error">{{ charactersLeft }}</p> <p v-if="isOverLengthLimit" class="error">{{ charactersLeft }}</p>
<p class="faint" v-else-if="hasStatusLengthLimit">{{ charactersLeft }}</p> <p class="faint" v-else-if="hasStatusLengthLimit">{{ charactersLeft }}</p>

View File

@ -1,5 +1,6 @@
import TabSwitcher from '../tab_switcher/tab_switcher.jsx' import TabSwitcher from '../tab_switcher/tab_switcher.jsx'
import StyleSwitcher from '../style_switcher/style_switcher.vue' import StyleSwitcher from '../style_switcher/style_switcher.vue'
import fileSizeFormatService from '../../services/file_size_format/file_size_format.js'
const UserSettings = { const UserSettings = {
data () { data () {
@ -14,8 +15,16 @@ const UserSettings = {
followImportError: false, followImportError: false,
followsImported: false, followsImported: false,
enableFollowsExport: true, enableFollowsExport: true,
uploading: [ false, false, false, false ], avatarUploading: false,
previews: [ null, null, null ], bannerUploading: false,
backgroundUploading: false,
followListUploading: false,
avatarPreview: null,
bannerPreview: null,
backgroundPreview: null,
avatarUploadError: null,
bannerUploadError: null,
backgroundUploadError: null,
deletingAccount: false, deletingAccount: false,
deleteAccountConfirmPasswordInput: '', deleteAccountConfirmPasswordInput: '',
deleteAccountError: false, deleteAccountError: false,
@ -84,19 +93,24 @@ const UserSettings = {
uploadFile (slot, e) { uploadFile (slot, e) {
const file = e.target.files[0] const file = e.target.files[0]
if (!file) { return } if (!file) { return }
if (file.size > this.$store.state.instance[slot + 'limit']) {
const filesize = fileSizeFormatService.fileSizeFormat(file.size)
const allowedsize = fileSizeFormatService.fileSizeFormat(this.$store.state.instance[slot + 'limit'])
this[slot + 'UploadError'] = this.$t('upload.error.base') + ' ' + this.$t('upload.error.file_too_big', {filesize: filesize.num, filesizeunit: filesize.unit, allowedsize: allowedsize.num, allowedsizeunit: allowedsize.unit})
return
}
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
const reader = new FileReader() const reader = new FileReader()
reader.onload = ({target}) => { reader.onload = ({target}) => {
const img = target.result const img = target.result
this.previews[slot] = img this[slot + 'Preview'] = img
this.$forceUpdate() // just changing the array with the index doesn't update the view
} }
reader.readAsDataURL(file) reader.readAsDataURL(file)
}, },
submitAvatar () { submitAvatar () {
if (!this.previews[0]) { return } if (!this.avatarPreview) { return }
let img = this.previews[0] let img = this.avatarPreview
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
let imginfo = new Image() let imginfo = new Image()
let cropX, cropY, cropW, cropH let cropX, cropY, cropW, cropH
@ -112,20 +126,25 @@ const UserSettings = {
cropX = Math.floor((imginfo.width - imginfo.height) / 2) cropX = Math.floor((imginfo.width - imginfo.height) / 2)
cropW = imginfo.height cropW = imginfo.height
} }
this.uploading[0] = true this.avatarUploading = true
this.$store.state.api.backendInteractor.updateAvatar({params: {img, cropX, cropY, cropW, cropH}}).then((user) => { this.$store.state.api.backendInteractor.updateAvatar({params: {img, cropX, cropY, cropW, cropH}}).then((user) => {
if (!user.error) { if (!user.error) {
this.$store.commit('addNewUsers', [user]) this.$store.commit('addNewUsers', [user])
this.$store.commit('setCurrentUser', user) this.$store.commit('setCurrentUser', user)
this.previews[0] = null this.avatarPreview = null
} else {
this.avatarUploadError = this.$t('upload.error.base') + user.error
} }
this.uploading[0] = false this.avatarUploading = false
}) })
}, },
clearUploadError (slot) {
this[slot + 'UploadError'] = null
},
submitBanner () { submitBanner () {
if (!this.previews[1]) { return } if (!this.bannerPreview) { return }
let banner = this.previews[1] let banner = this.bannerPreview
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
let imginfo = new Image() let imginfo = new Image()
/* eslint-disable camelcase */ /* eslint-disable camelcase */
@ -135,22 +154,24 @@ const UserSettings = {
height = imginfo.height height = imginfo.height
offset_top = 0 offset_top = 0
offset_left = 0 offset_left = 0
this.uploading[1] = true this.bannerUploading = true
this.$store.state.api.backendInteractor.updateBanner({params: {banner, offset_top, offset_left, width, height}}).then((data) => { this.$store.state.api.backendInteractor.updateBanner({params: {banner, offset_top, offset_left, width, height}}).then((data) => {
if (!data.error) { if (!data.error) {
let clone = JSON.parse(JSON.stringify(this.$store.state.users.currentUser)) let clone = JSON.parse(JSON.stringify(this.$store.state.users.currentUser))
clone.cover_photo = data.url clone.cover_photo = data.url
this.$store.commit('addNewUsers', [clone]) this.$store.commit('addNewUsers', [clone])
this.$store.commit('setCurrentUser', clone) this.$store.commit('setCurrentUser', clone)
this.previews[1] = null this.bannerPreview = null
} else {
this.bannerUploadError = this.$t('upload.error.base') + data.error
} }
this.uploading[1] = false this.bannerUploading = false
}) })
/* eslint-enable camelcase */ /* eslint-enable camelcase */
}, },
submitBg () { submitBg () {
if (!this.previews[2]) { return } if (!this.backgroundPreview) { return }
let img = this.previews[2] let img = this.backgroundPreview
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
let imginfo = new Image() let imginfo = new Image()
let cropX, cropY, cropW, cropH let cropX, cropY, cropW, cropH
@ -159,20 +180,22 @@ const UserSettings = {
cropY = 0 cropY = 0
cropW = imginfo.width cropW = imginfo.width
cropH = imginfo.width cropH = imginfo.width
this.uploading[2] = true this.backgroundUploading = true
this.$store.state.api.backendInteractor.updateBg({params: {img, cropX, cropY, cropW, cropH}}).then((data) => { this.$store.state.api.backendInteractor.updateBg({params: {img, cropX, cropY, cropW, cropH}}).then((data) => {
if (!data.error) { if (!data.error) {
let clone = JSON.parse(JSON.stringify(this.$store.state.users.currentUser)) let clone = JSON.parse(JSON.stringify(this.$store.state.users.currentUser))
clone.background_image = data.url clone.background_image = data.url
this.$store.commit('addNewUsers', [clone]) this.$store.commit('addNewUsers', [clone])
this.$store.commit('setCurrentUser', clone) this.$store.commit('setCurrentUser', clone)
this.previews[2] = null this.backgroundPreview = null
} else {
this.backgroundUploadError = this.$t('upload.error.base') + data.error
} }
this.uploading[2] = false this.backgroundUploading = false
}) })
}, },
importFollows () { importFollows () {
this.uploading[3] = true this.followListUploading = true
const followList = this.followList const followList = this.followList
this.$store.state.api.backendInteractor.followImport({params: followList}) this.$store.state.api.backendInteractor.followImport({params: followList})
.then((status) => { .then((status) => {
@ -181,7 +204,7 @@ const UserSettings = {
} else { } else {
this.followImportError = true this.followImportError = true
} }
this.uploading[3] = false this.followListUploading = false
}) })
}, },
/* This function takes an Array of Users /* This function takes an Array of Users

View File

@ -40,37 +40,49 @@
<p>{{$t('settings.current_avatar')}}</p> <p>{{$t('settings.current_avatar')}}</p>
<img :src="user.profile_image_url_original" class="old-avatar"></img> <img :src="user.profile_image_url_original" class="old-avatar"></img>
<p>{{$t('settings.set_new_avatar')}}</p> <p>{{$t('settings.set_new_avatar')}}</p>
<img class="new-avatar" v-bind:src="previews[0]" v-if="previews[0]"> <img class="new-avatar" v-bind:src="avatarPreview" v-if="avatarPreview">
</img> </img>
<div> <div>
<input type="file" @change="uploadFile(0, $event)" ></input> <input type="file" @change="uploadFile('avatar', $event)" ></input>
</div>
<i class="icon-spin4 animate-spin" v-if="avatarUploading"></i>
<button class="btn btn-default" v-else-if="avatarPreview" @click="submitAvatar">{{$t('general.submit')}}</button>
<div class='alert error' v-if="avatarUploadError">
Error: {{ avatarUploadError }}
<i class="icon-cancel" @click="clearUploadError('avatar')"></i>
</div> </div>
<i class="icon-spin4 animate-spin" v-if="uploading[0]"></i>
<button class="btn btn-default" v-else-if="previews[0]" @click="submitAvatar">{{$t('general.submit')}}</button>
</div> </div>
<div class="setting-item"> <div class="setting-item">
<h2>{{$t('settings.profile_banner')}}</h2> <h2>{{$t('settings.profile_banner')}}</h2>
<p>{{$t('settings.current_profile_banner')}}</p> <p>{{$t('settings.current_profile_banner')}}</p>
<img :src="user.cover_photo" class="banner"></img> <img :src="user.cover_photo" class="banner"></img>
<p>{{$t('settings.set_new_profile_banner')}}</p> <p>{{$t('settings.set_new_profile_banner')}}</p>
<img class="banner" v-bind:src="previews[1]" v-if="previews[1]"> <img class="banner" v-bind:src="bannerPreview" v-if="bannerPreview">
</img> </img>
<div> <div>
<input type="file" @change="uploadFile(1, $event)" ></input> <input type="file" @change="uploadFile('banner', $event)" ></input>
</div>
<i class=" icon-spin4 animate-spin uploading" v-if="bannerUploading"></i>
<button class="btn btn-default" v-else-if="bannerPreview" @click="submitBanner">{{$t('general.submit')}}</button>
<div class='alert error' v-if="bannerUploadError">
Error: {{ bannerUploadError }}
<i class="icon-cancel" @click="clearUploadError('banner')"></i>
</div> </div>
<i class=" icon-spin4 animate-spin uploading" v-if="uploading[1]"></i>
<button class="btn btn-default" v-else-if="previews[1]" @click="submitBanner">{{$t('general.submit')}}</button>
</div> </div>
<div class="setting-item"> <div class="setting-item">
<h2>{{$t('settings.profile_background')}}</h2> <h2>{{$t('settings.profile_background')}}</h2>
<p>{{$t('settings.set_new_profile_background')}}</p> <p>{{$t('settings.set_new_profile_background')}}</p>
<img class="bg" v-bind:src="previews[2]" v-if="previews[2]"> <img class="bg" v-bind:src="backgroundPreview" v-if="backgroundPreview">
</img> </img>
<div> <div>
<input type="file" @change="uploadFile(2, $event)" ></input> <input type="file" @change="uploadFile('background', $event)" ></input>
</div>
<i class=" icon-spin4 animate-spin uploading" v-if="backgroundUploading"></i>
<button class="btn btn-default" v-else-if="backgroundPreview" @click="submitBg">{{$t('general.submit')}}</button>
<div class='alert error' v-if="backgroundUploadError">
Error: {{ backgroundUploadError }}
<i class="icon-cancel" @click="clearUploadError('background')"></i>
</div> </div>
<i class=" icon-spin4 animate-spin uploading" v-if="uploading[2]"></i>
<button class="btn btn-default" v-else-if="previews[2]" @click="submitBg">{{$t('general.submit')}}</button>
</div> </div>
</div> </div>
@ -117,7 +129,7 @@
<form v-model="followImportForm"> <form v-model="followImportForm">
<input type="file" ref="followlist" v-on:change="followListChange"></input> <input type="file" ref="followlist" v-on:change="followListChange"></input>
</form> </form>
<i class=" icon-spin4 animate-spin uploading" v-if="uploading[3]"></i> <i class=" icon-spin4 animate-spin uploading" v-if="followListUploading"></i>
<button class="btn btn-default" v-else @click="importFollows">{{$t('general.submit')}}</button> <button class="btn btn-default" v-else @click="importFollows">{{$t('general.submit')}}</button>
<div v-if="followsImported"> <div v-if="followsImported">
<i class="icon-cross" @click="dismissImported"></i> <i class="icon-cross" @click="dismissImported"></i>

View File

@ -344,5 +344,19 @@
"reply": "Reply", "reply": "Reply",
"favorite": "Favorite", "favorite": "Favorite",
"user_settings": "User Settings" "user_settings": "User Settings"
},
"upload":{
"error": {
"base": "Upload failed.",
"file_too_big": "File too big [{filesize}{filesizeunit} / {allowedsize}{allowedsizeunit}]",
"default": "Try again later"
},
"file_size_units": {
"B": "B",
"KiB": "KiB",
"MiB": "MiB",
"GiB": "GiB",
"TiB": "TiB"
}
} }
} }

View File

@ -0,0 +1,17 @@
const fileSizeFormat = (num) => {
var exponent
var unit
var units = ['B', 'KiB', 'MiB', 'GiB', 'TiB']
if (num < 1) {
return num + ' ' + units[0]
}
exponent = Math.min(Math.floor(Math.log(num) / Math.log(1024)), units.length - 1)
num = (num / Math.pow(1024, exponent)).toFixed(2) * 1
unit = units[exponent]
return {num: num, unit: unit}
}
const fileSizeFormatService = {
fileSizeFormat
}
export default fileSizeFormatService

View File

@ -0,0 +1,34 @@
import fileSizeFormatService from '../../../../../src/services/file_size_format/file_size_format.js'
describe('fileSizeFormat', () => {
it('Formats file size', () => {
const values = [1, 1024, 1048576, 1073741824, 1099511627776]
const expected = [
{
num: 1,
unit: 'B'
},
{
num: 1,
unit: 'KiB'
},
{
num: 1,
unit: 'MiB'
},
{
num: 1,
unit: 'GiB'
},
{
num: 1,
unit: 'TiB'
}
]
var res = []
for (var value in values) {
res.push(fileSizeFormatService.fileSizeFormat(values[value]))
}
expect(res).to.eql(expected)
})
})