import Model from "wms-core/db/Model"; import Validator from "wms-core/db/Validator"; import Controller from "wms-core/Controller"; import config from "config"; import User from "wms-core/auth/models/User"; import {Request} from "express"; import URLRedirect from "./URLRedirect"; export default class FileModel extends Model { public static get table(): string { return 'files'; } public static async getBySlug(slug: string): Promise { return await this.select().where('slug', slug).first(); } public static async paginateForUser(req: Request, perPage: number, user_id: number): Promise { return await this.paginate(req, perPage, this.select().where('user_id', user_id)); } public readonly user_id!: number; public readonly slug!: string; public readonly real_name!: string; public readonly storage_type!: FileStorage; public readonly storage_path!: string; public readonly size!: number; public created_at?: Date; public readonly ttl!: number; protected init() { this.addProperty('user_id', new Validator().defined().exists(User, 'id')); this.addProperty('slug', new Validator().defined().minLength(1).maxLength(259).unique(FileModel, 'slug').unique(URLRedirect, 'slug')); this.addProperty('real_name', new Validator().defined().minLength(1).maxLength(259)); this.addProperty('storage_type', new Validator().defined().maxLength(64)); this.addProperty('storage_path', new Validator().defined().maxLength(1745)); this.addProperty('size', new Validator().defined().min(0)); this.addProperty('created_at', new Validator()); this.addProperty('ttl', new Validator().defined().min(0).max(4294967295)); } public getURL(): string { return config.get('base_url') + Controller.route('get-file', { slug: this.slug, }); } public getExpirationDate(): Date | null { if (!this.created_at) return new Date(); if (this.ttl === 0) return null; return new Date(this.created_at.getTime() + this.ttl * 1000); } public shouldBeDeleted(): boolean { const expirationDate = this.getExpirationDate(); if (!expirationDate) return false; return new Date().getTime() >= expirationDate.getTime(); } public canDelete(user_id: number): boolean { return this.user_id === user_id; } } export type FileStorage = 'local';