Beispiel #1
0
    def get(self, request):
        items = Cohort.objects.all()

        ids = request.GET.get('academy', '')
        slugs = request.GET.get('academy_slug', '')

        ids = ids.split(",") if ids else []
        slugs = slugs.split(",") if slugs else []

        if ids:
            items = Cohort.objects.filter(academy__id__in=ids).order_by('id')

        elif slugs:
            items = Cohort.objects.filter(
                academy__slug__in=slugs).order_by('id')

        else:
            items = []

        if not ids and not slugs:
            raise ValidationException(
                "You need to specify at least one academy or academy_slug (comma separated) in the querystring"
            )

        if (Academy.objects.filter(id__in=ids).count() != len(ids) or
                Academy.objects.filter(slug__in=slugs).count() != len(slugs)):
            raise ValidationException("Some academy not exist")

        items = items.exclude(stage='DELETED')

        upcoming = request.GET.get('upcoming')
        if upcoming == 'true':
            now = timezone.now()
            items = items.filter(kickoff_date__gte=now)

        academies_repr = ical_academies_repr(ids=ids, slugs=slugs)
        key = server_id()

        calendar = iCalendar()
        calendar.add(
            'prodid',
            f'-//BreatheCode//Academy Cohorts{academies_repr} {key}//EN')
        calendar.add('X-WR-CALNAME', f'Academy - Cohorts')
        calendar.add('X-WR-CALDESC', '')
        calendar.add('REFRESH-INTERVAL;VALUE=DURATION', 'PT15M')

        url = os.getenv('API_URL')
        if url:
            url = re.sub(r'/$', '', url) + '/v1/events/ical/cohorts'
            if ids or slugs:
                url = url + '?'

                if ids:
                    url = url + 'academy=' + ','.join(ids)

                if ids and slugs:
                    url = url + '&'

                if slugs:
                    url = url + 'academy_slug=' + ','.join(slugs)

            calendar.add('url', url)

        calendar.add('version', '2.0')

        for item in items:
            event = iEvent()
            event_first_day = iEvent()
            event_last_day = iEvent()
            has_last_day = False

            event.add('summary', item.name)
            event.add('uid', f'breathecode_cohort_{item.id}_{key}')
            event.add('dtstart', item.kickoff_date)

            timeslots = CohortTimeSlot.objects.filter(cohort__id=item.id)
            first_timeslot = timeslots.order_by('starting_at').first()

            if first_timeslot:
                event_first_day.add('summary', f'{item.name} - First day')
                event_first_day.add(
                    'uid', f'breathecode_cohort_{item.id}_first_{key}')
                event_first_day.add('dtstart', first_timeslot.starting_at)
                event_first_day.add('dtend', first_timeslot.ending_at)
                event_first_day.add('dtstamp', first_timeslot.created_at)

            if item.ending_date:
                event.add('dtend', item.ending_date)
                timeslots_datetime = []

                for timeslot in timeslots:
                    starting_at = timeslot.starting_at
                    ending_at = timeslot.ending_at
                    diff = ending_at - starting_at

                    if timeslot.recurrent:
                        ending_at = fix_datetime_weekday(item.ending_date,
                                                         ending_at,
                                                         prev=True)
                        starting_at = ending_at - diff

                    timeslots_datetime.append((starting_at, ending_at))

                last_timeslot = None

                if timeslots_datetime:
                    timeslots_datetime.sort(key=lambda x: x[1], reverse=True)
                    last_timeslot = timeslots_datetime[0]
                    has_last_day = True

                    event_last_day.add('summary', f'{item.name} - Last day')
                    event_last_day.add(
                        'uid', f'breathecode_cohort_{item.id}_last_{key}')
                    event_last_day.add('dtstart', last_timeslot[0])
                    event_last_day.add('dtend', last_timeslot[1])
                    event_last_day.add('dtstamp', item.created_at)

            event.add('dtstamp', item.created_at)

            teacher = CohortUser.objects.filter(role='TEACHER',
                                                cohort__id=item.id).first()

            if teacher:
                organizer = vCalAddress(f'MAILTO:{teacher.user.email}')

                if teacher.user.first_name and teacher.user.last_name:
                    organizer.params['cn'] = vText(
                        f'{teacher.user.first_name} '
                        f'{teacher.user.last_name}')
                elif teacher.user.first_name:
                    organizer.params['cn'] = vText(teacher.user.first_name)
                elif teacher.user.last_name:
                    organizer.params['cn'] = vText(teacher.user.last_name)

                organizer.params['role'] = vText('OWNER')
                event['organizer'] = organizer

                if first_timeslot:
                    event_first_day['organizer'] = organizer

                if has_last_day:
                    event_last_day['organizer'] = organizer

            location = item.academy.name

            if item.academy.website_url:
                location = f'{location} ({item.academy.website_url})'

            event['location'] = vText(item.academy.name)

            if first_timeslot:
                event_first_day['location'] = vText(item.academy.name)

            if has_last_day:
                event_last_day['location'] = vText(item.academy.name)

            if first_timeslot:
                calendar.add_component(event_first_day)
            calendar.add_component(event)

            if has_last_day:
                calendar.add_component(event_last_day)

        calendar_text = calendar.to_ical()

        response = HttpResponse(calendar_text, content_type='text/calendar')
        response['Content-Disposition'] = 'attachment; filename="calendar.ics"'
        return response
