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