UNPKG

23.1 kBJavaScriptView Raw
1'use strict';
2
3var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
4
5var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
6
7var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
8
9function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
10
11function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
12
13function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
14
15var fs = require('fs');
16
17var _require = require('path'),
18 extname = _require.extname,
19 basename = _require.basename;
20
21var Q = require('q');
22var Writable = require("stream").Writable;
23var urlLib = require('url');
24
25// eslint-disable-next-line import/order
26
27var _require2 = require("./config"),
28 upload_prefix = _require2.upload_prefix;
29
30var isSecure = !(upload_prefix && upload_prefix.slice(0, 5) === 'http:');
31var https = isSecure ? require('https') : require('http');
32
33var Cache = require('./cache');
34var utils = require("./utils");
35var UploadStream = require('./upload_stream');
36
37var build_upload_params = utils.build_upload_params,
38 extend = utils.extend,
39 includes = utils.includes,
40 isObject = utils.isObject,
41 isRemoteUrl = utils.isRemoteUrl,
42 merge = utils.merge;
43
44
45exports.unsigned_upload_stream = function unsigned_upload_stream(upload_preset, callback) {
46 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
47
48 return exports.upload_stream(callback, merge(options, {
49 unsigned: true,
50 upload_preset: upload_preset
51 }));
52};
53
54exports.upload_stream = function upload_stream(callback) {
55 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
56
57 return exports.upload(null, callback, extend({
58 stream: true
59 }, options));
60};
61
62exports.unsigned_upload = function unsigned_upload(file, upload_preset, callback) {
63 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
64
65 return exports.upload(file, callback, merge(options, {
66 unsigned: true,
67 upload_preset: upload_preset
68 }));
69};
70
71exports.upload = function upload(file, callback) {
72 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
73
74 return call_api("upload", callback, options, function () {
75 var params = build_upload_params(options);
76 return isRemoteUrl(file) ? [params, { file: file }] : [params, {}, file];
77 });
78};
79
80exports.upload_large = function upload_large(path, callback) {
81 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
82
83 if (path != null && path.match(/^https?:/)) {
84 // upload a remote file
85 return exports.upload(path, callback, options);
86 }
87 return exports.upload_chunked(path, callback, _extends({ resource_type: 'raw' }, options));
88};
89
90exports.upload_chunked = function upload_chunked(path, callback, options) {
91 var file_reader = fs.createReadStream(path);
92 var out_stream = exports.upload_chunked_stream(callback, options);
93 return file_reader.pipe(out_stream);
94};
95
96var Chunkable = function (_Writable) {
97 _inherits(Chunkable, _Writable);
98
99 function Chunkable(options) {
100 _classCallCheck(this, Chunkable);
101
102 var _this = _possibleConstructorReturn(this, (Chunkable.__proto__ || Object.getPrototypeOf(Chunkable)).call(this, options));
103
104 _this.chunk_size = options.chunk_size != null ? options.chunk_size : 20000000;
105 _this.buffer = Buffer.alloc(0);
106 _this.active = true;
107 _this.on('finish', function () {
108 if (_this.active) {
109 _this.emit('ready', _this.buffer, true, function () {});
110 }
111 });
112 return _this;
113 }
114
115 _createClass(Chunkable, [{
116 key: '_write',
117 value: function _write(data, encoding, done) {
118 var _this2 = this;
119
120 if (!this.active) {
121 done();
122 }
123 if (this.buffer.length + data.length <= this.chunk_size) {
124 this.buffer = Buffer.concat([this.buffer, data], this.buffer.length + data.length);
125 done();
126 } else {
127 var grab = this.chunk_size - this.buffer.length;
128 this.buffer = Buffer.concat([this.buffer, data.slice(0, grab)], this.buffer.length + grab);
129 this.emit('ready', this.buffer, false, function (active) {
130 _this2.active = active;
131 if (_this2.active) {
132 _this2.buffer = data.slice(grab);
133 done();
134 }
135 });
136 }
137 }
138 }]);
139
140 return Chunkable;
141}(Writable);
142
143exports.upload_large_stream = function upload_large_stream(_unused_, callback) {
144 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
145
146 return exports.upload_chunked_stream(callback, extend({
147 resource_type: 'raw'
148 }, options));
149};
150
151exports.upload_chunked_stream = function upload_chunked_stream(callback) {
152 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
153
154 options = extend({}, options, {
155 stream: true
156 });
157 options.x_unique_upload_id = utils.random_public_id();
158 var params = build_upload_params(options);
159 var chunk_size = options.chunk_size != null ? options.chunk_size : options.part_size;
160 var chunker = new Chunkable({
161 chunk_size: chunk_size
162 });
163 var sent = 0;
164 chunker.on('ready', function (buffer, is_last, done) {
165 var chunk_start = sent;
166 sent += buffer.length;
167 options.content_range = `bytes ${chunk_start}-${sent - 1}/${is_last ? sent : -1}`;
168 params.timestamp = utils.timestamp();
169 var finished_part = function finished_part(result) {
170 var errorOrLast = result.error != null || is_last;
171 if (errorOrLast && typeof callback === "function") {
172 callback(result);
173 }
174 return done(!errorOrLast);
175 };
176 var stream = call_api("upload", finished_part, options, function () {
177 return [params, {}, buffer];
178 });
179 return stream.write(buffer, 'buffer', function () {
180 return stream.end();
181 });
182 });
183 return chunker;
184};
185
186exports.explicit = function explicit(public_id, callback) {
187 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
188
189 return call_api("explicit", callback, options, function () {
190 return utils.build_explicit_api_params(public_id, options);
191 });
192};
193
194// Creates a new archive in the server and returns information in JSON format
195exports.create_archive = function create_archive(callback) {
196 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
197 var target_format = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
198
199 return call_api("generate_archive", callback, options, function () {
200 var opt = utils.archive_params(options);
201 if (target_format) {
202 opt.target_format = target_format;
203 }
204 return [opt];
205 });
206};
207
208// Creates a new zip archive in the server and returns information in JSON format
209exports.create_zip = function create_zip(callback) {
210 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
211
212 return exports.create_archive(callback, options, "zip");
213};
214
215exports.destroy = function destroy(public_id, callback) {
216 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
217
218 return call_api("destroy", callback, options, function () {
219 return [{
220 timestamp: utils.timestamp(),
221 type: options.type,
222 invalidate: options.invalidate,
223 public_id: public_id
224 }];
225 });
226};
227
228exports.rename = function rename(from_public_id, to_public_id, callback) {
229 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
230
231 return call_api("rename", callback, options, function () {
232 return [{
233 timestamp: utils.timestamp(),
234 type: options.type,
235 from_public_id: from_public_id,
236 to_public_id: to_public_id,
237 overwrite: options.overwrite,
238 invalidate: options.invalidate,
239 to_type: options.to_type
240 }];
241 });
242};
243
244var TEXT_PARAMS = ["public_id", "font_family", "font_size", "font_color", "text_align", "font_weight", "font_style", "background", "opacity", "text_decoration", "font_hinting", "font_antialiasing"];
245
246exports.text = function text(content, callback) {
247 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
248
249 return call_api("text", callback, options, function () {
250 var textParams = utils.only(options, TEXT_PARAMS);
251 var params = _extends({
252 timestamp: utils.timestamp(),
253 text: content
254 }, textParams);
255
256 return [params];
257 });
258};
259
260exports.generate_sprite = function generate_sprite(tag, callback) {
261 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
262
263 return call_api("sprite", callback, options, function () {
264 var transformation = utils.generate_transformation_string(extend({}, options, {
265 fetch_format: options.format
266 }));
267 return [{
268 timestamp: utils.timestamp(),
269 tag: tag,
270 transformation: transformation,
271 async: options.async,
272 notification_url: options.notification_url
273 }];
274 });
275};
276
277exports.multi = function multi(tag, callback) {
278 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
279
280 return call_api("multi", callback, options, function () {
281 var transformation = utils.generate_transformation_string(extend({}, options));
282 return [{
283 timestamp: utils.timestamp(),
284 tag: tag,
285 transformation: transformation,
286 format: options.format,
287 async: options.async,
288 notification_url: options.notification_url
289 }];
290 });
291};
292
293exports.explode = function explode(public_id, callback) {
294 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
295
296 return call_api("explode", callback, options, function () {
297 var transformation = utils.generate_transformation_string(extend({}, options));
298 return [{
299 timestamp: utils.timestamp(),
300 public_id: public_id,
301 transformation: transformation,
302 format: options.format,
303 type: options.type,
304 notification_url: options.notification_url
305 }];
306 });
307};
308
309// options may include 'exclusive' (boolean) which causes clearing this tag from all other resources
310exports.add_tag = function add_tag(tag) {
311 var public_ids = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
312 var callback = arguments[2];
313 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
314
315 var exclusive = utils.option_consume("exclusive", options);
316 var command = exclusive ? "set_exclusive" : "add";
317 return call_tags_api(tag, command, public_ids, callback, options);
318};
319
320exports.remove_tag = function remove_tag(tag) {
321 var public_ids = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
322 var callback = arguments[2];
323 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
324
325 return call_tags_api(tag, "remove", public_ids, callback, options);
326};
327
328exports.remove_all_tags = function remove_all_tags() {
329 var public_ids = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
330 var callback = arguments[1];
331 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
332
333 return call_tags_api(null, "remove_all", public_ids, callback, options);
334};
335
336exports.replace_tag = function replace_tag(tag) {
337 var public_ids = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
338 var callback = arguments[2];
339 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
340
341 return call_tags_api(tag, "replace", public_ids, callback, options);
342};
343
344function call_tags_api(tag, command) {
345 var public_ids = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
346 var callback = arguments[3];
347 var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
348
349 return call_api("tags", callback, options, function () {
350 var params = {
351 timestamp: utils.timestamp(),
352 public_ids: utils.build_array(public_ids),
353 command: command,
354 type: options.type
355 };
356 if (tag != null) {
357 params.tag = tag;
358 }
359 return [params];
360 });
361}
362
363exports.add_context = function add_context(context) {
364 var public_ids = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
365 var callback = arguments[2];
366 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
367
368 return call_context_api(context, 'add', public_ids, callback, options);
369};
370
371exports.remove_all_context = function remove_all_context() {
372 var public_ids = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
373 var callback = arguments[1];
374 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
375
376 return call_context_api(null, 'remove_all', public_ids, callback, options);
377};
378
379function call_context_api(context, command) {
380 var public_ids = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
381 var callback = arguments[3];
382 var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
383
384 return call_api('context', callback, options, function () {
385 var params = {
386 timestamp: utils.timestamp(),
387 public_ids: utils.build_array(public_ids),
388 command: command,
389 type: options.type
390 };
391 if (context != null) {
392 params.context = utils.encode_context(context);
393 }
394 return [params];
395 });
396}
397
398/**
399 * Cache (part of) the upload results.
400 * @param result
401 * @param {object} options
402 * @param {string} options.type
403 * @param {string} options.resource_type
404 */
405function cacheResults(result, _ref) {
406 var type = _ref.type,
407 resource_type = _ref.resource_type;
408
409 if (result.responsive_breakpoints) {
410 result.responsive_breakpoints.forEach(function (_ref2) {
411 var transformation = _ref2.transformation,
412 url = _ref2.url,
413 breakpoints = _ref2.breakpoints;
414 return Cache.set(result.public_id, { type, resource_type, raw_transformation: transformation, format: extname(breakpoints[0].url).slice(1) }, breakpoints.map(function (i) {
415 return i.width;
416 }));
417 });
418 }
419}
420
421function parseResult(buffer, res) {
422 var result = '';
423 try {
424 result = JSON.parse(buffer);
425 } catch (jsonError) {
426 result = {
427 error: {
428 message: `Server return invalid JSON response. Status Code ${res.statusCode}. ${jsonError}`
429 }
430 };
431 }
432 return result;
433}
434
435function call_api(action, callback, options, get_params) {
436 if (typeof callback !== "function") {
437 callback = function callback() {};
438 }
439
440 var deferred = Q.defer();
441 if (options == null) {
442 options = {};
443 }
444
445 var _get_params$call = get_params.call(),
446 _get_params$call2 = _slicedToArray(_get_params$call, 3),
447 params = _get_params$call2[0],
448 unsigned_params = _get_params$call2[1],
449 file = _get_params$call2[2];
450
451 params = utils.process_request_params(params, options);
452 params = extend(params, unsigned_params);
453 var api_url = utils.api_url(action, options);
454 var boundary = utils.random_public_id();
455 var errorRaised = false;
456 var handle_response = function handle_response(res) {
457 // var buffer;
458 if (errorRaised) {
459
460 // Already reported
461 } else if (res.error) {
462 errorRaised = true;
463 deferred.reject(res);
464 callback(res);
465 } else if (includes([200, 400, 401, 404, 420, 500], res.statusCode)) {
466 var buffer = "";
467 res.on("data", function (d) {
468 buffer += d;
469 return buffer;
470 });
471 res.on("end", function () {
472 var result = void 0;
473 if (errorRaised) {
474 return;
475 }
476 result = parseResult(buffer, res);
477 if (result.error) {
478 result.error.http_code = res.statusCode;
479 deferred.reject(result.error);
480 } else {
481 cacheResults(result, options);
482 deferred.resolve(result);
483 }
484 callback(result);
485 });
486 res.on("error", function (error) {
487 errorRaised = true;
488 deferred.reject(error);
489 callback({ error });
490 });
491 } else {
492 var error = {
493 message: `Server returned unexpected status code - ${res.statusCode}`,
494 http_code: res.statusCode
495 };
496 deferred.reject(error);
497 callback({ error });
498 }
499 };
500 var post_data = utils.hashToParameters(params).filter(function (_ref3) {
501 var _ref4 = _slicedToArray(_ref3, 2),
502 key = _ref4[0],
503 value = _ref4[1];
504
505 return value != null;
506 }).map(function (_ref5) {
507 var _ref6 = _slicedToArray(_ref5, 2),
508 key = _ref6[0],
509 value = _ref6[1];
510
511 return Buffer.from(encodeFieldPart(boundary, key, value), 'utf8');
512 });
513
514 var result = post(api_url, post_data, boundary, file, handle_response, options);
515 if (isObject(result)) {
516 return result;
517 }
518 return deferred.promise;
519}
520
521function post(url, post_data, boundary, file, callback, options) {
522 var file_header;
523 var finish_buffer = Buffer.from("--" + boundary + "--", 'ascii');
524 if (file != null || options.stream) {
525 var filename = options.stream ? "file" : basename(file);
526 file_header = Buffer.from(encodeFilePart(boundary, 'application/octet-stream', 'file', filename), 'binary');
527 }
528 var post_options = urlLib.parse(url);
529 var headers = {
530 'Content-Type': `multipart/form-data; boundary=${boundary}`,
531 'User-Agent': utils.getUserAgent()
532 };
533 if (options.content_range != null) {
534 headers['Content-Range'] = options.content_range;
535 }
536 if (options.x_unique_upload_id != null) {
537 headers['X-Unique-Upload-Id'] = options.x_unique_upload_id;
538 }
539 post_options = extend(post_options, {
540 method: 'POST',
541 headers: headers
542 });
543 if (options.agent != null) {
544 post_options.agent = options.agent;
545 }
546 var post_request = https.request(post_options, callback);
547 var upload_stream = new UploadStream({ boundary });
548 upload_stream.pipe(post_request);
549 var timeout = false;
550 post_request.on("error", function (error) {
551 if (timeout) {
552 error = {
553 message: "Request Timeout",
554 http_code: 499
555 };
556 }
557 return callback({ error });
558 });
559 post_request.setTimeout(options.timeout != null ? options.timeout : 60000, function () {
560 timeout = true;
561 return post_request.abort();
562 });
563 post_data.forEach(function (postDatum) {
564 return post_request.write(postDatum);
565 });
566 if (options.stream) {
567 post_request.write(file_header);
568 return upload_stream;
569 }
570 if (file != null) {
571 post_request.write(file_header);
572 fs.createReadStream(file).on('error', function (error) {
573 callback({
574 error: error
575 });
576 return post_request.abort();
577 }).pipe(upload_stream);
578 } else {
579 post_request.write(finish_buffer);
580 post_request.end();
581 }
582 return true;
583}
584
585function encodeFieldPart(boundary, name, value) {
586 return [`--${boundary}`, `Content-Disposition: form-data; name="${name}"`, '', value, ''].join("\r\n");
587}
588
589function encodeFilePart(boundary, type, name, filename) {
590 return [`--${boundary}`, `Content-Disposition: form-data; name="${name}"; filename="${filename}"`, `Content-Type: ${type}`, '', ''].join("\r\n");
591}
592
593exports.direct_upload = function direct_upload(callback_url) {
594 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
595
596 var params = build_upload_params(extend({
597 callback: callback_url
598 }, options));
599 params = utils.process_request_params(params, options);
600 var api_url = utils.api_url("upload", options);
601 return {
602 hidden_fields: params,
603 form_attrs: {
604 action: api_url,
605 method: "POST",
606 enctype: "multipart/form-data"
607 }
608 };
609};
610
611exports.upload_tag_params = function upload_tag_params() {
612 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
613
614 var params = build_upload_params(options);
615 params = utils.process_request_params(params, options);
616 return JSON.stringify(params);
617};
618
619exports.upload_url = function upload_url() {
620 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
621
622 if (options.resource_type == null) {
623 options.resource_type = "auto";
624 }
625 return utils.api_url("upload", options);
626};
627
628exports.image_upload_tag = function image_upload_tag(field) {
629 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
630
631 var html_options = options.html || {};
632 var tag_options = extend({
633 type: "file",
634 name: "file",
635 "data-url": exports.upload_url(options),
636 "data-form-data": exports.upload_tag_params(options),
637 "data-cloudinary-field": field,
638 "data-max-chunk-size": options.chunk_size,
639 "class": [html_options.class, "cloudinary-fileupload"].join(" ")
640 }, html_options);
641 return `<input ${utils.html_attrs(tag_options)}/>`;
642};
643
644exports.unsigned_image_upload_tag = function unsigned_image_upload_tag(field, upload_preset) {
645 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
646
647 return exports.image_upload_tag(field, merge(options, {
648 unsigned: true,
649 upload_preset: upload_preset
650 }));
651};
\No newline at end of file