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,
39 } from '../../types/models'
40 import { JobQueue } from '../job-queue'
42 // Set account keys, this could be long so process after the account creation and do not block the client
43 async function generateAndSaveActorKeys <T extends MActor> (actor: T) {
44 const { publicKey, privateKey } = await createPrivateAndPublicKeys()
46 actor.publicKey = publicKey
47 actor.privateKey = privateKey
52 function getOrCreateActorAndServerAndModel (
53 activityActor: string | ActivityPubActor,
55 recurseIfNeeded?: boolean,
56 updateCollections?: boolean
57 ): Promise<MActorFullActor>
59 function getOrCreateActorAndServerAndModel (
60 activityActor: string | ActivityPubActor,
61 fetchType?: 'association-ids',
62 recurseIfNeeded?: boolean,
63 updateCollections?: boolean
64 ): Promise<MActorAccountChannelId>
66 async function getOrCreateActorAndServerAndModel (
67 activityActor: string | ActivityPubActor,
68 fetchType: ActorFetchByUrlType = 'association-ids',
69 recurseIfNeeded = true,
70 updateCollections = false
71 ): Promise<MActorFullActor | MActorAccountChannelId> {
72 const actorUrl = getAPId(activityActor)
74 let accountPlaylistsUrl: string
76 let actor = await fetchActorByUrl(actorUrl, fetchType)
77 // Orphan actor (not associated to an account of channel) so recreate it
78 if (actor && (!actor.Account && !actor.VideoChannel)) {
83 // We don't have this actor in our database, fetch it on remote
85 const { result } = await fetchRemoteActor(actorUrl)
86 if (result === undefined) throw new Error('Cannot fetch remote actor ' + actorUrl)
88 // Create the attributed to actor
89 // In PeerTube a video channel is owned by an account
90 let ownerActor: MActorFullActor
91 if (recurseIfNeeded === true && result.actor.type === 'Group') {
92 const accountAttributedTo = result.attributedTo.find(a => a.type === 'Person')
93 if (!accountAttributedTo) throw new Error('Cannot find account attributed to video channel ' + actor.url)
95 if (checkUrlsSameHost(accountAttributedTo.id, actorUrl) !== true) {
96 throw new Error(`Account attributed to ${accountAttributedTo.id} does not have the same host than actor url ${actorUrl}`)
100 // Don't recurse another time
101 const recurseIfNeeded = false
102 ownerActor = await getOrCreateActorAndServerAndModel(accountAttributedTo.id, 'all', recurseIfNeeded)
104 logger.error('Cannot get or create account attributed to video channel ' + actorUrl)
109 actor = await retryTransactionWrapper(saveActorAndServerAndModelIfNotExist, result, ownerActor)
111 accountPlaylistsUrl = result.playlists
114 if (actor.Account) (actor as MActorAccountChannelIdActor).Account.Actor = actor
115 if (actor.VideoChannel) (actor as MActorAccountChannelIdActor).VideoChannel.Actor = actor
117 const { actor: actorRefreshed, refreshed } = await retryTransactionWrapper(refreshActorIfNeeded, actor, fetchType)
118 if (!actorRefreshed) throw new Error('Actor ' + actor.url + ' does not exist anymore.')
120 if ((created === true || refreshed === true) && updateCollections === true) {
121 const payload = { uri: actor.outboxUrl, type: 'activity' as 'activity' }
122 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
125 // We created a new account: fetch the playlists
126 if (created === true && actor.Account && accountPlaylistsUrl) {
127 const payload = { uri: accountPlaylistsUrl, accountId: actor.Account.id, type: 'account-playlists' as 'account-playlists' }
128 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
131 return actorRefreshed
134 function buildActorInstance (type: ActivityPubActorType, url: string, preferredUsername: string, uuid?: string) {
135 return new ActorModel({
144 inboxUrl: url + '/inbox',
145 outboxUrl: url + '/outbox',
146 sharedInboxUrl: WEBSERVER.URL + '/inbox',
147 followersUrl: url + '/followers',
148 followingUrl: url + '/following'
152 async function updateActorInstance (actorInstance: ActorModel, attributes: ActivityPubActor) {
153 const followersCount = await fetchActorTotalItems(attributes.followers)
154 const followingCount = await fetchActorTotalItems(attributes.following)
156 actorInstance.type = attributes.type
157 actorInstance.preferredUsername = attributes.preferredUsername
158 actorInstance.url = attributes.id
159 actorInstance.publicKey = attributes.publicKey.publicKeyPem
160 actorInstance.followersCount = followersCount
161 actorInstance.followingCount = followingCount
162 actorInstance.inboxUrl = attributes.inbox
163 actorInstance.outboxUrl = attributes.outbox
164 actorInstance.followersUrl = attributes.followers
165 actorInstance.followingUrl = attributes.following
167 if (attributes.endpoints?.sharedInbox) {
168 actorInstance.sharedInboxUrl = attributes.endpoints.sharedInbox
172 type AvatarInfo = { name: string, onDisk: boolean, fileUrl: string, type: ActorImageType }
173 async function updateActorImageInstance (actor: MActorImages, info: AvatarInfo, t: Transaction) {
174 if (!info.name) return actor
176 const oldImageModel = info.type === ActorImageType.AVATAR
181 // Don't update the avatar if the file URL did not change
182 if (info.fileUrl && oldImageModel.fileUrl === info.fileUrl) return actor
185 await oldImageModel.destroy({ transaction: t })
187 logger.error('Cannot remove old actor image of actor %s.', actor.url, { err })
191 const imageModel = await ActorImageModel.create({
194 fileUrl: info.fileUrl,
196 }, { transaction: t })
198 if (info.type === ActorImageType.AVATAR) {
199 actor.avatarId = imageModel.id
200 actor.Avatar = imageModel
202 actor.bannerId = imageModel.id
203 actor.Banner = imageModel
209 async function deleteActorImageInstance (actor: MActorImages, type: ActorImageType, t: Transaction) {
211 if (type === ActorImageType.AVATAR) {
212 await actor.Avatar.destroy({ transaction: t })
214 actor.avatarId = null
217 await actor.Banner.destroy({ transaction: t })
219 actor.bannerId = null
223 logger.error('Cannot remove old image of actor %s.', actor.url, { err })
229 async function fetchActorTotalItems (url: string) {
231 const { body } = await doJSONRequest<ActivityPubOrderedCollection<unknown>>(url, { activityPub: true })
233 return body.totalItems || 0
235 logger.warn('Cannot fetch remote actor count %s.', url, { err })
240 function getImageInfoIfExists (actorJSON: ActivityPubActor, type: ActorImageType) {
241 const mimetypes = MIMETYPES.IMAGE
242 const icon = type === ActorImageType.AVATAR
246 if (!icon || icon.type !== 'Image' || !isActivityPubUrlValid(icon.url)) return undefined
248 let extension: string
250 if (icon.mediaType) {
251 extension = mimetypes.MIMETYPE_EXT[icon.mediaType]
253 const tmp = extname(icon.url)
255 if (mimetypes.EXT_MIMETYPE[tmp] !== undefined) extension = tmp
258 if (!extension) return undefined
261 name: uuidv4() + extension,
267 async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
268 // Don't fetch ourselves
269 const serverActor = await getServerActor()
270 if (serverActor.id === actor.id) {
271 logger.error('Cannot fetch our own outbox!')
276 uri: actor.outboxUrl,
277 type: 'activity' as 'activity'
280 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
283 async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
285 fetchedType: ActorFetchByUrlType
286 ): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
287 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
289 // We need more attributes
290 const actor = fetchedType === 'all'
291 ? actorArg as MActorFull
292 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
297 actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
299 logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
303 const { result } = await fetchRemoteActor(actorUrl)
305 if (result === undefined) {
306 logger.warn('Cannot fetch remote actor in refresh actor.')
307 return { actor, refreshed: false }
310 return sequelizeTypescript.transaction(async t => {
311 updateInstanceWithAnother(actor, result.actor)
313 if (result.avatar !== undefined) {
315 name: result.avatar.name,
316 fileUrl: result.avatar.fileUrl,
318 type: ActorImageType.AVATAR
321 await updateActorImageInstance(actor, avatarInfo, t)
324 if (result.banner !== undefined) {
326 name: result.banner.name,
327 fileUrl: result.banner.fileUrl,
329 type: ActorImageType.BANNER
332 await updateActorImageInstance(actor, bannerInfo, t)
336 actor.setDataValue('updatedAt', new Date())
337 await actor.save({ transaction: t })
340 actor.Account.name = result.name
341 actor.Account.description = result.summary
343 await actor.Account.save({ transaction: t })
344 } else if (actor.VideoChannel) {
345 actor.VideoChannel.name = result.name
346 actor.VideoChannel.description = result.summary
347 actor.VideoChannel.support = result.support
349 await actor.VideoChannel.save({ transaction: t })
352 return { refreshed: true, actor }
355 if ((err as PeerTubeRequestError).statusCode === HttpStatusCode.NOT_FOUND_404) {
356 logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
358 ? await actor.Account.destroy()
359 : await actor.VideoChannel.destroy()
361 return { actor: undefined, refreshed: false }
364 logger.warn('Cannot refresh actor %s.', actor.url, { err })
365 return { actor, refreshed: false }
370 getOrCreateActorAndServerAndModel,
372 generateAndSaveActorKeys,
373 fetchActorTotalItems,
374 getImageInfoIfExists,
376 deleteActorImageInstance,
377 refreshActorIfNeeded,
378 updateActorImageInstance,
382 // ---------------------------------------------------------------------------
384 function saveActorAndServerAndModelIfNotExist (
385 result: FetchRemoteActorResult,
386 ownerActor?: MActorFullActor,
388 ): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
389 const actor = result.actor
391 if (t !== undefined) return save(t)
393 return sequelizeTypescript.transaction(t => save(t))
395 async function save (t: Transaction) {
396 const actorHost = new URL(actor.url).host
398 const serverOptions = {
407 const [ server ] = await ServerModel.findOrCreate(serverOptions)
409 // Save our new account in database
410 actor.serverId = server.id
414 const avatar = await ActorImageModel.create({
415 filename: result.avatar.name,
416 fileUrl: result.avatar.fileUrl,
418 type: ActorImageType.AVATAR
419 }, { transaction: t })
421 actor.avatarId = avatar.id
426 const banner = await ActorImageModel.create({
427 filename: result.banner.name,
428 fileUrl: result.banner.fileUrl,
430 type: ActorImageType.BANNER
431 }, { transaction: t })
433 actor.bannerId = banner.id
436 // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
437 // (which could be false in a retried query)
438 const [ actorCreated, created ] = await ActorModel.findOrCreate<MActorFullActor>({
439 defaults: actor.toJSON(),
446 serverId: actor.serverId,
447 preferredUsername: actor.preferredUsername
454 // Try to fix non HTTPS accounts of remote instances that fixed their URL afterwards
455 if (created !== true && actorCreated.url !== actor.url) {
456 // Only fix http://example.com/account/djidane to https://example.com/account/djidane
457 if (actorCreated.url.replace(/^http:\/\//, '') !== actor.url.replace(/^https:\/\//, '')) {
458 throw new Error(`Actor from DB with URL ${actorCreated.url} does not correspond to actor ${actor.url}`)
461 actorCreated.url = actor.url
462 await actorCreated.save({ transaction: t })
465 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
466 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountDefault
467 actorCreated.Account.Actor = actorCreated
468 } else if (actorCreated.type === 'Group') { // Video channel
469 const channel = await saveVideoChannel(actorCreated, result, ownerActor, t)
470 actorCreated.VideoChannel = Object.assign(channel, { Actor: actorCreated, Account: ownerActor.Account })
473 actorCreated.Server = server
479 type FetchRemoteActorResult = {
493 attributedTo: ActivityPubAttributedTo[]
495 async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
496 logger.info('Fetching remote actor %s.', actorUrl)
498 const requestResult = await doJSONRequest<ActivityPubActor>(actorUrl, { activityPub: true })
499 const actorJSON = requestResult.body
501 if (sanitizeAndCheckActorObject(actorJSON) === false) {
502 logger.debug('Remote actor JSON is not valid.', { actorJSON })
503 return { result: undefined, statusCode: requestResult.statusCode }
506 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
507 logger.warn('Actor url %s has not the same host than its AP id %s', actorUrl, actorJSON.id)
508 return { result: undefined, statusCode: requestResult.statusCode }
511 const followersCount = await fetchActorTotalItems(actorJSON.followers)
512 const followingCount = await fetchActorTotalItems(actorJSON.following)
514 const actor = new ActorModel({
515 type: actorJSON.type,
516 preferredUsername: actorJSON.preferredUsername,
518 publicKey: actorJSON.publicKey.publicKeyPem,
520 followersCount: followersCount,
521 followingCount: followingCount,
522 inboxUrl: actorJSON.inbox,
523 outboxUrl: actorJSON.outbox,
524 followersUrl: actorJSON.followers,
525 followingUrl: actorJSON.following,
527 sharedInboxUrl: actorJSON.endpoints?.sharedInbox
528 ? actorJSON.endpoints.sharedInbox
532 const avatarInfo = getImageInfoIfExists(actorJSON, ActorImageType.AVATAR)
533 const bannerInfo = getImageInfoIfExists(actorJSON, ActorImageType.BANNER)
535 const name = actorJSON.name || actorJSON.preferredUsername
537 statusCode: requestResult.statusCode,
543 summary: actorJSON.summary,
544 support: actorJSON.support,
545 playlists: actorJSON.playlists,
546 attributedTo: actorJSON.attributedTo
551 async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
552 const [ accountCreated ] = await AccountModel.findOrCreate({
555 description: result.summary,
564 return accountCreated as MAccount
567 async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
568 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
571 description: result.summary,
572 support: result.support,
574 accountId: ownerActor.Account.id
582 return videoChannelCreated as MChannel