]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/actor.ts
Add banners support
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / actor.ts
1 import * as Bluebird from 'bluebird'
2 import { extname } from 'path'
3 import { Op, Transaction } from 'sequelize'
4 import { URL } from 'url'
5 import { v4 as uuidv4 } from 'uuid'
6 import { getServerActor } from '@server/models/application/application'
7 import { ActorImageType } from '@shared/models'
8 import { HttpStatusCode } from '../../../shared/core-utils/miscs/http-error-codes'
9 import { ActivityPubActor, ActivityPubActorType, ActivityPubOrderedCollection } from '../../../shared/models/activitypub'
10 import { ActivityPubAttributedTo } from '../../../shared/models/activitypub/objects'
11 import { checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
12 import { ActorFetchByUrlType, fetchActorByUrl } from '../../helpers/actor'
13 import { sanitizeAndCheckActorObject } from '../../helpers/custom-validators/activitypub/actor'
14 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
15 import { retryTransactionWrapper, updateInstanceWithAnother } from '../../helpers/database-utils'
16 import { logger } from '../../helpers/logger'
17 import { createPrivateAndPublicKeys } from '../../helpers/peertube-crypto'
18 import { doJSONRequest, PeerTubeRequestError } from '../../helpers/requests'
19 import { getUrlFromWebfinger } from '../../helpers/webfinger'
20 import { MIMETYPES, WEBSERVER } from '../../initializers/constants'
21 import { sequelizeTypescript } from '../../initializers/database'
22 import { AccountModel } from '../../models/account/account'
23 import { ActorImageModel } from '../../models/account/actor-image'
24 import { ActorModel } from '../../models/activitypub/actor'
25 import { ServerModel } from '../../models/server/server'
26 import { VideoChannelModel } from '../../models/video/video-channel'
27 import {
28 MAccount,
29 MAccountDefault,
30 MActor,
31 MActorAccountChannelId,
32 MActorAccountChannelIdActor,
33 MActorAccountId,
34 MActorFull,
35 MActorFullActor,
36 MActorId,
37 MActorImages,
38 MChannel
39 } from '../../types/models'
40 import { JobQueue } from '../job-queue'
41
42 // Set account keys, this could be long so process after the account creation and do not block the client
43 async function generateAndSaveActorKeys <T extends MActor> (actor: T) {
44 const { publicKey, privateKey } = await createPrivateAndPublicKeys()
45
46 actor.publicKey = publicKey
47 actor.privateKey = privateKey
48
49 return actor.save()
50 }
51
52 function getOrCreateActorAndServerAndModel (
53 activityActor: string | ActivityPubActor,
54 fetchType: 'all',
55 recurseIfNeeded?: boolean,
56 updateCollections?: boolean
57 ): Promise<MActorFullActor>
58
59 function getOrCreateActorAndServerAndModel (
60 activityActor: string | ActivityPubActor,
61 fetchType?: 'association-ids',
62 recurseIfNeeded?: boolean,
63 updateCollections?: boolean
64 ): Promise<MActorAccountChannelId>
65
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)
73 let created = false
74 let accountPlaylistsUrl: string
75
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)) {
79 await actor.destroy()
80 actor = null
81 }
82
83 // We don't have this actor in our database, fetch it on remote
84 if (!actor) {
85 const { result } = await fetchRemoteActor(actorUrl)
86 if (result === undefined) throw new Error('Cannot fetch remote actor ' + actorUrl)
87
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)
94
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
99 try {
100 // Don't recurse another time
101 const recurseIfNeeded = false
102 ownerActor = await getOrCreateActorAndServerAndModel(accountAttributedTo.id, 'all', recurseIfNeeded)
103 } catch (err) {
104 logger.error('Cannot get or create account attributed to video channel ' + actorUrl)
105 throw new Error(err)
106 }
107 }
108
109 actor = await retryTransactionWrapper(saveActorAndServerAndModelIfNotExist, result, ownerActor)
110 created = true
111 accountPlaylistsUrl = result.playlists
112 }
113
114 if (actor.Account) (actor as MActorAccountChannelIdActor).Account.Actor = actor
115 if (actor.VideoChannel) (actor as MActorAccountChannelIdActor).VideoChannel.Actor = actor
116
117 const { actor: actorRefreshed, refreshed } = await retryTransactionWrapper(refreshActorIfNeeded, actor, fetchType)
118 if (!actorRefreshed) throw new Error('Actor ' + actor.url + ' does not exist anymore.')
119
120 if ((created === true || refreshed === true) && updateCollections === true) {
121 const payload = { uri: actor.outboxUrl, type: 'activity' as 'activity' }
122 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
123 }
124
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.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
129 }
130
131 return actorRefreshed
132 }
133
134 function 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',
146 sharedInboxUrl: WEBSERVER.URL + '/inbox',
147 followersUrl: url + '/followers',
148 followingUrl: url + '/following'
149 }) as MActor
150 }
151
152 async function updateActorInstance (actorInstance: ActorModel, attributes: ActivityPubActor) {
153 const followersCount = await fetchActorTotalItems(attributes.followers)
154 const followingCount = await fetchActorTotalItems(attributes.following)
155
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.followersUrl = attributes.followers
165 actorInstance.followingUrl = attributes.following
166
167 if (attributes.endpoints?.sharedInbox) {
168 actorInstance.sharedInboxUrl = attributes.endpoints.sharedInbox
169 }
170 }
171
172 type AvatarInfo = { name: string, onDisk: boolean, fileUrl: string, type: ActorImageType }
173 async function updateActorImageInstance (actor: MActorImages, info: AvatarInfo, t: Transaction) {
174 if (!info.name) return actor
175
176 const oldImageModel = info.type === ActorImageType.AVATAR
177 ? actor.Avatar
178 : actor.Banner
179
180 if (oldImageModel) {
181 // Don't update the avatar if the file URL did not change
182 if (info.fileUrl && oldImageModel.fileUrl === info.fileUrl) return actor
183
184 try {
185 await oldImageModel.destroy({ transaction: t })
186 } catch (err) {
187 logger.error('Cannot remove old actor image of actor %s.', actor.url, { err })
188 }
189 }
190
191 const imageModel = await ActorImageModel.create({
192 filename: info.name,
193 onDisk: info.onDisk,
194 fileUrl: info.fileUrl,
195 type: info.type
196 }, { transaction: t })
197
198 if (info.type === ActorImageType.AVATAR) {
199 actor.avatarId = imageModel.id
200 actor.Avatar = imageModel
201 } else {
202 actor.bannerId = imageModel.id
203 actor.Banner = imageModel
204 }
205
206 return actor
207 }
208
209 async function deleteActorImageInstance (actor: MActorImages, type: ActorImageType, t: Transaction) {
210 try {
211 if (type === ActorImageType.AVATAR) {
212 await actor.Avatar.destroy({ transaction: t })
213
214 actor.avatarId = null
215 actor.Avatar = null
216 } else {
217 await actor.Banner.destroy({ transaction: t })
218
219 actor.bannerId = null
220 actor.Banner = null
221 }
222 } catch (err) {
223 logger.error('Cannot remove old image of actor %s.', actor.url, { err })
224 }
225
226 return actor
227 }
228
229 async function fetchActorTotalItems (url: string) {
230 try {
231 const { body } = await doJSONRequest<ActivityPubOrderedCollection<unknown>>(url, { activityPub: true })
232
233 return body.totalItems || 0
234 } catch (err) {
235 logger.warn('Cannot fetch remote actor count %s.', url, { err })
236 return 0
237 }
238 }
239
240 function getImageInfoIfExists (actorJSON: ActivityPubActor, type: ActorImageType) {
241 const mimetypes = MIMETYPES.IMAGE
242 const icon = type === ActorImageType.AVATAR
243 ? actorJSON.icon
244 : actorJSON.image
245
246 if (!icon || icon.type !== 'Image' || !isActivityPubUrlValid(icon.url)) return undefined
247
248 let extension: string
249
250 if (icon.mediaType) {
251 extension = mimetypes.MIMETYPE_EXT[icon.mediaType]
252 } else {
253 const tmp = extname(icon.url)
254
255 if (mimetypes.EXT_MIMETYPE[tmp] !== undefined) extension = tmp
256 }
257
258 if (!extension) return undefined
259
260 return {
261 name: uuidv4() + extension,
262 fileUrl: icon.url,
263 type
264 }
265 }
266
267 async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
268 // Don't fetch ourselves
269 const serverActor = await getServerActor()
270 if (serverActor.id === actor.id) {
271 logger.error('Cannot fetch our own outbox!')
272 return undefined
273 }
274
275 const payload = {
276 uri: actor.outboxUrl,
277 type: 'activity' as 'activity'
278 }
279
280 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
281 }
282
283 async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
284 actorArg: T,
285 fetchedType: ActorFetchByUrlType
286 ): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
287 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
288
289 // We need more attributes
290 const actor = fetchedType === 'all'
291 ? actorArg as MActorFull
292 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
293
294 try {
295 let actorUrl: string
296 try {
297 actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
298 } catch (err) {
299 logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
300 actorUrl = actor.url
301 }
302
303 const { result } = await fetchRemoteActor(actorUrl)
304
305 if (result === undefined) {
306 logger.warn('Cannot fetch remote actor in refresh actor.')
307 return { actor, refreshed: false }
308 }
309
310 return sequelizeTypescript.transaction(async t => {
311 updateInstanceWithAnother(actor, result.actor)
312
313 if (result.avatar !== undefined) {
314 const avatarInfo = {
315 name: result.avatar.name,
316 fileUrl: result.avatar.fileUrl,
317 onDisk: false,
318 type: ActorImageType.AVATAR
319 }
320
321 await updateActorImageInstance(actor, avatarInfo, t)
322 }
323
324 if (result.banner !== undefined) {
325 const bannerInfo = {
326 name: result.banner.name,
327 fileUrl: result.banner.fileUrl,
328 onDisk: false,
329 type: ActorImageType.BANNER
330 }
331
332 await updateActorImageInstance(actor, bannerInfo, t)
333 }
334
335 // Force update
336 actor.setDataValue('updatedAt', new Date())
337 await actor.save({ transaction: t })
338
339 if (actor.Account) {
340 actor.Account.name = result.name
341 actor.Account.description = result.summary
342
343 await actor.Account.save({ transaction: t })
344 } else if (actor.VideoChannel) {
345 actor.VideoChannel.name = result.name
346 actor.VideoChannel.description = result.summary
347 actor.VideoChannel.support = result.support
348
349 await actor.VideoChannel.save({ transaction: t })
350 }
351
352 return { refreshed: true, actor }
353 })
354 } catch (err) {
355 if ((err as PeerTubeRequestError).statusCode === HttpStatusCode.NOT_FOUND_404) {
356 logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
357 actor.Account
358 ? await actor.Account.destroy()
359 : await actor.VideoChannel.destroy()
360
361 return { actor: undefined, refreshed: false }
362 }
363
364 logger.warn('Cannot refresh actor %s.', actor.url, { err })
365 return { actor, refreshed: false }
366 }
367 }
368
369 export {
370 getOrCreateActorAndServerAndModel,
371 buildActorInstance,
372 generateAndSaveActorKeys,
373 fetchActorTotalItems,
374 getImageInfoIfExists,
375 updateActorInstance,
376 deleteActorImageInstance,
377 refreshActorIfNeeded,
378 updateActorImageInstance,
379 addFetchOutboxJob
380 }
381
382 // ---------------------------------------------------------------------------
383
384 function saveActorAndServerAndModelIfNotExist (
385 result: FetchRemoteActorResult,
386 ownerActor?: MActorFullActor,
387 t?: Transaction
388 ): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
389 const actor = result.actor
390
391 if (t !== undefined) return save(t)
392
393 return sequelizeTypescript.transaction(t => save(t))
394
395 async function save (t: Transaction) {
396 const actorHost = new URL(actor.url).host
397
398 const serverOptions = {
399 where: {
400 host: actorHost
401 },
402 defaults: {
403 host: actorHost
404 },
405 transaction: t
406 }
407 const [ server ] = await ServerModel.findOrCreate(serverOptions)
408
409 // Save our new account in database
410 actor.serverId = server.id
411
412 // Avatar?
413 if (result.avatar) {
414 const avatar = await ActorImageModel.create({
415 filename: result.avatar.name,
416 fileUrl: result.avatar.fileUrl,
417 onDisk: false,
418 type: ActorImageType.AVATAR
419 }, { transaction: t })
420
421 actor.avatarId = avatar.id
422 }
423
424 // Banner?
425 if (result.banner) {
426 const banner = await ActorImageModel.create({
427 filename: result.banner.name,
428 fileUrl: result.banner.fileUrl,
429 onDisk: false,
430 type: ActorImageType.BANNER
431 }, { transaction: t })
432
433 actor.bannerId = banner.id
434 }
435
436 // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
437 // (which could be false in a retried query)
438 const [ actorCreated, created ] = await ActorModel.findOrCreate<MActorFullActor>({
439 defaults: actor.toJSON(),
440 where: {
441 [Op.or]: [
442 {
443 url: actor.url
444 },
445 {
446 serverId: actor.serverId,
447 preferredUsername: actor.preferredUsername
448 }
449 ]
450 },
451 transaction: t
452 })
453
454 // Try to fix non HTTPS accounts of remote instances that fixed their URL afterwards
455 if (created !== true && actorCreated.url !== actor.url) {
456 // Only fix http://example.com/account/djidane to https://example.com/account/djidane
457 if (actorCreated.url.replace(/^http:\/\//, '') !== actor.url.replace(/^https:\/\//, '')) {
458 throw new Error(`Actor from DB with URL ${actorCreated.url} does not correspond to actor ${actor.url}`)
459 }
460
461 actorCreated.url = actor.url
462 await actorCreated.save({ transaction: t })
463 }
464
465 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
466 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountDefault
467 actorCreated.Account.Actor = actorCreated
468 } else if (actorCreated.type === 'Group') { // Video channel
469 const channel = await saveVideoChannel(actorCreated, result, ownerActor, t)
470 actorCreated.VideoChannel = Object.assign(channel, { Actor: actorCreated, Account: ownerActor.Account })
471 }
472
473 actorCreated.Server = server
474
475 return actorCreated
476 }
477 }
478
479 type FetchRemoteActorResult = {
480 actor: MActor
481 name: string
482 summary: string
483 support?: string
484 playlists?: string
485 avatar?: {
486 name: string
487 fileUrl: string
488 }
489 banner?: {
490 name: string
491 fileUrl: string
492 }
493 attributedTo: ActivityPubAttributedTo[]
494 }
495 async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
496 logger.info('Fetching remote actor %s.', actorUrl)
497
498 const requestResult = await doJSONRequest<ActivityPubActor>(actorUrl, { activityPub: true })
499 const actorJSON = requestResult.body
500
501 if (sanitizeAndCheckActorObject(actorJSON) === false) {
502 logger.debug('Remote actor JSON is not valid.', { actorJSON })
503 return { result: undefined, statusCode: requestResult.statusCode }
504 }
505
506 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
507 logger.warn('Actor url %s has not the same host than its AP id %s', actorUrl, actorJSON.id)
508 return { result: undefined, statusCode: requestResult.statusCode }
509 }
510
511 const followersCount = await fetchActorTotalItems(actorJSON.followers)
512 const followingCount = await fetchActorTotalItems(actorJSON.following)
513
514 const actor = new ActorModel({
515 type: actorJSON.type,
516 preferredUsername: actorJSON.preferredUsername,
517 url: actorJSON.id,
518 publicKey: actorJSON.publicKey.publicKeyPem,
519 privateKey: null,
520 followersCount: followersCount,
521 followingCount: followingCount,
522 inboxUrl: actorJSON.inbox,
523 outboxUrl: actorJSON.outbox,
524 followersUrl: actorJSON.followers,
525 followingUrl: actorJSON.following,
526
527 sharedInboxUrl: actorJSON.endpoints?.sharedInbox
528 ? actorJSON.endpoints.sharedInbox
529 : null
530 })
531
532 const avatarInfo = getImageInfoIfExists(actorJSON, ActorImageType.AVATAR)
533 const bannerInfo = getImageInfoIfExists(actorJSON, ActorImageType.BANNER)
534
535 const name = actorJSON.name || actorJSON.preferredUsername
536 return {
537 statusCode: requestResult.statusCode,
538 result: {
539 actor,
540 name,
541 avatar: avatarInfo,
542 banner: bannerInfo,
543 summary: actorJSON.summary,
544 support: actorJSON.support,
545 playlists: actorJSON.playlists,
546 attributedTo: actorJSON.attributedTo
547 }
548 }
549 }
550
551 async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
552 const [ accountCreated ] = await AccountModel.findOrCreate({
553 defaults: {
554 name: result.name,
555 description: result.summary,
556 actorId: actor.id
557 },
558 where: {
559 actorId: actor.id
560 },
561 transaction: t
562 })
563
564 return accountCreated as MAccount
565 }
566
567 async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
568 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
569 defaults: {
570 name: result.name,
571 description: result.summary,
572 support: result.support,
573 actorId: actor.id,
574 accountId: ownerActor.Account.id
575 },
576 where: {
577 actorId: actor.id
578 },
579 transaction: t
580 })
581
582 return videoChannelCreated as MChannel
583 }