import base64
import mimetypes
import os

from django.conf import settings
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.cache import cache_control
from django.views.static import serve as django_serve

from database_files.models import File


@cache_control(max_age=86400)
def serve(request, name):
    """
    Retrieves the file from the database.
    """
    f = get_object_or_404(File, name=name)
    f.dump()
    mimetype = mimetypes.guess_type(name)[0] or 'application/octet-stream'
    response = HttpResponse(f.content, content_type=mimetype)
    response['Content-Length'] = f.size
    return response


def serve_mixed(request, *args, **kwargs):
    """
    First attempts to serve the file from the filesystem,
    then tries the database.
    """
    name = kwargs.get('name') or kwargs.get('path')
    document_root = kwargs.get('document_root')
    document_root = document_root or settings.MEDIA_ROOT
    try:
        # First attempt to serve from filesystem.
        return django_serve(request, name, document_root)
    except Http404:
        # Then try serving from database.
        return serve(request, name)

[((14, 1, 14, 29), 'django.views.decorators.cache.cache_control', 'cache_control', (), '', False, 'from django.views.decorators.cache import cache_control\n'), ((19, 8, 19, 42), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (), '', False, 'from django.shortcuts import get_object_or_404\n'), ((22, 15, 22, 61), 'django.http.HttpResponse', 'HttpResponse', (), '', False, 'from django.http import Http404, HttpResponse\n'), ((37, 15, 37, 57), 'django.views.static.serve', 'django_serve', ({(37, 28, 37, 35): 'request', (37, 37, 37, 41): 'name', (37, 43, 37, 56): 'document_root'}, {}), '(request, name, document_root)', True, 'from django.views.static import serve as django_serve\n'), ((21, 15, 21, 41), 'mimetypes.guess_type', 'mimetypes.guess_type', ({(21, 36, 21, 40): 'name'}, {}), '(name)', False, 'import mimetypes\n')]