Beispiel #1
0
 def test_alarm_repeat(self):
     a = DisplayAlarm(trigger=timedelta(minutes=15),
                      repeat=2,
                      duration=timedelta(minutes=10))
     self.assertEqual(15 * 60, a.trigger.total_seconds())
     self.assertEqual(2, a.repeat)
     self.assertEqual(10 * 60, a.duration.total_seconds())
Beispiel #2
0
    def _html_to_ics(self, markup: str, timezone: pytz.timezone) -> Calendar:
        soup = BeautifulSoup(markup, "lxml")
        monthly_prayers = soup.find("div", {"id": "tab-1"}).table
        headers = [i.text for i in monthly_prayers.thead.tr.find_all('th')][1:]
        data = [[i.text for i in tr.find_all('td')]
                for tr in monthly_prayers.tbody.find_all('tr')]
        calendar = Calendar(creator=app.config['APPLICATION_ID'])
        for day_record in data:
            events_starts = [
                timezone.localize(
                    datetime.strptime(day_record[0] + ' ' + _time,
                                      '%d.%m.%Y %H:%M'))
                for _time in day_record[1:]
            ]
            for i in range(len(headers)):
                display_alarm = DisplayAlarm(trigger=events_starts[i],
                                             display_text=headers[i])
                audio_alarm = AudioAlarm(trigger=events_starts[i])
                audio_alarm.sound = ContentLine('ATTACH',
                                                {'FMTTYPE': ['audio/mpeg']},
                                                app.config['ADHAN_AUDIO'])

                calendar.events.add(
                    Event(name=headers[i],
                          begin=events_starts[i],
                          duration=timedelta(minutes=1),
                          alarms=[audio_alarm, display_alarm]))
        return calendar
Beispiel #3
0
def create_ics(birthday=None,
               add_alarms=False,
               schedule_file='./vaccines.csv',
               ical_file='./vaccines.ics'):
    if birthday is None:
        birthday = date.today()
    else:
        birthday = parser.parse(birthday)

    c = Calendar()
    for v in load_csv(schedule_file):
        v = v._asdict()
        target_months = [k for k, v_ in v.items() if k.startswith('M') and v_]
        total = v[target_months[-1]]
        for month in target_months:
            name = v['name'] + f' {v[month]}/{total}'
            begin = birthday + relativedelta(months=int(month[1:]))
            if add_alarms:
                alarms = [DisplayAlarm(trigger=timedelta(hours=1))]
            else:
                alarms = None
            e = Event(name=name,
                      begin=begin,
                      description=v['abbv'],
                      alarms=alarms)
            e.make_all_day()
            c.events.add(e)
    with open(ical_file, 'w') as f:
        f.writelines(c)
Beispiel #4
0
 def test_plain_repr(self):
     test_description = 'Test description'
     a = DisplayAlarm(trigger=timedelta(minutes=15),
                      description=test_description)
     self.assertEqual(
         repr(a),
         "<<class 'ics.alarm.DisplayAlarm'> trigger:0:15:00 description:Test description>"
     )
Beispiel #5
0
    def test_alarm_timedelta_trigger_output(self):
        a = DisplayAlarm(trigger=timedelta(minutes=15))

        desired_output = CRLF.join([
            'BEGIN:VALARM', 'TRIGGER:-PT15M', 'ACTION:DISPLAY', 'DESCRIPTION:',
            'END:VALARM'
        ])

        self.assertEqual(desired_output, str(a))
Beispiel #6
0
 def test_alarm_datetime_trigger(self):
     alarm_time = datetime(year=2016,
                           month=1,
                           day=1,
                           hour=0,
                           minute=0,
                           second=0)
     a = DisplayAlarm(trigger=alarm_time)
     self.assertEqual(arrow.get(alarm_time), a.trigger)
Beispiel #7
0
 def test_repeat_repr(self):
     test_description = 'Test description'
     a = DisplayAlarm(trigger=timedelta(minutes=15),
                      repeat=2,
                      duration=timedelta(minutes=10),
                      description=test_description)
     self.assertEqual(
         repr(a),
         "<<class 'ics.alarm.DisplayAlarm'> trigger:0:15:00 repeat:2 "
         "duration:0:10:00 description:Test description>")
