]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/actor.ts
Add hover effect on login/create an account button
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / actor.ts
CommitLineData
50d6de9c 1import * as Bluebird from 'bluebird'
c5911fd3 2import { join } from 'path'
50d6de9c
C
3import { Transaction } from 'sequelize'
4import * as url from 'url'
c5911fd3 5import * as uuidv4 from 'uuid/v4'
50d6de9c
C
6import { ActivityPubActor, ActivityPubActorType } from '../../../shared/models/activitypub'
7import { ActivityPubAttributedTo } from '../../../shared/models/activitypub/objects'
da854ddd 8import { isRemoteActorValid } from '../../helpers/custom-validators/activitypub/actor'
c5911fd3 9import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
da854ddd
C
10import { retryTransactionWrapper } from '../../helpers/database-utils'
11import { logger } from '../../helpers/logger'
12import { createPrivateAndPublicKeys } from '../../helpers/peertube-crypto'
c5911fd3 13import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests'
da854ddd 14import { CONFIG, sequelizeTypescript } from '../../initializers'
50d6de9c
C
15import { AccountModel } from '../../models/account/account'
16import { ActorModel } from '../../models/activitypub/actor'
c5911fd3 17import { AvatarModel } from '../../models/avatar/avatar'
50d6de9c
C
18import { ServerModel } from '../../models/server/server'
19import { 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
22function 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
35async 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
69function 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
87export {
88 getOrCreateActorAndServerAndModel,
89 buildActorInstance,
90 setAsyncActorKeys
91}
92
93// ---------------------------------------------------------------------------
94
50d6de9c
C
95function 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
c5911fd3
C
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
50d6de9c
C
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
149type FetchRemoteActorResult = {
150 actor: ActorModel
e12a0092 151 name: string
50d6de9c 152 summary: string
c5911fd3 153 avatarName?: string
50d6de9c
C
154 attributedTo: ActivityPubAttributedTo[]
155}
156async function fetchRemoteActor (actorUrl: string): Promise<FetchRemoteActorResult> {
157 const options = {
158 uri: actorUrl,
159 method: 'GET',
da854ddd
C
160 json: true,
161 activityPub: true
50d6de9c
C
162 }
163
164 logger.info('Fetching remote actor %s.', actorUrl)
165
da854ddd
C
166 const requestResult = await doRequest(options)
167 const actorJSON: ActivityPubActor = requestResult.body
50d6de9c 168
50d6de9c
C
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,
e12a0092
C
180 preferredUsername: actorJSON.preferredUsername,
181 url: actorJSON.id,
50d6de9c
C
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
c5911fd3
C
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
e12a0092 210 const name = actorJSON.name || actorJSON.preferredUsername
50d6de9c
C
211 return {
212 actor,
e12a0092 213 name,
c5911fd3 214 avatarName,
50d6de9c
C
215 summary: actorJSON.summary,
216 attributedTo: actorJSON.attributedTo
217 }
218}
219
50d6de9c
C
220async function fetchActorTotalItems (url: string) {
221 const options = {
222 uri: url,
da854ddd
C
223 method: 'GET',
224 json: true,
225 activityPub: true
50d6de9c
C
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
239function saveAccount (actor: ActorModel, result: FetchRemoteActorResult, t: Transaction) {
240 const account = new AccountModel({
e12a0092 241 name: result.name,
50d6de9c
C
242 actorId: actor.id
243 })
244
245 return account.save({ transaction: t })
246}
247
248async function saveVideoChannel (actor: ActorModel, result: FetchRemoteActorResult, ownerActor: ActorModel, t: Transaction) {
249 const videoChannel = new VideoChannelModel({
e12a0092 250 name: result.name,
50d6de9c
C
251 description: result.summary,
252 actorId: actor.id,
253 accountId: ownerActor.Account.id
254 })
255
256 return videoChannel.save({ transaction: t })
257}