8c2a105fe0c81ba4fdb6d6943bf7f66c7989ab51
[pycalendar.git] / test / aggregate.py
1 #!/usr/bin/env python
2 #
3 # Copyright (C) 2013 W. Trevor King <wking@tremily.us>
4 #
5 # This file is part of pycalender.
6 #
7 # pycalender is free software: you can redistribute it and/or modify it under
8 # the terms of the GNU General Public License as published by the Free Software
9 # Foundation, either version 3 of the License, or (at your option) any later
10 # version.
11 #
12 # pycalender is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # pycalender.  If not, see <http://www.gnu.org/licenses/>.
18
19 """An example aggregation script
20
21 This script grabs all the ``.ics`` files in the ``test/`` directory
22 and aggregates them into a single iCalendar feed.  While it's doing
23 this, it also prints and geographic positions to stderr.  In a live
24 site, you could use a different version of ``add_event`` to build
25 javascript that renders a map showing event locations.
26 """
27
28 import os as _os
29 import sys as _sys
30
31 import pycalendar.aggregator as _pycalendar_aggregator
32 import pycalendar.feed as _pycalendar_feed
33
34
35 class Map (list):
36     def __init__(self, stream=_sys.stderr):
37         self.stream = stream
38
39     def add_feed(self, feed):
40         for event in feed['VEVENT']:
41             self.add_event(event=event)
42
43     def add_event(self, event):
44         if 'GEO' in event:
45             lat,lon = event.get_geo()
46             self.stream.write('{} at lat {}, lon {}\n'.format(
47                 event['UID'], lat, lon))
48
49
50 def get_urls(root=_os.path.dirname(__file__)):
51     for dirpath, dirnames, filenames in _os.walk(root):
52         for filename in filenames:
53             base,ext = _os.path.splitext(filename)
54             if ext == '.ics':
55                 path = _os.path.abspath(_os.path.join(dirpath, filename))
56                 yield 'file://{}'.format(path.replace(_os.sep, '/'))
57
58
59 def aggregate(**kwargs):
60     aggregator = _pycalendar_aggregator.Aggregator(
61         prodid='-//pycalendar//NONSGML testing//EN',
62         feeds=[_pycalendar_feed.Feed(url=url)
63                for url in get_urls()],
64         **kwargs)
65     aggregator.fetch()
66     return aggregator
67
68
69 if __name__ == '__main__':
70     geomap = Map()
71     aggregator = aggregate(processors=[geomap.add_feed])
72     aggregator.write(stream=_sys.stdout)