1 | 'use strict';
|
2 |
|
3 | var _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 |
|
5 | var _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 |
|
7 | var _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 |
|
9 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
10 |
|
11 | function _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 |
|
13 | function _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 |
|
15 | var fs = require('fs');
|
16 |
|
17 | var _require = require('path'),
|
18 | extname = _require.extname,
|
19 | basename = _require.basename;
|
20 |
|
21 | var Q = require('q');
|
22 | var Writable = require("stream").Writable;
|
23 | var urlLib = require('url');
|
24 |
|
25 |
|
26 |
|
27 | var _require2 = require("./config")(),
|
28 | upload_prefix = _require2.upload_prefix;
|
29 |
|
30 | var isSecure = !(upload_prefix && upload_prefix.slice(0, 5) === 'http:');
|
31 | var https = isSecure ? require('https') : require('http');
|
32 |
|
33 | var Cache = require('./cache');
|
34 | var utils = require("./utils");
|
35 | var UploadStream = require('./upload_stream');
|
36 | var config = require("./config");
|
37 | var ensureOption = require('./utils/ensureOption').defaults(config());
|
38 |
|
39 | var 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 |
|
48 | exports.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 |
|
57 | exports.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 |
|
65 | exports.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 |
|
74 | exports.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 |
|
83 | exports.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 |
|
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 |
|
98 | exports.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 |
|
104 | var 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 |
|
151 | exports.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 |
|
159 | exports.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 |
|
194 | exports.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 |
|
203 | exports.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 |
|
217 | exports.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 |
|
223 | exports.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 |
|
227 | var manifest_transformation = utils.generate_transformation_string(extend({}, options.manifest_transformation));
|
228 |
|
229 |
|
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 |
|
246 | exports.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 |
|
259 | exports.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 |
|
275 | var 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 |
|
277 | exports.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 |
|
293 |
|
294 |
|
295 |
|
296 |
|
297 |
|
298 |
|
299 |
|
300 |
|
301 |
|
302 |
|
303 |
|
304 |
|
305 |
|
306 |
|
307 | exports.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 |
|
317 |
|
318 |
|
319 |
|
320 |
|
321 |
|
322 |
|
323 |
|
324 |
|
325 | exports.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 |
|
333 |
|
334 |
|
335 |
|
336 |
|
337 |
|
338 |
|
339 |
|
340 |
|
341 |
|
342 | exports.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 |
|
350 |
|
351 |
|
352 |
|
353 |
|
354 |
|
355 |
|
356 |
|
357 |
|
358 |
|
359 |
|
360 |
|
361 |
|
362 |
|
363 | exports.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 |
|
371 | exports.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 |
|
390 |
|
391 |
|
392 |
|
393 |
|
394 |
|
395 |
|
396 |
|
397 |
|
398 |
|
399 |
|
400 | exports.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 |
|
412 |
|
413 |
|
414 |
|
415 |
|
416 |
|
417 |
|
418 |
|
419 |
|
420 |
|
421 |
|
422 | exports.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 |
|
430 | exports.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 |
|
438 | exports.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 |
|
446 | function 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 |
|
465 | exports.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 |
|
473 | exports.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 |
|
481 | function 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 |
|
502 |
|
503 |
|
504 |
|
505 |
|
506 |
|
507 | function 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 |
|
523 | function 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 |
|
541 | function 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 |
|
566 | if (errorRaised) {
|
567 |
|
568 |
|
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 |
|
643 | function 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 |
|
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 |
|
714 | function encodeFieldPart(boundary, name, value) {
|
715 | return [`--${boundary}`, `Content-Disposition: form-data; name="${name}"`, '', value, ''].join("\r\n");
|
716 | }
|
717 |
|
718 | function encodeFilePart(boundary, type, name, filename) {
|
719 | return [`--${boundary}`, `Content-Disposition: form-data; name="${name}"; filename="${filename}"`, `Content-Type: ${type}`, '', ''].join("\r\n");
|
720 | }
|
721 |
|
722 | exports.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 |
|
740 | exports.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 |
|
748 | exports.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 |
|
757 | exports.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 |
|
773 | exports.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 |
|
784 |
|
785 |
|
786 |
|
787 |
|
788 |
|
789 |
|
790 |
|
791 |
|
792 | exports.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 |