]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/activitypub/actor.ts
Add index on sharedInboxUrl
[github/Chocobozzz/PeerTube.git] / server / models / activitypub / actor.ts
1 import { values } from 'lodash'
2 import { extname } from 'path'
3 import * as Sequelize from 'sequelize'
4 import {
5 AllowNull,
6 BelongsTo,
7 Column,
8 CreatedAt,
9 DataType,
10 Default,
11 DefaultScope,
12 ForeignKey,
13 HasMany,
14 HasOne,
15 Is,
16 IsUUID,
17 Model,
18 Scopes,
19 Table,
20 UpdatedAt
21 } from 'sequelize-typescript'
22 import { ActivityPubActorType } from '../../../shared/models/activitypub'
23 import { Avatar } from '../../../shared/models/avatars/avatar.model'
24 import { activityPubContextify } from '../../helpers/activitypub'
25 import {
26 isActorFollowersCountValid,
27 isActorFollowingCountValid,
28 isActorPreferredUsernameValid,
29 isActorPrivateKeyValid,
30 isActorPublicKeyValid
31 } from '../../helpers/custom-validators/activitypub/actor'
32 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
33 import { ACTIVITY_PUB, ACTIVITY_PUB_ACTOR_TYPES, CONFIG, CONSTRAINTS_FIELDS } from '../../initializers'
34 import { AccountModel } from '../account/account'
35 import { AvatarModel } from '../avatar/avatar'
36 import { ServerModel } from '../server/server'
37 import { throwIfNotValid } from '../utils'
38 import { VideoChannelModel } from '../video/video-channel'
39 import { ActorFollowModel } from './actor-follow'
40
41 enum ScopeNames {
42 FULL = 'FULL'
43 }
44
45 @DefaultScope({
46 include: [
47 {
48 model: () => ServerModel,
49 required: false
50 },
51 {
52 model: () => AvatarModel,
53 required: false
54 }
55 ]
56 })
57 @Scopes({
58 [ScopeNames.FULL]: {
59 include: [
60 {
61 model: () => AccountModel.unscoped(),
62 required: false
63 },
64 {
65 model: () => VideoChannelModel.unscoped(),
66 required: false
67 },
68 {
69 model: () => ServerModel,
70 required: false
71 },
72 {
73 model: () => AvatarModel,
74 required: false
75 }
76 ]
77 }
78 })
79 @Table({
80 tableName: 'actor',
81 indexes: [
82 {
83 fields: [ 'url' ],
84 unique: true
85 },
86 {
87 fields: [ 'preferredUsername', 'serverId' ],
88 unique: true
89 },
90 {
91 fields: [ 'inboxUrl', 'sharedInboxUrl' ]
92 },
93 {
94 fields: [ 'sharedInboxUrl' ]
95 },
96 {
97 fields: [ 'serverId' ]
98 },
99 {
100 fields: [ 'avatarId' ]
101 },
102 {
103 fields: [ 'uuid' ],
104 unique: true
105 },
106 {
107 fields: [ 'followersUrl' ]
108 }
109 ]
110 })
111 export class ActorModel extends Model<ActorModel> {
112
113 @AllowNull(false)
114 @Column(DataType.ENUM(values(ACTIVITY_PUB_ACTOR_TYPES)))
115 type: ActivityPubActorType
116
117 @AllowNull(false)
118 @Default(DataType.UUIDV4)
119 @IsUUID(4)
120 @Column(DataType.UUID)
121 uuid: string
122
123 @AllowNull(false)
124 @Is('ActorPreferredUsername', value => throwIfNotValid(value, isActorPreferredUsernameValid, 'actor preferred username'))
125 @Column
126 preferredUsername: string
127
128 @AllowNull(false)
129 @Is('ActorUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
130 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
131 url: string
132
133 @AllowNull(true)
134 @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPublicKeyValid, 'public key'))
135 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PUBLIC_KEY.max))
136 publicKey: string
137
138 @AllowNull(true)
139 @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPrivateKeyValid, 'private key'))
140 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PRIVATE_KEY.max))
141 privateKey: string
142
143 @AllowNull(false)
144 @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowersCountValid, 'followers count'))
145 @Column
146 followersCount: number
147
148 @AllowNull(false)
149 @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowingCountValid, 'following count'))
150 @Column
151 followingCount: number
152
153 @AllowNull(false)
154 @Is('ActorInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'inbox url'))
155 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
156 inboxUrl: string
157
158 @AllowNull(false)
159 @Is('ActorOutboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'outbox url'))
160 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
161 outboxUrl: string
162
163 @AllowNull(false)
164 @Is('ActorSharedInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'shared inbox url'))
165 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
166 sharedInboxUrl: string
167
168 @AllowNull(false)
169 @Is('ActorFollowersUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'followers url'))
170 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
171 followersUrl: string
172
173 @AllowNull(false)
174 @Is('ActorFollowingUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'following url'))
175 @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
176 followingUrl: string
177
178 @CreatedAt
179 createdAt: Date
180
181 @UpdatedAt
182 updatedAt: Date
183
184 @ForeignKey(() => AvatarModel)
185 @Column
186 avatarId: number
187
188 @BelongsTo(() => AvatarModel, {
189 foreignKey: {
190 allowNull: true
191 },
192 onDelete: 'set null',
193 hooks: true
194 })
195 Avatar: AvatarModel
196
197 @HasMany(() => ActorFollowModel, {
198 foreignKey: {
199 name: 'actorId',
200 allowNull: false
201 },
202 onDelete: 'cascade'
203 })
204 ActorFollowing: ActorFollowModel[]
205
206 @HasMany(() => ActorFollowModel, {
207 foreignKey: {
208 name: 'targetActorId',
209 allowNull: false
210 },
211 as: 'ActorFollowers',
212 onDelete: 'cascade'
213 })
214 ActorFollowers: ActorFollowModel[]
215
216 @ForeignKey(() => ServerModel)
217 @Column
218 serverId: number
219
220 @BelongsTo(() => ServerModel, {
221 foreignKey: {
222 allowNull: true
223 },
224 onDelete: 'cascade'
225 })
226 Server: ServerModel
227
228 @HasOne(() => AccountModel, {
229 foreignKey: {
230 allowNull: true
231 },
232 onDelete: 'cascade',
233 hooks: true
234 })
235 Account: AccountModel
236
237 @HasOne(() => VideoChannelModel, {
238 foreignKey: {
239 allowNull: true
240 },
241 onDelete: 'cascade',
242 hooks: true
243 })
244 VideoChannel: VideoChannelModel
245
246 static load (id: number) {
247 return ActorModel.unscoped().findById(id)
248 }
249
250 static listByFollowersUrls (followersUrls: string[], transaction?: Sequelize.Transaction) {
251 const query = {
252 where: {
253 followersUrl: {
254 [ Sequelize.Op.in ]: followersUrls
255 }
256 },
257 transaction
258 }
259
260 return ActorModel.scope(ScopeNames.FULL).findAll(query)
261 }
262
263 static loadLocalByName (preferredUsername: string) {
264 const query = {
265 where: {
266 preferredUsername,
267 serverId: null
268 }
269 }
270
271 return ActorModel.scope(ScopeNames.FULL).findOne(query)
272 }
273
274 static loadByNameAndHost (preferredUsername: string, host: string) {
275 const query = {
276 where: {
277 preferredUsername
278 },
279 include: [
280 {
281 model: ServerModel,
282 required: true,
283 where: {
284 host
285 }
286 }
287 ]
288 }
289
290 return ActorModel.scope(ScopeNames.FULL).findOne(query)
291 }
292
293 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
294 const query = {
295 where: {
296 url
297 },
298 transaction
299 }
300
301 return ActorModel.scope(ScopeNames.FULL).findOne(query)
302 }
303
304 static incrementFollows (id: number, column: 'followersCount' | 'followingCount', by: number) {
305 // FIXME: typings
306 return (ActorModel as any).increment(column, {
307 by,
308 where: {
309 id
310 }
311 })
312 }
313
314 static async getActorsFollowerSharedInboxUrls (actors: ActorModel[], t: Sequelize.Transaction) {
315 const query = {
316 // attribute: [],
317 where: {
318 id: {
319 [Sequelize.Op.in]: actors.map(a => a.id)
320 }
321 },
322 include: [
323 {
324 // attributes: [ ],
325 model: ActorFollowModel.unscoped(),
326 required: true,
327 as: 'ActorFollowers',
328 where: {
329 state: 'accepted'
330 },
331 include: [
332 {
333 attributes: [ 'sharedInboxUrl' ],
334 model: ActorModel.unscoped(),
335 as: 'ActorFollower',
336 required: true
337 }
338 ]
339 }
340 ],
341 transaction: t
342 }
343
344 const hash: { [ id: number ]: string[] } = {}
345 const res = await ActorModel.findAll(query)
346 for (const actor of res) {
347 hash[actor.id] = actor.ActorFollowers.map(follow => follow.ActorFollower.sharedInboxUrl)
348 }
349
350 return hash
351 }
352
353 toFormattedJSON () {
354 let avatar: Avatar = null
355 if (this.Avatar) {
356 avatar = this.Avatar.toFormattedJSON()
357 }
358
359 return {
360 id: this.id,
361 url: this.url,
362 uuid: this.uuid,
363 name: this.preferredUsername,
364 host: this.getHost(),
365 followingCount: this.followingCount,
366 followersCount: this.followersCount,
367 avatar,
368 createdAt: this.createdAt,
369 updatedAt: this.updatedAt
370 }
371 }
372
373 toActivityPubObject (name: string, type: 'Account' | 'Application' | 'VideoChannel') {
374 let activityPubType
375 if (type === 'Account') {
376 activityPubType = 'Person' as 'Person'
377 } else if (type === 'Application') {
378 activityPubType = 'Application' as 'Application'
379 } else { // VideoChannel
380 activityPubType = 'Group' as 'Group'
381 }
382
383 let icon = undefined
384 if (this.avatarId) {
385 const extension = extname(this.Avatar.filename)
386 icon = {
387 type: 'Image',
388 mediaType: extension === '.png' ? 'image/png' : 'image/jpeg',
389 url: this.getAvatarUrl()
390 }
391 }
392
393 const json = {
394 type: activityPubType,
395 id: this.url,
396 following: this.getFollowingUrl(),
397 followers: this.getFollowersUrl(),
398 inbox: this.inboxUrl,
399 outbox: this.outboxUrl,
400 preferredUsername: this.preferredUsername,
401 url: this.url,
402 name,
403 endpoints: {
404 sharedInbox: this.sharedInboxUrl
405 },
406 uuid: this.uuid,
407 publicKey: {
408 id: this.getPublicKeyUrl(),
409 owner: this.url,
410 publicKeyPem: this.publicKey
411 },
412 icon
413 }
414
415 return activityPubContextify(json)
416 }
417
418 getFollowerSharedInboxUrls (t: Sequelize.Transaction) {
419 const query = {
420 attributes: [ 'sharedInboxUrl' ],
421 include: [
422 {
423 attribute: [],
424 model: ActorFollowModel.unscoped(),
425 required: true,
426 as: 'ActorFollowing',
427 where: {
428 state: 'accepted',
429 targetActorId: this.id
430 }
431 }
432 ],
433 transaction: t
434 }
435
436 return ActorModel.findAll(query)
437 .then(accounts => accounts.map(a => a.sharedInboxUrl))
438 }
439
440 getFollowingUrl () {
441 return this.url + '/following'
442 }
443
444 getFollowersUrl () {
445 return this.url + '/followers'
446 }
447
448 getPublicKeyUrl () {
449 return this.url + '#main-key'
450 }
451
452 isOwned () {
453 return this.serverId === null
454 }
455
456 getWebfingerUrl () {
457 return 'acct:' + this.preferredUsername + '@' + this.getHost()
458 }
459
460 getIdentifier () {
461 return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername
462 }
463
464 getHost () {
465 return this.Server ? this.Server.host : CONFIG.WEBSERVER.HOST
466 }
467
468 getAvatarUrl () {
469 if (!this.avatarId) return undefined
470
471 return CONFIG.WEBSERVER.URL + this.Avatar.getWebserverPath()
472 }
473
474 isOutdated () {
475 if (this.isOwned()) return false
476
477 const now = Date.now()
478 const createdAtTime = this.createdAt.getTime()
479 const updatedAtTime = this.updatedAt.getTime()
480
481 return (now - createdAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL &&
482 (now - updatedAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL
483 }
484 }