-
-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathfiles.js
More file actions
440 lines (416 loc) · 12.8 KB
/
files.js
File metadata and controls
440 lines (416 loc) · 12.8 KB
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
/**
* SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { defineStore } from 'pinia'
import { del, set } from 'vue'
import { getCurrentUser } from '@nextcloud/auth'
import axios from '@nextcloud/axios'
import { emit, subscribe } from '@nextcloud/event-bus'
import { loadState } from '@nextcloud/initial-state'
import Moment from '@nextcloud/moment'
import { generateOcsUrl } from '@nextcloud/router'
import { useFilesSortingStore } from './filesSorting.js'
import { useFiltersStore } from './filters.js'
import { useIdentificationDocumentStore } from './identificationDocument.js'
import { useSidebarStore } from './sidebar.js'
import { useSignStore } from './sign.js'
// from https://gist.github.com/codeguy/6684588
const slugfy = (val) =>
val
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase()
.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-') // collapse dashes
.replace(/^-+/, '') // trim - from start of text
.replace(/-+$/, '')
export const useFilesStore = function(...args) {
const emptyFile = { signers: [] }
const store = defineStore('files', {
state: () => {
return {
files: {},
selectedNodeId: 0,
identifyingSigner: false,
loading: false,
canRequestSign: loadState('libresign', 'can_request_sign', false),
ordered: [],
paginationNextUrl: '',
loadedAll: false,
}
},
actions: {
addFile(file) {
set(this.files, file.nodeId, file)
this.hydrateFile(file.nodeId)
if (!this.ordered.includes(file.nodeId)) {
this.ordered.push(file.nodeId)
}
},
selectFile(nodeId) {
this.selectedNodeId = nodeId ?? 0
if (this.selectedNodeId === 0) {
const signStore = useSignStore()
signStore.reset()
return
}
const sidebarStore = useSidebarStore()
sidebarStore.activeRequestSignatureTab()
},
getFile(file) {
if (typeof file === 'object') {
return file
}
return this.files[this.selectedNodeId] || emptyFile
},
async flushSelectedFile() {
const files = await this.getAllFiles({
'nodeIds[]': [this.selectedNodeId],
})
this.addFile(files[this.selectedNodeId])
},
enableIdentifySigner() {
this.identifyingSigner = true
},
disableIdentifySigner() {
this.identifyingSigner = false
},
hasSigners(file) {
file = this.getFile(file)
if (this.selectedNodeId === 0) {
return false
}
if (!Object.hasOwn(file, 'signers')) {
return false
}
return file.signers.length > 0
},
isPartialSigned(file) {
file = this.getFile(file)
if (!Object.hasOwn(file, 'signers')) {
return false
}
return file.signers
.filter(signer => signer.signed?.length > 0).length > 0
},
isFullSigned(file) {
file = this.getFile(file)
if (!Object.hasOwn(file, 'signers')) {
return false
}
return file.signers.length > 0
&& file.signers
.filter(signer => signer.signed?.length > 0).length === file.signers.length
},
canSign(file) {
file = this.getFile(file)
return !this.isFullSigned(file)
&& file.status > 0
&& file?.signers?.filter(signer => signer.me).length > 0
&& file?.signers?.filter(signer => signer.me)
.filter(signer => signer.signed?.length > 0).length === 0
},
canValidate(file) {
file = this.getFile(file)
return this.isPartialSigned(file)
|| this.isFullSigned(file)
},
canDelete(file) {
file = this.getFile(file)
return this.canRequestSign
&& (
!Object.hasOwn(file, 'requested_by')
|| file.requested_by.userId === getCurrentUser()?.uid
)
},
canAddSigner(file) {
file = this.getFile(file)
return this.canRequestSign
&& (
!Object.hasOwn(file, 'requested_by')
|| file.requested_by.userId === getCurrentUser()?.uid
)
&& !this.isPartialSigned(file)
&& !this.isFullSigned(file)
},
canSave(file) {
file = this.getFile(file)
return this.canRequestSign
&& (
!Object.hasOwn(file, 'requested_by')
|| file.requested_by.userId === getCurrentUser()?.uid
)
&& !this.isPartialSigned(file)
&& !this.isFullSigned(file)
&& file?.signers?.length > 0
},
getSubtitle() {
if (this.selectedNodeId === 0) {
return ''
}
const file = this.getFile()
if ((file?.requested_by?.userId ?? '').length === 0 || file?.created_at.length === 0) {
return ''
}
return t('libresign', 'Requested by {name}, at {date}', {
name: file.requested_by.userId,
date: Moment(Date.parse(file.created_at)).format('LL LTS'),
})
},
async hydrateFile(nodeId) {
this.addUniqueIdentifierToAllSigners(this.files[nodeId].signers)
if (Object.hasOwn(this.files[nodeId], 'uuid')) {
return
}
await axios.get(generateOcsUrl('/apps/libresign/api/v1/file/validate/file_id/{fileId}', {
fileId: nodeId,
}))
.then((response) => {
set(this.files, nodeId, response.data.ocs.data)
this.addUniqueIdentifierToAllSigners(this.files[nodeId].signers)
})
.catch(() => {
set(this.files[nodeId], 'signers', [])
})
},
addUniqueIdentifierToAllSigners(signers) {
if (signers === undefined) {
return
}
signers.map(signer => this.addIdentifierToSigner(signer))
},
addIdentifierToSigner(signer) {
if (signer.identify) {
return
}
// generate unique code to new signer to be possible delete or edit
if ((signer.identify === undefined || signer.identify === '') && signer.signRequestId === undefined) {
signer.identify = btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(signer))))
}
if (signer.signRequestId) {
signer.identify = signer.signRequestId
}
},
signerUpdate(signer) {
this.addIdentifierToSigner(signer)
if (!this.getFile().signers?.length) {
this.getFile().signers = []
}
// Remove if already exists
for (let i = this.getFile().signers.length - 1; i >= 0; i--) {
if (this.getFile().signers[i].identify === signer.identify) {
this.getFile().signers.splice(i, 1)
break
}
if (this.getFile().signers[i].signRequestId === signer.identify) {
this.getFile().signers.splice(i, 1)
break
}
}
if (!signer.signingOrder) {
const signatureFlow = loadState('libresign', 'signature_flow', 'parallel')
if (signatureFlow === 'ordered_numeric') {
const maxOrder = this.getFile().signers.reduce((max, s) => Math.max(max, s.signingOrder || 0), 0)
signer.signingOrder = maxOrder + 1
}
}
this.getFile().signers.push(signer)
const selected = this.selectedNodeId
this.selectFile(-1) // to force reactivity
this.selectFile(selected) // to force reactivity
},
async deleteSigner(signer) {
if (!isNaN(signer.signRequestId)) {
await axios.delete(generateOcsUrl('/apps/libresign/api/{apiVersion}/sign/file_id/{fileId}/{signRequestId}', {
apiVersion: 'v1',
fileId: this.selectedNodeId,
signRequestId: signer.signRequestId,
}))
}
const signatureFlow = loadState('libresign', 'signature_flow', 'parallel')
set(
this.files[this.selectedNodeId],
'signers',
this.files[this.selectedNodeId].signers.filter((i) => i.identify !== signer.identify),
)
if (signatureFlow === 'ordered_numeric' && signer.signingOrder) {
this.files[this.selectedNodeId].signers.forEach((s) => {
if (s.signingOrder && s.signingOrder > signer.signingOrder) {
s.signingOrder -= 1
}
})
}
},
async delete(file, deleteFile) {
file = this.getFile(file)
if (file?.uuid !== undefined) {
const url = deleteFile
? '/apps/libresign/api/v1/file/file_id/{fileId}'
: '/apps/libresign/api/v1/sign/file_id/{fileId}'
await axios.delete(generateOcsUrl(url, {
fileId: file.nodeId,
}))
.then(() => {
del(this.files, file.nodeId)
const index = this.ordered.indexOf(file.nodeId)
if (index > -1) {
this.ordered.splice(index, 1)
}
})
}
},
async deleteMultiple(nodeIds, deleteFile) {
this.loading = true
nodeIds.forEach(async nodeId => {
await this.delete(this.files[nodeId], deleteFile)
})
const toRemove = nodeIds.filter(nodeId => (!this.files[nodeId]?.uuid))
del(this.files, ...toRemove)
this.loading = false
},
async upload({ file, name }) {
const { data } = await axios.post(generateOcsUrl('/apps/libresign/api/v1/file'), {
file: { base64: file },
name,
settings: {
folderName: `requests/${Date.now().toString(16)}-${slugfy(name)}`,
},
})
return { ...data.ocs.data }
},
async getAllFiles(filter) {
if (this.loading || this.loadedAll) {
if (!filter) {
return this.files
}
if (!filter.force_fetch) {
return Object.fromEntries(
Object.entries(this.files).filter(([key, value]) => {
if (filter.signer_uuid) {
// return true when found signer by signer_uuid
return value.signers?.filter((signer) => {
// filter signers by signer_uuid
return signer.sign_uuid === filter.signer_uuid
}).length > 0
}
return false
}),
)
}
}
this.loading = true
const url = !this.paginationNextUrl
? generateOcsUrl('/apps/libresign/api/v1/file/list')
: this.paginationNextUrl
const urlObj = new URL(url)
const params = new URLSearchParams(urlObj.search)
if (filter) {
for (const [key, value] of Object.entries(filter)) {
params.set(key, value)
}
}
const { chips } = useFiltersStore()
if (chips?.status) {
chips.status.forEach(status => {
params.append('status[]', status.id)
})
}
if (chips?.modified?.length) {
const { start, end } = chips.modified[0]
params.set('start', Math.floor(start / 1000))
params.set('end', Math.floor(end / 1000))
}
const { sortingMode, sortingDirection } = useFilesSortingStore()
if (sortingMode) {
params.set('sortBy', sortingMode)
}
if (sortingDirection) {
params.set('sortDirection', sortingDirection)
}
urlObj.search = params.toString()
const response = await axios.get(urlObj.toString())
if (!this.paginationNextUrl) {
this.files = {}
this.ordered = []
}
this.paginationNextUrl = response.data.ocs.data.pagination.next
this.loadedAll = !this.paginationNextUrl
response.data.ocs.data.data.forEach((file) => {
this.addFile(file)
})
if (response.data.ocs.data.settings) {
const identificationDocumentStore = useIdentificationDocumentStore()
identificationDocumentStore.setEnabled(response.data.ocs.data.settings.needIdentificationDocuments)
identificationDocumentStore.setWaitingApproval(response.data.ocs.data.settings.identificationDocumentsWaitingApproval)
}
this.loading = false
emit('libresign:files:updated')
return this.files
},
async updateAllFiles() {
this.paginationNextUrl = null
this.loadedAll = false
return this.getAllFiles()
},
filesSorted() {
return this.ordered.map(key => this.files[key])
},
async saveWithVisibleElements({ visibleElements = [], signers = null, uuid = null, nodeId = null }) {
const file = this.getFile()
const config = {
url: generateOcsUrl('/apps/libresign/api/v1/request-signature'),
method: uuid || file.uuid ? 'patch' : 'post',
data: {
name: file?.name,
users: signers || file.signers,
visibleElements,
status: 0,
},
}
if (uuid || file.uuid) {
config.data.uuid = uuid || file.uuid
} else {
config.data.file = {
fileId: nodeId || this.selectedNodeId,
}
}
const { data } = await axios(config)
this.addFile(data.ocs.data.data)
return data.ocs.data
},
async updateSignatureRequest({ visibleElements = [], signers = null, uuid = null, nodeId = null, status = 1 }) {
const file = this.getFile()
const config = {
url: generateOcsUrl('/apps/libresign/api/v1/request-signature'),
method: uuid || file.uuid ? 'patch' : 'post',
data: {
name: file?.name,
users: signers || file.signers,
visibleElements,
status,
},
}
if (uuid || file.uuid) {
config.data.uuid = uuid || file.uuid
} else {
config.data.file = {
fileId: nodeId || this.selectedNodeId,
}
}
const { data } = await axios(config)
this.addFile(data.ocs.data.data)
return data.ocs.data
},
},
})
const filesStore = store(...args)
// Make sure we only register the listeners once
if (!filesStore._initialized) {
subscribe('libresign:filters:update', filesStore.updateAllFiles)
subscribe('libresign:sorting:update', filesStore.updateAllFiles)
filesStore._initialized = true
}
return filesStore
}