]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/lib/activitypub/crawl.ts
Try to fix weird CI test crashes
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / crawl.ts
... / ...
CommitLineData
1import { retryTransactionWrapper } from '@server/helpers/database-utils'
2import * as Bluebird from 'bluebird'
3import { URL } from 'url'
4import { ActivityPubOrderedCollection } from '../../../shared/models/activitypub'
5import { logger } from '../../helpers/logger'
6import { doJSONRequest } from '../../helpers/requests'
7import { ACTIVITY_PUB, WEBSERVER } from '../../initializers/constants'
8
9type HandlerFunction<T> = (items: T[]) => (Promise<any> | Bluebird<any>)
10type CleanerFunction = (startedDate: Date) => (Promise<any> | Bluebird<any>)
11
12async 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
58export {
59 crawlCollectionPage
60}