69 lines
2.4 KiB
TypeScript
69 lines
2.4 KiB
TypeScript
import config from "config";
|
|
import {Request} from "express";
|
|
import User from "swaf/auth/models/User";
|
|
import {route} from "swaf/common/Routing";
|
|
import Model from "swaf/db/Model";
|
|
import {ModelQueryResult} from "swaf/db/ModelQuery";
|
|
|
|
import URLRedirect from "./URLRedirect.js";
|
|
|
|
export default class FileModel extends Model {
|
|
public static get table(): string {
|
|
return 'files';
|
|
}
|
|
|
|
public static async getBySlug(slug: string): Promise<FileModel | null> {
|
|
return await this.select().where('slug', slug).first();
|
|
}
|
|
|
|
public static async paginateForUser(req: Request, perPage: number, user_id: number): Promise<ModelQueryResult<FileModel>> {
|
|
req.params.sortBy = 'created_at';
|
|
req.params.sortDirection = 'DESC';
|
|
return await this.paginate(req, perPage, this.select().where('user_id', user_id));
|
|
}
|
|
|
|
public id?: number = undefined;
|
|
public readonly user_id?: number = undefined;
|
|
public readonly slug?: string = undefined;
|
|
public readonly real_name?: string = undefined;
|
|
public readonly storage_type?: FileStorage = undefined;
|
|
public readonly storage_path?: string = undefined;
|
|
public readonly size?: number = undefined;
|
|
public created_at?: Date = undefined;
|
|
public expires_at?: Date | null = undefined;
|
|
|
|
/**
|
|
* @deprecated
|
|
*/
|
|
public ttl?: number = undefined;
|
|
|
|
protected init(): void {
|
|
this.setValidation('user_id').defined().exists(User, 'id');
|
|
this.setValidation('slug').defined().minLength(1).maxLength(259)
|
|
.unique(this, 'slug')
|
|
.unique(URLRedirect, 'slug');
|
|
this.setValidation('real_name').defined().minLength(1).maxLength(259);
|
|
this.setValidation('storage_type').defined().maxLength(64);
|
|
this.setValidation('storage_path').defined().maxLength(1745);
|
|
this.setValidation('size').defined().min(0);
|
|
}
|
|
|
|
public getURL(domain: string = config.get<string>('public_url')): string {
|
|
return (/^https?:\/\//.test(domain) ? '' : 'https://') + domain + route('get-file', {
|
|
slug: this.getOrFail('slug'),
|
|
});
|
|
}
|
|
|
|
public shouldBeDeleted(): boolean {
|
|
const expirationDate = this.expires_at;
|
|
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';
|