]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/actor.ts
Fix tests
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / actor.ts
CommitLineData
50d6de9c
C
1import * as Bluebird from 'bluebird'
2import { Transaction } from 'sequelize'
3import * as url from 'url'
c5911fd3 4import * as uuidv4 from 'uuid/v4'
50d6de9c
C
5import { ActivityPubActor, ActivityPubActorType } from '../../../shared/models/activitypub'
6import { ActivityPubAttributedTo } from '../../../shared/models/activitypub/objects'
848f499d 7import { checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
9977c128 8import { sanitizeAndCheckActorObject } from '../../helpers/custom-validators/activitypub/actor'
c5911fd3 9import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
a5625b41 10import { retryTransactionWrapper, updateInstanceWithAnother } from '../../helpers/database-utils'
da854ddd
C
11import { logger } from '../../helpers/logger'
12import { createPrivateAndPublicKeys } from '../../helpers/peertube-crypto'
557b13ae 13import { doRequest } from '../../helpers/requests'
a5625b41 14import { getUrlFromWebfinger } from '../../helpers/webfinger'
557b13ae 15import { MIMETYPES, WEBSERVER } from '../../initializers/constants'
50d6de9c
C
16import { AccountModel } from '../../models/account/account'
17import { ActorModel } from '../../models/activitypub/actor'
c5911fd3 18import { AvatarModel } from '../../models/avatar/avatar'
50d6de9c
C
19import { ServerModel } from '../../models/server/server'
20import { VideoChannelModel } from '../../models/video/video-channel'
16f29007
C
21import { JobQueue } from '../job-queue'
22import { getServerActor } from '../../helpers/utils'
e587e0ec 23import { ActorFetchByUrlType, fetchActorByUrl } from '../../helpers/actor'
74dc3bca 24import { sequelizeTypescript } from '../../initializers/database'
453e83ea
C
25import {
26 MAccount,
27 MActor,
28 MActorAccountChannelId,
29 MActorAccountId,
30 MActorDefault,
31 MActorFull,
32 MActorId,
33 MActorAccountChannelIdActor,
34 MChannel,
35 MActorFullActor, MAccountActorDefault, MChannelActorDefault, MChannelActorAccountDefault
36} from '../../typings/models'
50d6de9c 37
e12a0092 38// Set account keys, this could be long so process after the account creation and do not block the client
453e83ea 39function setAsyncActorKeys (actor: MActor) {
50d6de9c
C
40 return createPrivateAndPublicKeys()
41 .then(({ publicKey, privateKey }) => {
453e83ea
C
42 actor.publicKey = publicKey
43 actor.privateKey = privateKey
50d6de9c
C
44 return actor.save()
45 })
46 .catch(err => {
57cfff78 47 logger.error('Cannot set public/private keys of actor %d.', actor.url, { err })
50d6de9c
C
48 return actor
49 })
50}
51
453e83ea
C
52function getOrCreateActorAndServerAndModel (
53 activityActor: string | ActivityPubActor,
54 fetchType: 'all',
55 recurseIfNeeded?: boolean,
56 updateCollections?: boolean
57): Promise<MActorFullActor>
58
59function getOrCreateActorAndServerAndModel (
60 activityActor: string | ActivityPubActor,
61 fetchType?: 'association-ids',
62 recurseIfNeeded?: boolean,
63 updateCollections?: boolean
64): Promise<MActorAccountChannelId>
65
687d638c
C
66async function getOrCreateActorAndServerAndModel (
67 activityActor: string | ActivityPubActor,
453e83ea 68 fetchType: ActorFetchByUrlType = 'association-ids',
687d638c
C
69 recurseIfNeeded = true,
70 updateCollections = false
453e83ea 71): Promise<MActorFullActor | MActorAccountChannelId> {
848f499d 72 const actorUrl = getAPId(activityActor)
687d638c 73 let created = false
418d092a 74 let accountPlaylistsUrl: string
6be84cbc 75
e587e0ec 76 let actor = await fetchActorByUrl(actorUrl, fetchType)
25e4d6ee 77 // Orphan actor (not associated to an account of channel) so recreate it
6104adc3 78 if (actor && (!actor.Account && !actor.VideoChannel)) {
25e4d6ee
C
79 await actor.destroy()
80 actor = null
81 }
50d6de9c
C
82
83 // We don't have this actor in our database, fetch it on remote
84 if (!actor) {
f5b0af50 85 const { result } = await fetchRemoteActor(actorUrl)
601527d7 86 if (result === undefined) throw new Error('Cannot fetch remote actor ' + actorUrl)
50d6de9c
C
87
88 // Create the attributed to actor
89 // In PeerTube a video channel is owned by an account
453e83ea 90 let ownerActor: MActorFullActor
50d6de9c
C
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)
94
5c6d985f
C
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}`)
97 }
98
50d6de9c 99 try {
5c6d985f 100 // Don't recurse another time
418d092a
C
101 const recurseIfNeeded = false
102 ownerActor = await getOrCreateActorAndServerAndModel(accountAttributedTo.id, 'all', recurseIfNeeded)
50d6de9c
C
103 } catch (err) {
104 logger.error('Cannot get or create account attributed to video channel ' + actor.url)
105 throw new Error(err)
106 }
107 }
108
90d4bb81 109 actor = await retryTransactionWrapper(saveActorAndServerAndModelIfNotExist, result, ownerActor)
687d638c 110 created = true
418d092a 111 accountPlaylistsUrl = result.playlists
50d6de9c
C
112 }
113
453e83ea
C
114 if (actor.Account) (actor as MActorAccountChannelIdActor).Account.Actor = actor
115 if (actor.VideoChannel) (actor as MActorAccountChannelIdActor).VideoChannel.Actor = actor
d9bdd007 116
e587e0ec 117 const { actor: actorRefreshed, refreshed } = await retryTransactionWrapper(refreshActorIfNeeded, actor, fetchType)
687d638c 118 if (!actorRefreshed) throw new Error('Actor ' + actorRefreshed.url + ' does not exist anymore.')
f5b0af50 119
687d638c
C
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 })
123 }
124
418d092a
C
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 })
129 }
130
687d638c 131 return actorRefreshed
50d6de9c
C
132}
133
c5911fd3
C
134function buildActorInstance (type: ActivityPubActorType, url: string, preferredUsername: string, uuid?: string) {
135 return new ActorModel({
136 type,
137 url,
138 preferredUsername,
139 uuid,
140 publicKey: null,
141 privateKey: null,
142 followersCount: 0,
143 followingCount: 0,
144 inboxUrl: url + '/inbox',
145 outboxUrl: url + '/outbox',
6dd9de95 146 sharedInboxUrl: WEBSERVER.URL + '/inbox',
c5911fd3
C
147 followersUrl: url + '/followers',
148 followingUrl: url + '/following'
149 })
150}
151
a5625b41
C
152async function updateActorInstance (actorInstance: ActorModel, attributes: ActivityPubActor) {
153 const followersCount = await fetchActorTotalItems(attributes.followers)
154 const followingCount = await fetchActorTotalItems(attributes.following)
155
57cfff78
C
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
a5625b41
C
167}
168
453e83ea
C
169type AvatarInfo = { name: string, onDisk: boolean, fileUrl: string }
170async function updateActorAvatarInstance (actor: MActorDefault, info: AvatarInfo, t: Transaction) {
557b13ae
C
171 if (info.name !== undefined) {
172 if (actor.avatarId) {
a5625b41 173 try {
557b13ae 174 await actor.Avatar.destroy({ transaction: t })
a5625b41 175 } catch (err) {
557b13ae 176 logger.error('Cannot remove old avatar of actor %s.', actor.url, { err })
a5625b41
C
177 }
178 }
179
180 const avatar = await AvatarModel.create({
557b13ae
C
181 filename: info.name,
182 onDisk: info.onDisk,
183 fileUrl: info.fileUrl
a5625b41
C
184 }, { transaction: t })
185
557b13ae
C
186 actor.avatarId = avatar.id
187 actor.Avatar = avatar
a5625b41
C
188 }
189
557b13ae 190 return actor
a5625b41
C
191}
192
265ba139
C
193async function fetchActorTotalItems (url: string) {
194 const options = {
195 uri: url,
196 method: 'GET',
197 json: true,
198 activityPub: true
199 }
200
265ba139 201 try {
7006bc63
C
202 const { body } = await doRequest(options)
203 return body.totalItems ? body.totalItems : 0
265ba139 204 } catch (err) {
d5b7d911 205 logger.warn('Cannot fetch remote actor count %s.', url, { err })
7006bc63 206 return 0
265ba139 207 }
265ba139
C
208}
209
557b13ae 210async function getAvatarInfoIfExists (actorJSON: ActivityPubActor) {
265ba139 211 if (
14e2014a 212 actorJSON.icon && actorJSON.icon.type === 'Image' && MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType] !== undefined &&
265ba139
C
213 isActivityPubUrlValid(actorJSON.icon.url)
214 ) {
14e2014a 215 const extension = MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType]
265ba139 216
557b13ae
C
217 return {
218 name: uuidv4() + extension,
219 fileUrl: actorJSON.icon.url
220 }
265ba139
C
221 }
222
223 return undefined
224}
225
5224c394 226async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
16f29007
C
227 // Don't fetch ourselves
228 const serverActor = await getServerActor()
229 if (serverActor.id === actor.id) {
230 logger.error('Cannot fetch our own outbox!')
231 return undefined
232 }
233
234 const payload = {
f6eebcb3
C
235 uri: actor.outboxUrl,
236 type: 'activity' as 'activity'
16f29007
C
237 }
238
239 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
240}
241
453e83ea
C
242async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
243 actorArg: T,
744d0eca 244 fetchedType: ActorFetchByUrlType
453e83ea 245): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
744d0eca
C
246 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
247
248 // We need more attributes
453e83ea
C
249 const actor = fetchedType === 'all'
250 ? actorArg as MActorFull
251 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
744d0eca
C
252
253 try {
699b059e
C
254 let actorUrl: string
255 try {
256 actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
257 } catch (err) {
258 logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
259 actorUrl = actor.url
260 }
261
744d0eca
C
262 const { result, statusCode } = await fetchRemoteActor(actorUrl)
263
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 }
268 }
269
270 if (result === undefined) {
271 logger.warn('Cannot fetch remote actor in refresh actor.')
272 return { actor, refreshed: false }
273 }
274
275 return sequelizeTypescript.transaction(async t => {
276 updateInstanceWithAnother(actor, result.actor)
277
557b13ae
C
278 if (result.avatar !== undefined) {
279 const avatarInfo = {
280 name: result.avatar.name,
281 fileUrl: result.avatar.fileUrl,
282 onDisk: false
283 }
284
285 await updateActorAvatarInstance(actor, avatarInfo, t)
744d0eca
C
286 }
287
288 // Force update
289 actor.setDataValue('updatedAt', new Date())
290 await actor.save({ transaction: t })
291
292 if (actor.Account) {
6b9c966f
C
293 actor.Account.name = result.name
294 actor.Account.description = result.summary
744d0eca
C
295
296 await actor.Account.save({ transaction: t })
297 } else if (actor.VideoChannel) {
6b9c966f
C
298 actor.VideoChannel.name = result.name
299 actor.VideoChannel.description = result.summary
300 actor.VideoChannel.support = result.support
744d0eca
C
301
302 await actor.VideoChannel.save({ transaction: t })
303 }
304
305 return { refreshed: true, actor }
306 })
307 } catch (err) {
4ee7a4c9 308 logger.warn('Cannot refresh actor %s.', actor.url, { err })
744d0eca
C
309 return { actor, refreshed: false }
310 }
311}
312
c5911fd3
C
313export {
314 getOrCreateActorAndServerAndModel,
315 buildActorInstance,
265ba139
C
316 setAsyncActorKeys,
317 fetchActorTotalItems,
557b13ae 318 getAvatarInfoIfExists,
a5625b41 319 updateActorInstance,
744d0eca 320 refreshActorIfNeeded,
16f29007
C
321 updateActorAvatarInstance,
322 addFetchOutboxJob
c5911fd3
C
323}
324
325// ---------------------------------------------------------------------------
326
50d6de9c
C
327function saveActorAndServerAndModelIfNotExist (
328 result: FetchRemoteActorResult,
453e83ea 329 ownerActor?: MActorFullActor,
50d6de9c 330 t?: Transaction
453e83ea 331): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
50d6de9c
C
332 let actor = result.actor
333
334 if (t !== undefined) return save(t)
335
336 return sequelizeTypescript.transaction(t => save(t))
337
338 async function save (t: Transaction) {
339 const actorHost = url.parse(actor.url).host
340
341 const serverOptions = {
342 where: {
343 host: actorHost
344 },
345 defaults: {
346 host: actorHost
347 },
348 transaction: t
349 }
350 const [ server ] = await ServerModel.findOrCreate(serverOptions)
351
352 // Save our new account in database
557b13ae 353 actor.serverId = server.id
50d6de9c 354
c5911fd3 355 // Avatar?
557b13ae 356 if (result.avatar) {
c5911fd3 357 const avatar = await AvatarModel.create({
557b13ae
C
358 filename: result.avatar.name,
359 fileUrl: result.avatar.fileUrl,
360 onDisk: false
c5911fd3 361 }, { transaction: t })
557b13ae
C
362
363 actor.avatarId = avatar.id
c5911fd3
C
364 }
365
50d6de9c
C
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)
453e83ea 368 const [ actorCreated ] = await ActorModel.findOrCreate<MActorFullActor>({
2c897999
C
369 defaults: actor.toJSON(),
370 where: {
371 url: actor.url
372 },
373 transaction: t
374 })
50d6de9c
C
375
376 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
453e83ea 377 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountActorDefault
50d6de9c
C
378 actorCreated.Account.Actor = actorCreated
379 } else if (actorCreated.type === 'Group') { // Video channel
453e83ea 380 actorCreated.VideoChannel = await saveVideoChannel(actorCreated, result, ownerActor, t) as MChannelActorAccountDefault
50d6de9c 381 actorCreated.VideoChannel.Actor = actorCreated
f6eebcb3 382 actorCreated.VideoChannel.Account = ownerActor.Account
50d6de9c
C
383 }
384
883993c8
C
385 actorCreated.Server = server
386
50d6de9c
C
387 return actorCreated
388 }
389}
390
391type FetchRemoteActorResult = {
453e83ea 392 actor: MActor
e12a0092 393 name: string
50d6de9c 394 summary: string
2422c46b 395 support?: string
418d092a 396 playlists?: string
557b13ae
C
397 avatar?: {
398 name: string,
399 fileUrl: string
400 }
50d6de9c
C
401 attributedTo: ActivityPubAttributedTo[]
402}
f5b0af50 403async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
50d6de9c
C
404 const options = {
405 uri: actorUrl,
406 method: 'GET',
da854ddd
C
407 json: true,
408 activityPub: true
50d6de9c
C
409 }
410
411 logger.info('Fetching remote actor %s.', actorUrl)
412
4c280004 413 const requestResult = await doRequest<ActivityPubActor>(options)
4c280004 414 const actorJSON = requestResult.body
9977c128
C
415
416 if (sanitizeAndCheckActorObject(actorJSON) === false) {
b4593cd7 417 logger.debug('Remote actor JSON is not valid.', { actorJSON })
f5b0af50 418 return { result: undefined, statusCode: requestResult.response.statusCode }
50d6de9c
C
419 }
420
5c6d985f 421 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
9f79ade6
C
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 }
5c6d985f
C
424 }
425
50d6de9c
C
426 const followersCount = await fetchActorTotalItems(actorJSON.followers)
427 const followingCount = await fetchActorTotalItems(actorJSON.following)
428
429 const actor = new ActorModel({
430 type: actorJSON.type,
e12a0092
C
431 preferredUsername: actorJSON.preferredUsername,
432 url: actorJSON.id,
50d6de9c
C
433 publicKey: actorJSON.publicKey.publicKeyPem,
434 privateKey: null,
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
442 })
443
557b13ae 444 const avatarInfo = await getAvatarInfoIfExists(actorJSON)
c5911fd3 445
e12a0092 446 const name = actorJSON.name || actorJSON.preferredUsername
50d6de9c 447 return {
f5b0af50
C
448 statusCode: requestResult.response.statusCode,
449 result: {
450 actor,
451 name,
557b13ae 452 avatar: avatarInfo,
f5b0af50
C
453 summary: actorJSON.summary,
454 support: actorJSON.support,
418d092a 455 playlists: actorJSON.playlists,
f5b0af50
C
456 attributedTo: actorJSON.attributedTo
457 }
50d6de9c
C
458 }
459}
460
453e83ea 461async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
2c897999
C
462 const [ accountCreated ] = await AccountModel.findOrCreate({
463 defaults: {
464 name: result.name,
2422c46b 465 description: result.summary,
2c897999
C
466 actorId: actor.id
467 },
468 where: {
469 actorId: actor.id
470 },
471 transaction: t
50d6de9c
C
472 })
473
453e83ea 474 return accountCreated as MAccount
50d6de9c
C
475}
476
453e83ea 477async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
2c897999
C
478 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
479 defaults: {
480 name: result.name,
481 description: result.summary,
2422c46b 482 support: result.support,
2c897999
C
483 actorId: actor.id,
484 accountId: ownerActor.Account.id
485 },
486 where: {
487 actorId: actor.id
488 },
489 transaction: t
50d6de9c
C
490 })
491
453e83ea 492 return videoChannelCreated as MChannel
50d6de9c 493}