1 import * as url from 'url'
2 import { ActivityPubActor } from '../../../shared/models/activitypub/activitypub-actor'
3 import { isRemoteAccountValid } from '../../helpers/custom-validators/activitypub/account'
4 import { logger } from '../../helpers/logger'
5 import { doRequest } from '../../helpers/requests'
6 import { ACTIVITY_PUB } from '../../initializers/constants'
7 import { database as db } from '../../initializers/database'
9 async function getOrCreateAccount (accountUrl: string) {
10 let account = await db.Account.loadByUrl(accountUrl)
12 // We don't have this account in our database, fetch it on remote
14 const res = await fetchRemoteAccountAndCreateServer(accountUrl)
15 if (res === undefined) throw new Error('Cannot fetch remote account.')
17 // Save our new account in database
18 account = await res.account.save()
24 async function fetchRemoteAccountAndCreateServer (accountUrl: string) {
29 'Accept': ACTIVITY_PUB.ACCEPT_HEADER
33 logger.info('Fetching remote account %s.', accountUrl)
37 requestResult = await doRequest(options)
39 logger.warn('Cannot fetch remote account %s.', accountUrl, err)
43 const accountJSON: ActivityPubActor = JSON.parse(requestResult.body)
44 if (isRemoteAccountValid(accountJSON) === false) {
45 logger.debug('Remote account JSON is not valid.', { accountJSON })
49 const followersCount = await fetchAccountCount(accountJSON.followers)
50 const followingCount = await fetchAccountCount(accountJSON.following)
52 const account = db.Account.build({
53 uuid: accountJSON.uuid,
54 name: accountJSON.preferredUsername,
56 publicKey: accountJSON.publicKey.publicKeyPem,
58 followersCount: followersCount,
59 followingCount: followingCount,
60 inboxUrl: accountJSON.inbox,
61 outboxUrl: accountJSON.outbox,
62 sharedInboxUrl: accountJSON.endpoints.sharedInbox,
63 followersUrl: accountJSON.followers,
64 followingUrl: accountJSON.following
67 const accountHost = url.parse(account.url).host
68 const serverOptions = {
76 const [ server ] = await db.Server.findOrCreate(serverOptions)
77 account.set('serverId', server.id)
79 return { account, server }
84 fetchRemoteAccountAndCreateServer
87 // ---------------------------------------------------------------------------
89 async function fetchAccountCount (url: string) {
97 requestResult = await doRequest(options)
99 logger.warn('Cannot fetch remote account count %s.', url, err)
103 return requestResult.totalItems ? requestResult.totalItems : 0