]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/activitypub/actor.ts
2abf4071373ff4504b993fc214a181018f3384c6
[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, transaction?: Sequelize.Transaction) {
264 const query = {
265 where: {
266 preferredUsername,
267 serverId: null
268 },
269 transaction
270 }
271
272 return ActorModel.scope(ScopeNames.FULL).findOne(query)
273 }
274
275 static loadByNameAndHost (preferredUsername: string, host: string) {
276 const query = {
277 where: {
278 preferredUsername
279 },
280 include: [
281 {
282 model: ServerModel,
283 required: true,
284 where: {
285 host
286 }
287 }
288 ]
289 }
290
291 return ActorModel.scope(ScopeNames.FULL).findOne(query)
292 }
293
294 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
295 const query = {
296 where: {
297 url
298 },
299 transaction
300 }
301
302 return ActorModel.scope(ScopeNames.FULL).findOne(query)
303 }
304
305 static incrementFollows (id: number, column: 'followersCount' | 'followingCount', by: number) {
306 // FIXME: typings
307 return (ActorModel as any).increment(column, {
308 by,
309 where: {
310 id
311 }
312 })
313 }
314
315 static async getActorsFollowerSharedInboxUrls (actors: ActorModel[], t: Sequelize.Transaction) {
316 const query = {
317 // attribute: [],
318 where: {
319 id: {
320 [Sequelize.Op.in]: actors.map(a => a.id)
321 }
322 },
323 include: [
324 {
325 // attributes: [ ],
326 model: ActorFollowModel.unscoped(),
327 required: true,
328 as: 'ActorFollowers',
329 where: {
330 state: 'accepted'
331 },
332 include: [
333 {
334 attributes: [ 'sharedInboxUrl' ],
335 model: ActorModel.unscoped(),
336 as: 'ActorFollower',
337 required: true
338 }
339 ]
340 }
341 ],
342 transaction: t
343 }
344
345 const hash: { [ id: number ]: string[] } = {}
346 const res = await ActorModel.findAll(query)
347 for (const actor of res) {
348 hash[actor.id] = actor.ActorFollowers.map(follow => follow.ActorFollower.sharedInboxUrl)
349 }
350
351 return hash
352 }
353
354 toFormattedJSON () {
355 let avatar: Avatar = null
356 if (this.Avatar) {
357 avatar = this.Avatar.toFormattedJSON()
358 }
359
360 return {
361 id: this.id,
362 url: this.url,
363 uuid: this.uuid,
364 name: this.preferredUsername,
365 host: this.getHost(),
366 followingCount: this.followingCount,
367 followersCount: this.followersCount,
368 avatar,
369 createdAt: this.createdAt,
370 updatedAt: this.updatedAt
371 }
372 }
373
374 toActivityPubObject (name: string, type: 'Account' | 'Application' | 'VideoChannel') {
375 let activityPubType
376 if (type === 'Account') {
377 activityPubType = 'Person' as 'Person'
378 } else if (type === 'Application') {
379 activityPubType = 'Application' as 'Application'
380 } else { // VideoChannel
381 activityPubType = 'Group' as 'Group'
382 }
383
384 let icon = undefined
385 if (this.avatarId) {
386 const extension = extname(this.Avatar.filename)
387 icon = {
388 type: 'Image',
389 mediaType: extension === '.png' ? 'image/png' : 'image/jpeg',
390 url: this.getAvatarUrl()
391 }
392 }
393
394 const json = {
395 type: activityPubType,
396 id: this.url,
397 following: this.getFollowingUrl(),
398 followers: this.getFollowersUrl(),
399 inbox: this.inboxUrl,
400 outbox: this.outboxUrl,
401 preferredUsername: this.preferredUsername,
402 url: this.url,
403 name,
404 endpoints: {
405 sharedInbox: this.sharedInboxUrl
406 },
407 uuid: this.uuid,
408 publicKey: {
409 id: this.getPublicKeyUrl(),
410 owner: this.url,
411 publicKeyPem: this.publicKey
412 },
413 icon
414 }
415
416 return activityPubContextify(json)
417 }
418
419 getFollowerSharedInboxUrls (t: Sequelize.Transaction) {
420 const query = {
421 attributes: [ 'sharedInboxUrl' ],
422 include: [
423 {
424 attribute: [],
425 model: ActorFollowModel.unscoped(),
426 required: true,
427 as: 'ActorFollowing',
428 where: {
429 state: 'accepted',
430 targetActorId: this.id
431 }
432 }
433 ],
434 transaction: t
435 }
436
437 return ActorModel.findAll(query)
438 .then(accounts => accounts.map(a => a.sharedInboxUrl))
439 }
440
441 getFollowingUrl () {
442 return this.url + '/following'
443 }
444
445 getFollowersUrl () {
446 return this.url + '/followers'
447 }
448
449 getPublicKeyUrl () {
450 return this.url + '#main-key'
451 }
452
453 isOwned () {
454 return this.serverId === null
455 }
456
457 getWebfingerUrl () {
458 return 'acct:' + this.preferredUsername + '@' + this.getHost()
459 }
460
461 getIdentifier () {
462 return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername
463 }
464
465 getHost () {
466 return this.Server ? this.Server.host : CONFIG.WEBSERVER.HOST
467 }
468
469 getAvatarUrl () {
470 if (!this.avatarId) return undefined
471
472 return CONFIG.WEBSERVER.URL + this.Avatar.getWebserverPath()
473 }
474
475 isOutdated () {
476 if (this.isOwned()) return false
477
478 const now = Date.now()
479 const createdAtTime = this.createdAt.getTime()
480 const updatedAtTime = this.updatedAt.getTime()
481
482 return (now - createdAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL &&
483 (now - updatedAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL
484 }
485 }