]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/server/server.ts
Stricter models typing
[github/Chocobozzz/PeerTube.git] / server / models / server / server.ts
index 9749f503e30e7782f0ea3bf12a0dd62ed2829c12..25d9924fb33e7f91b8fc1f8bb6be01fa002ea8cb 100644 (file)
@@ -1,7 +1,10 @@
-import { AllowNull, Column, CreatedAt, HasMany, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
+import { AllowNull, Column, CreatedAt, Default, HasMany, Is, Model, Table, UpdatedAt } from 'sequelize-typescript'
+import { MServer, MServerFormattable } from '@server/types/models/server'
+import { AttributesOnly } from '@shared/core-utils'
 import { isHostValid } from '../../helpers/custom-validators/servers'
-import { ActorModel } from '../activitypub/actor'
+import { ActorModel } from '../actor/actor'
 import { throwIfNotValid } from '../utils'
+import { ServerBlocklistModel } from './server-blocklist'
 
 @Table({
   tableName: 'server',
@@ -12,13 +15,18 @@ import { throwIfNotValid } from '../utils'
     }
   ]
 })
-export class ServerModel extends Model<ServerModel> {
+export class ServerModel extends Model<Partial<AttributesOnly<ServerModel>>> {
 
   @AllowNull(false)
   @Is('Host', value => throwIfNotValid(value, isHostValid, 'valid host'))
   @Column
   host: string
 
+  @AllowNull(false)
+  @Default(false)
+  @Column
+  redundancyAllowed: boolean
+
   @CreatedAt
   createdAt: Date
 
@@ -34,4 +42,49 @@ export class ServerModel extends Model<ServerModel> {
     hooks: true
   })
   Actors: ActorModel[]
+
+  @HasMany(() => ServerBlocklistModel, {
+    foreignKey: {
+      allowNull: false
+    },
+    onDelete: 'CASCADE'
+  })
+  BlockedByAccounts: ServerBlocklistModel[]
+
+  static load (id: number): Promise<MServer> {
+    const query = {
+      where: {
+        id
+      }
+    }
+
+    return ServerModel.findOne(query)
+  }
+
+  static loadByHost (host: string): Promise<MServer> {
+    const query = {
+      where: {
+        host
+      }
+    }
+
+    return ServerModel.findOne(query)
+  }
+
+  static async loadOrCreateByHost (host: string) {
+    let server = await ServerModel.loadByHost(host)
+    if (!server) server = await ServerModel.create({ host })
+
+    return server
+  }
+
+  isBlocked () {
+    return this.BlockedByAccounts && this.BlockedByAccounts.length !== 0
+  }
+
+  toFormattedJSON (this: MServerFormattable) {
+    return {
+      host: this.host
+    }
+  }
 }