user.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # User info wrapper object
  2. import logging
  3. class User(object):
  4. """
  5. Wrapper object around an entry in users.json. Behaves like a read-only dictionary if
  6. asked, but adds some useful logic to decouple the front end from the JSON structure.
  7. """
  8. _NAME_KEYS = ["display_name", "real_name"]
  9. _DEFAULT_IMAGE_KEY = "image_512"
  10. def __init__(self, raw_data):
  11. self._raw = raw_data
  12. def __getitem__(self, key):
  13. return self._raw[key]
  14. @property
  15. def display_name(self):
  16. """
  17. Find the most appropriate display name for a user: look for a "display_name", then
  18. a "real_name", and finally fall back to the always-present "name".
  19. """
  20. for k in self._NAME_KEYS:
  21. if self._raw.get(k):
  22. return self._raw[k]
  23. if "profile" in self._raw and self._raw["profile"].get(k):
  24. return self._raw["profile"][k]
  25. return self._raw["name"]
  26. @property
  27. def email(self):
  28. """
  29. Shortcut property for finding the e-mail address or bot URL.
  30. """
  31. if "profile" in self._raw:
  32. email = self._raw["profile"].get("email")
  33. elif "bot_url" in self._raw:
  34. email = self._raw["bot_url"]
  35. else:
  36. email = None
  37. if not email:
  38. logging.debug("No email found for %s", self._raw.get("name"))
  39. return email
  40. def image_url(self, pixel_size=None):
  41. """
  42. Get the URL for the user icon in the desired pixel size, if it exists. If no
  43. size is supplied, give the URL for the full-size image.
  44. """
  45. if "profile" not in self._raw:
  46. return
  47. profile = self._raw["profile"]
  48. if (pixel_size):
  49. img_key = "image_%s" % pixel_size
  50. if img_key in profile:
  51. return profile[img_key]
  52. return profile[self._DEFAULT_IMAGE_KEY]
  53. def deleted_user(id):
  54. """
  55. Create a User object for a deleted user.
  56. """
  57. deleted_user = {
  58. "id": id,
  59. "name": "deleted-" + id,
  60. "deleted": True,
  61. "is_bot": False,
  62. "is_app_user": False,
  63. }
  64. return User(deleted_user)