X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Fmodels%2Fserver%2Fserver.ts;h=a5e05f460fffcfe90c8026321f6df023c513b121;hb=5e47f6ab984a7d00782e4c7030afffa1ba480add;hp=ca3b24d51dac3c6c6161398a047fb0d64a4f9fa8;hpb=c48e82b5e0478434de30626d14594a97f2402e7c;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/models/server/server.ts b/server/models/server/server.ts index ca3b24d51..a5e05f460 100644 --- a/server/models/server/server.ts +++ b/server/models/server/server.ts @@ -1,7 +1,11 @@ +import { Transaction } from 'sequelize' 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/typescript-utils' import { isHostValid } from '../../helpers/custom-validators/servers' -import { ActorModel } from '../activitypub/actor' -import { throwIfNotValid } from '../utils' +import { ActorModel } from '../actor/actor' +import { buildSQLAttributes, throwIfNotValid } from '../shared' +import { ServerBlocklistModel } from './server-blocklist' @Table({ tableName: 'server', @@ -12,7 +16,7 @@ import { throwIfNotValid } from '../utils' } ] }) -export class ServerModel extends Model { +export class ServerModel extends Model>> { @AllowNull(false) @Is('Host', value => throwIfNotValid(value, isHostValid, 'valid host')) @@ -40,7 +44,38 @@ export class ServerModel extends Model { }) Actors: ActorModel[] - static loadByHost (host: string) { + @HasMany(() => ServerBlocklistModel, { + foreignKey: { + allowNull: false + }, + onDelete: 'CASCADE' + }) + BlockedBy: ServerBlocklistModel[] + + // --------------------------------------------------------------------------- + + static getSQLAttributes (tableName: string, aliasPrefix = '') { + return buildSQLAttributes({ + model: this, + tableName, + aliasPrefix + }) + } + + // --------------------------------------------------------------------------- + + static load (id: number, transaction?: Transaction): Promise { + const query = { + where: { + id + }, + transaction + } + + return ServerModel.findOne(query) + } + + static loadByHost (host: string): Promise { const query = { where: { host @@ -49,4 +84,21 @@ export class ServerModel extends Model { 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.BlockedBy && this.BlockedBy.length !== 0 + } + + toFormattedJSON (this: MServerFormattable) { + return { + host: this.host + } + } }