]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/crawl.ts
Merge branch 'release/5.1.0' into develop
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / crawl.ts
1 import Bluebird from 'bluebird'
2 import { URL } from 'url'
3 import { retryTransactionWrapper } from '@server/helpers/database-utils'
4 import { ActivityPubOrderedCollection } from '../../../shared/models/activitypub'
5 import { logger } from '../../helpers/logger'
6 import { doJSONRequest } from '../../helpers/requests'
7 import { ACTIVITY_PUB, WEBSERVER } from '../../initializers/constants'
8
9 type HandlerFunction<T> = (items: T[]) => (Promise<any> | Bluebird<any>)
10 type CleanerFunction = (startedDate: Date) => Promise<any>
11
12 async function crawlCollectionPage <T> (argUrl: string, handler: HandlerFunction<T>, cleaner?: CleanerFunction) {
13 let url = argUrl
14
15 logger.info('Crawling ActivityPub data on %s.', url)
16
17 const options = { activityPub: true }
18
19 const startDate = new Date()
20
21 const response = await doJSONRequest<ActivityPubOrderedCollection<T>>(url, options)
22 const firstBody = response.body
23
24 const limit = ACTIVITY_PUB.FETCH_PAGE_LIMIT
25 let i = 0
26 let nextLink = firstBody.first
27 while (nextLink && i < limit) {
28 let body: any
29
30 if (typeof nextLink === 'string') {
31 // Don't crawl ourselves
32 const remoteHost = new URL(nextLink).host
33 if (remoteHost === WEBSERVER.HOST) continue
34
35 url = nextLink
36
37 const res = await doJSONRequest<ActivityPubOrderedCollection<T>>(url, options)
38 body = res.body
39 } else {
40 // nextLink is already the object we want
41 body = nextLink
42 }
43
44 nextLink = body.next
45 i++
46
47 if (Array.isArray(body.orderedItems)) {
48 const items = body.orderedItems
49 logger.info('Processing %i ActivityPub items for %s.', items.length, url)
50
51 await handler(items)
52 }
53 }
54
55 if (cleaner) await retryTransactionWrapper(cleaner, startDate)
56 }
57
58 export {
59 crawlCollectionPage
60 }