summaryrefslogtreecommitdiffstats
path: root/src/components/MessagesList/MessagesGroup/Message/MessagePart/FilePreview.vue
blob: b013d62d0278ce80651e78f4e09a878264adbc72 (plain)
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
<!--
  - @copyright Copyright (c) 2019 Joas Schilling <coding@schilljs.com>
  - @copyright Copyright (c) 2020 Marco Ambrosini <marcoambrosini@pm.me>
  -
  - @author Joas Schilling <coding@schilljs.com>
  - @author Marco Ambrosini <marcoambrosini@pm.me>
  -
  - @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>
	<file-preview v-bind="filePreview"
		:tabindex="wrapperTabIndex"
		class="file-preview"
		:class="{ 'file-preview--viewer-available': isViewerAvailable, 'file-preview--upload-editor': isUploadEditor }"
		@click="handleClick"
		@keydown.enter="handleClick">
		<div
			v-if="!isLoading"
			class="image-container"
			:class="{'playable': isPlayable}">
			<span v-if="isPlayable && !smallPreview" class="play-video-button">
				<PlayCircleOutline
					:size="48"
					decorative
					fill-color="#ffffff"
					title="" />
			</span>
			<img v-if="!failed"
				v-tooltip="previewTooltip"
				:class="previewImageClass"
				class="file-preview__image"
				alt=""
				:src="previewUrl">
			<img v-else
				:class="previewImageClass"
				alt=""
				:src="defaultIconUrl">
		</div>
		<span v-if="isLoading"
			v-tooltip="previewTooltip"
			class="preview loading" />
		<button v-if="isUploadEditor"
			tabindex="1"
			:aria-label="removeAriaLabel"
			class="remove-file primary">
			<Close
				class="remove-file__icon"
				decorative
				title=""
				@click="$emit('remove-file', id)" />
		</button>
		<ProgressBar v-if="isTemporaryUpload && !isUploadEditor" :value="uploadProgress" />
		<div class="name-container">
			<strong v-if="shouldShowFileName">{{ name }}</strong>
		</div>
	</file-preview>
</template>

<script>
import { generateUrl, imagePath, generateRemoteUrl } from '@nextcloud/router'
import ProgressBar from '@nextcloud/vue/dist/Components/ProgressBar'
import Tooltip from '@nextcloud/vue/dist/Directives/Tooltip'
import Close from 'vue-material-design-icons/Close'
import PlayCircleOutline from 'vue-material-design-icons/PlayCircleOutline'
import { getCapabilities } from '@nextcloud/capabilities'
import { encodePath } from '@nextcloud/paths'

const PREVIEW_TYPE = {
	TEMPORARY: 0,
	MIME_ICON: 1,
	DIRECT: 2,
	PREVIEW: 3,
}

