c54b122a2394a8d9352a760b91d543c597628a90
[pycalendar.git] / pycalendar / aggregator.py
1 # Copyright
2
3 class Aggregator (list):
4     r"""An iCalendar feed aggregator
5
6     Figure out where the example feeds are located, relative to the
7     directory from which you run this doctest (i.e., the project's
8     root directory).
9
10     >>> import os
11     >>> root_dir = os.curdir
12     >>> data_dir = os.path.abspath(os.path.join(root_dir, 'test', 'data'))
13     >>> base_url = 'file://{}'.format(data_dir.replace(os.sep, '/'))
14
15     >>> from .feed import Feed
16
17     >>> a = Aggregator(
18     ...     prodid='-//pycalendar//NONSGML testing//EN',
19     ...     feeds=[
20     ...         Feed(url='{}/{}'.format(base_url, name))
21     ...         for name in ['geohash.ics',]],
22     ...     )
23     >>> a  # doctest: +ELLIPSIS
24     [<Feed url:file://.../test/data/geohash.ics>]
25     >>> a.fetch()
26
27     Generate aggregate calendars with the ``.write`` method.
28
29     >>> import io
30     >>> stream = io.StringIO()
31     >>> a.write(stream=stream)
32     >>> value = stream.getvalue()
33     >>> value  # doctest: +ELLIPSIS
34     'BEGIN:VCALENDAR\r\nVERSION:2.0\r\n...END:VCALENDAR\r\n'
35     >>> print(value.replace('\r\n', '\n'))
36     BEGIN:VCALENDAR
37     VERSION:2.0
38     PRODID:-//pycalendar//NONSGML testing//EN
39     BEGIN:VEVENT
40     UID:2013-06-30@geohash.invalid
41     DTSTAMP:2013-06-30T00:00:00Z
42     DTSTART;VALUE=DATE:20130630
43     DTEND;VALUE=DATE:20130701
44     SUMMARY:XKCD geohashing\, Boston graticule
45     URL:http://xkcd.com/426/
46     LOCATION:Snow Hill\, Dover\, Massachusetts
47     GEO:42.226663,-71.28676
48     END:VEVENT
49     END:VCALENDAR
50     <BLANKLINE>
51     """
52     def __init__(self, prodid, version='2.0', feeds=None):
53         super(Aggregator, self).__init__()
54         self.prodid = prodid
55         self.version = version
56         if feeds:
57             self.extend(feeds)
58
59     def fetch(self):
60         for feed in self:
61             feed.fetch()
62
63     def write(self, stream):
64         stream.write('BEGIN:VCALENDAR\r\n')
65         stream.write('VERSION:{}\r\n'.format(self.version))
66         stream.write('PRODID:{}\r\n'.format(self.prodid))
67         for feed in self:
68             for entry in feed:
69                 entry.write(stream=stream)
70         stream.write('END:VCALENDAR\r\n')