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