]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/activitypub/actor-follow.ts
expliciting type checks and predicates (server only)
[github/Chocobozzz/PeerTube.git] / server / models / activitypub / actor-follow.ts
CommitLineData
50d6de9c
C
1import * as Bluebird from 'bluebird'
2import { values } from 'lodash'
3import * as Sequelize from 'sequelize'
60650c77 4import {
38768a36
C
5 AfterCreate, AfterDestroy, AfterUpdate, AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, ForeignKey, IsInt, Max, Model,
6 Table, UpdatedAt
60650c77 7} from 'sequelize-typescript'
50d6de9c 8import { FollowState } from '../../../shared/models/actors'
60650c77
C
9import { AccountFollow } from '../../../shared/models/actors/follow.model'
10import { logger } from '../../helpers/logger'
09cababd 11import { getServerActor } from '../../helpers/utils'
60650c77 12import { ACTOR_FOLLOW_SCORE } from '../../initializers'
50d6de9c
C
13import { FOLLOW_STATES } from '../../initializers/constants'
14import { ServerModel } from '../server/server'
15import { getSort } from '../utils'
16import { ActorModel } from './actor'
17
18@Table({
19 tableName: 'actorFollow',
20 indexes: [
21 {
22 fields: [ 'actorId' ]
23 },
24 {
25 fields: [ 'targetActorId' ]
26 },
27 {
28 fields: [ 'actorId', 'targetActorId' ],
29 unique: true
60650c77
C
30 },
31 {
32 fields: [ 'score' ]
50d6de9c
C
33 }
34 ]
35})
36export class ActorFollowModel extends Model<ActorFollowModel> {
37
38 @AllowNull(false)
39 @Column(DataType.ENUM(values(FOLLOW_STATES)))
40 state: FollowState
41
60650c77
C
42 @AllowNull(false)
43 @Default(ACTOR_FOLLOW_SCORE.BASE)
44 @IsInt
45 @Max(ACTOR_FOLLOW_SCORE.MAX)
46 @Column
47 score: number
48
50d6de9c
C
49 @CreatedAt
50 createdAt: Date
51
52 @UpdatedAt
53 updatedAt: Date
54
55 @ForeignKey(() => ActorModel)
56 @Column
57 actorId: number
58
59 @BelongsTo(() => ActorModel, {
60 foreignKey: {
61 name: 'actorId',
62 allowNull: false
63 },
64 as: 'ActorFollower',
65 onDelete: 'CASCADE'
66 })
67 ActorFollower: ActorModel
68
69 @ForeignKey(() => ActorModel)
70 @Column
71 targetActorId: number
72
73 @BelongsTo(() => ActorModel, {
74 foreignKey: {
75 name: 'targetActorId',
76 allowNull: false
77 },
78 as: 'ActorFollowing',
79 onDelete: 'CASCADE'
80 })
81 ActorFollowing: ActorModel
82
32b2b43c
C
83 @AfterCreate
84 @AfterUpdate
85 static incrementFollowerAndFollowingCount (instance: ActorFollowModel) {
38768a36 86 if (instance.state !== 'accepted') return undefined
32b2b43c
C
87
88 return Promise.all([
89 ActorModel.incrementFollows(instance.actorId, 'followingCount', 1),
90 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', 1)
91 ])
92 }
93
94 @AfterDestroy
95 static decrementFollowerAndFollowingCount (instance: ActorFollowModel) {
96 return Promise.all([
97 ActorModel.incrementFollows(instance.actorId, 'followingCount',-1),
98 ActorModel.incrementFollows(instance.targetActorId, 'followersCount', -1)
99 ])
100 }
101
60650c77
C
102 // Remove actor follows with a score of 0 (too many requests where they were unreachable)
103 static async removeBadActorFollows () {
104 const actorFollows = await ActorFollowModel.listBadActorFollows()
105
106 const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy())
107 await Promise.all(actorFollowsRemovePromises)
108
109 const numberOfActorFollowsRemoved = actorFollows.length
110
111 if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved)
112 }
113
c1e791ba 114 static updateActorFollowsScore (goodInboxes: string[], badInboxes: string[], t: Sequelize.Transaction | undefined) {
60650c77
C
115 if (goodInboxes.length === 0 && badInboxes.length === 0) return
116
117 logger.info('Updating %d good actor follows and %d bad actor follows scores.', goodInboxes.length, badInboxes.length)
118
119 if (goodInboxes.length !== 0) {
120 ActorFollowModel.incrementScores(goodInboxes, ACTOR_FOLLOW_SCORE.BONUS, t)
d5b7d911 121 .catch(err => logger.error('Cannot increment scores of good actor follows.', { err }))
60650c77
C
122 }
123
124 if (badInboxes.length !== 0) {
125 ActorFollowModel.incrementScores(badInboxes, ACTOR_FOLLOW_SCORE.PENALTY, t)
d5b7d911 126 .catch(err => logger.error('Cannot decrement scores of bad actor follows.', { err }))
60650c77
C
127 }
128 }
129
50d6de9c
C
130 static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Sequelize.Transaction) {
131 const query = {
132 where: {
133 actorId,
134 targetActorId: targetActorId
135 },
136 include: [
137 {
138 model: ActorModel,
139 required: true,
140 as: 'ActorFollower'
141 },
142 {
143 model: ActorModel,
144 required: true,
145 as: 'ActorFollowing'
146 }
147 ],
148 transaction: t
149 }
150
151 return ActorFollowModel.findOne(query)
152 }
153
154 static loadByActorAndTargetHost (actorId: number, targetHost: string, t?: Sequelize.Transaction) {
155 const query = {
156 where: {
157 actorId
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 include: [
170 {
171 model: ServerModel,
172 required: true,
173 where: {
174 host: targetHost
175 }
176 }
177 ]
178 }
179 ],
180 transaction: t
181 }
182
6502c3d4
C
183 return ActorFollowModel.findOne(query)
184 }
185
50d6de9c
C
186 static listFollowingForApi (id: number, start: number, count: number, sort: string) {
187 const query = {
188 distinct: true,
189 offset: start,
190 limit: count,
3bb6c526 191 order: getSort(sort),
50d6de9c
C
192 include: [
193 {
194 model: ActorModel,
195 required: true,
196 as: 'ActorFollower',
197 where: {
198 id
199 }
200 },
201 {
202 model: ActorModel,
203 as: 'ActorFollowing',
204 required: true,
205 include: [ ServerModel ]
206 }
207 ]
208 }
209
210 return ActorFollowModel.findAndCountAll(query)
211 .then(({ rows, count }) => {
212 return {
213 data: rows,
214 total: count
215 }
216 })
217 }
218
219 static listFollowersForApi (id: number, start: number, count: number, sort: string) {
220 const query = {
221 distinct: true,
222 offset: start,
223 limit: count,
3bb6c526 224 order: getSort(sort),
50d6de9c
C
225 include: [
226 {
227 model: ActorModel,
228 required: true,
229 as: 'ActorFollower',
230 include: [ ServerModel ]
231 },
232 {
233 model: ActorModel,
234 as: 'ActorFollowing',
235 required: true,
236 where: {
237 id
238 }
239 }
240 ]
241 }
242
243 return ActorFollowModel.findAndCountAll(query)
244 .then(({ rows, count }) => {
245 return {
246 data: rows,
247 total: count
248 }
249 })
250 }
251
252 static listAcceptedFollowerUrlsForApi (actorIds: number[], t: Sequelize.Transaction, start?: number, count?: number) {
253 return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count)
254 }
255
256 static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Sequelize.Transaction) {
ca309a9f 257 return ActorFollowModel.createListAcceptedFollowForApiQuery(
759f8a29 258 'followers',
ca309a9f
C
259 actorIds,
260 t,
261 undefined,
262 undefined,
759f8a29
C
263 'sharedInboxUrl',
264 true
ca309a9f 265 )
50d6de9c
C
266 }
267
268 static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Sequelize.Transaction, start?: number, count?: number) {
269 return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count)
270 }
271
09cababd
C
272 static async getStats () {
273 const serverActor = await getServerActor()
274
275 const totalInstanceFollowing = await ActorFollowModel.count({
276 where: {
277 actorId: serverActor.id
278 }
279 })
280
281 const totalInstanceFollowers = await ActorFollowModel.count({
282 where: {
283 targetActorId: serverActor.id
284 }
285 })
286
287 return {
288 totalInstanceFollowing,
289 totalInstanceFollowers
290 }
291 }
292
759f8a29
C
293 private static async createListAcceptedFollowForApiQuery (
294 type: 'followers' | 'following',
295 actorIds: number[],
296 t: Sequelize.Transaction,
297 start?: number,
298 count?: number,
299 columnUrl = 'url',
300 distinct = false
301 ) {
50d6de9c
C
302 let firstJoin: string
303 let secondJoin: string
304
305 if (type === 'followers') {
306 firstJoin = 'targetActorId'
307 secondJoin = 'actorId'
308 } else {
309 firstJoin = 'actorId'
310 secondJoin = 'targetActorId'
311 }
312
759f8a29
C
313 const selections: string[] = []
314 if (distinct === true) selections.push('DISTINCT("Follows"."' + columnUrl + '") AS "url"')
315 else selections.push('"Follows"."' + columnUrl + '" AS "url"')
316
317 selections.push('COUNT(*) AS "total"')
318
50d6de9c
C
319 const tasks: Bluebird<any>[] = []
320
759f8a29 321 for (let selection of selections) {
50d6de9c
C
322 let query = 'SELECT ' + selection + ' FROM "actor" ' +
323 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' +
324 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' +
325 'WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = \'accepted\' '
326
327 if (count !== undefined) query += 'LIMIT ' + count
328 if (start !== undefined) query += ' OFFSET ' + start
329
330 const options = {
331 bind: { actorIds },
332 type: Sequelize.QueryTypes.SELECT,
333 transaction: t
334 }
335 tasks.push(ActorFollowModel.sequelize.query(query, options))
336 }
337
8fffe21a 338 const [ followers, [ { total } ] ] = await Promise.all(tasks)
50d6de9c
C
339 const urls: string[] = followers.map(f => f.url)
340
341 return {
342 data: urls,
343 total: parseInt(total, 10)
344 }
345 }
346
c1e791ba 347 private static incrementScores (inboxUrls: string[], value: number, t: Sequelize.Transaction | undefined) {
60650c77
C
348 const inboxUrlsString = inboxUrls.map(url => `'${url}'`).join(',')
349
05bc4dfa 350 const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` +
60650c77
C
351 'WHERE id IN (' +
352 'SELECT "actorFollow"."id" FROM "actorFollow" ' +
353 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' +
354 'WHERE "actor"."inboxUrl" IN (' + inboxUrlsString + ') OR "actor"."sharedInboxUrl" IN (' + inboxUrlsString + ')' +
355 ')'
356
c1e791ba 357 const options = t ? {
60650c77
C
358 type: Sequelize.QueryTypes.BULKUPDATE,
359 transaction: t
c1e791ba 360 } : undefined
60650c77
C
361
362 return ActorFollowModel.sequelize.query(query, options)
363 }
364
365 private static listBadActorFollows () {
366 const query = {
367 where: {
368 score: {
369 [Sequelize.Op.lte]: 0
370 }
54e74059 371 },
23e27dd5 372 logging: false
60650c77
C
373 }
374
375 return ActorFollowModel.findAll(query)
376 }
377
378 toFormattedJSON (): AccountFollow {
50d6de9c
C
379 const follower = this.ActorFollower.toFormattedJSON()
380 const following = this.ActorFollowing.toFormattedJSON()
381
382 return {
383 id: this.id,
384 follower,
385 following,
60650c77 386 score: this.score,
50d6de9c
C
387 state: this.state,
388 createdAt: this.createdAt,
389 updatedAt: this.updatedAt
390 }
391 }
392}