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