]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/account/account-blocklist.ts
Move test functions outside extra-utils
[github/Chocobozzz/PeerTube.git] / server / models / account / account-blocklist.ts
1 import { Op, QueryTypes } from 'sequelize'
2 import { BelongsTo, Column, CreatedAt, ForeignKey, Model, Scopes, Table, UpdatedAt } from 'sequelize-typescript'
3 import { handlesToNameAndHost } from '@server/helpers/actors'
4 import { MAccountBlocklist, MAccountBlocklistAccounts, MAccountBlocklistFormattable } from '@server/types/models'
5 import { AttributesOnly } from '@shared/typescript-utils'
6 import { AccountBlock } from '../../../shared/models'
7 import { ActorModel } from '../actor/actor'
8 import { ServerModel } from '../server/server'
9 import { createSafeIn, getSort, searchAttribute } from '../utils'
10 import { AccountModel } from './account'
11
12 enum ScopeNames {
13 WITH_ACCOUNTS = 'WITH_ACCOUNTS'
14 }
15
16 @Scopes(() => ({
17 [ScopeNames.WITH_ACCOUNTS]: {
18 include: [
19 {
20 model: AccountModel,
21 required: true,
22 as: 'ByAccount'
23 },
24 {
25 model: AccountModel,
26 required: true,
27 as: 'BlockedAccount'
28 }
29 ]
30 }
31 }))
32
33 @Table({
34 tableName: 'accountBlocklist',
35 indexes: [
36 {
37 fields: [ 'accountId', 'targetAccountId' ],
38 unique: true
39 },
40 {
41 fields: [ 'targetAccountId' ]
42 }
43 ]
44 })
45 export class AccountBlocklistModel extends Model<Partial<AttributesOnly<AccountBlocklistModel>>> {
46
47 @CreatedAt
48 createdAt: Date
49
50 @UpdatedAt
51 updatedAt: Date
52
53 @ForeignKey(() => AccountModel)
54 @Column
55 accountId: number
56
57 @BelongsTo(() => AccountModel, {
58 foreignKey: {
59 name: 'accountId',
60 allowNull: false
61 },
62 as: 'ByAccount',
63 onDelete: 'CASCADE'
64 })
65 ByAccount: AccountModel
66
67 @ForeignKey(() => AccountModel)
68 @Column
69 targetAccountId: number
70
71 @BelongsTo(() => AccountModel, {
72 foreignKey: {
73 name: 'targetAccountId',
74 allowNull: false
75 },
76 as: 'BlockedAccount',
77 onDelete: 'CASCADE'
78 })
79 BlockedAccount: AccountModel
80
81 static isAccountMutedByAccounts (accountIds: number[], targetAccountId: number) {
82 const query = {
83 attributes: [ 'accountId', 'id' ],
84 where: {
85 accountId: {
86 [Op.in]: accountIds
87 },
88 targetAccountId
89 },
90 raw: true
91 }
92
93 return AccountBlocklistModel.unscoped()
94 .findAll(query)
95 .then(rows => {
96 const result: { [accountId: number]: boolean } = {}
97
98 for (const accountId of accountIds) {
99 result[accountId] = !!rows.find(r => r.accountId === accountId)
100 }
101
102 return result
103 })
104 }
105
106 static loadByAccountAndTarget (accountId: number, targetAccountId: number): Promise<MAccountBlocklist> {
107 const query = {
108 where: {
109 accountId,
110 targetAccountId
111 }
112 }
113
114 return AccountBlocklistModel.findOne(query)
115 }
116
117 static listForApi (parameters: {
118 start: number
119 count: number
120 sort: string
121 search?: string
122 accountId: number
123 }) {
124 const { start, count, sort, search, accountId } = parameters
125
126 const query = {
127 offset: start,
128 limit: count,
129 order: getSort(sort)
130 }
131
132 const where = {
133 accountId
134 }
135
136 if (search) {
137 Object.assign(where, {
138 [Op.or]: [
139 searchAttribute(search, '$BlockedAccount.name$'),
140 searchAttribute(search, '$BlockedAccount.Actor.url$')
141 ]
142 })
143 }
144
145 Object.assign(query, { where })
146
147 return AccountBlocklistModel
148 .scope([ ScopeNames.WITH_ACCOUNTS ])
149 .findAndCountAll<MAccountBlocklistAccounts>(query)
150 .then(({ rows, count }) => {
151 return { total: count, data: rows }
152 })
153 }
154
155 static listHandlesBlockedBy (accountIds: number[]): Promise<string[]> {
156 const query = {
157 attributes: [ 'id' ],
158 where: {
159 accountId: {
160 [Op.in]: accountIds
161 }
162 },
163 include: [
164 {
165 attributes: [ 'id' ],
166 model: AccountModel.unscoped(),
167 required: true,
168 as: 'BlockedAccount',
169 include: [
170 {
171 attributes: [ 'preferredUsername' ],
172 model: ActorModel.unscoped(),
173 required: true,
174 include: [
175 {
176 attributes: [ 'host' ],
177 model: ServerModel.unscoped(),
178 required: true
179 }
180 ]
181 }
182 ]
183 }
184 ]
185 }
186
187 return AccountBlocklistModel.findAll(query)
188 .then(entries => entries.map(e => `${e.BlockedAccount.Actor.preferredUsername}@${e.BlockedAccount.Actor.Server.host}`))
189 }
190
191 static getBlockStatus (byAccountIds: number[], handles: string[]): Promise<{ name: string, host: string, accountId: number }[]> {
192 const sanitizedHandles = handlesToNameAndHost(handles)
193
194 const localHandles = sanitizedHandles.filter(h => !h.host)
195 .map(h => h.name)
196
197 const remoteHandles = sanitizedHandles.filter(h => !!h.host)
198 .map(h => ([ h.name, h.host ]))
199
200 const handlesWhere: string[] = []
201
202 if (localHandles.length !== 0) {
203 handlesWhere.push(`("actor"."preferredUsername" IN (:localHandles) AND "server"."id" IS NULL)`)
204 }
205
206 if (remoteHandles.length !== 0) {
207 handlesWhere.push(`(("actor"."preferredUsername", "server"."host") IN (:remoteHandles))`)
208 }
209
210 const rawQuery = `SELECT "accountBlocklist"."accountId", "actor"."preferredUsername" AS "name", "server"."host" ` +
211 `FROM "accountBlocklist" ` +
212 `INNER JOIN "account" ON "account"."id" = "accountBlocklist"."targetAccountId" ` +
213 `INNER JOIN "actor" ON "actor"."id" = "account"."actorId" ` +
214 `LEFT JOIN "server" ON "server"."id" = "actor"."serverId" ` +
215 `WHERE "accountBlocklist"."accountId" IN (${createSafeIn(AccountBlocklistModel.sequelize, byAccountIds)}) ` +
216 `AND (${handlesWhere.join(' OR ')})`
217
218 return AccountBlocklistModel.sequelize.query(rawQuery, {
219 type: QueryTypes.SELECT as QueryTypes.SELECT,
220 replacements: { byAccountIds, localHandles, remoteHandles }
221 })
222 }
223
224 toFormattedJSON (this: MAccountBlocklistFormattable): AccountBlock {
225 return {
226 byAccount: this.ByAccount.toFormattedJSON(),
227 blockedAccount: this.BlockedAccount.toFormattedJSON(),
228 createdAt: this.createdAt
229 }
230 }
231 }