UNPKG

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