Function renaming and move into Song manager.

This commit is contained in:
Josh Washburne 2018-03-27 12:05:44 -04:00
parent 17a85b2197
commit 4a688bade0
2 changed files with 39 additions and 24 deletions

View file

@ -1,8 +1,17 @@
from django.db import models
from datetime import timedelta
from decimal import *
from django.db import models
from django.utils import timezone
from core.utils import get_setting
from .querysets import SongQuerySet
# Set decimal precision
getcontext().prec = 16
class SongManager(models.Manager):
"""
Custom object manager for filtering out common behaviors for a playlist.
@ -10,5 +19,31 @@ class SongManager(models.Manager):
def get_queryset(self):
return SongQuerySet(self.model, using=self._db)
def playlist_length(self):
"""
Total length of available songs in the playlist (in seconds).
"""
return self.available().aggregate(models.Sum('length'))['length__sum']
def wait_total(self):
"""
Default length in seconds before a song can be played again. This is
based on the replay ratio set in the application settings.
"""
wait = self.playlist_length() * Decimal(get_setting('replay_ratio'))
return wait.quantize(Decimal('.01'), rounding=ROUND_UP)
def datetime_from_wait(self):
"""
Datetime of now minus the default wait time for played songs.
"""
return timezone.now() - timedelta(seconds=float(self.wait_total()))
def available(self):
return self.get_queryset().songs().enabled().published()
def playable(self):
return self.available().filter(
models.Q(last_played__lt=self.datetime_from_wait()) |
models.Q(last_played__isnull=True)
)

View file

@ -5,40 +5,20 @@ from random import randint
from django.db import models
from django.utils import timezone
from core.utils import get_setting
from .models import Song
# Set decimal precision
getcontext().prec = 16
def get_playlist_length():
"""
Total length of available songs in the playlist (in seconds).
"""
songs = Song.music.available()
return songs.aggregate(models.Sum('length'))['length__sum']
def get_waittime():
"""
Default length in seconds before a song can be played again. This is based
on the replay ratio set in the application settings.
"""
waittime = get_playlist_length() * Decimal(get_setting('replay_ratio'))
return waittime.quantize(Decimal('.01'), rounding=ROUND_UP)
def get_next_allowed_play_time(song):
def get_wait_until_next_play(song):
"""
Length of time in seconds before a song can be played again.
"""
if not song.last_played:
return Decimal('0.00')
waittime = get_waittime()
nextplay = song.last_played + timedelta(seconds=float(waittime))
wait = song.music.wait_total()
nextplay = song.last_played + timedelta(seconds=float(wait))
current = (nextplay - timezone.now()).total_seconds()
return Decimal(current if current > 0 else 0).quantize(Decimal('.01'),