-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.js
448 lines (388 loc) · 13.8 KB
/
models.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
var fs = require('fs')
, path = require('path')
, mime = require('mime')
, im = require('imagemagick')
, _ = require('underscore')
, nconf = require('nconf')
, sha1 = require('sha1')
, extrafields = require('./extrafields')
;
/**
* Configuration
*/
nconf.file({ file: './conf.json' });
function define(mongoose, fn) {
/*
* Vars
*/
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
/*
* Schemas : Document
*/
Document_Schema = new Schema({
'slug': {
type: String, index: { unique: true },
set: function(v) {
return slugify(v);
}
},
'title': {
type: String,
set: function(v) {
if (v == '') v = this.title;
if (!this.slug) this.slug = v;
return v;
},
trim: true
},
'description': {
type: String
},
'resource': {
type: { name: String, file: String, size: Number, tmp: String, thumbnail: String, mime: String },
set: function(v) {
// A commenter pour import de docatl
// update file
if (v.tmp && !v.file) {
var filename = v.tmp.split('/').pop();
var pathfile = nconf.get('documents:dirs:files') + '/' + filename.substr(0, 2);
path.exists(pathfile, function(exist) {
if (!exist) fs.mkdirSync(pathfile, 0755);
fs.rename(v.tmp, pathfile + '/' + filename, function(err) {
//if (err) // how to do Something ???
//remove resource.tmp from document ?
});
});
v.size = fs.statSync(v.tmp).size;
v.thumbnail = null;
v.mime = mime.lookup(v.tmp);
v.file = '/' + filename.substr(0, 2) + '/' + filename;
//v.path = '/' + filename.substr(0, 2) + '/';
}
// Fin commentaire import docatl
// default title
if (!this.title) this.title = v.name;
return v;
}
},
'tags': {
type: [String],
set: function(v) {
var tags = v;
if (v.length == 1) tags = _.invoke(v[0].split(','), function() { return tagify(this); });
tags = _.uniq(tags);
// Save new tags
tags.forEach(function(tag_label) {
if(tag_label.trim()) {
Tag.findOne({ label: tag_label }, function(err, tag) {
if (!tag) {
tag = new Tag({label: tag_label});
tag.save();
}
});
}
});
return tags;
}
},
'statistics': [Date],
'status': Number, // 0 or undefined = exist, 1 = deleted
'created_at': {
type: Date,
default: Date.now,
set: function(v) {
if (!this.created_at) return Date.now();
return this.created_at;
}
},
'updated_at': {
type: Date,
default: Date.now
},
'_keywords': [String]
})
.pre('save', function(next) { // A tester
if (!this.created_at) {
this.created_at = this.updated_at = new Date;
} else {
this.updated_at = new Date;
}
// indexation
this._keywords = this.index();
next();
})
.pre('remove', function(next) {
// delete all resources
// Le probleme c'est que Model.remove() ne fait pas appel à ça
});
// virtual thumbnail getter and setter
Document_Schema
.virtual('thumbnail')
.get(function() {
return this.resource.thumbnail || this.resource.mime || mime.lookup(this.resource.file);
})
.set(function(v) {
// si not false, essaye d'utiliser v comme source si image si existe avec éventuellement retaille + renommage idem file
// sinon passe à null (retour fonc sur mime)
});
// virtual path getter and setter
Document_Schema
.virtual('path')
.get(function() {
var path = "";
this.tags.some(function(tag) {
if (tag.charAt(0) === '/') {
path = tag;
return true;
}
});
return path;
})
.set(function(path) {
var tags = this.tags;
tags.splice(tags.indexOf(this.path), 1, path);
this.set('tags', tags);
});
// Virtual download
Document_Schema
.virtual('addDownload')
.set(function() {
var stat = this.statistics;
stat.push(new Date());
this.set('statistics', stat);
this.save();
// For chaining
return this;
});
// Extra fields (from extrafields.js file)
Document_Schema.add(extrafields);
// Indexation
Document_Schema.methods.index = function() {
var indexables = nconf.get('documents:index')
, index = []
, _this = this
;
indexables.forEach(function(indexable) {
index = index.concat(_this[indexable] ? (_.isArray(_this[indexable]) ? _this[indexable] : _this[indexable].split(' ')) : [])
});
return index;
};
// toJSON with getters
// https://gist.github.com/1584121
// https://github.com/LearnBoost/mongoose/issues/412
Document_Schema.methods.toJSON2 = function() {
var json = this.toJSON()
, _this = this
;
Document_Schema.eachPath(function(path) {
json[path] = _this.get(path);
});
return json;
};
Document_Schema.methods.update = function(values, callback) {
var _this = this;
_.each(values, function(value, path) {
if (Document_Schema.path(path) || Document_Schema.virtualpath(path)) _this.set(path, value);
});
this.save(callback);
};
// thumbnail maker with imagemagick
Document_Schema.methods.createThumbnail = function(resource, callback) {
var doc = this
, options = nconf.get('thumbnails:options')
, srcPath = null
, dstPath = null;
// Si resource n'est une fonction c'est une création
if (typeof resource === 'function') {
callback = resource;
resource = this.resource;
srcPath = nconf.get('documents:dirs:files') + resource.file;
}
// Sinon c'est une maj
else {
resource.file = resource.path;
srcPath = resource.path;
dstPath = resource.path + '.png';
}
if (nconf.get('thumbnails:thumbables').indexOf(resource.mime) !== -1) {
var filename = resource.file.split('/').pop();
im.resize(_.extend(options, {
srcPath: srcPath + '[0]', // [0] first page pdf conversion
dstPath: dstPath || nconf.get('documents:dirs:tmp') + '/' + filename + '.png'
}), function(err) {
if (err) {
doc.set('resource.thumbnail', '');
callback(err);
} else { // move generated thumbnail
var pathfile = nconf.get('documents:dirs:thumbs') + '/' + filename.substr(0, 2);
path.exists(pathfile, function(exist) {
if (!exist) fs.mkdirSync(pathfile, 0755);
fs.rename(nconf.get('documents:dirs:tmp') + '/' + filename + '.png', pathfile + '/' + filename + '.png', function(err) {
if (err) callback(err);
else {
doc.set('resource.thumbnail', '/' + filename.substr(0, 2) + '/' + filename + '.png');
callback(null);
}
});
});
}
});
} else {
doc.set('resource.thumbnail', '');
callback(null);
}
};
Document_Schema.statics.getSome = function(req, callback) {
var query = {}
,blackhole = nconf.get('documents:blackhole')
,tags
,_this
;
// tags : impossible de le mettre dans le each ci-dessous, pas de helper $and
if (tags = req.tags) {
tags = _.isArray(tags) ? tags : tags.split(',');
tags = _.map(tags, function(tag) {
if (tag === blackhole) return { $or: [
{ tags: blackhole },
{ tags: { $not: /^\//g } }
]};
if (typeof tag === 'object') return tag;
else return {tags:tag};
});
query = { $and: tags };
};
// search : impossible de le mettre dans le each ci-dessous, pas de helper $and
if (search_query = req.search) {
// initilisation $and if needed (no tags)
if (!query.$and) query.$and = [];
var words = search_query.split(' ');
words.forEach(function(word){
word = word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
query.$and.push({"_keywords": new RegExp(word, 'i')});
});
}
_this = this.find(query);
_.each(req ,function(value, key) {
// Filtres
if (filter = _.find(nconf.get('documents:filters'), function(v, k) { return k == key; })) {
// Tranforme valeur si Number
// @TODO regarder eachPath sur http://mongoosejs.com/docs/api.html
var path = Document_Schema.path(key);
if (!(type = (path ? path.instance : false))) {
var subpaths = key.split('.');
var type = Document_Schema.path(subpaths[0]).options.type[subpaths[1]] || 'String';
type = (type == Number) ? 'Number' : 'String';
}
if (type == 'Number') value = parseFloat(value);
if (filter == 'exact') _this.where(key, value);
if (filter == 'like') _this.regex(key, new RegExp(value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'i'));
}
});
// LISTE et QUERY
// limit, offset, sort, search
return _this.run(callback);
};
// @TODO : A mettre dans une lib
var slugify = function(s) {
return s.replace(/\s+/ig, '_').replace(/[^a-zA-Z0-9_]+/ig, '').toLowerCase(); // TODO garder les accents (à trans en non accent)
};
// @TODO : A mettre dans une lib
var tagify = function(s) {
// caractères interdits : &,
return s.replace(/([&,])+/ig, '').trim();
};
/*
* Schemas : Tag
*/
Tag_Schema = new Schema({
'label': { type: String, index: { unique: true }, set: function(v) {
return tagify(v);
}}
});
Tag_Schema.statics.getSome = function(req, callback) {
var query = {}
,subdirsof
;
// Récupération des /tags fils direct d'un /tag
if (subdirsof = req.subdirsof) {
subdirsof = subdirsof.replace(new RegExp('/+$', 'g'), '');
var deep = subdirsof.split('/').length + 1;
query = { $and: [
{ label: new RegExp('^' + subdirsof + '/', 'i') },
{ $where: "this.label.split('/').length === " + deep }
]};
if (subdirsof === '') query.$and.push({ label: { $ne: '/' } });
}
if (startwith = req.startwith) {
if (startwith[0] === '/' && req.slash && req.slash === 'false') return [];
query = { label: new RegExp('^' + startwith, 'i') };
}
return this.find(query).sort('label', 'ascending').execFind(callback);
};
/*
* Schemas : User
*/
User_Schema = new Schema({
name: String
, email: String
, salt: String
, password: String
// @TODO gérer les roles
})
.pre('save', function(next) {
if (!this.salt) {
this.salt = sha1(this.email + +new Date);
}
this.password = sha1(this.salt + this.password);
next();
});
// Valid the password
User_Schema
.virtual('validPassword')
.get(function() {
return function(password) {
return sha1(this.salt + password) === this.password;
}
});
// Return the public
User_Schema
.virtual('getPublic')
.get(function() {
return {
name: this.name
, email: this.email
}
});
/**
* Collections' declaration
*/
var Document = mongoose.model('Document', Document_Schema);
/*
* Document.prototype.save - redefinition
*/
Document.prototype._save = Document.prototype.save;
Document.prototype.save = function(fn) {
var self = this;
self._save(function(err) {
if (!err) {
if (fn) fn(err);
} else if (err.message.indexOf('E11000') == 0) { // Sans doute prévoir un meilleur test (quid si autre champ unique ?)
// calcul du nouveau slug
var slug = self.slug.split('-');
var i = (slug.length > 1) ? slug.pop() : 0;
self.setValue('slug', slug.join('-') + '-' + (i*1+1));
self.isNew = true;
self.save(fn);
} else {
//throw new Error(err.message)
fn(err);
}
});
};
var Tag = mongoose.model('Tag', Tag_Schema);
var User = mongoose.model('User', User_Schema);
// Launch callback
fn();
};
exports.define = define;