Bug fix: Properly reads from stdin
[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         '''Unfolds a calendar so that items can be parsed'''
37
38         cal = []
39
40         # Strip newlines (
41         for line in oldcal:
42                 line = line.rstrip('\r\n')
43
44                 # Reassemble broken Lines
45                 if not line:
46                         if not cal: continue
47                         else: cal[-1] += '\\n'
48                 elif line[0] == ' ':
49                         if not cal: raise InvalidICS, 'First line of ICS must be element'
50                         line = line[1:len(line)]
51                         cal[-1] += line
52                 elif not icalEntry.match(line):
53                         if not cal: raise InvalidICS, 'First line of ICS must be element'
54                         cal[-1] += '\\n' + line
55                 else:
56                         if cal: cal[-1] += '\r\n'
57                         cal.append(line)
58
59         cal[-1] += '\r\n'
60
61         return cal
62
63 def lineFolder(oldcal, length=75):
64         '''Folds content lines to a specified length, returns a list'''
65
66         cal = []
67         sl = length - 1
68
69         for line in oldcal:
70                 # Line & line ending line ending fit inside length, do nothing
71                 if len(line.rstrip()) <= length:
72                         cal.append(line)
73                 else:
74                         brokenline = [line[0:length] + '\r\n']
75                         ll = length
76                         while ll < len(line.rstrip('\r\n')) + 1:
77                                 brokenline.append(' ' + line[ll:sl+ll].rstrip('\r\n') + '\r\n')
78                                 ll += sl
79                         cal += brokenline
80
81         return cal
82
83 if __name__ == '__main__':
84         from optparse import OptionParser
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         elif not options.stdin:
100                 url = args[0]
101         else:
102                 url = ''
103
104         # Work out what url parsers we're going to need based on what the user
105         # gave us on the command line - we do like files after all
106         parsedURL = urlparse.urlparse(url)
107         http = 'http' in parsedURL[0]
108
109         if not parsedURL[0]: u = False
110         else: u = True
111
112         if not options.stdin and http:
113                 try:
114                         import httplib2
115                 except ImportError:
116                         import urllib2
117
118         # Try and play nice with HTTP servers unless something goes wrong. We don't
119         # really care about this cache (A lot of ics files seem to be generated with
120         # php which hates caching with a passion).
121         h = False
122         if 'httplib2' in sys.modules:
123                 try: h = httplib2.Http('.httplib2-cache')
124                 except OSError: h = httplib2.Http()
125
126         # Load urllib2 if this is not a stdin
127         if not options.stdin and (not http or not 'httplib2' in sys.modules):
128                 import urllib2
129
130         try:
131                 content = u and (h and h.request(url)[1] or urllib2.urlopen(url).read())
132         except (ValueError, urllib2.URLError), e:
133                 sys.stderr.write('%s\n'%e)
134                 sys.exit(1)
135
136         if not u and not options.stdin:
137                 try: content = open(os.path.abspath(url),'r').read()
138                 except (IOError, OSError), e:
139                         sys.stderr.write('%s\n'%e)
140                         sys.exit(1)
141
142         if options.stdin:
143                 content = sys.stdin.read()
144
145         # RFC5545 and RFC5546 New calendars should be generated UTF-8 and we need to
146         # be able to read ANSI as well. This should take care of us.
147         content = unicode(content, encoding='utf-8')
148
149         #return content

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