forked from nextcloud/contacts
/
ContactDetailsAvatar.vue
453 lines (409 loc) 路 13.3 KB
/
ContactDetailsAvatar.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
<!--
- @copyright Copyright (c) 2018 Team Popcorn <teampopcornberlin@gmail.com>
-
- @author Team Popcorn <teampopcornberlin@gmail.com>
- @author John Molakvo忙 <skjnldsv@protonmail.com>
-
- @license GNU AGPL version 3 or any later version
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as
- published by the Free Software Foundation, either version 3 of the
- License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-->
<template>
<div class="contact-header-avatar">
<div class="contact-header-avatar__wrapper">
<div class="contact-header-avatar__background" @click="toggleModal" />
<div v-if="contact.photo"
:style="{ 'backgroundImage': `url(${contact.photoUrl})` }"
class="contact-header-avatar__photo"
@click="toggleModal" />
<div v-click-outside="closeMenu" class="contact-header-avatar__options">
<a v-tooltip.bottom="t('contacts', 'Add a new picture')"
href="#"
class="contact-avatar-options"
:class="loading ? 'icon-loading-small' : 'icon-picture-force-white'"
@click.stop.prevent="toggleMenu" />
<input id="contact-avatar-upload"
ref="uploadInput"
type="file"
class="hidden"
accept="image/*"
@change="processFile">
</div>
<Modal v-if="maximizeAvatar"
ref="modal"
class="contact-header-modal"
size="large"
:title="contact.displayName"
@close="toggleModal">
<template #actions>
<ActionButton v-if="!isReadOnly" icon="icon-upload" @click="selectFileInput">
{{ t('contacts', 'Upload new picture') }}
</ActionButton>
<ActionButton v-if="!isReadOnly" icon="icon-folder" @click="selectFilePicker">
{{ t('contacts', 'Choose from files') }}
</ActionButton>
<ActionLink :href="`${contact.url}?photo`" icon="icon-download" target="_blank">
{{ t('contacts', 'Download picture') }}
</ActionLink>
<ActionButton v-if="!isReadOnly" icon="icon-delete" @click="removePhoto">
{{ t('contacts', 'Delete picture') }}
</ActionButton>
</template>
<img ref="img"
:src="contact.photoUrl"
class="contact-header-modal__photo"
:style="{ width, height }"
@load="updateImgSize">
</Modal>
<!-- out of the avatar__options because of the overflow hidden -->
<Actions :open="opened" class="contact-avatar-options__popovermenu">
<ActionButton v-if="!isReadOnly" icon="icon-upload" @click="selectFileInput">
{{ t('contacts', 'Upload a new picture') }}
</ActionButton>
<ActionButton v-if="!isReadOnly" icon="icon-picture" @click="selectFilePicker">
{{ t('contacts', 'Choose from files') }}
</ActionButton>
<!-- FIXME: show only if facebookId present; deactivated for debugging CSP error -->
<!-- <ActionButton v-if="!isReadOnly && hasFacebookId" icon="icon-link" @click="selectWebInput"> -->
<ActionButton v-if="!isReadOnly" icon="icon-link" @click="selectWebInput">
{{ t('contacts', 'Update from social media') }}
</ActionButton>
</Actions>
</div>
</div>
</template>
<script>
import debounce from 'debounce'
import { ActionLink, ActionButton } from '@nextcloud/vue'
import { getFilePickerBuilder } from '@nextcloud/dialogs'
import { generateRemoteUrl } from '@nextcloud/router'
import { getCurrentUser } from '@nextcloud/auth'
import sanitizeSVG from '@mattkrick/sanitize-svg'
const axios = () => import('axios')
export default {
name: 'ContactDetailsAvatar',
components: {
ActionLink,
ActionButton,
},
props: {
contact: {
type: Object,
required: true,
},
},
data() {
return {
maximizeAvatar: false,
opened: false,
loading: false,
root: generateRemoteUrl(`dav/files/${getCurrentUser().uid}`),
width: 0,
height: 0,
}
},
computed: {
isReadOnly() {
if (this.contact.addressbook) {
return this.contact.addressbook.readOnly
}
return false
},
hasFacebookId() {
const jCal = this.contact.jCal.slice(0)
const facebookid = jCal[1].filter(props => props[0] === 'x-socialprofile')
if (facebookid.length > 0) { return true }
return false
},
},
mounted() {
// update image size on window resize
window.addEventListener('resize', debounce(() => {
this.updateImgSize()
}, 100))
},
methods: {
/**
* Handler to store a new photo on the current contact
*
* @param {Object} event the event object containing the image
*/
processFile(event) {
if (event.target.files && !this.loading) {
this.closeMenu()
const file = event.target.files[0]
if (file && file.size && file.size <= 1 * 1024 * 1024) {
const reader = new FileReader()
const self = this
let type = ''
reader.onloadend = async function(e) {
try {
// We got an ArrayBuffer, checking the true mime type...
if (typeof e.target.result === 'object') {
const uint = new Uint8Array(e.target.result)
const bytes = []
uint.forEach((byte) => {
bytes.push(byte.toString(16))
})
const hex = bytes.join('').toUpperCase()
if (self.getMimetype(hex).startsWith('image/')) {
type = self.getMimetype(hex)
// we got a valid image, read it again as base64
reader.readAsDataURL(file)
return
}
throw new Error('Wrong image mimetype')
}
// else we got the base64 and we're good to go!
const imageBase64 = e.target.result.split(',').pop()
if (e.target.result.indexOf('image/svg') > -1) {
const imageSvg = atob(imageBase64)
const cleanSvg = await sanitizeSVG(imageSvg)
if (!cleanSvg) {
throw new Error('Unsafe svg image')
}
}
// All is well! Set the photo
self.setPhoto(imageBase64, type)
} catch (error) {
console.error(error)
OC.Notification.showTemporary(t('contacts', 'Invalid image'))
} finally {
self.resetPicker()
}
}
// start by reading the magic bytes to detect proper photo mimetype
const blob = file.slice(0, 4)
reader.readAsArrayBuffer(blob)
} else {
OC.Notification.showTemporary(t('contacts', 'Image is too big (max 1MB).'))
this.resetPicker()
}
}
},
/**
* Reset image pciker input
*/
resetPicker() {
// reset input
this.$refs.uploadInput.value = ''
this.loading = false
},
/**
* Return the mimetype based on the first magix byte
*
* @param {string} signature the first 4 bytes
* @returns {string} the mimetype
*/
getMimetype(signature) {
switch (signature) {
case '89504E47':
return 'image/png'
case '47494638':
return 'image/gif'
case '3C3F786D':
case '3C737667':
return 'image/svg+xml'
case 'FFD8FFDB':
case 'FFD8FFE0':
case 'FFD8FFE1':
return 'image/jpeg'
default:
return 'application/octet-stream'
}
},
/**
* Update the contact photo
*
* @param {String} data the photo as base64 binary string
* @param {String} type mimetype
*/
setPhoto(data, type) {
// Vcard 3 and 4 have different syntax
// https://tools.ietf.org/html/rfc2426#page-11
if (this.contact.version === '3.0') {
// check if photo property exists to decide whether to add/update it
this.contact.photo
? this.contact.photo = data
: this.contact.vCard.addPropertyWithValue('photo', data)
const photo = this.contact.vCard.getFirstProperty('photo')
photo.setParameter('encoding', 'b')
if (type) {
photo.setParameter('type', type.split('/').pop())
}
} else {
// https://tools.ietf.org/html/rfc6350#section-6.2.4
// check if photo property exists to decide whether to add/update it
this.contact.photo
? this.contact.photo = `data:${type};base64,${data}`
: this.contact.vCard.addPropertyWithValue('photo', `data:${type};base64,${data}`)
}
this.$store.dispatch('updateContact', this.contact)
this.loading = false
},
/**
* Toggle the full image preview
*/
toggleModal() {
// maximise or minimise avatar photo
this.maximizeAvatar = !this.maximizeAvatar
},
/**
* Remove the contact's picture
*/
removePhoto() {
this.contact.vCard.removeProperty('photo')
this.maximizeAvatar = !this.maximizeAvatar
this.$store.dispatch('updateContact', this.contact)
},
/**
* Picker handlers
*/
selectFileInput() {
if (!this.loading) {
this.$refs.uploadInput.click()
}
},
async selectFilePicker() {
if (!this.loading) {
const picker = getFilePickerBuilder(t('contacts', 'Pick an avatar'))
.setMimeTypeFilter([
'image/png',
'image/jpeg',
'image/gif',
'image/x-xbitmap',
'image/bmp',
'image/svg+xml',
])
.build()
const file = await picker.pick()
if (file) {
this.loading = true
try {
const { get } = await axios()
const response = await get(`${this.root}${file}`, {
responseType: 'arraybuffer',
})
const type = response.headers['content-type']
const data = Buffer.from(response.data, 'binary').toString('base64')
this.setPhoto(data, type)
} catch (error) {
OC.Notification.showTemporary(t('contacts', 'Error while processing the picture.'))
console.error(error)
this.loading = false
}
}
}
},
/**
* WebImage handlers
*/
async selectWebInput() {
// getting facebook id from contact
const jCal = this.contact.jCal.slice(0)
const facebookid = jCal[1].filter(props => props[0] === 'x-socialprofile')
if (facebookid.length > 0) {
// TODO: data verification
this.fbProfileUrl = 'https://graph.facebook.com/' + facebookid[0][3] + '/picture?width=720'
console.debug('facebook image found: ' + this.fbProfileUrl)
}
// FIXME: overwriting non-functioning external imageUrl with local one works...
// const imageUrl = 'http://localhost:8099/core/preview?fileId=9&x=192&y=108&a=true'
// but external images don't :/
const imageUrl = 'https://github.githubassets.com/images/icons/emoji/unicode/2764.png'
console.debug('selectWebInput: ' + imageUrl)
if ((!this.loading) && (imageUrl)) {
this.loading = true
try {
const { get } = await axios()
const response = await get(`${imageUrl}`, {
responseType: 'arraybuffer',
})
const type = response.headers['content-type']
// TODO: error hanndling
console.debug('response: ' + response.status)
if (response.status !== 200) throw new URIError('verify set facebook profile id')
const data = Buffer.from(response.data, 'binary').toString('base64')
this.setPhoto(data, type)
} catch (error) {
OC.Notification.showTemporary(t('contacts', 'Error while processing the picture.'))
console.error(error)
this.loading = false
}
}
},
/**
* Menu handling
*/
toggleMenu() {
// only open if not loading
this.opened = !this.opened ? !this.opened && !this.loading : false
},
closeMenu() {
this.opened = false
},
updateImgSize() {
if (this.contact.photo && this.$refs.img) {
this.updateHeightWidth(this.$refs.img.naturalHeight, this.$refs.img.naturalWidth)
}
},
/**
* Updates the current height and width data
* based on the viewer maximum size
*
* @param {Integer} contentHeight your element height
* @param {Integer} contentWidth your element width
*/
updateHeightWidth(contentHeight, contentWidth) {
const modalWrapper = this.$refs.modal.$el.querySelector('.modal-wrapper')
if (modalWrapper) {
const modalContainer = modalWrapper.querySelector('.modal-container')
const wrapperMaxHeight = window.getComputedStyle(modalContainer).maxHeight.replace('%', '')
const wrapperMaxWidth = window.getComputedStyle(modalContainer).maxWidth.replace('%', '')
const parentHeight = Math.round(modalWrapper.clientHeight * Number(wrapperMaxHeight) / 100) - 50 // minus header
const parentWidth = Math.round(modalWrapper.clientWidth * Number(wrapperMaxWidth) / 100)
const heightRatio = parentHeight / contentHeight
const widthRatio = parentWidth / contentWidth
// if the video height is capped by the parent height
// AND the video is bigger than the parent
if (heightRatio < widthRatio && heightRatio < 1) {
this.height = parentHeight + 'px'
this.width = Math.round(contentWidth / contentHeight * parentHeight) + 'px'
// if the video width is capped by the parent width
// AND the video is bigger than the parent
} else if (heightRatio > widthRatio && widthRatio < 1) {
this.width = parentWidth + 'px'
this.height = Math.round(contentHeight / contentWidth * parentWidth) + 'px'
// RESET
} else {
// displaying tiny images makes no sense,
// let's try to an least dispay them at 100x100
// AND to keep the ratio
if (contentHeight < 100) {
this.height = 100 + 'px'
this.width = null
} else if (contentWidth < 100) {
this.width = 100 + 'px'
this.height = null
} else {
this.height = contentHeight + 'px'
this.width = contentWidth + 'px'
}
}
}
},
},
}
</script>