Status are sent to mastodon
[oweals/peertube.git] / server / models / activitypub / actor.ts
1 import { values } from 'lodash'
2 import { join } from 'path'
3 import * as Sequelize from 'sequelize'
4 import {
5   AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, DefaultScope, ForeignKey, HasMany, HasOne, Is, IsUUID, Model, Scopes,
6   Table, UpdatedAt
7 } from 'sequelize-typescript'
8 import { ActivityPubActorType } from '../../../shared/models/activitypub'
9 import { Avatar } from '../../../shared/models/avatars/avatar.model'
10 import { activityPubContextify } from '../../helpers'
11 import {
12   isActivityPubUrlValid, isActorFollowersCountValid, isActorFollowingCountValid, isActorPreferredUsernameValid,
13   isActorPrivateKeyValid, isActorPublicKeyValid
14 } from '../../helpers/custom-validators/activitypub'
15 import { ACTIVITY_PUB_ACTOR_TYPES, AVATARS_DIR, CONFIG, CONSTRAINTS_FIELDS } from '../../initializers'
16 import { AccountModel } from '../account/account'
17 import { AvatarModel } from '../avatar/avatar'
18 import { ServerModel } from '../server/server'
19 import { throwIfNotValid } from '../utils'
20 import { VideoChannelModel } from '../video/video-channel'
21 import { ActorFollowModel } from './actor-follow'
22
23 enum ScopeNames {
24   FULL = 'FULL'
25 }
26
27 @DefaultScope({
28   include: [
29     {
30       model: () => ServerModel,
31       required: false
32     }
33   ]
34 })
35 @Scopes({
36   [ScopeNames.FULL]: {
37     include: [
38       {
39         model: () => AccountModel,
40         required: false
41       },
42       {
43         model: () => VideoChannelModel,
44         required: false
45       },
46       {
47         model: () => ServerModel,
48         required: false
49       }
50     ]
51   }
52 })
53 @Table({
54   tableName: 'actor',
55   indexes: [
56     {
57       fields: [ 'preferredUsername', 'serverId' ],
58       unique: true
59     }
60   ]
61 })
62 export class ActorModel extends Model<ActorModel> {
63
64   @AllowNull(false)
65   @Column(DataType.ENUM(values(ACTIVITY_PUB_ACTOR_TYPES)))
66   type: ActivityPubActorType
67
68   @AllowNull(false)
69   @Default(DataType.UUIDV4)
70   @IsUUID(4)
71   @Column(DataType.UUID)
72   uuid: string
73
74   @AllowNull(false)
75   @Is('ActorPreferredUsername', value => throwIfNotValid(value, isActorPreferredUsernameValid, 'actor preferred username'))
76   @Column
77   preferredUsername: string
78
79   @AllowNull(false)
80   @Is('ActorUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
81   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.URL.max))
82   url: string
83
84   @AllowNull(true)
85   @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPublicKeyValid, 'public key'))
86   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.PUBLIC_KEY.max))
87   publicKey: string
88
89   @AllowNull(true)
90   @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPrivateKeyValid, 'private key'))
91   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.PRIVATE_KEY.max))
92   privateKey: string
93
94   @AllowNull(false)
95   @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowersCountValid, 'followers count'))
96   @Column
97   followersCount: number
98
99   @AllowNull(false)
100   @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowingCountValid, 'following count'))
101   @Column
102   followingCount: number
103
104   @AllowNull(false)
105   @Is('ActorInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'inbox url'))
106   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.URL.max))
107   inboxUrl: string
108
109   @AllowNull(false)
110   @Is('ActorOutboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'outbox url'))
111   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.URL.max))
112   outboxUrl: string
113
114   @AllowNull(false)
115   @Is('ActorSharedInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'shared inbox url'))
116   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.URL.max))
117   sharedInboxUrl: string
118
119   @AllowNull(false)
120   @Is('ActorFollowersUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'followers url'))
121   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.URL.max))
122   followersUrl: string
123
124   @AllowNull(false)
125   @Is('ActorFollowingUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'following url'))
126   @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.URL.max))
127   followingUrl: string
128
129   @CreatedAt
130   createdAt: Date
131
132   @UpdatedAt
133   updatedAt: Date
134
135   @ForeignKey(() => AvatarModel)
136   @Column
137   avatarId: number
138
139   @BelongsTo(() => AvatarModel, {
140     foreignKey: {
141       allowNull: true
142     },
143     onDelete: 'cascade'
144   })
145   Avatar: AvatarModel
146
147   @HasMany(() => ActorFollowModel, {
148     foreignKey: {
149       name: 'actorId',
150       allowNull: false
151     },
152     onDelete: 'cascade'
153   })
154   AccountFollowing: ActorFollowModel[]
155
156   @HasMany(() => ActorFollowModel, {
157     foreignKey: {
158       name: 'targetActorId',
159       allowNull: false
160     },
161     as: 'followers',
162     onDelete: 'cascade'
163   })
164   AccountFollowers: ActorFollowModel[]
165
166   @ForeignKey(() => ServerModel)
167   @Column
168   serverId: number
169
170   @BelongsTo(() => ServerModel, {
171     foreignKey: {
172       allowNull: true
173     },
174     onDelete: 'cascade'
175   })
176   Server: ServerModel
177
178   @HasOne(() => AccountModel, {
179     foreignKey: {
180       allowNull: true
181     },
182     onDelete: 'cascade'
183   })
184   Account: AccountModel
185
186   @HasOne(() => VideoChannelModel, {
187     foreignKey: {
188       allowNull: true
189     },
190     onDelete: 'cascade'
191   })
192   VideoChannel: VideoChannelModel
193
194   static load (id: number) {
195     return ActorModel.scope(ScopeNames.FULL).findById(id)
196   }
197
198   static listByFollowersUrls (followersUrls: string[], transaction?: Sequelize.Transaction) {
199     const query = {
200       where: {
201         followersUrl: {
202           [ Sequelize.Op.in ]: followersUrls
203         }
204       },
205       transaction
206     }
207
208     return ActorModel.scope(ScopeNames.FULL).findAll(query)
209   }
210
211   static loadLocalByName (preferredUsername: string) {
212     const query = {
213       where: {
214         preferredUsername,
215         serverId: null
216       }
217     }
218
219     return ActorModel.scope(ScopeNames.FULL).findOne(query)
220   }
221
222   static loadByNameAndHost (preferredUsername: string, host: string) {
223     const query = {
224       where: {
225         preferredUsername
226       },
227       include: [
228         {
229           model: ServerModel,
230           required: true,
231           where: {
232             host
233           }
234         }
235       ]
236     }
237
238     return ActorModel.scope(ScopeNames.FULL).findOne(query)
239   }
240
241   static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
242     const query = {
243       where: {
244         url
245       },
246       transaction
247     }
248
249     return ActorModel.scope(ScopeNames.FULL).findOne(query)
250   }
251
252   toFormattedJSON () {
253     let avatar: Avatar = null
254     if (this.Avatar) {
255       avatar = {
256         path: join(AVATARS_DIR.ACCOUNT, this.Avatar.filename),
257         createdAt: this.Avatar.createdAt,
258         updatedAt: this.Avatar.updatedAt
259       }
260     }
261
262     let score: number
263     if (this.Server) {
264       score = this.Server.score
265     }
266
267     return {
268       id: this.id,
269       uuid: this.uuid,
270       host: this.getHost(),
271       score,
272       followingCount: this.followingCount,
273       followersCount: this.followersCount,
274       avatar
275     }
276   }
277
278   toActivityPubObject (name: string, type: 'Account' | 'Application' | 'VideoChannel') {
279     let activityPubType
280     if (type === 'Account') {
281       activityPubType = 'Person' as 'Person'
282     } else if (type === 'Application') {
283       activityPubType = 'Application' as 'Application'
284     } else { // VideoChannel
285       activityPubType = 'Group' as 'Group'
286     }
287
288     const json = {
289       type: activityPubType,
290       id: this.url,
291       following: this.getFollowingUrl(),
292       followers: this.getFollowersUrl(),
293       inbox: this.inboxUrl,
294       outbox: this.outboxUrl,
295       preferredUsername: this.preferredUsername,
296       url: this.url,
297       name,
298       endpoints: {
299         sharedInbox: this.sharedInboxUrl
300       },
301       uuid: this.uuid,
302       publicKey: {
303         id: this.getPublicKeyUrl(),
304         owner: this.url,
305         publicKeyPem: this.publicKey
306       }
307     }
308
309     return activityPubContextify(json)
310   }
311
312   getFollowerSharedInboxUrls (t: Sequelize.Transaction) {
313     const query = {
314       attributes: [ 'sharedInboxUrl' ],
315       include: [
316         {
317           model: ActorFollowModel,
318           required: true,
319           as: 'followers',
320           where: {
321             targetActorId: this.id
322           }
323         }
324       ],
325       transaction: t
326     }
327
328     return ActorModel.findAll(query)
329       .then(accounts => accounts.map(a => a.sharedInboxUrl))
330   }
331
332   getFollowingUrl () {
333     return this.url + '/following'
334   }
335
336   getFollowersUrl () {
337     return this.url + '/followers'
338   }
339
340   getPublicKeyUrl () {
341     return this.url + '#main-key'
342   }
343
344   isOwned () {
345     return this.serverId === null
346   }
347
348   getWebfingerUrl () {
349     return 'acct:' + this.preferredUsername + '@' + this.getHost()
350   }
351
352   getHost () {
353     return this.Server ? this.Server.host : CONFIG.WEBSERVER.HOST
354   }
355 }