models.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import os
  2. import datetime
  3. import config
  4. from groupie.utils import get_path, json
  5. class Base(object):
  6. def __init__(self, data):
  7. self.data = data
  8. def __getattr__(self, key):
  9. try:
  10. return self.data[key]
  11. except KeyError:
  12. return super(Base, self).__getattr__(key)
  13. @property
  14. def model(self):
  15. return self.__class__.__name__
  16. class GroupNotFound(Exception):
  17. def __init__(self, slug):
  18. super(GroupNotFound, self).__init__("Group not found: %s" % slug)
  19. self.slug = slug
  20. class Group(Base):
  21. @property
  22. def link(self):
  23. return 'https://www.facebook.com/groups/%s/' % self.id
  24. @staticmethod
  25. def get(slug):
  26. path = get_path(slug, 'info')
  27. if not os.path.exists(path):
  28. raise GroupNotFound(slug)
  29. with open(get_path(slug, 'info')) as fp:
  30. group = Group(json.load(fp))
  31. group.slug = slug
  32. return group
  33. def get_path(self, *c):
  34. return get_path(self.slug, *c)
  35. class Post(Base):
  36. @property
  37. def comments(self):
  38. for data in self.data.get('comments', {}).get('data', []):
  39. comment = Comment(data)
  40. comment.post = self
  41. yield comment
  42. @property
  43. def time(self):
  44. return datetime.datetime.strptime(self.created_time, '%Y-%m-%dT%H:%M:%S+0000')
  45. @property
  46. def like_count(self):
  47. return self.data.get('likes', {}).get('count', 0)
  48. @property
  49. def comment_count(self):
  50. return self.data.get('comments', {}).get('count', 0)
  51. @property
  52. def original_link(self):
  53. return 'https://www.facebook.com/groups/%s/posts/%s' % (self.group.id, self.id.split('_')[-1])
  54. class Comment(Base):
  55. @property
  56. def link(self):
  57. '''Generate a permalink to the comment. UNDOCUMENTED'''
  58. return 'https://www.facebook.com/groups/%s/permalink/%s/?comment_id=%s' % (self.post.group.id, self.post.id.split('_')[-1], self.id.split('_')[-1])