diff options
author | bobzel <zzzman@gmail.com> | 2023-06-23 21:44:01 -0400 |
---|---|---|
committer | bobzel <zzzman@gmail.com> | 2023-06-23 21:44:01 -0400 |
commit | 85c017527f209c9d007d67ac70958843ab45e729 (patch) | |
tree | e2649860002e0c60e98d84439a67235002ddd9a4 /src/client/util/request-image-size.ts | |
parent | e9d5dbeef2bf1dab9dfb863d970b70b3074e3d0a (diff) | |
parent | 1429ab79eac9aa316082f52c14c576f6b3a97111 (diff) |
Merge branch 'master' into heartbeat
Diffstat (limited to 'src/client/util/request-image-size.ts')
-rw-r--r-- | src/client/util/request-image-size.ts | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/src/client/util/request-image-size.ts b/src/client/util/request-image-size.ts new file mode 100644 index 000000000..57e8516ac --- /dev/null +++ b/src/client/util/request-image-size.ts @@ -0,0 +1,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); + }); +}; |