]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/activitypub/actor-follow.ts
modify user-quota to match account settings style
[github/Chocobozzz/PeerTube.git] / server / models / activitypub / actor-follow.ts
CommitLineData
50d6de9c 1import * as Bluebird from 'bluebird'
a1587156 2import { difference, values } from 'lodash'
60650c77 3import {
06a05d5f
C
4 AfterCreate,
5 AfterDestroy,
6 AfterUpdate,
7 AllowNull,
8 BelongsTo,
9 Column,
10 CreatedAt,
11 DataType,
12 Default,
13 ForeignKey,
14 IsInt,
15 Max,
16 Model,
17 Table,
4f5d0459
RK
18 UpdatedAt,
19 Sequelize
60650c77 20} from 'sequelize-typescript'
50d6de9c 21import { FollowState } from '../../../shared/models/actors'
c48e82b5 22import { ActorFollow } from '../../../shared/models/actors/follow.model'
60650c77 23import { logger } from '../../helpers/logger'
6f1b4fa4 24import { ACTOR_FOLLOW_SCORE, FOLLOW_STATES, SERVER_ACTOR_NAME } from '../../initializers/constants'
50d6de9c 25import { ServerModel } from '../server/server'
4f5d0459 26import { createSafeIn, getFollowsSort, getSort, searchAttribute } from '../utils'
f37dc0dd 27import { ActorModel, unusedActorAttributesForAPI } from './actor'
06a05d5f 28import { VideoChannelModel } from '../video/video-channel'
22a16e36 29import { AccountModel } from '../account/account'
97ecddae 30import { IncludeOptions, Op, QueryTypes, Transaction, WhereOptions } from 'sequelize'
453e83ea
C
31import {
32 MActorFollowActorsDefault,
33 MActorFollowActorsDefaultSubscription,
34 MActorFollowFollowingHost,
1ca9f7c3 35 MActorFollowFormattable,
453e83ea 36 MActorFollowSubscriptions
26d6bf65 37} from '@server/types/models'
97ecddae 38import { ActivityPubActorType } from '@shared/models'
8c9e7875 39import { VideoModel } from '@server/models/video/video'
8dc8a34e 40import { getServerActor } from '@server/models/application/application'
50d6de9c
C
41
42@Table({
43 tableName: 'actorFollow',
44 indexes: [
45 {
46 fields: [ 'actorId' ]
47 },
48 {
49 fields: [ 'targetActorId' ]
50 },
51 {
52 fields: [ 'actorId', 'targetActorId' ],
53 unique: true
60650c77
C
54 },
55 {
56 fields: [ 'score' ]
50d6de9c
C
57 }
58 ]
59})
60export class ActorFollowModel extends Model<ActorFollowModel> {
61
62 @AllowNull(false)
1735c825 63 @Column(DataType.ENUM(...values(FOLLOW_STATES)))
50d6de9c
C
64 state: FollowState
65
60650c77
C
66 @AllowNull(false)
67 @Default(ACTOR_FOLLOW_SCORE.BASE)
68 @IsInt
69 @Max(ACTOR_FOLLOW_SCORE.MAX)
70 @Column
71 score: number
72
50d6de9c
C
73 @CreatedAt
74 createdAt: Date
75
76 @UpdatedAt
77 updatedAt: Date
78
79 @ForeignKey(() => ActorModel)
80 @Column
81 actorId: number
82
83 @BelongsTo(() => ActorModel, {
84 foreignKey: {
85 name: 'actorId',
86 allowNull: false
87 },
88 as: 'ActorFollower',
89 onDelete: 'CASCADE'
90 })
91 ActorFollower: ActorModel
92
93 @ForeignKey(() => ActorModel)
94 @Column
95 targetActorId: number
96
97 @BelongsTo(() => ActorModel, {
98 foreignKey: {
99 name: 'targetActorId',
100 allowNull: false
101 },
102 as: 'ActorFollowing',
103 onDelete: 'CASCADE'
104 })
105 ActorFollowing: ActorModel
106
32b2b43c
C
107 @AfterCreate
108 @AfterUpdate
e6122097 109 static incrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
38768a36 110 if (instance.state !== 'accepted') return undefined
32b2b43c
C
111
112 return Promise.all([
e6122097
C
113 ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction),
114 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction)
32b2b43c
C
115 ])
116 }
117
118 @AfterDestroy
e6122097 119 static decrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) {
32b2b43c 120 return Promise.all([
e6122097
C
121 ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction),
122 ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction)
32b2b43c
C
123 ])
124 }
125
44b88f18
C
126 static removeFollowsOf (actorId: number, t?: Transaction) {
127 const query = {
128 where: {
129 [Op.or]: [
130 {
131 actorId
132 },
133 {
134 targetActorId: actorId
135 }
136 ]
137 },
138 transaction: t
139 }
140
141 return ActorFollowModel.destroy(query)
142 }
143
60650c77
C
144 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
145 static async removeBadActorFollows () {
146 const actorFollows = await ActorFollowModel.listBadActorFollows()
147
148 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
149 await Promise.all(actorFollowsRemovePromises)
150
151 const numberOfActorFollowsRemoved = actorFollows.length
152
153 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
154 }
155
8c9e7875
C
156 static isFollowedBy (actorId: number, followerActorId: number) {
157 const query = 'SELECT 1 FROM "actorFollow" WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId LIMIT 1'
158 const options = {
159 type: QueryTypes.SELECT as QueryTypes.SELECT,
160 bind: { actorId, followerActorId },
161 raw: true
162 }
163
164 return VideoModel.sequelize.query(query, options)
165 .then(results => results.length === 1)
166 }
167
453e83ea 168 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Bluebird<MActorFollowActorsDefault> {
50d6de9c
C
169 const query = {
170 where: {
171 actorId,
172 targetActorId: targetActorId
173 },
174 include: [
175 {
176 model: ActorModel,
177 required: true,
178 as: 'ActorFollower'
179 },
180 {
181 model: ActorModel,
182 required: true,
183 as: 'ActorFollowing'
184 }
185 ],
186 transaction: t
187 }
188
189 return ActorFollowModel.findOne(query)
190 }
191
453e83ea
C
192 static loadByActorAndTargetNameAndHostForAPI (
193 actorId: number,
194 targetName: string,
195 targetHost: string,
196 t?: Transaction
197 ): Bluebird<MActorFollowActorsDefaultSubscription> {
1735c825 198 const actorFollowingPartInclude: IncludeOptions = {
06a05d5f
C
199 model: ActorModel,
200 required: true,
201 as: 'ActorFollowing',
202 where: {
203 preferredUsername: targetName
99492dbc
C
204 },
205 include: [
206 {
f37dc0dd 207 model: VideoChannelModel.unscoped(),
99492dbc
C
208 required: false
209 }
210 ]
06a05d5f
C
211 }
212
213 if (targetHost === null) {
214 actorFollowingPartInclude.where['serverId'] = null
215 } else {
99492dbc
C
216 actorFollowingPartInclude.include.push({
217 model: ServerModel,
218 required: true,
219 where: {
220 host: targetHost
221 }
06a05d5f
C
222 })
223 }
224
50d6de9c
C
225 const query = {
226 where: {
227 actorId
228 },
229 include: [
aa55a4da
C
230 actorFollowingPartInclude,
231 {
232 model: ActorModel,
233 required: true,
234 as: 'ActorFollower'
235 }
50d6de9c
C
236 ],
237 transaction: t
238 }
239
6502c3d4 240 return ActorFollowModel.findOne(query)
f37dc0dd 241 .then(result => {
a1587156 242 if (result?.ActorFollowing.VideoChannel) {
f37dc0dd
C
243 result.ActorFollowing.VideoChannel.Actor = result.ActorFollowing
244 }
245
246 return result
247 })
248 }
249
453e83ea 250 static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]): Bluebird<MActorFollowFollowingHost[]> {
f37dc0dd
C
251 const whereTab = targets
252 .map(t => {
253 if (t.host) {
254 return {
a1587156 255 [Op.and]: [
f37dc0dd 256 {
a1587156 257 $preferredUsername$: t.name
f37dc0dd
C
258 },
259 {
a1587156 260 $host$: t.host
f37dc0dd
C
261 }
262 ]
263 }
264 }
265
266 return {
a1587156 267 [Op.and]: [
f37dc0dd 268 {
a1587156 269 $preferredUsername$: t.name
f37dc0dd
C
270 },
271 {
a1587156 272 $serverId$: null
f37dc0dd
C
273 }
274 ]
275 }
276 })
277
278 const query = {
279 attributes: [],
280 where: {
a1587156 281 [Op.and]: [
f37dc0dd 282 {
a1587156 283 [Op.or]: whereTab
f37dc0dd
C
284 },
285 {
286 actorId
287 }
288 ]
289 },
290 include: [
291 {
292 attributes: [ 'preferredUsername' ],
293 model: ActorModel.unscoped(),
294 required: true,
295 as: 'ActorFollowing',
296 include: [
297 {
298 attributes: [ 'host' ],
299 model: ServerModel.unscoped(),
300 required: false
301 }
302 ]
303 }
304 ]
305 }
306
307 return ActorFollowModel.findAll(query)
6502c3d4
C
308 }
309
b8f4167f 310 static listFollowingForApi (options: {
a1587156
C
311 id: number
312 start: number
313 count: number
314 sort: string
315 state?: FollowState
316 actorType?: ActivityPubActorType
b8f4167f
C
317 search?: string
318 }) {
97ecddae 319 const { id, start, count, sort, search, state, actorType } = options
b8f4167f
C
320
321 const followWhere = state ? { state } : {}
97ecddae
C
322 const followingWhere: WhereOptions = {}
323 const followingServerWhere: WhereOptions = {}
324
325 if (search) {
326 Object.assign(followingServerWhere, {
327 host: {
a1587156 328 [Op.iLike]: '%' + search + '%'
97ecddae
C
329 }
330 })
331 }
332
333 if (actorType) {
334 Object.assign(followingWhere, { type: actorType })
335 }
b8f4167f 336
50d6de9c
C
337 const query = {
338 distinct: true,
339 offset: start,
340 limit: count,
cb5ce4cb 341 order: getFollowsSort(sort),
b8f4167f 342 where: followWhere,
50d6de9c
C
343 include: [
344 {
345 model: ActorModel,
346 required: true,
347 as: 'ActorFollower',
348 where: {
349 id
350 }
351 },
352 {
353 model: ActorModel,
354 as: 'ActorFollowing',
355 required: true,
97ecddae 356 where: followingWhere,
b014b6b9
C
357 include: [
358 {
359 model: ServerModel,
360 required: true,
97ecddae 361 where: followingServerWhere
b014b6b9
C
362 }
363 ]
50d6de9c
C
364 }
365 ]
366 }
367
453e83ea 368 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
50d6de9c
C
369 .then(({ rows, count }) => {
370 return {
371 data: rows,
372 total: count
373 }
374 })
375 }
376
b8f4167f 377 static listFollowersForApi (options: {
a1587156
C
378 actorId: number
379 start: number
380 count: number
381 sort: string
382 state?: FollowState
383 actorType?: ActivityPubActorType
b8f4167f
C
384 search?: string
385 }) {
97ecddae 386 const { actorId, start, count, sort, search, state, actorType } = options
b8f4167f
C
387
388 const followWhere = state ? { state } : {}
97ecddae
C
389 const followerWhere: WhereOptions = {}
390 const followerServerWhere: WhereOptions = {}
391
392 if (search) {
393 Object.assign(followerServerWhere, {
394 host: {
a1587156 395 [Op.iLike]: '%' + search + '%'
97ecddae
C
396 }
397 })
398 }
399
400 if (actorType) {
401 Object.assign(followerWhere, { type: actorType })
402 }
b8f4167f 403
b014b6b9
C
404 const query = {
405 distinct: true,
406 offset: start,
407 limit: count,
cb5ce4cb 408 order: getFollowsSort(sort),
b8f4167f 409 where: followWhere,
b014b6b9
C
410 include: [
411 {
412 model: ActorModel,
413 required: true,
414 as: 'ActorFollower',
97ecddae 415 where: followerWhere,
b014b6b9
C
416 include: [
417 {
418 model: ServerModel,
419 required: true,
97ecddae 420 where: followerServerWhere
b014b6b9
C
421 }
422 ]
423 },
424 {
425 model: ActorModel,
426 as: 'ActorFollowing',
427 required: true,
428 where: {
cef534ed 429 id: actorId
b014b6b9
C
430 }
431 }
432 ]
433 }
434
453e83ea 435 return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query)
b014b6b9
C
436 .then(({ rows, count }) => {
437 return {
438 data: rows,
439 total: count
440 }
441 })
442 }
443
4f5d0459
RK
444 static listSubscriptionsForApi (options: {
445 actorId: number
446 start: number
447 count: number
448 sort: string
449 search?: string
450 }) {
451 const { actorId, start, count, sort } = options
452 const where = {
453 actorId: actorId
454 }
455
456 if (options.search) {
457 Object.assign(where, {
458 [Op.or]: [
459 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
460 searchAttribute(options.search, '$ActorFollowing.VideoChannel.name$')
461 ]
462 })
463 }
464
06a05d5f 465 const query = {
f37dc0dd 466 attributes: [],
06a05d5f
C
467 distinct: true,
468 offset: start,
469 limit: count,
470 order: getSort(sort),
4f5d0459 471 where,
06a05d5f
C
472 include: [
473 {
f5b0af50
C
474 attributes: [ 'id' ],
475 model: ActorModel.unscoped(),
06a05d5f
C
476 as: 'ActorFollowing',
477 required: true,
478 include: [
479 {
f5b0af50 480 model: VideoChannelModel.unscoped(),
22a16e36
C
481 required: true,
482 include: [
483 {
f37dc0dd
C
484 attributes: {
485 exclude: unusedActorAttributesForAPI
486 },
487 model: ActorModel,
22a16e36 488 required: true
f37dc0dd
C
489 },
490 {
f5b0af50 491 model: AccountModel.unscoped(),
f37dc0dd
C
492 required: true,
493 include: [
494 {
495 attributes: {
496 exclude: unusedActorAttributesForAPI
497 },
498 model: ActorModel,
499 required: true
500 }
501 ]
22a16e36
C
502 }
503 ]
06a05d5f
C
504 }
505 ]
506 }
507 ]
508 }
509
453e83ea 510 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
06a05d5f
C
511 .then(({ rows, count }) => {
512 return {
513 data: rows.map(r => r.ActorFollowing.VideoChannel),
514 total: count
515 }
516 })
517 }
518
6f1b4fa4
C
519 static async keepUnfollowedInstance (hosts: string[]) {
520 const followerId = (await getServerActor()).id
521
522 const query = {
10a105f0 523 attributes: [ 'id' ],
6f1b4fa4
C
524 where: {
525 actorId: followerId
526 },
527 include: [
528 {
10a105f0 529 attributes: [ 'id' ],
6f1b4fa4
C
530 model: ActorModel.unscoped(),
531 required: true,
532 as: 'ActorFollowing',
533 where: {
534 preferredUsername: SERVER_ACTOR_NAME
535 },
536 include: [
537 {
538 attributes: [ 'host' ],
539 model: ServerModel.unscoped(),
540 required: true,
541 where: {
542 host: {
543 [Op.in]: hosts
544 }
545 }
546 }
547 ]
548 }
549 ]
550 }
551
552 const res = await ActorFollowModel.findAll(query)
10a105f0 553 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
6f1b4fa4
C
554
555 return difference(hosts, followedHosts)
556 }
557
1735c825 558 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
50d6de9c
C
559 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
560 }
561
1735c825 562 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
ca309a9f 563 return ActorFollowModel.createListAcceptedFollowForApiQuery(
759f8a29 564 'followers',
ca309a9f
C
565 actorIds,
566 t,
567 undefined,
568 undefined,
759f8a29
C
569 'sharedInboxUrl',
570 true
ca309a9f 571 )
50d6de9c
C
572 }
573
1735c825 574 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
50d6de9c
C
575 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
576 }
577
09cababd
C
578 static async getStats () {
579 const serverActor = await getServerActor()
580
581 const totalInstanceFollowing = await ActorFollowModel.count({
582 where: {
583 actorId: serverActor.id
584 }
585 })
586
587 const totalInstanceFollowers = await ActorFollowModel.count({
588 where: {
589 targetActorId: serverActor.id
590 }
591 })
592
593 return {
594 totalInstanceFollowing,
595 totalInstanceFollowers
596 }
597 }
598
6b9c966f 599 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
2f5c6b2f
C
600 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
601 'WHERE id IN (' +
cef534ed
C
602 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
603 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
604 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
2f5c6b2f
C
605 ')'
606
607 const options = {
1735c825 608 type: QueryTypes.BULKUPDATE,
2f5c6b2f
C
609 transaction: t
610 }
611
612 return ActorFollowModel.sequelize.query(query, options)
613 }
614
6b9c966f
C
615 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
616 if (serverIds.length === 0) return
617
618 const me = await getServerActor()
619 const serverIdsString = createSafeIn(ActorFollowModel, serverIds)
620
327b3318 621 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
6b9c966f
C
622 'WHERE id IN (' +
623 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
624 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
625 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
626 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
627 ')'
628
629 const options = {
630 type: QueryTypes.BULKUPDATE,
631 transaction: t
632 }
633
634 return ActorFollowModel.sequelize.query(query, options)
635 }
636
759f8a29
C
637 private static async createListAcceptedFollowForApiQuery (
638 type: 'followers' | 'following',
639 actorIds: number[],
1735c825 640 t: Transaction,
759f8a29
C
641 start?: number,
642 count?: number,
643 columnUrl = 'url',
644 distinct = false
645 ) {
50d6de9c
C
646 let firstJoin: string
647 let secondJoin: string
648
649 if (type === 'followers') {
650 firstJoin = 'targetActorId'
651 secondJoin = 'actorId'
652 } else {
653 firstJoin = 'actorId'
654 secondJoin = 'targetActorId'
655 }
656
759f8a29 657 const selections: string[] = []
862ead21
C
658 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
659 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
759f8a29
C
660
661 selections.push('COUNT(*) AS "total"')
662
50d6de9c
C
663 const tasks: Bluebird<any>[] = []
664
a1587156 665 for (const selection of selections) {
50d6de9c
C
666 let query = 'SELECT ' + selection + ' FROM "actor" ' +
667 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
668 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
862ead21 669 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
50d6de9c
C
670
671 if (count !== undefined) query += 'LIMIT ' + count
672 if (start !== undefined) query += ' OFFSET ' + start
673
674 const options = {
675 bind: { actorIds },
1735c825 676 type: QueryTypes.SELECT,
50d6de9c
C
677 transaction: t
678 }
679 tasks.push(ActorFollowModel.sequelize.query(query, options))
680 }
681
babecc3c 682 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
47581df0 683 const urls: string[] = followers.map(f => f.selectionUrl)
50d6de9c
C
684
685 return {
686 data: urls,
babecc3c 687 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
50d6de9c
C
688 }
689 }
690
60650c77
C
691 private static listBadActorFollows () {
692 const query = {
693 where: {
694 score: {
1735c825 695 [Op.lte]: 0
60650c77 696 }
54e74059 697 },
23e27dd5 698 logging: false
60650c77
C
699 }
700
701 return ActorFollowModel.findAll(query)
702 }
703
1ca9f7c3 704 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
50d6de9c
C
705 const follower = this.ActorFollower.toFormattedJSON()
706 const following = this.ActorFollowing.toFormattedJSON()
707
708 return {
709 id: this.id,
710 follower,
711 following,
60650c77 712 score: this.score,
50d6de9c
C
713 state: this.state,
714 createdAt: this.createdAt,
715 updatedAt: this.updatedAt
716 }
717 }
718}