UNPKG

30.4 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 _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; };
6
7var _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; }; }();
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');
36var config = require("./config");
37var ProxyAgent = utils.optionalRequire('proxy-agent');
38var ensureOption = require('./utils/ensureOption').defaults(config());
39
40var build_upload_params = utils.build_upload_params,
41 extend = utils.extend,
42 includes = utils.includes,
43 isEmpty = utils.isEmpty,
44 isObject = utils.isObject,
45 isRemoteUrl = utils.isRemoteUrl,
46 merge = utils.merge,
47 pickOnlyExistingValues = utils.pickOnlyExistingValues;
48
49
50exports.unsigned_upload_stream = function unsigned_upload_stream(upload_preset, callback) {
51 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
52
53 return exports.upload_stream(callback, merge(options, {
54 unsigned: true,
55 upload_preset: upload_preset
56 }));
57};
58
59exports.upload_stream = function upload_stream(callback) {
60 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
61
62 return exports.upload(null, callback, extend({
63 stream: true
64 }, options));
65};
66
67exports.unsigned_upload = function unsigned_upload(file, upload_preset, callback) {
68 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
69
70 return exports.upload(file, callback, merge(options, {
71 unsigned: true,
72 upload_preset: upload_preset
73 }));
74};
75
76exports.upload = function upload(file, callback) {
77 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
78
79 return call_api("upload", callback, options, function () {
80 var params = build_upload_params(options);
81 return isRemoteUrl(file) ? [params, { file: file }] : [params, {}, file];
82 });
83};
84
85exports.upload_large = function upload_large(path, callback) {
86 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
87
88 if (path != null && isRemoteUrl(path)) {
89 // upload a remote file
90 return exports.upload(path, callback, options);
91 }
92 if (path != null && !options.filename) {
93 options.filename = path.split(/(\\|\/)/g).pop().replace(/\.[^/.]+$/, "");
94 }
95 return exports.upload_chunked(path, callback, extend({
96 resource_type: 'raw'
97 }, options));
98};
99
100exports.upload_chunked = function upload_chunked(path, callback, options) {
101 var file_reader = fs.createReadStream(path);
102 var out_stream = exports.upload_chunked_stream(callback, options);
103 return file_reader.pipe(out_stream);
104};
105
106var Chunkable = function (_Writable) {
107 _inherits(Chunkable, _Writable);
108
109 function Chunkable(options) {
110 _classCallCheck(this, Chunkable);
111
112 var _this = _possibleConstructorReturn(this, (Chunkable.__proto__ || Object.getPrototypeOf(Chunkable)).call(this, options));
113
114 _this.chunk_size = options.chunk_size != null ? options.chunk_size : 20000000;
115 _this.buffer = Buffer.alloc(0);
116 _this.active = true;
117 _this.on('finish', function () {
118 if (_this.active) {
119 _this.emit('ready', _this.buffer, true, function () {});
120 }
121 });
122 return _this;
123 }
124
125 _createClass(Chunkable, [{
126 key: '_write',
127 value: function _write(data, encoding, done) {
128 var _this2 = this;
129
130 if (!this.active) {
131 done();
132 }
133 if (this.buffer.length + data.length <= this.chunk_size) {
134 this.buffer = Buffer.concat([this.buffer, data], this.buffer.length + data.length);
135 done();
136 } else {
137 var grab = this.chunk_size - this.buffer.length;
138 this.buffer = Buffer.concat([this.buffer, data.slice(0, grab)], this.buffer.length + grab);
139 this.emit('ready', this.buffer, false, function (active) {
140 _this2.active = active;
141 if (_this2.active) {
142 _this2.buffer = data.slice(grab);
143 done();
144 }
145 });
146 }
147 }
148 }]);
149
150 return Chunkable;
151}(Writable);
152
153exports.upload_large_stream = function upload_large_stream(_unused_, callback) {
154 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
155
156 return exports.upload_chunked_stream(callback, extend({
157 resource_type: 'raw'
158 }, options));
159};
160
161exports.upload_chunked_stream = function upload_chunked_stream(callback) {
162 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
163
164 options = extend({}, options, {
165 stream: true
166 });
167 options.x_unique_upload_id = utils.random_public_id();
168 var params = build_upload_params(options);
169 var chunk_size = options.chunk_size != null ? options.chunk_size : options.part_size;
170 var chunker = new Chunkable({
171 chunk_size: chunk_size
172 });
173 var sent = 0;
174 chunker.on('ready', function (buffer, is_last, done) {
175 var chunk_start = sent;
176 sent += buffer.length;
177 options.content_range = `bytes ${chunk_start}-${sent - 1}/${is_last ? sent : -1}`;
178 params.timestamp = utils.timestamp();
179 var finished_part = function finished_part(result) {
180 var errorOrLast = result.error != null || is_last;
181 if (errorOrLast && typeof callback === "function") {
182 callback(result);
183 }
184 return done(!errorOrLast);
185 };
186 var stream = call_api("upload", finished_part, options, function () {
187 return [params, {}, buffer];
188 });
189 return stream.write(buffer, 'buffer', function () {
190 return stream.end();
191 });
192 });
193 return chunker;
194};
195
196exports.explicit = function explicit(public_id, callback) {
197 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
198
199 return call_api("explicit", callback, options, function () {
200 return utils.build_explicit_api_params(public_id, options);
201 });
202};
203
204// Creates a new archive in the server and returns information in JSON format
205exports.create_archive = function create_archive(callback) {
206 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
207 var target_format = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
208
209 return call_api("generate_archive", callback, options, function () {
210 var opt = utils.archive_params(options);
211 if (target_format) {
212 opt.target_format = target_format;
213 }
214 return [opt];
215 });
216};
217
218// Creates a new zip archive in the server and returns information in JSON format
219exports.create_zip = function create_zip(callback) {
220 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
221
222 return exports.create_archive(callback, options, "zip");
223};
224
225exports.create_slideshow = function create_slideshow(options, callback) {
226 options.resource_type = ensureOption(options, "resource_type", "video");
227 return call_api("create_slideshow", callback, options, function () {
228 // Generate a transformation from the manifest_transformation key, which should be a valid transformation
229 var manifest_transformation = utils.generate_transformation_string(extend({}, options.manifest_transformation));
230
231 // Try to use {options.transformation} to generate a transformation (Example: options.transformation.width, options.transformation.height)
232 var transformation = utils.generate_transformation_string(extend({}, ensureOption(options, 'transformation', {})));
233
234 return [{
235 timestamp: utils.timestamp(),
236 manifest_transformation: manifest_transformation,
237 upload_preset: options.upload_preset,
238 overwrite: options.overwrite,
239 public_id: options.public_id,
240 notification_url: options.notification_url,
241 manifest_json: options.manifest_json,
242 tags: options.tags,
243 transformation: transformation
244 }];
245 });
246};
247
248exports.destroy = function destroy(public_id, callback) {
249 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
250
251 return call_api("destroy", callback, options, function () {
252 return [{
253 timestamp: utils.timestamp(),
254 type: options.type,
255 invalidate: options.invalidate,
256 public_id: public_id
257 }];
258 });
259};
260
261exports.rename = function rename(from_public_id, to_public_id, callback) {
262 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
263
264 return call_api("rename", callback, options, function () {
265 return [{
266 timestamp: utils.timestamp(),
267 type: options.type,
268 from_public_id: from_public_id,
269 to_public_id: to_public_id,
270 overwrite: options.overwrite,
271 invalidate: options.invalidate,
272 to_type: options.to_type
273 }];
274 });
275};
276
277var TEXT_PARAMS = ["public_id", "font_family", "font_size", "font_color", "text_align", "font_weight", "font_style", "background", "opacity", "text_decoration", "font_hinting", "font_antialiasing"];
278
279exports.text = function text(content, callback) {
280 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
281
282 return call_api("text", callback, options, function () {
283 var textParams = pickOnlyExistingValues.apply(undefined, [options].concat(TEXT_PARAMS));
284 var params = _extends({
285 timestamp: utils.timestamp(),
286 text: content
287 }, textParams);
288
289 return [params];
290 });
291};
292
293/**
294 * Generate a sprite by merging multiple images into a single large image for reducing network overhead and bypassing
295 * download limitations.
296 *
297 * The process produces 2 files as follows:
298 * - A single image file containing all the images with the specified tag (PNG by default).
299 * - A CSS file that includes the style class names and the location of the individual images in the sprite.
300 *
301 * @param {String|Object} tag A string specifying a tag that indicates which images to include or an object
302 * which includes options and image URLs.
303 * @param {Function} callback Callback function
304 * @param {Object} options Configuration options. If options are passed as the first parameter, this parameter
305 * should be empty
306 *
307 * @return {Object}
308 */
309exports.generate_sprite = function generate_sprite(tag, callback) {
310 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
311
312 return call_api("sprite", callback, options, function () {
313 return [utils.build_multi_and_sprite_params(tag, options)];
314 });
315};
316
317/**
318 * Returns a signed url to download a sprite
319 *
320 * @param {String|Object} tag A string specifying a tag that indicates which images to include or an object
321 * which includes options and image URLs.
322 * @param {Object} options Configuration options. If options are passed as the first parameter, this parameter
323 * should be empty
324 *
325 * @returns {string}
326 */
327exports.download_generated_sprite = function download_generated_sprite(tag) {
328 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
329
330 return utils.api_download_url("sprite", utils.build_multi_and_sprite_params(tag, options), options);
331};
332
333/**
334 * Returns a signed url to download a single animated image (GIF, PNG or WebP), video (MP4 or WebM) or a single PDF from
335 * multiple image assets.
336 *
337 * @param {String|Object} tag A string specifying a tag that indicates which images to include or an object
338 * which includes options and image URLs.
339 * @param {Object} options Configuration options. If options are passed as the first parameter, this parameter
340 * should be empty
341 *
342 * @returns {string}
343 */
344exports.download_multi = function download_multi(tag) {
345 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
346
347 return utils.api_download_url("multi", utils.build_multi_and_sprite_params(tag, options), options);
348};
349
350/**
351 * Creates either a single animated image (GIF, PNG or WebP), video (MP4 or WebM) or a single PDF from multiple image
352 * assets.
353 *
354 * Each asset is included as a single frame of the resulting animated image/video, or a page of the PDF (sorted
355 * alphabetically by their Public ID).
356 *
357 * @param {String|Object} tag A string specifying a tag that indicates which images to include or an object
358 * which includes options and image URLs.
359 * @param {Function} callback Callback function
360 * @param {Object} options Configuration options. If options are passed as the first parameter, this parameter
361 * should be empty
362 *
363 * @return {Object}
364 */
365exports.multi = function multi(tag, callback) {
366 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
367
368 return call_api("multi", callback, options, function () {
369 return [utils.build_multi_and_sprite_params(tag, options)];
370 });
371};
372
373exports.explode = function explode(public_id, callback) {
374 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
375
376 return call_api("explode", callback, options, function () {
377 var transformation = utils.generate_transformation_string(extend({}, options));
378 return [{
379 timestamp: utils.timestamp(),
380 public_id: public_id,
381 transformation: transformation,
382 format: options.format,
383 type: options.type,
384 notification_url: options.notification_url
385 }];
386 });
387};
388
389/**
390 *
391 * @param {String} tag The tag or tags to assign. Can specify multiple
392 * tags in a single string, separated by commas - "t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11".
393 *
394 * @param {Array} public_ids A list of public IDs (up to 1000) of assets uploaded to Cloudinary.
395 *
396 * @param {Function} callback Callback function
397 *
398 * @param {Object} options Configuration options may include 'exclusive' (boolean) which causes
399 * clearing this tag from all other resources
400 * @return {Object}
401 */
402exports.add_tag = function add_tag(tag) {
403 var public_ids = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
404 var callback = arguments[2];
405 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
406
407 var exclusive = utils.option_consume("exclusive", options);
408 var command = exclusive ? "set_exclusive" : "add";
409 return call_tags_api(tag, command, public_ids, callback, options);
410};
411
412/**
413 * @param {String} tag The tag or tags to remove. Can specify multiple
414 * tags in a single string, separated by commas - "t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11".
415 *
416 * @param {Array} public_ids A list of public IDs (up to 1000) of assets uploaded to Cloudinary.
417 *
418 * @param {Function} callback Callback function
419 *
420 * @param {Object} options Configuration options may include 'exclusive' (boolean) which causes
421 * clearing this tag from all other resources
422 * @return {Object}
423 */
424exports.remove_tag = function remove_tag(tag) {
425 var public_ids = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
426 var callback = arguments[2];
427 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
428
429 return call_tags_api(tag, "remove", public_ids, callback, options);
430};
431
432exports.remove_all_tags = function remove_all_tags() {
433 var public_ids = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
434 var callback = arguments[1];
435 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
436
437 return call_tags_api(null, "remove_all", public_ids, callback, options);
438};
439
440exports.replace_tag = function replace_tag(tag) {
441 var public_ids = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
442 var callback = arguments[2];
443 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
444
445 return call_tags_api(tag, "replace", public_ids, callback, options);
446};
447
448function call_tags_api(tag, command) {
449 var public_ids = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
450 var callback = arguments[3];
451 var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
452
453 return call_api("tags", callback, options, function () {
454 var params = {
455 timestamp: utils.timestamp(),
456 public_ids: utils.build_array(public_ids),
457 command: command,
458 type: options.type
459 };
460 if (tag != null) {
461 params.tag = tag;
462 }
463 return [params];
464 });
465}
466
467exports.add_context = function add_context(context) {
468 var public_ids = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
469 var callback = arguments[2];
470 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
471
472 return call_context_api(context, 'add', public_ids, callback, options);
473};
474
475exports.remove_all_context = function remove_all_context() {
476 var public_ids = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
477 var callback = arguments[1];
478 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
479
480 return call_context_api(null, 'remove_all', public_ids, callback, options);
481};
482
483function call_context_api(context, command) {
484 var public_ids = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
485 var callback = arguments[3];
486 var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
487
488 return call_api('context', callback, options, function () {
489 var params = {
490 timestamp: utils.timestamp(),
491 public_ids: utils.build_array(public_ids),
492 command: command,
493 type: options.type
494 };
495 if (context != null) {
496 params.context = utils.encode_context(context);
497 }
498 return [params];
499 });
500}
501
502/**
503 * Cache (part of) the upload results.
504 * @param result
505 * @param {object} options
506 * @param {string} options.type
507 * @param {string} options.resource_type
508 */
509function cacheResults(result, _ref) {
510 var type = _ref.type,
511 resource_type = _ref.resource_type;
512
513 if (result.responsive_breakpoints) {
514 result.responsive_breakpoints.forEach(function (_ref2) {
515 var transformation = _ref2.transformation,
516 url = _ref2.url,
517 breakpoints = _ref2.breakpoints;
518 return Cache.set(result.public_id, { type, resource_type, raw_transformation: transformation, format: extname(breakpoints[0].url).slice(1) }, breakpoints.map(function (i) {
519 return i.width;
520 }));
521 });
522 }
523}
524
525function parseResult(buffer, res) {
526 var result = '';
527 try {
528 result = JSON.parse(buffer);
529 if (result.error && !result.error.name) {
530 result.error.name = "Error";
531 }
532 } catch (jsonError) {
533 result = {
534 error: {
535 message: `Server return invalid JSON response. Status Code ${res.statusCode}. ${jsonError}`,
536 name: "Error"
537 }
538 };
539 }
540 return result;
541}
542
543function call_api(action, callback, options, get_params) {
544 if (typeof callback !== "function") {
545 callback = function callback() {};
546 }
547
548 var USE_PROMISES = !options.disable_promises;
549
550 var deferred = Q.defer();
551 if (options == null) {
552 options = {};
553 }
554
555 var _get_params$call = get_params.call(),
556 _get_params$call2 = _slicedToArray(_get_params$call, 3),
557 params = _get_params$call2[0],
558 unsigned_params = _get_params$call2[1],
559 file = _get_params$call2[2];
560
561 params = utils.process_request_params(params, options);
562 params = extend(params, unsigned_params);
563 var api_url = utils.api_url(action, options);
564 var boundary = utils.random_public_id();
565 var errorRaised = false;
566 var handle_response = function handle_response(res) {
567 // let buffer;
568 if (errorRaised) {
569
570 // Already reported
571 } else if (res.error) {
572 errorRaised = true;
573
574 if (USE_PROMISES) {
575 deferred.reject(res);
576 }
577 callback(res);
578 } else if (includes([200, 400, 401, 404, 420, 500], res.statusCode)) {
579 var buffer = "";
580 res.on("data", function (d) {
581 buffer += d;
582 return buffer;
583 });
584 res.on("end", function () {
585 var result = void 0;
586 if (errorRaised) {
587 return;
588 }
589 result = parseResult(buffer, res);
590 if (result.error) {
591 result.error.http_code = res.statusCode;
592 if (USE_PROMISES) {
593 deferred.reject(result.error);
594 }
595 } else {
596 cacheResults(result, options);
597 if (USE_PROMISES) {
598 deferred.resolve(result);
599 }
600 }
601 callback(result);
602 });
603 res.on("error", function (error) {
604 errorRaised = true;
605 if (USE_PROMISES) {
606 deferred.reject(error);
607 }
608 callback({ error });
609 });
610 } else {
611 var error = {
612 message: `Server returned unexpected status code - ${res.statusCode}`,
613 http_code: res.statusCode,
614 name: "UnexpectedResponse"
615 };
616 if (USE_PROMISES) {
617 deferred.reject(error);
618 }
619 callback({ error });
620 }
621 };
622 var post_data = utils.hashToParameters(params).filter(function (_ref3) {
623 var _ref4 = _slicedToArray(_ref3, 2),
624 key = _ref4[0],
625 value = _ref4[1];
626
627 return value != null;
628 }).map(function (_ref5) {
629 var _ref6 = _slicedToArray(_ref5, 2),
630 key = _ref6[0],
631 value = _ref6[1];
632
633 return Buffer.from(encodeFieldPart(boundary, key, value), 'utf8');
634 });
635 var result = post(api_url, post_data, boundary, file, handle_response, options);
636 if (isObject(result)) {
637 return result;
638 }
639
640 if (USE_PROMISES) {
641 return deferred.promise;
642 }
643}
644
645function post(url, post_data, boundary, file, callback, options) {
646 var file_header = void 0;
647 var finish_buffer = Buffer.from("--" + boundary + "--", 'ascii');
648 var oauth_token = options.oauth_token || config().oauth_token;
649 if (file != null || options.stream) {
650 // eslint-disable-next-line no-nested-ternary
651 var filename = options.stream ? options.filename ? options.filename : "file" : basename(file);
652 file_header = Buffer.from(encodeFilePart(boundary, 'application/octet-stream', 'file', filename), 'binary');
653 }
654 var post_options = urlLib.parse(url);
655 var headers = {
656 'Content-Type': `multipart/form-data; boundary=${boundary}`,
657 'User-Agent': utils.getUserAgent()
658 };
659 if (options.content_range != null) {
660 headers['Content-Range'] = options.content_range;
661 }
662 if (options.x_unique_upload_id != null) {
663 headers['X-Unique-Upload-Id'] = options.x_unique_upload_id;
664 }
665 if (oauth_token != null) {
666 headers.Authorization = `Bearer ${oauth_token}`;
667 }
668
669 post_options = extend(post_options, {
670 method: 'POST',
671 headers: headers
672 });
673 if (options.agent != null) {
674 post_options.agent = options.agent;
675 }
676 var proxy = options.api_proxy || config().api_proxy;
677 if (!isEmpty(proxy)) {
678 if (!post_options.agent) {
679 if (ProxyAgent === null) {
680 throw new Error("Proxy value is set, but `proxy-agent` is not installed, please install `proxy-agent` module.");
681 }
682 post_options.agent = new ProxyAgent(proxy);
683 } else {
684 console.warn("Proxy is set, but request uses a custom agent, proxy is ignored.");
685 }
686 }
687
688 var post_request = https.request(post_options, callback);
689 var upload_stream = new UploadStream({ boundary });
690 upload_stream.pipe(post_request);
691 var timeout = false;
692 post_request.on("error", function (error) {
693 if (timeout) {
694 error = {
695 message: "Request Timeout",
696 http_code: 499,
697 name: "TimeoutError"
698 };
699 }
700 return callback({ error });
701 });
702 post_request.setTimeout(options.timeout != null ? options.timeout : 60000, function () {
703 timeout = true;
704 return post_request.abort();
705 });
706 post_data.forEach(function (postDatum) {
707 return post_request.write(postDatum);
708 });
709 if (options.stream) {
710 post_request.write(file_header);
711 return upload_stream;
712 }
713 if (file != null) {
714 post_request.write(file_header);
715 fs.createReadStream(file).on('error', function (error) {
716 callback({
717 error: error
718 });
719 return post_request.abort();
720 }).pipe(upload_stream);
721 } else {
722 post_request.write(finish_buffer);
723 post_request.end();
724 }
725 return true;
726}
727
728function encodeFieldPart(boundary, name, value) {
729 return [`--${boundary}`, `Content-Disposition: form-data; name="${name}"`, '', value, ''].join("\r\n");
730}
731
732function encodeFilePart(boundary, type, name, filename) {
733 return [`--${boundary}`, `Content-Disposition: form-data; name="${name}"; filename="${filename}"`, `Content-Type: ${type}`, '', ''].join("\r\n");
734}
735
736exports.direct_upload = function direct_upload(callback_url) {
737 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
738
739 var params = build_upload_params(extend({
740 callback: callback_url
741 }, options));
742 params = utils.process_request_params(params, options);
743 var api_url = utils.api_url("upload", options);
744 return {
745 hidden_fields: params,
746 form_attrs: {
747 action: api_url,
748 method: "POST",
749 enctype: "multipart/form-data"
750 }
751 };
752};
753
754exports.upload_tag_params = function upload_tag_params() {
755 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
756
757 var params = build_upload_params(options);
758 params = utils.process_request_params(params, options);
759 return JSON.stringify(params);
760};
761
762exports.upload_url = function upload_url() {
763 var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
764
765 if (options.resource_type == null) {
766 options.resource_type = "auto";
767 }
768 return utils.api_url("upload", options);
769};
770
771exports.image_upload_tag = function image_upload_tag(field) {
772 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
773
774 var html_options = options.html || {};
775 var tag_options = extend({
776 type: "file",
777 name: "file",
778 "data-url": exports.upload_url(options),
779 "data-form-data": exports.upload_tag_params(options),
780 "data-cloudinary-field": field,
781 "data-max-chunk-size": options.chunk_size,
782 "class": [html_options.class, "cloudinary-fileupload"].join(" ")
783 }, html_options);
784 return `<input ${utils.html_attrs(tag_options)}/>`;
785};
786
787exports.unsigned_image_upload_tag = function unsigned_image_upload_tag(field, upload_preset) {
788 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
789
790 return exports.image_upload_tag(field, merge(options, {
791 unsigned: true,
792 upload_preset: upload_preset
793 }));
794};
795
796/**
797 * Populates metadata fields with the given values. Existing values will be overwritten.
798 *
799 * @param {Object} metadata A list of custom metadata fields (by external_id) and the values to assign to each
800 * @param {Array} public_ids The public IDs of the resources to update
801 * @param {Function} callback Callback function
802 * @param {Object} options Configuration options
803 *
804 * @return {Object}
805 */
806exports.update_metadata = function update_metadata(metadata, public_ids, callback) {
807 var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
808
809 return call_api("metadata", callback, options, function () {
810 var params = {
811 metadata: utils.encode_context(metadata),
812 public_ids: utils.build_array(public_ids),
813 timestamp: utils.timestamp(),
814 type: options.type
815 };
816 return [params];
817 });
818};
\No newline at end of file