def schedule(request, visualization_id): visualization = get_object_or_404(Visualization, pk=visualization_id, account=request.user.account) schedule = Schedule(created_by=request.user, visualization=visualization, email=request.POST.get('email', request.user.email), frequency=request.POST.get('frequency', 'daily'), time=request.POST.get('time', 'morning'), show_sum=request.POST.get('totals', 'no') == 'sum',) schedule.save() for option in dict(request.POST).get('options[]', []): schedule_option = ScheduleOption(schedule=schedule, option=int(option)) schedule_option.save() return HttpResponse(schedule.id, 'application/json')
def create_schedule(request): start = int(request.POST.get('start')) start = datetime.datetime.fromtimestamp(start / 1000.0) emission_type = request.POST.get('type') programme_id = int(request.POST.get('programmeId')) programme = get_object_or_404(Programme, id=programme_id) schedule_board_id = int(request.POST.get('scheduleBoardId')) scheduleBoard = get_object_or_404(ScheduleBoard, id=schedule_board_id) schedule = Schedule(programme=programme, schedule_board=scheduleBoard, day=start.weekday(), start_hour=start.time(), type=emission_type) schedule.clean() schedule.save() Episode.rearrange_episodes(programme, datetime.datetime.now()) return {'scheduleId': schedule.id, 'backgroundColor':background_colours[schedule.type], 'textColor':text_colours[schedule.type], 'type':schedule.type}
def rearrange_episodes(cls, programme, after): # TODO: improve from apps.schedules.models import Schedule next_episodes = Episode.objects.filter(issue_date__gte=after) | Episode.objects.filter(issue_date__isnull=True) if programme: next_episodes = next_episodes.filter(programme=programme) next_episodes = next_episodes.order_by('programme', 'season', 'number_in_season').select_related('programme') dt = after current_programme = None for episode in next_episodes: if current_programme != episode.programme: # reset dt if programme change current_programme = episode.programme dt = after if dt: schedule, date = Schedule.get_next_date(programme=episode.programme, after=dt) episode.issue_date = date if date: dt = date + episode.runtime else: dt = None else: episode.issue_date = None episode.save()
def rearrange_episodes(cls, programme, after): # TODO: improve from apps.schedules.models import Schedule next_episodes = Episode.objects.filter( issue_date__gte=after) | Episode.objects.filter( issue_date__isnull=True) if programme: next_episodes = next_episodes.filter(programme=programme) next_episodes = next_episodes.order_by( 'programme', 'season', 'number_in_season').select_related('programme') dt = after current_programme = None for episode in next_episodes: if current_programme != episode.programme: # reset dt if programme change current_programme = episode.programme dt = after if dt: schedule, date = Schedule.get_next_date( programme=episode.programme, after=dt) episode.issue_date = date if date: dt = date + episode.runtime else: dt = None else: episode.issue_date = None episode.save()
def schedule(request, visualization_id): visualization = get_object_or_404(Visualization, pk=visualization_id, account=request.user.account) schedule = Schedule( created_by=request.user, visualization=visualization, email=request.POST.get('email', request.user.email), frequency=request.POST.get('frequency', 'daily'), time=request.POST.get('time', 'morning'), show_sum=request.POST.get('totals', 'no') == 'sum', ) schedule.save() for option in dict(request.POST).get('options[]', []): schedule_option = ScheduleOption(schedule=schedule, option=int(option)) schedule_option.save() return HttpResponse(schedule.id, 'application/json')
def __get_events(after, before, json_mode=False): background_colours = {"L": "#F9AD81", "B": "#C4DF9B", "S": "#8493CA"} text_colours = {"L": "black", "B": "black", "S": "black"} next_schedules, next_dates = Schedule.between(after=after, before=before) schedules = [] dates = [] episodes = [] event_list = [] for x in range(len(next_schedules)): for y in range(len(next_dates[x])): # next_events.append([next_schedules[x], next_dates[x][y]]) schedule = next_schedules[x] schedules.append(schedule) date = next_dates[x][y] dates.append(date) episode = None # if schedule == live if next_schedules[x].type == 'L': try: episode = Episode.objects.get(issue_date=date) except Episode.DoesNotExist: pass # broadcast elif next_schedules[x].source: try: source_date = next_schedules[x].source.date_before(date) if source_date: episode = Episode.objects.get(issue_date=source_date) except Episode.DoesNotExist: pass episodes.append(episode) if episode: url = reverse( 'programmes:episode_detail', args=(schedule.programme.slug, episode.season, episode.number_in_season,) ) else: url = reverse('programmes:detail', args=(schedule.programme.slug,)) event_entry = { 'id': schedule.id, 'start': str(date), 'end': str(date + schedule.runtime()), 'allDay': False, 'title': schedule.programme.name, 'type': schedule.type, 'textColor': text_colours[schedule.type], 'backgroundColor': background_colours[schedule.type], 'url': url } event_list.append(event_entry) if json_mode: return event_list else: if schedules: dates, schedules, episodes = (list(t) for t in zip(*sorted(zip(dates, schedules, episodes)))) return zip(schedules, dates, episodes) return None
def test_now_playing_2(self): now_mock = datetime.datetime(2014, 1, 7, 0, 0, 0, 0) schedule, date = Schedule.schedule(now_mock) schedule_1 = Schedule.objects.get( programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=TU) self.assertEqual(schedule_1, schedule) self.assertEqual( datetime.datetime.combine(now_mock, schedule_1.start_hour), date)
def test_day_schedule(self): schedules, dates = Schedule.between(datetime.datetime(2014, 1, 6), datetime.datetime(2014, 1, 7)) self.assertEqual(4, len(schedules)) schedule_1 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=MO) schedule_2 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 09:00 - 10:00"), day=MO) schedule_3 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 10:00 - 12:00"), day=MO) schedule_4 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=TU) self.assertTrue(schedule_1 in schedules) self.assertTrue(schedule_2 in schedules) self.assertTrue(schedule_3 in schedules) self.assertTrue(schedule_4 in schedules)
def save_model(self, request, obj, form, change): if not obj.pk: programme = obj.programme last_episode = Episode.get_last_episode(programme) now = datetime.datetime.now() if last_episode: after = last_episode.issue_date + programme.runtime if after < now: after = now else: after = now schedule, date = Schedule.get_next_date(programme=programme, after=after) Episode.create_episode(episode=obj, date=date, programme=programme, last_episode=last_episode) else: obj.save()
def clean_programme(self): programme = self.cleaned_data['programme'] now = datetime.datetime.now() if not self.instance.pk: last_episode = Episode.get_last_episode(programme) if last_episode: if last_episode.issue_date: after = last_episode.issue_date + programme.runtime if after < now: after = now else: raise forms.ValidationError(_('There are no available schedules.')) else: after = now schedule, date = Schedule.get_next_date(programme=programme, after=after) if not date: raise forms.ValidationError(_('There are no available schedules.')) return programme
def recording_schedules(request): start = datetime.datetime.strptime(request.GET.get('start'), '%Y-%m-%d %H:%M:%S') next_hours = request.GET.get("next_hours", None) if not next_hours: next_hours = PodcastConfiguration.objects.get().next_events else: next_hours = int(next_hours) json_list = [] next_schedules, next_dates = Schedule.between(start, start + relativedelta(hours=next_hours), live=True) schedules = [] dates = [] for x in range(len(next_schedules)): for y in range(len(next_dates[x])): schedules.append(next_schedules[x]) dates.append(next_dates[x][y]) # sort if schedules: dates, schedules = (list(t) for t in zip(*sorted(zip(dates, schedules)))) for x in range(len(schedules)): schedule = schedules[x] date = dates[x] # Create the episode to retrieve season and episode number try: episode = Episode.objects.select_related('programme').get(issue_date=date, programme=schedule.programme) except Episode.DoesNotExist: episode = Episode.create_episode(date, schedule.programme) start_date = date + datetime.timedelta(seconds=PodcastConfiguration.objects.get().start_delay) duration = schedule.runtime().seconds - PodcastConfiguration.objects.get().start_delay - PodcastConfiguration.objects.get().end_delay # start = date.strftime("%Y-%m-%dT%H:%M:%S"+utc_str) json_entry = { 'id': schedule.programme.id, 'issue_date': date.strftime('%Y-%m-%d %H-%M-%S'), 'start': start_date.strftime('%Y-%m-%d %H-%M-%S'), 'duration': str(duration), 'genre': schedule.programme.get_category_display(), 'programme_name': schedule.programme.slug, 'title': episode.title, 'author': schedule.programme.name, 'album': _('Season') + ' ' + str(episode.season), 'track': episode.number_in_season } json_list.append(json_entry) return HttpResponse(json.dumps(json_list), content_type='application/json')
def index(request): now = datetime.datetime.now() schedule_now, start_time = Schedule.schedule(now) if schedule_now: end_time = start_time + schedule_now.runtime() percentage = str(round((now - start_time).total_seconds() / schedule_now.runtime().total_seconds() * 100)) else: end_time = now percentage = None next_events = __get_events(end_time, end_time + relativedelta(hours=+16)) other_programmes = Programme.objects.order_by('?').all()[:10] latest_episodes = Episode.objects.filter(podcast__isnull=False).order_by('-issue_date')[:5] context = {'schedule_now':schedule_now, 'start_time':start_time, 'percentage':percentage, 'end_time':end_time, 'now': now, 'next_events':next_events, 'other_programmes':other_programmes, 'latest_episodes':latest_episodes} return render(request, 'radio/index.html', context)
def test_day_schedule(self): schedules, dates = Schedule.between(datetime.datetime(2014, 1, 6), datetime.datetime(2014, 1, 7)) self.assertEqual(4, len(schedules)) schedule_1 = Schedule.objects.get( programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=MO) schedule_2 = Schedule.objects.get( programme=Programme.objects.get(name="Programme 09:00 - 10:00"), day=MO) schedule_3 = Schedule.objects.get( programme=Programme.objects.get(name="Programme 10:00 - 12:00"), day=MO) schedule_4 = Schedule.objects.get( programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=TU) self.assertTrue(schedule_1 in schedules) self.assertTrue(schedule_2 in schedules) self.assertTrue(schedule_3 in schedules) self.assertTrue(schedule_4 in schedules)
def clean_programme(self): programme = self.cleaned_data['programme'] now = datetime.datetime.now() if not self.instance.pk: last_episode = Episode.get_last_episode(programme) if last_episode: if last_episode.issue_date: after = last_episode.issue_date + programme.runtime if after < now: after = now else: raise forms.ValidationError( _('There are no available schedules.')) else: after = now schedule, date = Schedule.get_next_date(programme=programme, after=after) if not date: raise forms.ValidationError( _('There are no available schedules.')) return programme
def index(request): now = datetime.datetime.now() schedule_now, start_time = Schedule.schedule(now) if schedule_now: end_time = start_time + schedule_now.runtime() percentage = str(round((now - start_time).total_seconds() / schedule_now.runtime().total_seconds() * 100)) else: end_time = now percentage = None next_events = __get_events(end_time, end_time + relativedelta(hours=+16)) other_programmes = Programme.objects.order_by('?').all()[:10] latest_episodes = Episode.objects.filter(podcast__isnull=False).order_by('-issue_date')[:5] context = { 'schedule_now': schedule_now, 'start_time': start_time, 'percentage': percentage, 'end_time': end_time, 'now': now, 'next_events': next_events, 'other_programmes': other_programmes, 'latest_episodes': latest_episodes } return render(request, 'radio/index.html', context)
def create_schedule(request): start = int(request.POST.get('start')) start = datetime.datetime.fromtimestamp(start / 1000.0) emission_type = request.POST.get('type') programme_id = int(request.POST.get('programmeId')) programme = get_object_or_404(Programme, id=programme_id) schedule_board_id = int(request.POST.get('scheduleBoardId')) scheduleBoard = get_object_or_404(ScheduleBoard, id=schedule_board_id) schedule = Schedule(programme=programme, schedule_board=scheduleBoard, day=start.weekday(), start_hour=start.time(), type=emission_type) schedule.clean() schedule.save() Episode.rearrange_episodes(programme, datetime.datetime.now()) return { 'scheduleId': schedule.id, 'backgroundColor': background_colours[schedule.type], 'textColor': text_colours[schedule.type], 'type': schedule.type }
def test_now_playing_2(self): now_mock = datetime.datetime(2014, 1, 7, 0, 0, 0, 0) schedule, date = Schedule.schedule(now_mock) schedule_1 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=TU) self.assertEqual(schedule_1, schedule) self.assertEqual(datetime.datetime.combine(now_mock, schedule_1.start_hour), date)
def __get_events(after, before, json_mode=False): background_colours = {"L": "#F9AD81", "B": "#C4DF9B", "S": "#8493CA"} text_colours = {"L": "black", "B": "black", "S": "black"} next_schedules, next_dates = Schedule.between(after=after, before=before) schedules = [] dates = [] episodes = [] event_list = [] for x in range(len(next_schedules)): for y in range(len(next_dates[x])): # next_events.append([next_schedules[x], next_dates[x][y]]) schedule = next_schedules[x] schedules.append(schedule) date = next_dates[x][y] dates.append(date) episode = None # if schedule == live if next_schedules[x].type == 'L': try: episode = Episode.objects.get(issue_date=date) except Episode.DoesNotExist: pass # broadcast elif next_schedules[x].source: try: source_date = next_schedules[x].source.date_before(date) if source_date: episode = Episode.objects.get(issue_date=source_date) except Episode.DoesNotExist: pass episodes.append(episode) if episode: url = reverse('programmes:episode_detail', args=( schedule.programme.slug, episode.season, episode.number_in_season, )) else: url = reverse('programmes:detail', args=(schedule.programme.slug, )) event_entry = { 'id': schedule.id, 'start': str(date), 'end': str(date + schedule.runtime()), 'allDay': False, 'title': schedule.programme.name, 'type': schedule.type, 'textColor': text_colours[schedule.type], 'backgroundColor': background_colours[schedule.type], 'url': url } event_list.append(event_entry) if json_mode: return event_list else: if schedules: dates, schedules, episodes = (list(t) for t in zip( *sorted(zip(dates, schedules, episodes)))) return zip(schedules, dates, episodes) return None