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