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