Beispiel #2
0
    def get(self, request):
        items = Event.objects.filter(status='ACTIVE')

        ids = request.GET.get('academy', '')
        slugs = request.GET.get('academy_slug', '')

        ids = ids.split(",") if ids else []
        slugs = slugs.split(",") if slugs else []

        if ids:
            items = Event.objects.filter(academy__id__in=ids,
                                         status='ACTIVE').order_by('id')

        elif slugs:
            items = Event.objects.filter(academy__slug__in=slugs,
                                         status='ACTIVE').order_by('id')

        else:
            items = []

        if not ids and not slugs:
            raise ValidationException(
                "You need to specify at least one academy or academy_slug (comma separated) in the querystring"
            )

        if (Academy.objects.filter(id__in=ids).count() != len(ids) or
                Academy.objects.filter(slug__in=slugs).count() != len(slugs)):
            raise ValidationException("Some academy not exist")

        upcoming = request.GET.get('upcoming')
        if upcoming == 'true':
            now = timezone.now()
            items = items.filter(starting_at__gte=now)

        academies_repr = ical_academies_repr(ids=ids, slugs=slugs)
        key = server_id()

        calendar = iCalendar()
        calendar.add(
            'prodid',
            f'-//BreatheCode//Academy Events{academies_repr} {key}//EN')
        calendar.add('X-WR-CALNAME', f'Academy - Events')
        calendar.add('X-WR-CALDESC', '')
        calendar.add('REFRESH-INTERVAL;VALUE=DURATION', 'PT15M')

        url = os.getenv('API_URL')
        if url:
            url = re.sub(r'/$', '', url) + '/v1/events/ical/events'
            if ids or slugs:
                url = url + '?'

                if ids:
                    url = url + 'academy=' + ','.join(ids)

                if ids and slugs:
                    url = url + '&'

                if slugs:
                    url = url + 'academy_slug=' + ','.join(slugs)

            calendar.add('url', url)

        calendar.add('version', '2.0')

        for item in items:
            event = iEvent()

            if item.title:
                event.add('summary', item.title)

            description = ''
            description = f'{description}Url: {item.url}\n'

            if item.academy:
                description = f'{description}Academy: {item.academy.name}\n'

            if item.venue and item.venue.title:
                description = f'{description}Venue: {item.venue.title}\n'

            if item.event_type:
                description = f'{description}Event type: {item.event_type.name}\n'

            if item.online_event:
                description = f'{description}Location: online\n'

            event.add('description', description)
            event.add('uid', f'breathecode_event_{item.id}_{key}')
            event.add('dtstart', item.starting_at)
            event.add('dtend', item.ending_at)
            event.add('dtstamp', item.created_at)

            if item.author and item.author.email:
                organizer = vCalAddress(f'MAILTO:{item.author.email}')

                if item.author.first_name and item.author.last_name:
                    organizer.params['cn'] = vText(f'{item.author.first_name} '
                                                   f'{item.author.last_name}')
                elif item.author.first_name:
                    organizer.params['cn'] = vText(item.author.first_name)
                elif item.author.last_name:
                    organizer.params['cn'] = vText(item.author.last_name)

                organizer.params['role'] = vText('OWNER')
                event['organizer'] = organizer

            if item.venue and (item.venue.country or item.venue.state or
                               item.venue.city or item.venue.street_address):
                value = ''

                if item.venue.street_address:
                    value = f'{value}{item.venue.street_address}, '

                if item.venue.city:
                    value = f'{value}{item.venue.city}, '

                if item.venue.state:
                    value = f'{value}{item.venue.state}, '

                if item.venue.country:
                    value = f'{value}{item.venue.country}'

                value = re.sub(', $', '', value)
                event['location'] = vText(value)

            calendar.add_component(event)

        calendar_text = calendar.to_ical()

        response = HttpResponse(calendar_text, content_type='text/calendar')
        response['Content-Disposition'] = 'attachment; filename="calendar.ics"'
        return response
