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,
38 RemoteVideoCreateData,
39 RemoteVideoUpdateData,
40 RemoteVideoRemoveData,
41 RemoteVideoReportAbuseData
44 type QaduParam = { videoId: string, type: RequestVideoQaduType }
45 type EventParam = { videoId: string, type: RequestVideoEventType }
47 const ENDPOINT_ACTIONS = REQUEST_ENDPOINT_ACTIONS[REQUEST_ENDPOINTS.VIDEOS]
49 const requestScheduler = new RequestScheduler()
50 const requestVideoQaduScheduler = new RequestVideoQaduScheduler()
51 const requestVideoEventScheduler = new RequestVideoEventScheduler()
53 function activateSchedulers () {
54 requestScheduler.activate()
55 requestVideoQaduScheduler.activate()
56 requestVideoEventScheduler.activate()
59 function addVideoToFriends (videoData: RemoteVideoCreateData, transaction: Sequelize.Transaction) {
61 type: ENDPOINT_ACTIONS.ADD,
62 endpoint: REQUEST_ENDPOINTS.VIDEOS,
66 return createRequest(options)
69 function updateVideoToFriends (videoData: RemoteVideoUpdateData, transaction: Sequelize.Transaction) {
71 type: ENDPOINT_ACTIONS.UPDATE,
72 endpoint: REQUEST_ENDPOINTS.VIDEOS,
76 return createRequest(options)
79 function removeVideoToFriends (videoParams: RemoteVideoRemoveData) {
81 type: ENDPOINT_ACTIONS.REMOVE,
82 endpoint: REQUEST_ENDPOINTS.VIDEOS,
86 return createRequest(options)
89 function reportAbuseVideoToFriend (reportData: RemoteVideoReportAbuseData, video: VideoInstance, transaction: Sequelize.Transaction) {
91 type: ENDPOINT_ACTIONS.REPORT_ABUSE,
92 endpoint: REQUEST_ENDPOINTS.VIDEOS,
94 toIds: [ video.Author.podId ],
97 return createRequest(options)
100 function quickAndDirtyUpdateVideoToFriends (qaduParam: QaduParam, transaction?: Sequelize.Transaction) {
102 videoId: qaduParam.videoId,
103 type: qaduParam.type,
106 return createVideoQaduRequest(options)
109 function quickAndDirtyUpdatesVideoToFriends (qadusParams: QaduParam[], transaction: Sequelize.Transaction) {
112 qadusParams.forEach(function (qaduParams) {
113 tasks.push(quickAndDirtyUpdateVideoToFriends(qaduParams, transaction))
116 return Promise.all(tasks)
119 function addEventToRemoteVideo (eventParam: EventParam, transaction?: Sequelize.Transaction) {
121 videoId: eventParam.videoId,
122 type: eventParam.type,
125 return createVideoEventRequest(options)
128 function addEventsToRemoteVideo (eventsParams: EventParam[], transaction: Sequelize.Transaction) {
131 eventsParams.forEach(function (eventParams) {
132 tasks.push(addEventToRemoteVideo(eventParams, transaction))
135 return Promise.all(tasks)
138 function hasFriends () {
139 return db.Pod.countAll().then(count => count !== 0)
142 function makeFriends (hosts: string[]) {
145 logger.info('Make friends!')
146 return getMyPublicCert()
148 return Promise.each(hosts, host => computeForeignPodsList(host, podsScore)).then(() => cert)
151 logger.debug('Pods scores computed.', { podsScore: podsScore })
152 const podsList = computeWinningPods(hosts, podsScore)
153 logger.debug('Pods that we keep.', { podsToKeep: podsList })
155 return makeRequestsToWinningPods(cert, podsList)
159 function quitFriends () {
160 // Stop pool requests
161 requestScheduler.deactivate()
163 return requestScheduler.flush()
165 return requestVideoQaduScheduler.flush()
171 const requestParams = {
172 method: 'POST' as 'POST',
173 path: '/api/' + API_VERSION + '/remote/pods/remove',
177 // Announce we quit them
178 // We don't care if the request fails
179 // The other pod will exclude us automatically after a while
180 return Promise.map(pods, pod => {
181 requestParams.toPod = pod
183 return makeSecureRequest(requestParams)
184 }, { concurrency: REQUESTS_IN_PARALLEL })
187 logger.error('Some errors while quitting friends.', err)
188 // Don't stop the process
193 pods.forEach(pod => tasks.push(pod.destroy()))
195 return Promise.all(pods)
198 logger.info('Removed all remote videos.')
199 // Don't forget to re activate the scheduler, even if there was an error
200 return requestScheduler.activate()
202 .finally(() => requestScheduler.activate())
205 function sendOwnedVideosToPod (podId: number) {
206 db.Video.listOwnedAndPopulateAuthorAndTags()
207 .then(videosList => {
209 videosList.forEach(video => {
210 const promise = video.toAddRemoteJSON()
211 .then(remoteVideo => {
214 endpoint: REQUEST_ENDPOINTS.VIDEOS,
219 return createRequest(options)
222 logger.error('Cannot convert video to remote.', err)
223 // Don't break the process
230 return Promise.all(tasks)
234 function getRequestScheduler () {
235 return requestScheduler
238 function getRequestVideoQaduScheduler () {
239 return requestVideoQaduScheduler
242 function getRequestVideoEventScheduler () {
243 return requestVideoEventScheduler
246 // ---------------------------------------------------------------------------
251 updateVideoToFriends,
252 reportAbuseVideoToFriend,
253 quickAndDirtyUpdateVideoToFriends,
254 quickAndDirtyUpdatesVideoToFriends,
255 addEventToRemoteVideo,
256 addEventsToRemoteVideo,
260 removeVideoToFriends,
261 sendOwnedVideosToPod,
263 getRequestVideoQaduScheduler,
264 getRequestVideoEventScheduler
267 // ---------------------------------------------------------------------------
269 function computeForeignPodsList (host: string, podsScore: { [ host: string ]: number }) {
271 return getForeignPodsList(host).then((res: any) => {
272 const foreignPodsList = res.data
274 // Let's give 1 point to the pod we ask the friends list
275 foreignPodsList.push({ host })
277 foreignPodsList.forEach(foreignPod => {
278 const foreignPodHost = foreignPod.host
280 if (podsScore[foreignPodHost]) podsScore[foreignPodHost]++
281 else podsScore[foreignPodHost] = 1
288 function computeWinningPods (hosts: string[], podsScore: { [ host: string ]: number }) {
289 // Build the list of pods to add
290 // Only add a pod if it exists in more than a half base pods
292 const baseScore = hosts.length / 2
294 Object.keys(podsScore).forEach(podHost => {
295 // If the pod is not me and with a good score we add it
296 if (isMe(podHost) === false && podsScore[podHost] > baseScore) {
297 podsList.push({ host: podHost })
304 function getForeignPodsList (host: string) {
305 return new Promise((res, rej) => {
306 const path = '/api/' + API_VERSION + '/pods'
308 request.get(REMOTE_SCHEME.HTTP + '://' + host + path, function (err, response, body) {
309 if (err) return rej(err)
312 const json = JSON.parse(body)
321 function makeRequestsToWinningPods (cert: string, podsList: PodInstance[]) {
322 // Stop pool requests
323 requestScheduler.deactivate()
324 // Flush pool requests
325 requestScheduler.forceSend()
327 return Promise.map(podsList, pod => {
329 url: REMOTE_SCHEME.HTTP + '://' + pod.host + '/api/' + API_VERSION + '/pods/',
330 method: 'POST' as 'POST',
332 host: CONFIG.WEBSERVER.HOST,
333 email: CONFIG.ADMIN.EMAIL,
338 return makeRetryRequest(params)
339 .then(({ response, body }) => {
340 body = body as { cert: string, email: string }
342 if (response.statusCode === 200) {
343 const podObj = db.Pod.build({ host: pod.host, publicKey: body.cert, email: body.email })
345 .then(podCreated => {
347 // Add our videos to the request scheduler
348 sendOwnedVideosToPod(podCreated.id)
351 logger.error('Cannot add friend %s pod.', pod.host, err)
354 logger.error('Status not 200 for %s pod.', pod.host)
358 logger.error('Error with adding %s pod.', pod.host, { error: err.stack })
359 // Don't break the process
361 }, { concurrency: REQUESTS_IN_PARALLEL })
362 .then(() => logger.debug('makeRequestsToWinningPods finished.'))
364 // Final callback, we've ended all the requests
365 // Now we made new friends, we can re activate the pool of requests
366 requestScheduler.activate()
370 // Wrapper that populate "toIds" argument with all our friends if it is not specified
371 type CreateRequestOptions = {
373 endpoint: RequestEndpoint
376 transaction: Sequelize.Transaction
378 function createRequest (options: CreateRequestOptions) {
379 if (options.toIds !== undefined) return requestScheduler.createRequest(options as RequestSchedulerOptions)
381 // If the "toIds" pods is not specified, we send the request to all our friends
382 return db.Pod.listAllIds(options.transaction).then(podIds => {
383 const newOptions = Object.assign(options, { toIds: podIds })
384 return requestScheduler.createRequest(newOptions)
388 function createVideoQaduRequest (options: RequestVideoQaduSchedulerOptions) {
389 return requestVideoQaduScheduler.createRequest(options)
392 function createVideoEventRequest (options: RequestVideoEventSchedulerOptions) {
393 return requestVideoEventScheduler.createRequest(options)
396 function isMe (host: string) {
397 return host === CONFIG.WEBSERVER.HOST