aboutsummaryrefslogtreecommitdiff
path: root/src/client/util/request-image-size.ts
blob: 57e8516acb4ba404bdeab677d719872747d3b450 (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
/**
 * request-image-size: Detect image dimensions via request.
 * Licensed under the MIT license.
 *
 * https://github.com/FdezRomero/request-image-size
 * © 2017 Rodrigo Fernández Romero
 *
 * Based on the work of Johannes J. Schmidt
 * https://github.com/jo/http-image-size
 */

const request = require('request');
const imageSize = require('image-size');
const HttpError = require('standard-http-error');

module.exports = function requestImageSize(options: any) {
    let opts = {
        encoding: null,
    };

    if (options && typeof options === 'object') {
        opts = Object.assign(options, opts);
    } else if (options && typeof options === 'string') {
        opts = Object.assign(
            {
                uri: options,
            },
            opts
        );
    } else {
        return Promise.reject(new Error('You should provide an URI string or a "request" options object.'));
    }

    opts.encoding = null;

    return new Promise((resolve, reject) => {
        const req = request(opts);

        req.on('response', (res: any) => {
            if (res.statusCode >= 400) {
                return reject(new HttpError(res.statusCode, res.statusMessage));
            }

            let buffer = Buffer.from([]);
            let size: any;

            res.on('data', (chunk: any) => {
                buffer = Buffer.concat([buffer, chunk]);

                try {
                    size = imageSize(buffer);
                    if (size) {
                        resolve(size);
                        return req.abort();
                    }
                } catch (err) {}
            });

            res.on('error', reject);

            res.on('end', () => {
                if (!size) {
                    return reject(new Error('Image has no size'));
                }

                size.downloaded = buffer.length;
                return resolve(size);
            });
        });

        req.on('error', reject);
    });
};