Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow users to play mp3 files but don't expose them directly on the web

I want to store some mp3s in a folder which is not public, can't be directly accessed through the web and allow users to hear/download the songs with a browser only if they are logged in.

How can I do that?

I do my web development with Django, but if I know how it works is enough.

like image 701
Victor Avatar asked Dec 13 '22 21:12

Victor


2 Answers

You first need to setup authentication. The django tutorials thoroughly explore this.

You don't' link the mp3's directly, You link to a django script that checks the auth, then reads the mp3 and serves it to the client with a mp3 content type header.

http://yourserver.com/listen?file=Fat+Boys+Greatest+Hits

like image 149
Byron Whitlock Avatar answered Feb 16 '23 00:02

Byron Whitlock


I assume you use django. Then you can try something like this:

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse


@login_required
def listen(request, file_name):
    # note that MP3_STORAGE should not be in MEDIA_ROOT
    file = open("%smp3/%s" % (settings.MP3_STORAGE, file_name))
    response = HttpResponse(file.read(), mimetype="audio/mpeg")
    return response

Note that you will get dramatic speed decrease. Using generator to read file in blocks may help to save memory.

Lazy Method for Reading Big File in Python?

like image 28
Dmitry Gladkov Avatar answered Feb 16 '23 02:02

Dmitry Gladkov