trackers.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from datetime import timedelta
  2. from django.conf import settings
  3. from django.utils import timezone
  4. from misago.readstracker.models import Record
  5. from misago.threads.models import Thread
  6. class ForumsTracker(object):
  7. def __init__(self, user):
  8. self.user = user
  9. self.cutoff = timezone.now() - timedelta(days=settings.READS_TRACKER_LENGTH)
  10. self.forums = {}
  11. if self.user.is_authenticated() and settings.READS_TRACKER_LENGTH > 0:
  12. for forum in Record.objects.filter(user=user).filter(updated__gte=self.cutoff).values('id', 'forum_id', 'updated', 'cleared'):
  13. self.forums[forum['forum_id']] = forum
  14. print self.forums
  15. def is_read(self, forum):
  16. if not self.user.is_authenticated() or not forum.last_thread_date:
  17. return True
  18. try:
  19. return forum.last_thread_date <= self.cutoff or forum.last_thread_date <= self.forums[forum.pk]['cleared']
  20. except KeyError:
  21. return False
  22. class ThreadsTracker(object):
  23. def __init__(self, user, forum):
  24. self.need_sync = False
  25. self.need_update = False
  26. self.user = user
  27. self.forum = forum
  28. self.cutoff = timezone.now() - timedelta(days=settings.READS_TRACKER_LENGTH)
  29. try:
  30. self.record = Record.objects.get(user=user,forum=forum)
  31. except Record.DoesNotExist:
  32. self.record = Record(user=user,forum=forum,cleared=self.cutoff)
  33. self.threads = self.record.get_threads()
  34. def is_read(self, thread):
  35. if not self.user.is_authenticated():
  36. return True
  37. try:
  38. if thread.last <= self.cutoff and thread.pk in self.threads:
  39. del self.threads[thread.pk]
  40. self.need_update = True
  41. return thread.last <= self.cutoff or thread.last <= self.threads[thread.pk]
  42. except KeyError:
  43. return False
  44. def set_read(self, thread, post):
  45. if self.user.is_authenticated():
  46. try:
  47. if self.threads[thread.pk] < post.date:
  48. self.threads[thread.pk] = post.date
  49. self.need_sync = True
  50. except KeyError:
  51. self.threads[thread.pk] = post.date
  52. self.need_sync = True
  53. def sync(self):
  54. now = timezone.now()
  55. if self.need_sync:
  56. unread_threads = 0
  57. for thread in Thread.objects.filter(last__gte=self.record.cleared).all():
  58. if not self.is_read(thread):
  59. unread_threads += 1
  60. if not unread_threads:
  61. self.record.cleared = now
  62. if self.need_sync or self.need_update:
  63. self.record.updated = now
  64. self.record.set_threads(self.threads)
  65. self.record.save(force_update=self.record.pk)