Exemplo n.º 1
0
def stream_html5(request, uuid):

    media = get_object_or_404(Media, uuid=uuid)

    stream_permission = False

    if request.user and request.user.has_perm('alibrary.play_media'):
        stream_permission = True

    # check if unrestricted license
    #if not stream_permission:
    #    if media.license and media.license.restricted == False:
    #        stream_permission = True

    if not stream_permission:
        log.warning('unauthorized attempt by "%s" to download: %s - "%s"' %
                    (request.user.username if request.user else 'unknown',
                     media.pk, media.name))
        raise PermissionDenied

    try:
        from atracker.util import create_event
        create_event(request.user, media, None, 'stream')
    except:
        pass

    media_file = media.get_cache_file('mp3', 'base')

    if not media_file:
        return HttpResponseBadRequest('unable to get cache file')

    return sendfile(request, media_file)
Exemplo n.º 2
0
def start_play(item, channel=None, user=None):
    log.debug('item: %s - channel: %s - user: %s' % (item, channel, user))

    # Set current values to cache
    cache.set('abcast_on_air_%s' % channel.pk, item, 30)

    # Broadcast to pushy clients
    pushy_custom('%son-air/' % channel.get_api_url())


    if item.release and not 'jingle' in item.release.name.lower():

        try:
            text = '%s by %s - %s' % (item.name, item.artist.name, item.release.name)
            set_stream_metadata(channel, text)
        except Exception as e:
            log.warning('unable to set stream metadata: {}'.format(e))

        try:
            set_tunein_metadata(channel, item)
        except Exception as e:
            log.warning('unable to set tunein metadata: {}'.format(e))

        try:
            set_radioplayer_metadata(item)
        except Exception as e:
            log.warning('unable to set radioplayer metadata: {}'.format(e))


    try:
        from atracker.util import create_event
        create_event(user, item, channel, 'playout')
    except Exception as e:
        log.warning('exception: %s' % e)
Exemplo n.º 3
0
def start_play(item, channel=None, user=None):
    log = logging.getLogger('abcast.util.notify.start_play')

    log.debug('item: %s' % item)
    log.debug('channel: %s' % channel)
    log.debug('user: %s' % user)

    """
    Set current values to cache
    """
    cache.set('abcast_on_air_%s' % channel.pk, item, 30)


    """
    Broadcast to pushy clients
    """
    from pushy.util import pushy_custom
    pushy_custom('%son-air/' % channel.get_api_url())

    """
    Update stream metadata
    """
    text = u'%s by %s - %s' % (item.name, item.artist.name, item.release.name)
    api = IcecastAPI()
    api.set_metadata(channel, text)

    try:
        from atracker.util import create_event
        user = None
        create_event(user, item, channel, 'playout')
    except Exception, e:
        log.warning('exception: %s' % e)
Exemplo n.º 4
0
    def get(self, request, *args, **kwargs):

        media_uuid = kwargs.get('media_uuid', None)
        quality = kwargs.get('quality', None)
        encoding = kwargs.get('encoding', None)
        media = get_object_or_404(Media, uuid=media_uuid)

        stream_permission = False

        if request.user and request.user.has_perm('alibrary.play_media'):
            stream_permission = True


        if not stream_permission:
            log.warning('unauthorized attempt by "%s" to download: %s - "%s"' % (request.user.username if request.user else 'unknown', media.pk, media.name))
            raise PermissionDenied

        format, format_created = Format.objects.get_or_create(media=media, quality=quality, encoding=encoding)

        # TODO: nasty hack to wait until file is ready
        i = 0
        while format.status in [Format.INIT, Format.PROCESSING]:
            log.debug('format not ready yet. sleep for a while')
            if i > 6:
                log.warning('format creation timeout')
                return HttpResponse(status=202)

            i += 1
            time.sleep(2)
            format.refresh_from_db()

        try:
            from atracker.util import create_event
            create_event(request.user, media, None, 'stream')
        except:
            pass

        # set access timestamp
        Format.objects.filter(pk=format.pk).update(accessed=timezone.now())


        data = open(format.path, "rb").read()
        #return HttpResponse(data, content_type='audio/mpeg')

        response = HttpResponse(data, content_type='audio/mpeg')
        response['Content-Length'] = format.filesize

        return response
