]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/pods.js
4020a96034bed386feaa9723f74eb336ef685e9f
[github/Chocobozzz/PeerTube.git] / server / models / pods.js
1 'use strict'
2
3 const mongoose = require('mongoose')
4 const map = require('lodash/map')
5 const validator = require('express-validator').validator
6
7 const constants = require('../initializers/constants')
8
9 // ---------------------------------------------------------------------------
10
11 const PodSchema = mongoose.Schema({
12 url: String,
13 publicKey: String,
14 score: { type: Number, max: constants.FRIEND_SCORE.MAX },
15 createdDate: {
16 type: Date,
17 default: Date.now
18 }
19 })
20
21 // TODO: set options (TLD...)
22 PodSchema.path('url').validate(validator.isURL)
23 PodSchema.path('publicKey').required(true)
24 PodSchema.path('score').validate(function (value) { return !isNaN(value) })
25
26 PodSchema.methods = {
27 toFormatedJSON
28 }
29
30 PodSchema.statics = {
31 countAll,
32 incrementScores,
33 list,
34 listAllIds,
35 listBadPods,
36 load,
37 loadByUrl,
38 removeAll
39 }
40
41 PodSchema.pre('save', function (next) {
42 const self = this
43
44 Pod.loadByUrl(this.url, function (err, pod) {
45 if (err) return next(err)
46
47 if (pod) return next(new Error('Pod already exists.'))
48
49 self.score = constants.FRIEND_SCORE.BASE
50 return next()
51 })
52 })
53
54 const Pod = mongoose.model('Pod', PodSchema)
55
56 // ------------------------------ METHODS ------------------------------
57
58 function toFormatedJSON () {
59 const json = {
60 id: this._id,
61 url: this.url,
62 score: this.score,
63 createdDate: this.createdDate
64 }
65
66 return json
67 }
68
69 // ------------------------------ Statics ------------------------------
70
71 function countAll (callback) {
72 return this.count(callback)
73 }
74
75 function incrementScores (ids, value, callback) {
76 if (!callback) callback = function () {}
77 return this.update({ _id: { $in: ids } }, { $inc: { score: value } }, { multi: true }, callback)
78 }
79
80 function list (callback) {
81 return this.find(callback)
82 }
83
84 function listAllIds (callback) {
85 return this.find({}, { _id: 1 }, function (err, pods) {
86 if (err) return callback(err)
87
88 return callback(null, map(pods, '_id'))
89 })
90 }
91
92 function listBadPods (callback) {
93 return this.find({ score: 0 }, callback)
94 }
95
96 function load (id, callback) {
97 return this.findById(id, callback)
98 }
99
100 function loadByUrl (url, callback) {
101 return this.findOne({ url: url }, callback)
102 }
103
104 function removeAll (callback) {
105 return this.remove({}, callback)
106 }