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