Added uploadAvatar method

This commit is contained in:
Alexander Corn 2015-08-12 19:32:16 -04:00
parent 115f13f686
commit 22f388e110

View File

@ -1,6 +1,7 @@
var SteamCommunity = require('../index.js');
var SteamID = require('steamid');
var Cheerio = require('cheerio');
var fs = require('fs');
SteamCommunity.PrivacyState = {
"Private": 1,
@ -211,3 +212,152 @@ SteamCommunity.prototype.profileSettings = function(settings, callback) {
});
});
};
SteamCommunity.prototype.uploadAvatar = function(image, format, callback) {
if(typeof format === 'function') {
callback = format;
format = null;
}
var self = this;
if(image instanceof Buffer) {
doUpload(image);
} else if(image.match(/^https?:\/\//)) {
this.request.get({
"uri": image,
"encoding": null
}, function(err, response, body) {
if(err || response.statusCode != 200) {
if(callback) {
callback(err ? new Error(err.message + " downloading image") : new Error("HTTP error " + response.statusCode + " downloading image"));
}
return;
}
if(!format) {
format = response.headers['content-type'];
}
doUpload(body);
})
} else {
if(!format) {
format = image.match(/\.([^\.]+)$/);
if(format) {
format = format[1];
}
}
fs.readFile(image, function(err, file) {
if(err) {
if(callback) {
callback(err);
}
return;
}
doUpload(file);
})
}
function doUpload(buffer) {
if(!format) {
if(callback) {
callback(new Error("Unknown image format"));
}
return;
}
if(format.match(/^image\//)) {
format = format.substring(6);
}
var filename = '';
var contentType = '';
switch(format.toLowerCase()) {
case 'jpg':
case 'jpeg':
filename = 'avatar.jpg';
contentType = 'image/jpeg';
break;
case 'png':
filename = 'avatar.png';
contentType = 'image/png';
break;
case 'gif':
filename = 'avatar.gif';
contentType = 'image/gif';
break;
default:
if(callback) {
callback(new Error("Unknown or invalid image format"));
}
return;
}
self.request.post({
"uri": "https://steamcommunity.com/actions/FileUploader",
"formData": {
"MAX_FILE_SIZE": buffer.length,
"type": "player_avatar_image",
"sId": self.steamID.getSteamID64(),
"sessionid": self.getSessionID(),
"doSub": 1,
"json": 1,
"avatar": {
"value": buffer,
"options": {
"filename": filename,
"contentType": contentType
}
}
},
"json": true
}, function(err, response, body) {
if(err) {
if(callback) {
callback(err);
}
return;
}
if(body && !body.success && body.message) {
if(callback) {
callback(new Error(body.message));
}
return;
}
if(response.statusCode != 200) {
if(callback) {
callback(new Error("HTTP error " + response.statusCode));
}
return;
}
if(!body || !body.success) {
if(callback) {
callback(new Error("Malformed response"));
}
return;
}
if(callback) {
callback(null, body.images.full);
}
});
}
};