aboutsummaryrefslogtreecommitdiff
path: root/src/server/DashUploadUtils.ts
blob: 66874e96c5481ef7c4987c748d2f374956ad6001 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import * as fs from 'fs';
import { Utils } from '../Utils';
import * as path from 'path';
import { Opt } from '../new_fields/Doc';
import * as sharp from 'sharp';
import request = require('request-promise');

const uploadDirectory = path.join(__dirname, './public/files/');

export namespace DashUploadUtils {

    export interface Size {
        width: number;
        suffix: string;
    }

    export const Sizes: { [size: string]: Size } = {
        SMALL: { width: 100, suffix: "_s" },
        MEDIUM: { width: 400, suffix: "_m" },
        LARGE: { width: 900, suffix: "_l" },
    };

    const gifs = [".gif"];
    const pngs = [".png"];
    const jpgs = [".jpg", ".jpeg"];
    const imageFormats = [...pngs, ...jpgs, ...gifs];
    const videoFormats = [".mov", ".mp4"];

    const size = "content-length";
    const type = "content-type";

    export interface UploadInformation {
        mediaPaths: string[];
        fileNames: { [key: string]: string };
        contentSize?: number;
        contentType?: string;
    }

    const generate = (prefix: string, url: string) => `${prefix}upload_${Utils.GenerateGuid()}${path.extname(url).toLowerCase()}`;
    const sanitize = (filename: string) => filename.replace(/\s+/g, "_");

    export interface InspectionResults {
        isLocal: boolean;
        stream: any;
        normalizedUrl: string;
        contentSize?: number;
        contentType?: string;
    }

    export const InspectImage = async (url: string): Promise<InspectionResults> => {
        const { isLocal, stream, normalized: normalizedUrl } = classify(url);
        const results = {
            isLocal,
            stream,
            normalizedUrl
        };
        if (isLocal) {
            return results;
        }
        const metadata = (await new Promise<any>((resolve, reject) => {
            request.head(url, async (error, res) => {
                if (error) {
                    return reject(error);
                }
                resolve(res);
            });
        })).headers;
        return {
            contentSize: parseInt(metadata[size]),
            contentType: metadata[type],
            ...results
        };
    };

    export const UploadImage = async (metadata: InspectionResults, filename?: string, prefix = ""): Promise<Opt<UploadInformation>> => {
        const { isLocal, stream, normalizedUrl, contentSize, contentType } = metadata;
        const resolved = filename ? sanitize(filename) : generate(prefix, normalizedUrl);
        let extension = path.extname(normalizedUrl) || path.extname(resolved);
        extension && (extension = extension.toLowerCase());
        let information: UploadInformation = {
            mediaPaths: [],
            fileNames: { clean: resolved },
            contentSize,
            contentType,
        };
        return new Promise<UploadInformation>(async (resolve, reject) => {
            const resizers = [
                { resizer: sharp().rotate(), suffix: "_o" },
                ...Object.values(Sizes).map(size => ({
                    resizer: sharp().resize(size.width, undefined, { withoutEnlargement: true }).rotate(),
                    suffix: size.suffix
                }))
            ];
            let nonVisual = false;
            if (pngs.includes(extension)) {
                resizers.forEach(element => element.resizer = element.resizer.png());
            } else if (jpgs.includes(extension)) {
                resizers.forEach(element => element.resizer = element.resizer.jpeg());
            } else if (![...imageFormats, ...videoFormats].includes(extension.toLowerCase())) {
                nonVisual = true;
            }
            if (imageFormats.includes(extension)) {
                for (let resizer of resizers) {
                    const suffix = resizer.suffix;
                    let mediaPath: string;
                    await new Promise<void>(resolve => {
                        const filename = resolved.substring(0, resolved.length - extension.length) + suffix + extension;
                        information.mediaPaths.push(mediaPath = uploadDirectory + filename);
                        information.fileNames[suffix] = filename;
                        stream(normalizedUrl).pipe(resizer.resizer).pipe(fs.createWriteStream(mediaPath))
                            .on('close', resolve)
                            .on('error', reject);
                    });
                }
            }
            if (!isLocal || nonVisual) {
                await new Promise<void>(resolve => {
                    stream(normalizedUrl).pipe(fs.createWriteStream(uploadDirectory + resolved)).on('close', resolve);
                });
            }
            resolve(information);
        });
    };

    const classify = (url: string) => {
        const isLocal = /Dash-Web(\\|\/)src(\\|\/)server(\\|\/)public(\\|\/)files/g.test(url);
        return {
            isLocal,
            stream: isLocal ? fs.createReadStream : request,
            normalized: isLocal ? path.normalize(url) : url
        };
    };

    export const createIfNotExists = async (path: string) => {
        if (await new Promise<boolean>(resolve => fs.exists(path, resolve))) {
            return true;
        }
        return new Promise<boolean>(resolve => fs.mkdir(path, error => resolve(error === null)));
    };

    export const Destroy = (mediaPath: string) => new Promise<boolean>(resolve => fs.unlink(mediaPath, error => resolve(error === null)));

}