Server: add ability to update a video
[oweals/peertube.git] / server / lib / friends.js
1 'use strict'
2
3 const each = require('async/each')
4 const eachLimit = require('async/eachLimit')
5 const eachSeries = require('async/eachSeries')
6 const fs = require('fs')
7 const request = require('request')
8 const waterfall = require('async/waterfall')
9
10 const constants = require('../initializers/constants')
11 const db = require('../initializers/database')
12 const logger = require('../helpers/logger')
13 const requests = require('../helpers/requests')
14
15 const friends = {
16   addVideoToFriends,
17   updateVideoToFriends,
18   hasFriends,
19   getMyCertificate,
20   makeFriends,
21   quitFriends,
22   removeVideoToFriends,
23   sendOwnedVideosToPod
24 }
25
26 function addVideoToFriends (video) {
27   createRequest('add', constants.REQUEST_ENDPOINTS.VIDEOS, video)
28 }
29
30 function updateVideoToFriends (video) {
31   createRequest('update', constants.REQUEST_ENDPOINTS.VIDEOS, video)
32 }
33
34 function hasFriends (callback) {
35   db.Pod.countAll(function (err, count) {
36     if (err) return callback(err)
37
38     const hasFriends = (count !== 0)
39     callback(null, hasFriends)
40   })
41 }
42
43 function getMyCertificate (callback) {
44   fs.readFile(constants.CONFIG.STORAGE.CERT_DIR + 'peertube.pub', 'utf8', callback)
45 }
46
47 function makeFriends (hosts, callback) {
48   const podsScore = {}
49
50   logger.info('Make friends!')
51   getMyCertificate(function (err, cert) {
52     if (err) {
53       logger.error('Cannot read public cert.')
54       return callback(err)
55     }
56
57     eachSeries(hosts, function (host, callbackEach) {
58       computeForeignPodsList(host, podsScore, callbackEach)
59     }, function (err) {
60       if (err) return callback(err)
61
62       logger.debug('Pods scores computed.', { podsScore: podsScore })
63       const podsList = computeWinningPods(hosts, podsScore)
64       logger.debug('Pods that we keep.', { podsToKeep: podsList })
65
66       makeRequestsToWinningPods(cert, podsList, callback)
67     })
68   })
69 }
70
71 function quitFriends (callback) {
72   // Stop pool requests
73   db.Request.deactivate()
74
75   waterfall([
76     function flushRequests (callbackAsync) {
77       db.Request.flush(callbackAsync)
78     },
79
80     function getPodsList (callbackAsync) {
81       return db.Pod.list(callbackAsync)
82     },
83
84     function announceIQuitMyFriends (pods, callbackAsync) {
85       const requestParams = {
86         method: 'POST',
87         path: '/api/' + constants.API_VERSION + '/pods/remove',
88         sign: true
89       }
90
91       // Announce we quit them
92       // We don't care if the request fails
93       // The other pod will exclude us automatically after a while
94       eachLimit(pods, constants.REQUESTS_IN_PARALLEL, function (pod, callbackEach) {
95         requestParams.toPod = pod
96         requests.makeSecureRequest(requestParams, callbackEach)
97       }, function (err) {
98         if (err) {
99           logger.error('Some errors while quitting friends.', { err: err })
100           // Don't stop the process
101         }
102
103         return callbackAsync(null, pods)
104       })
105     },
106
107     function removePodsFromDB (pods, callbackAsync) {
108       each(pods, function (pod, callbackEach) {
109         pod.destroy().asCallback(callbackEach)
110       }, callbackAsync)
111     }
112   ], function (err) {
113     // Don't forget to re activate the scheduler, even if there was an error
114     db.Request.activate()
115
116     if (err) return callback(err)
117
118     logger.info('Removed all remote videos.')
119     return callback(null)
120   })
121 }
122
123 function removeVideoToFriends (videoParams) {
124   createRequest('remove', constants.REQUEST_ENDPOINTS.VIDEOS, videoParams)
125 }
126
127 function sendOwnedVideosToPod (podId) {
128   db.Video.listOwnedAndPopulateAuthorAndTags(function (err, videosList) {
129     if (err) {
130       logger.error('Cannot get the list of videos we own.')
131       return
132     }
133
134     videosList.forEach(function (video) {
135       video.toAddRemoteJSON(function (err, remoteVideo) {
136         if (err) {
137           logger.error('Cannot convert video to remote.', { error: err })
138           // Don't break the process
139           return
140         }
141
142         createRequest('add', constants.REQUEST_ENDPOINTS.VIDEOS, remoteVideo, [ podId ])
143       })
144     })
145   })
146 }
147
148 // ---------------------------------------------------------------------------
149
150 module.exports = friends
151
152 // ---------------------------------------------------------------------------
153
154 function computeForeignPodsList (host, podsScore, callback) {
155   getForeignPodsList(host, function (err, foreignPodsList) {
156     if (err) return callback(err)
157
158     if (!foreignPodsList) foreignPodsList = []
159
160     // Let's give 1 point to the pod we ask the friends list
161     foreignPodsList.push({ host })
162
163     foreignPodsList.forEach(function (foreignPod) {
164       const foreignPodHost = foreignPod.host
165
166       if (podsScore[foreignPodHost]) podsScore[foreignPodHost]++
167       else podsScore[foreignPodHost] = 1
168     })
169
170     callback()
171   })
172 }
173
174 function computeWinningPods (hosts, podsScore) {
175   // Build the list of pods to add
176   // Only add a pod if it exists in more than a half base pods
177   const podsList = []
178   const baseScore = hosts.length / 2
179   Object.keys(podsScore).forEach(function (podHost) {
180     // If the pod is not me and with a good score we add it
181     if (isMe(podHost) === false && podsScore[podHost] > baseScore) {
182       podsList.push({ host: podHost })
183     }
184   })
185
186   return podsList
187 }
188
189 function getForeignPodsList (host, callback) {
190   const path = '/api/' + constants.API_VERSION + '/pods'
191
192   request.get(constants.REMOTE_SCHEME.HTTP + '://' + host + path, function (err, response, body) {
193     if (err) return callback(err)
194
195     try {
196       const json = JSON.parse(body)
197       return callback(null, json)
198     } catch (err) {
199       return callback(err)
200     }
201   })
202 }
203
204 function makeRequestsToWinningPods (cert, podsList, callback) {
205   // Stop pool requests
206   db.Request.deactivate()
207   // Flush pool requests
208   db.Request.forceSend()
209
210   eachLimit(podsList, constants.REQUESTS_IN_PARALLEL, function (pod, callbackEach) {
211     const params = {
212       url: constants.REMOTE_SCHEME.HTTP + '://' + pod.host + '/api/' + constants.API_VERSION + '/pods/',
213       method: 'POST',
214       json: {
215         host: constants.CONFIG.WEBSERVER.HOST,
216         publicKey: cert
217       }
218     }
219
220     requests.makeRetryRequest(params, function (err, res, body) {
221       if (err) {
222         logger.error('Error with adding %s pod.', pod.host, { error: err })
223         // Don't break the process
224         return callbackEach()
225       }
226
227       if (res.statusCode === 200) {
228         const podObj = db.Pod.build({ host: pod.host, publicKey: body.cert })
229         podObj.save().asCallback(function (err, podCreated) {
230           if (err) {
231             logger.error('Cannot add friend %s pod.', pod.host, { error: err })
232             return callbackEach()
233           }
234
235           // Add our videos to the request scheduler
236           sendOwnedVideosToPod(podCreated.id)
237
238           return callbackEach()
239         })
240       } else {
241         logger.error('Status not 200 for %s pod.', pod.host)
242         return callbackEach()
243       }
244     })
245   }, function endRequests () {
246     // Final callback, we've ended all the requests
247     // Now we made new friends, we can re activate the pool of requests
248     db.Request.activate()
249
250     logger.debug('makeRequestsToWinningPods finished.')
251     return callback()
252   })
253 }
254
255 // Wrapper that populate "to" argument with all our friends if it is not specified
256 function createRequest (type, endpoint, data, to) {
257   if (to) return _createRequest(type, endpoint, data, to)
258
259   // If the "to" pods is not specified, we send the request to all our friends
260   db.Pod.listAllIds(function (err, podIds) {
261     if (err) {
262       logger.error('Cannot get pod ids', { error: err })
263       return
264     }
265
266     return _createRequest(type, endpoint, data, podIds)
267   })
268 }
269
270 function _createRequest (type, endpoint, data, to) {
271   const pods = []
272
273   // If there are no destination pods abort
274   if (to.length === 0) return
275
276   to.forEach(function (toPod) {
277     pods.push(db.Pod.build({ id: toPod }))
278   })
279
280   const createQuery = {
281     endpoint,
282     request: {
283       type: type,
284       data: data
285     }
286   }
287
288   // We run in transaction to keep coherency between Request and RequestToPod tables
289   db.sequelize.transaction(function (t) {
290     const dbRequestOptions = {
291       transaction: t
292     }
293
294     return db.Request.create(createQuery, dbRequestOptions).then(function (request) {
295       return request.setPods(pods, dbRequestOptions)
296     })
297   }).asCallback(function (err) {
298     if (err) logger.error('Error in createRequest transaction.', { error: err })
299   })
300 }
301
302 function isMe (host) {
303   return host === constants.CONFIG.WEBSERVER.HOST
304 }