UNPKG

1.86 kBJavaScriptView Raw
1var PRELOADED_CLOUDINARY_PATH, PreloadedFile, config, utils;
2
3utils = require("./utils");
4
5config = require("./config");
6
7PRELOADED_CLOUDINARY_PATH = /^([^\/]+)\/([^\/]+)\/v(\d+)\/([^#]+)#([^\/]+)$/;
8
9PreloadedFile = class 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 = this.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, public_id;
28 public_id = this.resource_type === "raw" ? this.filename : this.public_id;
29 expected_signature = utils.api_sign_request({
30 public_id: this.public_id,
31 version: this.version
32 }, config().api_secret);
33 return this.signature === expected_signature;
34 }
35
36 split_format(identifier) {
37 var format, last_dot, public_id;
38 last_dot = identifier.lastIndexOf(".");
39 if (last_dot === -1) {
40 return [identifier, null];
41 }
42 public_id = identifier.substr(0, last_dot);
43 format = identifier.substr(last_dot + 1);
44 return [public_id, format];
45 }
46
47 identifier() {
48 return "v" + this.version + "/" + this.filename;
49 }
50
51 toString() {
52 return this.resource_type + "/" + this.type + "/v" + this.version + "/" + this.filename + "#" + this.signature;
53 }
54
55 toJSON() {
56 var key, ref, result, val;
57 result = {};
58 ref = this;
59 for (key in ref) {
60 val = ref[key];
61 if (typeof val !== 'function') {
62 result[key] = val;
63 }
64 }
65 return result;
66 }
67
68};
69
70module.exports = PreloadedFile;