attachments.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. if attachment.forum:
  14. request.acl.forums.allow_forum_view(attachment.forum)
  15. if attachment.thread:
  16. request.acl.threads.allow_thread_view(request.user, attachment.thread)
  17. if attachment.forum.special == 'private_threads':
  18. if not request.user.is_authenticated():
  19. raise ACLError404()
  20. can_see_thread_because_reported = (
  21. request.acl.private_threads.is_mod() and attachment.thread.replies_reported)
  22. can_see_thread_because_participates = request.user in attachment.thread.participants.all()
  23. if not (can_see_thread_because_reported or can_see_thread_because_participates):
  24. raise ACLError404()
  25. if attachment.post:
  26. request.acl.threads.allow_post_view(request.user, attachment.thread, attachment.post)
  27. request.acl.threads.allow_attachment_download(request.user, attachment.forum, attachment.post)
  28. return serve_file(attachment, thumb)
  29. except ACLError403:
  30. if attachment.is_image:
  31. return serve_403_image()
  32. return error403(request, _("You don't have permission to download this file."))
  33. except (Attachment.DoesNotExist, ACLError404):
  34. if thumb:
  35. return serve_404_image()
  36. return error404(request, _("Requested file could not be found."))
  37. def serve_file(attachment, thumb):
  38. if thumb:
  39. response = StreamingHttpResponse(open(attachment.thumb_path), content_type=attachment.content_type)
  40. else:
  41. response = StreamingHttpResponse(open(attachment.file_path), content_type=attachment.content_type)
  42. response['Cache-Control'] = 'no-cache'
  43. if not attachment.is_image:
  44. response['Content-Disposition'] = 'attachment;filename="%s"' % attachment.name
  45. return response
  46. def serve_403_image():
  47. response = StreamingHttpResponse(open('%s403.png' % settings.ATTACHMENTS_ROOT), content_type='image/png')
  48. response['Cache-Control'] = 'no-cache'
  49. return response
  50. def serve_404_image():
  51. response = StreamingHttpResponse(open('%s404.png' % settings.ATTACHMENTS_ROOT), content_type='image/png')
  52. response['Cache-Control'] = 'no-cache'
  53. return response