-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
101 lines (86 loc) · 2.76 KB
/
index.js
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
'use strict';
var PluginError = require('plugin-error');
var md5 = require("md5");
var queryString = require('querystring');
var request = require('request');
var through = require('through2');
const PLUGIN_NAME = 'gulp-onesky-post';
function makePostOptions(options) {
var timestamp = Math.floor(Date.now() / 1000);
var devHash = md5(timestamp + options.secretKey);
var apiAddress = "https://platform.api.onesky.io"
return {
method: 'POST',
url: apiAddress + '/1/projects/' + options.projectId + '/files?' + queryString.stringify({
api_key: options.publicKey,
timestamp: timestamp,
dev_hash: devHash
}),
formData: {
file: {
value: options.content,
options: {
filename: options.fileName
}
},
api_key: options.publicKey,
dev_hash: devHash,
file_format: options.format,
is_keeping_all_strings: options.keepStrings.toString(),
locale: options.locale,
timestamp: timestamp.toString(),
is_allow_translation_same_as_original: (options.allowSameAsOriginal || false).toString()
}
};
}
function sendRequest(requestData, callback) {
request(requestData, function (error, response, body) {
body = JSON.parse(body);
if (error) {
error = new PluginError(PLUGIN_NAME, 'error in sending request to one sky api');
}
else if (body.meta.status !== 201) {
error = new PluginError(PLUGIN_NAME, JSON.stringify(body.meta));
}
else {
body = body.meta.data;
}
callback(error,body);
});
}
function postFile(options) {
options = options || {};
if (!options.publicKey || !options.secretKey)
throw new PluginError(PLUGIN_NAME, 'please specify public and secret keys');
if (!options.projectId)
throw new PluginError(PLUGIN_NAME, 'please specify project id');
if(!options.fileName)
throw new PluginError(PLUGIN_NAME, 'please specify file name');
if(!options.format)
throw new PluginError(PLUGIN_NAME, 'please specify the format');
if (options.keepStrings !== true && options.keepStrings !== false)
options.keepStrings = true;
var stream = through.obj(function(file, enc, cb) {
if (file.isBuffer()) {
var fileContent = file.contents;
// if null is read
if (!fileContent) {
throw new PluginError(PLUGIN_NAME, 'file content is NULL');
}
fileContent = fileContent.toString(enc);
options.content = fileContent;
var requestData = makePostOptions(options);
sendRequest(requestData, function(error, body){
if(error) {
stream.emit("error", error);
}
stream.emit('end');
});
}
this.push(file);
cb();
});
return stream;
}
// Exporting the plugin main function
module.exports = postFile;