UNPKG

1.73 kBJavaScriptView Raw
1var PRELOADED_CLOUDINARY_PATH, config, utils;
2
3utils = require("./utils");
4
5config = require("./config");
6
7PRELOADED_CLOUDINARY_PATH = /^([^\/]+)\/([^\/]+)\/v(\d+)\/([^#]+)#([^\/]+)$/;
8
9class PreloadedFile {
10 constructor(file_info) {
11 var matches, public_id_and_format;
12 matches = file_info.match(PRELOADED_CLOUDINARY_PATH);
13 if (!matches) {
14 throw "Invalid preloaded file info";
15 }
16 this.resource_type = matches[1];
17 this.type = matches[2];
18 this.version = matches[3];
19 this.filename = matches[4];
20 this.signature = matches[5];
21 public_id_and_format = PreloadedFile.split_format(this.filename);
22 this.public_id = public_id_and_format[0];
23 this.format = public_id_and_format[1];
24 }
25
26 is_valid() {
27 var expected_signature;
28 expected_signature = utils.api_sign_request({
29 public_id: this.public_id,
30 version: this.version,
31 }, config().api_secret);
32 return this.signature === expected_signature;
33 }
34
35 static split_format(identifier) {
36 var format, last_dot, public_id;
37 last_dot = identifier.lastIndexOf(".");
38 if (last_dot === -1) {
39 return [identifier, null];
40 }
41 public_id = identifier.substr(0, last_dot);
42 format = identifier.substr(last_dot + 1);
43 return [public_id, format];
44 }
45
46 identifier() {
47 return `v${this.version}/${this.filename}`;
48 }
49
50 toString() {
51 return `${this.resource_type}/${this.type}/v${this.version}/${this.filename}#${this.signature}`;
52 }
53
54 toJSON() {
55 var result = {};
56 Object.getOwnPropertyNames(this).forEach((key) => {
57 let val = this[key];
58 if (typeof val !== 'function') {
59 result[key] = val;
60 }
61 });
62 return result;
63 }
64}
65
66module.exports = PreloadedFile;