524aadc27af33365d26d4225323bbcdbd573ce9b
[oweals/peertube.git] / server / lib / job-queue / handlers / activitypub-http-fetcher.ts
1 import * as Bull from 'bull'
2 import * as Bluebird from 'bluebird'
3 import { logger } from '../../../helpers/logger'
4 import { processActivities } from '../../activitypub/process'
5 import { addVideoComments } from '../../activitypub/video-comments'
6 import { crawlCollectionPage } from '../../activitypub/crawl'
7 import { VideoModel } from '../../../models/video/video'
8 import { addVideoShares } from '../../activitypub/share'
9 import { createRates } from '../../activitypub/video-rates'
10 import { createAccountPlaylists } from '../../activitypub/playlist'
11 import { AccountModel } from '../../../models/account/account'
12 import { AccountVideoRateModel } from '../../../models/account/account-video-rate'
13 import { VideoShareModel } from '../../../models/video/video-share'
14 import { VideoCommentModel } from '../../../models/video/video-comment'
15 import { MAccountDefault, MVideoFullLight } from '../../../typings/models'
16 import { ActivitypubHttpFetcherPayload, FetchType } from '@shared/models'
17
18 async function processActivityPubHttpFetcher (job: Bull.Job) {
19   logger.info('Processing ActivityPub fetcher in job %d.', job.id)
20
21   const payload = job.data as ActivitypubHttpFetcherPayload
22
23   let video: MVideoFullLight
24   if (payload.videoId) video = await VideoModel.loadAndPopulateAccountAndServerAndTags(payload.videoId)
25
26   let account: MAccountDefault
27   if (payload.accountId) account = await AccountModel.load(payload.accountId)
28
29   const fetcherType: { [ id in FetchType ]: (items: any[]) => Promise<any> } = {
30     'activity': items => processActivities(items, { outboxUrl: payload.uri, fromFetch: true }),
31     'video-likes': items => createRates(items, video, 'like'),
32     'video-dislikes': items => createRates(items, video, 'dislike'),
33     'video-shares': items => addVideoShares(items, video),
34     'video-comments': items => addVideoComments(items),
35     'account-playlists': items => createAccountPlaylists(items, account)
36   }
37
38   const cleanerType: { [ id in FetchType ]?: (crawlStartDate: Date) => Bluebird<any> } = {
39     'video-likes': crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'like' as 'like', crawlStartDate),
40     'video-dislikes': crawlStartDate => AccountVideoRateModel.cleanOldRatesOf(video.id, 'dislike' as 'dislike', crawlStartDate),
41     'video-shares': crawlStartDate => VideoShareModel.cleanOldSharesOf(video.id, crawlStartDate),
42     'video-comments': crawlStartDate => VideoCommentModel.cleanOldCommentsOf(video.id, crawlStartDate)
43   }
44
45   return crawlCollectionPage(payload.uri, fetcherType[payload.type], cleanerType[payload.type])
46 }
47
48 // ---------------------------------------------------------------------------
49
50 export {
51   processActivityPubHttpFetcher
52 }