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