1 import * as url from 'url'
3 import { database as db } from '../initializers'
4 import { logger } from './logger'
5 import { doRequest } from './requests'
6 import { isRemoteAccountValid } from './custom-validators'
7 import { ActivityPubActor } from '../../shared/models/activitypub/activitypub-actor'
8 import { ResultList } from '../../shared/models/result-list.model'
10 async function fetchRemoteAccountAndCreatePod (accountUrl: string) {
18 requestResult = await doRequest(options)
20 logger.warning('Cannot fetch remote account %s.', accountUrl, err)
24 const accountJSON: ActivityPubActor = requestResult.body
25 if (isRemoteAccountValid(accountJSON) === false) return undefined
27 const followersCount = await fetchAccountCount(accountJSON.followers)
28 const followingCount = await fetchAccountCount(accountJSON.following)
30 const account = db.Account.build({
31 uuid: accountJSON.uuid,
32 name: accountJSON.preferredUsername,
34 publicKey: accountJSON.publicKey.publicKeyPem,
36 followersCount: followersCount,
37 followingCount: followingCount,
38 inboxUrl: accountJSON.inbox,
39 outboxUrl: accountJSON.outbox,
40 sharedInboxUrl: accountJSON.endpoints.sharedInbox,
41 followersUrl: accountJSON.followers,
42 followingUrl: accountJSON.following
45 const accountHost = url.parse(account.url).host
54 const pod = await db.Pod.findOrCreate(podOptions)
56 return { account, pod }
59 function activityPubContextify (data: object) {
60 return Object.assign(data,{
62 'https://www.w3.org/ns/activitystreams',
63 'https://w3id.org/security/v1',
65 'Hashtag': 'as:Hashtag',
66 'uuid': 'http://schema.org/identifier',
67 'category': 'http://schema.org/category',
68 'licence': 'http://schema.org/license',
69 'nsfw': 'as:sensitive',
70 'language': 'http://schema.org/inLanguage',
71 'views': 'http://schema.org/Number',
72 'size': 'http://schema.org/Number'
78 function activityPubCollectionPagination (url: string, page: number, result: ResultList<any>) {
79 const baseUrl = url.split('?').shift
84 totalItems: result.total,
86 id: baseUrl + '?page=' + page,
87 type: 'CollectionPage',
88 totalItems: result.total,
89 next: baseUrl + '?page=' + (page + 1),
95 return activityPubContextify(obj)
98 // ---------------------------------------------------------------------------
101 fetchRemoteAccountAndCreatePod,
102 activityPubContextify,
103 activityPubCollectionPagination
106 // ---------------------------------------------------------------------------
108 async function fetchAccountCount (url: string) {
116 requestResult = await doRequest(options)
118 logger.warning('Cannot fetch remote account count %s.', url, err)
122 return requestResult.totalItems ? requestResult.totalItems : 0