exports.getKey = function(platform, id, success, fail) {
doCall("keys/"+platform +"/"+id, function(res) {
if(res.error && res.error.length && fail) fail(res.error);
else success(res);
},function(e) {
if(fail) fail(e);
});
}
function getConfig(path) {
return {
auth: username + ":" + password,
host:"build.phonegap.com",
port:"443",
path:"/api/v1/"+path
}
}
//I handle doing the config get, http, string contact, etc
function doCall(path, success, fail) {
var options = getConfig(path);
var req = http.get(options, function(res) {
var resultString = "";
res.on("data", function(c) {
resultString+=c;
});
res.on("end",function() {
var result = JSON.parse(resultString);
success(result);
});
}).on("error", function(e) {
if(fail) fail(e);
});
}
//CREDIT:
//Note that I modified his code quite a bit
//For file uploads
function EncodeFieldPart(boundary,name,value) {
var return_part = "--" + boundary + "\r\n";
return_part += "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n";
return_part += value + "\r\n";
return return_part;
}
function EncodeFilePart(boundary,type,name,filename) {
var return_part = "--" + boundary + "\r\n";
return_part += "Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + filename + "\"\r\n";
return_part += "Content-Type: " + type + "\r\n\r\n";
return return_part;
}
//I expect the config options, the JSON data string, and file path
function PreparePost(httpOptions,data,file,success) {
var boundary = Math.random();
var post_data = [];
post_data.push(new Buffer(EncodeFieldPart(boundary, 'data', data), 'ascii'));
post_data.push(new Buffer(EncodeFilePart(boundary, 'text/plain', 'file', path.basename(file)), 'ascii'));
var contents = fs.readFileSync(file, "ascii");
post_data.push(new Buffer(contents, "utf8"));
post_data.push(new Buffer("\r\n--" + boundary + "--"), 'ascii');
MakePost(httpOptions,post_data, boundary,success);
}
function MakePost(httpOptions,post_data, boundary,success) {
var length = 0;
for(var i = 0; i < post_data.length; i++) {
length += post_data[i].length;
}
httpOptions.headers = {
'Content-Type' : 'multipart/form-data; boundary=' + boundary,
'Content-Length' : length
};
var post_request = http.request(httpOptions, function(response){
response.setEncoding('utf8');
var res="";
response.on('data', function(chunk){
res+=chunk;
});
response.on('end',function() {
success(JSON.parse(res));
});
});
for (var i = 0; i < post_data.length; i++) {
post_request.write(post_data[i]);
}
post_request.end();
}