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