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