Repository navigation
Expand file tree
/
Copy pathcore.js
More file actions
379 lines (354 loc) 路 11.4 KB
/
Copy pathcore.js
File metadata and controls
379 lines (354 loc) 路 11.4 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
import { EventEmitter } from 'eventemitter3';
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { check, Match } from 'meteor/check';
import { formatFileURL, helpers } from './lib.js';
import { FilesCursor, FileCursor } from './cursor.js';
/* eslint-disable new-cap */
/**
* @const {Match.Pattern} SELECTOR_PATTERN - Selectors accepted by `find`, `findOne`, `findOneAsync`, and `countDocuments`
*/
const SELECTOR_PATTERN = Match.Optional(Match.OneOf(Object, String, Boolean, Number, null, Mongo.ObjectID));
/* eslint-enable new-cap */
export default class FilesCollectionCore extends EventEmitter {
constructor() {
super();
}
static __helpers = helpers;
static schema = {
_id: {
type: String
},
size: {
type: Number
},
name: {
type: String
},
type: {
type: String
},
path: {
type: String
},
isVideo: {
type: Boolean
},
isAudio: {
type: Boolean
},
isImage: {
type: Boolean
},
isText: {
type: Boolean
},
isJSON: {
type: Boolean
},
isPDF: {
type: Boolean
},
extension: {
type: String,
optional: true
},
ext: {
type: String,
optional: true
},
extensionWithDot: {
type: String,
optional: true
},
mime: {
type: String,
optional: true
},
'mime-type': {
type: String,
optional: true
},
_storagePath: {
type: String
},
_downloadRoute: {
type: String
},
_collectionName: {
type: String
},
public: {
type: Boolean,
optional: true
},
meta: {
type: Object,
blackbox: true,
optional: true
},
userId: {
type: String,
optional: true
},
updatedAt: {
type: Date,
optional: true
},
versions: {
type: Object,
blackbox: true
}
};
/**
* Print logs in debug mode.
* @locus Anywhere
* @memberOf FilesCollectionCore
* @returns {void}
*/
_debug(...args) {
if (this.debug) {
// if debug is truthy but not true it should be a function
const debugFn = this.debug === true ? null : this.debug;
// eslint-disable-next-line no-console
const logger = console.info || console.log || function () {};
if (!debugFn) {
logger.apply(undefined, args);
return;
}
try {
debugFn.apply(undefined, args);
} catch (error) {
// A failing custom logger must not break uploads or downloads
logger.call(undefined, '[FilesCollection] [debug] Custom debug function threw:', error);
}
}
}
/**
* Returns file's name.
* @locus Anywhere
* @memberOf FilesCollectionCore
* @param {FileData} fileData - File data object
* @returns {string} The sanitized file name
*/
_getFileName(fileData) {
const fileName = fileData.name || fileData.fileName;
if (helpers.isString(fileName) && fileName.length > 0) {
return fileName.replace(/^\.\.+/, '').replace(/\.{2,}/g, '.').replace(/\//g, '');
}
return '';
}
/**
* Extracts extension information from a file name.
* @locus Anywhere
* @memberOf FilesCollectionCore
* @param {string} fileName - The file name
* @returns {Partial<FileData>} An object with properties: ext, extension, and extensionWithDot
*/
_getExt(fileName) {
if (fileName.includes('.')) {
const extension = (fileName.split('.').pop().split('?')[0] || '')
.toLowerCase()
.replace(/([^a-z0-9\-\_\.]+)/gi, '')
.substring(0, 20);
return { ext: extension, extension, extensionWithDot: `.${extension}` };
}
return { ext: '', extension: '', extensionWithDot: '' };
}
/**
* Classifies the file based on its MIME type.
* @locus Anywhere
* @memberOf FilesCollectionCore
* @param {Partial<FileObj>} data - File data object
* @returns {void}
*/
_updateFileTypes(data) {
data.isVideo = /^video\//i.test(data.type);
data.isAudio = /^audio\//i.test(data.type);
data.isImage = /^image\//i.test(data.type);
data.isText = /^text\//i.test(data.type);
data.isJSON = /^application\/json$/i.test(data.type);
data.isPDF = /^application\/(x-)?pdf$/i.test(data.type);
}
/**
* Builds an object that conforms to the default schema from file data.
* @locus Anywhere
* @memberOf FilesCollectionCore
* @param {FileData & Partial<FileObj>} data - File data combined with optional FileObj properties
* @returns {Partial<FileObj>} The schema-compliant file object
*/
_dataToSchema(data) {
const ds = {
name: data.name,
extension: data.extension,
ext: data.extension,
extensionWithDot: data.extension ? `.${data.extension}` : '',
path: data.path,
meta: data.meta,
type: data.type,
mime: data.type,
'mime-type': data.type,
size: data.size,
userId: data.userId || null,
versions: {
original: {
path: data.path,
size: data.size,
type: data.type,
extension: data.extension
}
},
_downloadRoute: data._downloadRoute || this.downloadRoute,
_collectionName: data._collectionName || this.collectionName
};
// Optional fileId
if (data.fileId) {
ds._id = data.fileId;
}
this._updateFileTypes(ds);
ds._storagePath = data._storagePath || this.storagePath(Object.assign({}, data, ds));
if (typeof ds._storagePath?.then === 'function') {
throw new Meteor.Error(500, `[FilesCollection.${this.collectionName}] async "storagePath" result must be resolved and passed as "_storagePath"`);
}
return ds;
}
/**
* Finds and returns a FileCursor for a matching document asynchronously.
* @locus Anywhere
* @memberOf FilesCollectionCore
* @param {MeteorFilesSelector} [selector={}] - Mongo-style selector
* @param {MeteorFilesOptions} [options] - Mongo query options
* @returns {Promise<FileCursor|null>} A FileCursor instance, or null if not found
*/
async findOneAsync(selector = {}, options) {
this._debug(`[FilesCollection] [findOneAsync(${JSON.stringify(selector)}, ${JSON.stringify(options)})]`);
/* eslint-disable new-cap */
check(selector, SELECTOR_PATTERN);
check(options, Match.Optional(Object));
/* eslint-enable new-cap */
const doc = await this.collection.findOneAsync(selector, options);
if (doc) {
return new FileCursor(doc, this);
}
return null;
}
/**
* Finds and returns a FileCursor for a matching document (client only).
* @locus Client
* @memberOf FilesCollectionCore
* @param {MeteorFilesSelector} [selector={}] - Mongo-style selector
* @param {MeteorFilesOptions} [options] - Mongo query options
* @returns {FileCursor|null} A FileCursor instance, or null if not found
* @throws {Meteor.Error} If called on the server
*/
findOne(selector = {}, options) {
this._debug(`[FilesCollection] [findOne(${JSON.stringify(selector)}, ${JSON.stringify(options)})]`, Meteor.isServer);
if (Meteor.isServer) {
throw new Meteor.Error(404, 'FilesCollection#findOne() not available in server! Use .findOneAsync instead');
}
/* eslint-disable new-cap */
check(selector, SELECTOR_PATTERN);
check(options, Match.Optional(Object));
/* eslint-enable new-cap */
const doc = this.collection.findOne(selector, options);
if (doc) {
return new FileCursor(doc, this);
}
return null;
}
/**
* Finds and returns a FilesCursor for matching documents.
* @locus Anywhere
* @memberOf FilesCollectionCore
* @param {MeteorFilesSelector} [selector={}] - Mongo-style selector
* @param {MeteorFilesOptions} [options] - Mongo query options
* @returns {FilesCursor} A FilesCursor instance
*/
find(selector = {}, options) {
this._debug(`[FilesCollection] [find(${JSON.stringify(selector)}, ${JSON.stringify(options)})]`);
/* eslint-disable new-cap */
check(selector, SELECTOR_PATTERN);
check(options, Match.Optional(Object));
/* eslint-enable new-cap */
return new FilesCursor(selector, options, this);
}
/**
* Links to the underlying Mongo.Collection update method.
* @locus Client
* @memberOf FilesCollectionCore
* @param {...*} args - Update method arguments
* @returns {Mongo.Collection} The underlying collection
*/
update(...args) {
this.collection.update.apply(this.collection, args);
return this.collection;
}
/**
* Links to the underlying Mongo.Collection updateAsync method.
* @locus Anywhere
* @memberOf FilesCollectionCore
* @param {...*} args - Update method arguments
* @returns {Promise<number>} The number of updated records
*/
async updateAsync(...args) {
return await this.collection.updateAsync.apply(this.collection, args);
}
/**
* Counts records matching a selector.
* @locus Anywhere
* @memberOf FilesCollectionCore
* @param {MeteorFilesSelector} [_selector={}] - Mongo-style selector
* @param {Mongo.CountDocumentsOptions} [options] - Mongo's CountDocumentsOptions
* @returns {Promise<number>} The number of matching records
*/
async countDocuments(_selector = {}, options) {
this._debug(`[FilesCollection] [countDocuments(${JSON.stringify(_selector)}, ${JSON.stringify(options)})]`);
/* eslint-disable new-cap */
check(_selector, SELECTOR_PATTERN);
check(options, Match.Optional(Object));
/* eslint-enable new-cap */
let selector = _selector;
if (helpers.isString(selector) || helpers.isNumber(selector) || selector instanceof Mongo.ObjectID) {
// Same shorthand as `find()`: scalars match `_id`
selector = { _id: selector };
}
if (!selector || (helpers.isObject(selector) && Object.hasOwn(selector, '_id') && !selector._id)) {
// Same as `find()`: falsy selectors match nothing
return 0;
}
return await this.collection.countDocuments(selector, options);
}
/**
* Asynchronously returns the number of estimated documents qty in the Collection
* @locus Anywhere
* @memberOf FilesCollectionCore
* @param {Mongo.EstimatedDocumentCountOptions} [options] - EstimatedDocumentCountOptions
* @returns {Promise<number>}
*/
async estimatedDocumentCount(options) {
/* eslint-disable-next-line new-cap */
check(options, Match.Optional(Object));
this._debug('[FilesCollection] [estimatedDocumentCount()]');
return await this.collection.estimatedDocumentCount(options);
}
/**
* Returns a downloadable URL for a file.
* @locus Anywhere
* @memberOf FilesCollectionCore
* @param {Partial<FileObj>|FileCursor|null} fileObj - A file object reference, or a FileCursor
* @param {string} [version='original'] - The file version
* @param {string} [uriBase] - Optional URI base
* @summary Uses the document's stored `_downloadRoute` and `_collectionName` when they are safe, otherwise this collection's values
* @returns {string} The download URL, or an empty string if the file is not found
*/
link(fileObj, version = 'original', uriBase) {
if (!fileObj) {
return '';
}
const fileRef = (fileObj instanceof FileCursor) ? fileObj._fileRef : fileObj;
this._debug(`[FilesCollection] [link(${helpers.isObject(fileRef) ? fileRef._id : undefined}, ${version})]`);
// eslint-disable-next-line new-cap
check(fileRef, Match.Where((obj) => helpers.isObject(obj)));
return formatFileURL(fileRef, version, uriBase, this);
}
}