helpers.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 (user has no skin)
  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 || null;
  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. // callback is a function with 3 parameters:
  29. // error, status, image buffer
  30. // image is the user's face+helm when helm is true, or the face otherwise
  31. //
  32. // the status gives information about how the image was received
  33. // -1: error
  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, helm, size, callback) {
  38. var facepath = config.faces_dir + uuid + ".png";
  39. var helmpath = config.helms_dir + uuid + ".png";
  40. var filepath = helm ? helmpath : facepath;
  41. if (fs.existsSync(filepath)) {
  42. // file found on disk
  43. skins.resize_img(filepath, size, function(err, result) {
  44. callback(err, 1, result);
  45. });
  46. } else {
  47. // download skin
  48. networking.get_profile(uuid, function(err, profile) {
  49. if (err) {
  50. callback(err, -1, profile);
  51. return;
  52. }
  53. var skinurl = exp.skin_url(profile);
  54. if (skinurl) {
  55. networking.skin_file(skinurl, facepath, helmpath, function(err) {
  56. if (err) {
  57. callback(err, -1, null);
  58. } else {
  59. console.log('got skin');
  60. skins.resize_img(filepath, size, function(err, result) {
  61. if (err) {
  62. callback(err, -1, null);
  63. } else {
  64. callback(null, 2, result);
  65. }
  66. });
  67. }
  68. });
  69. } else {
  70. // profile found, but has no skin
  71. callback(null, 3, null);
  72. }
  73. });
  74. }
  75. };
  76. module.exports = exp;