]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/activitypub/actor-follow.ts
Fix no history message
[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,
225a7682 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'
4f5d0459 25import { createSafeIn, getFollowsSort, getSort, searchAttribute } 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
4f5d0459
RK
443 static listSubscriptionsForApi (options: {
444 actorId: number
445 start: number
446 count: number
447 sort: string
448 search?: string
449 }) {
450 const { actorId, start, count, sort } = options
451 const where = {
452 actorId: actorId
453 }
454
455 if (options.search) {
456 Object.assign(where, {
457 [Op.or]: [
458 searchAttribute(options.search, '$ActorFollowing.preferredUsername$'),
459 searchAttribute(options.search, '$ActorFollowing.VideoChannel.name$')
460 ]
461 })
462 }
463
06a05d5f 464 const query = {
f37dc0dd 465 attributes: [],
06a05d5f
C
466 distinct: true,
467 offset: start,
468 limit: count,
469 order: getSort(sort),
4f5d0459 470 where,
06a05d5f
C
471 include: [
472 {
f5b0af50
C
473 attributes: [ 'id' ],
474 model: ActorModel.unscoped(),
06a05d5f
C
475 as: 'ActorFollowing',
476 required: true,
477 include: [
478 {
f5b0af50 479 model: VideoChannelModel.unscoped(),
22a16e36
C
480 required: true,
481 include: [
482 {
f37dc0dd
C
483 attributes: {
484 exclude: unusedActorAttributesForAPI
485 },
486 model: ActorModel,
22a16e36 487 required: true
f37dc0dd
C
488 },
489 {
f5b0af50 490 model: AccountModel.unscoped(),
f37dc0dd
C
491 required: true,
492 include: [
493 {
494 attributes: {
495 exclude: unusedActorAttributesForAPI
496 },
497 model: ActorModel,
498 required: true
499 }
500 ]
22a16e36
C
501 }
502 ]
06a05d5f
C
503 }
504 ]
505 }
506 ]
507 }
508
453e83ea 509 return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query)
06a05d5f
C
510 .then(({ rows, count }) => {
511 return {
512 data: rows.map(r => r.ActorFollowing.VideoChannel),
513 total: count
514 }
515 })
516 }
517
6f1b4fa4
C
518 static async keepUnfollowedInstance (hosts: string[]) {
519 const followerId = (await getServerActor()).id
520
521 const query = {
10a105f0 522 attributes: [ 'id' ],
6f1b4fa4
C
523 where: {
524 actorId: followerId
525 },
526 include: [
527 {
10a105f0 528 attributes: [ 'id' ],
6f1b4fa4
C
529 model: ActorModel.unscoped(),
530 required: true,
531 as: 'ActorFollowing',
532 where: {
533 preferredUsername: SERVER_ACTOR_NAME
534 },
535 include: [
536 {
537 attributes: [ 'host' ],
538 model: ServerModel.unscoped(),
539 required: true,
540 where: {
541 host: {
542 [Op.in]: hosts
543 }
544 }
545 }
546 ]
547 }
548 ]
549 }
550
551 const res = await ActorFollowModel.findAll(query)
10a105f0 552 const followedHosts = res.map(row => row.ActorFollowing.Server.host)
6f1b4fa4
C
553
554 return difference(hosts, followedHosts)
555 }
556
1735c825 557 static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) {
50d6de9c
C
558 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
559 }
560
1735c825 561 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) {
ca309a9f 562 return ActorFollowModel.createListAcceptedFollowForApiQuery(
759f8a29 563 'followers',
ca309a9f
C
564 actorIds,
565 t,
566 undefined,
567 undefined,
759f8a29
C
568 'sharedInboxUrl',
569 true
ca309a9f 570 )
50d6de9c
C
571 }
572
1735c825 573 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) {
50d6de9c
C
574 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
575 }
576
09cababd
C
577 static async getStats () {
578 const serverActor = await getServerActor()
579
580 const totalInstanceFollowing = await ActorFollowModel.count({
581 where: {
582 actorId: serverActor.id
583 }
584 })
585
586 const totalInstanceFollowers = await ActorFollowModel.count({
587 where: {
588 targetActorId: serverActor.id
589 }
590 })
591
592 return {
593 totalInstanceFollowing,
594 totalInstanceFollowers
595 }
596 }
597
6b9c966f 598 static updateScore (inboxUrl: string, value: number, t?: Transaction) {
2f5c6b2f
C
599 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
600 'WHERE id IN (' +
cef534ed
C
601 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
602 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
603 `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` +
2f5c6b2f
C
604 ')'
605
606 const options = {
1735c825 607 type: QueryTypes.BULKUPDATE,
2f5c6b2f
C
608 transaction: t
609 }
610
611 return ActorFollowModel.sequelize.query(query, options)
612 }
613
6b9c966f
C
614 static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) {
615 if (serverIds.length === 0) return
616
617 const me = await getServerActor()
618 const serverIdsString = createSafeIn(ActorFollowModel, serverIds)
619
327b3318 620 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
6b9c966f
C
621 'WHERE id IN (' +
622 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
623 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' +
624 `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower
625 `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings
626 ')'
627
628 const options = {
629 type: QueryTypes.BULKUPDATE,
630 transaction: t
631 }
632
633 return ActorFollowModel.sequelize.query(query, options)
634 }
635
759f8a29
C
636 private static async createListAcceptedFollowForApiQuery (
637 type: 'followers' | 'following',
638 actorIds: number[],
1735c825 639 t: Transaction,
759f8a29
C
640 start?: number,
641 count?: number,
642 columnUrl = 'url',
643 distinct = false
644 ) {
50d6de9c
C
645 let firstJoin: string
646 let secondJoin: string
647
648 if (type === 'followers') {
649 firstJoin = 'targetActorId'
650 secondJoin = 'actorId'
651 } else {
652 firstJoin = 'actorId'
653 secondJoin = 'targetActorId'
654 }
655
759f8a29 656 const selections: string[] = []
862ead21
C
657 if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`)
658 else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`)
759f8a29
C
659
660 selections.push('COUNT(*) AS "total"')
661
50d6de9c
C
662 const tasks: Bluebird<any>[] = []
663
a1587156 664 for (const selection of selections) {
50d6de9c
C
665 let query = 'SELECT ' + selection + ' FROM "actor" ' +
666 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
667 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
862ead21 668 `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL `
50d6de9c
C
669
670 if (count !== undefined) query += 'LIMIT ' + count
671 if (start !== undefined) query += ' OFFSET ' + start
672
673 const options = {
674 bind: { actorIds },
1735c825 675 type: QueryTypes.SELECT,
50d6de9c
C
676 transaction: t
677 }
678 tasks.push(ActorFollowModel.sequelize.query(query, options))
679 }
680
babecc3c 681 const [ followers, [ dataTotal ] ] = await Promise.all(tasks)
47581df0 682 const urls: string[] = followers.map(f => f.selectionUrl)
50d6de9c
C
683
684 return {
685 data: urls,
babecc3c 686 total: dataTotal ? parseInt(dataTotal.total, 10) : 0
50d6de9c
C
687 }
688 }
689
60650c77
C
690 private static listBadActorFollows () {
691 const query = {
692 where: {
693 score: {
1735c825 694 [Op.lte]: 0
60650c77 695 }
54e74059 696 },
23e27dd5 697 logging: false
60650c77
C
698 }
699
700 return ActorFollowModel.findAll(query)
701 }
702
1ca9f7c3 703 toFormattedJSON (this: MActorFollowFormattable): ActorFollow {
50d6de9c
C
704 const follower = this.ActorFollower.toFormattedJSON()
705 const following = this.ActorFollowing.toFormattedJSON()
706
707 return {
708 id: this.id,
709 follower,
710 following,
60650c77 711 score: this.score,
50d6de9c
C
712 state: this.state,
713 createdAt: this.createdAt,
714 updatedAt: this.updatedAt
715 }
716 }
717}