1 import * as request from 'request'
2 import * as Sequelize from 'sequelize'
3 import * as Promise from 'bluebird'
5 import { database as db } from '../initializers/database'
11 REQUEST_ENDPOINT_ACTIONS,
13 } from '../initializers'
22 RequestSchedulerOptions,
24 RequestVideoQaduScheduler,
25 RequestVideoQaduSchedulerOptions,
27 RequestVideoEventScheduler,
28 RequestVideoEventSchedulerOptions
36 RequestVideoEventType,
40 type QaduParam = { videoId: string, type: RequestVideoQaduType }
41 type EventParam = { videoId: string, type: RequestVideoEventType }
43 const ENDPOINT_ACTIONS = REQUEST_ENDPOINT_ACTIONS[REQUEST_ENDPOINTS.VIDEOS]
45 const requestScheduler = new RequestScheduler()
46 const requestVideoQaduScheduler = new RequestVideoQaduScheduler()
47 const requestVideoEventScheduler = new RequestVideoEventScheduler()
49 function activateSchedulers () {
50 requestScheduler.activate()
51 requestVideoQaduScheduler.activate()
52 requestVideoEventScheduler.activate()
55 function addVideoToFriends (videoData: Object, transaction: Sequelize.Transaction) {
57 type: ENDPOINT_ACTIONS.ADD,
58 endpoint: REQUEST_ENDPOINTS.VIDEOS,
62 return createRequest(options)
65 function updateVideoToFriends (videoData: Object, transaction: Sequelize.Transaction) {
67 type: ENDPOINT_ACTIONS.UPDATE,
68 endpoint: REQUEST_ENDPOINTS.VIDEOS,
72 return createRequest(options)
75 function removeVideoToFriends (videoParams: Object) {
77 type: ENDPOINT_ACTIONS.REMOVE,
78 endpoint: REQUEST_ENDPOINTS.VIDEOS,
82 return createRequest(options)
85 function reportAbuseVideoToFriend (reportData: Object, video: VideoInstance, transaction: Sequelize.Transaction) {
87 type: ENDPOINT_ACTIONS.REPORT_ABUSE,
88 endpoint: REQUEST_ENDPOINTS.VIDEOS,
90 toIds: [ video.Author.podId ],
93 return createRequest(options)
96 function quickAndDirtyUpdateVideoToFriends (qaduParam: QaduParam, transaction?: Sequelize.Transaction) {
98 videoId: qaduParam.videoId,
102 return createVideoQaduRequest(options)
105 function quickAndDirtyUpdatesVideoToFriends (qadusParams: QaduParam[], transaction: Sequelize.Transaction) {
108 qadusParams.forEach(function (qaduParams) {
109 tasks.push(quickAndDirtyUpdateVideoToFriends(qaduParams, transaction))
112 return Promise.all(tasks)
115 function addEventToRemoteVideo (eventParam: EventParam, transaction?: Sequelize.Transaction) {
117 videoId: eventParam.videoId,
118 type: eventParam.type,
121 return createVideoEventRequest(options)
124 function addEventsToRemoteVideo (eventsParams: EventParam[], transaction: Sequelize.Transaction) {
127 eventsParams.forEach(function (eventParams) {
128 tasks.push(addEventToRemoteVideo(eventParams, transaction))
131 return Promise.all(tasks)
134 function hasFriends () {
135 return db.Pod.countAll().then(count => count !== 0)
138 function makeFriends (hosts: string[]) {
141 logger.info('Make friends!')
142 return getMyPublicCert()
144 return Promise.mapSeries(hosts, host => {
145 return computeForeignPodsList(host, podsScore)
149 logger.debug('Pods scores computed.', { podsScore: podsScore })
150 const podsList = computeWinningPods(hosts, podsScore)
151 logger.debug('Pods that we keep.', { podsToKeep: podsList })
153 return makeRequestsToWinningPods(cert, podsList)
157 function quitFriends () {
158 // Stop pool requests
159 requestScheduler.deactivate()
161 return requestScheduler.flush()
163 return requestVideoQaduScheduler.flush()
169 const requestParams = {
170 method: 'POST' as 'POST',
171 path: '/api/' + API_VERSION + '/remote/pods/remove',
176 // Announce we quit them
177 // We don't care if the request fails
178 // The other pod will exclude us automatically after a while
179 return Promise.map(pods, pod => {
180 requestParams.toPod = pod
181 return makeSecureRequest(requestParams)
182 }, { concurrency: REQUESTS_IN_PARALLEL })
185 logger.error('Some errors while quitting friends.', { err: err })
186 // Don't stop the process
191 pods.forEach(pod => tasks.push(pod.destroy()))
193 return Promise.all(pods)
196 logger.info('Removed all remote videos.')
197 // Don't forget to re activate the scheduler, even if there was an error
198 return requestScheduler.activate()
200 .finally(() => requestScheduler.activate())
203 function sendOwnedVideosToPod (podId: number) {
204 db.Video.listOwnedAndPopulateAuthorAndTags()
205 .then(videosList => {
207 videosList.forEach(video => {
208 const promise = video.toAddRemoteJSON()
209 .then(remoteVideo => {
212 endpoint: REQUEST_ENDPOINTS.VIDEOS,
217 return createRequest(options)
220 logger.error('Cannot convert video to remote.', { error: err })
221 // Don't break the process
228 return Promise.all(tasks)
232 function getRequestScheduler () {
233 return requestScheduler
236 function getRequestVideoQaduScheduler () {
237 return requestVideoQaduScheduler
240 function getRequestVideoEventScheduler () {
241 return requestVideoEventScheduler
244 // ---------------------------------------------------------------------------
249 updateVideoToFriends,
250 reportAbuseVideoToFriend,
251 quickAndDirtyUpdateVideoToFriends,
252 quickAndDirtyUpdatesVideoToFriends,
253 addEventToRemoteVideo,
254 addEventsToRemoteVideo,
258 removeVideoToFriends,
259 sendOwnedVideosToPod,
261 getRequestVideoQaduScheduler,
262 getRequestVideoEventScheduler
265 // ---------------------------------------------------------------------------
267 function computeForeignPodsList (host: string, podsScore: { [ host: string ]: number }) {
269 return getForeignPodsList(host).then((res: any) => {
270 const foreignPodsList = res.data
272 // Let's give 1 point to the pod we ask the friends list
273 foreignPodsList.push({ host })
275 foreignPodsList.forEach(foreignPod => {
276 const foreignPodHost = foreignPod.host
278 if (podsScore[foreignPodHost]) podsScore[foreignPodHost]++
279 else podsScore[foreignPodHost] = 1
286 function computeWinningPods (hosts: string[], podsScore: { [ host: string ]: number }) {
287 // Build the list of pods to add
288 // Only add a pod if it exists in more than a half base pods
290 const baseScore = hosts.length / 2
292 Object.keys(podsScore).forEach(podHost => {
293 // If the pod is not me and with a good score we add it
294 if (isMe(podHost) === false && podsScore[podHost] > baseScore) {
295 podsList.push({ host: podHost })
302 function getForeignPodsList (host: string) {
303 return new Promise((res, rej) => {
304 const path = '/api/' + API_VERSION + '/pods'
306 request.get(REMOTE_SCHEME.HTTP + '://' + host + path, function (err, response, body) {
307 if (err) return rej(err)
310 const json = JSON.parse(body)
319 function makeRequestsToWinningPods (cert: string, podsList: PodInstance[]) {
320 // Stop pool requests
321 requestScheduler.deactivate()
322 // Flush pool requests
323 requestScheduler.forceSend()
325 return Promise.map(podsList, pod => {
327 url: REMOTE_SCHEME.HTTP + '://' + pod.host + '/api/' + API_VERSION + '/pods/',
328 method: 'POST' as 'POST',
330 host: CONFIG.WEBSERVER.HOST,
331 email: CONFIG.ADMIN.EMAIL,
336 return makeRetryRequest(params)
337 .then(({ response, body }) => {
338 body = body as { cert: string, email: string }
340 if (response.statusCode === 200) {
341 const podObj = db.Pod.build({ host: pod.host, publicKey: body.cert, email: body.email })
343 .then(podCreated => {
345 // Add our videos to the request scheduler
346 sendOwnedVideosToPod(podCreated.id)
349 logger.error('Cannot add friend %s pod.', pod.host, { error: err })
352 logger.error('Status not 200 for %s pod.', pod.host)
356 logger.error('Error with adding %s pod.', pod.host, { error: err.stack })
357 // Don't break the process
359 }, { concurrency: REQUESTS_IN_PARALLEL })
360 .then(() => logger.debug('makeRequestsToWinningPods finished.'))
362 // Final callback, we've ended all the requests
363 // Now we made new friends, we can re activate the pool of requests
364 requestScheduler.activate()
368 // Wrapper that populate "toIds" argument with all our friends if it is not specified
369 type CreateRequestOptions = {
371 endpoint: RequestEndpoint
374 transaction: Sequelize.Transaction
376 function createRequest (options: CreateRequestOptions) {
377 if (options.toIds !== undefined) return requestScheduler.createRequest(options as RequestSchedulerOptions)
379 // If the "toIds" pods is not specified, we send the request to all our friends
380 return db.Pod.listAllIds(options.transaction).then(podIds => {
381 const newOptions = Object.assign(options, { toIds: podIds })
382 return requestScheduler.createRequest(newOptions)
386 function createVideoQaduRequest (options: RequestVideoQaduSchedulerOptions) {
387 return requestVideoQaduScheduler.createRequest(options)
390 function createVideoEventRequest (options: RequestVideoEventSchedulerOptions) {
391 return requestVideoEventScheduler.createRequest(options)
394 function isMe (host: string) {
395 return host === CONFIG.WEBSERVER.HOST