import json

from django.http import HttpResponse, Http404, FileResponse
from django.template import loader, RequestContext
from django.contrib.auth.decorators import login_required
from .models import *
from django.conf import settings

def get_file_from_message(request, msg_id, file_name):
    from django.http import FileResponse

    try:

        msg = Message.objects.get(id=msg_id)

        if request.user not in (msg.sender, msg.receiver):
            raise Http404

        for file in msg.files:
            if file['file_name'] == file_name:
                f = open(f'chat_file_storage/{msg.id}/{file["file_name"]}', 'rb')

                return FileResponse(f)

    except Exception as e:
        raise Http404
