-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathnode.ts
More file actions
426 lines (370 loc) · 10.7 KB
/
node.ts
File metadata and controls
426 lines (370 loc) · 10.7 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
/**
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import { basename, extname, dirname } from 'path'
import { encodePath } from '@nextcloud/paths'
import { Permission } from '../permissions'
import { FileType } from './fileType'
import { Attribute, fixDates, fixRegExp, isDavResource, NodeData, validateData } from './nodeData'
export enum NodeStatus {
/** This is a new node and it doesn't exists on the filesystem yet */
NEW = 'new',
/** This node has failed and is unavailable */
FAILED = 'failed',
/** This node is currently loading or have an operation in progress */
LOADING = 'loading',
/** This node is locked and cannot be modified */
LOCKED = 'locked',
}
export type NodeConstructorData = [NodeData, RegExp?]
export abstract class Node {
private _attributes: Attribute
protected _data: NodeData
protected _knownDavService = /(remote|public)\.php\/(web)?dav/i
private readonlyAttributes = Object.entries(Object.getOwnPropertyDescriptors(Node.prototype))
.filter(e => typeof e[1].get === 'function' && e[0] !== '__proto__')
.map(e => e[0])
private handler = {
set: (target: Attribute, prop: string, value: unknown): boolean => {
if (this.readonlyAttributes.includes(prop)) {
return false
}
// Apply original changes
return Reflect.set(target, prop, value)
},
deleteProperty: (target: Attribute, prop: string): boolean => {
if (this.readonlyAttributes.includes(prop)) {
return false
}
// Apply original changes
return Reflect.deleteProperty(target, prop)
},
} as ProxyHandler<Attribute>
protected constructor(...[data, davService]: NodeConstructorData) {
if (!data.mime) {
data.mime = 'application/octet-stream'
}
// Fix primitive types if needed
fixDates(data)
davService = fixRegExp(davService || this._knownDavService)
// Validate data
validateData(data, davService)
this._data = {
...data,
attributes: {},
}
// Proxy the attributes to update the mtime on change
this._attributes = new Proxy(this._data.attributes!, this.handler)
// Update attributes, this sanitizes the attributes to only contain valid attributes
this.update(data.attributes ?? {})
if (davService) {
this._knownDavService = davService
}
}
/**
* Get the source url to this object
* There is no setter as the source is not meant to be changed manually.
* You can use the rename or move method to change the source.
*/
get source(): string {
// strip any ending slash
return this._data.source.replace(/\/$/i, '')
}
/**
* Get the encoded source url to this object for requests purposes
*/
get encodedSource(): string {
const { origin } = new URL(this.source)
return origin + encodePath(this.source.slice(origin.length))
}
/**
* Get this object name
* There is no setter as the source is not meant to be changed manually.
* You can use the rename or move method to change the source.
*/
get basename(): string {
return basename(this.source)
}
/**
* The nodes displayname
* By default the display name and the `basename` are identical,
* but it is possible to have a different name. This happens
* on the files app for example for shared folders.
*/
get displayname(): string {
return this._data.displayname || this.basename
}
/**
* Set the displayname
*/
set displayname(displayname: string) {
validateData({ ...this._data, displayname }, this._knownDavService)
this._data.displayname = displayname
}
/**
* Get this object's extension
* There is no setter as the source is not meant to be changed manually.
* You can use the rename or move method to change the source.
*/
get extension(): string|null {
return extname(this.source)
}
/**
* Get the directory path leading to this object
* Will use the relative path to root if available
*
* There is no setter as the source is not meant to be changed manually.
* You can use the rename or move method to change the source.
*/
get dirname(): string {
if (this.root) {
let source = this.source
if (this.isDavResource) {
// ensure we only work on the real path in case root is not distinct
source = source.split(this._knownDavService).pop()!
}
// Using replace would remove all part matching root
const firstMatch = source.indexOf(this.root)
// Ensure we do not remove the leading slash
const root = this.root.replace(/\/$/, '')
return dirname(source.slice(firstMatch + root.length) || '/')
}
// This should always be a valid URL
// as this is tested in the constructor
const url = new URL(this.source)
return dirname(url.pathname)
}
/**
* Is it a file or a folder ?
*/
abstract get type(): FileType
/**
* Get the file mime
*/
get mime(): string {
return this._data.mime || 'application/octet-stream'
}
/**
* Set the file mime
* Removing the mime type will set it to `application/octet-stream`
*/
set mime(mime: string|undefined) {
mime ??= 'application/octet-stream'
validateData({ ...this._data, mime }, this._knownDavService)
this._data.mime = mime
}
/**
* Get the file modification time
*/
get mtime(): Date|undefined {
return this._data.mtime
}
/**
* Set the file modification time
*/
set mtime(mtime: Date|undefined) {
validateData({ ...this._data, mtime }, this._knownDavService)
this._data.mtime = mtime
}
/**
* Get the file creation time
* There is no setter as the creation time is not meant to be changed
*/
get crtime(): Date|undefined {
return this._data.crtime
}
/**
* Get the file size
*/
get size(): number|undefined {
return this._data.size
}
/**
* Set the file size
*/
set size(size: number|undefined) {
validateData({ ...this._data, size }, this._knownDavService)
this.updateMtime()
this._data.size = size
}
/**
* Get the file attribute
* This contains all additional attributes not provided by the Node class
*/
get attributes(): Attribute {
return this._attributes
}
/**
* Get the file permissions
*/
get permissions(): Permission {
// If this is not a dav resource, we can only read it
if (this.owner === null && !this.isDavResource) {
return Permission.READ
}
// If the permissions are not defined, we have none
return this._data.permissions !== undefined
? this._data.permissions
: Permission.NONE
}
/**
* Set the file permissions
*/
set permissions(permissions: Permission) {
validateData({ ...this._data, permissions }, this._knownDavService)
this.updateMtime()
this._data.permissions = permissions
}
/**
* Get the file owner
* There is no setter as the owner is not meant to be changed
*/
get owner(): string|null {
// Remote resources have no owner
if (!this.isDavResource) {
return null
}
return this._data.owner
}
/**
* Is this a dav-related resource ?
*/
get isDavResource(): boolean {
return isDavResource(this.source, this._knownDavService)
}
/**
* Get the dav root of this object
* There is no setter as the root is not meant to be changed
*/
get root(): string|null {
// If provided (recommended), use the root and strip away the ending slash
if (this._data.root) {
return this._data.root.replace(/^(.+)\/$/, '$1')
}
// Use the source to get the root from the dav service
if (this.isDavResource) {
const root = dirname(this.source)
return root.split(this._knownDavService).pop() || null
}
return null
}
/**
* Get the absolute path of this object relative to the root
*/
get path(): string {
if (this.root) {
let source = this.source
if (this.isDavResource) {
// ensure we only work on the real path in case root is not distinct
source = source.split(this._knownDavService).pop()!
}
// Using replace would remove all part matching root
const firstMatch = source.indexOf(this.root)
// Ensure we do not remove the leading slash
const root = this.root.replace(/\/$/, '')
return source.slice(firstMatch + root.length) || '/'
}
return (this.dirname + '/' + this.basename).replace(/\/\//g, '/')
}
/**
* Get the node id if defined.
* There is no setter as the fileid is not meant to be changed
*/
get fileid(): number|undefined {
return this._data?.id
}
/**
* Get the node status.
*/
get status(): NodeStatus|undefined {
return this._data?.status
}
/**
* Set the node status.
*/
set status(status: NodeStatus|undefined) {
validateData({ ...this._data, status }, this._knownDavService)
this._data.status = status
}
/**
* Move the node to a new destination
*
* @param {string} destination the new source.
* e.g. https://cloud.domain.com/remote.php/dav/files/emma/Photos/picture.jpg
*/
move(destination: string) {
validateData({ ...this._data, source: destination }, this._knownDavService)
const oldBasename = this.basename
this._data.source = destination
// Check if the displayname and the (old) basename were the same
// meaning no special displayname was set but just a fallback to the basename by Nextcloud's WebDAV server
if (this.displayname === oldBasename
&& this.basename !== oldBasename) {
// We have to assume that the displayname was not set but just a copy of the basename
// this can not be guaranteed, so to be sure users should better refetch the node
this.displayname = this.basename
}
}
/**
* Rename the node
* This aliases the move method for easier usage
*
* @param basename The new name of the node
*/
rename(basename: string) {
if (basename.includes('/')) {
throw new Error('Invalid basename')
}
this.move(dirname(this.source) + '/' + basename)
}
/**
* Update the mtime if exists
*/
updateMtime() {
if (this._data.mtime) {
this._data.mtime = new Date()
}
}
/**
* Update the attributes of the node
* Warning, updating attributes will NOT automatically update the mtime.
*
* @param attributes The new attributes to update on the Node attributes
*/
update(attributes: Attribute) {
for (const [name, value] of Object.entries(attributes)) {
try {
if (value === undefined) {
delete this.attributes[name]
} else {
this.attributes[name] = value
}
} catch (e) {
// Ignore readonly attributes
if (e instanceof TypeError) {
continue
}
// Throw all other exceptions
throw e
}
}
}
/**
* Returns a clone of the node
*/
clone(): this {
// @ts-expect-error -- this class is abstract and cannot be instantiated directly but all its children can
return new this.constructor(structuredClone(this._data), this._knownDavService)
}
/**
* JSON representation of the node
*/
toJSON(): string {
return JSON.stringify([structuredClone(this._data), this._knownDavService.toString()])
}
}
/**
* Interface of the node class
*/
export type INode = Pick<Node, keyof Node>