3 const each = require('async/each')
4 const mongoose = require('mongoose')
5 const map = require('lodash/map')
6 const validator = require('express-validator').validator
8 const constants = require('../initializers/constants')
10 const Video = mongoose.model('Video')
12 // ---------------------------------------------------------------------------
14 const PodSchema = mongoose.Schema({
17 score: { type: Number, max: constants.FRIEND_SCORE.MAX },
24 PodSchema.path('host').validate(validator.isURL)
25 PodSchema.path('publicKey').required(true)
26 PodSchema.path('score').validate(function (value) { return !isNaN(value) })
43 PodSchema.pre('save', function (next) {
46 Pod.loadByHost(this.host, function (err, pod) {
47 if (err) return next(err)
49 if (pod) return next(new Error('Pod already exists.'))
51 self.score = constants.FRIEND_SCORE.BASE
56 PodSchema.pre('remove', function (next) {
57 // Remove the videos owned by this pod too
58 Video.listByHost(this.host, function (err, videos) {
59 if (err) return next(err)
61 each(videos, function (video, callbackEach) {
62 video.remove(callbackEach)
67 const Pod = mongoose.model('Pod', PodSchema)
69 // ------------------------------ METHODS ------------------------------
71 function toFormatedJSON () {
76 createdDate: this.createdDate
82 // ------------------------------ Statics ------------------------------
84 function countAll (callback) {
85 return this.count(callback)
88 function incrementScores (ids, value, callback) {
89 if (!callback) callback = function () {}
90 return this.update({ _id: { $in: ids } }, { $inc: { score: value } }, { multi: true }, callback)
93 function list (callback) {
94 return this.find(callback)
97 function listAllIds (callback) {
98 return this.find({}, { _id: 1 }, function (err, pods) {
99 if (err) return callback(err)
101 return callback(null, map(pods, '_id'))
105 function listBadPods (callback) {
106 return this.find({ score: 0 }, callback)
109 function load (id, callback) {
110 return this.findById(id, callback)
113 function loadByHost (host, callback) {
114 return this.findOne({ host }, callback)
117 function removeAll (callback) {
118 return this.remove({}, callback)