]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/activitypub/actor-follow.ts
Fix error logging
[github/Chocobozzz/PeerTube.git] / server / models / activitypub / actor-follow.ts
index 78a65a0ff58cdaf8f937e08993cfd1c6510ad935..c97f4cead2a773442bd5805fc7e8445bbf35ebb7 100644 (file)
@@ -2,12 +2,13 @@ import * as Bluebird from 'bluebird'
 import { values } from 'lodash'
 import * as Sequelize from 'sequelize'
 import {
-  AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, IsInt, Max, Model, Table,
-  UpdatedAt
+  AfterCreate, AfterDestroy, AfterUpdate, AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, IsInt, Max, Model,
+  Table, UpdatedAt
 } from 'sequelize-typescript'
 import { FollowState } from '../../../shared/models/actors'
 import { AccountFollow } from '../../../shared/models/actors/follow.model'
 import { logger } from '../../helpers/logger'
+import { getServerActor } from '../../helpers/utils'
 import { ACTOR_FOLLOW_SCORE } from '../../initializers'
 import { FOLLOW_STATES } from '../../initializers/constants'
 import { ServerModel } from '../server/server'
@@ -79,6 +80,25 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
   })
   ActorFollowing: ActorModel
 
+  @AfterCreate
+  @AfterUpdate
+  static incrementFollowerAndFollowingCount (instance: ActorFollowModel) {
+    if (instance.state !== 'accepted') return undefined
+
+    return Promise.all([
+      ActorModel.incrementFollows(instance.actorId, 'followingCount', 1),
+      ActorModel.incrementFollows(instance.targetActorId, 'followersCount', 1)
+    ])
+  }
+
+  @AfterDestroy
+  static decrementFollowerAndFollowingCount (instance: ActorFollowModel) {
+    return Promise.all([
+      ActorModel.incrementFollows(instance.actorId, 'followingCount',-1),
+      ActorModel.incrementFollows(instance.targetActorId, 'followersCount', -1)
+    ])
+  }
+
   // Remove actor follows with a score of 0 (too many requests where they were unreachable)
   static async removeBadActorFollows () {
     const actorFollows = await ActorFollowModel.listBadActorFollows()
@@ -91,19 +111,19 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
     if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
   }
 
-  static updateActorFollowsScoreAndRemoveBadOnes (goodInboxes: string[], badInboxes: string[], t: Sequelize.Transaction) {
+  static updateActorFollowsScore (goodInboxes: string[], badInboxes: string[], t: Sequelize.Transaction) {
     if (goodInboxes.length === 0 && badInboxes.length === 0) return
 
     logger.info('Updating %d good actor follows and %d bad actor follows scores.', goodInboxes.length, badInboxes.length)
 
     if (goodInboxes.length !== 0) {
       ActorFollowModel.incrementScores(goodInboxes, ACTOR_FOLLOW_SCORE.BONUS, t)
-        .catch(err => logger.error('Cannot increment scores of good actor follows.', err))
+        .catch(err => logger.error('Cannot increment scores of good actor follows.', { err }))
     }
 
     if (badInboxes.length !== 0) {
       ActorFollowModel.incrementScores(badInboxes, ACTOR_FOLLOW_SCORE.PENALTY, t)
-        .catch(err => logger.error('Cannot decrement scores of bad actor follows.', err))
+        .catch(err => logger.error('Cannot decrement scores of bad actor follows.', { err }))
     }
   }
 
@@ -168,7 +188,7 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
       distinct: true,
       offset: start,
       limit: count,
-      order: [ getSort(sort) ],
+      order: getSort(sort),
       include: [
         {
           model: ActorModel,
@@ -201,7 +221,7 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
       distinct: true,
       offset: start,
       limit: count,
-      order: [ getSort(sort) ],
+      order: getSort(sort),
       include: [
         {
           model: ActorModel,
@@ -249,6 +269,27 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
     return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
   }
 
+  static async getStats () {
+    const serverActor = await getServerActor()
+
+    const totalInstanceFollowing = await ActorFollowModel.count({
+      where: {
+        actorId: serverActor.id
+      }
+    })
+
+    const totalInstanceFollowers = await ActorFollowModel.count({
+      where: {
+        targetActorId: serverActor.id
+      }
+    })
+
+    return {
+      totalInstanceFollowing,
+      totalInstanceFollowers
+    }
+  }
+
   private static async createListAcceptedFollowForApiQuery (
     type: 'followers' | 'following',
     actorIds: number[],
@@ -307,7 +348,7 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
   private static incrementScores (inboxUrls: string[], value: number, t: Sequelize.Transaction) {
     const inboxUrlsString = inboxUrls.map(url => `'${url}'`).join(',')
 
-    const query = 'UPDATE "actorFollow" SET "score" = "score" +' + value + ' ' +
+    const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
       'WHERE id IN (' +
         'SELECT "actorFollow"."id" FROM "actorFollow" ' +
         'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
@@ -328,7 +369,8 @@ export class ActorFollowModel extends Model<ActorFollowModel> {
         score: {
           [Sequelize.Op.lte]: 0
         }
-      }
+      },
+      logging: false
     }
 
     return ActorFollowModel.findAll(query)