Exemplo n.º 5
0
    def process_task(obj):

        from atracker.util import create_event

        process = Process()

        dbox = None
        # dbox = Synchronizer(obj.user)

        log = logging.getLogger('exporter.models.process_task')

        archive_dir = create_archive_dir(obj)
        archive_cache_dir = os.path.join(archive_dir, 'cache/')
        archive_path = os.path.join(archive_dir, 'archive') # .zip appended by 'make_archive'

        # clean cache and recreate
        shutil.rmtree(archive_cache_dir, True)
        os.makedirs(archive_cache_dir)

        log.debug('archive_dir: %s' % (archive_dir))
        log.debug('archive_cache_dir: %s' % (archive_cache_dir))
        log.debug('archive_path: %s' % (archive_path))

        """
        first collect respective items and store everything in a temporary directory
        (the archive_cache_dir)
        """

        try:


            for item in obj.export_items.all():

                log.debug('export ctype: %s | id: %s' % (item.content_type, item.object_id))

                # switching processing for different types

                """
                Releases
                """
                if item.content_type.name.lower() == 'release':

                    t_item = item.content_object

                    """
                    create item specific path
                    < Artist Name >/< Release Name >/...
                    """

                    # relative path, for any target
                    item_rel_dir = os.path.join(safe_name(t_item.get_artist_display()), safe_name(t_item.name))
                    item_cache_dir = os.path.join(archive_cache_dir, item_rel_dir)

                    os.makedirs(item_cache_dir)

                    # holder for playlist entries
                    playlist_items = []

                    # string format for filename
                    filename_format = '%s - %s - %s.%s'

                    for media in t_item.media_release.all():

                        log.debug('export item: %s | id: %s' % ( media.name, media.pk))

                        if obj.fileformat == 'mp3':

                            filename = filename_format % (media.tracknumber, media.name, media.artist.name, 'mp3')
                            filename = safe_name(filename)
                            #filepath = os.path.join(archive_cache_dir, filename)
                            filepath = os.path.join(item_cache_dir, filename)

                            shutil.copyfile(media.get_cache_file('mp3', 'base'), filepath)
                            try:
                                process.inject_metadata(filepath, media)
                            except Exception, e:
                                pass

                        # just dummy - not possible...
                        if obj.fileformat == 'flac':

                            filename = filename_format % (media.tracknumber, media.name, media.artist.name, 'mp3')
                            filename = safe_name(filename)
                            filepath = os.path.join(item_cache_dir, filename)

                            shutil.copyfile(media.get_cache_file('mp3', 'base'), filepath)
                            try:
                                process.inject_metadata(filepath, media)
                            except Exception, e:
                                pass

                        playlist_items.append({'filename': filename, 'item': media})

                        if dbox:
                            dbox.upload(filepath, os.path.join('Releases', item_rel_dir, filename))

                        create_event(obj.user, media, None, 'download')

                    if t_item.main_image:
                        try:
                            shutil.copyfile(t_item.main_image.path, os.path.join(item_cache_dir, 'cover.jpg'))
                        except Exception, e:
                            print e
                            pass


                            #archive_file.write(t_item.main_image.path, 'cover.jpg')

                    """
                    Add additional assets
                    REATME.TXT LICENSE.TXT etc
                    """
                    with open(os.path.join(item_cache_dir, 'README.TXT'), "w") as txt:
                        str = render_to_string('exporter/txt/README.TXT', {'object': t_item})
                        txt.write(str)

                    """
Exemplo n.º 6
0
                        # just dummy - not possible...
                        if obj.fileformat == 'flac':

                            filename = filename_format % (media.name, media.artist.name, 'mp3')
                            filename = safe_name(filename)
                            filepath = os.path.join(item_cache_dir, filename)

                            shutil.copyfile(media.get_cache_file('mp3', 'base'), filepath)
                            try:
                                process.inject_metadata(filepath, media)
                            except Exception, e:
                                pass

                            playlist_items.append({'filename': filename, 'item': media})

                        create_event(obj.user, media, None, 'download')

                    if t_item.release and t_item.release.main_image:
                        try:
                            shutil.copyfile(t_item.release.main_image.path, os.path.join(item_cache_dir, 'image.jpg'))
                        except Exception, e:
                            print e
                            pass


                            #archive_file.write(t_item.main_image.path, 'cover.jpg')

                    """
                    Add additional assets
                    REATME.TXT LICENSE.TXT etc
                    """
Exemplo n.º 7
0
    def process_task(obj):

        from atracker.util import create_event

        process = Process()

        log = logging.getLogger('exporter.models.process_task')

        archive_dir = create_archive_dir(obj)
        archive_cache_dir = os.path.join(archive_dir, 'cache/')
        archive_path = os.path.join(
            archive_dir, 'archive')  # .zip appended by 'make_archive'
        #archive_file = ZipFile(archive_path, "w")

        log.debug('archive_dir: %s' % (archive_dir))
        log.debug('archive_cache_dir: %s' % (archive_cache_dir))
        log.debug('archive_path: %s' % (archive_path))

        # do shizzle
        for item in obj.export_items.all():
            print
            print 'item: %s' % item.content_type
            print 'pk: %s' % item.object_id

            # maybe not too elegant.. switching processing for different types
            if item.content_type.name.lower() == 'release':

                t_item = item.content_object

                filename_format = '%s - %s - %s.%s'

                print 'GOT RELEAZE!'

                for media in t_item.media_release.all():
                    print 'Media: %s' % media.name

                    if obj.fileformat == 'mp3':

                        filename = filename_format % (media.tracknumber,
                                                      media.name,
                                                      media.artist.name, 'mp3')
                        filepath = os.path.join(archive_cache_dir, filename)

                        shutil.copyfile(media.get_cache_file('mp3', 'base'),
                                        filepath)
                        process.incect_metadata(filepath, media)

                    # just dummy - not possible...
                    if obj.fileformat == 'flac':

                        filename = filename_format % (media.tracknumber,
                                                      media.name,
                                                      media.artist.name, 'mp3')
                        filepath = os.path.join(archive_cache_dir, filename)

                        shutil.copyfile(media.get_cache_file('mp3', 'base'),
                                        filepath)
                        process.incect_metadata(filepath, media)

                    create_event(obj.user, media, None, 'download')

                if t_item.main_image:
                    pass
                    #archive_file.write(t_item.main_image.path, 'cover.jpg')

            print

        shutil.make_archive(archive_path, 'zip', archive_cache_dir)

        obj.file = DjangoFile(open(archive_path + '.zip'), u'archive.zip')
        obj.filesize = os.path.getsize(archive_path + '.zip')

        # get filesize
        obj.filename = generate_export_filename(obj.export_items)
        #obj.filename = 'asdasdas'

        # update status
        obj.status = 1
        obj.save()
Exemplo n.º 8
0
    def process_item(self, item):

        log.info('export ctype: %s | id: %s' % (item.content_type, item.object_id))

        media_set = None
        content_object = item.content_object
        image = None

        ct = item.content_type.name.lower()


        if ct == 'release':
            media_set = content_object.media_release.all()
            image = content_object.main_image
            if content_object.get_artist_display:
                item_rel_dir = os.path.join(
                    safe_name(content_object.get_artist_display()),
                    safe_name(content_object.name)
                )
            else:
                item_rel_dir = safe_name(content_object.get_artist_display())


        if ct == 'track':
            media_set = [content_object]
            if content_object.artist and content_object.release:
                item_rel_dir = os.path.join(
                    safe_name(content_object.artist.name),
                    safe_name(content_object.release.name)
                )
            elif content_object.artist:
                item_rel_dir = safe_name(content_object.artist.name)
            else:
                item_rel_dir = safe_name(content_object.name)


        if ct == 'playlist':
            media_set = []
            image = content_object.main_image
            for m in content_object.get_items():
                media_set.append(m.content_object)

            if content_object.user and content_object.user.get_full_name():
                item_rel_dir = '%s (%s)' % (
                    safe_name(content_object.name),
                    safe_name(content_object.user.get_full_name())
                )
            else:
                item_rel_dir = safe_name(content_object.name)


        item_cache_dir = os.path.join(
            self.archive_cache_dir,
            safe_name(item_rel_dir)
        )
        if not os.path.exists(item_cache_dir):
            os.makedirs(item_cache_dir)

        log.debug('%s tracks to export' % len(media_set))

        # process tracks
        for media in media_set:
            if self.process_media(media, item_cache_dir, item_rel_dir) and CREATE_EVENTS:
                create_event(self.instance.user, media, None, 'download')

        # process additional resources
        if image and os.path.isfile(image.path):
            try:
                shutil.copyfile(image.path, os.path.join(item_cache_dir, IMAGE_FILENAME))
            except Exception, e:
                print e
Exemplo n.º 9
0
    def process_item(self, item):

        log.info('export ctype: %s | id: %s' %
                 (item.content_type, item.object_id))

        media_set = None
        content_object = item.content_object
        image = None

        ct = item.content_type.name.lower()

        if ct == 'release':
            media_set = content_object.media_release.all()
            image = content_object.main_image
            if content_object.get_artist_display:
                item_rel_dir = os.path.join(
                    safe_filename(content_object.get_artist_display()),
                    safe_filename(content_object.name))
            else:
                item_rel_dir = safe_filename(
                    content_object.get_artist_display())

        if ct == 'track':
            media_set = [content_object]
            if content_object.artist and content_object.release:
                item_rel_dir = os.path.join(
                    safe_filename(content_object.artist.name),
                    safe_filename(content_object.release.name))
            elif content_object.artist:
                item_rel_dir = safe_filename(content_object.artist.name)
            else:
                item_rel_dir = safe_filename(content_object.name)

        if ct == 'playlist':
            media_set = []
            image = content_object.main_image
            for m in content_object.get_items():
                media_set.append(m.content_object)

            if content_object.user and content_object.user.get_full_name():
                item_rel_dir = '%s (%s)' % (
                    safe_filename(content_object.name),
                    safe_filename(content_object.user.get_full_name()))
            else:
                item_rel_dir = safe_filename(content_object.name)

        item_cache_dir = os.path.join(self.archive_cache_dir,
                                      safe_filename(item_rel_dir))
        if not os.path.exists(item_cache_dir):
            os.makedirs(item_cache_dir)

        log.debug('%s tracks to export' % len(media_set))

        # process tracks
        for media in media_set:
            if self.process_media(media, item_cache_dir,
                                  item_rel_dir) and CREATE_EVENTS:
                create_event(self.instance.user, media, None, 'download')

        # process additional resources
        if image and os.path.isfile(image.path):
            try:
                shutil.copyfile(image.path,
                                os.path.join(item_cache_dir, IMAGE_FILENAME))
            except Exception as e:
                log.warning('unable to copy image: {}'.format(image.path))

        if INCLUDE_README:
            self.process_readme(instance=content_object,
                                cache_dir=item_cache_dir)

        if INCLUDE_HTML_README:
            try:
                self.process_html_readme(instance=content_object,
                                         cache_dir=item_cache_dir)
            except:
                pass

        if INCLUDE_LICENSE:
            self.process_license(instance=content_object,
                                 cache_dir=item_cache_dir,
                                 file_list=self.file_list)

        if ct == 'playlist' and INCLUDE_PLAYLIST:
            self.process_playlist(instance=content_object,
                                  cache_dir=item_cache_dir,
                                  file_list=self.file_list)

        # include mixdown file in download
        # TODO: this is an experimental implementation!
        if ct == 'playlist' and self.user and self.user.profile.enable_alpha_features:
            if content_object.mixdown_file and os.path.exists(
                    content_object.mixdown_file.path):
                try:
                    shutil.copyfile(
                        content_object.mixdown_file.path,
                        os.path.join(
                            item_cache_dir,
                            content_object.mixdown_file.name.split('/')[-1]))
                    log.debug('include mixdown file for playlist')
                except Exception as e:
                    log.warning('unable to copy mixdown file: {}'.format(
                        content_object.mixdown_file.path))
            else:
                log.debug('mixdown file not available')

            self.process_playlist(instance=content_object,
                                  cache_dir=item_cache_dir,
                                  file_list=self.file_list)

        return None, None
Exemplo n.º 10
0
    def create_event_for_user(self, request, **kwargs):

        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)
        self.throttle_check(request)

        object_uuid = kwargs.get('object_uuid', None)

        content_type = kwargs.get('content_type', None)
        orig_ct = content_type
        action = kwargs.get('action', None)
        user_id = kwargs.get('user_id', None)
        if user_id:
            user_id = int(user_id)

        log.debug(
            'create_event_for_user - content_type: %s - object_uuid: %s - action: %s - user_id: %s'
            % (content_type, object_uuid, action, user_id))

        if isinstance(content_type, basestring) and '.' in content_type:
            app, modelname = content_type.split('.')
            content_type = ContentType.objects.get(app_label=app,
                                                   model__iexact=modelname)
        elif isinstance(content_type, basestring):
            content_type = ContentType.objects.get(id=int(content_type))
        else:
            raise ValueError(
                'content_type must a ct id or "app.modelname" string')

        if user_id:
            log.debug('creating event on _behalf_ of user with id: %s' %
                      user_id)

            if request.user.has_perm('atracker.track_for_user'):
                user = get_user_model().objects.get(pk=user_id)
                log.info('voting for user by id: %s' % user.username)
            else:
                log.warning('no permission for %s to vote in behalf of %s' %
                            (request.user, user_id))
                user = None

        elif request.user and request.user.is_authenticated():
            user = request.user
            log.info('creating event for user by request: %s' % user.username)

        else:
            log.debug('no authenticated user')
            user = None

        object = content_type.model_class().objects.get(uuid=object_uuid)

        if action:
            if not user:
                return HttpUnauthorized(
                    'No permission to update this resource.')

            create_event(user, object, None, action)

        bundle = {
            'object_id': object.id,
            'object_uuid': object.uuid,
            'ct': orig_ct,
            'action': action,
        }

        self.log_throttled_access(request)
        return self.create_response(request, bundle)
Exemplo n.º 11
0
    def create_event_for_user(self, request, **kwargs):

        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)
        self.throttle_check(request)

        object_uuid = kwargs.get('object_uuid', None)

        content_type = kwargs.get('content_type', None)
        orig_ct = content_type
        action = kwargs.get('action', None)
        user_id = kwargs.get('user_id', None)
        if user_id:
            user_id = int(user_id)

        log.debug('create_event_for_user - content_type: %s - object_uuid: %s - action: %s - user_id: %s' % (
            content_type, object_uuid, action, user_id
        ))

        if isinstance(content_type, basestring) and '.' in content_type:
            app, modelname = content_type.split('.')
            content_type = ContentType.objects.get(app_label=app, model__iexact=modelname)
        elif isinstance(content_type, basestring):
            content_type = ContentType.objects.get(id=int(content_type))
        else:
            raise ValueError('content_type must a ct id or "app.modelname" string')

        if user_id:
            log.debug('creating event on _behalf_ of user with id: %s' % user_id)

            if request.user.has_perm('atracker.track_for_user'):
                user = User.objects.get(pk=user_id)
                log.info('voting for user by id: %s' % user.username)
            else:
                log.warning('no permission for %s to vote in behalf of %s' % (request.user, user_id))
                user = None


        elif request.user and request.user.is_authenticated():
            user = request.user
            log.info('creating event for user by request: %s' % user.username)

        else:
            log.debug('no authenticated user')
            user = None

        object = content_type.model_class().objects.get(uuid=object_uuid)

        if action:
            if not user:
                return HttpUnauthorized('No permission to update this resource.')

            create_event(user, object, None, action)

        bundle = {
            'object_id': object.id,
            'object_uuid': object.uuid,
            'ct': orig_ct,
            'action': action,
        }

        self.log_throttled_access(request)
        return self.create_response(request, bundle)
Exemplo n.º 12
0
    def process_task(obj):
        
        from atracker.util import create_event
        
        process = Process()
        
        log = logging.getLogger('exporter.models.process_task')
        
        archive_dir = create_archive_dir(obj)
        archive_cache_dir = os.path.join(archive_dir, 'cache/')
        archive_path = os.path.join(archive_dir, 'archive') # .zip appended by 'make_archive'
        #archive_file = ZipFile(archive_path, "w")
        
        log.debug('archive_dir: %s' % (archive_dir))
        log.debug('archive_cache_dir: %s' % (archive_cache_dir))
        log.debug('archive_path: %s' % (archive_path))
        
        # do shizzle
        for item in obj.export_items.all():
            print
            print 'item: %s' % item.content_type
            print 'pk: %s' % item.object_id
            
            # maybe not too elegant.. switching processing for different types
            if item.content_type.name.lower() == 'release':
                
                t_item = item.content_object
                
                filename_format = '%s - %s - %s.%s'
                
                print 'GOT RELEAZE!'
                
                for media in t_item.media_release.all():
                    print 'Media: %s' % media.name
                
                    if obj.fileformat == 'mp3':
                
                        filename = filename_format % (media.tracknumber, media.name, media.artist.name, 'mp3')
                        filepath = os.path.join(archive_cache_dir, filename)
                        
                        shutil.copyfile(media.get_cache_file('mp3', 'base'), filepath)
                        process.incect_metadata(filepath, media)
                
                    # just dummy - not possible...
                    if obj.fileformat == 'flac':
                
                        filename = filename_format % (media.tracknumber, media.name, media.artist.name, 'mp3')
                        filepath = os.path.join(archive_cache_dir, filename)
                        
                        shutil.copyfile(media.get_cache_file('mp3', 'base'), filepath)
                        process.incect_metadata(filepath, media)
                        
                    create_event(obj.user, media, None, 'download')
                    
                if t_item.main_image:
                    pass
                    #archive_file.write(t_item.main_image.path, 'cover.jpg')
                    
                    
                
            
            print
            
        shutil.make_archive(archive_path, 'zip', archive_cache_dir)
            
        
        obj.file = DjangoFile(open(archive_path + '.zip'), u'archive.zip')
        obj.filesize = os.path.getsize(archive_path + '.zip')

            
        # get filesize
        obj.filename = generate_export_filename(obj.export_items)
        #obj.filename = 'asdasdas'
        
        # update status
        obj.status = 1;
        obj.save()
Exemplo n.º 13
0
    def get(self, request, *args, **kwargs):

        media_uuid = kwargs.get('media_uuid', None)
        quality = kwargs.get('quality', None)
        encoding = kwargs.get('encoding', None)
        media = get_object_or_404(Media, uuid=media_uuid)

        stream_permission = False

        # TODO: DISABLE DEFAULT PERMISSION!!!!!
        # stream_permission = True

        if request.user and request.user.has_perm('alibrary.play_media'):
            stream_permission = True

        if not stream_permission:
            log.warning('unauthorized attempt by "%s" to download: %s - "%s"' %
                        (request.user.username if request.user else 'unknown',
                         media.pk, media.name))
            raise PermissionDenied

        # request a default encoded version of the 'master'
        format = Format.objects.get_or_create_for_media(media=media,
                                                        quality=quality,
                                                        encoding=encoding,
                                                        wait=True)

        # set access timestamp
        Format.objects.filter(pk=format.pk).update(accessed=timezone.now())

        if NGINX_X_ACCEL_REDIRECT:

            x_path = '/protected/{}'.format(format.relative_path)

            # TODO: improve handling of initial / range
            requested_range = self.request.META.get('HTTP_RANGE', None)
            if requested_range:
                requested_range = requested_range.split('=')[1].split('-')

                log.debug(u'requested range %s' % (requested_range))
                if requested_range and requested_range[0] == '0':
                    try:
                        from atracker.util import create_event
                        create_event(request.user, media, None, 'stream')
                    except:
                        pass

                else:
                    log.debug(u'seek play')

            # serving through nginx
            response = HttpResponse(content_type='audio/mpeg')
            response['Content-Length'] = format.filesize
            response['X-Accel-Redirect'] = x_path
            return response

        else:
            # # original part - serving through django
            data = open(format.path, "rb").read()
            response = HttpResponse(data, content_type='audio/mpeg')
            response['Content-Length'] = format.filesize

            try:
                from atracker.util import create_event
                create_event(request.user, media, None, 'stream')
            except:
                pass

            return response
Exemplo n.º 14
0
    def get(self, request, *args, **kwargs):

        media_uuid = kwargs.get('media_uuid', None)
        quality = kwargs.get('quality', None)
        encoding = kwargs.get('encoding', None)
        media = get_object_or_404(Media, uuid=media_uuid)

        stream_permission = False


        # TODO: DISABLE DEFAULT PERMISSION!!!!!
        # stream_permission = True

        if request.user and request.user.has_perm('alibrary.play_media'):
            stream_permission = True


        if not stream_permission:
            log.warning('unauthorized attempt by "%s" to download: %s - "%s"' % (request.user.username if request.user else 'unknown', media.pk, media.name))
            raise PermissionDenied

        # request a default encoded version of the 'master'
        format = Format.objects.get_or_create_for_media(media=media, quality=quality, encoding=encoding, wait=True)

        # set access timestamp
        Format.objects.filter(pk=format.pk).update(accessed=timezone.now())

        if NGINX_X_ACCEL_REDIRECT:

            x_path = '/protected/{}'.format(format.relative_path)

            # TODO: improve handling of initial / range
            requested_range = self.request.META.get('HTTP_RANGE', None)
            if requested_range:
                requested_range = requested_range.split('=')[1].split('-')

                log.debug(u'requested range %s' % (requested_range))
                if requested_range and requested_range[0] == '0':
                    try:
                        from atracker.util import create_event
                        create_event(request.user, media, None, 'stream')
                    except:
                        pass

                else:
                    log.debug(u'seek play')


            # serving through nginx
            response = HttpResponse(content_type='audio/mpeg')
            response['Content-Length'] = format.filesize
            response['X-Accel-Redirect'] = x_path
            return response

        else:
            # # original part - serving through django
            data = open(format.path, "rb").read()
            response = HttpResponse(data, content_type='audio/mpeg')
            response['Content-Length'] = format.filesize

            try:
                from atracker.util import create_event
                create_event(request.user, media, None, 'stream')
            except:
                pass

            return response