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