]> git.0d.be Git - django-panik-nonstop.git/blobdiff - nonstop/models.py
add model for recurring streams
[django-panik-nonstop.git] / nonstop / models.py
index e704786fdc38be5cce85982c806f6b2dc82147d1..e29f57146c254c4c5e89627d2ef9bb5c3b5ac478 100644 (file)
@@ -1,9 +1,30 @@
+import datetime
+import os
+
+import mutagen
+
+from django.conf import settings
 from django.core.urlresolvers import reverse
 from django.db import models
+from django.db.models.signals import post_delete
+from django.dispatch import receiver
+from django.utils.timezone import now
 from django.utils.translation import ugettext_lazy as _
 
 REMOTE_BASE_PATH = '/srv/soma/nonstop/'
+LOCAL_BASE_PATH = '/media/nonstop/'
 
+TRANCHE_SLUG_DIR_MAPPING = {
+    'acouphene': 'Acouphene',
+    'biodiversite': 'Biodiversite',
+    'l-heure-de-pointe': 'Heure_de_pointe',
+    'hop-bop-co': 'Hop_Bop_and_co',
+    'la-panique': 'la_panique',
+    'le-mange-disque': 'Mange_Disque',
+    'matin-tranquille': 'Matins_tranquilles',
+    'reveries': 'Reveries',
+    'up-beat-tempo': 'Up_Beat_Tempo',
+}
 
 class Artist(models.Model):
     name = models.CharField(_('Name'), max_length=255)
@@ -11,6 +32,9 @@ class Artist(models.Model):
     class Meta:
         ordering = ['name']
 
+    def __str__(self):
+        return self.name
+
     def get_absolute_url(self):
         return reverse('artist-view', kwargs={'pk': self.id})
 
@@ -40,6 +64,17 @@ class Track(models.Model):
     cfwb = models.BooleanField('CFWB', default=False)
     nonstop_zones = models.ManyToManyField('emissions.Nonstop', blank=True)
 
+    creation_timestamp = models.DateTimeField(auto_now_add=True, null=True)
+    added_to_nonstop_timestamp = models.DateTimeField(null=True)
+    uploader = models.ForeignKey(settings.AUTH_USER_MODEL, null=True)
+    duration = models.DurationField(_('Duration'), null=True)
+
+    class Meta:
+        ordering = ['creation_timestamp']
+
+    def __str__(self):
+        return 'Track %s (%s)' % (self.title, self.artist or 'unknown')
+
     def get_absolute_url(self):
         return reverse('track-view', kwargs={'pk': self.id})
 
@@ -47,9 +82,56 @@ class Track(models.Model):
         return SomaLogLine.objects.filter(filepath__track=self
                 ).exclude(on_air=False).order_by('-play_timestamp')
 
+    def file_path(self):
+        nfile = None
+        for nfile in self.nonstopfile_set.all().order_by('creation_timestamp'):
+            if os.path.exists(nfile.get_local_filepath()):
+                return nfile.get_local_filepath()
+        if nfile:
+           return nfile.get_local_filepath()
+        return None
+
+    def file_exists(self):
+        file_path = self.file_path()
+        if not file_path:
+            return False
+        try:
+            return os.path.exists(file_path)
+        except AttributeError:
+            return False
+
+    def sync_nonstop_zones(self):
+        current_zones = self.nonstop_zones.all()
+        if current_zones.count():
+            if not self.added_to_nonstop_timestamp:
+                self.added_to_nonstop_timestamp = now()
+                self.save()
+        else:
+            self.added_to_nonstop_timestamp = None
+            self.save()
+
+        if not self.file_exists():
+            return
+        nonstop_file = self.nonstopfile_set.order_by('creation_timestamp').last()
+        filename = nonstop_file.filename
+        from emissions.models import Nonstop
+
+        for zone in Nonstop.objects.all():
+            if not zone.slug in TRANCHE_SLUG_DIR_MAPPING:
+                continue
+            zone_dir = TRANCHE_SLUG_DIR_MAPPING[zone.slug]
+            zone_path = os.path.join(LOCAL_BASE_PATH, 'Tranches', zone_dir, filename)
+            if zone in current_zones:
+                if not os.path.exists(zone_path):
+                    os.symlink(os.path.join('..', '..', nonstop_file.short), zone_path)
+            else:
+                if os.path.exists(zone_path):
+                    os.unlink(zone_path)
+
 
 class NonstopFile(models.Model):
     filepath = models.CharField(_('Filepath'), max_length=255)
+    filename = models.CharField(_('Filename'), max_length=255, null=True)
     creation_timestamp = models.DateTimeField(auto_now_add=True, null=True)
     track = models.ForeignKey(Track, null=True)
 
@@ -57,6 +139,15 @@ class NonstopFile(models.Model):
     def short(self):
         return self.filepath[len(REMOTE_BASE_PATH):]
 
