]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/actor.ts
e557896e854ed273cab559e741c7c5a2624b293e
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / actor.ts
1 import * as Bluebird from 'bluebird'
2 import { join } from 'path'
3 import { Transaction } from 'sequelize'
4 import * as url from 'url'
5 import * as uuidv4 from 'uuid/v4'
6 import { ActivityPubActor, ActivityPubActorType } from '../../../shared/models/activitypub'
7 import { ActivityPubAttributedTo } from '../../../shared/models/activitypub/objects'
8 import { isRemoteActorValid } from '../../helpers/custom-validators/activitypub/actor'
9 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
10 import { retryTransactionWrapper } from '../../helpers/database-utils'
11 import { logger } from '../../helpers/logger'
12 import { createPrivateAndPublicKeys } from '../../helpers/peertube-crypto'
13 import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests'
14 import { CONFIG, sequelizeTypescript } from '../../initializers'
15 import { AccountModel } from '../../models/account/account'
16 import { ActorModel } from '../../models/activitypub/actor'
17 import { AvatarModel } from '../../models/avatar/avatar'
18 import { ServerModel } from '../../models/server/server'
19 import { VideoChannelModel } from '../../models/video/video-channel'
20
21 // Set account keys, this could be long so process after the account creation and do not block the client
22 function setAsyncActorKeys (actor: ActorModel) {
23 return createPrivateAndPublicKeys()
24 .then(({ publicKey, privateKey }) => {
25 actor.set('publicKey', publicKey)
26 actor.set('privateKey', privateKey)
27 return actor.save()
28 })
29 .catch(err => {
30 logger.error('Cannot set public/private keys of actor %d.', actor.uuid, err)
31 return actor
32 })
33 }
34
35 async function getOrCreateActorAndServerAndModel (actorUrl: string, recurseIfNeeded = true) {
36 let actor = await ActorModel.loadByUrl(actorUrl)
37
38 // We don't have this actor in our database, fetch it on remote
39 if (!actor) {
40 const result = await fetchRemoteActor(actorUrl)
41 if (result === undefined) throw new Error('Cannot fetch remote actor.')
42
43 // Create the attributed to actor
44 // In PeerTube a video channel is owned by an account
45 let ownerActor: ActorModel = undefined
46 if (recurseIfNeeded === true && result.actor.type === 'Group') {
47 const accountAttributedTo = result.attributedTo.find(a => a.type === 'Person')
48 if (!accountAttributedTo) throw new Error('Cannot find account attributed to video channel ' + actor.url)
49
50 try {
51 // Assert we don't recurse another time
52 ownerActor = await getOrCreateActorAndServerAndModel(accountAttributedTo.id, false)
53 } catch (err) {
54 logger.error('Cannot get or create account attributed to video channel ' + actor.url)
55 throw new Error(err)
56 }
57 }
58
59 const options = {
60 arguments: [ result, ownerActor ],
61 errorMessage: 'Cannot save actor and server with many retries.'
62 }
63 actor = await retryTransactionWrapper(saveActorAndServerAndModelIfNotExist, options)
64 }
65
66 return actor
67 }
68
69 function buildActorInstance (type: ActivityPubActorType, url: string, preferredUsername: string, uuid?: string) {
70 return new ActorModel({
71 type,
72 url,
73 preferredUsername,
74 uuid,
75 publicKey: null,
76 privateKey: null,
77 followersCount: 0,
78 followingCount: 0,
79 inboxUrl: url + '/inbox',
80 outboxUrl: url + '/outbox',
81 sharedInboxUrl: CONFIG.WEBSERVER.URL + '/inbox',
82 followersUrl: url + '/followers',
83 followingUrl: url + '/following'
84 })
85 }
86
87 export {
88 getOrCreateActorAndServerAndModel,
89 buildActorInstance,
90 setAsyncActorKeys
91 }
92
93 // ---------------------------------------------------------------------------
94
95 function saveActorAndServerAndModelIfNotExist (
96 result: FetchRemoteActorResult,
97 ownerActor?: ActorModel,
98 t?: Transaction
99 ): Bluebird<ActorModel> | Promise<ActorModel> {
100 let actor = result.actor
101
102 if (t !== undefined) return save(t)
103
104 return sequelizeTypescript.transaction(t => save(t))
105
106 async function save (t: Transaction) {
107 const actorHost = url.parse(actor.url).host
108
109 const serverOptions = {
110 where: {
111 host: actorHost
112 },
113 defaults: {
114 host: actorHost
115 },
116 transaction: t
117 }
118 const [ server ] = await ServerModel.findOrCreate(serverOptions)
119
120 // Save our new account in database
121 actor.set('serverId', server.id)
122
123 // Avatar?
124 if (result.avatarName) {
125 const avatar = await AvatarModel.create({
126 filename: result.avatarName
127 }, { transaction: t })
128 actor.set('avatarId', avatar.id)
129 }
130
131 // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
132 // (which could be false in a retried query)
133 const actorCreated = await ActorModel.create(actor.toJSON(), { transaction: t })
134
135 if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
136 const account = await saveAccount(actorCreated, result, t)
137 actorCreated.Account = account
138 actorCreated.Account.Actor = actorCreated
139 } else if (actorCreated.type === 'Group') { // Video channel
140 const videoChannel = await saveVideoChannel(actorCreated, result, ownerActor, t)
141 actorCreated.VideoChannel = videoChannel
142 actorCreated.VideoChannel.Actor = actorCreated
143 }
144
145 return actorCreated
146 }
147 }
148
149 type FetchRemoteActorResult = {
150 actor: ActorModel
151 name: string
152 summary: string
153 avatarName?: string
154 attributedTo: ActivityPubAttributedTo[]
155 }
156 async function fetchRemoteActor (actorUrl: string): Promise<FetchRemoteActorResult> {
157 const options = {
158 uri: actorUrl,
159 method: 'GET',
160 json: true,
161 activityPub: true
162 }
163
164 logger.info('Fetching remote actor %s.', actorUrl)
165
166 const requestResult = await doRequest(options)
167 const actorJSON: ActivityPubActor = requestResult.body
168
169 if (isRemoteActorValid(actorJSON) === false) {
170 logger.debug('Remote actor JSON is not valid.', { actorJSON: actorJSON })
171 return undefined
172 }
173
174 const followersCount = await fetchActorTotalItems(actorJSON.followers)
175 const followingCount = await fetchActorTotalItems(actorJSON.following)
176
177 const actor = new ActorModel({
178 type: actorJSON.type,
179 uuid: actorJSON.uuid,
180 preferredUsername: actorJSON.preferredUsername,
181 url: actorJSON.id,
182 publicKey: actorJSON.publicKey.publicKeyPem,
183 privateKey: null,
184 followersCount: followersCount,
185 followingCount: followingCount,
186 inboxUrl: actorJSON.inbox,
187 outboxUrl: actorJSON.outbox,
188 sharedInboxUrl: actorJSON.endpoints.sharedInbox,
189 followersUrl: actorJSON.followers,
190 followingUrl: actorJSON.following
191 })
192
193 // Fetch icon?
194 let avatarName: string = undefined
195 if (
196 actorJSON.icon && actorJSON.icon.type === 'Image' && actorJSON.icon.mediaType === 'image/png' &&
197 isActivityPubUrlValid(actorJSON.icon.url)
198 ) {
199 const extension = actorJSON.icon.mediaType === 'image/png' ? '.png' : '.jpg'
200
201 avatarName = uuidv4() + extension
202 const destPath = join(CONFIG.STORAGE.AVATARS_DIR, avatarName)
203
204 await doRequestAndSaveToFile({
205 method: 'GET',
206 uri: actorJSON.icon.url
207 }, destPath)
208 }
209
210 const name = actorJSON.name || actorJSON.preferredUsername
211 return {
212 actor,
213 name,
214 avatarName,
215 summary: actorJSON.summary,
216 attributedTo: actorJSON.attributedTo
217 }
218 }
219
220 async function fetchActorTotalItems (url: string) {
221 const options = {
222 uri: url,
223 method: 'GET',
224 json: true,
225 activityPub: true
226 }
227
228 let requestResult
229 try {
230 requestResult = await doRequest(options)
231 } catch (err) {
232 logger.warn('Cannot fetch remote actor count %s.', url, err)
233 return undefined
234 }
235
236 return requestResult.totalItems ? requestResult.totalItems : 0
237 }
238
239 function saveAccount (actor: ActorModel, result: FetchRemoteActorResult, t: Transaction) {
240 const account = new AccountModel({
241 name: result.name,
242 actorId: actor.id
243 })
244
245 return account.save({ transaction: t })
246 }
247
248 async function saveVideoChannel (actor: ActorModel, result: FetchRemoteActorResult, ownerActor: ActorModel, t: Transaction) {
249 const videoChannel = new VideoChannelModel({
250 name: result.name,
251 description: result.summary,
252 actorId: actor.id,
253 accountId: ownerActor.Account.id
254 })
255
256 return videoChannel.save({ transaction: t })
257 }