-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathViewer.vue
1371 lines (1200 loc) · 36.4 KB
/
Viewer.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
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!--
- @copyright Copyright (c) 2019 John Molakvoæ <skjnldsv@protonmail.com>
- @copyright Copyright (c) 2020 Gary Kim <gary@garykim.dev>
-
- @author John Molakvoæ <skjnldsv@protonmail.com>
-
- @license AGPL-3.0-or-later
-
- 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>
<!-- Single-file rendering -->
<div v-if="el"
id="viewer"
:data-handler="handlerId">
<component :is="currentFile.modal"
v-if="!currentFile.failed"
:key="currentFile | uniqueKey"
ref="content"
:active="true"
:can-swipe="false"
v-bind="currentFile"
:file-list="[currentFile]"
:is-full-screen="false"
:loaded.sync="currentFile.loaded"
:is-sidebar-shown="false"
class="viewer__file viewer__file--active"
@error="currentFailed" />
<Error v-else
:name="currentFile.basename" />
</div>
<!-- Modal view rendering -->
<NcModal v-else-if="initiated || currentFile.modal"
id="viewer"
:additional-trap-elements="trapElements"
:class="modalClass"
:clear-view-delay="-1 /* disable fade-out because of accessibility reasons */"
:close-button-contained="false"
:dark="true"
:data-handler="handlerId"
:enable-slideshow="hasPrevious || hasNext"
:slideshow-paused="editing"
:enable-swipe="canSwipe && !editing"
:has-next="hasNext"
:has-previous="hasPrevious"
:inline-actions="canEdit ? 1 : 0"
:spread-navigation="true"
:style="{ width: isSidebarShown ? `${sidebarPosition}px` : null }"
:name="currentFile.basename"
:view="currentFile.modal"
class="viewer"
size="full"
@close="close"
@previous="previous"
@next="next">
<!-- ACTIONS -->
<template #actions>
<!-- Inline items -->
<NcActionButton v-if="canEdit"
:close-after-click="true"
@click="onEdit">
<template #icon>
<Pencil :size="20" />
</template>
{{ t('viewer', 'Edit') }}
</NcActionButton>
<!-- Menu items -->
<NcActionButton :close-after-click="true"
@click="toggleFullScreen">
<template #icon>
<Fullscreen v-if="!isFullscreenMode" :size="20" />
<FullscreenExit v-else :size="20" />
</template>
{{ isFullscreenMode ? t('viewer', 'Exit full screen') : t('viewer', 'Full screen') }}
</NcActionButton>
<NcActionButton v-if="enableSidebar && Sidebar && sidebarOpenFilePath && !isSidebarShown"
:close-after-click="true"
icon="icon-menu-sidebar"
@click="showSidebar">
{{ t('viewer', 'Open sidebar') }}
</NcActionButton>
<NcActionLink v-if="canDownload"
:download="currentFile.basename"
:close-after-click="true"
:href="downloadPath">
<template #icon>
<Download :size="24" />
</template>
{{ t('viewer', 'Download') }}
</NcActionLink>
<NcActionButton v-if="canDelete"
:close-after-click="true"
@click="onDelete">
<template #icon>
<Delete :size="22" />
</template>
{{ t('viewer', 'Delete') }}
</NcActionButton>
</template>
<div class="viewer__content" :class="contentClass" @click.self.exact="close">
<!-- COMPARE FILE -->
<div v-if="comparisonFile && !comparisonFile.failed && showComparison" class="viewer__file-wrapper">
<component :is="comparisonFile.modal"
:key="comparisonFile | uniqueKey"
ref="comparison-content"
v-bind="comparisonFile"
:active="true"
:can-swipe="false"
:can-zoom="false"
:editing="false"
:is-full-screen="isFullscreen"
:is-sidebar-shown="isSidebarShown"
:loaded.sync="comparisonFile.loaded"
class="viewer__file viewer__file--active"
@error="comparisonFailed" />
</div>
<!-- PREVIOUS -->
<div v-if="previousFile"
:key="previousFile | uniqueKey"
class="viewer__file-wrapper viewer__file-wrapper--hidden"
aria-hidden="true"
inert>
<component :is="previousFile.modal"
v-if="!previousFile.failed"
ref="previous-content"
v-bind="previousFile"
:file-list="fileList"
class="viewer__file"
@error="previousFailed" />
<Error v-else
:name="previousFile.basename" />
</div>
<!-- CURRENT -->
<div :key="currentFile | uniqueKey" class="viewer__file-wrapper">
<component :is="currentFile.modal"
v-if="!currentFile.failed"
ref="content"
v-bind="currentFile"
:active="true"
:can-swipe.sync="canSwipe"
:can-zoom="canZoom"
:editing.sync="editing"
:file-list="fileList"
:is-full-screen="isFullscreen"
:is-sidebar-shown="isSidebarShown"
:loaded.sync="currentFile.loaded"
class="viewer__file viewer__file--active"
@error="currentFailed" />
<Error v-else
:name="currentFile.basename" />
</div>
<!-- NEXT -->
<div v-if="nextFile"
:key="nextFile | uniqueKey"
class="viewer__file-wrapper viewer__file-wrapper--hidden"
aria-hidden="true"
inert>
<component :is="nextFile.modal"
v-if="!nextFile.failed"
ref="next-content"
v-bind="nextFile"
:file-list="fileList"
class="viewer__file"
@error="nextFailed" />
<Error v-else
:name="nextFile.basename" />
</div>
</div>
</NcModal>
</template>
<script>
import '@nextcloud/dialogs/style.css'
import Vue from 'vue'
import axios from '@nextcloud/axios'
import { showError } from '@nextcloud/dialogs'
import { emit, subscribe, unsubscribe } from '@nextcloud/event-bus'
import { registerFileAction, FileAction, Permission, DefaultType, Node, davRemoteURL, davRootPath } from '@nextcloud/files'
import { loadState } from '@nextcloud/initial-state'
import getSortingConfig from '../services/FileSortingConfig.ts'
import isFullscreen from '@nextcloud/vue/dist/Mixins/isFullscreen.js'
import isMobile from '@nextcloud/vue/dist/Mixins/isMobile.js'
import { extractFilePaths, sortCompare } from '../utils/fileUtils.ts'
import canDownload from '../utils/canDownload.js'
import cancelableRequest from '../utils/CancelableRequest.js'
import Error from '../components/Error.vue'
import File from '../models/file.js'
import filesActionHandler from '../services/FilesActionHandler.js'
import legacyFilesActionHandler from '../services/LegacyFilesActionHandler.js'
import getFileInfo from '../services/FileInfo.ts'
import getFileList from '../services/FileList.ts'
import Mime from '../mixins/Mime.js'
import logger from '../services/logger.js'
import Delete from 'vue-material-design-icons/Delete.vue'
import Download from 'vue-material-design-icons/Download.vue'
import EyeSvg from '@mdi/svg/svg/eye.svg?raw'
import Fullscreen from 'vue-material-design-icons/Fullscreen.vue'
import FullscreenExit from 'vue-material-design-icons/FullscreenExit.vue'
import Pencil from 'vue-material-design-icons/Pencil.vue'
// Dynamic loading
const NcModal = () => import(
/* webpackChunkName: 'components' */
/* webpackPrefetch: true */
'@nextcloud/vue/dist/Components/NcModal.js')
const NcActionLink = () => import(/* webpackChunkName: 'components' */'@nextcloud/vue/dist/Components/NcActionLink.js')
const NcActionButton = () => import(/* webpackChunkName: 'components' */'@nextcloud/vue/dist/Components/NcActionButton.js')
export default {
name: 'Viewer',
components: {
Delete,
Download,
Error,
Fullscreen,
FullscreenExit,
NcActionButton,
NcActionLink,
NcModal,
Pencil,
},
filters: {
uniqueKey(file) {
return '' + file.fileid + file.source
},
},
mixins: [isFullscreen, isMobile],
data() {
return {
// Reactivity bindings
Viewer: OCA.Viewer,
Sidebar: null,
handlers: OCA.Viewer.availableHandlers,
// Viewer variables
components: {},
mimeGroups: {},
registeredHandlers: {},
// Files variables
currentIndex: 0,
previousFile: {},
currentFile: {},
comparisonFile: null,
nextFile: {},
fileList: [],
sortingConfig: null,
// States
isLoaded: false,
initiated: false,
editing: false,
// cancellable requests
cancelRequestFile: () => {},
cancelRequestFolder: () => {},
// Flags
sidebarPosition: 0,
isSidebarShown: false,
isFullscreenMode: false,
canSwipe: true,
// TODO: remove OCA?.Files?.fileActions when public Files is Vue
isStandalone: OCP?.Files === undefined && OCA?.Files?.fileActions === undefined,
theme: null,
root: davRemoteURL,
handlerId: '',
trapElements: [],
}
},
computed: {
downloadPath() {
return this.currentFile.source ?? this.currentFile.davPath
},
hasPrevious() {
return this.fileList.length > 1
&& (this.canLoop || !this.isStartOfList)
},
hasNext() {
return this.fileList.length > 1
&& (this.canLoop || !this.isEndOfList)
},
file() {
return this.Viewer.file
},
fileInfo() {
return this.Viewer.fileInfo
},
comparisonFileInfo() {
return this.Viewer.compareFileInfo
},
files() {
return this.Viewer.files
},
enableSidebar() {
return this.Viewer.enableSidebar
},
el() {
return this.Viewer.el
},
loadMore() {
return this.Viewer.loadMore
},
canLoop() {
return this.Viewer.canLoop
},
canZoom() {
return !this.Viewer.el
},
isStartOfList() {
return this.currentIndex === 0
},
isEndOfList() {
return this.currentIndex === this.fileList.length - 1
},
isImage() {
return ['image/jpeg', 'image/png', 'image/webp'].includes(this.currentFile?.mime)
},
/**
* Returns the path to the current opened file in the sidebar.
*
* If the sidebar is available but closed an empty string is returned.
* If the sidebar is not available null is returned.
*
* @return {string|null} the path to the current opened file in the
* sidebar, if any.
*/
sidebarFile() {
return this.Sidebar && this.Sidebar.file
},
sidebarOpenFilePath() {
try {
const relativePath = this.currentFile?.davPath?.split(davRootPath)[1]
return relativePath?.split('/')?.map(decodeURIComponent)?.join('/')
} catch (e) {
return false
}
},
/**
* Is the current user allowed to delete the file?
*
* @return {boolean}
*/
canDelete() {
return this.currentFile?.permissions?.includes('D')
},
/**
* Is the current user allowed to download the file in public mode?
*
* @return {boolean}
*/
canDownload() {
return canDownload() && !this.comparisonFile
},
/**
* Is the current user allowed to edit the file ?
* https://github.com/nextcloud/server/blob/7718c9776c5903474b8f3cf958cdd18a53b2449e/apps/dav/lib/Connector/Sabre/Node.php#L357-L387
*
* @return {boolean}
*/
canEdit() {
return !this.isMobile
&& canDownload()
&& this.currentFile?.permissions?.includes('W')
&& this.isImage
&& !this.comparisonFile
&& (loadState('core', 'config', [])['enable_non-accessible_features'] ?? true)
},
modalClass() {
return {
'icon-loading': !this.currentFile.loaded && !this.currentFile.failed,
'theme--undefined': this.theme === null,
'theme--dark': this.theme === 'dark',
'theme--light': this.theme === 'light',
'theme--default': this.theme === 'default',
'image--fullscreen': this.isImage && this.isFullscreenMode,
}
},
showComparison() {
return !this.isMobile
},
contentClass() {
return {
'viewer--split': this.comparisonFile,
}
},
isSameFile() {
return (fileInfo = null, path = null) => {
if (
path && path === this.currentFile.path
&& !this.currentFile.source
) {
return true
}
if (
fileInfo && fileInfo.fileid === this.currentFile.fileid
&& fileInfo.mtime && fileInfo.mtime === this.currentFile.mtime
&& fileInfo.source && fileInfo.source === this.currentFile.source
) {
return true
}
return false
}
},
},
watch: {
el(element) {
logger.info(element)
this.$nextTick(() => {
const viewerRoot = document.getElementById('viewer')
if (element) {
const el = document.querySelector(element)
if (el) {
el.appendChild(viewerRoot)
} else {
logger.warn('Could not find element ', { element })
}
} else {
document.body.appendChild(viewerRoot)
}
})
},
file(path) {
// we got a valid path! Load file...
if (path && path.trim() !== '') {
logger.info('Opening viewer for file ', { path })
this.openFile(path, OCA.Viewer.overrideHandlerId)
} else {
// path is empty, we're closing!
this.cleanup()
}
},
fileInfo(fileInfo) {
if (fileInfo) {
logger.info('Opening viewer for fileInfo ', { fileInfo })
this.openFileInfo(fileInfo, OCA.Viewer.overrideHandlerId)
} else {
// object is undefined, we're closing!
this.cleanup()
}
},
comparisonFileInfo(fileInfo) {
if (fileInfo) {
logger.info('Opening viewer for comparisonFileInfo ', { fileInfo })
this.compareFile(fileInfo)
} else {
// object is undefined, we're closing!
this.cleanup()
}
},
files(fileList) {
// the files list changed, let's update the current opened index
const currentIndex = fileList.findIndex(file => file.filename === this.currentFile.filename)
if (currentIndex > -1) {
this.currentIndex = currentIndex
logger.debug('The files list changed, new current file index is ' + currentIndex)
}
// finally replace the fileList
this.fileList = fileList
},
// user reached the end of list
async isEndOfList(isEndOfList) {
if (!isEndOfList) {
return
}
// if we have a loadMore handler, let's fetch more files
if (this.loadMore && typeof this.loadMore === 'function') {
logger.debug('Fetching additional files...')
const list = await this.loadMore()
if (Array.isArray(list) && list.length > 0) {
this.fileList.push(...list)
}
}
},
},
beforeMount() {
// register on load
document.addEventListener('DOMContentLoaded', () => {
// register all primary components mimes
this.handlers.forEach(handler => {
this.registerHandler(handler)
})
// then register aliases. We need to have the components
// first so we can bind the alias to them.
this.handlers.forEach(handler => {
this.registerHandlerAlias(handler)
})
this.isLoaded = true
// bind Sidebar if available
if (OCA?.Files?.Sidebar) {
this.Sidebar = OCA.Files.Sidebar.state
}
this.registerFileActions()
logger.info(`${this.handlers.length} viewer handlers registered`, { handlers: this.handlers })
})
window.addEventListener('resize', this.onResize)
if (this.isStandalone) {
logger.info('No OCP.Files app found, viewer is now in standalone mode')
}
},
mounted() {
// React to Files' Sidebar events.
subscribe('files:sidebar:opened', this.handleAppSidebarOpen)
subscribe('files:sidebar:closed', this.handleAppSidebarClose)
subscribe('files:node:updated', this.handleFileUpdated)
subscribe('viewer:trapElements:changed', this.handleTrapElementsChange)
window.addEventListener('keydown', this.keyboardDeleteFile)
window.addEventListener('keydown', this.keyboardDownloadFile)
window.addEventListener('keydown', this.keyboardEditFile)
this.addFullscreenEventListeners()
},
beforeDestroy() {
window.removeEventListener('resize', this.onResize)
},
destroyed() {
// Unsubscribe to Files Sidebar events.
unsubscribe('files:sidebar:opened', this.handleAppSidebarOpen)
unsubscribe('files:sidebar:closed', this.handleAppSidebarClose)
unsubscribe('viewer:trapElements:changed', this.handleTrapElementsChange)
window.removeEventListener('keydown', this.keyboardDeleteFile)
window.removeEventListener('keydown', this.keyboardDownloadFile)
window.removeEventListener('keydown', this.keyboardEditFile)
this.removeFullscreenEventListeners()
},
methods: {
async beforeOpen() {
// initial loading start
this.initiated = true
if (OCA?.Files?.Sidebar?.setFullScreenMode) {
OCA.Files.Sidebar.setFullScreenMode(true)
}
this.sortingConfig = await getSortingConfig()
},
/**
* Open the view and display the clicked file
*
* @param {string} path the file path to open
* @param {string|null} overrideHandlerId the ID of the handler with which to view the files, if any
*/
async openFile(path, overrideHandlerId = null) {
await this.beforeOpen()
// cancel any previous request
this.cancelRequestFile()
// do not open the same file again
if (this.isSameFile(null, path)) {
return
}
const { request: fileRequest, cancel: cancelRequestFile } = cancelableRequest(getFileInfo)
this.cancelRequestFile = cancelRequestFile
// extract needed info from path
const [, fileName] = extractFilePaths(path)
// prevent scrolling while opened
if (!this.el) {
document.body.style.overflow = 'hidden'
document.documentElement.style.overflow = 'hidden'
}
// swap title with original one
const title = document.getElementsByTagName('head')[0].getElementsByTagName('title')[0]
if (title && !title.dataset.old) {
title.dataset.old = document.title
this.updateTitle(fileName)
}
try {
// retrieve and store the file info
const fileInfo = await fileRequest(path)
console.debug('File info for ' + path + ' fetched', fileInfo)
await this.openFileInfo(fileInfo, overrideHandlerId)
} catch (error) {
if (error?.response?.status === 404) {
logger.error('The file no longer exists, error: ', { error })
showError(t('viewer', 'This file no longer exists'))
this.close()
} else {
console.error('Could not open file ' + path, error)
}
}
},
/**
* Open the view and display the clicked file from a known file info object
*
* @param {object} fileInfo the file info object to open
* @param {string|null} overrideHandlerId the ID of the handler with which to view the files, if any
*/
async openFileInfo(fileInfo, overrideHandlerId = null) {
this.beforeOpen()
// cancel any previous request
this.cancelRequestFolder()
// do not open the same file info again
if (this.isSameFile(fileInfo)) {
return
}
// get original mime and alias
const mime = fileInfo.mime
const alias = mime.split('/')[0]
let handler
// Try provided handler, if any
if (overrideHandlerId !== null) {
const overrideHandler = Object.values(this.registeredHandlers).find(h => h.id === overrideHandlerId)
handler = overrideHandler ?? handler
}
// If no provided handler, or provided handler not found: try a supported handler with mime/mime-alias
if (!handler) {
handler = this.registeredHandlers[mime] ?? this.registeredHandlers[alias]
}
// if we don't have a handler for this mime, abort
if (!handler) {
logger.error('The following file could not be displayed', { fileInfo })
showError(t('viewer', 'There is no plugin available to display this file type'))
this.close()
return
}
this.theme = handler.theme ?? 'dark'
this.handlerId = handler.id
// check if part of a group, if so retrieve full files list
const group = this.mimeGroups[mime]
if (this.files && this.files.length > 0) {
logger.debug('A files list have been provided. No folder content will be fetched.')
// we won't sort files here, let's use the order the array has
this.fileList = this.files
// store current position
this.currentIndex = this.fileList.findIndex(file => file.filename === fileInfo.filename)
} else if (group && this.el === null) {
const mimes = this.mimeGroups[group]
? this.mimeGroups[group]
: [mime]
// retrieve folder list
const { request: folderRequest, cancel: cancelRequestFolder } = cancelableRequest(getFileList)
this.cancelRequestFolder = cancelRequestFolder
const [dirPath] = extractFilePaths(fileInfo.filename)
const fileList = await folderRequest(dirPath)
// filter out the unwanted mimes
const filteredFiles = fileList.filter(file => file.mime && mimes.indexOf(file.mime) !== -1)
// sort like the files list
// TODO: implement global sorting API
// https://github.com/nextcloud/server/blob/a83b79c5f8ab20ed9b4d751167417a65fa3c42b8/apps/files/lib/Controller/ApiController.php#L247
this.fileList = filteredFiles.sort((a, b) => sortCompare(a, b, this.sortingConfig.key, this.sortingConfig.asc))
// store current position
this.currentIndex = this.fileList.findIndex(file => file.filename === fileInfo.filename)
} else {
this.currentIndex = 0
this.fileList = [fileInfo]
}
// get saved fileInfo
fileInfo = this.fileList[this.currentIndex]
// show file
this.currentFile = new File(fileInfo, mime, handler.component)
this.comparisonFile = null
this.updatePreviousNext()
// if sidebar was opened before, let's update the file
this.changeSidebar()
},
/**
* Open the view and display the file from the file list
*
* @param {object} fileInfo the opened file info
*/
openFileFromList(fileInfo) {
// override mimetype if existing alias
const mime = fileInfo.mime
this.currentFile = new File(fileInfo, mime, this.components[mime])
this.changeSidebar()
this.updatePreviousNext()
},
async compareFile(fileInfo) {
this.comparisonFile = new File(fileInfo, fileInfo.mime, this.components[fileInfo.mime])
},
/**
* Show sidebar if available and a file is already opened
*/
changeSidebar() {
if (this.sidebarFile) {
this.showSidebar()
}
},
/**
* Update the previous and next file components
*/
updatePreviousNext() {
const prev = this.fileList[this.currentIndex - 1]
const next = this.fileList[this.currentIndex + 1]
if (prev) {
const mime = prev.mime
if (this.components[mime]) {
this.previousFile = new File(prev, mime, this.components[mime])
}
} else {
// RESET
this.previousFile = null
}
if (next) {
const mime = next.mime
if (this.components[mime]) {
this.nextFile = new File(next, mime, this.components[mime])
}
} else {
// RESET
this.nextFile = null
}
},
updateTitle(fileName) {
document.title = `${fileName} - ${OCA.Theming?.name ?? oc_defaults.name}`
},
/**
* Registering possible new handers
*
* @param {object} handler the handler to register
* @param {string} handler.id unique handler identifier
* @param {Array} handler.mimes list of valid mimes compatible with the handler
* @param {object} handler.component a vuejs component to render when a file matching the mime list is opened
* @param {string} [handler.group] a group name to be associated with for the slideshow
*/
registerHandler(handler) {
// checking if handler is not already registered
if (handler.id && Object.values(this.registeredHandlers).findIndex((h) => h.id === handler.id) > -1) {
logger.error('The following handler is already registered', { handler })
return
}
// checking valid handler id
if (!handler.id || handler.id.trim() === '' || typeof handler.id !== 'string') {
logger.error('The following handler doesn\'t have a valid id', { handler })
return
}
// checking if no valid mimes data but alias. If so, skipping...
if (!(handler.mimes && Array.isArray(handler.mimes)) && handler.mimesAliases) {
return
}
// Nothing available to process! Failure
if (!(handler.mimes && Array.isArray(handler.mimes)) && !handler.mimesAliases) {
logger.error('The following handler doesn\'t have a valid mime array', { handler })
return
}
// checking valid handler component data
if ((!handler.component || (typeof handler.component !== 'object' && typeof handler.component !== 'function'))) {
logger.error('The following handler doesn\'t have a valid component', { handler })
return
}
// force apply mixin
handler.component.mixins = [...handler?.component?.mixins ?? [], Mime]
// parsing mimes registration
if (handler.mimes) {
handler.mimes.forEach(mime => {
// checking valid mime
if (this.components[mime]) {
logger.error('The following mime is already registered', { mime, handler })
return
}
// register file action and groups
this.registerLegacyAction({ mime, group: handler.group })
// register groups
this.registerGroups({ mime, group: handler.group })
// register mime's component
this.components[mime] = handler.component
Vue.component(handler.component.name, handler.component)
// set the handler as registered
this.registeredHandlers[mime] = handler
})
}
},
registerHandlerAlias(handler) {
// parsing aliases registration
if (handler.mimesAliases) {
Object.keys(handler.mimesAliases).forEach(mime => {
if (handler.mimesAliases && typeof handler.mimesAliases !== 'object') {
logger.error('The following handler doesn\'t have a valid mimesAliases object', { handler })
return
}
// this is the targeted alias
const alias = handler.mimesAliases[mime]
// checking valid mime
if (this.components[mime]) {
logger.error('The following mime is already registered', { mime, handler })
return
}
if (!this.components[alias]) {
logger.error('The requested alias does not exists', { alias, mime, handler })
return
}
// register file action and groups if the request alias had a group
this.registerLegacyAction({ mime, group: this.mimeGroups[alias] })
// register groups if the request alias had a group
this.registerGroups({ mime, group: this.mimeGroups[alias] })
// register mime's component
this.components[mime] = this.components[alias]
// set the handler as registered
this.registeredHandlers[mime] = handler
})
}
},
registerLegacyAction({ mime, group }) {
if (!this.isStandalone && OCA?.Files?.fileActions) {
// unregistered handler, let's go!
OCA.Files.fileActions.registerAction({
name: 'view',
displayName: t('viewer', 'View'),
mime,
permissions: OC.PERMISSION_READ,
actionHandler: legacyFilesActionHandler,
})
OCA.Files.fileActions.setDefault(mime, 'view')
logger.debug('Legacy file action registered for mime ' + mime, { mime, group })
}
// register groups
if (group) {
this.mimeGroups[mime] = group
// init if undefined
if (!this.mimeGroups[group]) {
this.mimeGroups[group] = []
}
this.mimeGroups[group].push(mime)
}
},
registerGroups({ mime, group }) {
if (group) {
this.mimeGroups[mime] = group
// init if undefined
if (!this.mimeGroups[group]) {
this.mimeGroups[group] = []
}
this.mimeGroups[group].push(mime)
}
},
registerFileActions() {
if (!this.isStandalone) {
registerFileAction(new FileAction({
id: 'view',
displayName() {
return t('viewer', 'View')
},
iconSvgInline: () => EyeSvg,
default: DefaultType.DEFAULT,
enabled: (nodes) => {
// Disable if not located in user root
if (nodes.some(node => !(node.isDavRessource && node.root?.startsWith('/files')))) {
return false
}
// Faster to check if at least one node doesn't match the requirements
return !nodes.some(node => (
(node.permissions & Permission.READ) === 0
|| !this.Viewer.mimetypes.includes(node.mime)
))
},
exec: filesActionHandler,
}))
}
},
/**
* Close the viewer
*/
close() {
// This will set file to ''
// which then triggers cleanup.
OCA.Viewer.close()
if (OCA?.Files?.Sidebar) {
OCA.Files.Sidebar.setFullScreenMode(false)
}
if (this.isFullscreenMode) {
this.exitFullscreen()
}
},
keyboardDeleteFile(event) {
if (this.canDelete && event.key === 'Delete' && event.ctrlKey === true) {
this.onDelete()
}
},
keyboardDownloadFile(event) {
if (event.key === 's' && event.ctrlKey === true) {
event.preventDefault()
if (this.canDownload) {
const a = document.createElement('a')
a.href = this.currentFile.davPath
a.download = this.currentFile.basename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
}
},
keyboardEditFile(event) {
if (event.key === 'e' && event.ctrlKey === true) {
event.preventDefault()
if (this.canEdit) {