def skip(self): try: current = Track.objects.get(now_playing=True, establishment=self.establishment) self.stop_track(current) qs = Track.objects.filter(now_playing=False, establishment=self.establishment ).exclude(id=current.id) except Track.DoesNotExist: current = None qs = Track.objects.filter(establishment=self.establishment, now_playing=False) # use current to prevent skip to the same song # get the first by vote if current is not None: track = Track.ordered_qs(establishment=self.establishment ).exclude(id=current.id).first() else: track = Track.ordered_qs(establishment=self.establishment ).first() # get random if not track: new_qs = qs.filter(played_on_random=False) if new_qs.exists(): qs = new_qs else: qs.update(played_on_random=False) # select a track at random last = qs.count() - 1 if last >= 0: index = randint(0, last) try: track = qs[index] except IndexError: # on the very unlikely event of selecting an index that # disappeared between the two queries we try selecting the # first one. track = qs.first() if track: with transaction.atomic(): # make sure we don't have a race condition and end up with # two tracks now_playing track.now_playing = True track.played_on_random = True track.save() assert Track.objects.filter(now_playing=True, establishment=self.establishment ).count() == 1 self.broadcast_track_changed(track) return track
def skip(self): try: current = Track.objects.get(now_playing=True, establishment=self.establishment) self.stop_track(current) qs = Track.objects.filter( now_playing=False, establishment=self.establishment).exclude(id=current.id) except Track.DoesNotExist: current = None qs = Track.objects.filter(establishment=self.establishment, now_playing=False) # use current to prevent skip to the same song # get the first by vote if current is not None: track = Track.ordered_qs(establishment=self.establishment).exclude( id=current.id).first() else: track = Track.ordered_qs(establishment=self.establishment).first() # get random if not track: new_qs = qs.filter(played_on_random=False) if new_qs.exists(): qs = new_qs else: qs.update(played_on_random=False) # select a track at random last = qs.count() - 1 if last >= 0: index = randint(0, last) try: track = qs[index] except IndexError: # on the very unlikely event of selecting an index that # disappeared between the two queries we try selecting the # first one. track = qs.first() if track: with transaction.atomic(): # make sure we don't have a race condition and end up with # two tracks now_playing track.now_playing = True track.played_on_random = True track.save() assert Track.objects.filter( now_playing=True, establishment=self.establishment).count() == 1 self.broadcast_track_changed(track) return track
def track_list_serialize(self): qs = Track.ordered_qs(establishment=self.establishment) PlayList = namedtuple('PlayList', ['tracks', 'now_playing']) return TrackListSerializer(PlayList(qs, self.get_now_playing()))