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.each(hosts, host => computeForeignPodsList(host, podsScore)).then(() => cert)
147 logger.debug('Pods scores computed.', { podsScore: podsScore })
148 const podsList = computeWinningPods(hosts, podsScore)
149 logger.debug('Pods that we keep.', { podsToKeep: podsList })
151 return makeRequestsToWinningPods(cert, podsList)
155 function quitFriends () {
156 // Stop pool requests
157 requestScheduler.deactivate()
159 return requestScheduler.flush()
161 return requestVideoQaduScheduler.flush()
167 const requestParams = {
168 method: 'POST' as 'POST',
169 path: '/api/' + API_VERSION + '/remote/pods/remove',
173 // Announce we quit them
174 // We don't care if the request fails
175 // The other pod will exclude us automatically after a while
176 return Promise.map(pods, pod => {
177 requestParams.toPod = pod
179 return makeSecureRequest(requestParams)
180 }, { concurrency: REQUESTS_IN_PARALLEL })
183 logger.error('Some errors while quitting friends.', err)
184 // Don't stop the process
189 pods.forEach(pod => tasks.push(pod.destroy()))
191 return Promise.all(pods)
194 logger.info('Removed all remote videos.')
195 // Don't forget to re activate the scheduler, even if there was an error
196 return requestScheduler.activate()
198 .finally(() => requestScheduler.activate())
201 function sendOwnedVideosToPod (podId: number) {
202 db.Video.listOwnedAndPopulateAuthorAndTags()
203 .then(videosList => {
205 videosList.forEach(video => {
206 const promise = video.toAddRemoteJSON()
207 .then(remoteVideo => {
210 endpoint: REQUEST_ENDPOINTS.VIDEOS,
215 return createRequest(options)
218 logger.error('Cannot convert video to remote.', err)
219 // Don't break the process
226 return Promise.all(tasks)
230 function getRequestScheduler () {
231 return requestScheduler
234 function getRequestVideoQaduScheduler () {
235 return requestVideoQaduScheduler
238 function getRequestVideoEventScheduler () {
239 return requestVideoEventScheduler
242 // ---------------------------------------------------------------------------
247 updateVideoToFriends,
248 reportAbuseVideoToFriend,
249 quickAndDirtyUpdateVideoToFriends,
250 quickAndDirtyUpdatesVideoToFriends,
251 addEventToRemoteVideo,
252 addEventsToRemoteVideo,
256 removeVideoToFriends,
257 sendOwnedVideosToPod,
259 getRequestVideoQaduScheduler,
260 getRequestVideoEventScheduler
263 // ---------------------------------------------------------------------------
265 function computeForeignPodsList (host: string, podsScore: { [ host: string ]: number }) {
267 return getForeignPodsList(host).then((res: any) => {
268 const foreignPodsList = res.data
270 // Let's give 1 point to the pod we ask the friends list
271 foreignPodsList.push({ host })
273 foreignPodsList.forEach(foreignPod => {
274 const foreignPodHost = foreignPod.host
276 if (podsScore[foreignPodHost]) podsScore[foreignPodHost]++
277 else podsScore[foreignPodHost] = 1
284 function computeWinningPods (hosts: string[], podsScore: { [ host: string ]: number }) {
285 // Build the list of pods to add
286 // Only add a pod if it exists in more than a half base pods
288 const baseScore = hosts.length / 2
290 Object.keys(podsScore).forEach(podHost => {
291 // If the pod is not me and with a good score we add it
292 if (isMe(podHost) === false && podsScore[podHost] > baseScore) {
293 podsList.push({ host: podHost })
300 function getForeignPodsList (host: string) {
301 return new Promise((res, rej) => {
302 const path = '/api/' + API_VERSION + '/pods'
304 request.get(REMOTE_SCHEME.HTTP + '://' + host + path, function (err, response, body) {
305 if (err) return rej(err)
308 const json = JSON.parse(body)
317 function makeRequestsToWinningPods (cert: string, podsList: PodInstance[]) {
318 // Stop pool requests
319 requestScheduler.deactivate()
320 // Flush pool requests
321 requestScheduler.forceSend()
323 return Promise.map(podsList, pod => {
325 url: REMOTE_SCHEME.HTTP + '://' + pod.host + '/api/' + API_VERSION + '/pods/',
326 method: 'POST' as 'POST',
328 host: CONFIG.WEBSERVER.HOST,
329 email: CONFIG.ADMIN.EMAIL,
334 return makeRetryRequest(params)
335 .then(({ response, body }) => {
336 body = body as { cert: string, email: string }
338 if (response.statusCode === 200) {
339 const podObj = db.Pod.build({ host: pod.host, publicKey: body.cert, email: body.email })
341 .then(podCreated => {
343 // Add our videos to the request scheduler
344 sendOwnedVideosToPod(podCreated.id)
347 logger.error('Cannot add friend %s pod.', pod.host, err)
350 logger.error('Status not 200 for %s pod.', pod.host)
354 logger.error('Error with adding %s pod.', pod.host, { error: err.stack })
355 // Don't break the process
357 }, { concurrency: REQUESTS_IN_PARALLEL })
358 .then(() => logger.debug('makeRequestsToWinningPods finished.'))
360 // Final callback, we've ended all the requests
361 // Now we made new friends, we can re activate the pool of requests
362 requestScheduler.activate()
366 // Wrapper that populate "toIds" argument with all our friends if it is not specified
367 type CreateRequestOptions = {
369 endpoint: RequestEndpoint
372 transaction: Sequelize.Transaction
374 function createRequest (options: CreateRequestOptions) {
375 if (options.toIds !== undefined) return requestScheduler.createRequest(options as RequestSchedulerOptions)
377 // If the "toIds" pods is not specified, we send the request to all our friends
378 return db.Pod.listAllIds(options.transaction).then(podIds => {
379 const newOptions = Object.assign(options, { toIds: podIds })
380 return requestScheduler.createRequest(newOptions)
384 function createVideoQaduRequest (options: RequestVideoQaduSchedulerOptions) {
385 return requestVideoQaduScheduler.createRequest(options)
388 function createVideoEventRequest (options: RequestVideoEventSchedulerOptions) {
389 return requestVideoEventScheduler.createRequest(options)
392 function isMe (host: string) {
393 return host === CONFIG.WEBSERVER.HOST