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'
28 MActorAccountChannelId,
33 MActorAccountChannelIdActor,
35 MActorFullActor, MAccountActorDefault, MChannelActorDefault, MChannelActorAccountDefault
36 } from '../../typings/models'
38 // Set account keys, this could be long so process after the account creation and do not block the client
39 function setAsyncActorKeys (actor: MActor) {
40 return createPrivateAndPublicKeys()
41 .then(({ publicKey, privateKey }) => {
42 actor.publicKey = publicKey
43 actor.privateKey = privateKey
47 logger.error('Cannot set public/private keys of actor %d.', actor.url, { err })
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 ' + actor.url)
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 ' + actorRefreshed.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.createJob({ 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.createJob({ 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.sharedInboxUrl = attributes.endpoints.sharedInbox
165 actorInstance.followersUrl = attributes.followers
166 actorInstance.followingUrl = attributes.following
169 type AvatarInfo = { name: string, onDisk: boolean, fileUrl: string }
170 async function updateActorAvatarInstance (actor: MActorDefault, info: AvatarInfo, t: Transaction) {
171 if (info.name !== undefined) {
172 if (actor.avatarId) {
174 await actor.Avatar.destroy({ transaction: t })
176 logger.error('Cannot remove old avatar of actor %s.', actor.url, { err })
180 const avatar = await AvatarModel.create({
183 fileUrl: info.fileUrl
184 }, { transaction: t })
186 actor.avatarId = avatar.id
187 actor.Avatar = avatar
193 async function fetchActorTotalItems (url: string) {
202 const { body } = await doRequest(options)
203 return body.totalItems ? body.totalItems : 0
205 logger.warn('Cannot fetch remote actor count %s.', url, { err })
210 async function getAvatarInfoIfExists (actorJSON: ActivityPubActor) {
212 actorJSON.icon && actorJSON.icon.type === 'Image' && MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType] !== undefined &&
213 isActivityPubUrlValid(actorJSON.icon.url)
215 const extension = MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType]
218 name: uuidv4() + extension,
219 fileUrl: actorJSON.icon.url
226 async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
227 // Don't fetch ourselves
228 const serverActor = await getServerActor()
229 if (serverActor.id === actor.id) {
230 logger.error('Cannot fetch our own outbox!')
235 uri: actor.outboxUrl,
236 type: 'activity' as 'activity'
239 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
242 async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
244 fetchedType: ActorFetchByUrlType
245 ): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
246 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
248 // We need more attributes
249 const actor = fetchedType === 'all'
250 ? actorArg as MActorFull
251 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
256 actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
258 logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
262 const { result, statusCode } = await fetchRemoteActor(actorUrl)
264 if (statusCode === 404) {
265 logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
266 actor.Account ? actor.Account.destroy() : actor.VideoChannel.destroy()
267 return { actor: undefined, refreshed: false }
270 if (result === undefined) {
271 logger.warn('Cannot fetch remote actor in refresh actor.')
272 return { actor, refreshed: false }
275 return sequelizeTypescript.transaction(async t => {
276 updateInstanceWithAnother(actor, result.actor)
278 if (result.avatar !== undefined) {
280 name: result.avatar.name,
281 fileUrl: result.avatar.fileUrl,
285 await updateActorAvatarInstance(actor, avatarInfo, t)
289 actor.setDataValue('updatedAt', new Date())
290 await actor.save({ transaction: t })
293 actor.Account.name = result.name
294 actor.Account.description = result.summary
296 await actor.Account.save({ transaction: t })
297 } else if (actor.VideoChannel) {
298 actor.VideoChannel.name = result.name
299 actor.VideoChannel.description = result.summary
300 actor.VideoChannel.support = result.support
302 await actor.VideoChannel.save({ transaction: t })
305 return { refreshed: true, actor }
308 logger.warn('Cannot refresh actor %s.', actor.url, { err })
309 return { actor, refreshed: false }
314 getOrCreateActorAndServerAndModel,
317 fetchActorTotalItems,
318 getAvatarInfoIfExists,
320 refreshActorIfNeeded,
321 updateActorAvatarInstance,
325 // ---------------------------------------------------------------------------
327 function saveActorAndServerAndModelIfNotExist (
328 result: FetchRemoteActorResult,
329 ownerActor?: MActorFullActor,
331 ): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
332 let actor = result.actor
334 if (t !== undefined) return save(t)
336 return sequelizeTypescript.transaction(t => save(t))
338 async function save (t: Transaction) {
339 const actorHost = url.parse(actor.url).host
341 const serverOptions = {
350 const [ server ] = await ServerModel.findOrCreate(serverOptions)
352 // Save our new account in database
353 actor.serverId = server.id
357 const avatar = await AvatarModel.create({
358 filename: result.avatar.name,
359 fileUrl: result.avatar.fileUrl,
361 }, { transaction: t })
363 actor.avatarId = avatar.id
366 // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
367 // (which could be false in a retried query)
368 const [ actorCreated ] = await ActorModel.findOrCreate<MActorFullActor>({
369 defaults: actor.toJSON(),
376 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
377 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountActorDefault
378 actorCreated.Account.Actor = actorCreated
379 } else if (actorCreated.type === 'Group') { // Video channel
380 actorCreated.VideoChannel = await saveVideoChannel(actorCreated, result, ownerActor, t) as MChannelActorAccountDefault
381 actorCreated.VideoChannel.Actor = actorCreated
382 actorCreated.VideoChannel.Account = ownerActor.Account
385 actorCreated.Server = server
391 type FetchRemoteActorResult = {
401 attributedTo: ActivityPubAttributedTo[]
403 async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
411 logger.info('Fetching remote actor %s.', actorUrl)
413 const requestResult = await doRequest<ActivityPubActor>(options)
414 const actorJSON = requestResult.body
416 if (sanitizeAndCheckActorObject(actorJSON) === false) {
417 logger.debug('Remote actor JSON is not valid.', { actorJSON })
418 return { result: undefined, statusCode: requestResult.response.statusCode }
421 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
422 logger.warn('Actor url %s has not the same host than its AP id %s', actorUrl, actorJSON.id)
423 return { result: undefined, statusCode: requestResult.response.statusCode }
426 const followersCount = await fetchActorTotalItems(actorJSON.followers)
427 const followingCount = await fetchActorTotalItems(actorJSON.following)
429 const actor = new ActorModel({
430 type: actorJSON.type,
431 preferredUsername: actorJSON.preferredUsername,
433 publicKey: actorJSON.publicKey.publicKeyPem,
435 followersCount: followersCount,
436 followingCount: followingCount,
437 inboxUrl: actorJSON.inbox,
438 outboxUrl: actorJSON.outbox,
439 sharedInboxUrl: actorJSON.endpoints.sharedInbox,
440 followersUrl: actorJSON.followers,
441 followingUrl: actorJSON.following
444 const avatarInfo = await getAvatarInfoIfExists(actorJSON)
446 const name = actorJSON.name || actorJSON.preferredUsername
448 statusCode: requestResult.response.statusCode,
453 summary: actorJSON.summary,
454 support: actorJSON.support,
455 playlists: actorJSON.playlists,
456 attributedTo: actorJSON.attributedTo
461 async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
462 const [ accountCreated ] = await AccountModel.findOrCreate({
465 description: result.summary,
474 return accountCreated as MAccount
477 async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
478 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
481 description: result.summary,
482 support: result.support,
484 accountId: ownerActor.Account.id
492 return videoChannelCreated as MChannel