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) {
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
197 pods.forEach(pod => tasks.push(pod.destroy()))
199 return Promise.all(pods)
202 logger.info('Removed all remote videos.')
203 // Don't forget to re activate the scheduler, even if there was an error
204 return requestScheduler.activate()
206 .finally(() => requestScheduler.activate())
209 function sendOwnedVideosToPod (podId: number) {
210 db.Video.listOwnedAndPopulateAuthorAndTags()
211 .then(videosList => {
213 videosList.forEach(video => {
214 const promise = video.toAddRemoteJSON()
215 .then(remoteVideo => {
218 endpoint: REQUEST_ENDPOINTS.VIDEOS,
223 return createRequest(options)
226 logger.error('Cannot convert video to remote.', err)
227 // Don't break the process
234 return Promise.all(tasks)
238 function fetchRemotePreview (pod: PodInstance, video: VideoInstance) {
239 const host = video.Author.Pod.host
240 const path = join(STATIC_PATHS.PREVIEWS, video.getPreviewName())
242 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path)
245 function removeFriend (pod: PodInstance) {
246 const requestParams = {
247 method: 'POST' as 'POST',
248 path: '/api/' + API_VERSION + '/remote/pods/remove',
252 return makeSecureRequest(requestParams)
253 .then(() => pod.destroy())
255 logger.info('Removed friend.')
258 logger.error('Some errors while quitting friend %s (id: %d).', pod.host, pod.id, err)
262 function getRequestScheduler () {
263 return requestScheduler
266 function getRequestVideoQaduScheduler () {
267 return requestVideoQaduScheduler
270 function getRequestVideoEventScheduler () {
271 return requestVideoEventScheduler
274 // ---------------------------------------------------------------------------
279 updateVideoToFriends,
280 reportAbuseVideoToFriend,
281 quickAndDirtyUpdateVideoToFriends,
282 quickAndDirtyUpdatesVideoToFriends,
283 addEventToRemoteVideo,
284 addEventsToRemoteVideo,
289 removeVideoToFriends,
290 sendOwnedVideosToPod,
292 getRequestVideoQaduScheduler,
293 getRequestVideoEventScheduler,
297 // ---------------------------------------------------------------------------
299 function computeForeignPodsList (host: string, podsScore: { [ host: string ]: number }) {
301 return getForeignPodsList(host).then(res => {
302 const foreignPodsList: { host: string }[] = res.data
304 // Let's give 1 point to the pod we ask the friends list
305 foreignPodsList.push({ host })
307 foreignPodsList.forEach(foreignPod => {
308 const foreignPodHost = foreignPod.host
310 if (podsScore[foreignPodHost]) podsScore[foreignPodHost]++
311 else podsScore[foreignPodHost] = 1
318 function computeWinningPods (hosts: string[], podsScore: { [ host: string ]: number }) {
319 // Build the list of pods to add
320 // Only add a pod if it exists in more than a half base pods
322 const baseScore = hosts.length / 2
324 Object.keys(podsScore).forEach(podHost => {
325 // If the pod is not me and with a good score we add it
326 if (isMe(podHost) === false && podsScore[podHost] > baseScore) {
327 podsList.push({ host: podHost })
334 function getForeignPodsList (host: string) {
335 return new Promise< ResultList<FormattedPod> >((res, rej) => {
336 const path = '/api/' + API_VERSION + '/pods'
338 request.get(REMOTE_SCHEME.HTTP + '://' + host + path, (err, response, body) => {
339 if (err) return rej(err)
342 const json = JSON.parse(body)
351 function makeRequestsToWinningPods (cert: string, podsList: PodInstance[]) {
352 // Stop pool requests
353 requestScheduler.deactivate()
354 // Flush pool requests
355 requestScheduler.forceSend()
357 return Promise.map(podsList, pod => {
359 url: REMOTE_SCHEME.HTTP + '://' + pod.host + '/api/' + API_VERSION + '/pods/',
360 method: 'POST' as 'POST',
362 host: CONFIG.WEBSERVER.HOST,
363 email: CONFIG.ADMIN.EMAIL,
368 return makeRetryRequest(params)
369 .then(({ response, body }) => {
370 body = body as { cert: string, email: string }
372 if (response.statusCode === 200) {
373 const podObj = db.Pod.build({ host: pod.host, publicKey: body.cert, email: body.email })
375 .then(podCreated => {
377 // Add our videos to the request scheduler
378 sendOwnedVideosToPod(podCreated.id)
381 logger.error('Cannot add friend %s pod.', pod.host, err)
384 logger.error('Status not 200 for %s pod.', pod.host)
388 logger.error('Error with adding %s pod.', pod.host, { error: err.stack })
389 // Don't break the process
391 }, { concurrency: REQUESTS_IN_PARALLEL })
392 .then(() => logger.debug('makeRequestsToWinningPods finished.'))
394 // Final callback, we've ended all the requests
395 // Now we made new friends, we can re activate the pool of requests
396 requestScheduler.activate()
400 // Wrapper that populate "toIds" argument with all our friends if it is not specified
401 type CreateRequestOptions = {
403 endpoint: RequestEndpoint
406 transaction: Sequelize.Transaction
408 function createRequest (options: CreateRequestOptions) {
409 if (options.toIds !== undefined) return requestScheduler.createRequest(options as RequestSchedulerOptions)
411 // If the "toIds" pods is not specified, we send the request to all our friends
412 return db.Pod.listAllIds(options.transaction).then(podIds => {
413 const newOptions = Object.assign(options, { toIds: podIds })
414 return requestScheduler.createRequest(newOptions)
418 function createVideoQaduRequest (options: RequestVideoQaduSchedulerOptions) {
419 return requestVideoQaduScheduler.createRequest(options)
422 function createVideoEventRequest (options: RequestVideoEventSchedulerOptions) {
423 return requestVideoEventScheduler.createRequest(options)
426 function isMe (host: string) {
427 return host === CONFIG.WEBSERVER.HOST