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