Beispiel #8
0
    def test_alarm_datetime_trigger_output(self):
        alarm_time = arrow.get('2016-01-01')
        a = DisplayAlarm(trigger=alarm_time)

        desired_output = CRLF.join([
            'BEGIN:VALARM', 'TRIGGER;VALUE=DATE-TIME:20160101T000000Z',
            'ACTION:DISPLAY', 'DESCRIPTION:', 'END:VALARM'
        ])

        self.assertEqual(desired_output, str(a))
Beispiel #9
0
    def test_alarm_repeat_duration_output(self):
        a = DisplayAlarm(trigger=timedelta(minutes=15),
                         repeat=2,
                         duration=timedelta(minutes=10))

        desired_output = CRLF.join([
            'BEGIN:VALARM', 'TRIGGER:-PT15M', 'DURATION:PT10M', 'REPEAT:2',
            'ACTION:DISPLAY', 'DESCRIPTION:', 'END:VALARM'
        ])

        self.assertEqual(desired_output, str(a))
Beispiel #10
0
    def test_alarm_output(self):
        a = DisplayAlarm(trigger=timedelta(minutes=15),
                         display_text="Test description")

        desired_output = CRLF.join([
            "BEGIN:VALARM",
            "ACTION:DISPLAY",
            "DESCRIPTION:Test description",
            "TRIGGER:PT15M",
            "END:VALARM",
        ])

        self.assertEqual(desired_output, str(a))
Beispiel #11
0
def create_ics(sender, instance, **kwargs):
    c = Calendar()
    alarm = [DisplayAlarm(trigger=timedelta(minutes=30))]

    e = Event()
    e.name = instance.title
    e.begin = instance.date
    e.end = instance.dateend
    e.alarms = alarm
    if instance.duration != None:
        e.duration = instance.duration
    if (instance.cost == 0 or instance.cost == None):
        cost = 'Бесплатно'
        e.description = str(instance.intro) + ' Стоимость: ' + str(cost)
    else:
        e.description = str(instance.intro) + ' Стоимость: ' + str(instance.cost)+  'р.'
    e.location = instance.location
    if instance.timepad != None:
        e.url = instance.timepad
    c.events.add(e)

    instance.ics.delete(save=False)
    instance.ics.save(instance.title +'.ics', ContentFile(str(c)), save=True)
    #Формирование глобального файла со всеми мероприятиями
    global_ics = EventIndex.objects.all()[0]
    events = global_ics.get_children()
    c = Calendar()
    for event in events:
        if (event.specific.date < timezone.now()):
            pass
        else:
            e = Event()
            e.name = event.title
            e.begin = event.specific.date
            e.end = event.specific.dateend
            e.alarms = alarm
            if event.specific.duration != None:
                e.duration = event.specific.duration
            if (event.specific.cost == 0 or event.specific.cost == None):
                cost = 'Бесплатно'
                e.description = str(event.specific.intro.strip("<p>*</p>")) + ' Стоимость: ' + str(cost)
            else:
                e.description = str(event.specific.intro.strip("<p>*</p>")) + ' Стоимость: ' + str(event.specific.cost)+  'р.'
            e.location = event.specific.location
            if event.specific.timepad != None:
                e.url = event.specific.timepad
            c.events.add(e)
    global_ics.calenadar_file.delete(save=False)
    global_ics.calenadar_file.save('global.ics', ContentFile(str(c)), save=True)
Beispiel #12
0
    def test_alarm_datetime_trigger_output(self):
        alarm_time = datetime(year=2016,
                              month=1,
                              day=1,
                              hour=0,
                              minute=0,
                              second=0)
        a = DisplayAlarm(trigger=alarm_time)

        desired_output = CRLF.join([
            'BEGIN:VALARM', 'TRIGGER;VALUE=DATE-TIME:20160101T000000Z',
            'ACTION:DISPLAY', 'DESCRIPTION:', 'END:VALARM'
        ])

        self.assertEqual(desired_output, str(a))
