Try to make a better communication (between pods) module
[oweals/peertube.git] / server / models / pods.js
1 'use strict'
2
3 const mongoose = require('mongoose')
4
5 const constants = require('../initializers/constants')
6 const logger = require('../helpers/logger')
7
8 // ---------------------------------------------------------------------------
9
10 const podsSchema = mongoose.Schema({
11   url: String,
12   publicKey: String,
13   score: { type: Number, max: constants.FRIEND_BASE_SCORE }
14 })
15 const PodsDB = mongoose.model('pods', podsSchema)
16
17 // ---------------------------------------------------------------------------
18
19 const Pods = {
20   add: add,
21   count: count,
22   findById: findById,
23   findByUrl: findByUrl,
24   findBadPods: findBadPods,
25   incrementScores: incrementScores,
26   list: list,
27   listAllIds: listAllIds,
28   listAllUrls: listAllUrls,
29   remove: remove,
30   removeAll: removeAll,
31   removeAllByIds: removeAllByIds
32 }
33
34 // TODO: check if the pod is not already a friend
35 function add (data, callback) {
36   if (!callback) callback = function () {}
37   const params = {
38     url: data.url,
39     publicKey: data.publicKey,
40     score: constants.FRIEND_BASE_SCORE
41   }
42
43   PodsDB.create(params, callback)
44 }
45
46 function count (callback) {
47   return PodsDB.count(callback)
48 }
49
50 function findBadPods (callback) {
51   PodsDB.find({ score: 0 }, callback)
52 }
53
54 function findById (id, callback) {
55   PodsDB.findById(id, callback)
56 }
57
58 function findByUrl (url, callback) {
59   PodsDB.findOne({ url: url }, callback)
60 }
61
62 function incrementScores (ids, value, callback) {
63   if (!callback) callback = function () {}
64   PodsDB.update({ _id: { $in: ids } }, { $inc: { score: value } }, { multi: true }, callback)
65 }
66
67 function list (callback) {
68   PodsDB.find(function (err, podsList) {
69     if (err) {
70       logger.error('Cannot get the list of the pods.')
71       return callback(err)
72     }
73
74     return callback(null, podsList)
75   })
76 }
77
78 function listAllIds (callback) {
79   return PodsDB.find({}, { _id: 1 }, callback)
80 }
81
82 function listAllUrls (callback) {
83   return PodsDB.find({}, { _id: 0, url: 1 }, callback)
84 }
85
86 function remove (url, callback) {
87   if (!callback) callback = function () {}
88   PodsDB.remove({ url: url }, callback)
89 }
90
91 function removeAll (callback) {
92   if (!callback) callback = function () {}
93   PodsDB.remove(callback)
94 }
95
96 function removeAllByIds (ids, callback) {
97   if (!callback) callback = function () {}
98   PodsDB.remove({ _id: { $in: ids } }, callback)
99 }
100
101 // ---------------------------------------------------------------------------
102
103 module.exports = Pods