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