def generate_calendar_for_games(games_array):
    calendar = Calendar()

    for game in games:
        event = Event()
        event.name = f'{game["fixture"]} ({game["competition"]})'
        start = game['kick_off']
        event.begin = start
        event.end = start.shift(hours=+2)
        event.location = game['channel']
        if args.alert_minutes:
            alarm = DisplayAlarm(trigger=timedelta(minutes=args.alert_minutes))
            event.alarms.append(alarm)
        calendar.events.add(event)

    return calendar
Beispiel #14
0
    def ical_alarms(self) -> Dict[int, List[base.BaseAlarm]]:
        alarms: Dict[int, List[base.BaseAlarm]] = defaultdict(list)

        for alert in self.alerts:
            # Invert timedelta to make it represent time before the event
            inverted_timedelta = -alert.timedelta
            # Alarms at the event's time break, so use the event's time - 1 second
            if not inverted_timedelta:
                inverted_timedelta = timedelta(minutes=-1)

            if alert.type == EventAlertType.EMAIL:
                alarm = EmailAlarm(inverted_timedelta)
            else:
                alarm = DisplayAlarm(inverted_timedelta)

            alarms[int(alert.event_id)].append(alarm)
        return alarms
Beispiel #15
0
    e = Event()
    date_begin_str = f'{init_date} {i["begin"]}+0530'
    date_end_str = f'{init_date} {i["end"]}+0530'

    date_begin = datetime.strptime(date_begin_str,
                                   "%Y-%m-%d %H%M%z") + timedelta(
                                       days.index(i['day'].lower()))
    date_end = datetime.strptime(date_end_str, "%Y-%m-%d %H%M%z") + timedelta(
        days.index(i['day'].lower()))

    e.name = i['name']
    e.begin = date_begin.strftime("%Y-%m-%d %H:%M:%S%z")
    e.end = date_end.strftime("%Y-%m-%d %H:%M:%S%z")
    e.description = i['desc']
    e.alarms = [
        DisplayAlarm(trigger=timedelta(minutes=-5)),
        DisplayAlarm(trigger=date_begin)
    ]

    if i['name'] != "Economics B":
        e.attendees = ['*****@*****.**']

    c.events.add(e)

    print(
        f'Created {i["name"]} {datetime.strftime(date_begin, "%Y-%m-%d %H:%M:%S")} - {datetime.strftime(date_end, "%Y-%m-%d %H:%M:%S")}'
    )

with open('out.ics', 'w') as my_file:
    my_file.writelines(c)
Beispiel #16
0
 def test_alarm(self):
     test_description = "Test description"
     a = DisplayAlarm(trigger=timedelta(minutes=15),
                      display_text=test_description)
     self.assertEqual(test_description, a.display_text)
Beispiel #17
0
 def test_alarm(self):
     test_description = 'Test description'
     a = DisplayAlarm(trigger=timedelta(minutes=15),
                      description=test_description)
     self.assertEqual(test_description, a.description)
Beispiel #18
0
 def test_alarm_datetime_trigger(self):
     alarm_time = arrow.get('2016-01-01')
     a = DisplayAlarm(trigger=alarm_time)
     self.assertEqual(arrow.get(alarm_time), a.trigger)
Beispiel #19
0
 def test_alarm_timedelta_trigger(self):
     a = DisplayAlarm(trigger=timedelta(minutes=15))
     self.assertEqual(15 * 60, a.trigger.total_seconds())
Beispiel #20
0
 def test_alarm_invalid_duration(self):
     with self.assertRaises(ValueError):
         DisplayAlarm(trigger=timedelta(minutes=15),
                      repeat=2,
                      duration=timedelta(minutes=-10))
Beispiel #21
0
 def test_alarm_missing_duration(self):
     with self.assertRaises(ValueError):
         DisplayAlarm(trigger=timedelta(minutes=15), repeat=2)