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