1 import * as request from 'request'
2 import * as Sequelize from 'sequelize'
3 import * as Promise from 'bluebird'
4 import { join } from 'path'
6 import { database as db } from '../initializers/database'
12 REQUEST_ENDPOINT_ACTIONS,
15 } from '../initializers'
24 RequestSchedulerOptions,
26 RequestVideoQaduScheduler,
27 RequestVideoQaduSchedulerOptions,
29 RequestVideoEventScheduler,
30 RequestVideoEventSchedulerOptions
38 RequestVideoEventType,
40 RemoteVideoCreateData,
41 RemoteVideoUpdateData,
42 RemoteVideoRemoveData,
43 RemoteVideoReportAbuseData,
48 type QaduParam = { videoId: number, type: RequestVideoQaduType }
49 type EventParam = { videoId: number, type: RequestVideoEventType }
51 const ENDPOINT_ACTIONS = REQUEST_ENDPOINT_ACTIONS[REQUEST_ENDPOINTS.VIDEOS]
53 const requestScheduler = new RequestScheduler()
54 const requestVideoQaduScheduler = new RequestVideoQaduScheduler()
55 const requestVideoEventScheduler = new RequestVideoEventScheduler()
57 function activateSchedulers () {
58 requestScheduler.activate()
59 requestVideoQaduScheduler.activate()
60 requestVideoEventScheduler.activate()
63 function addVideoToFriends (videoData: RemoteVideoCreateData, transaction: Sequelize.Transaction) {
65 type: ENDPOINT_ACTIONS.ADD,
66 endpoint: REQUEST_ENDPOINTS.VIDEOS,
70 return createRequest(options)
73 function updateVideoToFriends (videoData: RemoteVideoUpdateData, transaction: Sequelize.Transaction) {
75 type: ENDPOINT_ACTIONS.UPDATE,
76 endpoint: REQUEST_ENDPOINTS.VIDEOS,
80 return createRequest(options)
83 function removeVideoToFriends (videoParams: RemoteVideoRemoveData, transaction: Sequelize.Transaction) {
85 type: ENDPOINT_ACTIONS.REMOVE,
86 endpoint: REQUEST_ENDPOINTS.VIDEOS,
90 return createRequest(options)
93 function reportAbuseVideoToFriend (reportData: RemoteVideoReportAbuseData, video: VideoInstance, transaction: Sequelize.Transaction) {
95 type: ENDPOINT_ACTIONS.REPORT_ABUSE,
96 endpoint: REQUEST_ENDPOINTS.VIDEOS,
98 toIds: [ video.Author.podId ],
101 return createRequest(options)
104 function quickAndDirtyUpdateVideoToFriends (qaduParam: QaduParam, transaction?: Sequelize.Transaction) {
106 videoId: qaduParam.videoId,
107 type: qaduParam.type,
110 return createVideoQaduRequest(options)
113 function quickAndDirtyUpdatesVideoToFriends (qadusParams: QaduParam[], transaction: Sequelize.Transaction) {
116 qadusParams.forEach(qaduParams => {
117 tasks.push(quickAndDirtyUpdateVideoToFriends(qaduParams, transaction))
120 return Promise.all(tasks)
123 function addEventToRemoteVideo (eventParam: EventParam, transaction?: Sequelize.Transaction) {
125 videoId: eventParam.videoId,
126 type: eventParam.type,
129 return createVideoEventRequest(options)
132 function addEventsToRemoteVideo (eventsParams: EventParam[], transaction: Sequelize.Transaction) {
135 eventsParams.forEach(eventParams => {
136 tasks.push(addEventToRemoteVideo(eventParams, transaction))
139 return Promise.all(tasks)
142 function hasFriends () {
143 return db.Pod.countAll().then(count => count !== 0)
146 function makeFriends (hosts: string[]) {
149 logger.info('Make friends!')
150 return getMyPublicCert()
152 return Promise.each(hosts, host => computeForeignPodsList(host, podsScore)).then(() => cert)
155 logger.debug('Pods scores computed.', { podsScore: podsScore })
156 const podsList = computeWinningPods(hosts, podsScore)
157 logger.debug('Pods that we keep.', { podsToKeep: podsList })
159 return makeRequestsToWinningPods(cert, podsList)
163 function quitFriends () {
164 // Stop pool requests
165 requestScheduler.deactivate()
167 return requestScheduler.flush()
169 return requestVideoQaduScheduler.flush()
175 const requestParams = {
176 method: 'POST' as 'POST',
177 path: '/api/' + API_VERSION + '/remote/pods/remove',
181 // Announce we quit them
182 // We don't care if the request fails
183 // The other pod will exclude us automatically after a while
184 return Promise.map(pods, pod => {
185 requestParams.toPod = pod
187 return makeSecureRequest(requestParams)
188 }, { concurrency: REQUESTS_IN_PARALLEL })
191 logger.error('Some errors while quitting friends.', err)
192 // Don't stop the process
198 pods.forEach(pod => tasks.push(pod.destroy()))
200 return Promise.all(pods)
203 logger.info('Removed all remote videos.')
204 // Don't forget to re activate the scheduler, even if there was an error
205 return requestScheduler.activate()
207 .finally(() => requestScheduler.activate())
210 function sendOwnedVideosToPod (podId: number) {
211 db.Video.listOwnedAndPopulateAuthorAndTags()
212 .then(videosList => {
214 videosList.forEach(video => {
215 const promise = video.toAddRemoteJSON()
216 .then(remoteVideo => {
219 endpoint: REQUEST_ENDPOINTS.VIDEOS,
224 return createRequest(options)
227 logger.error('Cannot convert video to remote.', err)
228 // Don't break the process
235 return Promise.all(tasks)
239 function fetchRemotePreview (pod: PodInstance, video: VideoInstance) {
240 const host = video.Author.Pod.host
241 const path = join(STATIC_PATHS.PREVIEWS, video.getPreviewName())
243 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path)
246 function removeFriend (pod: PodInstance) {
247 const requestParams = {
248 method: 'POST' as 'POST',
249 path: '/api/' + API_VERSION + '/remote/pods/remove',
253 return makeSecureRequest(requestParams)
254 .then(() => pod.destroy())
256 logger.info('Removed friend.')
259 logger.error('Some errors while quitting friend %s (id: %d).', pod.host, pod.id, err)
263 function getRequestScheduler () {
264 return requestScheduler
267 function getRequestVideoQaduScheduler () {
268 return requestVideoQaduScheduler
271 function getRequestVideoEventScheduler () {
272 return requestVideoEventScheduler
275 // ---------------------------------------------------------------------------
280 updateVideoToFriends,
281 reportAbuseVideoToFriend,
282 quickAndDirtyUpdateVideoToFriends,
283 quickAndDirtyUpdatesVideoToFriends,
284 addEventToRemoteVideo,
285 addEventsToRemoteVideo,
290 removeVideoToFriends,
291 sendOwnedVideosToPod,
293 getRequestVideoQaduScheduler,
294 getRequestVideoEventScheduler,
298 // ---------------------------------------------------------------------------
300 function computeForeignPodsList (host: string, podsScore: { [ host: string ]: number }) {
302 return getForeignPodsList(host).then(res => {
303 const foreignPodsList: { host: string }[] = res.data
305 // Let's give 1 point to the pod we ask the friends list
306 foreignPodsList.push({ host })
308 foreignPodsList.forEach(foreignPod => {
309 const foreignPodHost = foreignPod.host
311 if (podsScore[foreignPodHost]) podsScore[foreignPodHost]++
312 else podsScore[foreignPodHost] = 1
319 function computeWinningPods (hosts: string[], podsScore: { [ host: string ]: number }) {
320 // Build the list of pods to add
321 // Only add a pod if it exists in more than a half base pods
323 const baseScore = hosts.length / 2
325 Object.keys(podsScore).forEach(podHost => {
326 // If the pod is not me and with a good score we add it
327 if (isMe(podHost) === false && podsScore[podHost] > baseScore) {
328 podsList.push({ host: podHost })
335 function getForeignPodsList (host: string) {
336 return new Promise< ResultList<FormattedPod> >((res, rej) => {
337 const path = '/api/' + API_VERSION + '/pods'
339 request.get(REMOTE_SCHEME.HTTP + '://' + host + path, (err, response, body) => {
340 if (err) return rej(err)
343 const json = JSON.parse(body)
352 function makeRequestsToWinningPods (cert: string, podsList: PodInstance[]) {
353 // Stop pool requests
354 requestScheduler.deactivate()
355 // Flush pool requests
356 requestScheduler.forceSend()
358 return Promise.map(podsList, pod => {
360 url: REMOTE_SCHEME.HTTP + '://' + pod.host + '/api/' + API_VERSION + '/pods/',
361 method: 'POST' as 'POST',
363 host: CONFIG.WEBSERVER.HOST,
364 email: CONFIG.ADMIN.EMAIL,
369 return makeRetryRequest(params)
370 .then(({ response, body }) => {
371 body = body as { cert: string, email: string }
373 if (response.statusCode === 200) {
374 const podObj = db.Pod.build({ host: pod.host, publicKey: body.cert, email: body.email })
376 .then(podCreated => {
378 // Add our videos to the request scheduler
379 sendOwnedVideosToPod(podCreated.id)
382 logger.error('Cannot add friend %s pod.', pod.host, err)
385 logger.error('Status not 200 for %s pod.', pod.host)
389 logger.error('Error with adding %s pod.', pod.host, { error: err.stack })
390 // Don't break the process
392 }, { concurrency: REQUESTS_IN_PARALLEL })
393 .then(() => logger.debug('makeRequestsToWinningPods finished.'))
395 // Final callback, we've ended all the requests
396 // Now we made new friends, we can re activate the pool of requests
397 requestScheduler.activate()
401 // Wrapper that populate "toIds" argument with all our friends if it is not specified
402 type CreateRequestOptions = {
404 endpoint: RequestEndpoint
407 transaction: Sequelize.Transaction
409 function createRequest (options: CreateRequestOptions) {
410 if (options.toIds !== undefined) return requestScheduler.createRequest(options as RequestSchedulerOptions)
412 // If the "toIds" pods is not specified, we send the request to all our friends
413 return db.Pod.listAllIds(options.transaction).then(podIds => {
414 const newOptions = Object.assign(options, { toIds: podIds })
415 return requestScheduler.createRequest(newOptions)
419 function createVideoQaduRequest (options: RequestVideoQaduSchedulerOptions) {
420 return requestVideoQaduScheduler.createRequest(options)
423 function createVideoEventRequest (options: RequestVideoEventSchedulerOptions) {
424 return requestVideoEventScheduler.createRequest(options)
427 function isMe (host: string) {
428 return host === CONFIG.WEBSERVER.HOST