Beispiel #3
0
    def get(self, request, user_id):
        items = Cohort.objects.all()

        if not User.objects.filter(id=user_id).count():
            raise ValidationException("Student not exist",
                                      404,
                                      slug='student-not-exist')

        cohort_ids = (CohortUser.objects.filter(user_id=user_id).values_list(
            'cohort_id', flat=True).exclude(cohort__stage='DELETED'))

        items = CohortTimeSlot.objects.filter(
            cohort__id__in=cohort_ids).order_by('id')
        items = items

        upcoming = request.GET.get('upcoming')
        if upcoming == 'true':
            now = timezone.now()
            items = items.filter(cohort__kickoff_date__gte=now)

        key = server_id()

        calendar = iCalendar()
        calendar.add(
            'prodid',
            f'-//BreatheCode//Student Schedule ({user_id}) {key}//EN')
        calendar.add('X-WR-CALNAME', f'Academy - Schedule')
        calendar.add('X-WR-CALDESC', '')
        calendar.add('REFRESH-INTERVAL;VALUE=DURATION', 'PT15M')

        url = os.getenv('API_URL')
        if url:
            url = re.sub(r'/$', '',
                         url) + '/v1/events/ical/student/' + str(user_id)
            calendar.add('url', url)

        calendar.add('version', '2.0')

        for item in items:
            event = iEvent()

            event.add('summary', item.cohort.name)
            event.add('uid', f'breathecode_cohort_time_slot_{item.id}_{key}')

            event.add('dtstart', item.starting_at)
            event.add('dtstamp', item.starting_at)

            until_date = item.cohort.ending_date

            if not until_date:
                until_date = timezone.make_aware(
                    datetime(year=2100,
                             month=12,
                             day=31,
                             hour=12,
                             minute=00,
                             second=00))

            if item.recurrent:
                event.add('rrule', {
                    'freq': item.recurrency_type,
                    'until': until_date
                })

            event.add('dtend', item.ending_at)

            teacher = CohortUser.objects.filter(
                role='TEACHER', cohort__id=item.cohort.id).first()

            if teacher:
                organizer = vCalAddress(f'MAILTO:{teacher.user.email}')

                if teacher.user.first_name and teacher.user.last_name:
                    organizer.params['cn'] = vText(
                        f'{teacher.user.first_name} '
                        f'{teacher.user.last_name}')
                elif teacher.user.first_name:
                    organizer.params['cn'] = vText(teacher.user.first_name)
                elif teacher.user.last_name:
                    organizer.params['cn'] = vText(teacher.user.last_name)

                organizer.params['role'] = vText('OWNER')
                event['organizer'] = organizer

            location = item.cohort.academy.name

            if item.cohort.academy.website_url:
                location = f'{location} ({item.cohort.academy.website_url})'
            event['location'] = vText(item.cohort.academy.name)

            calendar.add_component(event)

        calendar_text = calendar.to_ical()

        response = HttpResponse(calendar_text, content_type='text/calendar')
        response['Content-Disposition'] = 'attachment; filename="calendar.ics"'
        return response