def submit(request):
    # Is it a POST request, i.e is the form being submitted
    if request.method == 'POST':
        form = MediaForm(request.POST, request.FILES)

        # Run through any validation rules we have
        if form.is_valid():
            # Save the form data to the db
            form = form.save(commit=False)
            form.author = WinaUser.objects.get(id=request.user.id)

            # Is audio/video/image being submitted? If so we need to override content
            if form.type in ['audio', 'video', 'image']:
                form.content = get_serving_url(blob_key=request.FILES['file'].blob_key, file_name=request.FILES['file'].name)

            form.save()

            # Show a success message to the user
            messages.success(request, 'Submission recieved, thank you!')

            # Redirect them back to the media home page
            return redirect('/')

    form = form if request.method == 'POST' else MediaForm()

    return render(request, 'frontend/form.html', {
        'title': 'Media Submission',
        'form': form,
        'submit': 'Submit',
    })
def media(request):
    # Set up a dict to return
    response = {
        'error': None,
        'data': [],
    }

    # Is media being uploaded?
    if request.method == 'POST':
        try:
            # Authenticate the api user
            user = __authenticate_user(request)

            # Check the user has sufficient permissions to add media
            if user.has_perm('api.wina_add_media'):
                media_form = MediaForm(request.POST, request.FILES)

                # Check that the request passes validation
                if media_form.is_valid():
                    # Save the form data to the db
                    media_form = media_form.save(commit=False)
                    media_form.author = WinaUser.objects.get(id=user.id)

                    # Is audio/video/image being submitted? If so we need to override content with the uploaded file url
                    if media_form.type in ['audio', 'video', 'image']:
                        media_form.content = get_serving_url(blob_key=request.FILES['file'].blob_key, file_name=request.FILES['file'].name)

                    media_form.save()

                    # And finally append the newly created media object to the return response
                    response['data'].append(__formatMediaOrStory(media_form))

                else:
                    raise Exception('Invalid request')

            else:
                raise Exception('You do not have sufficient permisisons to do that')

        except Exception as e:
            response['message'] = str(e)

    # Else assume it's a GET method and get all media
    else:
        # Get all the media objects
        media = Media.objects.all()

        # Append all the media objects to the response object
        for object in media:
            response['data'].append(__formatMediaOrStory(object))

    # Return the response as json
    return HttpResponse(json.dumps(response), mimetype='application/json')
def media_add_or_edit(request, id=False):
    user = request.user

    # Is it a POST request, i.e is the form being submitted
    if request.method == "POST":
        # If the id is not false then we are editing, so we need to
        # get an instance of that media first
        if id is not False:
            media = Media.objects.get(id=id)

            # Check the has valid permissions to edit this media
            if user.has_perm("api.wina_edit_any_media") or (
                media.author.id == user.id and user.has_perm("api.wina_edit_own_media")
            ):
                media_form = MediaForm(request.POST, request.FILES, instance=media)

            else:
                raise PermissionDenied

        # Otherwise we can just pass the form data straight to the form, this is
        # a POST request for adding media
        else:
            # Check the user has valid permissions to add media
            if user.has_perm("api.wina_add_media"):
                media_form = MediaForm(request.POST, request.FILES)

            else:
                raise PermissionDenied

        # Run through any validation rules we have
        if media_form.is_valid():
            # Save the form data to the db
            media_form = media_form.save(commit=False)
            media_form.author = WinaUser.objects.get(id=request.user.id)

            # Is audio/video/image being submitted? If so we need to override content
            if media_form.type in ["audio", "video", "image"]:
                media_form.content = get_serving_url(
                    blob_key=request.FILES["file"].blob_key, file_name=request.FILES["file"].name
                )

            media_form.save()

            # Show a success message to the user
            message_suffix = "added!" if id is False else "edited"
            messages.success(request, "Media succesfully %s" % message_suffix)

            # Redirect them back to the media home page
            return redirect("media-home")

    # Were we passed the id? i.e are we editing an object, if so get it to pass to the template
    if id is not False:
        media = Media.objects.get(id=id)

        # Check the user has valid permissions to edit this media
        if user.has_perm("api.wina_edit_any_media") or (
            media.author.id == user.id and user.has_perm("api.wina_edit_own_media")
        ):
            media_form = media_form if request.method == "POST" else MediaForm(instance=media)
            template_data = {"form": media_form, "title": media.title}

        else:
            raise PermissionDenied

    # If not we must be adding new media as we have no id in the URL
    else:
        # Check the user has valid permissions to add a media
        if user.has_perm("api.wina_add_media"):
            media_form = media_form if request.method == "POST" else MediaForm()
            template_data = {"form": media_form, "title": "Add Media"}

        else:
            raise PermissionDenied

    return render(request, "cms/form.html", template_data)