1 import * as Bluebird from 'bluebird'
2 import { extname } from 'path'
3 import { Op, Transaction } from 'sequelize'
4 import { URL } from 'url'
5 import { v4 as uuidv4 } from 'uuid'
6 import { getServerActor } from '@server/models/application/application'
7 import { ActorImageType } from '@shared/models'
8 import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
9 import { ActivityPubActor, ActivityPubActorType, ActivityPubOrderedCollection } from '../../../shared/models/activitypub'
10 import { ActivityPubAttributedTo } from '../../../shared/models/activitypub/objects'
11 import { checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
12 import { ActorFetchByUrlType, fetchActorByUrl } from '../../helpers/actor'
13 import { sanitizeAndCheckActorObject } from '../../helpers/custom-validators/activitypub/actor'
14 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
15 import { retryTransactionWrapper, updateInstanceWithAnother } from '../../helpers/database-utils'
16 import { logger } from '../../helpers/logger'
17 import { createPrivateAndPublicKeys } from '../../helpers/peertube-crypto'
18 import { doJSONRequest, PeerTubeRequestError } from '../../helpers/requests'
19 import { getUrlFromWebfinger } from '../../helpers/webfinger'
20 import { MIMETYPES, WEBSERVER } from '../../initializers/constants'
21 import { sequelizeTypescript } from '../../initializers/database'
22 import { AccountModel } from '../../models/account/account'
23 import { ActorImageModel } from '../../models/account/actor-image'
24 import { ActorModel } from '../../models/activitypub/actor'
25 import { ServerModel } from '../../models/server/server'
26 import { VideoChannelModel } from '../../models/video/video-channel'
31 MActorAccountChannelId,
32 MActorAccountChannelIdActor,
40 } from '../../types/models'
41 import { JobQueue } from '../job-queue'
43 // Set account keys, this could be long so process after the account creation and do not block the client
44 async function generateAndSaveActorKeys <T extends MActor> (actor: T) {
45 const { publicKey, privateKey } = await createPrivateAndPublicKeys()
47 actor.publicKey = publicKey
48 actor.privateKey = privateKey
53 function getOrCreateActorAndServerAndModel (
54 activityActor: string | ActivityPubActor,
56 recurseIfNeeded?: boolean,
57 updateCollections?: boolean
58 ): Promise<MActorFullActor>
60 function getOrCreateActorAndServerAndModel (
61 activityActor: string | ActivityPubActor,
62 fetchType?: 'association-ids',
63 recurseIfNeeded?: boolean,
64 updateCollections?: boolean
65 ): Promise<MActorAccountChannelId>
67 async function getOrCreateActorAndServerAndModel (
68 activityActor: string | ActivityPubActor,
69 fetchType: ActorFetchByUrlType = 'association-ids',
70 recurseIfNeeded = true,
71 updateCollections = false
72 ): Promise<MActorFullActor | MActorAccountChannelId> {
73 const actorUrl = getAPId(activityActor)
75 let accountPlaylistsUrl: string
77 let actor = await fetchActorByUrl(actorUrl, fetchType)
78 // Orphan actor (not associated to an account of channel) so recreate it
79 if (actor && (!actor.Account && !actor.VideoChannel)) {
84 // We don't have this actor in our database, fetch it on remote
86 const { result } = await fetchRemoteActor(actorUrl)
87 if (result === undefined) throw new Error('Cannot fetch remote actor ' + actorUrl)
89 // Create the attributed to actor
90 // In PeerTube a video channel is owned by an account
91 let ownerActor: MActorFullActor
92 if (recurseIfNeeded === true && result.actor.type === 'Group') {
93 const accountAttributedTo = result.attributedTo.find(a => a.type === 'Person')
94 if (!accountAttributedTo) throw new Error('Cannot find account attributed to video channel ' + actor.url)
96 if (checkUrlsSameHost(accountAttributedTo.id, actorUrl) !== true) {
97 throw new Error(`Account attributed to ${accountAttributedTo.id} does not have the same host than actor url ${actorUrl}`)
101 // Don't recurse another time
102 const recurseIfNeeded = false
103 ownerActor = await getOrCreateActorAndServerAndModel(accountAttributedTo.id, 'all', recurseIfNeeded)
105 logger.error('Cannot get or create account attributed to video channel ' + actorUrl)
110 actor = await retryTransactionWrapper(saveActorAndServerAndModelIfNotExist, result, ownerActor)
112 accountPlaylistsUrl = result.playlists
115 if (actor.Account) (actor as MActorAccountChannelIdActor).Account.Actor = actor
116 if (actor.VideoChannel) (actor as MActorAccountChannelIdActor).VideoChannel.Actor = actor
118 const { actor: actorRefreshed, refreshed } = await retryTransactionWrapper(refreshActorIfNeeded, actor, fetchType)
119 if (!actorRefreshed) throw new Error('Actor ' + actor.url + ' does not exist anymore.')
121 if ((created === true || refreshed === true) && updateCollections === true) {
122 const payload = { uri: actor.outboxUrl, type: 'activity' as 'activity' }
123 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
126 // We created a new account: fetch the playlists
127 if (created === true && actor.Account && accountPlaylistsUrl) {
128 const payload = { uri: accountPlaylistsUrl, accountId: actor.Account.id, type: 'account-playlists' as 'account-playlists' }
129 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
132 return actorRefreshed
135 function buildActorInstance (type: ActivityPubActorType, url: string, preferredUsername: string, uuid?: string) {
136 return new ActorModel({
145 inboxUrl: url + '/inbox',
146 outboxUrl: url + '/outbox',
147 sharedInboxUrl: WEBSERVER.URL + '/inbox',
148 followersUrl: url + '/followers',
149 followingUrl: url + '/following'
153 async function updateActorInstance (actorInstance: ActorModel, attributes: ActivityPubActor) {
154 const followersCount = await fetchActorTotalItems(attributes.followers)
155 const followingCount = await fetchActorTotalItems(attributes.following)
157 actorInstance.type = attributes.type
158 actorInstance.preferredUsername = attributes.preferredUsername
159 actorInstance.url = attributes.id
160 actorInstance.publicKey = attributes.publicKey.publicKeyPem
161 actorInstance.followersCount = followersCount
162 actorInstance.followingCount = followingCount
163 actorInstance.inboxUrl = attributes.inbox
164 actorInstance.outboxUrl = attributes.outbox
165 actorInstance.followersUrl = attributes.followers
166 actorInstance.followingUrl = attributes.following
168 if (attributes.published) actorInstance.remoteCreatedAt = new Date(attributes.published)
170 if (attributes.endpoints?.sharedInbox) {
171 actorInstance.sharedInboxUrl = attributes.endpoints.sharedInbox
182 async function updateActorImageInstance (actor: MActorImages, type: ActorImageType, imageInfo: ImageInfo | null, t: Transaction) {
183 const oldImageModel = type === ActorImageType.AVATAR
188 // Don't update the avatar if the file URL did not change
189 if (imageInfo?.fileUrl && oldImageModel.fileUrl === imageInfo.fileUrl) return actor
192 await oldImageModel.destroy({ transaction: t })
194 setActorImage(actor, type, null)
196 logger.error('Cannot remove old actor image of actor %s.', actor.url, { err })
201 const imageModel = await ActorImageModel.create({
202 filename: imageInfo.name,
203 onDisk: imageInfo.onDisk ?? false,
204 fileUrl: imageInfo.fileUrl,
205 height: imageInfo.height,
206 width: imageInfo.width,
208 }, { transaction: t })
210 setActorImage(actor, type, imageModel)
216 async function deleteActorImageInstance (actor: MActorImages, type: ActorImageType, t: Transaction) {
218 if (type === ActorImageType.AVATAR) {
219 await actor.Avatar.destroy({ transaction: t })
221 actor.avatarId = null
224 await actor.Banner.destroy({ transaction: t })
226 actor.bannerId = null
230 logger.error('Cannot remove old image of actor %s.', actor.url, { err })
236 async function fetchActorTotalItems (url: string) {
238 const { body } = await doJSONRequest<ActivityPubOrderedCollection<unknown>>(url, { activityPub: true })
240 return body.totalItems || 0
242 logger.warn('Cannot fetch remote actor count %s.', url, { err })
247 function getImageInfoIfExists (actorJSON: ActivityPubActor, type: ActorImageType) {
248 const mimetypes = MIMETYPES.IMAGE
249 const icon = type === ActorImageType.AVATAR
253 if (!icon || icon.type !== 'Image' || !isActivityPubUrlValid(icon.url)) return undefined
255 let extension: string
257 if (icon.mediaType) {
258 extension = mimetypes.MIMETYPE_EXT[icon.mediaType]
260 const tmp = extname(icon.url)
262 if (mimetypes.EXT_MIMETYPE[tmp] !== undefined) extension = tmp
265 if (!extension) return undefined
268 name: uuidv4() + extension,
276 async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
277 // Don't fetch ourselves
278 const serverActor = await getServerActor()
279 if (serverActor.id === actor.id) {
280 logger.error('Cannot fetch our own outbox!')
285 uri: actor.outboxUrl,
286 type: 'activity' as 'activity'
289 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
292 async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
294 fetchedType: ActorFetchByUrlType
295 ): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
296 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
298 // We need more attributes
299 const actor = fetchedType === 'all'
300 ? actorArg as MActorFull
301 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
306 actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
308 logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
312 const { result } = await fetchRemoteActor(actorUrl)
314 if (result === undefined) {
315 logger.warn('Cannot fetch remote actor in refresh actor.')
316 return { actor, refreshed: false }
319 return sequelizeTypescript.transaction(async t => {
320 updateInstanceWithAnother(actor, result.actor)
322 await updateActorImageInstance(actor, ActorImageType.AVATAR, result.avatar, t)
323 await updateActorImageInstance(actor, ActorImageType.BANNER, result.banner, t)
326 actor.setDataValue('updatedAt', new Date())
327 await actor.save({ transaction: t })
330 actor.Account.name = result.name
331 actor.Account.description = result.summary
333 await actor.Account.save({ transaction: t })
334 } else if (actor.VideoChannel) {
335 actor.VideoChannel.name = result.name
336 actor.VideoChannel.description = result.summary
337 actor.VideoChannel.support = result.support
339 await actor.VideoChannel.save({ transaction: t })
342 return { refreshed: true, actor }
345 if ((err as PeerTubeRequestError).statusCode === HttpStatusCode.NOT_FOUND_404) {
346 logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
348 ? await actor.Account.destroy()
349 : await actor.VideoChannel.destroy()
351 return { actor: undefined, refreshed: false }
354 logger.warn('Cannot refresh actor %s.', actor.url, { err })
355 return { actor, refreshed: false }
360 getOrCreateActorAndServerAndModel,
362 generateAndSaveActorKeys,
363 fetchActorTotalItems,
364 getImageInfoIfExists,
366 deleteActorImageInstance,
367 refreshActorIfNeeded,
368 updateActorImageInstance,
372 // ---------------------------------------------------------------------------
374 function setActorImage (actorModel: MActorImages, type: ActorImageType, imageModel: MActorImage) {
375 const id = imageModel
379 if (type === ActorImageType.AVATAR) {
380 actorModel.avatarId = id
381 actorModel.Avatar = imageModel
383 actorModel.bannerId = id
384 actorModel.Banner = imageModel
390 function saveActorAndServerAndModelIfNotExist (
391 result: FetchRemoteActorResult,
392 ownerActor?: MActorFullActor,
394 ): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
395 const actor = result.actor
397 if (t !== undefined) return save(t)
399 return sequelizeTypescript.transaction(t => save(t))
401 async function save (t: Transaction) {
402 const actorHost = new URL(actor.url).host
404 const serverOptions = {
413 const [ server ] = await ServerModel.findOrCreate(serverOptions)
415 // Save our new account in database
416 actor.serverId = server.id
420 const avatar = await ActorImageModel.create({
421 filename: result.avatar.name,
422 fileUrl: result.avatar.fileUrl,
423 width: result.avatar.width,
424 height: result.avatar.height,
426 type: ActorImageType.AVATAR
427 }, { transaction: t })
429 actor.avatarId = avatar.id
434 const banner = await ActorImageModel.create({
435 filename: result.banner.name,
436 fileUrl: result.banner.fileUrl,
437 width: result.banner.width,
438 height: result.banner.height,
440 type: ActorImageType.BANNER
441 }, { transaction: t })
443 actor.bannerId = banner.id
446 // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
447 // (which could be false in a retried query)
448 const [ actorCreated, created ] = await ActorModel.findOrCreate<MActorFullActor>({
449 defaults: actor.toJSON(),
456 serverId: actor.serverId,
457 preferredUsername: actor.preferredUsername
464 // Try to fix non HTTPS accounts of remote instances that fixed their URL afterwards
465 if (created !== true && actorCreated.url !== actor.url) {
466 // Only fix http://example.com/account/djidane to https://example.com/account/djidane
467 if (actorCreated.url.replace(/^http:\/\//, '') !== actor.url.replace(/^https:\/\//, '')) {
468 throw new Error(`Actor from DB with URL ${actorCreated.url} does not correspond to actor ${actor.url}`)
471 actorCreated.url = actor.url
472 await actorCreated.save({ transaction: t })
475 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
476 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountDefault
477 actorCreated.Account.Actor = actorCreated
478 } else if (actorCreated.type === 'Group') { // Video channel
479 const channel = await saveVideoChannel(actorCreated, result, ownerActor, t)
480 actorCreated.VideoChannel = Object.assign(channel, { Actor: actorCreated, Account: ownerActor.Account })
483 actorCreated.Server = server
496 type FetchRemoteActorResult = {
504 attributedTo: ActivityPubAttributedTo[]
506 async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
507 logger.info('Fetching remote actor %s.', actorUrl)
509 const requestResult = await doJSONRequest<ActivityPubActor>(actorUrl, { activityPub: true })
510 const actorJSON = requestResult.body
512 if (sanitizeAndCheckActorObject(actorJSON) === false) {
513 logger.debug('Remote actor JSON is not valid.', { actorJSON })
514 return { result: undefined, statusCode: requestResult.statusCode }
517 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
518 logger.warn('Actor url %s has not the same host than its AP id %s', actorUrl, actorJSON.id)
519 return { result: undefined, statusCode: requestResult.statusCode }
522 const followersCount = await fetchActorTotalItems(actorJSON.followers)
523 const followingCount = await fetchActorTotalItems(actorJSON.following)
525 const actor = new ActorModel({
526 type: actorJSON.type,
527 preferredUsername: actorJSON.preferredUsername,
529 publicKey: actorJSON.publicKey.publicKeyPem,
531 followersCount: followersCount,
532 followingCount: followingCount,
533 inboxUrl: actorJSON.inbox,
534 outboxUrl: actorJSON.outbox,
535 followersUrl: actorJSON.followers,
536 followingUrl: actorJSON.following,
538 sharedInboxUrl: actorJSON.endpoints?.sharedInbox
539 ? actorJSON.endpoints.sharedInbox
543 const avatarInfo = getImageInfoIfExists(actorJSON, ActorImageType.AVATAR)
544 const bannerInfo = getImageInfoIfExists(actorJSON, ActorImageType.BANNER)
546 const name = actorJSON.name || actorJSON.preferredUsername
548 statusCode: requestResult.statusCode,
554 summary: actorJSON.summary,
555 support: actorJSON.support,
556 playlists: actorJSON.playlists,
557 attributedTo: actorJSON.attributedTo
562 async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
563 const [ accountCreated ] = await AccountModel.findOrCreate({
566 description: result.summary,
575 return accountCreated as MAccount
578 async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
579 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
582 description: result.summary,
583 support: result.support,
585 accountId: ownerActor.Account.id
593 return videoChannelCreated as MChannel