3b9091a45f05ceca1e5630f8b06ef64d94814fab
[frenchie/icalparse.git] / icalparse.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2010 James French <[email protected]>
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 # THE SOFTWARE.
22
23 import sys
24 import re
25 import urlparse
26 import os
27
28 class InvalidICS(Exception): pass
29 class notJoined(Exception): pass
30
31 # RFC5545 and RFC5546 iCalendar registries contain upper case letters
32 # and dashes only and are separated from the value by a colon (:)
33 icalEntry = re.compile('^[A-Z\-]+:.*')
34
35 def lineJoiner(oldcal):
36         '''Takes a string containing a calendar and returns an array of its lines'''
37
38         if list(oldcal) == oldcal:
39                 oldcal = '\r\n'.join(oldcal)
40
41         # RFC2445 This sequence defines a content 'fold' and needs to be stripped
42         # from the output before writing the file
43         oldcal.replace('\r\n ', '')
44         return oldcal.split('\r\n')
45
46
47 def lineFolder(oldcal, length=75):
48         '''Folds content lines to a specified length, returns a list'''
49
50         cal = []
51         sl = length - 1
52
53         for line in oldcal:
54                 # Line & line ending line ending fit inside length, do nothing
55                 if len(line.rstrip()) <= length:
56                         cal.append(line)
57                 else:
58                         brokenline = [line[0:length] + '\r\n']
59                         ll = length
60                         while ll < len(line.rstrip('\r\n')) + 1:
61                                 brokenline.append(' ' + line[ll:sl+ll].rstrip('\r\n') + '\r\n')
62                                 ll += sl
63                         cal += brokenline
64
65         return cal
66
67 if __name__ == '__main__':
68         from optparse import OptionParser
69         # If the user passed us a 'stdin' argument, we'll go with that,
70         # otherwise we'll try for a url opener
71
72         parser = OptionParser('usage: %prog [options] url')
73         parser.add_option('-s', '--stdin', action='store_true', dest='stdin',
74                 default=False, help='Take a calendar from standard input')
75         parser.add_option('-o', '--output', dest='outfile', default='',
76                 help='Specify output file (defaults to standard output)')
77
78         (options, args) = parser.parse_args()
79
80         if not args and not options.stdin:
81                 parser.print_usage()
82                 sys.exit(0)
83         elif not options.stdin:
84                 url = args[0]
85         else:
86                 url = ''
87
88         # Work out what url parsers we're going to need based on what the user
89         # gave us on the command line - we do like files after all
90         parsedURL = urlparse.urlparse(url)
91         http = 'http' in parsedURL[0]
92
93         if not parsedURL[0]: u = False
94         else: u = True
95
96         if not options.stdin and http:
97                 try:
98                         import httplib2
99                 except ImportError:
100                         import urllib2
101
102         # Try and play nice with HTTP servers unless something goes wrong. We don't
103         # really care about this cache (A lot of ics files seem to be generated with
104         # php which hates caching with a passion).
105         h = False
106         if 'httplib2' in sys.modules:
107                 try: h = httplib2.Http('.httplib2-cache')
108                 except OSError: h = httplib2.Http()
109
110         # Load urllib2 if this is not a stdin
111         if not options.stdin and (not http or not 'httplib2' in sys.modules):
112                 import urllib2
113
114         try:
115                 content = u and (h and h.request(url)[1] or urllib2.urlopen(url).read())
116         except (ValueError, urllib2.URLError), e:
117                 sys.stderr.write('%s\n'%e)
118                 sys.exit(1)
119
120         if not u and not options.stdin:
121                 try: content = open(os.path.abspath(url),'r').read()
122                 except (IOError, OSError), e:
123                         sys.stderr.write('%s\n'%e)
124                         sys.exit(1)
125
126         if options.stdin:
127                 content = sys.stdin.read()
128
129         # RFC5545 and RFC5546 New calendars should be generated UTF-8 and we need to
130         # be able to read ANSI as well. This should take care of us.
131         content = unicode(content, encoding='utf-8')
132
133         #return content

UCC git Repository :: git.ucc.asn.au