def _build_components(self): super(Calendar, self)._build_components() # parse timezones for vtimezone in self._components['VTIMEZONE']: timezones = tzical(StringIO(str(vtimezone))) # tzical does not like strings for key in timezones.keys(): self._timezones[key] = timezones.get(key)
def parseTzs(self, tzs): if not tzs: return for tz in tzs: if "X-LIC-LOCATION" in tz: del tz["X-LIC-LOCATION"] data = "".join([str(i) for i in tzs]) data = "\r\n".join([i for i in data.splitlines() if i.strip()]) fd = StringIO(data) times = tzmod.tzical(fd) for tz in times.keys(): self.timezones[tz] = times.get(tz)
def gather(self, url): # Check when we last updated this URL cal, created = Calendar.objects.get_or_create(url=url, defaults={'ts': datetime.datetime.now()}) if not created: old_ts = cal.ts cal.ts = datetime.datetime.now() Calendar.objects.filter(pk=cal.pk).update(ts=cal.ts) if old_ts and datetime.datetime.now() - old_ts < datetime.timedelta(hours=1): return # Load the calendar data = urllib2.urlopen(url).read() data = data.replace('00001231T000000Z', '00011231T000000Z') # datetime doesn't like year=0 ical = icalendar.Calendar.from_string(data) # Delete all existing events for this URL cal.events.all().delete() # Update the name cal.name = ical.get('X-WR-CALNAME') or '' Calendar.objects.filter(pk=cal.pk).update(name=cal.name) # Get the timezone for this calendar now = datetime.datetime.now(tz.tzlocal()) for vtimezone in ical.walk('VTIMEZONE'): sio = StringIO() for line in str(vtimezone).splitlines(): if not line.lower().startswith('x-'): sio.write(line) sio.write('\r\n') sio.seek(0) cal_tz = tz.tzical(sio).get() break else: cal_tz = tz.tzutc() # Add new events for vevent in ical.walk('VEVENT'): dtstart = vevent['DTSTART'].dt if not isinstance(dtstart, datetime.datetime): dtstart = datetime.datetime.combine(dtstart, datetime.time(0)) if dtstart.tzinfo is None: dtstart = dtstart.replace(tzinfo=cal_tz) if 'RRULE' in vevent: recur = rrule.rrulestr(str(vevent['RRULE']), dtstart=dtstart) for dt in recur[:20]: print dt if dt >= now: CalendarEvent.objects.create(calendar=cal, date=dt.astimezone(tz.tzutc()), title=vevent['SUMMARY']) elif dtstart >= now: CalendarEvent.objects.create(calendar=cal, date=dtstart.astimezone(tz.tzutc()), title=vevent['SUMMARY'])
def timezone(calendar, vtimezones): """Receives a list of VTIMEZONE blocks. Parses them and adds them to calendar._timezones. """ for vtimezone in vtimezones: remove_x(vtimezone) # Remove non standard lines from the block fake_file = StringIO() fake_file.write(str(vtimezone)) # Represent the block as a string fake_file.seek(0) timezones = tzical(fake_file) # tzical does not like strings # timezones is a tzical object and could contain multiple timezones for key in timezones.keys(): calendar._timezones[key] = timezones.get(key)
def parse_vtimezone(calendar: "Calendar", vtimezones: List["Container"]): """Receives a list of VTIMEZONE blocks. Parses them and adds them to calendar._timezones. """ for vtimezone in vtimezones: remove_x(vtimezone) # Remove non standard lines from the block remove_sequence( vtimezone ) # Remove SEQUENCE lines because tzical does not understand them fake_file = StringIO() fake_file.write(str(vtimezone)) # Represent the block as a string fake_file.seek(0) timezones = tzical(fake_file) # tzical does not like strings # timezones is a tzical object and could contain multiple timezones for key in timezones.keys(): calendar._timezones[key] = timezones.get(key)
def populate(self, component: "Component", item: ContainerItem, context: ContextDict) -> bool: assert isinstance(item, Container) self._check_component(component, context) item = item.clone([ line for line in item if not line.name.startswith("X-") and not line.name == "SEQUENCE" ]) fake_file = StringIO() fake_file.write(item.serialize()) # Represent the block as a string fake_file.seek(0) timezones = tzical(fake_file) # tzical does not like strings # timezones is a tzical object and could contain multiple timezones print("got timezone", timezones.keys(), timezones.get()) self.set_or_append_value(component, timezones.get()) return True
def timezone(calendar, vtimezones): """Receives a list of VTIMEZONE blocks. Parses them and adds them to calendar._timezones. """ timezone_idx = 0 for vtimezone in vtimezones: remove_lines_starting_with(vtimezone, ['X-', 'SEQUENCE']) # Remove non standard lines from the block vtimezone_str = str(vtimezone) if "\nTZID:" not in vtimezone_str: insert_place = string.split(vtimezone_str, '\n', 1) vtimezone_str = "{}\n{}\n{}".format(insert_place[0], "TZID:uniqueTzId{}".format(timezone_idx), insert_place[1]) timezone_idx = timezone_idx + 1 fake_file = StringIO() fake_file.write(vtimezone_str) # Represent the block as a string fake_file.seek(0) timezones = tzical(fake_file) # tzical does not like strings # timezones is a tzical object and could contain multiple timezones for key in timezones.keys(): calendar._timezones[key] = timezones.get(key)
def getICalTzinfo(self, lines): fileobj = cStringIO.StringIO("\r\n".join(lines)) parsed = tz.tzical(fileobj) return parsed.get()
def testICalEnd1(self): tzc = tz.tzical(StringIO(TZICAL_EST5EDT)).get() self.assertEqual( datetime(2003, 10, 26, 0, 59, tzinfo=tzc).tzname(), "EDT") self.assertEqual( datetime(2003, 10, 26, 1, 00, tzinfo=tzc).tzname(), "EST")
def main(): cal = sys.stdin.read() lines = [] linesx = [] for line in cal.splitlines(): if line.startswith('X-'): # Don't process unsupported entries with dateutil.tz to # avoid throwing an exception in tzical. We'll show them # out to the user later. linesx.append(line) else: lines.append(line) tmpfile = StringIO.StringIO() tmpfile.write("\n".join(lines)) tmpfile.seek(0) try: tzical = tz.tzical(tmpfile) except ValueError: sys.stderr.write( "Sorry, I could not read the calendar file properly.\n" + "Please e-mail it to the developer so I can be fixed.\n" ) sys.exit(1) try: icaltz = tzical.get() except ValueError: # No Timezone in iCal, assume UTC? icaltz = tz.tzutc() cal = Calendar.from_ical(cal) events = cal.walk('VEVENT') evnum = len(events) for n, e in enumerate(events): if evnum > 1: print '** Event %s:' % (n+1) # DEBUG #print e #print "--------" start = e['dtstart'].dt.replace(tzinfo=icaltz).astimezone(tz.tzlocal()) end = e['dtend'].dt.replace(tzinfo=icaltz).astimezone(tz.tzlocal()) print 'Event: %s' % e['summary'].encode('UTF-8') print 'Start: %s' % start.strftime('%a, %Y-%m-%d %H:%M %Z') print 'End: %s' % end.strftime('%a, %Y-%m-%d %H:%M %Z') if e.get('organizer'): print 'Organizer: %s' % format_atendee(e['organizer']) if e.get('status'): print 'Status: %s' % e['status'] if e.get('location'): print 'Location: %s' % e['location'].encode('UTF-8') if e.get('attendee'): print 'Atendee(s):' if not isinstance(e['attendee'], basestring): for a in e['attendee']: print " %s" % format_atendee(a) else: print " %s" % format_atendee(e['attendee']) if e.get('description'): print '\n%s' % e['description'].encode('UTF-8') if linesx: print "\n-----" for line in linesx: print line
def testPickleTzICal(self): tzc = tz.tzical(StringIO(TZICAL_EST5EDT)).get() self.assertPicklable(tzc)
def testICalStart1(self): tzc = tz.tzical(StringIO(TZICAL_EST5EDT)).get() self.assertEqual( datetime(2003, 4, 6, 1, 59, tzinfo=tzc).tzname(), "EST") self.assertEqual( datetime(2003, 4, 6, 2, 00, tzinfo=tzc).tzname(), "EDT")
def testICalEnd1(self): tzc = tz.tzical(StringIO(TZICAL_EST5EDT)).get() self.assertEqual(datetime(2003, 10, 26, 0, 59, tzinfo=tzc).tzname(), "EDT") self.assertEqual(datetime(2003, 10, 26, 1, 00, tzinfo=tzc).tzname(), "EST")
def testICalStart1(self): tzc = tz.tzical(StringIO(TZICAL_EST5EDT)).get() self.assertEqual(datetime(2003, 4, 6, 1, 59, tzinfo=tzc).tzname(), "EST") self.assertEqual(datetime(2003, 4, 6, 2, 00, tzinfo=tzc).tzname(), "EDT")
def main(): cal = sys.stdin.read() lines = [] linesx = [] for line in cal.splitlines(): if line.startswith('X-'): # Don't process unsupported entries with dateutil.tz to # avoid throwing an exception in tzical. We'll show them # out to the user later. linesx.append(line) else: lines.append(line) tmpfile = StringIO.StringIO() tmpfile.write("\n".join(lines)) tmpfile.seek(0) try: tzical = tz.tzical(tmpfile) except ValueError: sys.stderr.write( "Sorry, I could not read the calendar file properly.\n" + "Please e-mail it to the developer so I can be fixed.\n") sys.exit(1) try: icaltz = tzical.get() except ValueError: # No Timezone in iCal, assume UTC? icaltz = tz.tzutc() cal = Calendar.from_ical(cal) events = cal.walk('VEVENT') evnum = len(events) for n, e in enumerate(events): if evnum > 1: print '** Event %s:' % (n + 1) # DEBUG #print e #print "--------" start = e['dtstart'].dt.replace(tzinfo=icaltz).astimezone(tz.tzlocal()) end = e['dtend'].dt.replace(tzinfo=icaltz).astimezone(tz.tzlocal()) print 'Event: %s' % e['summary'].encode('UTF-8') print 'Start: %s' % start.strftime('%a, %Y-%m-%d %H:%M %Z') print 'End: %s' % end.strftime('%a, %Y-%m-%d %H:%M %Z') if e.get('organizer'): print 'Organizer: %s' % format_atendee(e['organizer']) if e.get('status'): print 'Status: %s' % e['status'] if e.get('location'): print 'Location: %s' % e['location'].encode('UTF-8') if e.get('attendee'): print 'Atendee(s):' if not isinstance(e['attendee'], basestring): for a in e['attendee']: print " %s" % format_atendee(a) else: print " %s" % format_atendee(e['attendee']) if e.get('description'): print '\n%s' % e['description'].encode('UTF-8') if linesx: print "\n-----" for line in linesx: print line