MongoDB Media Server

Code available on GitHub

The included code is a show case, not a full media server! This is also a somewhat older project, if I missed something feel free to add an issue on GitHub.

So I’ve been going through playground folder on my hard disk. That’s the place I store all my projects I did for showcasing or simply to play around with new things.
And I found a little something I did about a year ago for the Senacor DevCon. It’s a small media server project based on Spring Data and MongoDB.

I am releasing it because I think it’s a great example for the simplicity of Spring Data combined with SpringMVC.
NOTE: There’s a a python script included to import your MP3s into the database. You will need Mutagen on your machine to use it.

All the interesting things happen in the LibraryRessource. Let’s take a look at the most important parts.
The things we nee to work with are the SongRepository (a simple Spring Data repository), MongoTemplate (here be CRUD) and the GridFsTemplate, which is required for documents >16 MB (see GridFS).

public class LibraryRessource {

    private MongoTemplate mongoTemplate;

    private GridFsTemplate gridFsTemplate;

    private SongRepository songRepository;

Most of the @RequestMapping-annotated classes should be self explaining so I will foxus on the “tricky” ones.
getSongs(..)_ is responsible for assembling the Song-JSON documents which contain a link to the GridFS-file to start streaming. To be able to assemble I have to git hold of the MD5-checksum to reference it.

    @RequestMapping(value = "/library/songs", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody Songs getSongs(HttpServletRequest request) {
        Songs songs = new Songs();
        for (Song song: songRepository.findAll()) {
            GridFSDBFile file = gridFsTemplate.findOne(query(where("_id").is(song.getFileId())));
            String requestBase = request.getRequestURL().toString().split("song")[0];
            song.setFileHref(requestBase + "files/" + file.getMD5());
        return songs;

The actual streaming is done in getFile(..). Thanks to the fluent-API of GridFsTemplate it turned out that the trickiest part of my application could be done in a single line of code. The only thing to be aware of is that getting hold of the HttpServletResponse used by your request is by adding it to the method signature.

    @RequestMapping(value = "/library/files/{md5}", method = RequestMethod.GET)
    public void getFile(HttpServletResponse response, @PathVariable("md5") String md5) throws IOException {

The generated URLs can be accessed using VLC.


About codepitbull
A nerd, a geek, a software developer. Oh, and married ;)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: