]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/actor.ts
Manual approves followers only for the instance
[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) {
66fb2aa3 176 if (!info.name) return actor
a5625b41 177
66fb2aa3
C
178 if (actor.Avatar) {
179 // Don't update the avatar if the filename did not change
2fa9c40e 180 if (actor.Avatar.fileUrl === info.fileUrl) return actor
a5625b41 181
66fb2aa3
C
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 }
a5625b41
C
187 }
188
66fb2aa3
C
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
557b13ae 198 return actor
a5625b41
C
199}
200
265ba139
C
201async function fetchActorTotalItems (url: string) {
202 const options = {
203 uri: url,
204 method: 'GET',
205 json: true,
206 activityPub: true
207 }
208
265ba139 209 try {
7006bc63
C
210 const { body } = await doRequest(options)
211 return body.totalItems ? body.totalItems : 0
265ba139 212 } catch (err) {
d5b7d911 213 logger.warn('Cannot fetch remote actor count %s.', url, { err })
7006bc63 214 return 0
265ba139 215 }
265ba139
C
216}
217
557b13ae 218async function getAvatarInfoIfExists (actorJSON: ActivityPubActor) {
265ba139 219 if (
14e2014a 220 actorJSON.icon && actorJSON.icon.type === 'Image' && MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType] !== undefined &&
265ba139
C
221 isActivityPubUrlValid(actorJSON.icon.url)
222 ) {
14e2014a 223 const extension = MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType]
265ba139 224
557b13ae
C
225 return {
226 name: uuidv4() + extension,
227 fileUrl: actorJSON.icon.url
228 }
265ba139
C
229 }
230
231 return undefined
232}
233
5224c394 234async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
16f29007
C
235 // Don't fetch ourselves
236 const serverActor = await getServerActor()
237 if (serverActor.id === actor.id) {
238 logger.error('Cannot fetch our own outbox!')
239 return undefined
240 }
241
242 const payload = {
f6eebcb3
C
243 uri: actor.outboxUrl,
244 type: 'activity' as 'activity'
16f29007
C
245 }
246
247 return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
248}
249
453e83ea
C
250async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
251 actorArg: T,
744d0eca 252 fetchedType: ActorFetchByUrlType
453e83ea 253): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
744d0eca
C
254 if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
255
256 // We need more attributes
453e83ea
C
257 const actor = fetchedType === 'all'
258 ? actorArg as MActorFull
259 : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
744d0eca
C
260
261 try {
699b059e
C
262 let actorUrl: string
263 try {
264 actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
265 } catch (err) {
266 logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
267 actorUrl = actor.url
268 }
269
744d0eca
C
270 const { result, statusCode } = await fetchRemoteActor(actorUrl)
271
272 if (statusCode === 404) {
273 logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
274 actor.Account ? actor.Account.destroy() : actor.VideoChannel.destroy()
275 return { actor: undefined, refreshed: false }
276 }
277
278 if (result === undefined) {
279 logger.warn('Cannot fetch remote actor in refresh actor.')
280 return { actor, refreshed: false }
281 }
282
283 return sequelizeTypescript.transaction(async t => {
284 updateInstanceWithAnother(actor, result.actor)
285
557b13ae
C
286 if (result.avatar !== undefined) {
287 const avatarInfo = {
288 name: result.avatar.name,
289 fileUrl: result.avatar.fileUrl,
290 onDisk: false
291 }
292
293 await updateActorAvatarInstance(actor, avatarInfo, t)
744d0eca
C
294 }
295
296 // Force update
297 actor.setDataValue('updatedAt', new Date())
298 await actor.save({ transaction: t })
299
300 if (actor.Account) {
6b9c966f
C
301 actor.Account.name = result.name
302 actor.Account.description = result.summary
744d0eca
C
303
304 await actor.Account.save({ transaction: t })
305 } else if (actor.VideoChannel) {
6b9c966f
C
306 actor.VideoChannel.name = result.name
307 actor.VideoChannel.description = result.summary
308 actor.VideoChannel.support = result.support
744d0eca
C
309
310 await actor.VideoChannel.save({ transaction: t })
311 }
312
313 return { refreshed: true, actor }
314 })
315 } catch (err) {
4ee7a4c9 316 logger.warn('Cannot refresh actor %s.', actor.url, { err })
744d0eca
C
317 return { actor, refreshed: false }
318 }
319}
320
c5911fd3
C
321export {
322 getOrCreateActorAndServerAndModel,
323 buildActorInstance,
265ba139
C
324 setAsyncActorKeys,
325 fetchActorTotalItems,
557b13ae 326 getAvatarInfoIfExists,
a5625b41 327 updateActorInstance,
744d0eca 328 refreshActorIfNeeded,
16f29007
C
329 updateActorAvatarInstance,
330 addFetchOutboxJob
c5911fd3
C
331}
332
333// ---------------------------------------------------------------------------
334
50d6de9c
C
335function saveActorAndServerAndModelIfNotExist (
336 result: FetchRemoteActorResult,
453e83ea 337 ownerActor?: MActorFullActor,
50d6de9c 338 t?: Transaction
453e83ea 339): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
50d6de9c
C
340 let actor = result.actor
341
342 if (t !== undefined) return save(t)
343
344 return sequelizeTypescript.transaction(t => save(t))
345
346 async function save (t: Transaction) {
347 const actorHost = url.parse(actor.url).host
348
349 const serverOptions = {
350 where: {
351 host: actorHost
352 },
353 defaults: {
354 host: actorHost
355 },
356 transaction: t
357 }
358 const [ server ] = await ServerModel.findOrCreate(serverOptions)
359
360 // Save our new account in database
557b13ae 361 actor.serverId = server.id
50d6de9c 362
c5911fd3 363 // Avatar?
557b13ae 364 if (result.avatar) {
c5911fd3 365 const avatar = await AvatarModel.create({
557b13ae
C
366 filename: result.avatar.name,
367 fileUrl: result.avatar.fileUrl,
368 onDisk: false
c5911fd3 369 }, { transaction: t })
557b13ae
C
370
371 actor.avatarId = avatar.id
c5911fd3
C
372 }
373
50d6de9c
C
374 // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
375 // (which could be false in a retried query)
453e83ea 376 const [ actorCreated ] = await ActorModel.findOrCreate<MActorFullActor>({
2c897999
C
377 defaults: actor.toJSON(),
378 where: {
379 url: actor.url
380 },
381 transaction: t
382 })
50d6de9c
C
383
384 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
0283eaac 385 actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountDefault
50d6de9c
C
386 actorCreated.Account.Actor = actorCreated
387 } else if (actorCreated.type === 'Group') { // Video channel
0283eaac
C
388 const channel = await saveVideoChannel(actorCreated, result, ownerActor, t)
389 actorCreated.VideoChannel = Object.assign(channel, { Actor: actorCreated, Account: ownerActor.Account })
50d6de9c
C
390 }
391
883993c8
C
392 actorCreated.Server = server
393
50d6de9c
C
394 return actorCreated
395 }
396}
397
398type FetchRemoteActorResult = {
453e83ea 399 actor: MActor
e12a0092 400 name: string
50d6de9c 401 summary: string
2422c46b 402 support?: string
418d092a 403 playlists?: string
557b13ae
C
404 avatar?: {
405 name: string,
406 fileUrl: string
407 }
50d6de9c
C
408 attributedTo: ActivityPubAttributedTo[]
409}
f5b0af50 410async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
50d6de9c
C
411 const options = {
412 uri: actorUrl,
413 method: 'GET',
da854ddd
C
414 json: true,
415 activityPub: true
50d6de9c
C
416 }
417
418 logger.info('Fetching remote actor %s.', actorUrl)
419
4c280004 420 const requestResult = await doRequest<ActivityPubActor>(options)
4c280004 421 const actorJSON = requestResult.body
9977c128
C
422
423 if (sanitizeAndCheckActorObject(actorJSON) === false) {
b4593cd7 424 logger.debug('Remote actor JSON is not valid.', { actorJSON })
f5b0af50 425 return { result: undefined, statusCode: requestResult.response.statusCode }
50d6de9c
C
426 }
427
5c6d985f 428 if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
9f79ade6
C
429 logger.warn('Actor url %s has not the same host than its AP id %s', actorUrl, actorJSON.id)
430 return { result: undefined, statusCode: requestResult.response.statusCode }
5c6d985f
C
431 }
432
50d6de9c
C
433 const followersCount = await fetchActorTotalItems(actorJSON.followers)
434 const followingCount = await fetchActorTotalItems(actorJSON.following)
435
436 const actor = new ActorModel({
437 type: actorJSON.type,
e12a0092
C
438 preferredUsername: actorJSON.preferredUsername,
439 url: actorJSON.id,
50d6de9c
C
440 publicKey: actorJSON.publicKey.publicKeyPem,
441 privateKey: null,
442 followersCount: followersCount,
443 followingCount: followingCount,
444 inboxUrl: actorJSON.inbox,
445 outboxUrl: actorJSON.outbox,
50d6de9c 446 followersUrl: actorJSON.followers,
47581df0
C
447 followingUrl: actorJSON.following,
448
449 sharedInboxUrl: actorJSON.endpoints && actorJSON.endpoints.sharedInbox
450 ? actorJSON.endpoints.sharedInbox
a82ddfad 451 : null
50d6de9c
C
452 })
453
557b13ae 454 const avatarInfo = await getAvatarInfoIfExists(actorJSON)
c5911fd3 455
e12a0092 456 const name = actorJSON.name || actorJSON.preferredUsername
50d6de9c 457 return {
f5b0af50
C
458 statusCode: requestResult.response.statusCode,
459 result: {
460 actor,
461 name,
557b13ae 462 avatar: avatarInfo,
f5b0af50
C
463 summary: actorJSON.summary,
464 support: actorJSON.support,
418d092a 465 playlists: actorJSON.playlists,
f5b0af50
C
466 attributedTo: actorJSON.attributedTo
467 }
50d6de9c
C
468 }
469}
470
453e83ea 471async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
2c897999
C
472 const [ accountCreated ] = await AccountModel.findOrCreate({
473 defaults: {
474 name: result.name,
2422c46b 475 description: result.summary,
2c897999
C
476 actorId: actor.id
477 },
478 where: {
479 actorId: actor.id
480 },
481 transaction: t
50d6de9c
C
482 })
483
453e83ea 484 return accountCreated as MAccount
50d6de9c
C
485}
486
453e83ea 487async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
2c897999
C
488 const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
489 defaults: {
490 name: result.name,
491 description: result.summary,
2422c46b 492 support: result.support,
2c897999
C
493 actorId: actor.id,
494 accountId: ownerActor.Account.id
495 },
496 where: {
497 actorId: actor.id
498 },
499 transaction: t
50d6de9c
C
500 })
501
453e83ea 502 return videoChannelCreated as MChannel
50d6de9c 503}