export default {
	name: 'FilePreview',

	components: {
		ProgressBar,
		Close,
		PlayCircleOutline,
	},

	directives: {
		tooltip: Tooltip,
	},

	props: {
		/**
		 * File id
		 */
		id: {
			type: String,
			required: true,
		},
		/**
		 * File name
		 */
		name: {
			type: String,
			required: true,
		},
		/**
		 * File path relative to the user's home storage,
		 * or link share root, includes the file name.
		 */
		path: {
			type: String,
			default: '',
		},
		/**
		 * File size in bytes
		 */
		size: {
			type: Number,
			default: -1,
		},
		/**
		 * Download link
		 */
		link: {
			type: String,
			default: '',
		},
		/**
		 * Mime type
		 */
		mimetype: {
			type: String,
			default: '',
		},
		/**
		 * Whether a preview is available, string "yes" for yes
		 * otherwise the string "no"
		 */
		// FIXME: use booleans here
		previewAvailable: {
			type: String,
			default: 'no',
		},
		/**
		 * Whether to render a small preview to embed in replies
		 */
		smallPreview: {
			type: Boolean,
			default: false,
		},
		/**
		 * Upload id from the file upload store.
		 *
		 * In case this component is used to display a file that is being uploaded
		 * this parameter is used to access the file upload status in the store
		 */
		uploadId: {
			type: Number,
			default: null,
		},
		/**
		 * File upload index from the file upload store.
		 *
		 * In case this component is used to display a file that is being uploaded
		 * this parameter is used to access the file upload status in the store
		 */
		index: {
			type: String,
			default: '',
		},
		/**
		 * Whether the container is the upload editor.
		 * True if this component is used in the upload editor.
		 */
		// FIXME: file-preview should be encapsulated and not be aware of its surroundings
		isUploadEditor: {
			type: Boolean,
			default: false,
		},
		/**
		 * The link to the file for displaying it in the preview
		 */
		localUrl: {
			type: String,
			default: '',
		},
	},
	data() {
		return {
			isLoading: true,
			failed: false,
		}
	},
	computed: {
		shouldShowFileName() {
			// display the file name below the preview if the preview
			// is not easily recognizable, when:
			return (
				// the file is not an image
				!this.mimetype.startsWith('image/')
				// the image has no preview (ex: disabled on server)
				|| (this.previewAvailable !== 'yes' && !this.localUrl)
				// the preview failed loading
				|| this.failed
				// always show in upload editor
				|| this.isUploadEditor
			)
		},
		previewTooltip() {
			if (this.shouldShowFileName) {
				// no tooltip as the file name is already visible directly
				return null
			}
			return {
				content: this.name,
				delay: { show: 500 },
				placement: 'left',
			}
		},
		// This is used to decide which outer element type to use
		// a or div
		filePreview() {
			if (this.isUploadEditor || this.isTemporaryUpload) {
				return {
					is: 'div',
					tag: 'div',
				}
			}
			return {
				is: 'a',
				tag: 'a',
				href: this.link,
				target: '_blank',
				rel: 'noopener noreferrer',
			}
		},
		defaultIconUrl() {
			return imagePath('core', 'filetypes/file')
		},
		previewImageClass() {
			let classes = ''
			if (this.smallPreview) {
				classes += 'preview-small '
			} else {
				classes += 'preview '
			}

			if (this.failed || this.previewType === PREVIEW_TYPE.MIME_ICON) {
				classes += 'mimeicon'
			}
			return classes
		},
		previewType() {
			if (this.hasTemporaryImageUrl) {
				return PREVIEW_TYPE.TEMPORARY
			}

			if (this.previewAvailable !== 'yes') {
				return PREVIEW_TYPE.MIME_ICON
			}
			const maxGifSize = getCapabilities()?.spreed?.config?.previews?.['max-gif-size'] || 3145728
			if (this.mimetype === 'image/gif' && this.size <= maxGifSize) {
				return PREVIEW_TYPE.DIRECT
			}

			return PREVIEW_TYPE.PREVIEW
		},
		previewUrl() {
			const userId = this.$store.getters.getUserId()

			if (this.previewType === PREVIEW_TYPE.TEMPORARY) {
				return this.localUrl
			}
			if (this.previewType === PREVIEW_TYPE.MIME_ICON) {
				return OC.MimeType.getIconUrl(this.mimetype)
			}
			// whether to embed/render the file directly
			if (this.previewType === PREVIEW_TYPE.DIRECT) {
				// return direct image
				if (userId === null) {
					// guest mode, use public link download URL
					return this.link + '/download/' + encodePath(this.name)
				} else {
					// use direct DAV URL
					return generateRemoteUrl(`dav/files/${userId}`) + encodePath(this.internalAbsolutePath)
				}
			}

			// use preview provider URL to render a smaller preview
			let previewSize = 384
			if (this.smallPreview) {
				previewSize = 32
			}
			previewSize = Math.ceil(previewSize * window.devicePixelRatio)
			if (userId === null) {
				// guest mode: grab token from the link URL
				// FIXME: use a cleaner way...
				const token = this.link.substr(this.link.lastIndexOf('/') + 1)
				return generateUrl('/apps/files_sharing/publicpreview/{token}?x=-1&y={height}&a=1', {
					token: token,
					height: previewSize,
				})
			} else {
				return generateUrl('/core/preview?fileId={fileId}&x=-1&y={height}&a=1', {
					fileId: this.id,
					height: previewSize,
				})
			}
		},
		isViewerAvailable() {
			if (!OCA.Viewer) {
				return false
			}

			const availableHandlers = OCA.Viewer.availableHandlers
			for (let i = 0; i < availableHandlers.length; i++) {
				if (availableHandlers[i]?.mimes?.includes(this.mimetype)) {
					return true
				}
			}

			return false
		},
		isPlayable() {
			// don't show play button for direct renders
			if (this.failed || !this.isViewerAvailable || this.previewType !== PREVIEW_TYPE.PREVIEW) {
				return false
			}

			// videos only display a preview, so always show a button if playable
			return this.mimetype === 'image/gif' || this.mimetype.startsWith('video/')
		},
		internalAbsolutePath() {
			if (this.path.startsWith('/')) {
				return this.path
			}

			return '/' + this.path
		},
		isTemporaryUpload() {
			return this.id.startsWith('temp') && this.index && this.uploadId
		},
		uploadProgress() {
			if (this.isTemporaryUpload) {
				if (this.$store.getters.uploadProgress(this.uploadId, this.index)) {
					return this.$store.getters.uploadProgress(this.uploadId, this.index)
				}
			}
			// likely never reached
			return 0
		},
		hasTemporaryImageUrl() {
			return this.mimetype.startsWith('image/') && this.localUrl
		},

		wrapperTabIndex() {
			return this.isUploadEditor ? '0' : ''
		},

		removeAriaLabel() {
			return t('spreed', 'Remove {fileName}', { fileName: this.name })
		},
	},
	mounted() {
		const img = new Image()
		img.onerror = () => {
			this.isLoading = false
			this.failed = true
		}
		img.onload = () => {
			this.isLoading = false
		}
		img.src = this.previewUrl
	},
	methods: {
		handleClick(event) {
			if (this.isUploadEditor) {
				this.$emit('remove-file', this.id)
				return
			}

			if (!this.isViewerAvailable) {
				// Regular event handling by opening the link.
				return
			}

			event.stopPropagation()
			event.preventDefault()

			// The Viewer expects a file to be set in the sidebar if the sidebar
			// is open.
			if (this.$store.getters.getSidebarStatus) {
				OCA.Files.Sidebar.state.file = this.internalAbsolutePath
			}

			OCA.Viewer.open({
				// Viewer expects an internal absolute path starting with "/".
				path: this.internalAbsolutePath,
				list: [
					{
						fileid: parseInt(this.id, 10),
						filename: this.internalAbsolutePath,
						basename: this.name,
						mime: this.mimetype,
						hasPreview: this.previewAvailable === 'yes',
					},
				],
			})
		},
	},
}
</script>

