helpers.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var networking = require('./networking');
  2. var config = require('./config');
  3. var skins = require('./skins');
  4. var fs = require('fs');
  5. var valid_uuid = /^[0-9a-f]{32}$/;
  6. var exp = {};
  7. // exracts the skin url of a +profile+ object
  8. // returns null when no url found
  9. exp.skin_url = function(profile) {
  10. var url = null;
  11. if (profile && profile.properties) {
  12. profile.properties.forEach(function(prop) {
  13. if (prop.name == 'textures') {
  14. var json = Buffer(prop.value, 'base64').toString();
  15. var props = JSON.parse(json);
  16. url = props && props.textures && props.textures.SKIN && props.textures.SKIN.url;
  17. }
  18. });
  19. }
  20. return url;
  21. };
  22. // returns true if the +uuid+ is a valid uuid
  23. // the uuid may be not exist, however
  24. exp.uuid_valid = function(uuid) {
  25. return valid_uuid.test(uuid);
  26. };
  27. // handles requests for +uuid+ images with +size+
  28. //
  29. // callback is a function with 3 parameters:
  30. // error, status, image buffer
  31. //
  32. // the status gives information about how the image was received
  33. // -1: profile requested, but it was not found
  34. // 1: found on disk
  35. // 2: profile requested/found, skin downloaded from mojang servers
  36. // 3: profile requested/found, but it has no skin
  37. exp.get_avatar = function(uuid, size, callback) {
  38. var filepath = config.skins_dir + uuid + ".png";
  39. if (fs.existsSync(filepath)) {
  40. skins.resize_img(filepath, size, function(result) {
  41. callback(null, 1, result);
  42. });
  43. } else {
  44. networking.get_profile(uuid, function(err, profile) {
  45. if (err) {
  46. callback(err, -1, profile);
  47. }
  48. var skinurl = exp.skin_url(profile);
  49. if (skinurl) {
  50. networking.skin_file(skinurl, filepath, function() {
  51. console.log('got skin');
  52. skins.resize_img(filepath, size, function(result) {
  53. callback(null, 2, result);
  54. });
  55. });
  56. } else {
  57. // profile found, but has no skin
  58. callback(null, 3, null);
  59. }
  60. });
  61. }
  62. };
  63. module.exports = exp;