Now parses urls/files okay
[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 from optparse import OptionParser
28
29 class InvalidICS(Exception): pass
30 class notJoined(Exception): pass
31
32 # RFC5545 and RFC5546 iCalendar registries contain upper case letters
33 # and dashes only and are separated from the value by a colon (:)
34 icalEntry = re.compile('^[A-Z\-]+:.*')
35
36 def lineJoiner(oldcal):
37         '''Unfolds a calendar so that items can be parsed'''
38
39         cal = []
40
41         # Strip newlines (
42         for line in oldcal:
43                 line = line.rstrip('\r\n')
44
45                 # Reassemble broken Lines
46                 if not line:
47                         if not cal: continue
48                         else: cal[-1] += '\\n'
49                 elif line[0] == ' ':
50                         if not cal: raise InvalidICS, 'First line of ICS must be element'
51                         line = line[1:len(line)]
52                         cal[-1] += line
53                 elif not icalEntry.match(line):
54                         if not cal: raise InvalidICS, 'First line of ICS must be element'
55                         cal[-1] += '\\n' + line
56                 else:
57                         if cal: cal[-1] += '\r\n'
58                         cal.append(line)
59
60         cal[-1] += '\r\n'
61
62         return cal
63
64 def lineSplitter(oldcal, length=75):
65         '''Folds content lines to a specified length, returns a list'''
66
67         cal = []
68         sl = length - 1
69
70         for line in oldcal:
71                 # Line & line ending line ending fit inside length, do nothing
72                 if len(line.rstrip()) <= length:
73                         cal.append(line)
74                 else:
75                         brokenline = [line[0:length] + '\r\n']
76                         ll = length
77                         while ll < len(line.rstrip('\r\n')) + 1:
78                                 brokenline.append(' ' + line[ll:sl+ll].rstrip('\r\n') + '\r\n')
79                                 ll += sl
80                         cal += brokenline
81
82         return cal
83
84 if __name__ == '__main__':
85         # If the user passed us a 'stdin' argument, we'll go with that,
86         # otherwise we'll try for a url opener
87
88         parser = OptionParser('usage: %prog [options] url')
89         parser.add_option('-s', '--stdin', action='store_true', dest='stdin',
90                 default=False, help='Take a calendar from standard input')
91         parser.add_option('-o', '--output', dest='outfile', default='',
92                 help='Specify output file (defaults to standard output)')
93
94         (options, args) = parser.parse_args()
95
96         if not args and not options.stdin:
97                 parser.print_usage()
98                 sys.exit(0)
99
100         url = args[0]
101
102         # Work out what url parsers we're going to need based on what the user
103         # gave us on the command line - we do like files after all
104         parsedURL = urlparse.urlparse(url)
105         http = 'http' in parsedURL[0]
106
107         if not parsedURL[0]: u = False
108         else: u = True
109
110         if not options.stdin and http:
111                 try:
112                         import httplib2
113                 except ImportError:
114                         import urllib2
115
116         # Try and play nice with HTTP servers unless something goes wrong. We don't
117         # really care about this cache so it can be somewhere volatile
118         h = False
119         if 'httplib2' in sys.modules:
120                 try: h = httplib2.Http('.httplib2-cache')
121                 except OSError: h = httplib2.Http()
122
123         if not options.stdin and (not http or not 'httplib2' in sys.modules):
124                 import urllib2
125
126         try:
127                 content = u and (h and h.request(url)[1] or urllib2.urlopen(url).read())
128         except (ValueError, urllib2.URLError), e:
129                 sys.stderr.write('%s\n'%e)
130                 sys.exit(1)
131
132         if not u:
133                 try: content = open(os.path.abspath(url),'r').read()
134                 except (IOError, OSError), e:
135                         sys.stderr.write('%s\n'%e)
136                         sys.exit(1)
137
138         # RFC5545 and RFC5546 Calendars should be generated UTF-8 and we need to
139         # be able to read ANSI as well. This should take care of us.
140         content = unicode(content, encoding='utf-8')

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