attachments.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from django.conf import settings
  2. from django.http import StreamingHttpResponse
  3. from django.template import RequestContext
  4. from misago.acl.exceptions import ACLError403, ACLError404
  5. from django.utils.translation import ugettext as _
  6. from misago.apps.errors import error403, error404
  7. from misago.models import Attachment
  8. from misago.readstrackers import ForumsTracker
  9. from misago.shortcuts import render_to_response
  10. def server(request, attachment, thumb=False):
  11. try:
  12. attachment = Attachment.objects.select_related('forum', 'thread', 'post', 'user').get(hash_id=attachment)
  13. request.acl.forums.allow_forum_view(attachment.forum)
  14. if attachment.thread:
  15. request.acl.threads.allow_thread_view(request.user, attachment.thread)
  16. if attachment.forum.special == 'private_threads':
  17. if not request.user.is_authenticated():
  18. raise ACLError404()
  19. can_see_thread_because_reported = (
  20. request.acl.privatethreads.is_mod() and attachment.thread.replies_reported)
  21. can_see_thread_because_participates = request.user in thread.participants
  22. if not (can_see_thread_because_reported or can_see_thread_because_participates):
  23. raise ACLError404()
  24. if attachment.post:
  25. request.acl.threads.allow_post_view(request.user, attachment.thread, attachment.post)
  26. request.acl.threads.allow_attachment_download(request.user, attachment.forum, attachment.post)
  27. return serve_file(attachment, thumb)
  28. except ACLError403:
  29. if attachment.is_image:
  30. return serve_403_image()
  31. return error403(request, _("You don't have permission to download this file."))
  32. except (Attachment.DoesNotExist, ACLError404):
  33. if thumb:
  34. return serve_404_image()
  35. return error404(request, _("Requested file could not be found."))
  36. def serve_file(attachment, thumb):
  37. if thumb:
  38. response = StreamingHttpResponse(open(attachment.thumb_path), content_type=attachment.content_type)
  39. else:
  40. response = StreamingHttpResponse(open(attachment.file_path), content_type=attachment.content_type)
  41. response['Cache-Control'] = 'no-cache'
  42. if not attachment.is_image:
  43. response['Content-Disposition'] = 'attachment;filename="%s"' % attachment.name
  44. return response
  45. def serve_403_image():
  46. response = StreamingHttpResponse(open('%s403.png' % settings.ATTACHMENTS_ROOT), content_type='image/png')
  47. response['Cache-Control'] = 'no-cache'
  48. return response
  49. def serve_404_image():
  50. response = StreamingHttpResponse(open('%s404.png' % settings.ATTACHMENTS_ROOT), content_type='image/png')
  51. response['Cache-Control'] = 'no-cache'
  52. return response