1 import * as Bluebird from 'bluebird'
2 import { Transaction } from 'sequelize'
3 import { URL } from 'url'
4 import * as uuidv4 from 'uuid/v4'
5 import { ActivityPubActor, ActivityPubActorType } 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 { getServerActor } from '../../helpers/utils'
23 import { ActorFetchByUrlType, fetchActorByUrl } from '../../helpers/actor'
24 import { sequelizeTypescript } from '../../initializers/database'
29 MActorAccountChannelId,
30 MActorAccountChannelIdActor,
37 } from '../../typings/models'
39 // Set account keys, this could be long so process after the account creation and do not block the client
40 function setAsyncActorKeys <T extends MActor> (actor: T) {
41 return createPrivateAndPublicKeys()
42 .then(({ publicKey, privateKey }) => {
43 actor.publicKey = publicKey
44 actor.privateKey = privateKey
48 logger.error('Cannot set public/private keys of actor %d.', actor.url, { err })
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 ' + actor.url)
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 ' + actorRefreshed.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.endpoints && attributes.endpoints.sharedInbox) {
169 actorInstance.sharedInboxUrl = attributes.endpoints.sharedInbox
173 type AvatarInfo = { name: string, onDisk: boolean, fileUrl: string }
174 async function updateActorAvatarInstance (actor: MActorDefault, info: AvatarInfo, t: Transaction) {
175 if (!info.name) return actor
178 // Don't update the avatar if the filename did not change
179 if (actor.Avatar.fileUrl === info.fileUrl) return actor
182 await actor.Avatar.destroy({ transaction: t })
184 logger.error('Cannot remove old avatar of actor %s.', actor.url, { err })
188 const avatar = await AvatarModel.create({
191 fileUrl: info.fileUrl
192 }, { transaction: t })
194 actor.avatarId = avatar.id
195 actor.Avatar = avatar
200 async function fetchActorTotalItems (url: string) {
209 const { body } = await doRequest(options)
210 return body.totalItems ? body.totalItems : 0
212 logger.warn('Cannot fetch remote actor count %s.', url, { err })
217 function getAvatarInfoIfExists (actorJSON: ActivityPubActor) {
219 actorJSON.icon && actorJSON.icon.type === 'Image' && MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType] !== undefined &&
220 isActivityPubUrlValid(actorJSON.icon.url)
222 const extension = MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType]
225 name: uuidv4() + extension,
226 fileUrl: actorJSON.icon.url
233 async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
234 // Don't fetch ourselves
235 const serverActor = await getServerActor()
236 if (serverActor.id === actor.id) {
237 logger.error('Cannot fetch our own outbox!')
242 uri: actor.outboxUrl,
243 type: 'activity' as 'activity'
246 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
249 async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
251 fetchedType: ActorFetchByUrlType
252 ): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
253 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
255 // We need more attributes
256 const actor = fetchedType === 'all'
257 ? actorArg as MActorFull
258 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
263 actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
265 logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
269 const { result, statusCode } = await fetchRemoteActor(actorUrl)
271 if (statusCode === 404) {
272 logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
274 ? await actor.Account.destroy()
275 : await actor.VideoChannel.destroy()
277 return { actor: undefined, refreshed: false }
280 if (result === undefined) {
281 logger.warn('Cannot fetch remote actor in refresh actor.')
282 return { actor, refreshed: false }
285 return sequelizeTypescript.transaction(async t => {
286 updateInstanceWithAnother(actor, result.actor)
288 if (result.avatar !== undefined) {
290 name: result.avatar.name,
291 fileUrl: result.avatar.fileUrl,
295 await updateActorAvatarInstance(actor, avatarInfo, t)
299 actor.setDataValue('updatedAt', new Date())
300 await actor.save({ transaction: t })
303 actor.Account.name = result.name
304 actor.Account.description = result.summary
306 await actor.Account.save({ transaction: t })
307 } else if (actor.VideoChannel) {
308 actor.VideoChannel.name = result.name
309 actor.VideoChannel.description = result.summary
310 actor.VideoChannel.support = result.support
312 await actor.VideoChannel.save({ transaction: t })
315 return { refreshed: true, actor }
318 logger.warn('Cannot refresh actor %s.', actor.url, { err })
319 return { actor, refreshed: false }
324 getOrCreateActorAndServerAndModel,
327 fetchActorTotalItems,
328 getAvatarInfoIfExists,
330 refreshActorIfNeeded,
331 updateActorAvatarInstance,
335 // ---------------------------------------------------------------------------
337 function saveActorAndServerAndModelIfNotExist (
338 result: FetchRemoteActorResult,
339 ownerActor?: MActorFullActor,
341 ): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
342 const actor = result.actor
344 if (t !== undefined) return save(t)
346 return sequelizeTypescript.transaction(t => save(t))
348 async function save (t: Transaction) {
349 const actorHost = new URL(actor.url).host
351 const serverOptions = {
360 const [ server ] = await ServerModel.findOrCreate(serverOptions)
362 // Save our new account in database
363 actor.serverId = server.id
367 const avatar = await AvatarModel.create({
368 filename: result.avatar.name,
369 fileUrl: result.avatar.fileUrl,
371 }, { transaction: t })
373 actor.avatarId = avatar.id
376 // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
377 // (which could be false in a retried query)
378 const [ actorCreated ] = await ActorModel.findOrCreate<MActorFullActor>({
379 defaults: actor.toJSON(),
386 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
387 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountDefault
388 actorCreated.Account.Actor = actorCreated
389 } else if (actorCreated.type === 'Group') { // Video channel
390 const channel = await saveVideoChannel(actorCreated, result, ownerActor, t)
391 actorCreated.VideoChannel = Object.assign(channel, { Actor: actorCreated, Account: ownerActor.Account })
394 actorCreated.Server = server
400 type FetchRemoteActorResult = {
410 attributedTo: ActivityPubAttributedTo[]
412 async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
420 logger.info('Fetching remote actor %s.', actorUrl)
422 const requestResult = await doRequest<ActivityPubActor>(options)
423 const actorJSON = requestResult.body
425 if (sanitizeAndCheckActorObject(actorJSON) === false) {
426 logger.debug('Remote actor JSON is not valid.', { actorJSON })
427 return { result: undefined, statusCode: requestResult.response.statusCode }
430 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
431 logger.warn('Actor url %s has not the same host than its AP id %s', actorUrl, actorJSON.id)
432 return { result: undefined, statusCode: requestResult.response.statusCode }
435 const followersCount = await fetchActorTotalItems(actorJSON.followers)
436 const followingCount = await fetchActorTotalItems(actorJSON.following)
438 const actor = new ActorModel({
439 type: actorJSON.type,
440 preferredUsername: actorJSON.preferredUsername,
442 publicKey: actorJSON.publicKey.publicKeyPem,
444 followersCount: followersCount,
445 followingCount: followingCount,
446 inboxUrl: actorJSON.inbox,
447 outboxUrl: actorJSON.outbox,
448 followersUrl: actorJSON.followers,
449 followingUrl: actorJSON.following,
451 sharedInboxUrl: actorJSON.endpoints && actorJSON.endpoints.sharedInbox
452 ? actorJSON.endpoints.sharedInbox
456 const avatarInfo = await getAvatarInfoIfExists(actorJSON)
458 const name = actorJSON.name || actorJSON.preferredUsername
460 statusCode: requestResult.response.statusCode,
465 summary: actorJSON.summary,
466 support: actorJSON.support,
467 playlists: actorJSON.playlists,
468 attributedTo: actorJSON.attributedTo
473 async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
474 const [ accountCreated ] = await AccountModel.findOrCreate({
477 description: result.summary,
486 return accountCreated as MAccount
489 async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
490 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
493 description: result.summary,
494 support: result.support,
496 accountId: ownerActor.Account.id
504 return videoChannelCreated as MChannel