<style lang="scss" scoped>
@import '../../../../../assets/variables.scss';

.file-preview {
	position: relative;
	width: 100%;
	/* The file preview can not be a block; otherwise it would fill the whole
	width of the container and the loading icon would not be centered on the
	image. */
	display: inline-block;

	border-radius: 16px;

	&:hover,
	&:focus {
		background-color: var(--color-background-hover);
		/* Trick to keep the same position while adding a padding to show
			* the background. */
		box-sizing: content-box !important;
		.remove-file {
			visibility: visible;
		}
	}

	&__image {
		object-fit: cover;
	}

	.loading {
		display: inline-block;
		width: 100%;
	}

	.mimeicon {
		min-height: 128px;
	}

	.mimeicon.preview-small {
		min-height: auto;
		height: 32px;
	}

	.preview {
		display: inline-block;
		border-radius: var(--border-radius);
		max-width: 100%;
		max-height: 384px;
	}
	.preview-small {
		display: inline-block;
		border-radius: var(--border-radius);
		max-width: 100%;
		max-height: 32px;
	}

	.image-container {
		display: inline-block;
		position: relative;

		&.playable {
			.preview {
				transition: filter 250ms ease-in-out;
			}

			.play-video-button {
				position: absolute;
				height: 48px; /* for proper vertical centering */
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				opacity: 0.8;
				z-index: 1;
				transition: opacity 250ms ease-in-out;
			}

			&:hover {
				.preview {
					filter: brightness(80%);
				}

				.play-video-button {
					opacity: 1;
				}
			}
		}
	}

	.name-container {
		/* Ellipsis with 100% width */
		display: table;
		table-layout: fixed;
		width: 100%;

		strong {
			/* As the file preview is an inline block the name is set as a block to
			force it to be on its own line below the preview. */
			display: block;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}
	}

	&:not(.file-preview--viewer-available) {
		strong:after {
			content: ' ↗';
		}
	}
	&--upload-editor {
		max-width: 160px;
		max-height: 160px;
		margin: 10px;
		padding: 12px;
		.preview {
			margin: auto;
			width: 128px;
			height: 128px;
		}
		.loading {
			width: 100%;
		}
	}
}

.remove-file {
	visibility: hidden;
	position: absolute;
	top: 8px;
	right: 8px;
	box-shadow: 0 0 4px var(--color-box-shadow);
	width: $clickable-area;
	height: $clickable-area;
	padding: 0;
	margin: 0;
	&__icon {
		color: var(--color-primary-text);
	}
}

</style>