Split types and typings
[oweals/peertube.git] / server / lib / blocklist.ts
1 import { sequelizeTypescript } from '@server/initializers/database'
2 import { getServerActor } from '@server/models/application/application'
3 import { MAccountBlocklist, MAccountId, MAccountServer, MServerBlocklist } from '@server/types/models'
4 import { AccountBlocklistModel } from '../models/account/account-blocklist'
5 import { ServerBlocklistModel } from '../models/server/server-blocklist'
6
7 function addAccountInBlocklist (byAccountId: number, targetAccountId: number) {
8   return sequelizeTypescript.transaction(async t => {
9     return AccountBlocklistModel.upsert({
10       accountId: byAccountId,
11       targetAccountId: targetAccountId
12     }, { transaction: t })
13   })
14 }
15
16 function addServerInBlocklist (byAccountId: number, targetServerId: number) {
17   return sequelizeTypescript.transaction(async t => {
18     return ServerBlocklistModel.upsert({
19       accountId: byAccountId,
20       targetServerId
21     }, { transaction: t })
22   })
23 }
24
25 function removeAccountFromBlocklist (accountBlock: MAccountBlocklist) {
26   return sequelizeTypescript.transaction(async t => {
27     return accountBlock.destroy({ transaction: t })
28   })
29 }
30
31 function removeServerFromBlocklist (serverBlock: MServerBlocklist) {
32   return sequelizeTypescript.transaction(async t => {
33     return serverBlock.destroy({ transaction: t })
34   })
35 }
36
37 async function isBlockedByServerOrAccount (targetAccount: MAccountServer, userAccount?: MAccountId) {
38   const serverAccountId = (await getServerActor()).Account.id
39   const sourceAccounts = [ serverAccountId ]
40
41   if (userAccount) sourceAccounts.push(userAccount.id)
42
43   const accountMutedHash = await AccountBlocklistModel.isAccountMutedByMulti(sourceAccounts, targetAccount.id)
44   if (accountMutedHash[serverAccountId] || (userAccount && accountMutedHash[userAccount.id])) {
45     return true
46   }
47
48   const instanceMutedHash = await ServerBlocklistModel.isServerMutedByMulti(sourceAccounts, targetAccount.Actor.serverId)
49   if (instanceMutedHash[serverAccountId] || (userAccount && instanceMutedHash[userAccount.id])) {
50     return true
51   }
52
53   return false
54 }
55
56 export {
57   addAccountInBlocklist,
58   addServerInBlocklist,
59   removeAccountFromBlocklist,
60   removeServerFromBlocklist,
61   isBlockedByServerOrAccount
62 }