]>
Commit | Line | Data |
---|---|---|
50d6de9c | 1 | import * as Bluebird from 'bluebird' |
c5911fd3 | 2 | import { join } from 'path' |
50d6de9c C |
3 | import { Transaction } from 'sequelize' |
4 | import * as url from 'url' | |
c5911fd3 | 5 | import * as uuidv4 from 'uuid/v4' |
50d6de9c C |
6 | import { ActivityPubActor, ActivityPubActorType } from '../../../shared/models/activitypub' |
7 | import { ActivityPubAttributedTo } from '../../../shared/models/activitypub/objects' | |
265ba139 | 8 | import { isActorObjectValid } from '../../helpers/custom-validators/activitypub/actor' |
c5911fd3 | 9 | import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc' |
da854ddd C |
10 | import { retryTransactionWrapper } from '../../helpers/database-utils' |
11 | import { logger } from '../../helpers/logger' | |
12 | import { createPrivateAndPublicKeys } from '../../helpers/peertube-crypto' | |
c5911fd3 | 13 | import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests' |
265ba139 | 14 | import { AVATAR_MIMETYPE_EXT, CONFIG, sequelizeTypescript } from '../../initializers' |
50d6de9c C |
15 | import { AccountModel } from '../../models/account/account' |
16 | import { ActorModel } from '../../models/activitypub/actor' | |
c5911fd3 | 17 | import { AvatarModel } from '../../models/avatar/avatar' |
50d6de9c C |
18 | import { ServerModel } from '../../models/server/server' |
19 | import { VideoChannelModel } from '../../models/video/video-channel' | |
20 | ||
e12a0092 | 21 | // Set account keys, this could be long so process after the account creation and do not block the client |
50d6de9c C |
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 | ||
c5911fd3 C |
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 | ||
265ba139 C |
87 | async function fetchActorTotalItems (url: string) { |
88 | const options = { | |
89 | uri: url, | |
90 | method: 'GET', | |
91 | json: true, | |
92 | activityPub: true | |
93 | } | |
94 | ||
95 | let requestResult | |
96 | try { | |
97 | requestResult = await doRequest(options) | |
98 | } catch (err) { | |
99 | logger.warn('Cannot fetch remote actor count %s.', url, err) | |
100 | return undefined | |
101 | } | |
102 | ||
103 | return requestResult.totalItems ? requestResult.totalItems : 0 | |
104 | } | |
105 | ||
106 | async function fetchAvatarIfExists (actorJSON: ActivityPubActor) { | |
107 | if ( | |
108 | actorJSON.icon && actorJSON.icon.type === 'Image' && AVATAR_MIMETYPE_EXT[actorJSON.icon.mediaType] !== undefined && | |
109 | isActivityPubUrlValid(actorJSON.icon.url) | |
110 | ) { | |
111 | const extension = AVATAR_MIMETYPE_EXT[actorJSON.icon.mediaType] | |
112 | ||
113 | const avatarName = uuidv4() + extension | |
114 | const destPath = join(CONFIG.STORAGE.AVATARS_DIR, avatarName) | |
115 | ||
116 | await doRequestAndSaveToFile({ | |
117 | method: 'GET', | |
118 | uri: actorJSON.icon.url | |
119 | }, destPath) | |
120 | ||
121 | return avatarName | |
122 | } | |
123 | ||
124 | return undefined | |
125 | } | |
126 | ||
c5911fd3 C |
127 | export { |
128 | getOrCreateActorAndServerAndModel, | |
129 | buildActorInstance, | |
265ba139 C |
130 | setAsyncActorKeys, |
131 | fetchActorTotalItems, | |
132 | fetchAvatarIfExists | |
c5911fd3 C |
133 | } |
134 | ||
135 | // --------------------------------------------------------------------------- | |
136 | ||
50d6de9c C |
137 | function saveActorAndServerAndModelIfNotExist ( |
138 | result: FetchRemoteActorResult, | |
139 | ownerActor?: ActorModel, | |
140 | t?: Transaction | |
141 | ): Bluebird<ActorModel> | Promise<ActorModel> { | |
142 | let actor = result.actor | |
143 | ||
144 | if (t !== undefined) return save(t) | |
145 | ||
146 | return sequelizeTypescript.transaction(t => save(t)) | |
147 | ||
148 | async function save (t: Transaction) { | |
149 | const actorHost = url.parse(actor.url).host | |
150 | ||
151 | const serverOptions = { | |
152 | where: { | |
153 | host: actorHost | |
154 | }, | |
155 | defaults: { | |
156 | host: actorHost | |
157 | }, | |
158 | transaction: t | |
159 | } | |
160 | const [ server ] = await ServerModel.findOrCreate(serverOptions) | |
161 | ||
162 | // Save our new account in database | |
163 | actor.set('serverId', server.id) | |
164 | ||
c5911fd3 C |
165 | // Avatar? |
166 | if (result.avatarName) { | |
167 | const avatar = await AvatarModel.create({ | |
168 | filename: result.avatarName | |
169 | }, { transaction: t }) | |
170 | actor.set('avatarId', avatar.id) | |
171 | } | |
172 | ||
50d6de9c C |
173 | // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists |
174 | // (which could be false in a retried query) | |
175 | const actorCreated = await ActorModel.create(actor.toJSON(), { transaction: t }) | |
176 | ||
177 | if (actorCreated.type === 'Person' || actorCreated.type === 'Application') { | |
178 | const account = await saveAccount(actorCreated, result, t) | |
179 | actorCreated.Account = account | |
180 | actorCreated.Account.Actor = actorCreated | |
181 | } else if (actorCreated.type === 'Group') { // Video channel | |
182 | const videoChannel = await saveVideoChannel(actorCreated, result, ownerActor, t) | |
183 | actorCreated.VideoChannel = videoChannel | |
184 | actorCreated.VideoChannel.Actor = actorCreated | |
185 | } | |
186 | ||
187 | return actorCreated | |
188 | } | |
189 | } | |
190 | ||
191 | type FetchRemoteActorResult = { | |
192 | actor: ActorModel | |
e12a0092 | 193 | name: string |
50d6de9c | 194 | summary: string |
c5911fd3 | 195 | avatarName?: string |
50d6de9c C |
196 | attributedTo: ActivityPubAttributedTo[] |
197 | } | |
198 | async function fetchRemoteActor (actorUrl: string): Promise<FetchRemoteActorResult> { | |
199 | const options = { | |
200 | uri: actorUrl, | |
201 | method: 'GET', | |
da854ddd C |
202 | json: true, |
203 | activityPub: true | |
50d6de9c C |
204 | } |
205 | ||
206 | logger.info('Fetching remote actor %s.', actorUrl) | |
207 | ||
da854ddd C |
208 | const requestResult = await doRequest(options) |
209 | const actorJSON: ActivityPubActor = requestResult.body | |
50d6de9c | 210 | |
265ba139 | 211 | if (isActorObjectValid(actorJSON) === false) { |
50d6de9c C |
212 | logger.debug('Remote actor JSON is not valid.', { actorJSON: actorJSON }) |
213 | return undefined | |
214 | } | |
215 | ||
216 | const followersCount = await fetchActorTotalItems(actorJSON.followers) | |
217 | const followingCount = await fetchActorTotalItems(actorJSON.following) | |
218 | ||
219 | const actor = new ActorModel({ | |
220 | type: actorJSON.type, | |
221 | uuid: actorJSON.uuid, | |
e12a0092 C |
222 | preferredUsername: actorJSON.preferredUsername, |
223 | url: actorJSON.id, | |
50d6de9c C |
224 | publicKey: actorJSON.publicKey.publicKeyPem, |
225 | privateKey: null, | |
226 | followersCount: followersCount, | |
227 | followingCount: followingCount, | |
228 | inboxUrl: actorJSON.inbox, | |
229 | outboxUrl: actorJSON.outbox, | |
230 | sharedInboxUrl: actorJSON.endpoints.sharedInbox, | |
231 | followersUrl: actorJSON.followers, | |
232 | followingUrl: actorJSON.following | |
233 | }) | |
234 | ||
265ba139 | 235 | const avatarName = await fetchAvatarIfExists(actorJSON) |
c5911fd3 | 236 | |
e12a0092 | 237 | const name = actorJSON.name || actorJSON.preferredUsername |
50d6de9c C |
238 | return { |
239 | actor, | |
e12a0092 | 240 | name, |
c5911fd3 | 241 | avatarName, |
50d6de9c C |
242 | summary: actorJSON.summary, |
243 | attributedTo: actorJSON.attributedTo | |
244 | } | |
245 | } | |
246 | ||
50d6de9c C |
247 | function saveAccount (actor: ActorModel, result: FetchRemoteActorResult, t: Transaction) { |
248 | const account = new AccountModel({ | |
e12a0092 | 249 | name: result.name, |
50d6de9c C |
250 | actorId: actor.id |
251 | }) | |
252 | ||
253 | return account.save({ transaction: t }) | |
254 | } | |
255 | ||
256 | async function saveVideoChannel (actor: ActorModel, result: FetchRemoteActorResult, ownerActor: ActorModel, t: Transaction) { | |
257 | const videoChannel = new VideoChannelModel({ | |
e12a0092 | 258 | name: result.name, |
50d6de9c C |
259 | description: result.summary, |
260 | actorId: actor.id, | |
261 | accountId: ownerActor.Account.id | |
262 | }) | |
263 | ||
264 | return videoChannel.save({ transaction: t }) | |
265 | } |