+    def set_track_filepath(self, filepath):
+        self.filepath = os.path.join(REMOTE_BASE_PATH, 'tracks', filepath)
+        self.filename = os.path.basename(filepath)
+
+    def get_local_filepath(self):
+        if not self.short:
+            return None
+        return os.path.join(LOCAL_BASE_PATH, self.short)
+
 
 class SomaLogLine(models.Model):
     class Meta:
@@ -67,3 +158,121 @@ class SomaLogLine(models.Model):
     filepath = models.ForeignKey(NonstopFile)
     play_timestamp = models.DateTimeField()
     on_air = models.NullBooleanField('On Air')
+
+
+class Jingle(models.Model):
+    class Meta:
+        verbose_name = _('Jingle')
+        verbose_name_plural = _('Jingles')
+        ordering = ['label']
+
+    label = models.CharField(_('Label'), max_length=100)
+    filepath = models.CharField(_('File Path'), max_length=255)
+    duration = models.DurationField(_('Duration'), null=True, blank=True)
+    default_for_initial_diffusions = models.BooleanField(_('Default for initial diffusions'), default=False)
+    default_for_reruns = models.BooleanField(_('Default for reruns'), default=False)
+    default_for_streams = models.BooleanField(_('Default for streams'), default=False)
+
+    def __str__(self):
+        return self.label
+
+    def save(self, **kwargs):
+        for attr in ('default_for_initial_diffusions', 'default_for_reruns', 'default_for_streams'):
+            if getattr(self, attr):
+                Jingle.objects.all().update(**{attr: False})
+        return super(Jingle, self).save(**kwargs)
+
+    @property
+    def title(self):
+        return self.label
+
+
+class Stream(models.Model):
+    class Meta:
+        verbose_name = _('Stream')
+        verbose_name_plural = _('Streams')
+        ordering = ['label']
+
+    label = models.CharField(_('Label'), max_length=100)
+    url = models.URLField(_('URL'), max_length=255)
+
+    def __str__(self):
+        return self.label
+
+
+class ScheduledDiffusion(models.Model):
+    class Meta:
+        verbose_name = _('Scheduled diffusion')
+        verbose_name_plural = _('Scheduled diffusions')
+
+    diffusion = models.ForeignKey('emissions.Diffusion', null=True, blank=True, on_delete=models.SET_NULL)
+    jingle = models.ForeignKey(Jingle, null=True, blank=True)
+    stream = models.ForeignKey(Stream, null=True, blank=True)
+    creation_timestamp = models.DateTimeField(auto_now_add=True, null=True)
+    added_to_nonstop_timestamp = models.DateTimeField(null=True)
+
+    def __str__(self):
+        return 'Diffusion of %s' % self.diffusion
+
+    @property
+    def datetime(self):
+        return self.diffusion.datetime
+
+    @property
+    def end_datetime(self):
+        if self.is_stream():
+            return self.diffusion.end_datetime
+        dt = self.diffusion.datetime
+        if self.jingle:
+            dt += self.jingle.duration
+        dt += datetime.timedelta(seconds=self.soundfile.duration)
+        return dt
+
+    @property
+    def soundfile(self):
+        return self.diffusion.episode.soundfile_set.filter(fragment=False).first()
+
+    @property
+    def duration(self):
+        return (self.end_datetime - self.datetime).seconds
+
+    @property
+    def episode(self):
+        return self.diffusion.episode
+
+    @property
+    def soma_id(self):
+        if self.is_stream():
+            return '[stream:%s]' % self.id
+        else:
+            return '[sound:%s]' % self.id
+
+    def is_stream(self):
+        return bool(self.stream_id)
+
+
+class NonstopZoneSettings(models.Model):
+    nonstop = models.ForeignKey('emissions.Nonstop', on_delete=models.CASCADE)
+    intro_jingle = models.ForeignKey(Jingle, blank=True, null=True, related_name='+')
+    jingles = models.ManyToManyField(Jingle, blank=True)
+
+    def __str__(self):
+        return str(self.nonstop)
+
+
+class RecurringStreamDiffusion(models.Model):
+    schedule = models.ForeignKey('emissions.Schedule', on_delete=models.CASCADE)
+    jingle = models.ForeignKey(Jingle, null=True, blank=True)
+    stream = models.ForeignKey(Stream)
+    is_active = models.BooleanField('Active', default=True)
+
+
+@receiver(post_delete)
+def remove_soundfile(sender, instance=None, **kwargs):
+    from emissions.models import SoundFile
+    if not issubclass(sender, SoundFile):
+        return
+    ScheduledDiffusion.objects.filter(
+            diffusion__episode_id=instance.episode_id,
+            stream_id=None).update(
+            diffusion=None)