attachments.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from __future__ import unicode_literals
  2. import re
  3. from misago.threads.models import Attachment
  4. from .. import fetch_assoc, movedids
  5. ATTACHMENT_RE = re.compile(r'/attachment/(?P<hash>[a-z0-9]+)/')
  6. ATTACHMENT_THUMB_RE = re.compile(r'/attachment/thumb/(?P<hash>[a-z0-9]+)/')
  7. def update_attachments_urls(post):
  8. if '/attachment/' not in post:
  9. return post
  10. post = ATTACHMENT_THUMB_RE.sub(update_thumb_url, post)
  11. post = ATTACHMENT_RE.sub(update_full_url, post)
  12. return post
  13. def update_thumb_url(matchobj):
  14. hash = matchobj.group('hash')
  15. attachment = get_attachment_for_hash(hash)
  16. if attachment:
  17. return attachment.get_thumbnail_url()
  18. return matchobj.group(0)
  19. def update_full_url(matchobj):
  20. hash = matchobj.group('hash')
  21. attachment = get_attachment_for_hash(hash)
  22. if attachment:
  23. return attachment.get_absolute_url()
  24. return matchobj.group(0)
  25. def get_attachment_for_hash(hash):
  26. query = 'SELECT * FROM misago_attachment WHERE hash_id = %s'
  27. for attachment in fetch_assoc(query, [hash]):
  28. attachment_pk = movedids.get('attachment', attachment['id'])
  29. try:
  30. return Attachment.objects.get(pk=attachment_pk)
  31. except Attachment.DoesNotExist:
  32. return None
  33. return None