1 import * as Bluebird from 'bluebird'
2 import { Transaction } from 'sequelize'
3 import * as 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 MChannelAccountDefault
38 } from '../../typings/models'
40 // Set account keys, this could be long so process after the account creation and do not block the client
41 function setAsyncActorKeys <T extends MActor> (actor: T) {
42 return createPrivateAndPublicKeys()
43 .then(({ publicKey, privateKey }) => {
44 actor.publicKey = publicKey
45 actor.privateKey = privateKey
49 logger.error('Cannot set public/private keys of actor %d.', actor.url, { err })
54 function getOrCreateActorAndServerAndModel (
55 activityActor: string | ActivityPubActor,
57 recurseIfNeeded?: boolean,
58 updateCollections?: boolean
59 ): Promise<MActorFullActor>
61 function getOrCreateActorAndServerAndModel (
62 activityActor: string | ActivityPubActor,
63 fetchType?: 'association-ids',
64 recurseIfNeeded?: boolean,
65 updateCollections?: boolean
66 ): Promise<MActorAccountChannelId>
68 async function getOrCreateActorAndServerAndModel (
69 activityActor: string | ActivityPubActor,
70 fetchType: ActorFetchByUrlType = 'association-ids',
71 recurseIfNeeded = true,
72 updateCollections = false
73 ): Promise<MActorFullActor | MActorAccountChannelId> {
74 const actorUrl = getAPId(activityActor)
76 let accountPlaylistsUrl: string
78 let actor = await fetchActorByUrl(actorUrl, fetchType)
79 // Orphan actor (not associated to an account of channel) so recreate it
80 if (actor && (!actor.Account && !actor.VideoChannel)) {
85 // We don't have this actor in our database, fetch it on remote
87 const { result } = await fetchRemoteActor(actorUrl)
88 if (result === undefined) throw new Error('Cannot fetch remote actor ' + actorUrl)
90 // Create the attributed to actor
91 // In PeerTube a video channel is owned by an account
92 let ownerActor: MActorFullActor
93 if (recurseIfNeeded === true && result.actor.type === 'Group') {
94 const accountAttributedTo = result.attributedTo.find(a => a.type === 'Person')
95 if (!accountAttributedTo) throw new Error('Cannot find account attributed to video channel ' + actor.url)
97 if (checkUrlsSameHost(accountAttributedTo.id, actorUrl) !== true) {
98 throw new Error(`Account attributed to ${accountAttributedTo.id} does not have the same host than actor url ${actorUrl}`)
102 // Don't recurse another time
103 const recurseIfNeeded = false
104 ownerActor = await getOrCreateActorAndServerAndModel(accountAttributedTo.id, 'all', recurseIfNeeded)
106 logger.error('Cannot get or create account attributed to video channel ' + actor.url)
111 actor = await retryTransactionWrapper(saveActorAndServerAndModelIfNotExist, result, ownerActor)
113 accountPlaylistsUrl = result.playlists
116 if (actor.Account) (actor as MActorAccountChannelIdActor).Account.Actor = actor
117 if (actor.VideoChannel) (actor as MActorAccountChannelIdActor).VideoChannel.Actor = actor
119 const { actor: actorRefreshed, refreshed } = await retryTransactionWrapper(refreshActorIfNeeded, actor, fetchType)
120 if (!actorRefreshed) throw new Error('Actor ' + actorRefreshed.url + ' does not exist anymore.')
122 if ((created === true || refreshed === true) && updateCollections === true) {
123 const payload = { uri: actor.outboxUrl, type: 'activity' as 'activity' }
124 await JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
127 // We created a new account: fetch the playlists
128 if (created === true && actor.Account && accountPlaylistsUrl) {
129 const payload = { uri: accountPlaylistsUrl, accountId: actor.Account.id, type: 'account-playlists' as 'account-playlists' }
130 await JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
133 return actorRefreshed
136 function buildActorInstance (type: ActivityPubActorType, url: string, preferredUsername: string, uuid?: string) {
137 return new ActorModel({
146 inboxUrl: url + '/inbox',
147 outboxUrl: url + '/outbox',
148 sharedInboxUrl: WEBSERVER.URL + '/inbox',
149 followersUrl: url + '/followers',
150 followingUrl: url + '/following'
154 async function updateActorInstance (actorInstance: ActorModel, attributes: ActivityPubActor) {
155 const followersCount = await fetchActorTotalItems(attributes.followers)
156 const followingCount = await fetchActorTotalItems(attributes.following)
158 actorInstance.type = attributes.type
159 actorInstance.preferredUsername = attributes.preferredUsername
160 actorInstance.url = attributes.id
161 actorInstance.publicKey = attributes.publicKey.publicKeyPem
162 actorInstance.followersCount = followersCount
163 actorInstance.followingCount = followingCount
164 actorInstance.inboxUrl = attributes.inbox
165 actorInstance.outboxUrl = attributes.outbox
166 actorInstance.followersUrl = attributes.followers
167 actorInstance.followingUrl = attributes.following
169 if (attributes.endpoints && attributes.endpoints.sharedInbox) {
170 actorInstance.sharedInboxUrl = attributes.endpoints.sharedInbox
174 type AvatarInfo = { name: string, onDisk: boolean, fileUrl: string }
175 async function updateActorAvatarInstance (actor: MActorDefault, info: AvatarInfo, t: Transaction) {
176 if (info.name !== undefined) {
177 if (actor.avatarId) {
179 await actor.Avatar.destroy({ transaction: t })
181 logger.error('Cannot remove old avatar of actor %s.', actor.url, { err })
185 const avatar = await AvatarModel.create({
188 fileUrl: info.fileUrl
189 }, { transaction: t })
191 actor.avatarId = avatar.id
192 actor.Avatar = avatar
198 async function fetchActorTotalItems (url: string) {
207 const { body } = await doRequest(options)
208 return body.totalItems ? body.totalItems : 0
210 logger.warn('Cannot fetch remote actor count %s.', url, { err })
215 async function getAvatarInfoIfExists (actorJSON: ActivityPubActor) {
217 actorJSON.icon && actorJSON.icon.type === 'Image' && MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType] !== undefined &&
218 isActivityPubUrlValid(actorJSON.icon.url)
220 const extension = MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType]
223 name: uuidv4() + extension,
224 fileUrl: actorJSON.icon.url
231 async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
232 // Don't fetch ourselves
233 const serverActor = await getServerActor()
234 if (serverActor.id === actor.id) {
235 logger.error('Cannot fetch our own outbox!')
240 uri: actor.outboxUrl,
241 type: 'activity' as 'activity'
244 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
247 async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
249 fetchedType: ActorFetchByUrlType
250 ): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
251 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
253 // We need more attributes
254 const actor = fetchedType === 'all'
255 ? actorArg as MActorFull
256 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
261 actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
263 logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
267 const { result, statusCode } = await fetchRemoteActor(actorUrl)
269 if (statusCode === 404) {
270 logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
271 actor.Account ? actor.Account.destroy() : actor.VideoChannel.destroy()
272 return { actor: undefined, refreshed: false }
275 if (result === undefined) {
276 logger.warn('Cannot fetch remote actor in refresh actor.')
277 return { actor, refreshed: false }
280 return sequelizeTypescript.transaction(async t => {
281 updateInstanceWithAnother(actor, result.actor)
283 if (result.avatar !== undefined) {
285 name: result.avatar.name,
286 fileUrl: result.avatar.fileUrl,
290 await updateActorAvatarInstance(actor, avatarInfo, t)
294 actor.setDataValue('updatedAt', new Date())
295 await actor.save({ transaction: t })
298 actor.Account.name = result.name
299 actor.Account.description = result.summary
301 await actor.Account.save({ transaction: t })
302 } else if (actor.VideoChannel) {
303 actor.VideoChannel.name = result.name
304 actor.VideoChannel.description = result.summary
305 actor.VideoChannel.support = result.support
307 await actor.VideoChannel.save({ transaction: t })
310 return { refreshed: true, actor }
313 logger.warn('Cannot refresh actor %s.', actor.url, { err })
314 return { actor, refreshed: false }
319 getOrCreateActorAndServerAndModel,
322 fetchActorTotalItems,
323 getAvatarInfoIfExists,
325 refreshActorIfNeeded,
326 updateActorAvatarInstance,
330 // ---------------------------------------------------------------------------
332 function saveActorAndServerAndModelIfNotExist (
333 result: FetchRemoteActorResult,
334 ownerActor?: MActorFullActor,
336 ): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
337 let actor = result.actor
339 if (t !== undefined) return save(t)
341 return sequelizeTypescript.transaction(t => save(t))
343 async function save (t: Transaction) {
344 const actorHost = url.parse(actor.url).host
346 const serverOptions = {
355 const [ server ] = await ServerModel.findOrCreate(serverOptions)
357 // Save our new account in database
358 actor.serverId = server.id
362 const avatar = await AvatarModel.create({
363 filename: result.avatar.name,
364 fileUrl: result.avatar.fileUrl,
366 }, { transaction: t })
368 actor.avatarId = avatar.id
371 // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
372 // (which could be false in a retried query)
373 const [ actorCreated ] = await ActorModel.findOrCreate<MActorFullActor>({
374 defaults: actor.toJSON(),
381 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
382 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountDefault
383 actorCreated.Account.Actor = actorCreated
384 } else if (actorCreated.type === 'Group') { // Video channel
385 const channel = await saveVideoChannel(actorCreated, result, ownerActor, t)
386 actorCreated.VideoChannel = Object.assign(channel, { Actor: actorCreated, Account: ownerActor.Account })
389 actorCreated.Server = server
395 type FetchRemoteActorResult = {
405 attributedTo: ActivityPubAttributedTo[]
407 async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
415 logger.info('Fetching remote actor %s.', actorUrl)
417 const requestResult = await doRequest<ActivityPubActor>(options)
418 const actorJSON = requestResult.body
420 if (sanitizeAndCheckActorObject(actorJSON) === false) {
421 logger.debug('Remote actor JSON is not valid.', { actorJSON })
422 return { result: undefined, statusCode: requestResult.response.statusCode }
425 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
426 logger.warn('Actor url %s has not the same host than its AP id %s', actorUrl, actorJSON.id)
427 return { result: undefined, statusCode: requestResult.response.statusCode }
430 const followersCount = await fetchActorTotalItems(actorJSON.followers)
431 const followingCount = await fetchActorTotalItems(actorJSON.following)
433 const actor = new ActorModel({
434 type: actorJSON.type,
435 preferredUsername: actorJSON.preferredUsername,
437 publicKey: actorJSON.publicKey.publicKeyPem,
439 followersCount: followersCount,
440 followingCount: followingCount,
441 inboxUrl: actorJSON.inbox,
442 outboxUrl: actorJSON.outbox,
443 followersUrl: actorJSON.followers,
444 followingUrl: actorJSON.following,
446 sharedInboxUrl: actorJSON.endpoints && actorJSON.endpoints.sharedInbox
447 ? actorJSON.endpoints.sharedInbox
451 const avatarInfo = await getAvatarInfoIfExists(actorJSON)
453 const name = actorJSON.name || actorJSON.preferredUsername
455 statusCode: requestResult.response.statusCode,
460 summary: actorJSON.summary,
461 support: actorJSON.support,
462 playlists: actorJSON.playlists,
463 attributedTo: actorJSON.attributedTo
468 async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
469 const [ accountCreated ] = await AccountModel.findOrCreate({
472 description: result.summary,
481 return accountCreated as MAccount
484 async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
485 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
488 description: result.summary,
489 support: result.support,
491 accountId: ownerActor.Account.id
499 return videoChannelCreated as MChannel