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