This repository has been archived by the owner on Jun 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
/
fileManagement.js
476 lines (432 loc) · 16.8 KB
/
fileManagement.js
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
const Promise = require('promise')
const dav = require('davclient.js')
/**
* @class Files
* @classdesc
* <b><i> The Files class, has all the methods for your ownCloud files management.</i></b><br><br>
* Supported Methods are:
* <ul>
* <li><b>Files Management</b>
* <ul>
* <li>list</li>
* <li>getFileContents</li>
* <li>putFileContents</li>
* <li>mkdir</li>
* <li>createFolder</li>
* <li>delete</li>
* <li>fileInfo</li>
* <li>getDirectoryAsZip</li>
* <li>putFile</li>
* <li>putDirectory</li>
* <li>move</li>
* <li>copy</li>
* </ul>
* </li>
* </ul>
*
* @author Noveen Sachdeva
* @version 1.0.0
* @param {helpers} helperFile instance of the helpers class
*/
class Files {
constructor (helperFile) {
this.helpers = helperFile
this.davClient = new dav.Client({
baseUrl: this.helpers._webdavUrl,
xmlNamespaces: {
'DAV:': 'd',
'http://owncloud.org/ns': 'oc'
}
})
}
/**
* Returns the listing/contents of the given remote directory
* @param {string} path path of the file/folder at OC instance
* @param {string} depth 0: only file/folder, 1: upto 1 depth, infinity: infinite depth
* @param {array} properties Array[string] with dav properties to be requested
* @returns {Promise.<fileInfo>} Array[objects]: each object is an instance of class fileInfo
* @returns {Promise.<error>} string: error message, if any.
*/
list (path, depth = '1', properties = []) {
if (!this.helpers.getAuthorization()) {
return Promise.reject('Please specify an authorization first.')
}
const headers = this.helpers.buildHeaders()
return this.davClient.propFind(this.helpers._buildFullWebDAVPath(path), properties, depth, headers).then(result => {
if (result.status !== 207) {
return Promise.reject(this.helpers.buildHttpErrorFromDavResponse(result.status, result.xhr.response))
} else {
const entries = this.helpers._parseBody(result.body)
entries[0].tusSupport = this.helpers._parseTusHeaders(result.xhr)
return Promise.resolve(entries)
}
})
}
/**
* Returns the contents of a remote file
* @param {string} path path of the remote file at OC instance
* @param {Object} options
* @returns {Promise.<string>} string: contents of file
* @returns {Promise.<error>} string: error message, if any.
*/
getFileContents (path, options = {}) {
return this.helpers._get(this.helpers._buildFullWebDAVPath(path)).then(data => {
const response = data.response
const body = data.body
if (response.statusCode !== 200) {
return Promise.reject(this.helpers.buildHttpErrorFromDavResponse(response.status, body))
}
options = options || []
const resolveWithResponseObject = options.resolveWithResponseObject || false
if (resolveWithResponseObject) {
return Promise.resolve({
body: body,
headers: {
ETag: response.getResponseHeader('etag'),
'OC-FileId': response.getResponseHeader('oc-fileid')
}
})
}
return Promise.resolve(body)
})
}
/**
* Returns the url of a remote file - using the version 1 endpoint
* @param {string} path path of the remote file at OC instance
* @returns {string} Url of the remote file
*/
getFileUrl (path) {
return this.helpers._buildFullWebDAVPath(path)
}
/**
* Returns the url of a remote file - using the version 2 endpoint
* @param {string} path path of the remote file at OC instance
* @returns {string} Url of the remote file
*/
getFileUrlV2 (path) {
path = path[0] === '/' ? path : '/' + path
const target = '/files/' + this.helpers.getCurrentUser().id + path
return this.helpers._buildFullWebDAVPathV2(target)
}
/**
* Queries the server for the real path of the authenticated user for a given fileId
*
* @param {number} fileId
* @return {*|Promise<string>}
*/
getPathForFileId (fileId) {
const path = '/meta/' + fileId
return this.davClient.propFind(this.helpers._buildFullWebDAVPathV2(path), [
'{http://owncloud.org/ns}meta-path-for-user'
], 0, {
Authorization: this.helpers.getAuthorization()
}).then(result => {
if (result.status !== 207) {
return Promise.reject(this.helpers.buildHttpErrorFromDavResponse(result.status, result.body))
}
const file = this.helpers._parseBody(result.body)
return Promise.resolve(file[0].getProperty('{http://owncloud.org/ns}meta-path-for-user'))
})
}
/**
* Write data into a remote file
* @param {string} path path of the file at OC instance
* @param {string} content content to be put
* @param {Object} options
* @param {Object} [options.headers] optional extra headers
* @param {boolean} [options.overwrite] whether to force-overwrite the target
* @param {String} [options.previousEntityTag] previous entity tag to avoid concurrent overwrites
* @param {Function} options.onProgress progress callback
* @returns {Promise.<status>} boolean: whether the operation was successful
* @returns {Promise.<error>} string: error message, if any.
*/
putFileContents (path, content, options = {}) {
if (!this.helpers.getAuthorization()) {
return Promise.reject('Please specify an authorization first.')
}
options = options || []
const headers = Object.assign({}, this.helpers.buildHeaders(), options.headers)
const previousEntityTag = options.previousEntityTag || false
if (previousEntityTag) {
// will ensure that no other client uploaded a different version meanwhile
headers['If-Match'] = previousEntityTag
} else if (!options.overwrite) {
// will trigger 412 precondition failed if a file already exists
headers['If-None-Match'] = '*'
}
const requestOptions = {}
if (options.onProgress) {
requestOptions.onProgress = options.onProgress
}
return this.davClient.request('PUT', this.helpers._buildFullWebDAVPath(path), headers, content, null, requestOptions).then(result => {
if ([200, 201, 204, 207].indexOf(result.status) > -1) {
return Promise.resolve({
ETag: result.xhr.getResponseHeader('etag'),
'OC-FileId': result.xhr.getResponseHeader('oc-fileid')
})
} else {
return Promise.reject(this.helpers.buildHttpErrorFromDavResponse(result.status, result.body))
}
})
}
/**
* Creates a remote directory
* @param {string} path path of the folder to be created at OC instance
* @returns {Promise.<status>} boolean: whether the operation was successful
* @returns {Promise.<error>} string: error message, if any.
*/
mkdir (path) {
if (path[path.length - 1] !== '/') {
path += '/'
}
if (!this.helpers.getAuthorization()) {
return Promise.reject('Please specify an authorization first.')
}
return this.davClient.request('MKCOL', this.helpers._buildFullWebDAVPath(path), this.helpers.buildHeaders()).then(result => {
if ([200, 201, 204, 207].indexOf(result.status) > -1) {
return Promise.resolve(true)
}
return Promise.reject(this.helpers.buildHttpErrorFromDavResponse(result.status, result.body))
})
}
/**
* Creates a remote directory
* @param {string} path path of the folder to be created at OC instance
* @returns {Promise.<status>} boolean: whether the operation was successful
* @returns {Promise.<error>} string: error message, if any.
*/
createFolder (path) {
return this.mkdir(path)
}
/**
* Deletes a remote file or directory
* @param {string} path path of the file/folder at OC instance
* @returns {Promise.<status>} boolean: whether the operation was successful
* @returns {Promise.<error>} string: error message, if any.
*/
delete (path) {
if (!this.helpers.getAuthorization()) {
return Promise.reject('Please specify an authorization first.')
}
return this.davClient.request('DELETE', this.helpers._buildFullWebDAVPath(path), this.helpers.buildHeaders()).then(result => {
if ([200, 201, 204, 207].indexOf(result.status) > -1) {
return Promise.resolve(true)
} else {
return Promise.reject(this.helpers.buildHttpErrorFromDavResponse(result.status, result.body))
}
})
}
/**
* Returns the file info for the given remote file
* @param {string} path path of the file/folder at OC instance
* @param {Object.<string, string>} properties WebDAV properties
* @returns {Promise.<FileInfo>} object: instance of class fileInfo
* @returns {Promise.<error>} string: error message, if any.
*/
fileInfo (path, properties) {
return this.list(path, '0', properties).then(fileInfo => {
return Promise.resolve(fileInfo[0])
})
}
/**
* Helper for putDirectory
* This function first makes all the directories required
* @param {object} array file list (ls -R) of the directory to be put
* @return {Promise.<status>} boolean: whether mkdir was successful
* @returns {Promise.<error>} string: error message, if any.
*/
recursiveMkdir (array) {
const self = this
return new Promise(function (resolve, reject) {
self.mkdir(array[0].path).then(() => {
array.shift()
if (array.length === 0) {
resolve(true)
return
}
self.recursiveMkdir(array).then(() => {
resolve(true)
}).catch(err => {
reject(err)
})
}).catch(error => {
reject(error)
})
})
}
/**
* Moves a remote file or directory
* @param {string} source initial path of file/folder
* @param {string} target path where to move file/folder finally
* @returns {Promise.<status>} boolean: whether the operation was successful
* @returns {Promise.<error>} string: error message, if any.
*/
move (source, target) {
if (!this.helpers.getAuthorization()) {
return Promise.reject('Please specify an authorization first.')
}
const headers = this.helpers.buildHeaders()
headers.Destination = this.helpers._buildFullWebDAVPath(target)
return this.davClient.request('MOVE', this.helpers._buildFullWebDAVPath(source), headers).then(result => {
if ([200, 201, 204, 207].indexOf(result.status) > -1) {
return Promise.resolve(true)
}
return Promise.reject(this.helpers.buildHttpErrorFromDavResponse(result.status, result.body))
})
}
/**
* Copies a remote file or directory
* @param {string} source initial path of file/folder
* @param {string} target path where to copy file/folder finally
* @returns {Promise.<status>} boolean: whether the operation was successful
* @returns {Promise.<error>} string: error message, if any.
*/
copy (source, target) {
if (!this.helpers.getAuthorization()) {
return Promise.reject('Please specify an authorization first.')
}
const headers = this.helpers.buildHeaders()
headers.Destination = this.helpers._buildFullWebDAVPath(target)
return this.davClient.request('COPY', this.helpers._buildFullWebDAVPath(source), headers).then(result => {
if ([200, 201, 204, 207].indexOf(result.status) > -1) {
return Promise.resolve(true)
}
return Promise.reject(this.helpers.buildHttpErrorFromDavResponse(result.status, result.body))
})
}
/**
* Mark a remote file or directory as favorite
* @param {string} path path of file/folder
* @param {boolean} value Add or remove the favorite marker of a file/folder
* @returns {Promise.<status>} boolean: whether the operation was successful
* @returns {Promise.<error>} string: error message, if any.
*/
favorite (path, value = true) {
if (!this.helpers.getAuthorization()) {
return Promise.reject('Please specify an authorization first.')
}
return this.davClient.propPatch(this.helpers._buildFullWebDAVPath(path), {
'{http://owncloud.org/ns}favorite': value ? 'true' : 'false'
}, this.helpers.buildHeaders()).then(result => {
if ([200, 201, 204, 207].indexOf(result.status) > -1) {
return Promise.resolve(true)
}
return Promise.reject(this.helpers.buildHttpErrorFromDavResponse(result.status, result.body))
})
}
/**
* Search in all files of the user for a given pattern
* @param {string} pattern pattern to be searched for
* @param {number} limit maximum number of results
* @param {string[]} properties list of DAV properties which are expected in the response
* @returns {Promise.<FileInfo[]>} boolean: whether the operation was successful
* @returns {Promise.<error>} string: error message, if any.
*/
search (pattern, limit, properties) {
pattern = pattern || ''
limit = limit || 30
let body =
'<?xml version="1.0"?>\n' +
'<oc:search-files '
let namespace
for (namespace in this.davClient.xmlNamespaces) {
body += ' xmlns:' + this.davClient.xmlNamespaces[namespace] + '="' + namespace + '"'
}
body += '>\n'
body += this._renderProperties(properties)
body +=
' <oc:search>\n' +
' <oc:pattern>' + this.helpers.escapeXml(pattern) + '</oc:pattern>\n' +
' <oc:limit>' + this.helpers.escapeXml(limit) + '</oc:limit>\n' +
' </oc:search>\n' +
'</oc:search-files>'
return this._sendDavReport(body)
}
/**
* Get all favorite files and folder of the user
* @param {string[]} properties list of DAV properties which are expected in the response
* @returns {Promise.<FileInfo[]>} boolean: whether the operation was successful
* @returns {Promise.<error>} string: error message, if any.
*/
getFavoriteFiles (properties) {
let body =
'<?xml version="1.0"?>\n' +
'<oc:filter-files '
let namespace
for (namespace in this.davClient.xmlNamespaces) {
body += ' xmlns:' + this.davClient.xmlNamespaces[namespace] + '="' + namespace + '"'
}
body += '>\n'
body += this._renderProperties(properties)
body +=
'<oc:filter-rules>\n' +
'<oc:favorite>1</oc:favorite>\n' +
'</oc:filter-rules>\n' +
'</oc:filter-files>'
return this._sendDavReport(body)
}
_renderProperties (properties) {
if (!properties) {
return ''
}
let body = ' <d:prop>\n'
for (const ii in properties) {
if (!Object.prototype.hasOwnProperty.call(properties, ii)) {
continue
}
const property = this.davClient.parseClarkNotation(properties[ii])
if (this.davClient.xmlNamespaces[property.namespace]) {
body += ' <' + this.davClient.xmlNamespaces[property.namespace] + ':' + property.name + ' />\n'
} else {
body += ' <x:' + property.name + ' xmlns:x="' + property.namespace + '" />\n'
}
}
body += ' </d:prop>\n'
return body
}
/**
* Get all files and folder of the user for a given list of tags
* @param {number[]} tags list of tag ids
* @param {string[]} properties list of DAV properties which are expected in the response
* @returns {Promise.<FileInfo[]>} boolean: whether the operation was successful
* @returns {Promise.<error>} string: error message, if any.
*/
getFilesByTags (tags, properties) {
let body =
'<?xml version="1.0"?>\n' +
'<oc:filter-files '
let namespace
for (namespace in this.davClient.xmlNamespaces) {
body += ' xmlns:' + this.davClient.xmlNamespaces[namespace] + '="' + namespace + '"'
}
body += '>\n'
body += this._renderProperties(properties)
body += '<oc:filter-rules>'
for (const tag in tags) {
body += '<oc:systemtag>'
body += tags[tag]
body += '</oc:systemtag>'
}
body += '</oc:filter-rules>'
body += '</oc:filter-files>'
return this._sendDavReport(body)
}
_sendDavReport (body) {
if (!this.helpers.getAuthorization()) {
return Promise.reject('Please specify an authorization first.')
}
return this.helpers.getCurrentUserAsync().then(user => {
const path = '/files/' + user.id + '/'
const headers = this.helpers.buildHeaders()
headers['Content-Type'] = 'application/xml; charset=utf-8'
return this.davClient.request('REPORT', this.helpers._buildFullWebDAVPathV2(path), headers, body).then(result => {
if (result.status !== 207) {
return Promise.reject(this.helpers.buildHttpErrorFromDavResponse(result.status, result.body))
} else {
return Promise.resolve(this.helpers._parseBody(result.body, 2))
}
})
})
}
}
module.exports = Files