]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/actor.ts
Merge branch 'release/2.1.0' into develop
[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
39 // Set account keys, this could be long so process after the account creation and do not block the client
40 function setAsyncActorKeys <T extends MActor> (actor: T) {
41 return createPrivateAndPublicKeys()
42 .then(({ publicKey, privateKey }) => {
43 actor.publicKey = publicKey
44 actor.privateKey = privateKey
45 return actor.save()
46 })
47 .catch(err => {
48 logger.error('Cannot set public/private keys of actor %d.', actor.url, { err })
49 return actor
50 })
51 }
52
53 function getOrCreateActorAndServerAndModel (
54 activityActor: string | ActivityPubActor,
55 fetchType: 'all',
56 recurseIfNeeded?: boolean,
57 updateCollections?: boolean
58 ): Promise<MActorFullActor>
59
60 function getOrCreateActorAndServerAndModel (
61 activityActor: string | ActivityPubActor,
62 fetchType?: 'association-ids',
63 recurseIfNeeded?: boolean,
64 updateCollections?: boolean
65 ): Promise<MActorAccountChannelId>
66
67 async function getOrCreateActorAndServerAndModel (
68 activityActor: string | ActivityPubActor,
69 fetchType: ActorFetchByUrlType = 'association-ids',
70 recurseIfNeeded = true,
71 updateCollections = false
72 ): Promise<MActorFullActor | MActorAccountChannelId> {
73 const actorUrl = getAPId(activityActor)
74 let created = false
75 let accountPlaylistsUrl: string
76
77 let actor = await fetchActorByUrl(actorUrl, fetchType)
78 // Orphan actor (not associated to an account of channel) so recreate it
79 if (actor && (!actor.Account && !actor.VideoChannel)) {
80 await actor.destroy()
81 actor = null
82 }
83
84 // We don't have this actor in our database, fetch it on remote
85 if (!actor) {
86 const { result } = await fetchRemoteActor(actorUrl)
87 if (result === undefined) throw new Error('Cannot fetch remote actor ' + actorUrl)
88
89 // Create the attributed to actor
90 // In PeerTube a video channel is owned by an account
91 let ownerActor: MActorFullActor
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
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
100 try {
101 // Don't recurse another time
102 const recurseIfNeeded = false
103 ownerActor = await getOrCreateActorAndServerAndModel(accountAttributedTo.id, 'all', recurseIfNeeded)
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
110 actor = await retryTransactionWrapper(saveActorAndServerAndModelIfNotExist, result, ownerActor)
111 created = true
112 accountPlaylistsUrl = result.playlists
113 }
114
115 if (actor.Account) (actor as MActorAccountChannelIdActor).Account.Actor = actor
116 if (actor.VideoChannel) (actor as MActorAccountChannelIdActor).VideoChannel.Actor = actor
117
118 const { actor: actorRefreshed, refreshed } = await retryTransactionWrapper(refreshActorIfNeeded, actor, fetchType)
119 if (!actorRefreshed) throw new Error('Actor ' + actorRefreshed.url + ' does not exist anymore.')
120
121 if ((created === true || refreshed === true) && updateCollections === true) {
122 const payload = { uri: actor.outboxUrl, type: 'activity' as 'activity' }
123 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
124 }
125
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' }
129 await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })
130 }
131
132 return actorRefreshed
133 }
134
135 function 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',
147 sharedInboxUrl: WEBSERVER.URL + '/inbox',
148 followersUrl: url + '/followers',
149 followingUrl: url + '/following'
150 }) as MActor
151 }
152
153 async function updateActorInstance (actorInstance: ActorModel, attributes: ActivityPubActor) {
154 const followersCount = await fetchActorTotalItems(attributes.followers)
155 const followingCount = await fetchActorTotalItems(attributes.following)
156
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
165 actorInstance.followersUrl = attributes.followers
166 actorInstance.followingUrl = attributes.following
167
168 if (attributes.endpoints && attributes.endpoints.sharedInbox) {
169 actorInstance.sharedInboxUrl = attributes.endpoints.sharedInbox
170 }
171 }
172
173 type AvatarInfo = { name: string, onDisk: boolean, fileUrl: string }
174 async function updateActorAvatarInstance (actor: MActorDefault, info: AvatarInfo, t: Transaction) {
175 if (!info.name) return actor
176
177 if (actor.Avatar) {
178 // Don't update the avatar if the filename did not change
179 if (actor.Avatar.fileUrl === info.fileUrl) return actor
180
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 }
186 }
187
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
197 return actor
198 }
199
200 async function fetchActorTotalItems (url: string) {
201 const options = {
202 uri: url,
203 method: 'GET',
204 json: true,
205 activityPub: true
206 }
207
208 try {
209 const { body } = await doRequest(options)
210 return body.totalItems ? body.totalItems : 0
211 } catch (err) {
212 logger.warn('Cannot fetch remote actor count %s.', url, { err })
213 return 0
214 }
215 }
216
217 function getAvatarInfoIfExists (actorJSON: ActivityPubActor) {
218 if (
219 actorJSON.icon && actorJSON.icon.type === 'Image' && MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType] !== undefined &&
220 isActivityPubUrlValid(actorJSON.icon.url)
221 ) {
222 const extension = MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType]
223
224 return {
225 name: uuidv4() + extension,
226 fileUrl: actorJSON.icon.url
227 }
228 }
229
230 return undefined
231 }
232
233 async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
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 = {
242 uri: actor.outboxUrl,
243 type: 'activity' as 'activity'
244 }
245
246 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
247 }
248
249 async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
250 actorArg: T,
251 fetchedType: ActorFetchByUrlType
252 ): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
253 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
254
255 // We need more attributes
256 const actor = fetchedType === 'all'
257 ? actorArg as MActorFull
258 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
259
260 try {
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
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)
273 actor.Account
274 ? await actor.Account.destroy()
275 : await actor.VideoChannel.destroy()
276
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
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)
296 }
297
298 // Force update
299 actor.setDataValue('updatedAt', new Date())
300 await actor.save({ transaction: t })
301
302 if (actor.Account) {
303 actor.Account.name = result.name
304 actor.Account.description = result.summary
305
306 await actor.Account.save({ transaction: t })
307 } else if (actor.VideoChannel) {
308 actor.VideoChannel.name = result.name
309 actor.VideoChannel.description = result.summary
310 actor.VideoChannel.support = result.support
311
312 await actor.VideoChannel.save({ transaction: t })
313 }
314
315 return { refreshed: true, actor }
316 })
317 } catch (err) {
318 logger.warn('Cannot refresh actor %s.', actor.url, { err })
319 return { actor, refreshed: false }
320 }
321 }
322
323 export {
324 getOrCreateActorAndServerAndModel,
325 buildActorInstance,
326 setAsyncActorKeys,
327 fetchActorTotalItems,
328 getAvatarInfoIfExists,
329 updateActorInstance,
330 refreshActorIfNeeded,
331 updateActorAvatarInstance,
332 addFetchOutboxJob
333 }
334
335 // ---------------------------------------------------------------------------
336
337 function saveActorAndServerAndModelIfNotExist (
338 result: FetchRemoteActorResult,
339 ownerActor?: MActorFullActor,
340 t?: Transaction
341 ): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
342 const actor = result.actor
343
344 if (t !== undefined) return save(t)
345
346 return sequelizeTypescript.transaction(t => save(t))
347
348 async function save (t: Transaction) {
349 const actorHost = new URL(actor.url).host
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
363 actor.serverId = server.id
364
365 // Avatar?
366 if (result.avatar) {
367 const avatar = await AvatarModel.create({
368 filename: result.avatar.name,
369 fileUrl: result.avatar.fileUrl,
370 onDisk: false
371 }, { transaction: t })
372
373 actor.avatarId = avatar.id
374 }
375
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)
378 const [ actorCreated ] = await ActorModel.findOrCreate<MActorFullActor>({
379 defaults: actor.toJSON(),
380 where: {
381 url: actor.url
382 },
383 transaction: t
384 })
385
386 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
387 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountDefault
388 actorCreated.Account.Actor = actorCreated
389 } else if (actorCreated.type === 'Group') { // Video channel
390 const channel = await saveVideoChannel(actorCreated, result, ownerActor, t)
391 actorCreated.VideoChannel = Object.assign(channel, { Actor: actorCreated, Account: ownerActor.Account })
392 }
393
394 actorCreated.Server = server
395
396 return actorCreated
397 }
398 }
399
400 type FetchRemoteActorResult = {
401 actor: MActor
402 name: string
403 summary: string
404 support?: string
405 playlists?: string
406 avatar?: {
407 name: string
408 fileUrl: string
409 }
410 attributedTo: ActivityPubAttributedTo[]
411 }
412 async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
413 const options = {
414 uri: actorUrl,
415 method: 'GET',
416 json: true,
417 activityPub: true
418 }
419
420 logger.info('Fetching remote actor %s.', actorUrl)
421
422 const requestResult = await doRequest<ActivityPubActor>(options)
423 const actorJSON = requestResult.body
424
425 if (sanitizeAndCheckActorObject(actorJSON) === false) {
426 logger.debug('Remote actor JSON is not valid.', { actorJSON })
427 return { result: undefined, statusCode: requestResult.response.statusCode }
428 }
429
430 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
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 }
433 }
434
435 const followersCount = await fetchActorTotalItems(actorJSON.followers)
436 const followingCount = await fetchActorTotalItems(actorJSON.following)
437
438 const actor = new ActorModel({
439 type: actorJSON.type,
440 preferredUsername: actorJSON.preferredUsername,
441 url: actorJSON.id,
442 publicKey: actorJSON.publicKey.publicKeyPem,
443 privateKey: null,
444 followersCount: followersCount,
445 followingCount: followingCount,
446 inboxUrl: actorJSON.inbox,
447 outboxUrl: actorJSON.outbox,
448 followersUrl: actorJSON.followers,
449 followingUrl: actorJSON.following,
450
451 sharedInboxUrl: actorJSON.endpoints && actorJSON.endpoints.sharedInbox
452 ? actorJSON.endpoints.sharedInbox
453 : null
454 })
455
456 const avatarInfo = await getAvatarInfoIfExists(actorJSON)
457
458 const name = actorJSON.name || actorJSON.preferredUsername
459 return {
460 statusCode: requestResult.response.statusCode,
461 result: {
462 actor,
463 name,
464 avatar: avatarInfo,
465 summary: actorJSON.summary,
466 support: actorJSON.support,
467 playlists: actorJSON.playlists,
468 attributedTo: actorJSON.attributedTo
469 }
470 }
471 }
472
473 async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
474 const [ accountCreated ] = await AccountModel.findOrCreate({
475 defaults: {
476 name: result.name,
477 description: result.summary,
478 actorId: actor.id
479 },
480 where: {
481 actorId: actor.id
482 },
483 transaction: t
484 })
485
486 return accountCreated as MAccount
487 }
488
489 async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
490 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
491 defaults: {
492 name: result.name,
493 description: result.summary,
494 support: result.support,
495 actorId: actor.id,
496 accountId: ownerActor.Account.id
497 },
498 where: {
499 actorId: actor.id
500 },
501 transaction: t
502 })
503
504 return videoChannelCreated as MChannel
505 }