ily.li/src/models/FileModel.ts

67 lines
2.5 KiB
TypeScript
Raw Normal View History

2020-06-14 13:01:52 +02:00
import Model from "wms-core/db/Model";
import Validator from "wms-core/db/Validator";
import Controller from "wms-core/Controller";
import config from "config";
2020-06-14 18:10:01 +02:00
import User from "wms-core/auth/models/User";
2020-06-14 21:23:57 +02:00
import {Request} from "express";
import URLRedirect from "./URLRedirect";
2020-06-14 13:01:52 +02:00
export default class FileModel extends Model {
public static get table(): string {
return 'files';
}
public static async getBySlug(slug: string): Promise<FileModel | null> {
2020-06-27 16:31:36 +02:00
return await this.select().where('slug', slug).first();
2020-06-14 13:01:52 +02:00
}
2020-06-14 21:23:57 +02:00
public static async paginateForUser(req: Request, perPage: number, user_id: number): Promise<FileModel[]> {
return await this.paginate(req, perPage, this.select().where('user_id', user_id));
2020-06-14 21:23:57 +02:00
}
2020-06-14 18:10:01 +02:00
public readonly user_id!: number;
2020-06-14 13:01:52 +02:00
public readonly slug!: string;
public readonly real_name!: string;
public readonly storage_type!: FileStorage;
public readonly storage_path!: string;
2020-06-14 18:10:01 +02:00
public readonly size!: number;
public created_at?: Date;
public readonly ttl!: number;
2020-06-14 13:01:52 +02:00
2020-06-27 16:31:36 +02:00
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'));
2020-06-27 16:31:36 +02:00
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));
2020-06-14 13:01:52 +02:00
}
public getURL(domain: string = config.get<string>('base_url')): string {
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + Controller.route('get-file', {
2020-06-14 13:01:52 +02:00
slug: this.slug,
});
}
2020-06-14 17:37:47 +02:00
public getExpirationDate(): Date | null {
if (!this.created_at) return new Date();
2020-06-14 17:37:47 +02:00
if (this.ttl === 0) return null;
return new Date(this.created_at.getTime() + this.ttl * 1000);
}
public shouldBeDeleted(): boolean {
2020-06-14 17:37:47 +02:00
const expirationDate = this.getExpirationDate();
if (!expirationDate) return false;
return new Date().getTime() >= expirationDate.getTime();
}
2020-06-14 18:10:01 +02:00
public canDelete(user_id: number): boolean {
return this.user_id === user_id;
}
2020-06-14 13:01:52 +02:00
}
export type FileStorage = 'local';