1 import * as Bluebird from 'bluebird'
2 import { Op, Transaction } from 'sequelize'
3 import { URL } from 'url'
4 import { v4 as uuidv4 } from 'uuid'
5 import { ActivityPubActor, ActivityPubActorType, ActivityPubOrderedCollection } from '../../../shared/models/activitypub'
6 import { ActivityPubAttributedTo } from '../../../shared/models/activitypub/objects'
7 import { checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
8 import { sanitizeAndCheckActorObject } from '../../helpers/custom-validators/activitypub/actor'
9 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
10 import { retryTransactionWrapper, updateInstanceWithAnother } from '../../helpers/database-utils'
11 import { logger } from '../../helpers/logger'
12 import { createPrivateAndPublicKeys } from '../../helpers/peertube-crypto'
13 import { doRequest } from '../../helpers/requests'
14 import { getUrlFromWebfinger } from '../../helpers/webfinger'
15 import { MIMETYPES, WEBSERVER } from '../../initializers/constants'
16 import { AccountModel } from '../../models/account/account'
17 import { ActorModel } from '../../models/activitypub/actor'
18 import { AvatarModel } from '../../models/avatar/avatar'
19 import { ServerModel } from '../../models/server/server'
20 import { VideoChannelModel } from '../../models/video/video-channel'
21 import { JobQueue } from '../job-queue'
22 import { ActorFetchByUrlType, fetchActorByUrl } from '../../helpers/actor'
23 import { sequelizeTypescript } from '../../initializers/database'
28 MActorAccountChannelId,
29 MActorAccountChannelIdActor,
36 } from '../../types/models'
37 import { extname } from 'path'
38 import { getServerActor } from '@server/models/application/application'
39 import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
41 // Set account keys, this could be long so process after the account creation and do not block the client
42 async function generateAndSaveActorKeys <T extends MActor> (actor: T) {
43 const { publicKey, privateKey } = await createPrivateAndPublicKeys()
45 actor.publicKey = publicKey
46 actor.privateKey = privateKey
51 function getOrCreateActorAndServerAndModel (
52 activityActor: string | ActivityPubActor,
54 recurseIfNeeded?: boolean,
55 updateCollections?: boolean
56 ): Promise<MActorFullActor>
58 function getOrCreateActorAndServerAndModel (
59 activityActor: string | ActivityPubActor,
60 fetchType?: 'association-ids',
61 recurseIfNeeded?: boolean,
62 updateCollections?: boolean
63 ): Promise<MActorAccountChannelId>
65 async function getOrCreateActorAndServerAndModel (
66 activityActor: string | ActivityPubActor,
67 fetchType: ActorFetchByUrlType = 'association-ids',
68 recurseIfNeeded = true,
69 updateCollections = false
70 ): Promise<MActorFullActor | MActorAccountChannelId> {
71 const actorUrl = getAPId(activityActor)
73 let accountPlaylistsUrl: string
75 let actor = await fetchActorByUrl(actorUrl, fetchType)
76 // Orphan actor (not associated to an account of channel) so recreate it
77 if (actor && (!actor.Account && !actor.VideoChannel)) {
82 // We don't have this actor in our database, fetch it on remote
84 const { result } = await fetchRemoteActor(actorUrl)
85 if (result === undefined) throw new Error('Cannot fetch remote actor ' + actorUrl)
87 // Create the attributed to actor
88 // In PeerTube a video channel is owned by an account
89 let ownerActor: MActorFullActor
90 if (recurseIfNeeded === true && result.actor.type === 'Group') {
91 const accountAttributedTo = result.attributedTo.find(a => a.type === 'Person')
92 if (!accountAttributedTo) throw new Error('Cannot find account attributed to video channel ' + actor.url)
94 if (checkUrlsSameHost(accountAttributedTo.id, actorUrl) !== true) {
95 throw new Error(`Account attributed to ${accountAttributedTo.id} does not have the same host than actor url ${actorUrl}`)
99 // Don't recurse another time
100 const recurseIfNeeded = false
101 ownerActor = await getOrCreateActorAndServerAndModel(accountAttributedTo.id, 'all', recurseIfNeeded)
103 logger.error('Cannot get or create account attributed to video channel ' + actorUrl)
108 actor = await retryTransactionWrapper(saveActorAndServerAndModelIfNotExist, result, ownerActor)
110 accountPlaylistsUrl = result.playlists
113 if (actor.Account) (actor as MActorAccountChannelIdActor).Account.Actor = actor
114 if (actor.VideoChannel) (actor as MActorAccountChannelIdActor).VideoChannel.Actor = actor
116 const { actor: actorRefreshed, refreshed } = await retryTransactionWrapper(refreshActorIfNeeded, actor, fetchType)
117 if (!actorRefreshed) throw new Error('Actor ' + actor.url + ' does not exist anymore.')
119 if ((created === true || refreshed === true) && updateCollections === true) {
120 const payload = { uri: actor.outboxUrl, type: 'activity' as 'activity' }
121 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
124 // We created a new account: fetch the playlists
125 if (created === true && actor.Account && accountPlaylistsUrl) {
126 const payload = { uri: accountPlaylistsUrl, accountId: actor.Account.id, type: 'account-playlists' as 'account-playlists' }
127 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
130 return actorRefreshed
133 function buildActorInstance (type: ActivityPubActorType, url: string, preferredUsername: string, uuid?: string) {
134 return new ActorModel({
143 inboxUrl: url + '/inbox',
144 outboxUrl: url + '/outbox',
145 sharedInboxUrl: WEBSERVER.URL + '/inbox',
146 followersUrl: url + '/followers',
147 followingUrl: url + '/following'
151 async function updateActorInstance (actorInstance: ActorModel, attributes: ActivityPubActor) {
152 const followersCount = await fetchActorTotalItems(attributes.followers)
153 const followingCount = await fetchActorTotalItems(attributes.following)
155 actorInstance.type = attributes.type
156 actorInstance.preferredUsername = attributes.preferredUsername
157 actorInstance.url = attributes.id
158 actorInstance.publicKey = attributes.publicKey.publicKeyPem
159 actorInstance.followersCount = followersCount
160 actorInstance.followingCount = followingCount
161 actorInstance.inboxUrl = attributes.inbox
162 actorInstance.outboxUrl = attributes.outbox
163 actorInstance.followersUrl = attributes.followers
164 actorInstance.followingUrl = attributes.following
166 if (attributes.endpoints?.sharedInbox) {
167 actorInstance.sharedInboxUrl = attributes.endpoints.sharedInbox
171 type AvatarInfo = { name: string, onDisk: boolean, fileUrl: string }
172 async function updateActorAvatarInstance (actor: MActorDefault, info: AvatarInfo, t: Transaction) {
173 if (!info.name) return actor
176 // Don't update the avatar if the file URL did not change
177 if (info.fileUrl && actor.Avatar.fileUrl === info.fileUrl) return actor
180 await actor.Avatar.destroy({ transaction: t })
182 logger.error('Cannot remove old avatar of actor %s.', actor.url, { err })
186 const avatar = await AvatarModel.create({
189 fileUrl: info.fileUrl
190 }, { transaction: t })
192 actor.avatarId = avatar.id
193 actor.Avatar = avatar
198 async function deleteActorAvatarInstance (actor: MActorDefault, t: Transaction) {
200 await actor.Avatar.destroy({ transaction: t })
202 logger.error('Cannot remove old avatar of actor %s.', actor.url, { err })
205 actor.avatarId = null
211 async function fetchActorTotalItems (url: string) {
220 const { body } = await doRequest<ActivityPubOrderedCollection<unknown>>(options)
221 return body.totalItems ? body.totalItems : 0
223 logger.warn('Cannot fetch remote actor count %s.', url, { err })
228 function getAvatarInfoIfExists (actorJSON: ActivityPubActor) {
229 const mimetypes = MIMETYPES.IMAGE
230 const icon = actorJSON.icon
232 if (!icon || icon.type !== 'Image' || !isActivityPubUrlValid(icon.url)) return undefined
234 let extension: string
236 if (icon.mediaType) {
237 extension = mimetypes.MIMETYPE_EXT[icon.mediaType]
239 const tmp = extname(icon.url)
241 if (mimetypes.EXT_MIMETYPE[tmp] !== undefined) extension = tmp
244 if (!extension) return undefined
247 name: uuidv4() + extension,
252 async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
253 // Don't fetch ourselves
254 const serverActor = await getServerActor()
255 if (serverActor.id === actor.id) {
256 logger.error('Cannot fetch our own outbox!')
261 uri: actor.outboxUrl,
262 type: 'activity' as 'activity'
265 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
268 async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
270 fetchedType: ActorFetchByUrlType
271 ): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
272 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
274 // We need more attributes
275 const actor = fetchedType === 'all'
276 ? actorArg as MActorFull
277 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
282 actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
284 logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
288 const { result, statusCode } = await fetchRemoteActor(actorUrl)
290 if (statusCode === HttpStatusCode.NOT_FOUND_404) {
291 logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
293 ? await actor.Account.destroy()
294 : await actor.VideoChannel.destroy()
296 return { actor: undefined, refreshed: false }
299 if (result === undefined) {
300 logger.warn('Cannot fetch remote actor in refresh actor.')
301 return { actor, refreshed: false }
304 return sequelizeTypescript.transaction(async t => {
305 updateInstanceWithAnother(actor, result.actor)
307 if (result.avatar !== undefined) {
309 name: result.avatar.name,
310 fileUrl: result.avatar.fileUrl,
314 await updateActorAvatarInstance(actor, avatarInfo, t)
318 actor.setDataValue('updatedAt', new Date())
319 await actor.save({ transaction: t })
322 actor.Account.name = result.name
323 actor.Account.description = result.summary
325 await actor.Account.save({ transaction: t })
326 } else if (actor.VideoChannel) {
327 actor.VideoChannel.name = result.name
328 actor.VideoChannel.description = result.summary
329 actor.VideoChannel.support = result.support
331 await actor.VideoChannel.save({ transaction: t })
334 return { refreshed: true, actor }
337 logger.warn('Cannot refresh actor %s.', actor.url, { err })
338 return { actor, refreshed: false }
343 getOrCreateActorAndServerAndModel,
345 generateAndSaveActorKeys,
346 fetchActorTotalItems,
347 getAvatarInfoIfExists,
349 deleteActorAvatarInstance,
350 refreshActorIfNeeded,
351 updateActorAvatarInstance,
355 // ---------------------------------------------------------------------------
357 function saveActorAndServerAndModelIfNotExist (
358 result: FetchRemoteActorResult,
359 ownerActor?: MActorFullActor,
361 ): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
362 const actor = result.actor
364 if (t !== undefined) return save(t)
366 return sequelizeTypescript.transaction(t => save(t))
368 async function save (t: Transaction) {
369 const actorHost = new URL(actor.url).host
371 const serverOptions = {
380 const [ server ] = await ServerModel.findOrCreate(serverOptions)
382 // Save our new account in database
383 actor.serverId = server.id
387 const avatar = await AvatarModel.create({
388 filename: result.avatar.name,
389 fileUrl: result.avatar.fileUrl,
391 }, { transaction: t })
393 actor.avatarId = avatar.id
396 // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
397 // (which could be false in a retried query)
398 const [ actorCreated, created ] = await ActorModel.findOrCreate<MActorFullActor>({
399 defaults: actor.toJSON(),
406 serverId: actor.serverId,
407 preferredUsername: actor.preferredUsername
414 // Try to fix non HTTPS accounts of remote instances that fixed their URL afterwards
415 if (created !== true && actorCreated.url !== actor.url) {
416 // Only fix http://example.com/account/djidane to https://example.com/account/djidane
417 if (actorCreated.url.replace(/^http:\/\//, '') !== actor.url.replace(/^https:\/\//, '')) {
418 throw new Error(`Actor from DB with URL ${actorCreated.url} does not correspond to actor ${actor.url}`)
421 actorCreated.url = actor.url
422 await actorCreated.save({ transaction: t })
425 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
426 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountDefault
427 actorCreated.Account.Actor = actorCreated
428 } else if (actorCreated.type === 'Group') { // Video channel
429 const channel = await saveVideoChannel(actorCreated, result, ownerActor, t)
430 actorCreated.VideoChannel = Object.assign(channel, { Actor: actorCreated, Account: ownerActor.Account })
433 actorCreated.Server = server
439 type FetchRemoteActorResult = {
449 attributedTo: ActivityPubAttributedTo[]
451 async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
459 logger.info('Fetching remote actor %s.', actorUrl)
461 const requestResult = await doRequest<ActivityPubActor>(options)
462 const actorJSON = requestResult.body
464 if (sanitizeAndCheckActorObject(actorJSON) === false) {
465 logger.debug('Remote actor JSON is not valid.', { actorJSON })
466 return { result: undefined, statusCode: requestResult.response.statusCode }
469 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
470 logger.warn('Actor url %s has not the same host than its AP id %s', actorUrl, actorJSON.id)
471 return { result: undefined, statusCode: requestResult.response.statusCode }
474 const followersCount = await fetchActorTotalItems(actorJSON.followers)
475 const followingCount = await fetchActorTotalItems(actorJSON.following)
477 const actor = new ActorModel({
478 type: actorJSON.type,
479 preferredUsername: actorJSON.preferredUsername,
481 publicKey: actorJSON.publicKey.publicKeyPem,
483 followersCount: followersCount,
484 followingCount: followingCount,
485 inboxUrl: actorJSON.inbox,
486 outboxUrl: actorJSON.outbox,
487 followersUrl: actorJSON.followers,
488 followingUrl: actorJSON.following,
490 sharedInboxUrl: actorJSON.endpoints?.sharedInbox
491 ? actorJSON.endpoints.sharedInbox
495 const avatarInfo = await getAvatarInfoIfExists(actorJSON)
497 const name = actorJSON.name || actorJSON.preferredUsername
499 statusCode: requestResult.response.statusCode,
504 summary: actorJSON.summary,
505 support: actorJSON.support,
506 playlists: actorJSON.playlists,
507 attributedTo: actorJSON.attributedTo
512 async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
513 const [ accountCreated ] = await AccountModel.findOrCreate({
516 description: result.summary,
525 return accountCreated as MAccount
528 async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
529 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
532 description: result.summary,
533 support: result.support,
535 accountId: ownerActor.Account.id
543 return videoChannelCreated as MChannel