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