fileUtils.ts

1import multer from 'multer';
2import { getPictureDirs } from './system';
3import { Request } from 'express';
4
5export const picDir = getPictureDirs();
6
7export function generateId() {
8	return [...Array(8)]
9		.map(() => Math.floor(Math.random() * 16).toString(16))
10		.join('');
11}
12
13export function timeDifference(date: Date) {
14	const now = new Date();
15	const diff = now.getTime() - date.getTime();
16	const minutes = Math.floor(diff / 60000);
17	if (minutes < 60) return `${minutes} minute(s) ago`;
18	const hours = Math.floor(minutes / 60);
19	if (hours < 24) return `${hours} hour(s) ago`;
20	const days = Math.floor(hours / 24);
21	return `${days} day(s) ago`;
22}
23
24export function makeUUID() {
25	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
26		const r = (Math.random() * 16) | 0;
27		const v = c === 'x' ? r : (r & 0x3) | 0x8;
28		return v.toString(16);
29	});
30}
31
32export const storageForImages = multer.diskStorage({
33	destination: (req, file, cb) => {
34		cb(null, picDir.image);
35	},
36	filename: (req: Request, file, cb) => {
37		cb(null, `${makeUUID()}.${file.originalname.split('.').pop()}`); // Use the original file name
38	},
39});
40
41export const storageForAvatars = multer.diskStorage({
42	destination: (req, file, cb) => {
43		cb(null, picDir.avatar);
44	},
45	filename: (req: Request, file, cb) => {
46		cb(null, `${makeUUID()}.${file.originalname.split('.').pop()}`); // Use the original file name
47	},
48});
49
50export const storageForVideos = multer.diskStorage({
51	destination: (req, file, cb) => {
52		cb(null, picDir.video);
53	},
54	filename: (req: Request, file, cb) => {
55		cb(null, `${makeUUID()}.${file.originalname.split('.').pop()}`); // Use the original file name
56	},
57});
58