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