attachments.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from __future__ import unicode_literals
  2. import re
  3. from misago.datamover import fetch_assoc, movedids
  4. from misago.threads.models import Attachment
  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. if attachment.thumbnail:
  18. return attachment.get_thumbnail_url()
  19. else:
  20. return attachment.get_absolute_url()
  21. return matchobj.group(0)
  22. def update_full_url(matchobj):
  23. hash = matchobj.group('hash')
  24. attachment = get_attachment_for_hash(hash)
  25. if attachment:
  26. return attachment.get_absolute_url()
  27. return matchobj.group(0)
  28. def get_attachment_for_hash(hash):
  29. query = 'SELECT * FROM misago_attachment WHERE hash_id = %s'
  30. for attachment in fetch_assoc(query, [hash]):
  31. attachment_pk = movedids.get('attachment', attachment['id'])
  32. try:
  33. return Attachment.objects.get(pk=attachment_pk)
  34. except Attachment.DoesNotExist:
  35. return None
  36. return None