]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/activitypub/actor.ts
Move subscription helper in the account line
[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 BeforeDestroy,
7 BelongsTo,
8 Column,
9 CreatedAt,
10 DataType,
11 Default,
12 DefaultScope,
13 ForeignKey,
14 HasMany,
15 HasOne,
16 Is,
17 IsUUID,
18 Model,
19 Scopes,
20 Table,
21 UpdatedAt
22 } from 'sequelize-typescript'
23 import { ActivityPubActorType } from '../../../shared/models/activitypub'
24 import { Avatar } from '../../../shared/models/avatars/avatar.model'
25 import { activityPubContextify } from '../../helpers/activitypub'
26 import {
27 isActorFollowersCountValid,
28 isActorFollowingCountValid,
29 isActorPreferredUsernameValid,
30 isActorPrivateKeyValid,
31 isActorPublicKeyValid
32 } from '../../helpers/custom-validators/activitypub/actor'
33 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
34 import { ACTIVITY_PUB, ACTIVITY_PUB_ACTOR_TYPES, CONFIG, CONSTRAINTS_FIELDS } from '../../initializers'
35 import { AccountModel } from '../account/account'
36 import { AvatarModel } from '../avatar/avatar'
37 import { ServerModel } from '../server/server'
38 import { throwIfNotValid } from '../utils'
39 import { VideoChannelModel } from '../video/video-channel'
40 import { ActorFollowModel } from './actor-follow'
41 import { logger } from '../../helpers/logger'
42 import { sendDeleteActor } from '../../lib/activitypub/send'
43
44 enum ScopeNames {
45 FULL = 'FULL'
46 }
47
48 @DefaultScope({
49 include: [
50 {
51 model: () => ServerModel,
52 required: false
53 },
54 {
55 model: () => AvatarModel,
56 required: false
57 }
58 ]
59 })
60 @Scopes({
61 [ScopeNames.FULL]: {
62 include: [
63 {
64 model: () => AccountModel.unscoped(),
65 required: false
66 },
67 {
68 model: () => VideoChannelModel.unscoped(),
69 required: false
70 },
71 {
72 model: () => ServerModel,
73 required: false
74 },
75 {
76 model: () => AvatarModel,
77 required: false
78 }
79 ]
80 }
81 })
82 @Table({
83 tableName: 'actor',
84 indexes: [
85 {
86 fields: [ 'url' ],
87 unique: true
88 },
89 {
90 fields: [ 'preferredUsername', 'serverId' ],
91 unique: true
92 },
93 {
94 fields: [ 'inboxUrl', '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: false
231 }
232 })
233 Account: AccountModel
234
235 @HasOne(() => VideoChannelModel, {
236 foreignKey: {
237 allowNull: false
238 }
239 })
240 VideoChannel: VideoChannelModel
241
242 @BeforeDestroy
243 static async sendDeleteIfOwned (instance: ActorModel, options) {
244 if (instance.isOwned()) {
245 logger.debug('Sending delete of actor %s.', instance.url)
246 return sendDeleteActor(instance, options.transaction)
247 }
248
249 return undefined
250 }
251
252 static load (id: number) {
253 return ActorModel.unscoped().findById(id)
254 }
255
256 static listByFollowersUrls (followersUrls: string[], transaction?: Sequelize.Transaction) {
257 const query = {
258 where: {
259 followersUrl: {
260 [ Sequelize.Op.in ]: followersUrls
261 }
262 },
263 transaction
264 }
265
266 return ActorModel.scope(ScopeNames.FULL).findAll(query)
267 }
268
269 static loadLocalByName (preferredUsername: string) {
270 const query = {
271 where: {
272 preferredUsername,
273 serverId: null
274 }
275 }
276
277 return ActorModel.scope(ScopeNames.FULL).findOne(query)
278 }
279
280 static loadByNameAndHost (preferredUsername: string, host: string) {
281 const query = {
282 where: {
283 preferredUsername
284 },
285 include: [
286 {
287 model: ServerModel,
288 required: true,
289 where: {
290 host
291 }
292 }
293 ]
294 }
295
296 return ActorModel.scope(ScopeNames.FULL).findOne(query)
297 }
298
299 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
300 const query = {
301 where: {
302 url
303 },
304 transaction
305 }
306
307 return ActorModel.scope(ScopeNames.FULL).findOne(query)
308 }
309
310 static incrementFollows (id: number, column: 'followersCount' | 'followingCount', by: number) {
311 // FIXME: typings
312 return (ActorModel as any).increment(column, {
313 by,
314 where: {
315 id
316 }
317 })
318 }
319
320 static async getActorsFollowerSharedInboxUrls (actors: ActorModel[], t: Sequelize.Transaction) {
321 const query = {
322 // attribute: [],
323 where: {
324 id: {
325 [Sequelize.Op.in]: actors.map(a => a.id)
326 }
327 },
328 include: [
329 {
330 // attributes: [ ],
331 model: ActorFollowModel.unscoped(),
332 required: true,
333 as: 'ActorFollowers',
334 where: {
335 state: 'accepted'
336 },
337 include: [
338 {
339 attributes: [ 'sharedInboxUrl' ],
340 model: ActorModel.unscoped(),
341 as: 'ActorFollower',
342 required: true
343 }
344 ]
345 }
346 ],
347 transaction: t
348 }
349
350 const hash: { [ id: number ]: string[] } = {}
351 const res = await ActorModel.findAll(query)
352 for (const actor of res) {
353 hash[actor.id] = actor.ActorFollowers.map(follow => follow.ActorFollower.sharedInboxUrl)
354 }
355
356 return hash
357 }
358
359 toFormattedJSON () {
360 let avatar: Avatar = null
361 if (this.Avatar) {
362 avatar = this.Avatar.toFormattedJSON()
363 }
364
365 return {
366 id: this.id,
367 url: this.url,
368 uuid: this.uuid,
369 name: this.preferredUsername,
370 host: this.getHost(),
371 followingCount: this.followingCount,
372 followersCount: this.followersCount,
373 avatar,
374 createdAt: this.createdAt,
375 updatedAt: this.updatedAt
376 }
377 }
378
379 toActivityPubObject (name: string, type: 'Account' | 'Application' | 'VideoChannel') {
380 let activityPubType
381 if (type === 'Account') {
382 activityPubType = 'Person' as 'Person'
383 } else if (type === 'Application') {
384 activityPubType = 'Application' as 'Application'
385 } else { // VideoChannel
386 activityPubType = 'Group' as 'Group'
387 }
388
389 let icon = undefined
390 if (this.avatarId) {
391 const extension = extname(this.Avatar.filename)
392 icon = {
393 type: 'Image',
394 mediaType: extension === '.png' ? 'image/png' : 'image/jpeg',
395 url: this.getAvatarUrl()
396 }
397 }
398
399 const json = {
400 type: activityPubType,
401 id: this.url,
402 following: this.getFollowingUrl(),
403 followers: this.getFollowersUrl(),
404 inbox: this.inboxUrl,
405 outbox: this.outboxUrl,
406 preferredUsername: this.preferredUsername,
407 url: this.url,
408 name,
409 endpoints: {
410 sharedInbox: this.sharedInboxUrl
411 },
412 uuid: this.uuid,
413 publicKey: {
414 id: this.getPublicKeyUrl(),
415 owner: this.url,
416 publicKeyPem: this.publicKey
417 },
418 icon
419 }
420
421 return activityPubContextify(json)
422 }
423
424 getFollowerSharedInboxUrls (t: Sequelize.Transaction) {
425 const query = {
426 attributes: [ 'sharedInboxUrl' ],
427 include: [
428 {
429 attribute: [],
430 model: ActorFollowModel.unscoped(),
431 required: true,
432 as: 'ActorFollowing',
433 where: {
434 state: 'accepted',
435 targetActorId: this.id
436 }
437 }
438 ],
439 transaction: t
440 }
441
442 return ActorModel.findAll(query)
443 .then(accounts => accounts.map(a => a.sharedInboxUrl))
444 }
445
446 getFollowingUrl () {
447 return this.url + '/following'
448 }
449
450 getFollowersUrl () {
451 return this.url + '/followers'
452 }
453
454 getPublicKeyUrl () {
455 return this.url + '#main-key'
456 }
457
458 isOwned () {
459 return this.serverId === null
460 }
461
462 getWebfingerUrl () {
463 return 'acct:' + this.preferredUsername + '@' + this.getHost()
464 }
465
466 getHost () {
467 return this.Server ? this.Server.host : CONFIG.WEBSERVER.HOST
468 }
469
470 getAvatarUrl () {
471 if (!this.avatarId) return undefined
472
473 return CONFIG.WEBSERVER.URL + this.Avatar.getWebserverPath()
474 }
475
476 isOutdated () {
477 if (this.isOwned()) return false
478
479 const now = Date.now()
480 const createdAtTime = this.createdAt.getTime()
481 const updatedAtTime = this.updatedAt.getTime()
482
483 return (now - createdAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL &&
484 (now - updatedAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL
485 }
486 }