]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/lib/activitypub/actor.ts
Fix lint
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / actor.ts
... / ...
CommitLineData
1import * as Bluebird from 'bluebird'
2import { Transaction } from 'sequelize'
3import * as url from 'url'
4import * as uuidv4 from 'uuid/v4'
5import { ActivityPubActor, ActivityPubActorType } from '../../../shared/models/activitypub'
6import { ActivityPubAttributedTo } from '../../../shared/models/activitypub/objects'
7import { checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
8import { sanitizeAndCheckActorObject } from '../../helpers/custom-validators/activitypub/actor'
9import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
10import { retryTransactionWrapper, updateInstanceWithAnother } from '../../helpers/database-utils'
11import { logger } from '../../helpers/logger'
12import { createPrivateAndPublicKeys } from '../../helpers/peertube-crypto'
13import { doRequest } from '../../helpers/requests'
14import { getUrlFromWebfinger } from '../../helpers/webfinger'
15import { MIMETYPES, WEBSERVER } from '../../initializers/constants'
16import { AccountModel } from '../../models/account/account'
17import { ActorModel } from '../../models/activitypub/actor'
18import { AvatarModel } from '../../models/avatar/avatar'
19import { ServerModel } from '../../models/server/server'
20import { VideoChannelModel } from '../../models/video/video-channel'
21import { JobQueue } from '../job-queue'
22import { getServerActor } from '../../helpers/utils'
23import { ActorFetchByUrlType, fetchActorByUrl } from '../../helpers/actor'
24import { sequelizeTypescript } from '../../initializers/database'
25import {
26 MAccount,
27 MAccountDefault,
28 MActor,
29 MActorAccountChannelId,
30 MActorAccountChannelIdActor,
31 MActorAccountId,
32 MActorDefault,
33 MActorFull,
34 MActorFullActor,
35 MActorId,
36 MChannel,
37 MChannelAccountDefault
38} from '../../typings/models'
39
40// Set account keys, this could be long so process after the account creation and do not block the client
41function 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
54function getOrCreateActorAndServerAndModel (
55 activityActor: string | ActivityPubActor,
56 fetchType: 'all',
57 recurseIfNeeded?: boolean,
58 updateCollections?: boolean
59): Promise<MActorFullActor>
60
61function getOrCreateActorAndServerAndModel (
62 activityActor: string | ActivityPubActor,
63 fetchType?: 'association-ids',
64 recurseIfNeeded?: boolean,
65 updateCollections?: boolean
66): Promise<MActorAccountChannelId>
67
68async 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.createJob({ 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.createJob({ type: 'activitypub-http-fetcher', payload })
131 }
132
133 return actorRefreshed
134}
135
136function 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
154async 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
174type AvatarInfo = { name: string, onDisk: boolean, fileUrl: string }
175async function updateActorAvatarInstance (actor: MActorDefault, info: AvatarInfo, t: Transaction) {
176 if (info.name !== undefined) {
177 if (actor.avatarId) {
178 try {
179 await actor.Avatar.destroy({ transaction: t })
180 } catch (err) {
181 logger.error('Cannot remove old avatar of actor %s.', actor.url, { err })
182 }
183 }
184
185 const avatar = await AvatarModel.create({
186 filename: info.name,
187 onDisk: info.onDisk,
188 fileUrl: info.fileUrl
189 }, { transaction: t })
190
191 actor.avatarId = avatar.id
192 actor.Avatar = avatar
193 }
194
195 return actor
196}
197
198async function fetchActorTotalItems (url: string) {
199 const options = {
200 uri: url,
201 method: 'GET',
202 json: true,
203 activityPub: true
204 }
205
206 try {
207 const { body } = await doRequest(options)
208 return body.totalItems ? body.totalItems : 0
209 } catch (err) {
210 logger.warn('Cannot fetch remote actor count %s.', url, { err })
211 return 0
212 }
213}
214
215async function getAvatarInfoIfExists (actorJSON: ActivityPubActor) {
216 if (
217 actorJSON.icon && actorJSON.icon.type === 'Image' && MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType] !== undefined &&
218 isActivityPubUrlValid(actorJSON.icon.url)
219 ) {
220 const extension = MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType]
221
222 return {
223 name: uuidv4() + extension,
224 fileUrl: actorJSON.icon.url
225 }
226 }
227
228 return undefined
229}
230
231async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
232 // Don't fetch ourselves
233 const serverActor = await getServerActor()
234 if (serverActor.id === actor.id) {
235 logger.error('Cannot fetch our own outbox!')
236 return undefined
237 }
238
239 const payload = {
240 uri: actor.outboxUrl,
241 type: 'activity' as 'activity'
242 }
243
244 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
245}
246
247async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
248 actorArg: T,
249 fetchedType: ActorFetchByUrlType
250): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
251 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
252
253 // We need more attributes
254 const actor = fetchedType === 'all'
255 ? actorArg as MActorFull
256 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
257
258 try {
259 let actorUrl: string
260 try {
261 actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
262 } catch (err) {
263 logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
264 actorUrl = actor.url
265 }
266
267 const { result, statusCode } = await fetchRemoteActor(actorUrl)
268
269 if (statusCode === 404) {
270 logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
271 actor.Account ? actor.Account.destroy() : actor.VideoChannel.destroy()
272 return { actor: undefined, refreshed: false }
273 }
274
275 if (result === undefined) {
276 logger.warn('Cannot fetch remote actor in refresh actor.')
277 return { actor, refreshed: false }
278 }
279
280 return sequelizeTypescript.transaction(async t => {
281 updateInstanceWithAnother(actor, result.actor)
282
283 if (result.avatar !== undefined) {
284 const avatarInfo = {
285 name: result.avatar.name,
286 fileUrl: result.avatar.fileUrl,
287 onDisk: false
288 }
289
290 await updateActorAvatarInstance(actor, avatarInfo, t)
291 }
292
293 // Force update
294 actor.setDataValue('updatedAt', new Date())
295 await actor.save({ transaction: t })
296
297 if (actor.Account) {
298 actor.Account.name = result.name
299 actor.Account.description = result.summary
300
301 await actor.Account.save({ transaction: t })
302 } else if (actor.VideoChannel) {
303 actor.VideoChannel.name = result.name
304 actor.VideoChannel.description = result.summary
305 actor.VideoChannel.support = result.support
306
307 await actor.VideoChannel.save({ transaction: t })
308 }
309
310 return { refreshed: true, actor }
311 })
312 } catch (err) {
313 logger.warn('Cannot refresh actor %s.', actor.url, { err })
314 return { actor, refreshed: false }
315 }
316}
317
318export {
319 getOrCreateActorAndServerAndModel,
320 buildActorInstance,
321 setAsyncActorKeys,
322 fetchActorTotalItems,
323 getAvatarInfoIfExists,
324 updateActorInstance,
325 refreshActorIfNeeded,
326 updateActorAvatarInstance,
327 addFetchOutboxJob
328}
329
330// ---------------------------------------------------------------------------
331
332function saveActorAndServerAndModelIfNotExist (
333 result: FetchRemoteActorResult,
334 ownerActor?: MActorFullActor,
335 t?: Transaction
336): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
337 let actor = result.actor
338
339 if (t !== undefined) return save(t)
340
341 return sequelizeTypescript.transaction(t => save(t))
342
343 async function save (t: Transaction) {
344 const actorHost = url.parse(actor.url).host
345
346 const serverOptions = {
347 where: {
348 host: actorHost
349 },
350 defaults: {
351 host: actorHost
352 },
353 transaction: t
354 }
355 const [ server ] = await ServerModel.findOrCreate(serverOptions)
356
357 // Save our new account in database
358 actor.serverId = server.id
359
360 // Avatar?
361 if (result.avatar) {
362 const avatar = await AvatarModel.create({
363 filename: result.avatar.name,
364 fileUrl: result.avatar.fileUrl,
365 onDisk: false
366 }, { transaction: t })
367
368 actor.avatarId = avatar.id
369 }
370
371 // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
372 // (which could be false in a retried query)
373 const [ actorCreated ] = await ActorModel.findOrCreate<MActorFullActor>({
374 defaults: actor.toJSON(),
375 where: {
376 url: actor.url
377 },
378 transaction: t
379 })
380
381 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
382 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountDefault
383 actorCreated.Account.Actor = actorCreated
384 } else if (actorCreated.type === 'Group') { // Video channel
385 const channel = await saveVideoChannel(actorCreated, result, ownerActor, t)
386 actorCreated.VideoChannel = Object.assign(channel, { Actor: actorCreated, Account: ownerActor.Account })
387 }
388
389 actorCreated.Server = server
390
391 return actorCreated
392 }
393}
394
395type FetchRemoteActorResult = {
396 actor: MActor
397 name: string
398 summary: string
399 support?: string
400 playlists?: string
401 avatar?: {
402 name: string,
403 fileUrl: string
404 }
405 attributedTo: ActivityPubAttributedTo[]
406}
407async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
408 const options = {
409 uri: actorUrl,
410 method: 'GET',
411 json: true,
412 activityPub: true
413 }
414
415 logger.info('Fetching remote actor %s.', actorUrl)
416
417 const requestResult = await doRequest<ActivityPubActor>(options)
418 const actorJSON = requestResult.body
419
420 if (sanitizeAndCheckActorObject(actorJSON) === false) {
421 logger.debug('Remote actor JSON is not valid.', { actorJSON })
422 return { result: undefined, statusCode: requestResult.response.statusCode }
423 }
424
425 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
426 logger.warn('Actor url %s has not the same host than its AP id %s', actorUrl, actorJSON.id)
427 return { result: undefined, statusCode: requestResult.response.statusCode }
428 }
429
430 const followersCount = await fetchActorTotalItems(actorJSON.followers)
431 const followingCount = await fetchActorTotalItems(actorJSON.following)
432
433 const actor = new ActorModel({
434 type: actorJSON.type,
435 preferredUsername: actorJSON.preferredUsername,
436 url: actorJSON.id,
437 publicKey: actorJSON.publicKey.publicKeyPem,
438 privateKey: null,
439 followersCount: followersCount,
440 followingCount: followingCount,
441 inboxUrl: actorJSON.inbox,
442 outboxUrl: actorJSON.outbox,
443 followersUrl: actorJSON.followers,
444 followingUrl: actorJSON.following,
445
446 sharedInboxUrl: actorJSON.endpoints && actorJSON.endpoints.sharedInbox
447 ? actorJSON.endpoints.sharedInbox
448 : null
449 })
450
451 const avatarInfo = await getAvatarInfoIfExists(actorJSON)
452
453 const name = actorJSON.name || actorJSON.preferredUsername
454 return {
455 statusCode: requestResult.response.statusCode,
456 result: {
457 actor,
458 name,
459 avatar: avatarInfo,
460 summary: actorJSON.summary,
461 support: actorJSON.support,
462 playlists: actorJSON.playlists,
463 attributedTo: actorJSON.attributedTo
464 }
465 }
466}
467
468async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
469 const [ accountCreated ] = await AccountModel.findOrCreate({
470 defaults: {
471 name: result.name,
472 description: result.summary,
473 actorId: actor.id
474 },
475 where: {
476 actorId: actor.id
477 },
478 transaction: t
479 })
480
481 return accountCreated as MAccount
482}
483
484async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
485 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
486 defaults: {
487 name: result.name,
488 description: result.summary,
489 support: result.support,
490 actorId: actor.id,
491 accountId: ownerActor.Account.id
492 },
493 where: {
494 actorId: actor.id
495 },
496 transaction: t
497 })
498
499 return videoChannelCreated as MChannel
500}