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
|
/**
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { emit } from '@nextcloud/event-bus'
import { fetchNode } from '../services/WebdavClient.ts'
import { showError, showSuccess } from '@nextcloud/dialogs'
import { getCurrentUser } from '@nextcloud/auth'
// eslint-disable-next-line import/no-unresolved, n/no-missing-import
import PQueue from 'p-queue'
import debounce from 'debounce'
import Share from '../models/Share.js'
import SharesRequests from './ShareRequests.js'
import ShareTypes from './ShareTypes.js'
import Config from '../services/ConfigService.ts'
import logger from '../services/logger.ts'
import {
BUNDLED_PERMISSIONS,
} from '../lib/SharePermissionsToolBox.js'
export default {
mixins: [SharesRequests, ShareTypes],
props: {
fileInfo: {
type: Object,
default: () => { },
required: true,
},
share: {
type: Share,
default: null,
},
isUnique: {
type: Boolean,
default: true,
},
},
data() {
return {
config: new Config(),
node: null,
// errors helpers
errors: {},
// component status toggles
loading: false,
saving: false,
open: false,
// concurrency management queue
// we want one queue per share
updateQueue: new PQueue({ concurrency: 1 }),
/**
* ! This allow vue to make the Share class state reactive
* ! do not remove it ot you'll lose all reactivity here
*/
reactiveState: this.share?.state,
}
},
computed: {
path() {
return (this.fileInfo.path + '/' + this.fileInfo.name).replace('//', '/')
},
/**
* Does the current share have a note
*
* @return {boolean}
*/
hasNote: {
get() {
return this.share.note !== ''
},
set(enabled) {
this.share.note = enabled
? null // enabled but user did not changed the content yet
: '' // empty = no note = disabled
},
},
dateTomorrow() {
return new Date(new Date().setDate(new Date().getDate() + 1))
},
// Datepicker language
lang() {
const weekdaysShort = window.dayNamesShort
? window.dayNamesShort // provided by nextcloud
: ['Sun.', 'Mon.', 'Tue.', 'Wed.', 'Thu.', 'Fri.', 'Sat.']
const monthsShort = window.monthNamesShort
? window.monthNamesShort // provided by nextcloud
: ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May.', 'Jun.', 'Jul.', 'Aug.', 'Sep.', 'Oct.', 'Nov.', 'Dec.']
const firstDayOfWeek = window.firstDay ? window.firstDay : 0
return {
formatLocale: {
firstDayOfWeek,
monthsShort,
weekdaysMin: weekdaysShort,
weekdaysShort,
},
monthFormat: 'MMM',
}
},
isFolder() {
return this.fileInfo.type === 'dir'
},
isPublicShare() {
const shareType = this.share.shareType ?? this.share.type
return [this.SHARE_TYPES.SHARE_TYPE_LINK, this.SHARE_TYPES.SHARE_TYPE_EMAIL].includes(shareType)
},
isRemoteShare() {
return this.share.type === this.SHARE_TYPES.SHARE_TYPE_REMOTE_GROUP || this.share.type === this.SHARE_TYPES.SHARE_TYPE_REMOTE
},
isShareOwner() {
return this.share && this.share.owner === getCurrentUser().uid
},
isExpiryDateEnforced() {
if (this.isPublicShare) {
return this.config.isDefaultExpireDateEnforced
}
if (this.isRemoteShare) {
return this.config.isDefaultRemoteExpireDateEnforced
}
return this.config.isDefaultInternalExpireDateEnforced
},
hasCustomPermissions() {
const bundledPermissions = [
BUNDLED_PERMISSIONS.ALL,
BUNDLED_PERMISSIONS.READ_ONLY,
BUNDLED_PERMISSIONS.FILE_DROP,
]
return !bundledPermissions.includes(this.share.permissions)
},
maxExpirationDateEnforced() {
if (this.isExpiryDateEnforced) {
if (this.isPublicShare) {
return this.config.defaultExpirationDate
}
if (this.isRemoteShare) {
return this.config.defaultRemoteExpirationDateString
}
// If it get's here then it must be an internal share
return this.config.defaultInternalExpirationDate
}
return null
},
},
methods: {
/**
* Fetch webdav node
*
* @return {Node}
*/
async getNode() {
const node = { path: this.path }
try {
this.node = await fetchNode(node)
logger.info('Fetched node:', { node: this.node })
} catch (error) {
logger.error('Error:', error)
}
},
/**
* Check if a share is valid before
* firing the request
*
* @param {Share} share the share to check
* @return {boolean}
*/
checkShare(share) {
if (share.password) {
if (typeof share.password !== 'string' || share.password.trim() === '') {
return false
}
}
if (share.expirationDate) {
const date = share.expirationDate
if (!date.isValid()) {
return false
}
}
return true
},
/**
* @param {string} date a date with YYYY-MM-DD format
* @return {Date} date
*/
parseDateString(date) {
if (!date) {
return
}
const regex = /([0-9]{4}-[0-9]{2}-[0-9]{2})/i
return new Date(date.match(regex)?.pop())
},
/**
* @param {Date} date
* @return {string} date a date with YYYY-MM-DD format
*/
formatDateToString(date) {
// Force utc time. Drop time information to be timezone-less
const utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
// Format to YYYY-MM-DD
return utcDate.toISOString().split('T')[0]
},
/**
* Save given value to expireDate and trigger queueUpdate
*
* @param {Date} date
*/
onExpirationChange: debounce(function(date) {
this.share.expireDate = this.formatDateToString(new Date(date))
}, 500),
/**
* Uncheck expire date
* We need this method because @update:checked
* is ran simultaneously as @uncheck, so
* so we cannot ensure data is up-to-date
*/
onExpirationDisable() {
this.share.expireDate = ''
},
/**
* Note changed, let's save it to a different key
*
* @param {string} note the share note
*/
onNoteChange(note) {
this.$set(this.share, 'newNote', note.trim())
},
/**
* When the note change, we trim, save and dispatch
*
*/
onNoteSubmit() {
if (this.share.newNote) {
this.share.note = this.share.newNote
this.$delete(this.share, 'newNote')
this.queueUpdate('note')
}
},
/**
* Delete share button handler
*/
async onDelete() {
try {
this.loading = true
this.open = false
await this.deleteShare(this.share.id)
console.debug('Share deleted', this.share.id)
const message = this.share.itemType === 'file'
? t('files_sharing', 'File "{path}" has been unshared', { path: this.share.path })
: t('files_sharing', 'Folder "{path}" has been unshared', { path: this.share.path })
showSuccess(message)
this.$emit('remove:share', this.share)
await this.getNode()
emit('files:node:updated', this.node)
} catch (error) {
// re-open menu if error
this.open = true
} finally {
this.loading = false
}
},
/**
* Send an update of the share to the queue
*
* @param {Array<string>} propertyNames the properties to sync
*/
queueUpdate(...propertyNames) {
if (propertyNames.length === 0) {
// Nothing to update
return
}
if (this.share.id) {
const properties = {}
// force value to string because that is what our
// share api controller accepts
propertyNames.forEach(name => {
if ((typeof this.share[name]) === 'object') {
properties[name] = JSON.stringify(this.share[name])
} else {
properties[name] = this.share[name].toString()
}
})
this.updateQueue.add(async () => {
this.saving = true
this.errors = {}
try {
const updatedShare = await this.updateShare(this.share.id, properties)
if (propertyNames.indexOf('password') >= 0) {
// reset password state after sync
this.$delete(this.share, 'newPassword')
// updates password expiration time after sync
this.share.passwordExpirationTime = updatedShare.password_expiration_time
}
// clear any previous errors
this.$delete(this.errors, propertyNames[0])
showSuccess(t('files_sharing', 'Share {propertyName} saved', { propertyName: propertyNames[0] }))
} catch ({ message }) {
if (message && message !== '') {
this.onSyncError(propertyNames[0], message)
showError(t('files_sharing', message))
}
} finally {
this.saving = false
}
})
return
}
// This share does not exists on the server yet
console.debug('Updated local share', this.share)
},
/**
* Manage sync errors
*
* @param {string} property the errored property, e.g. 'password'
* @param {string} message the error message
*/
onSyncError(property, message) {
// re-open menu if closed
this.open = true
switch (property) {
case 'password':
case 'pending':
case 'expireDate':
case 'label':
case 'note': {
// show error
this.$set(this.errors, property, message)
let propertyEl = this.$refs[property]
if (propertyEl) {
if (propertyEl.$el) {
propertyEl = propertyEl.$el
}
// focus if there is a focusable action element
const focusable = propertyEl.querySelector('.focusable')
if (focusable) {
focusable.focus()
}
}
break
}
case 'sendPasswordByTalk': {
// show error
this.$set(this.errors, property, message)
// Restore previous state
this.share.sendPasswordByTalk = !this.share.sendPasswordByTalk
break
}
}
},
/**
* Debounce queueUpdate to avoid requests spamming
* more importantly for text data
*
* @param {string} property the property to sync
*/
debounceQueueUpdate: debounce(function(property) {
this.queueUpdate(property)
}, 500),
},
}
|