Merge lp:~salgado/launchpad/remove-crap into lp:launchpad
- remove-crap
- Merge into devel
Status: | Merged |
---|---|
Approved by: | Jonathan Lange |
Approved revision: | no longer in the source branch. |
Merged at revision: | not available |
Proposed branch: | lp:~salgado/launchpad/remove-crap |
Merge into: | lp:launchpad |
Diff against target: |
3508 lines (+0/-3401) 17 files modified
lib/canonical/launchpad/components/cal.py (+0/-89) lib/canonical/launchpad/components/crowd.py (+0/-80) lib/canonical/launchpad/doc/crowd.txt (+0/-124) lib/canonical/launchpad/interfaces/launchpad.py (+0/-20) lib/canonical/launchpad/zcml/configure.zcml (+0/-1) lib/canonical/launchpad/zcml/crowd.zcml (+0/-17) lib/schoolbell/README.txt (+0/-7) lib/schoolbell/__init__.py (+0/-38) lib/schoolbell/browser.py (+0/-71) lib/schoolbell/icalendar.py (+0/-1127) lib/schoolbell/interfaces.py (+0/-396) lib/schoolbell/mixins.py (+0/-314) lib/schoolbell/simple.py (+0/-96) lib/schoolbell/tests/__init__.py (+0/-1) lib/schoolbell/tests/test_icalendar.py (+0/-782) lib/schoolbell/tests/test_schoolbell.py (+0/-74) lib/schoolbell/utils.py (+0/-164) |
To merge this branch: | bzr merge lp:~salgado/launchpad/remove-crap |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Jonathan Lange (community) | Approve | ||
Review via email: mp+21549@code.launchpad.net |
Commit message
Description of the change
Just remove some crap that was no longer used:
lib/schoolbell/
lib/canonical
lib/canonical
= Launchpad lint =
Checking for conflicts. and issues in doctests and templates.
Running jslint, xmllint, pyflakes, and pylint.
Using normal rules.
Linting changed files:
lib/canonical
lib/canonical
== Pyflakes notices ==
lib/canonical/
25: 'UnexpectedForm
25: 'UnsafeFormGetS
25: 'NotFoundError' imported but unused
25: 'IBasicLaunchpa
25: 'IOpenLaunchBag' imported but unused
25: 'ILaunchpadRoot' imported but unused
25: 'ILaunchBag' imported but unused
== Pylint notices ==
lib/canonical/
17: [F0401] Unable to import 'lazr.restful.
Preview Diff
1 | === removed file 'lib/canonical/launchpad/components/cal.py' | |||
2 | --- lib/canonical/launchpad/components/cal.py 2009-07-17 00:26:05 +0000 | |||
3 | +++ lib/canonical/launchpad/components/cal.py 1970-01-01 00:00:00 +0000 | |||
4 | @@ -1,89 +0,0 @@ | |||
5 | 1 | # Copyright 2009 Canonical Ltd. This software is licensed under the | ||
6 | 2 | # GNU Affero General Public License version 3 (see the file LICENSE). | ||
7 | 3 | |||
8 | 4 | """ | ||
9 | 5 | Calendaring for Launchpad | ||
10 | 6 | |||
11 | 7 | This package contains various components that don't fit into database/ | ||
12 | 8 | or browser/. | ||
13 | 9 | """ | ||
14 | 10 | |||
15 | 11 | __metaclass__ = type | ||
16 | 12 | |||
17 | 13 | from zope.interface import implements | ||
18 | 14 | from zope.component import getUtility | ||
19 | 15 | |||
20 | 16 | from canonical.launchpad import _ | ||
21 | 17 | from schoolbell.interfaces import ICalendar | ||
22 | 18 | from canonical.launchpad.interfaces import ( | ||
23 | 19 | ILaunchBag, ILaunchpadCalendar, ILaunchpadMergedCalendar, | ||
24 | 20 | ICalendarSubscriptionSubset) | ||
25 | 21 | |||
26 | 22 | from schoolbell.mixins import CalendarMixin, EditableCalendarMixin | ||
27 | 23 | from schoolbell.icalendar import convert_calendar_to_ical | ||
28 | 24 | |||
29 | 25 | |||
30 | 26 | def calendarFromCalendarOwner(calendarowner): | ||
31 | 27 | """Adapt ICalendarOwner to ICalendar.""" | ||
32 | 28 | return calendarowner.calendar | ||
33 | 29 | |||
34 | 30 | |||
35 | 31 | ############# Merged Calendar ############# | ||
36 | 32 | |||
37 | 33 | |||
38 | 34 | class MergedCalendar(CalendarMixin, EditableCalendarMixin): | ||
39 | 35 | implements(ILaunchpadCalendar, ILaunchpadMergedCalendar) | ||
40 | 36 | |||
41 | 37 | def __init__(self): | ||
42 | 38 | self.id = None | ||
43 | 39 | self.revision = 0 | ||
44 | 40 | self.owner = getUtility(ILaunchBag).user | ||
45 | 41 | if self.owner is None: | ||
46 | 42 | # The merged calendar can not be accessed when the user is | ||
47 | 43 | # not logged in. However this object still needs to be | ||
48 | 44 | # instantiable when not logged in, so that the user gets | ||
49 | 45 | # redirected to the login page when trying to access the | ||
50 | 46 | # calendar, rather than seeing an error page. | ||
51 | 47 | return | ||
52 | 48 | self.subscriptions = ICalendarSubscriptionSubset(self.owner) | ||
53 | 49 | self.title = _('Merged Calendar for %s') % self.owner.displayname | ||
54 | 50 | |||
55 | 51 | def __iter__(self): | ||
56 | 52 | for calendar in self.subscriptions: | ||
57 | 53 | for event in calendar: | ||
58 | 54 | yield event | ||
59 | 55 | |||
60 | 56 | def expand(self, first, last): | ||
61 | 57 | for calendar in self.subscriptions: | ||
62 | 58 | for event in calendar.expand(first, last): | ||
63 | 59 | yield event | ||
64 | 60 | |||
65 | 61 | def addEvent(self, event): | ||
66 | 62 | calendar = self.owner.getOrCreateCalendar() | ||
67 | 63 | calendar.addEvent(event) | ||
68 | 64 | |||
69 | 65 | def removeEvent(self, event): | ||
70 | 66 | calendar = event.calendar | ||
71 | 67 | calendar.removeEvent(event) | ||
72 | 68 | |||
73 | 69 | |||
74 | 70 | ############# iCalendar export ################### | ||
75 | 71 | |||
76 | 72 | class ViewICalendar: | ||
77 | 73 | """Publish an object implementing the ICalendar interface in | ||
78 | 74 | the iCalendar format. This allows desktop calendar clients to | ||
79 | 75 | display the events.""" | ||
80 | 76 | __used_for__ = ICalendar | ||
81 | 77 | |||
82 | 78 | def __init__(self, context, request): | ||
83 | 79 | self.context = context | ||
84 | 80 | self.request = request | ||
85 | 81 | |||
86 | 82 | def __call__(self): | ||
87 | 83 | result = convert_calendar_to_ical(self.context) | ||
88 | 84 | result = '\r\n'.join(result) | ||
89 | 85 | |||
90 | 86 | self.request.response.setHeader('Content-Type', 'text/calendar') | ||
91 | 87 | self.request.response.setHeader('Content-Length', len(result)) | ||
92 | 88 | |||
93 | 89 | return result | ||
94 | 90 | 0 | ||
95 | === removed file 'lib/canonical/launchpad/components/crowd.py' | |||
96 | --- lib/canonical/launchpad/components/crowd.py 2009-06-25 05:30:52 +0000 | |||
97 | +++ lib/canonical/launchpad/components/crowd.py 1970-01-01 00:00:00 +0000 | |||
98 | @@ -1,80 +0,0 @@ | |||
99 | 1 | # Copyright 2009 Canonical Ltd. This software is licensed under the | ||
100 | 2 | # GNU Affero General Public License version 3 (see the file LICENSE). | ||
101 | 3 | |||
102 | 4 | __metaclass__ = type | ||
103 | 5 | |||
104 | 6 | from zope.interface import implements | ||
105 | 7 | |||
106 | 8 | from canonical.launchpad.interfaces import ICrowd, IPerson, ITeam | ||
107 | 9 | |||
108 | 10 | |||
109 | 11 | class CrowdOfOnePerson: | ||
110 | 12 | implements(ICrowd) | ||
111 | 13 | __used_for__ = IPerson | ||
112 | 14 | |||
113 | 15 | def __init__(self, person): | ||
114 | 16 | self.person = person | ||
115 | 17 | |||
116 | 18 | def __contains__(self, person_or_team): | ||
117 | 19 | return person_or_team.id == self.person.id | ||
118 | 20 | |||
119 | 21 | def __add__(self, crowd): | ||
120 | 22 | return CrowdsAddedTogether(crowd, self) | ||
121 | 23 | |||
122 | 24 | |||
123 | 25 | class CrowdOfOneTeam: | ||
124 | 26 | implements(ICrowd) | ||
125 | 27 | __used_for__ = ITeam | ||
126 | 28 | |||
127 | 29 | def __init__(self, team): | ||
128 | 30 | self.team = team | ||
129 | 31 | |||
130 | 32 | def __contains__(self, person_or_team): | ||
131 | 33 | if person_or_team.id == self.team.id: | ||
132 | 34 | return True | ||
133 | 35 | return person_or_team.inTeam(self.team) | ||
134 | 36 | |||
135 | 37 | def __add__(self, crowd): | ||
136 | 38 | return CrowdsAddedTogether(crowd, self) | ||
137 | 39 | |||
138 | 40 | |||
139 | 41 | class CrowdsAddedTogether: | ||
140 | 42 | |||
141 | 43 | implements(ICrowd) | ||
142 | 44 | |||
143 | 45 | def __init__(self, *crowds): | ||
144 | 46 | self.crowds = crowds | ||
145 | 47 | |||
146 | 48 | def __contains__(self, person_or_team): | ||
147 | 49 | for crowd in self.crowds: | ||
148 | 50 | if person_or_team in crowd: | ||
149 | 51 | return True | ||
150 | 52 | return False | ||
151 | 53 | |||
152 | 54 | def __add__(self, crowd): | ||
153 | 55 | return CrowdsAddedTogether(crowd, *self.crowds) | ||
154 | 56 | |||
155 | 57 | |||
156 | 58 | # XXX ddaa 2005-04-01: This shouldn't be in components | ||
157 | 59 | class AnyPersonCrowd: | ||
158 | 60 | |||
159 | 61 | implements(ICrowd) | ||
160 | 62 | |||
161 | 63 | def __contains__(self, person_or_team): | ||
162 | 64 | return IPerson.providedBy(person_or_team) | ||
163 | 65 | |||
164 | 66 | def __add__(self, crowd): | ||
165 | 67 | return CrowdsAddedTogether(crowd, self) | ||
166 | 68 | |||
167 | 69 | # XXX ddaa 2005-04-01: This shouldn't be in components | ||
168 | 70 | class EmptyCrowd: | ||
169 | 71 | |||
170 | 72 | implements(ICrowd) | ||
171 | 73 | |||
172 | 74 | def __contains__(self, person_or_team): | ||
173 | 75 | return False | ||
174 | 76 | |||
175 | 77 | def __add__(self, crowd): | ||
176 | 78 | return crowd | ||
177 | 79 | |||
178 | 80 | |||
179 | 81 | 0 | ||
180 | === removed file 'lib/canonical/launchpad/doc/crowd.txt' | |||
181 | --- lib/canonical/launchpad/doc/crowd.txt 2009-08-13 15:12:16 +0000 | |||
182 | +++ lib/canonical/launchpad/doc/crowd.txt 1970-01-01 00:00:00 +0000 | |||
183 | @@ -1,124 +0,0 @@ | |||
184 | 1 | |||
185 | 2 | |||
186 | 3 | A person is adaptable to ICrowd. | ||
187 | 4 | |||
188 | 5 | >>> from canonical.launchpad.interfaces import IPersonSet, ICrowd | ||
189 | 6 | >>> from zope.component import getUtility | ||
190 | 7 | >>> personset = getUtility(IPersonSet) | ||
191 | 8 | >>> mark = personset.getByName('mark') | ||
192 | 9 | >>> print mark.name | ||
193 | 10 | mark | ||
194 | 11 | >>> mark_crowd = ICrowd(mark) | ||
195 | 12 | |||
196 | 13 | The person is in that crowd. | ||
197 | 14 | |||
198 | 15 | >>> mark in mark_crowd | ||
199 | 16 | True | ||
200 | 17 | |||
201 | 18 | |||
202 | 19 | A team is adaptable to ICrowd, but it gets a different adapter than that used | ||
203 | 20 | for a person. | ||
204 | 21 | |||
205 | 22 | >>> vcs_imports = personset.getByName('vcs-imports') | ||
206 | 23 | >>> print vcs_imports.name | ||
207 | 24 | vcs-imports | ||
208 | 25 | >>> vcs_imports_crowd = ICrowd(vcs_imports) | ||
209 | 26 | |||
210 | 27 | The team is in that crowd. | ||
211 | 28 | |||
212 | 29 | >>> vcs_imports in vcs_imports_crowd | ||
213 | 30 | True | ||
214 | 31 | |||
215 | 32 | mark is not in that crowd, because he is not in the vcs-imports team. | ||
216 | 33 | |||
217 | 34 | >>> mark in vcs_imports_crowd | ||
218 | 35 | False | ||
219 | 36 | |||
220 | 37 | lifeless is in the vcs-imports team. So, lifeless is in that crowd. | ||
221 | 38 | |||
222 | 39 | >>> lifeless = personset.getByName('lifeless') | ||
223 | 40 | >>> print lifeless.name | ||
224 | 41 | lifeless | ||
225 | 42 | >>> lifeless in vcs_imports_crowd | ||
226 | 43 | True | ||
227 | 44 | |||
228 | 45 | Adding mark_crowd to the vcs_imports_crowd gives us a crowd that contains | ||
229 | 46 | mark and the vcs-imports team and lifeless, but not stevea. | ||
230 | 47 | This tests ICrowd(team).__add__. | ||
231 | 48 | |||
232 | 49 | >>> combined_crowd = vcs_imports_crowd + mark_crowd | ||
233 | 50 | >>> stevea = personset.getByName('stevea') | ||
234 | 51 | >>> stevea not in combined_crowd | ||
235 | 52 | True | ||
236 | 53 | >>> lifeless in combined_crowd | ||
237 | 54 | True | ||
238 | 55 | >>> mark in combined_crowd | ||
239 | 56 | True | ||
240 | 57 | >>> vcs_imports in combined_crowd | ||
241 | 58 | True | ||
242 | 59 | |||
243 | 60 | Now, to try it the other way around: adding vcs_imports_crowd to mark_crowd. | ||
244 | 61 | This tests ICrowd(person).__add__. | ||
245 | 62 | |||
246 | 63 | >>> combined_crowd = mark_crowd + vcs_imports_crowd | ||
247 | 64 | >>> lifeless in combined_crowd | ||
248 | 65 | True | ||
249 | 66 | >>> mark in combined_crowd | ||
250 | 67 | True | ||
251 | 68 | >>> vcs_imports in combined_crowd | ||
252 | 69 | True | ||
253 | 70 | |||
254 | 71 | There is an AnyPersonCrowd that contains any person or team. | ||
255 | 72 | |||
256 | 73 | >>> from canonical.launchpad.components.crowd import AnyPersonCrowd | ||
257 | 74 | >>> mark in AnyPersonCrowd() | ||
258 | 75 | True | ||
259 | 76 | >>> vcs_imports in AnyPersonCrowd() | ||
260 | 77 | True | ||
261 | 78 | >>> vcs_imports_crowd in AnyPersonCrowd() | ||
262 | 79 | False | ||
263 | 80 | |||
264 | 81 | Adding an AnyPersonCrowd to some other crowd works as expected. | ||
265 | 82 | |||
266 | 83 | >>> combined_crowd = mark_crowd + AnyPersonCrowd() | ||
267 | 84 | >>> mark in combined_crowd | ||
268 | 85 | True | ||
269 | 86 | >>> stevea in combined_crowd | ||
270 | 87 | True | ||
271 | 88 | |||
272 | 89 | Same goes for the other way around. | ||
273 | 90 | |||
274 | 91 | >>> combined_crowd = AnyPersonCrowd() + mark_crowd | ||
275 | 92 | >>> mark in combined_crowd | ||
276 | 93 | True | ||
277 | 94 | >>> stevea in combined_crowd | ||
278 | 95 | True | ||
279 | 96 | |||
280 | 97 | |||
281 | 98 | The EmptyCrowd doens't contain anything. | ||
282 | 99 | |||
283 | 100 | >>> from canonical.launchpad.components.crowd import EmptyCrowd | ||
284 | 101 | >>> mark in EmptyCrowd() | ||
285 | 102 | False | ||
286 | 103 | >>> vcs_imports_crowd in EmptyCrowd() | ||
287 | 104 | False | ||
288 | 105 | |||
289 | 106 | Adding a crowd to EmptyCrowd, and vice versa, gives you essentially that crowd. | ||
290 | 107 | |||
291 | 108 | >>> combined_crowd = EmptyCrowd() + vcs_imports_crowd | ||
292 | 109 | >>> vcs_imports in combined_crowd | ||
293 | 110 | True | ||
294 | 111 | >>> mark in combined_crowd | ||
295 | 112 | False | ||
296 | 113 | >>> lifeless in combined_crowd | ||
297 | 114 | True | ||
298 | 115 | |||
299 | 116 | >>> combined_crowd = vcs_imports_crowd + EmptyCrowd() | ||
300 | 117 | >>> vcs_imports in combined_crowd | ||
301 | 118 | True | ||
302 | 119 | >>> mark in combined_crowd | ||
303 | 120 | False | ||
304 | 121 | >>> lifeless in combined_crowd | ||
305 | 122 | True | ||
306 | 123 | |||
307 | 124 | |||
308 | 125 | 0 | ||
309 | === modified file 'lib/canonical/launchpad/interfaces/launchpad.py' | |||
310 | --- lib/canonical/launchpad/interfaces/launchpad.py 2010-02-24 23:18:40 +0000 | |||
311 | +++ lib/canonical/launchpad/interfaces/launchpad.py 2010-03-17 12:06:32 +0000 | |||
312 | @@ -34,7 +34,6 @@ | |||
313 | 34 | 'IAuthServerApplication', | 34 | 'IAuthServerApplication', |
314 | 35 | 'IBasicLaunchpadRequest', | 35 | 'IBasicLaunchpadRequest', |
315 | 36 | 'IBazaarApplication', | 36 | 'IBazaarApplication', |
316 | 37 | 'ICrowd', | ||
317 | 38 | 'IFeedsApplication', | 37 | 'IFeedsApplication', |
318 | 39 | 'IHasAppointedDriver', | 38 | 'IHasAppointedDriver', |
319 | 40 | 'IHasAssignee', | 39 | 'IHasAssignee', |
320 | @@ -244,25 +243,6 @@ | |||
321 | 244 | """ | 243 | """ |
322 | 245 | 244 | ||
323 | 246 | 245 | ||
324 | 247 | class ICrowd(Interface): | ||
325 | 248 | |||
326 | 249 | def __contains__(person_or_team_or_anything): | ||
327 | 250 | """Return True if person_or_team_or_anything is in the crowd. | ||
328 | 251 | |||
329 | 252 | Note that a particular crowd can choose to answer 'True' to this | ||
330 | 253 | question, if that is what it is supposed to do. So, crowds that | ||
331 | 254 | contain other crowds will want to allow the other crowds the | ||
332 | 255 | opportunity to answer __contains__ before that crowd does. | ||
333 | 256 | """ | ||
334 | 257 | |||
335 | 258 | def __add__(crowd): | ||
336 | 259 | """Return a new ICrowd that is this crowd added to the given crowd. | ||
337 | 260 | |||
338 | 261 | The returned crowd contains the person or teams in | ||
339 | 262 | both this crowd and the given crowd. | ||
340 | 263 | """ | ||
341 | 264 | |||
342 | 265 | |||
343 | 266 | class IPrivateMaloneApplication(ILaunchpadApplication): | 246 | class IPrivateMaloneApplication(ILaunchpadApplication): |
344 | 267 | """Private application root for malone.""" | 247 | """Private application root for malone.""" |
345 | 268 | 248 | ||
346 | 269 | 249 | ||
347 | === modified file 'lib/canonical/launchpad/zcml/configure.zcml' | |||
348 | --- lib/canonical/launchpad/zcml/configure.zcml 2010-02-18 17:00:54 +0000 | |||
349 | +++ lib/canonical/launchpad/zcml/configure.zcml 2010-03-17 12:06:32 +0000 | |||
350 | @@ -12,7 +12,6 @@ | |||
351 | 12 | <include file="account.zcml" /> | 12 | <include file="account.zcml" /> |
352 | 13 | <include file="batchnavigator.zcml" /> | 13 | <include file="batchnavigator.zcml" /> |
353 | 14 | <include file="binaryandsourcepackagename.zcml" /> | 14 | <include file="binaryandsourcepackagename.zcml" /> |
354 | 15 | <include file="crowd.zcml" /> | ||
355 | 16 | <include file="datetime.zcml" /> | 15 | <include file="datetime.zcml" /> |
356 | 17 | <include file="decoratedresultset.zcml" /> | 16 | <include file="decoratedresultset.zcml" /> |
357 | 18 | <include file="emailaddress.zcml" /> | 17 | <include file="emailaddress.zcml" /> |
358 | 19 | 18 | ||
359 | === removed file 'lib/canonical/launchpad/zcml/crowd.zcml' | |||
360 | --- lib/canonical/launchpad/zcml/crowd.zcml 2009-07-13 18:15:02 +0000 | |||
361 | +++ lib/canonical/launchpad/zcml/crowd.zcml 1970-01-01 00:00:00 +0000 | |||
362 | @@ -1,17 +0,0 @@ | |||
363 | 1 | <!-- Copyright 2009 Canonical Ltd. This software is licensed under the | ||
364 | 2 | GNU Affero General Public License version 3 (see the file LICENSE). | ||
365 | 3 | --> | ||
366 | 4 | |||
367 | 5 | <configure xmlns="http://namespaces.zope.org/zope"> | ||
368 | 6 | <adapter | ||
369 | 7 | for="canonical.launchpad.interfaces.IPerson" | ||
370 | 8 | provides="canonical.launchpad.interfaces.ICrowd" | ||
371 | 9 | factory="canonical.launchpad.components.crowd.CrowdOfOnePerson" | ||
372 | 10 | /> | ||
373 | 11 | <adapter | ||
374 | 12 | for="canonical.launchpad.interfaces.ITeam" | ||
375 | 13 | provides="canonical.launchpad.interfaces.ICrowd" | ||
376 | 14 | factory="canonical.launchpad.components.crowd.CrowdOfOneTeam" | ||
377 | 15 | /> | ||
378 | 16 | </configure> | ||
379 | 17 | |||
380 | 18 | 0 | ||
381 | === removed symlink 'lib/mercurial' | |||
382 | === target was u'../sourcecode/mercurial/mercurial' | |||
383 | === removed directory 'lib/schoolbell' | |||
384 | === removed file 'lib/schoolbell/README.txt' | |||
385 | --- lib/schoolbell/README.txt 2005-10-31 18:29:12 +0000 | |||
386 | +++ lib/schoolbell/README.txt 1970-01-01 00:00:00 +0000 | |||
387 | @@ -1,7 +0,0 @@ | |||
388 | 1 | SchoolBell | ||
389 | 2 | ========== | ||
390 | 3 | |||
391 | 4 | SchoolBell is a calendaring library for Zope 3. | ||
392 | 5 | |||
393 | 6 | See the docstring of __init__.py for a list of features and shortcomings. | ||
394 | 7 | |||
395 | 8 | 0 | ||
396 | === removed file 'lib/schoolbell/__init__.py' | |||
397 | --- lib/schoolbell/__init__.py 2005-10-31 18:29:12 +0000 | |||
398 | +++ lib/schoolbell/__init__.py 1970-01-01 00:00:00 +0000 | |||
399 | @@ -1,38 +0,0 @@ | |||
400 | 1 | """ | ||
401 | 2 | Calendaring for Zope 3 applications. | ||
402 | 3 | |||
403 | 4 | SchoolBell is a calendaring library for Zope 3. Its main features are | ||
404 | 5 | (currently most of these features are science fiction): | ||
405 | 6 | |||
406 | 7 | - It can parse and generate iCalendar files. Only a subset of the iCalendar | ||
407 | 8 | spec is supported, however it is a sensible subset that should be enough for | ||
408 | 9 | interoperation with desktop calendaring applications like Apple's iCal, | ||
409 | 10 | Mozilla Calendar, Evolution, and KOrganizer. | ||
410 | 11 | |||
411 | 12 | - It has browser views for presenting calendars in various ways (daily, weekly, | ||
412 | 13 | monthly, yearly views). | ||
413 | 14 | |||
414 | 15 | - It is storage independent -- your application could store the calendar in | ||
415 | 16 | ZODB, in a relational database, or elsewhere, as long as the storage | ||
416 | 17 | component provides the necessary interface. A default content component | ||
417 | 18 | that stores data in ZODB is provided. | ||
418 | 19 | |||
419 | 20 | - You can also generate calendars on the fly from other data (e.g. a bug | ||
420 | 21 | tracking system). These calendars can be read-only (simpler) or read-write. | ||
421 | 22 | |||
422 | 23 | - You can display several calendars in a single view by using calendar | ||
423 | 24 | composition. | ||
424 | 25 | |||
425 | 26 | - It supports recurring events (daily, weekly, monthly and yearly). | ||
426 | 27 | |||
427 | 28 | Things that are not currently supported: | ||
428 | 29 | |||
429 | 30 | - Timezone handling (UTC times are converted into server's local time in the | ||
430 | 31 | iCalendar parser, but that's all). | ||
431 | 32 | |||
432 | 33 | - All-day events (that is, events that only specify the date but not the time). | ||
433 | 34 | |||
434 | 35 | - Informing the user when uploaded iCalendar files use features that are not | ||
435 | 36 | supported by SchoolBell. | ||
436 | 37 | |||
437 | 38 | """ | ||
438 | 39 | 0 | ||
439 | === removed file 'lib/schoolbell/browser.py' | |||
440 | --- lib/schoolbell/browser.py 2005-10-31 18:29:12 +0000 | |||
441 | +++ lib/schoolbell/browser.py 1970-01-01 00:00:00 +0000 | |||
442 | @@ -1,71 +0,0 @@ | |||
443 | 1 | r""" | ||
444 | 2 | Browser views for schoolbell. | ||
445 | 3 | |||
446 | 4 | iCalendar views | ||
447 | 5 | --------------- | ||
448 | 6 | |||
449 | 7 | CalendarICalendarView can export calendars in iCalendar format | ||
450 | 8 | |||
451 | 9 | >>> from datetime import datetime, timedelta | ||
452 | 10 | >>> from schoolbell.simple import ImmutableCalendar, SimpleCalendarEvent | ||
453 | 11 | >>> event = SimpleCalendarEvent(datetime(2004, 12, 16, 11, 46, 16), | ||
454 | 12 | ... timedelta(hours=1), "doctests", | ||
455 | 13 | ... location=u"Matar\u00f3", | ||
456 | 14 | ... unique_id="12345678-5432@example.com") | ||
457 | 15 | >>> calendar = ImmutableCalendar([event]) | ||
458 | 16 | |||
459 | 17 | >>> from zope.publisher.browser import TestRequest | ||
460 | 18 | >>> view = CalendarICalendarView() | ||
461 | 19 | >>> view.context = calendar | ||
462 | 20 | >>> view.request = TestRequest() | ||
463 | 21 | >>> output = view.show() | ||
464 | 22 | |||
465 | 23 | >>> lines = output.splitlines(True) | ||
466 | 24 | >>> from pprint import pprint | ||
467 | 25 | >>> pprint(lines) | ||
468 | 26 | ['BEGIN:VCALENDAR\r\n', | ||
469 | 27 | 'VERSION:2.0\r\n', | ||
470 | 28 | 'PRODID:-//SchoolTool.org/NONSGML SchoolBell//EN\r\n', | ||
471 | 29 | 'BEGIN:VEVENT\r\n', | ||
472 | 30 | 'UID:12345678-5432@example.com\r\n', | ||
473 | 31 | 'SUMMARY:doctests\r\n', | ||
474 | 32 | 'LOCATION:Matar\xc3\xb3\r\n', | ||
475 | 33 | 'DTSTART:20041216T114616\r\n', | ||
476 | 34 | 'DURATION:PT1H\r\n', | ||
477 | 35 | 'DTSTAMP:...\r\n', | ||
478 | 36 | 'END:VEVENT\r\n', | ||
479 | 37 | 'END:VCALENDAR'] | ||
480 | 38 | |||
481 | 39 | XXX: Should the last line also end in '\r\n'? Go read RFC 2445 and experiment | ||
482 | 40 | with calendaring clients. | ||
483 | 41 | |||
484 | 42 | Register the iCalendar read view in ZCML as | ||
485 | 43 | |||
486 | 44 | <browser:page | ||
487 | 45 | for="schoolbell.interfaces.ICalendar" | ||
488 | 46 | name="calendar.ics" | ||
489 | 47 | permission="zope.Public" | ||
490 | 48 | class="schoolbell.browser.CalendarICalendarView" | ||
491 | 49 | attribute="show" | ||
492 | 50 | /> | ||
493 | 51 | |||
494 | 52 | """ | ||
495 | 53 | |||
496 | 54 | from schoolbell.icalendar import convert_calendar_to_ical | ||
497 | 55 | |||
498 | 56 | __metaclass__ = type | ||
499 | 57 | |||
500 | 58 | |||
501 | 59 | class CalendarICalendarView: | ||
502 | 60 | """RFC 2445 (ICalendar) view for calendars.""" | ||
503 | 61 | |||
504 | 62 | def show(self): | ||
505 | 63 | data = "\r\n".join(convert_calendar_to_ical(self.context)) | ||
506 | 64 | request = self.request | ||
507 | 65 | if request is not None: | ||
508 | 66 | request.response.setHeader('Content-Type', | ||
509 | 67 | 'text/calendar; charset=UTF-8') | ||
510 | 68 | request.response.setHeader('Content-Length', len(data)) | ||
511 | 69 | |||
512 | 70 | return data | ||
513 | 71 | |||
514 | 72 | 0 | ||
515 | === removed file 'lib/schoolbell/icalendar.py' | |||
516 | --- lib/schoolbell/icalendar.py 2010-02-09 01:31:05 +0000 | |||
517 | +++ lib/schoolbell/icalendar.py 1970-01-01 00:00:00 +0000 | |||
518 | @@ -1,1127 +0,0 @@ | |||
519 | 1 | r""" | ||
520 | 2 | iCalendar parsing and generating. | ||
521 | 3 | |||
522 | 4 | iCalendar (RFC 2445) is a big and hard-to-read specification. This module | ||
523 | 5 | supports only a subset of it: VEVENT components with a limited set of | ||
524 | 6 | attributes and a limited recurrence model. The subset should be sufficient | ||
525 | 7 | for interoperation with desktop calendaring applications like Apple's iCal, | ||
526 | 8 | Mozilla Calendar, Evolution and KOrganizer. | ||
527 | 9 | |||
528 | 10 | If you have a calendar, you can convert it to an iCalendar file like this: | ||
529 | 11 | |||
530 | 12 | >>> from datetime import datetime, timedelta | ||
531 | 13 | >>> from schoolbell.simple import ImmutableCalendar, SimpleCalendarEvent | ||
532 | 14 | >>> event = SimpleCalendarEvent(datetime(2004, 12, 16, 10, 58, 47), | ||
533 | 15 | ... timedelta(hours=1), "doctests", | ||
534 | 16 | ... location=u"Matar\u00f3", | ||
535 | 17 | ... unique_id="12345678-5432@example.com") | ||
536 | 18 | >>> calendar = ImmutableCalendar([event]) | ||
537 | 19 | |||
538 | 20 | >>> ical_file_as_string = "\r\n".join(convert_calendar_to_ical(calendar)) | ||
539 | 21 | |||
540 | 22 | The returned string is in UTF-8. | ||
541 | 23 | |||
542 | 24 | >>> event.location.encode("UTF-8") in ical_file_as_string | ||
543 | 25 | True | ||
544 | 26 | |||
545 | 27 | You can also parse iCalendar files back into calendars: | ||
546 | 28 | |||
547 | 29 | >>> event_iterator = read_icalendar(ical_file_as_string) | ||
548 | 30 | >>> new_calendar = ImmutableCalendar(event_iterator) | ||
549 | 31 | >>> [e.title for e in new_calendar] | ||
550 | 32 | [u'doctests'] | ||
551 | 33 | |||
552 | 34 | """ | ||
553 | 35 | |||
554 | 36 | import datetime | ||
555 | 37 | import calendar | ||
556 | 38 | import re | ||
557 | 39 | import pytz | ||
558 | 40 | from cStringIO import StringIO | ||
559 | 41 | from schoolbell.simple import SimpleCalendarEvent | ||
560 | 42 | |||
561 | 43 | _utc_tz = pytz.timezone('UTC') | ||
562 | 44 | |||
563 | 45 | def convert_event_to_ical(event): | ||
564 | 46 | r"""Convert an ICalendarEvent to iCalendar VEVENT component. | ||
565 | 47 | |||
566 | 48 | Returns a list of strings (without newlines) in UTF-8. | ||
567 | 49 | |||
568 | 50 | >>> from datetime import datetime, timedelta | ||
569 | 51 | >>> event = SimpleCalendarEvent(datetime(2004, 12, 16, 10, 7, 29), | ||
570 | 52 | ... timedelta(hours=1), "iCal rendering", | ||
571 | 53 | ... location="Big room", | ||
572 | 54 | ... unique_id="12345678-5432@example.com") | ||
573 | 55 | >>> lines = convert_event_to_ical(event) | ||
574 | 56 | >>> print "\n".join(lines) | ||
575 | 57 | BEGIN:VEVENT | ||
576 | 58 | UID:12345678-5432@example.com | ||
577 | 59 | SUMMARY:iCal rendering | ||
578 | 60 | LOCATION:Big room | ||
579 | 61 | DTSTART:20041216T100729 | ||
580 | 62 | DURATION:PT1H | ||
581 | 63 | DTSTAMP:... | ||
582 | 64 | END:VEVENT | ||
583 | 65 | |||
584 | 66 | """ | ||
585 | 67 | dtstamp = datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ") | ||
586 | 68 | result = [ | ||
587 | 69 | "BEGIN:VEVENT", | ||
588 | 70 | "UID:%s" % ical_text(event.unique_id), | ||
589 | 71 | "SUMMARY:%s" % ical_text(event.title)] | ||
590 | 72 | if event.description: | ||
591 | 73 | result.append("DESCRIPTION:%s" % ical_text(event.description)) | ||
592 | 74 | if event.location: | ||
593 | 75 | result.append("LOCATION:%s" % ical_text(event.location)) | ||
594 | 76 | ### if event.recurrence is not None: # TODO | ||
595 | 77 | ### start = event.dtstart | ||
596 | 78 | ### result.extend(event.recurrence.iCalRepresentation(start)) | ||
597 | 79 | result += [ | ||
598 | 80 | "DTSTART:%s" % ical_datetime(event.dtstart), | ||
599 | 81 | "DURATION:%s" % ical_duration(event.duration), | ||
600 | 82 | "DTSTAMP:%s" % dtstamp, | ||
601 | 83 | "END:VEVENT", | ||
602 | 84 | ] | ||
603 | 85 | return result | ||
604 | 86 | |||
605 | 87 | |||
606 | 88 | def convert_calendar_to_ical(calendar): | ||
607 | 89 | r"""Convert an ICalendar to iCalendar VCALENDAR component. | ||
608 | 90 | |||
609 | 91 | Returns a list of strings (without newlines) in UTF-8. They should be | ||
610 | 92 | joined with '\r\n' to get a valid iCalendar file. | ||
611 | 93 | |||
612 | 94 | >>> from schoolbell.simple import ImmutableCalendar | ||
613 | 95 | >>> from schoolbell.simple import SimpleCalendarEvent | ||
614 | 96 | >>> from datetime import datetime, timedelta | ||
615 | 97 | >>> event = SimpleCalendarEvent(datetime(2004, 12, 16, 10, 7, 29), | ||
616 | 98 | ... timedelta(hours=1), "iCal rendering", | ||
617 | 99 | ... location="Big room", | ||
618 | 100 | ... unique_id="12345678-5432@example.com") | ||
619 | 101 | >>> calendar = ImmutableCalendar([event]) | ||
620 | 102 | >>> lines = convert_calendar_to_ical(calendar) | ||
621 | 103 | >>> print "\n".join(lines) | ||
622 | 104 | BEGIN:VCALENDAR | ||
623 | 105 | VERSION:2.0 | ||
624 | 106 | PRODID:-//SchoolTool.org/NONSGML SchoolBell//EN | ||
625 | 107 | BEGIN:VEVENT | ||
626 | 108 | UID:12345678-5432@example.com | ||
627 | 109 | SUMMARY:iCal rendering | ||
628 | 110 | LOCATION:Big room | ||
629 | 111 | DTSTART:20041216T100729 | ||
630 | 112 | DURATION:PT1H | ||
631 | 113 | DTSTAMP:... | ||
632 | 114 | END:VEVENT | ||
633 | 115 | END:VCALENDAR | ||
634 | 116 | |||
635 | 117 | Empty calendars are not allowed by RFC 2445, so we have to invent a dummy | ||
636 | 118 | event: | ||
637 | 119 | |||
638 | 120 | >>> lines = convert_calendar_to_ical(ImmutableCalendar()) | ||
639 | 121 | >>> print "\n".join(lines) | ||
640 | 122 | BEGIN:VCALENDAR | ||
641 | 123 | VERSION:2.0 | ||
642 | 124 | PRODID:-//SchoolTool.org/NONSGML SchoolBell//EN | ||
643 | 125 | BEGIN:VEVENT | ||
644 | 126 | UID:... | ||
645 | 127 | SUMMARY:Empty calendar | ||
646 | 128 | DTSTART:19700101T000000 | ||
647 | 129 | DURATION:P0D | ||
648 | 130 | DTSTAMP:... | ||
649 | 131 | END:VEVENT | ||
650 | 132 | END:VCALENDAR | ||
651 | 133 | |||
652 | 134 | """ | ||
653 | 135 | header = [ | ||
654 | 136 | "BEGIN:VCALENDAR", | ||
655 | 137 | "VERSION:2.0", | ||
656 | 138 | "PRODID:-//SchoolTool.org/NONSGML SchoolBell//EN", | ||
657 | 139 | ] | ||
658 | 140 | footer = [ | ||
659 | 141 | "END:VCALENDAR" | ||
660 | 142 | ] | ||
661 | 143 | events = [] | ||
662 | 144 | for event in calendar: | ||
663 | 145 | events += convert_event_to_ical(event) | ||
664 | 146 | if not events: | ||
665 | 147 | placeholder = SimpleCalendarEvent(datetime.datetime(1970, 1, 1), | ||
666 | 148 | datetime.timedelta(0), | ||
667 | 149 | "Empty calendar") | ||
668 | 150 | events += convert_event_to_ical(placeholder) | ||
669 | 151 | return header + events + footer | ||
670 | 152 | |||
671 | 153 | |||
672 | 154 | def ical_text(value): | ||
673 | 155 | r"""Format value according to iCalendar TEXT escaping rules. | ||
674 | 156 | |||
675 | 157 | Converts Unicode strings to UTF-8 as well. | ||
676 | 158 | |||
677 | 159 | >>> ical_text('Foo') | ||
678 | 160 | 'Foo' | ||
679 | 161 | >>> ical_text(u'Matar\u00f3') | ||
680 | 162 | 'Matar\xc3\xb3' | ||
681 | 163 | >>> ical_text('\\') | ||
682 | 164 | '\\\\' | ||
683 | 165 | >>> ical_text(';') | ||
684 | 166 | '\\;' | ||
685 | 167 | >>> ical_text(',') | ||
686 | 168 | '\\,' | ||
687 | 169 | >>> ical_text('\n') | ||
688 | 170 | '\\n' | ||
689 | 171 | """ | ||
690 | 172 | return (value.encode('UTF-8') | ||
691 | 173 | .replace('\\', '\\\\') | ||
692 | 174 | .replace(';', '\\;') | ||
693 | 175 | .replace(',', '\\,') | ||
694 | 176 | .replace('\n', '\\n')) | ||
695 | 177 | |||
696 | 178 | |||
697 | 179 | def ical_datetime(value): | ||
698 | 180 | """Format a datetime as an iCalendar DATETIME value. | ||
699 | 181 | |||
700 | 182 | >>> from datetime import datetime | ||
701 | 183 | >>> from pytz import timezone | ||
702 | 184 | >>> ical_datetime(datetime(2004, 12, 16, 10, 45, 07)) | ||
703 | 185 | '20041216T104507' | ||
704 | 186 | >>> ical_datetime(datetime(2004, 12, 16, 10, 45, 07, | ||
705 | 187 | ... tzinfo=timezone('Australia/Perth'))) | ||
706 | 188 | '20041216T024507Z' | ||
707 | 189 | |||
708 | 190 | """ | ||
709 | 191 | if value.tzinfo: | ||
710 | 192 | value = value.astimezone(_utc_tz) | ||
711 | 193 | return value.strftime('%Y%m%dT%H%M%SZ') | ||
712 | 194 | return value.strftime('%Y%m%dT%H%M%S') | ||
713 | 195 | |||
714 | 196 | |||
715 | 197 | def ical_duration(value): | ||
716 | 198 | """Format a timedelta as an iCalendar DURATION value. | ||
717 | 199 | |||
718 | 200 | >>> from datetime import timedelta | ||
719 | 201 | >>> ical_duration(timedelta(11)) | ||
720 | 202 | 'P11D' | ||
721 | 203 | >>> ical_duration(timedelta(-14)) | ||
722 | 204 | '-P14D' | ||
723 | 205 | >>> ical_duration(timedelta(1, 7384)) | ||
724 | 206 | 'P1DT2H3M4S' | ||
725 | 207 | >>> ical_duration(timedelta(1, 7380)) | ||
726 | 208 | 'P1DT2H3M' | ||
727 | 209 | >>> ical_duration(timedelta(1, 7200)) | ||
728 | 210 | 'P1DT2H' | ||
729 | 211 | >>> ical_duration(timedelta(0, 7200)) | ||
730 | 212 | 'PT2H' | ||
731 | 213 | >>> ical_duration(timedelta(0, 7384)) | ||
732 | 214 | 'PT2H3M4S' | ||
733 | 215 | >>> ical_duration(timedelta(0, 184)) | ||
734 | 216 | 'PT3M4S' | ||
735 | 217 | >>> ical_duration(timedelta(0, 22)) | ||
736 | 218 | 'PT22S' | ||
737 | 219 | >>> ical_duration(timedelta(0, 3622)) | ||
738 | 220 | 'PT1H0M22S' | ||
739 | 221 | """ | ||
740 | 222 | sign = "" | ||
741 | 223 | if value.days < 0: | ||
742 | 224 | sign = "-" | ||
743 | 225 | timepart = "" | ||
744 | 226 | if value.seconds: | ||
745 | 227 | timepart = "T" | ||
746 | 228 | hours = value.seconds // 3600 | ||
747 | 229 | minutes = value.seconds % 3600 // 60 | ||
748 | 230 | seconds = value.seconds % 60 | ||
749 | 231 | if hours: | ||
750 | 232 | timepart += "%dH" % hours | ||
751 | 233 | if minutes or (hours and seconds): | ||
752 | 234 | timepart += "%dM" % minutes | ||
753 | 235 | if seconds: | ||
754 | 236 | timepart += "%dS" % seconds | ||
755 | 237 | if value.days == 0 and timepart: | ||
756 | 238 | return "%sP%s" % (sign, timepart) | ||
757 | 239 | else: | ||
758 | 240 | return "%sP%dD%s" % (sign, abs(value.days), timepart) | ||
759 | 241 | |||
760 | 242 | |||
761 | 243 | def read_icalendar(icalendar_text): | ||
762 | 244 | """Read an iCalendar file and return calendar events. | ||
763 | 245 | |||
764 | 246 | Returns an iterator over calendar events. | ||
765 | 247 | |||
766 | 248 | `icalendar_text` can be a file object or a string. It is assumed that | ||
767 | 249 | the iCalendar file contains UTF-8 text. | ||
768 | 250 | |||
769 | 251 | Unsuppored features of the iCalendar file (e.g. VTODO components, complex | ||
770 | 252 | recurrence rules, unknown properties) are silently ignored. | ||
771 | 253 | """ | ||
772 | 254 | if isinstance(icalendar_text, str): | ||
773 | 255 | icalendar_text = StringIO(icalendar_text) | ||
774 | 256 | reader = ICalReader(icalendar_text) | ||
775 | 257 | for vevent in reader.iterEvents(): | ||
776 | 258 | # TODO: ignore empty calendar placeholder | ||
777 | 259 | |||
778 | 260 | # Currently SchoolBell does not support all-day events, so we must | ||
779 | 261 | # convert them into ordinary events that last 24 hours | ||
780 | 262 | dtstart = vevent.dtstart | ||
781 | 263 | if not isinstance(dtstart, datetime.datetime): | ||
782 | 264 | dtstart = datetime.datetime.combine(dtstart, | ||
783 | 265 | datetime.time(0)) | ||
784 | 266 | |||
785 | 267 | yield SimpleCalendarEvent(dtstart, vevent.duration, vevent.summary, | ||
786 | 268 | location=vevent.location, | ||
787 | 269 | unique_id=vevent.uid, | ||
788 | 270 | recurrence=vevent.rrule) | ||
789 | 271 | |||
790 | 272 | |||
791 | 273 | # | ||
792 | 274 | # The rest of this module could use some review and refactoring | ||
793 | 275 | # | ||
794 | 276 | |||
795 | 277 | class ICalReader: | ||
796 | 278 | """An object which reads in an iCalendar file. | ||
797 | 279 | |||
798 | 280 | The `iterEvents` method returns an iterator over all VEvent objects | ||
799 | 281 | corresponding to the events in the iCalendar file. | ||
800 | 282 | |||
801 | 283 | Short grammar of iCalendar files (RFC 2445 is the full spec): | ||
802 | 284 | |||
803 | 285 | contentline = name *(";" param ) ":" value CRLF | ||
804 | 286 | ; content line first must be unfolded by replacing CRLF followed by a | ||
805 | 287 | ; single WSP with an empty string | ||
806 | 288 | name = x-name / iana-token | ||
807 | 289 | x-name = "X-" [vendorid "-"] 1*(ALPHA / DIGIT / "-") | ||
808 | 290 | iana-token = 1*(ALPHA / DIGIT / "-") | ||
809 | 291 | vendorid = 3*(ALPHA / DIGIT) | ||
810 | 292 | param = param-name "=" param-value *("," param-value) | ||
811 | 293 | param-name = iana-token / x-token | ||
812 | 294 | param-value = paramtext / quoted-string | ||
813 | 295 | paramtext = *SAFE-CHAR | ||
814 | 296 | value = *VALUE-CHAR | ||
815 | 297 | quoted-string = DQUOTE *QSAFE-CHAR DQUOTE | ||
816 | 298 | |||
817 | 299 | NON-US-ASCII = %x80-F8 | ||
818 | 300 | QSAFE-CHAR = WSP / %x21 / %x23-7E / NON-US-ASCII | ||
819 | 301 | ; Any character except CTLs and DQUOTE | ||
820 | 302 | SAFE-CHAR = WSP / %x21 / %x23-2B / %x2D-39 / %x3C-7E | ||
821 | 303 | / NON-US-ASCII | ||
822 | 304 | ; Any character except CTLs, DQUOTE, ";", ":", "," | ||
823 | 305 | VALUE-CHAR = WSP / %x21-7E / NON-US-ASCII ; anything except CTLs | ||
824 | 306 | CR = %x0D | ||
825 | 307 | LF = %x0A | ||
826 | 308 | CRLF = CR LF | ||
827 | 309 | CTL = %x00-08 / %x0A-1F / %x7F | ||
828 | 310 | ALPHA = %x41-5A / %x61-7A ; A-Z / a-z | ||
829 | 311 | DIGIT = %x30-39 ; 0-9 | ||
830 | 312 | DQUOTE = %x22 ; Quotation Mark | ||
831 | 313 | WSP = SPACE / HTAB | ||
832 | 314 | SPACE = %x20 | ||
833 | 315 | HTAB = %x09 | ||
834 | 316 | """ | ||
835 | 317 | |||
836 | 318 | def __init__(self, file, charset='UTF-8'): | ||
837 | 319 | self.file = file | ||
838 | 320 | self.charset = charset | ||
839 | 321 | |||
840 | 322 | def _parseRow(record_str): | ||
841 | 323 | """Parse a single content line. | ||
842 | 324 | |||
843 | 325 | A content line consists of a property name (optionally followed by a | ||
844 | 326 | number of parameters) and a value, separated by a colon. Parameters | ||
845 | 327 | (if present) are separated from the property name and from each other | ||
846 | 328 | with semicolons. Parameters are of the form name=value; value | ||
847 | 329 | can be double-quoted. | ||
848 | 330 | |||
849 | 331 | Returns a tuple (name, value, param_dict). Case-insensitive values | ||
850 | 332 | (i.e. property names, parameter names, unquoted parameter values) are | ||
851 | 333 | uppercased. | ||
852 | 334 | |||
853 | 335 | Raises ICalParseError on syntax errors. | ||
854 | 336 | |||
855 | 337 | >>> ICalReader._parseRow('foo:bar') | ||
856 | 338 | ('FOO', 'bar', {}) | ||
857 | 339 | >>> ICalReader._parseRow('foo;value=bar:BAZFOO') | ||
858 | 340 | ('FOO', 'BAZFOO', {'VALUE': 'BAR'}) | ||
859 | 341 | """ | ||
860 | 342 | |||
861 | 343 | it = iter(record_str) | ||
862 | 344 | getChar = it.next | ||
863 | 345 | |||
864 | 346 | def err(msg): | ||
865 | 347 | raise ICalParseError("%s in line:\n%s" % (msg, record_str)) | ||
866 | 348 | |||
867 | 349 | try: | ||
868 | 350 | c = getChar() | ||
869 | 351 | # name | ||
870 | 352 | key = '' | ||
871 | 353 | while c.isalnum() or c == '-': | ||
872 | 354 | key += c | ||
873 | 355 | c = getChar() | ||
874 | 356 | if not key: | ||
875 | 357 | err("Missing property name") | ||
876 | 358 | key = key.upper() | ||
877 | 359 | # optional parameters | ||
878 | 360 | params = {} | ||
879 | 361 | while c == ';': | ||
880 | 362 | c = getChar() | ||
881 | 363 | # param name | ||
882 | 364 | param = '' | ||
883 | 365 | while c.isalnum() or c == '-': | ||
884 | 366 | param += c | ||
885 | 367 | c = getChar() | ||
886 | 368 | if not param: | ||
887 | 369 | err("Missing parameter name") | ||
888 | 370 | param = param.upper() | ||
889 | 371 | # = | ||
890 | 372 | if c != '=': | ||
891 | 373 | err("Expected '='") | ||
892 | 374 | # value (or rather a list of values) | ||
893 | 375 | pvalues = [] | ||
894 | 376 | while True: | ||
895 | 377 | c = getChar() | ||
896 | 378 | if c == '"': | ||
897 | 379 | c = getChar() | ||
898 | 380 | pvalue = '' | ||
899 | 381 | while c >= ' ' and c not in ('\177', '"'): | ||
900 | 382 | pvalue += c | ||
901 | 383 | c = getChar() | ||
902 | 384 | # value is case-sensitive in this case | ||
903 | 385 | if c != '"': | ||
904 | 386 | err("Expected '\"'") | ||
905 | 387 | c = getChar() | ||
906 | 388 | else: | ||
907 | 389 | # unquoted value | ||
908 | 390 | pvalue = '' | ||
909 | 391 | while c >= ' ' and c not in ('\177', '"', ';', ':', | ||
910 | 392 | ','): | ||
911 | 393 | pvalue += c | ||
912 | 394 | c = getChar() | ||
913 | 395 | pvalue = pvalue.upper() | ||
914 | 396 | pvalues.append(pvalue) | ||
915 | 397 | if c != ',': | ||
916 | 398 | break | ||
917 | 399 | if len(pvalues) > 1: | ||
918 | 400 | params[param] = pvalues | ||
919 | 401 | else: | ||
920 | 402 | params[param] = pvalues[0] | ||
921 | 403 | # colon and value | ||
922 | 404 | if c != ':': | ||
923 | 405 | err("Expected ':'") | ||
924 | 406 | value = ''.join(it) | ||
925 | 407 | except StopIteration: | ||
926 | 408 | err("Syntax error") | ||
927 | 409 | else: | ||
928 | 410 | return (key, value, params) | ||
929 | 411 | |||
930 | 412 | _parseRow = staticmethod(_parseRow) | ||
931 | 413 | |||
932 | 414 | def _iterRow(self): | ||
933 | 415 | """A generator that returns one record at a time, as a tuple of | ||
934 | 416 | (name, value, params). | ||
935 | 417 | """ | ||
936 | 418 | record = [] | ||
937 | 419 | for line in self.file.readlines(): | ||
938 | 420 | if line[0] in '\t ': | ||
939 | 421 | line = line[1:] | ||
940 | 422 | elif record: | ||
941 | 423 | row = "".join(record).decode(self.charset) | ||
942 | 424 | yield self._parseRow(row) | ||
943 | 425 | record = [] | ||
944 | 426 | if line.endswith('\r\n'): | ||
945 | 427 | record.append(line[:-2]) | ||
946 | 428 | elif line.endswith('\n'): | ||
947 | 429 | # strictly speaking this is a violation of RFC 2445 | ||
948 | 430 | record.append(line[:-1]) | ||
949 | 431 | else: | ||
950 | 432 | # strictly speaking this is a violation of RFC 2445 | ||
951 | 433 | record.append(line) | ||
952 | 434 | if record: | ||
953 | 435 | row = "".join(record).decode(self.charset) | ||
954 | 436 | yield self._parseRow(row) | ||
955 | 437 | |||
956 | 438 | def iterEvents(self): | ||
957 | 439 | """Iterate over all VEVENT objects in an ICalendar file.""" | ||
958 | 440 | iterator = self._iterRow() | ||
959 | 441 | |||
960 | 442 | # Check that the stream begins with BEGIN:VCALENDAR | ||
961 | 443 | try: | ||
962 | 444 | key, value, params = iterator.next() | ||
963 | 445 | if (key, value, params) != ('BEGIN', 'VCALENDAR', {}): | ||
964 | 446 | raise ICalParseError('This is not iCalendar') | ||
965 | 447 | except StopIteration: | ||
966 | 448 | # The file is empty. Mozilla produces a 0-length file when | ||
967 | 449 | # publishing an empty calendar. Let's accept it as a valid | ||
968 | 450 | # calendar that has no events. I'm not sure if a 0-length | ||
969 | 451 | # file is a valid text/calendar object according to RFC 2445. | ||
970 | 452 | raise | ||
971 | 453 | component_stack = ['VCALENDAR'] | ||
972 | 454 | |||
973 | 455 | # Extract all VEVENT components | ||
974 | 456 | obj = None | ||
975 | 457 | for key, value, params in iterator: | ||
976 | 458 | if key == "BEGIN": | ||
977 | 459 | if obj is not None: | ||
978 | 460 | # Subcomponents terminate the processing of a VEVENT | ||
979 | 461 | # component. We can get away with this now, because we're | ||
980 | 462 | # not interested in alarms and RFC 2445 specifies, that all | ||
981 | 463 | # properties inside a VEVENT component ought to precede any | ||
982 | 464 | # VALARM subcomponents. | ||
983 | 465 | obj.validate() | ||
984 | 466 | yield obj | ||
985 | 467 | obj = None | ||
986 | 468 | if not component_stack and value != "VCALENDAR": | ||
987 | 469 | raise ICalParseError("Text outside VCALENDAR component") | ||
988 | 470 | if value == "VEVENT": | ||
989 | 471 | obj = VEvent() | ||
990 | 472 | component_stack.append(value) | ||
991 | 473 | elif key == "END": | ||
992 | 474 | if obj is not None and value == "VEVENT": | ||
993 | 475 | obj.validate() | ||
994 | 476 | yield obj | ||
995 | 477 | obj = None | ||
996 | 478 | if not component_stack or component_stack[-1] != value: | ||
997 | 479 | raise ICalParseError("Mismatched BEGIN/END") | ||
998 | 480 | component_stack.pop() | ||
999 | 481 | elif obj is not None: | ||
1000 | 482 | obj.add(key, value, params) | ||
1001 | 483 | elif not component_stack: | ||
1002 | 484 | raise ICalParseError("Text outside VCALENDAR component") | ||
1003 | 485 | if component_stack: | ||
1004 | 486 | raise ICalParseError("Unterminated components") | ||
1005 | 487 | |||
1006 | 488 | |||
1007 | 489 | def parse_text(value): | ||
1008 | 490 | r"""Parse iCalendar TEXT value. | ||
1009 | 491 | |||
1010 | 492 | >>> parse_text('Foo') | ||
1011 | 493 | 'Foo' | ||
1012 | 494 | >>> parse_text('\\\\') | ||
1013 | 495 | '\\' | ||
1014 | 496 | >>> parse_text('\\;') | ||
1015 | 497 | ';' | ||
1016 | 498 | >>> parse_text('\\,') | ||
1017 | 499 | ',' | ||
1018 | 500 | >>> parse_text('\\n') | ||
1019 | 501 | '\n' | ||
1020 | 502 | >>> parse_text('A string with\\; some\\\\ characters\\nin\\Nit') | ||
1021 | 503 | 'A string with; some\\ characters\nin\nit' | ||
1022 | 504 | >>> parse_text('Unterminated \\') | ||
1023 | 505 | Traceback (most recent call last): | ||
1024 | 506 | ... | ||
1025 | 507 | IndexError: string index out of range | ||
1026 | 508 | |||
1027 | 509 | """ | ||
1028 | 510 | if '\\' not in value: | ||
1029 | 511 | return value | ||
1030 | 512 | out = [] | ||
1031 | 513 | prev = 0 | ||
1032 | 514 | while True: | ||
1033 | 515 | idx = value.find('\\', prev) | ||
1034 | 516 | if idx == -1: | ||
1035 | 517 | break | ||
1036 | 518 | out.append(value[prev:idx]) | ||
1037 | 519 | if value[idx + 1] in 'nN': | ||
1038 | 520 | out.append('\n') | ||
1039 | 521 | else: | ||
1040 | 522 | out.append(value[idx + 1]) | ||
1041 | 523 | prev = idx + 2 | ||
1042 | 524 | out.append(value[prev:]) | ||
1043 | 525 | return "".join(out) | ||
1044 | 526 | |||
1045 | 527 | |||
1046 | 528 | def parse_date(value): | ||
1047 | 529 | """Parse iCalendar DATE value. Returns a date instance. | ||
1048 | 530 | |||
1049 | 531 | >>> parse_date('20030405') | ||
1050 | 532 | datetime.date(2003, 4, 5) | ||
1051 | 533 | >>> parse_date('20030405T060708') | ||
1052 | 534 | Traceback (most recent call last): | ||
1053 | 535 | ... | ||
1054 | 536 | ValueError: Invalid iCalendar date: '20030405T060708' | ||
1055 | 537 | >>> parse_date('') | ||
1056 | 538 | Traceback (most recent call last): | ||
1057 | 539 | ... | ||
1058 | 540 | ValueError: Invalid iCalendar date: '' | ||
1059 | 541 | >>> parse_date('yyyymmdd') | ||
1060 | 542 | Traceback (most recent call last): | ||
1061 | 543 | ... | ||
1062 | 544 | ValueError: Invalid iCalendar date: 'yyyymmdd' | ||
1063 | 545 | """ | ||
1064 | 546 | if len(value) != 8: | ||
1065 | 547 | raise ValueError('Invalid iCalendar date: %r' % value) | ||
1066 | 548 | try: | ||
1067 | 549 | y, m, d = int(value[0:4]), int(value[4:6]), int(value[6:8]) | ||
1068 | 550 | except ValueError: | ||
1069 | 551 | raise ValueError('Invalid iCalendar date: %r' % value) | ||
1070 | 552 | else: | ||
1071 | 553 | return datetime.date(y, m, d) | ||
1072 | 554 | |||
1073 | 555 | |||
1074 | 556 | def parse_date_time(value): | ||
1075 | 557 | """Parse iCalendar DATE-TIME value. Returns a datetime instance. | ||
1076 | 558 | |||
1077 | 559 | A simple usage example: | ||
1078 | 560 | |||
1079 | 561 | >>> parse_date_time('20030405T060708') | ||
1080 | 562 | datetime.datetime(2003, 4, 5, 6, 7, 8) | ||
1081 | 563 | |||
1082 | 564 | Examples of invalid arguments: | ||
1083 | 565 | |||
1084 | 566 | >>> parse_date_time('20030405T060708A') | ||
1085 | 567 | Traceback (most recent call last): | ||
1086 | 568 | ... | ||
1087 | 569 | ValueError: Invalid iCalendar date-time: '20030405T060708A' | ||
1088 | 570 | >>> parse_date_time('') | ||
1089 | 571 | Traceback (most recent call last): | ||
1090 | 572 | ... | ||
1091 | 573 | ValueError: Invalid iCalendar date-time: '' | ||
1092 | 574 | |||
1093 | 575 | For timezone tests see tests.test_icalendar.TestParseDateTime. | ||
1094 | 576 | |||
1095 | 577 | """ | ||
1096 | 578 | datetime_rx = re.compile(r'(\d{4})(\d{2})(\d{2})' | ||
1097 | 579 | r'T(\d{2})(\d{2})(\d{2})(Z?)$') | ||
1098 | 580 | match = datetime_rx.match(value) | ||
1099 | 581 | if match is None: | ||
1100 | 582 | raise ValueError('Invalid iCalendar date-time: %r' % value) | ||
1101 | 583 | y, m, d, hh, mm, ss, utc = match.groups() | ||
1102 | 584 | dt = datetime.datetime(int(y), int(m), int(d), | ||
1103 | 585 | int(hh), int(mm), int(ss)) | ||
1104 | 586 | if utc: | ||
1105 | 587 | # In the future we might want to get the timezone from the iCalendar | ||
1106 | 588 | # file, but for now using the local timezone of the server should | ||
1107 | 589 | # be adequate. | ||
1108 | 590 | timetuple = dt.timetuple() | ||
1109 | 591 | ticks = calendar.timegm(timetuple) | ||
1110 | 592 | dt = datetime.datetime.fromtimestamp(ticks) | ||
1111 | 593 | |||
1112 | 594 | return dt | ||
1113 | 595 | |||
1114 | 596 | |||
1115 | 597 | def parse_duration(value): | ||
1116 | 598 | """Parse iCalendar DURATION value. Returns a timedelta instance. | ||
1117 | 599 | |||
1118 | 600 | >>> parse_duration('+P11D') | ||
1119 | 601 | datetime.timedelta(11) | ||
1120 | 602 | >>> parse_duration('-P2W') | ||
1121 | 603 | datetime.timedelta(-14) | ||
1122 | 604 | >>> parse_duration('P1DT2H3M4S') | ||
1123 | 605 | datetime.timedelta(1, 7384) | ||
1124 | 606 | >>> parse_duration('P1DT2H3M') | ||
1125 | 607 | datetime.timedelta(1, 7380) | ||
1126 | 608 | >>> parse_duration('P1DT2H') | ||
1127 | 609 | datetime.timedelta(1, 7200) | ||
1128 | 610 | >>> parse_duration('PT2H') | ||
1129 | 611 | datetime.timedelta(0, 7200) | ||
1130 | 612 | >>> parse_duration('PT2H3M4S') | ||
1131 | 613 | datetime.timedelta(0, 7384) | ||
1132 | 614 | >>> parse_duration('PT3M4S') | ||
1133 | 615 | datetime.timedelta(0, 184) | ||
1134 | 616 | >>> parse_duration('PT22S') | ||
1135 | 617 | datetime.timedelta(0, 22) | ||
1136 | 618 | >>> parse_duration('') | ||
1137 | 619 | Traceback (most recent call last): | ||
1138 | 620 | ... | ||
1139 | 621 | ValueError: Invalid iCalendar duration: '' | ||
1140 | 622 | >>> parse_duration('xyzzy') | ||
1141 | 623 | Traceback (most recent call last): | ||
1142 | 624 | ... | ||
1143 | 625 | ValueError: Invalid iCalendar duration: 'xyzzy' | ||
1144 | 626 | >>> parse_duration('P') | ||
1145 | 627 | Traceback (most recent call last): | ||
1146 | 628 | ... | ||
1147 | 629 | ValueError: Invalid iCalendar duration: 'P' | ||
1148 | 630 | >>> parse_duration('P1WT2H') | ||
1149 | 631 | Traceback (most recent call last): | ||
1150 | 632 | ... | ||
1151 | 633 | ValueError: Invalid iCalendar duration: 'P1WT2H' | ||
1152 | 634 | """ | ||
1153 | 635 | date_part = r'(\d+)D' | ||
1154 | 636 | time_part = r'T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?' | ||
1155 | 637 | datetime_part = '(?:%s)?(?:%s)?' % (date_part, time_part) | ||
1156 | 638 | weeks_part = r'(\d+)W' | ||
1157 | 639 | duration_rx = re.compile(r'([-+]?)P(?:%s|%s)$' | ||
1158 | 640 | % (weeks_part, datetime_part)) | ||
1159 | 641 | match = duration_rx.match(value) | ||
1160 | 642 | if match is None: | ||
1161 | 643 | raise ValueError('Invalid iCalendar duration: %r' % value) | ||
1162 | 644 | sign, weeks, days, hours, minutes, seconds = match.groups() | ||
1163 | 645 | if weeks: | ||
1164 | 646 | value = datetime.timedelta(weeks=int(weeks)) | ||
1165 | 647 | else: | ||
1166 | 648 | if (days is None and hours is None | ||
1167 | 649 | and minutes is None and seconds is None): | ||
1168 | 650 | raise ValueError('Invalid iCalendar duration: %r' | ||
1169 | 651 | % value) | ||
1170 | 652 | value = datetime.timedelta(days=int(days or 0), | ||
1171 | 653 | hours=int(hours or 0), | ||
1172 | 654 | minutes=int(minutes or 0), | ||
1173 | 655 | seconds=int(seconds or 0)) | ||
1174 | 656 | if sign == '-': | ||
1175 | 657 | value = -value | ||
1176 | 658 | return value | ||
1177 | 659 | |||
1178 | 660 | |||
1179 | 661 | def parse_period(value): | ||
1180 | 662 | """Parse iCalendar PERIOD value. Returns a Period instance. | ||
1181 | 663 | |||
1182 | 664 | >>> p = parse_period('20030405T060708/20030405T060709') | ||
1183 | 665 | >>> print repr(p).replace('),', '),\\n ') | ||
1184 | 666 | Period(datetime.datetime(2003, 4, 5, 6, 7, 8), | ||
1185 | 667 | datetime.datetime(2003, 4, 5, 6, 7, 9)) | ||
1186 | 668 | >>> parse_period('20030405T060708/PT1H1M1S') | ||
1187 | 669 | Period(datetime.datetime(2003, 4, 5, 6, 7, 8), datetime.timedelta(0, 3661)) | ||
1188 | 670 | >>> parse_period('xyzzy') | ||
1189 | 671 | Traceback (most recent call last): | ||
1190 | 672 | ... | ||
1191 | 673 | ValueError: Invalid iCalendar period: 'xyzzy' | ||
1192 | 674 | >>> parse_period('foo/foe') | ||
1193 | 675 | Traceback (most recent call last): | ||
1194 | 676 | ... | ||
1195 | 677 | ValueError: Invalid iCalendar period: 'foo/foe' | ||
1196 | 678 | """ | ||
1197 | 679 | parts = value.split('/') | ||
1198 | 680 | if len(parts) != 2: | ||
1199 | 681 | raise ValueError('Invalid iCalendar period: %r' % value) | ||
1200 | 682 | try: | ||
1201 | 683 | start = parse_date_time(parts[0]) | ||
1202 | 684 | try: | ||
1203 | 685 | end_or_duration = parse_date_time(parts[1]) | ||
1204 | 686 | except ValueError: | ||
1205 | 687 | end_or_duration = parse_duration(parts[1]) | ||
1206 | 688 | except ValueError: | ||
1207 | 689 | raise ValueError('Invalid iCalendar period: %r' % value) | ||
1208 | 690 | else: | ||
1209 | 691 | return Period(start, end_or_duration) | ||
1210 | 692 | |||
1211 | 693 | |||
1212 | 694 | ## TODO: implement recurrences | ||
1213 | 695 | |||
1214 | 696 | ## def _parse_recurrence_weekly(args): | ||
1215 | 697 | ## """Parse iCalendar weekly recurrence rule. | ||
1216 | 698 | ## | ||
1217 | 699 | ## args is a mapping from attribute names in RRULE to their string values. | ||
1218 | 700 | ## | ||
1219 | 701 | ## >>> _parse_recurrence_weekly({}) | ||
1220 | 702 | ## WeeklyRecurrenceRule(1, None, None, (), ()) | ||
1221 | 703 | ## >>> _parse_recurrence_weekly({'BYDAY': 'WE'}) | ||
1222 | 704 | ## WeeklyRecurrenceRule(1, None, None, (), (2,)) | ||
1223 | 705 | ## >>> _parse_recurrence_weekly({'BYDAY': 'MO,WE,SU'}) | ||
1224 | 706 | ## WeeklyRecurrenceRule(1, None, None, (), (0, 2, 6)) | ||
1225 | 707 | ## | ||
1226 | 708 | ## """ | ||
1227 | 709 | ## from schooltool.cal import WeeklyRecurrenceRule | ||
1228 | 710 | ## weekdays = [] | ||
1229 | 711 | ## days = args.get('BYDAY', None) | ||
1230 | 712 | ## if days is not None: | ||
1231 | 713 | ## for day in days.split(','): | ||
1232 | 714 | ## weekdays.append(ical_weekdays.index(day)) | ||
1233 | 715 | ## return WeeklyRecurrenceRule(weekdays=weekdays) | ||
1234 | 716 | ## | ||
1235 | 717 | ## | ||
1236 | 718 | ## def _parse_recurrence_monthly(args): | ||
1237 | 719 | ## """Parse iCalendar monthly recurrence rule. | ||
1238 | 720 | ## | ||
1239 | 721 | ## args is a mapping from attribute names in RRULE to their string values. | ||
1240 | 722 | ## | ||
1241 | 723 | ## Month-day recurrency is the default: | ||
1242 | 724 | ## | ||
1243 | 725 | ## >>> _parse_recurrence_monthly({}) | ||
1244 | 726 | ## MonthlyRecurrenceRule(1, None, None, (), 'monthday') | ||
1245 | 727 | ## | ||
1246 | 728 | ## 3rd Tuesday in a month: | ||
1247 | 729 | ## | ||
1248 | 730 | ## >>> _parse_recurrence_monthly({'BYDAY': '3TU'}) | ||
1249 | 731 | ## MonthlyRecurrenceRule(1, None, None, (), 'weekday') | ||
1250 | 732 | ## | ||
1251 | 733 | ## Last Wednesday: | ||
1252 | 734 | ## | ||
1253 | 735 | ## >>> _parse_recurrence_monthly({'BYDAY': '-1WE'}) | ||
1254 | 736 | ## MonthlyRecurrenceRule(1, None, None, (), 'lastweekday') | ||
1255 | 737 | ## """ | ||
1256 | 738 | ## from schooltool.cal import MonthlyRecurrenceRule | ||
1257 | 739 | ## if 'BYDAY' in args: | ||
1258 | 740 | ## if args['BYDAY'][0] == '-': | ||
1259 | 741 | ## monthly = 'lastweekday' | ||
1260 | 742 | ## else: | ||
1261 | 743 | ## monthly = 'weekday' | ||
1262 | 744 | ## else: | ||
1263 | 745 | ## monthly = 'monthday' | ||
1264 | 746 | ## return MonthlyRecurrenceRule(monthly=monthly) | ||
1265 | 747 | ## | ||
1266 | 748 | ## | ||
1267 | 749 | ## def parse_recurrence_rule(value): | ||
1268 | 750 | ## """Parse iCalendar RRULE entry. | ||
1269 | 751 | ## | ||
1270 | 752 | ## Returns the corresponding subclass of RecurrenceRule. | ||
1271 | 753 | ## | ||
1272 | 754 | ## params is a mapping from attribute names in RRULE to their string values, | ||
1273 | 755 | ## | ||
1274 | 756 | ## A trivial example of a daily recurrence: | ||
1275 | 757 | ## | ||
1276 | 758 | ## >>> parse_recurrence_rule('FREQ=DAILY') | ||
1277 | 759 | ## DailyRecurrenceRule(1, None, None, ()) | ||
1278 | 760 | ## | ||
1279 | 761 | ## A slightly more complex example: | ||
1280 | 762 | ## | ||
1281 | 763 | ## >>> parse_recurrence_rule('FREQ=DAILY;INTERVAL=5;COUNT=7') | ||
1282 | 764 | ## DailyRecurrenceRule(5, 7, None, ()) | ||
1283 | 765 | ## | ||
1284 | 766 | ## An example that includes use of UNTIL: | ||
1285 | 767 | ## | ||
1286 | 768 | ## >>> parse_recurrence_rule('FREQ=DAILY;UNTIL=20041008T000000') | ||
1287 | 769 | ## DailyRecurrenceRule(1, None, datetime.datetime(2004, 10, 8, 0, 0), ()) | ||
1288 | 770 | ## >>> parse_recurrence_rule('FREQ=DAILY;UNTIL=20041008') | ||
1289 | 771 | ## DailyRecurrenceRule(1, None, datetime.datetime(2004, 10, 8, 0, 0), ()) | ||
1290 | 772 | ## | ||
1291 | 773 | ## Of course, other recurrence frequencies may be used: | ||
1292 | 774 | ## | ||
1293 | 775 | ## >>> parse_recurrence_rule('FREQ=WEEKLY;BYDAY=MO,WE,SU') | ||
1294 | 776 | ## WeeklyRecurrenceRule(1, None, None, (), (0, 2, 6)) | ||
1295 | 777 | ## >>> parse_recurrence_rule('FREQ=MONTHLY') | ||
1296 | 778 | ## MonthlyRecurrenceRule(1, None, None, (), 'monthday') | ||
1297 | 779 | ## >>> parse_recurrence_rule('FREQ=YEARLY') | ||
1298 | 780 | ## YearlyRecurrenceRule(1, None, None, ()) | ||
1299 | 781 | ## | ||
1300 | 782 | ## You have to provide a valid recurrence frequency, or you will get an error: | ||
1301 | 783 | ## | ||
1302 | 784 | ## >>> parse_recurrence_rule('') | ||
1303 | 785 | ## Traceback (most recent call last): | ||
1304 | 786 | ## ... | ||
1305 | 787 | ## ValueError: Invalid frequency of recurrence: None | ||
1306 | 788 | ## >>> parse_recurrence_rule('FREQ=bogus') | ||
1307 | 789 | ## Traceback (most recent call last): | ||
1308 | 790 | ## ... | ||
1309 | 791 | ## ValueError: Invalid frequency of recurrence: 'bogus' | ||
1310 | 792 | ## | ||
1311 | 793 | ## Unknown keys in params are ignored silently: | ||
1312 | 794 | ## | ||
1313 | 795 | ## >>> parse_recurrence_rule('FREQ=DAILY;WHATEVER=IGNORED') | ||
1314 | 796 | ## DailyRecurrenceRule(1, None, None, ()) | ||
1315 | 797 | ## | ||
1316 | 798 | ## """ | ||
1317 | 799 | ## from schooltool.cal import DailyRecurrenceRule, YearlyRecurrenceRule | ||
1318 | 800 | ## | ||
1319 | 801 | ## # split up the given value into parameters | ||
1320 | 802 | ## params = {} | ||
1321 | 803 | ## if value: | ||
1322 | 804 | ## for pair in value.split(';'): | ||
1323 | 805 | ## k, v = pair.split('=', 1) | ||
1324 | 806 | ## params[k] = v | ||
1325 | 807 | ## | ||
1326 | 808 | ## # parse common recurrency attributes | ||
1327 | 809 | ## interval = int(params.pop('INTERVAL', '1')) | ||
1328 | 810 | ## count = params.pop('COUNT', None) | ||
1329 | 811 | ## if count is not None: | ||
1330 | 812 | ## count = int(count) | ||
1331 | 813 | ## until = params.pop('UNTIL', None) | ||
1332 | 814 | ## if until is not None: | ||
1333 | 815 | ## if len(until) == 8: | ||
1334 | 816 | ## until = datetime.datetime.combine(parse_date(until), | ||
1335 | 817 | ## datetime.time(0, 0)) | ||
1336 | 818 | ## else: | ||
1337 | 819 | ## until = parse_date_time(until) | ||
1338 | 820 | ## | ||
1339 | 821 | ## # instantiate the corresponding recurrence rule | ||
1340 | 822 | ## freq = params.pop('FREQ', None) | ||
1341 | 823 | ## if freq == 'DAILY': | ||
1342 | 824 | ## rule = DailyRecurrenceRule() | ||
1343 | 825 | ## elif freq == 'WEEKLY': | ||
1344 | 826 | ## rule = _parse_recurrence_weekly(params) | ||
1345 | 827 | ## elif freq == 'MONTHLY': | ||
1346 | 828 | ## rule = _parse_recurrence_monthly(params) | ||
1347 | 829 | ## elif freq == 'YEARLY': | ||
1348 | 830 | ## rule = YearlyRecurrenceRule() | ||
1349 | 831 | ## else: | ||
1350 | 832 | ## raise ValueError('Invalid frequency of recurrence: %r' % freq) | ||
1351 | 833 | ## | ||
1352 | 834 | ## return rule.replace(interval=interval, count=count, until=until) | ||
1353 | 835 | ## | ||
1354 | 836 | |||
1355 | 837 | def parse_recurrence_rule(value): | ||
1356 | 838 | return None # XXX | ||
1357 | 839 | |||
1358 | 840 | |||
1359 | 841 | class VEvent: | ||
1360 | 842 | """iCalendar event. | ||
1361 | 843 | |||
1362 | 844 | Life cycle: when a VEvent is created, a number of properties should be | ||
1363 | 845 | added to it using the add method. Then validate should be called. | ||
1364 | 846 | After that you can start using query methods (getOne, hasProp, iterDates). | ||
1365 | 847 | |||
1366 | 848 | Events are classified into two kinds: | ||
1367 | 849 | - normal events | ||
1368 | 850 | - all-day events | ||
1369 | 851 | |||
1370 | 852 | All-day events are identified by their DTSTART property having a DATE value | ||
1371 | 853 | instead of the default DATE-TIME. All-day events should satisfy the | ||
1372 | 854 | following requirements (otherwise an exception will be raised): | ||
1373 | 855 | - DURATION property (if defined) should be an integral number of days | ||
1374 | 856 | - DTEND property (if defined) should have a DATE value | ||
1375 | 857 | - any RDATE and EXDATE properties should only contain DATE values | ||
1376 | 858 | |||
1377 | 859 | The first two requirements are stated in RFC 2445; I'm not so sure about | ||
1378 | 860 | the third one. | ||
1379 | 861 | """ | ||
1380 | 862 | |||
1381 | 863 | default_type = { | ||
1382 | 864 | # Default value types for some properties | ||
1383 | 865 | 'DTSTAMP': 'DATE-TIME', | ||
1384 | 866 | 'DTSTART': 'DATE-TIME', | ||
1385 | 867 | 'CREATED': 'DATE-TIME', | ||
1386 | 868 | 'DTEND': 'DATE-TIME', | ||
1387 | 869 | 'DURATION': 'DURATION', | ||
1388 | 870 | 'LAST-MODIFIED': 'DATE-TIME', | ||
1389 | 871 | 'PRIORITY': 'INTEGER', | ||
1390 | 872 | 'RECURRENCE-ID': 'DATE-TIME', | ||
1391 | 873 | 'SEQUENCE': 'INTEGER', | ||
1392 | 874 | 'URL': 'URI', | ||
1393 | 875 | 'ATTACH': 'URI', | ||
1394 | 876 | 'EXDATE': 'DATE-TIME', | ||
1395 | 877 | 'EXRULE': 'RECUR', | ||
1396 | 878 | 'RDATE': 'DATE-TIME', | ||
1397 | 879 | 'RRULE': 'RECUR', | ||
1398 | 880 | 'LOCATION': 'TEXT', | ||
1399 | 881 | 'UID': 'TEXT', | ||
1400 | 882 | } | ||
1401 | 883 | |||
1402 | 884 | converters = { | ||
1403 | 885 | 'INTEGER': int, | ||
1404 | 886 | 'DATE': parse_date, | ||
1405 | 887 | 'DATE-TIME': parse_date_time, | ||
1406 | 888 | 'DURATION': parse_duration, | ||
1407 | 889 | 'PERIOD': parse_period, | ||
1408 | 890 | 'TEXT': parse_text, | ||
1409 | 891 | 'RECUR': parse_recurrence_rule, | ||
1410 | 892 | } | ||
1411 | 893 | |||
1412 | 894 | singleton_properties = set([ | ||
1413 | 895 | 'DTSTAMP', | ||
1414 | 896 | 'DTSTART', | ||
1415 | 897 | 'UID', | ||
1416 | 898 | 'CLASS', | ||
1417 | 899 | 'CREATED', | ||
1418 | 900 | 'DESCRIPTION', | ||
1419 | 901 | 'DTEND', | ||
1420 | 902 | 'DURATION', | ||
1421 | 903 | 'GEO', | ||
1422 | 904 | 'LAST-MODIFIED', | ||
1423 | 905 | 'LOCATION', | ||
1424 | 906 | 'ORGANIZER', | ||
1425 | 907 | 'PRIORITY', | ||
1426 | 908 | 'RECURRENCE-ID', | ||
1427 | 909 | 'SEQUENCE', | ||
1428 | 910 | 'STATUS', | ||
1429 | 911 | 'SUMMARY', | ||
1430 | 912 | 'TRANSP', | ||
1431 | 913 | 'URL', | ||
1432 | 914 | ]) | ||
1433 | 915 | |||
1434 | 916 | rdate_types = set(['DATE', 'DATE-TIME', 'PERIOD']) | ||
1435 | 917 | exdate_types = set(['DATE', 'DATE-TIME']) | ||
1436 | 918 | |||
1437 | 919 | def __init__(self): | ||
1438 | 920 | self._props = {} | ||
1439 | 921 | |||
1440 | 922 | def add(self, property, value, params=None): | ||
1441 | 923 | """Add a property. | ||
1442 | 924 | |||
1443 | 925 | Property name is case insensitive. Params should be a dict from | ||
1444 | 926 | uppercased parameter names to their values. | ||
1445 | 927 | |||
1446 | 928 | Multiple calls to add with the same property name override the | ||
1447 | 929 | value. This is sufficient for now, but will have to be changed | ||
1448 | 930 | soon. | ||
1449 | 931 | """ | ||
1450 | 932 | if params is None: | ||
1451 | 933 | params = {} | ||
1452 | 934 | key = property.upper() | ||
1453 | 935 | if key in self._props: | ||
1454 | 936 | if key in self.singleton_properties: | ||
1455 | 937 | raise ICalParseError("Property %s cannot occur more than once" | ||
1456 | 938 | % key) | ||
1457 | 939 | self._props[key].append((value, params)) | ||
1458 | 940 | else: | ||
1459 | 941 | self._props[key] = [(value, params)] | ||
1460 | 942 | |||
1461 | 943 | def validate(self): | ||
1462 | 944 | """Check that this VEvent has all the necessary properties. | ||
1463 | 945 | |||
1464 | 946 | Also sets the following attributes: | ||
1465 | 947 | uid The unique id of this event | ||
1466 | 948 | summary Textual summary of this event | ||
1467 | 949 | all_day_event True if this is an all-day event | ||
1468 | 950 | dtstart start of the event (inclusive) | ||
1469 | 951 | dtend end of the event (not inclusive) | ||
1470 | 952 | duration length of the event | ||
1471 | 953 | location location of the event | ||
1472 | 954 | rrule recurrency rule | ||
1473 | 955 | rdates a list of recurrence dates or periods | ||
1474 | 956 | exdates a list of exception dates | ||
1475 | 957 | """ | ||
1476 | 958 | if not self.hasProp('UID'): | ||
1477 | 959 | raise ICalParseError("VEVENT must have a UID property") | ||
1478 | 960 | if not self.hasProp('DTSTART'): | ||
1479 | 961 | raise ICalParseError("VEVENT must have a DTSTART property") | ||
1480 | 962 | if self._getType('DTSTART') not in ('DATE', 'DATE-TIME'): | ||
1481 | 963 | raise ICalParseError("DTSTART property should have a DATE or" | ||
1482 | 964 | " DATE-TIME value") | ||
1483 | 965 | if self.hasProp('DTEND'): | ||
1484 | 966 | if self._getType('DTEND') != self._getType('DTSTART'): | ||
1485 | 967 | raise ICalParseError("DTEND property should have the same type" | ||
1486 | 968 | " as DTSTART") | ||
1487 | 969 | if self.hasProp('DURATION'): | ||
1488 | 970 | raise ICalParseError("VEVENT cannot have both a DTEND" | ||
1489 | 971 | " and a DURATION property") | ||
1490 | 972 | if self.hasProp('DURATION'): | ||
1491 | 973 | if self._getType('DURATION') != 'DURATION': | ||
1492 | 974 | raise ICalParseError("DURATION property should have type" | ||
1493 | 975 | " DURATION") | ||
1494 | 976 | |||
1495 | 977 | self.uid = self.getOne('UID') | ||
1496 | 978 | self.summary = self.getOne('SUMMARY') | ||
1497 | 979 | |||
1498 | 980 | self.all_day_event = self._getType('DTSTART') == 'DATE' | ||
1499 | 981 | self.dtstart = self.getOne('DTSTART') | ||
1500 | 982 | if self.hasProp('DURATION'): | ||
1501 | 983 | self.duration = self.getOne('DURATION') | ||
1502 | 984 | self.dtend = self.dtstart + self.duration | ||
1503 | 985 | else: | ||
1504 | 986 | self.dtend = self.getOne('DTEND', None) | ||
1505 | 987 | if self.dtend is None: | ||
1506 | 988 | self.dtend = self.dtstart | ||
1507 | 989 | if self.all_day_event: | ||
1508 | 990 | self.dtend += datetime.date.resolution | ||
1509 | 991 | self.duration = self.dtend - self.dtstart | ||
1510 | 992 | |||
1511 | 993 | self.location = self.getOne('LOCATION', None) | ||
1512 | 994 | |||
1513 | 995 | if self.dtstart > self.dtend: | ||
1514 | 996 | raise ICalParseError("Event start time should precede end time") | ||
1515 | 997 | elif self.all_day_event and self.dtstart == self.dtend: | ||
1516 | 998 | raise ICalParseError("Event start time should precede end time") | ||
1517 | 999 | |||
1518 | 1000 | self.rdates = self._extractListOfDates('RDATE', self.rdate_types, | ||
1519 | 1001 | self.all_day_event) | ||
1520 | 1002 | self.exdates = self._extractListOfDates('EXDATE', self.exdate_types, | ||
1521 | 1003 | self.all_day_event) | ||
1522 | 1004 | |||
1523 | 1005 | self.rrule = self.getOne('RRULE', None) | ||
1524 | 1006 | if self.rrule is not None and self.exdates: | ||
1525 | 1007 | if self._getType('EXDATE') == 'DATE-TIME': | ||
1526 | 1008 | exceptions = [dt.date() for dt in self.exdates] | ||
1527 | 1009 | else: | ||
1528 | 1010 | exceptions = self.exdates | ||
1529 | 1011 | self.rrule = self.rrule.replace(exceptions=exceptions) | ||
1530 | 1012 | |||
1531 | 1013 | def _extractListOfDates(self, key, accepted_types, all_day_event): | ||
1532 | 1014 | """Parse a comma separated list of values. | ||
1533 | 1015 | |||
1534 | 1016 | If all_day_event is True, only accepts DATE values. Otherwise accepts | ||
1535 | 1017 | all value types listed in 'accepted_types'. | ||
1536 | 1018 | """ | ||
1537 | 1019 | dates = [] | ||
1538 | 1020 | default_type = self.default_type[key] | ||
1539 | 1021 | for value, params in self._props.get(key, []): | ||
1540 | 1022 | value_type = params.get('VALUE', default_type) | ||
1541 | 1023 | if value_type not in accepted_types: | ||
1542 | 1024 | raise ICalParseError('Invalid value type for %s: %s' | ||
1543 | 1025 | % (key, value_type)) | ||
1544 | 1026 | if all_day_event and value_type != 'DATE': | ||
1545 | 1027 | raise ICalParseError('I do not understand how to interpret ' | ||
1546 | 1028 | '%s values in %s for all-day events.' | ||
1547 | 1029 | % (value_type, key)) | ||
1548 | 1030 | converter = self.converters.get(value_type) | ||
1549 | 1031 | dates.extend(map(converter, value.split(','))) | ||
1550 | 1032 | return dates | ||
1551 | 1033 | |||
1552 | 1034 | def _getType(self, property): | ||
1553 | 1035 | """Return the type of the property value.""" | ||
1554 | 1036 | key = property.upper() | ||
1555 | 1037 | values = self._props[key] | ||
1556 | 1038 | assert len(values) == 1 | ||
1557 | 1039 | value, params = values[0] | ||
1558 | 1040 | default_type = self.default_type.get(key, 'TEXT') | ||
1559 | 1041 | return params.get('VALUE', default_type) | ||
1560 | 1042 | |||
1561 | 1043 | def getOne(self, property, default=None): | ||
1562 | 1044 | """Return the value of a property as an appropriate Python object. | ||
1563 | 1045 | |||
1564 | 1046 | Only call getOne for properties that do not occur more than once. | ||
1565 | 1047 | """ | ||
1566 | 1048 | try: | ||
1567 | 1049 | values = self._props[property.upper()] | ||
1568 | 1050 | assert len(values) == 1 | ||
1569 | 1051 | value, params = values[0] | ||
1570 | 1052 | except KeyError: | ||
1571 | 1053 | return default | ||
1572 | 1054 | else: | ||
1573 | 1055 | converter = self.converters.get(self._getType(property)) | ||
1574 | 1056 | if converter is None: | ||
1575 | 1057 | return value | ||
1576 | 1058 | else: | ||
1577 | 1059 | return converter(value) | ||
1578 | 1060 | |||
1579 | 1061 | def hasProp(self, property): | ||
1580 | 1062 | """Return True if this VEvent has a named property.""" | ||
1581 | 1063 | return property.upper() in self._props | ||
1582 | 1064 | |||
1583 | 1065 | def iterDates(self): | ||
1584 | 1066 | """Iterate over all dates within this event. | ||
1585 | 1067 | |||
1586 | 1068 | This is only valid for all-day events at the moment. | ||
1587 | 1069 | """ | ||
1588 | 1070 | if not self.all_day_event: | ||
1589 | 1071 | raise ValueError('iterDates is only defined for all-day events') | ||
1590 | 1072 | |||
1591 | 1073 | # Find out the set of start dates | ||
1592 | 1074 | start_set = {self.dtstart: None} | ||
1593 | 1075 | for rdate in self.rdates: | ||
1594 | 1076 | start_set[rdate] = rdate | ||
1595 | 1077 | for exdate in self.exdates: | ||
1596 | 1078 | if exdate in start_set: | ||
1597 | 1079 | del start_set[exdate] | ||
1598 | 1080 | |||
1599 | 1081 | # Find out the set of all dates | ||
1600 | 1082 | date_set = set(start_set) | ||
1601 | 1083 | duration = self.duration.days | ||
1602 | 1084 | for d in start_set: | ||
1603 | 1085 | for n in range(1, duration): | ||
1604 | 1086 | d += datetime.date.resolution | ||
1605 | 1087 | date_set.add(d) | ||
1606 | 1088 | |||
1607 | 1089 | # Yield all dates in chronological order | ||
1608 | 1090 | dates = list(date_set) | ||
1609 | 1091 | dates.sort() | ||
1610 | 1092 | for d in dates: | ||
1611 | 1093 | yield d | ||
1612 | 1094 | |||
1613 | 1095 | |||
1614 | 1096 | class Period: | ||
1615 | 1097 | """A period of time""" | ||
1616 | 1098 | |||
1617 | 1099 | def __init__(self, start, end_or_duration): | ||
1618 | 1100 | self.start = start | ||
1619 | 1101 | self.end_or_duration = end_or_duration | ||
1620 | 1102 | if isinstance(end_or_duration, datetime.timedelta): | ||
1621 | 1103 | self.duration = end_or_duration | ||
1622 | 1104 | self.end = self.start + self.duration | ||
1623 | 1105 | else: | ||
1624 | 1106 | self.end = end_or_duration | ||
1625 | 1107 | self.duration = self.end - self.start | ||
1626 | 1108 | if self.start > self.end: | ||
1627 | 1109 | raise ValueError("Start time is greater than end time") | ||
1628 | 1110 | |||
1629 | 1111 | def __repr__(self): | ||
1630 | 1112 | return "Period(%r, %r)" % (self.start, self.end_or_duration) | ||
1631 | 1113 | |||
1632 | 1114 | def __cmp__(self, other): | ||
1633 | 1115 | if not isinstance(other, Period): | ||
1634 | 1116 | raise NotImplementedError('Cannot compare Period with %r' % other) | ||
1635 | 1117 | return cmp((self.start, self.end), (other.start, other.end)) | ||
1636 | 1118 | |||
1637 | 1119 | def overlaps(self, other): | ||
1638 | 1120 | if self.start > other.start: | ||
1639 | 1121 | return other.overlaps(self) | ||
1640 | 1122 | if self.start <= other.start < self.end: | ||
1641 | 1123 | return True | ||
1642 | 1124 | return False | ||
1643 | 1125 | |||
1644 | 1126 | class ICalParseError(Exception): | ||
1645 | 1127 | """Invalid syntax in an iCalendar file.""" | ||
1646 | 1128 | 0 | ||
1647 | === removed file 'lib/schoolbell/interfaces.py' | |||
1648 | --- lib/schoolbell/interfaces.py 2005-11-17 21:44:26 +0000 | |||
1649 | +++ lib/schoolbell/interfaces.py 1970-01-01 00:00:00 +0000 | |||
1650 | @@ -1,396 +0,0 @@ | |||
1651 | 1 | """ | ||
1652 | 2 | Interface definitions for SchoolBell. | ||
1653 | 3 | |||
1654 | 4 | There are two interfaces for calendars: `ICalendar` for read-only calendars, | ||
1655 | 5 | and `IEditCalendar` for read-write calendars. | ||
1656 | 6 | |||
1657 | 7 | Semantically calendars are unordered sets of events. Events themselves | ||
1658 | 8 | (`ICalendarEvent`) are immutable and comparable. If you have an editable | ||
1659 | 9 | calendar, and want to change an event in it, you need to create a new event | ||
1660 | 10 | object and put it into the calendar: | ||
1661 | 11 | |||
1662 | 12 | calendar.removeEvent(event) | ||
1663 | 13 | replacement_event = event.replace(title=u"New title", ...) | ||
1664 | 14 | calendar.addEvent(replacement_event) | ||
1665 | 15 | |||
1666 | 16 | Calendars have globally unique IDs. If you are changing an event in the | ||
1667 | 17 | fashion demonstrated above, you should preserve its unique_id attribute. | ||
1668 | 18 | |||
1669 | 19 | """ | ||
1670 | 20 | |||
1671 | 21 | from zope.interface import Interface | ||
1672 | 22 | from zope.schema import Text, TextLine, Int, Datetime, Date, List, Set, Choice | ||
1673 | 23 | from zope.schema import Field, Object | ||
1674 | 24 | |||
1675 | 25 | |||
1676 | 26 | class ICalendar(Interface): | ||
1677 | 27 | """Calendar. | ||
1678 | 28 | |||
1679 | 29 | A calendar is a set of calendar events (see ICalendarEvent). Recurring | ||
1680 | 30 | events are listed only once. | ||
1681 | 31 | """ | ||
1682 | 32 | |||
1683 | 33 | def __iter__(): | ||
1684 | 34 | """Return an iterator over all events in this calendar. | ||
1685 | 35 | |||
1686 | 36 | The order of events is not defined. | ||
1687 | 37 | """ | ||
1688 | 38 | |||
1689 | 39 | def find(unique_id): | ||
1690 | 40 | """Return an event with the given unique id. | ||
1691 | 41 | |||
1692 | 42 | Raises a KeyError if there is no event with this id. | ||
1693 | 43 | """ | ||
1694 | 44 | |||
1695 | 45 | def expand(first, last): | ||
1696 | 46 | """Return an iterator over all expanded events in a given time period. | ||
1697 | 47 | |||
1698 | 48 | "Expanding" here refers to expanding recurring events, that is, | ||
1699 | 49 | creating objects for all occurrences of recurring events. If a | ||
1700 | 50 | recurring event has occurreces that overlap the specified time | ||
1701 | 51 | interval, every such occurrence is represented as a new calendar event | ||
1702 | 52 | with the `dtstart` attribute replaced with the date and time of that | ||
1703 | 53 | occurrence. These events provide IExpandedCalendarEvent and have an | ||
1704 | 54 | additional attribute which points to the original event. | ||
1705 | 55 | |||
1706 | 56 | `first` and `last` are datetime.datetimes and define a half-open | ||
1707 | 57 | time interval. | ||
1708 | 58 | |||
1709 | 59 | The order of returned events is not defined. | ||
1710 | 60 | """ | ||
1711 | 61 | |||
1712 | 62 | |||
1713 | 63 | class IEditCalendar(ICalendar): | ||
1714 | 64 | """Editable calendar. | ||
1715 | 65 | |||
1716 | 66 | Calendar events are read-only, so to change an event you need to remove | ||
1717 | 67 | the old event, and add a replacement event in the calendar. | ||
1718 | 68 | """ | ||
1719 | 69 | |||
1720 | 70 | def clear(): | ||
1721 | 71 | """Remove all events.""" | ||
1722 | 72 | |||
1723 | 73 | def addEvent(event): | ||
1724 | 74 | """Add an event to the calendar. | ||
1725 | 75 | |||
1726 | 76 | Raises ValueError if an event with the same unique_id already exists | ||
1727 | 77 | in the calendar. | ||
1728 | 78 | |||
1729 | 79 | Returns the newly added event (which may be a copy of the argument, | ||
1730 | 80 | e.g. if the calendar needs its events to be instances of a particular | ||
1731 | 81 | class). | ||
1732 | 82 | |||
1733 | 83 | It is perhaps not a good idea to add calendar events that have no | ||
1734 | 84 | occurrences into calendars (see ICalendarEvent.hasOccurrences), as they | ||
1735 | 85 | will be invisible in date-based of calendar views. | ||
1736 | 86 | |||
1737 | 87 | Do not call addEvent while iterating over the calendar. | ||
1738 | 88 | """ | ||
1739 | 89 | |||
1740 | 90 | def removeEvent(event): | ||
1741 | 91 | """Remove event from the calendar. | ||
1742 | 92 | |||
1743 | 93 | Raises ValueError if event is not present in the calendar. | ||
1744 | 94 | |||
1745 | 95 | Do not call removeEvent while iterating over the calendar. | ||
1746 | 96 | """ | ||
1747 | 97 | |||
1748 | 98 | def update(calendar): | ||
1749 | 99 | """Add all events from another calendar. | ||
1750 | 100 | |||
1751 | 101 | cal1.update(cal2) | ||
1752 | 102 | |||
1753 | 103 | is equivalent to | ||
1754 | 104 | |||
1755 | 105 | for event in cal2: | ||
1756 | 106 | cal1.addEvent(event) | ||
1757 | 107 | """ | ||
1758 | 108 | |||
1759 | 109 | |||
1760 | 110 | class IRecurrenceRule(Interface): | ||
1761 | 111 | """Base interface of the recurrence rules. | ||
1762 | 112 | |||
1763 | 113 | Recurrence rules are stored as attributes of ICalendarEvent. They | ||
1764 | 114 | are also immutable and comparable. To modify the recurrence | ||
1765 | 115 | rule of an event, you need to create a new recurrence rule, and a new | ||
1766 | 116 | event: | ||
1767 | 117 | |||
1768 | 118 | replacement_rule = event.recurrence.replace(count=3, until=None) | ||
1769 | 119 | replacement_event = event.replace(recurrence=replacement_rule) | ||
1770 | 120 | calendar.removeEvent(event) | ||
1771 | 121 | calendar.addEvent(replacement_event) | ||
1772 | 122 | |||
1773 | 123 | """ | ||
1774 | 124 | |||
1775 | 125 | interval = Int( | ||
1776 | 126 | title=u"Interval", | ||
1777 | 127 | min=1, | ||
1778 | 128 | description=u""" | ||
1779 | 129 | Interval of recurrence (a positive integer). | ||
1780 | 130 | |||
1781 | 131 | For example, to indicate that an event occurs every second day, | ||
1782 | 132 | you would create a DailyRecurrenceRule witl interval equal to 2. | ||
1783 | 133 | """) | ||
1784 | 134 | |||
1785 | 135 | count = Int( | ||
1786 | 136 | title=u"Count", | ||
1787 | 137 | required=False, | ||
1788 | 138 | description=u""" | ||
1789 | 139 | Number of times the event is repeated. | ||
1790 | 140 | |||
1791 | 141 | Can be None or an integer value. If count is not None then | ||
1792 | 142 | until must be None. If both count and until are None the | ||
1793 | 143 | event repeats forever. | ||
1794 | 144 | """) | ||
1795 | 145 | |||
1796 | 146 | until = Date( | ||
1797 | 147 | title=u"Until", | ||
1798 | 148 | required=False, | ||
1799 | 149 | description=u""" | ||
1800 | 150 | The date of the last recurrence of the event. | ||
1801 | 151 | |||
1802 | 152 | Can be None or a datetime.date instance. If until is not None | ||
1803 | 153 | then count must be None. If both count and until are None the | ||
1804 | 154 | event repeats forever. | ||
1805 | 155 | """) | ||
1806 | 156 | |||
1807 | 157 | exceptions = List( | ||
1808 | 158 | title=u"Exceptions", | ||
1809 | 159 | value_type=Date(), | ||
1810 | 160 | description=u""" | ||
1811 | 161 | A list of days when this event does not occur. | ||
1812 | 162 | |||
1813 | 163 | Values in this list must be instances of datetime.date. | ||
1814 | 164 | """) | ||
1815 | 165 | |||
1816 | 166 | def replace(**kw): | ||
1817 | 167 | """Return a copy of this recurrence rule with new specified fields.""" | ||
1818 | 168 | |||
1819 | 169 | def __eq__(other): | ||
1820 | 170 | """See if self == other.""" | ||
1821 | 171 | |||
1822 | 172 | def __ne__(other): | ||
1823 | 173 | """See if self != other.""" | ||
1824 | 174 | |||
1825 | 175 | def apply(event, enddate=None): | ||
1826 | 176 | """Apply this rule to an event. | ||
1827 | 177 | |||
1828 | 178 | This is a generator that returns the dates on which the event should | ||
1829 | 179 | recur. Be careful when iterating over these dates -- rules that do not | ||
1830 | 180 | have either 'until' or 'count' attributes will go on forever. | ||
1831 | 181 | |||
1832 | 182 | The optional enddate attribute can be used to set a range on the dates | ||
1833 | 183 | generated by this function (inclusive). | ||
1834 | 184 | """ | ||
1835 | 185 | |||
1836 | 186 | def iCalRepresentation(dtstart): | ||
1837 | 187 | """Return the rule in iCalendar format. | ||
1838 | 188 | |||
1839 | 189 | Returns a list of strings. XXX more details, please | ||
1840 | 190 | |||
1841 | 191 | dtstart is a datetime representing the date that the recurring | ||
1842 | 192 | event starts on. | ||
1843 | 193 | """ | ||
1844 | 194 | |||
1845 | 195 | |||
1846 | 196 | class IDailyRecurrenceRule(IRecurrenceRule): | ||
1847 | 197 | """Daily recurrence.""" | ||
1848 | 198 | |||
1849 | 199 | |||
1850 | 200 | class IYearlyRecurrenceRule(IRecurrenceRule): | ||
1851 | 201 | """Yearly recurrence.""" | ||
1852 | 202 | |||
1853 | 203 | |||
1854 | 204 | class IWeeklyRecurrenceRule(IRecurrenceRule): | ||
1855 | 205 | """Weekly recurrence.""" | ||
1856 | 206 | |||
1857 | 207 | weekdays = Set( | ||
1858 | 208 | title=u"Weekdays", | ||
1859 | 209 | value_type=Int(min=0, max=6), | ||
1860 | 210 | description=u""" | ||
1861 | 211 | A set of weekdays when this event occurs. | ||
1862 | 212 | |||
1863 | 213 | Weekdays are represented as integers from 0 (Monday) to 6 (Sunday). | ||
1864 | 214 | This is what the `calendar` and `datetime` modules use. | ||
1865 | 215 | |||
1866 | 216 | The event repeats on the weekday of the first occurence even | ||
1867 | 217 | if that weekday is not in this set. | ||
1868 | 218 | """) | ||
1869 | 219 | |||
1870 | 220 | |||
1871 | 221 | class IMonthlyRecurrenceRule(IRecurrenceRule): | ||
1872 | 222 | """Monthly recurrence.""" | ||
1873 | 223 | |||
1874 | 224 | monthly = Choice( | ||
1875 | 225 | title=u"Type", | ||
1876 | 226 | values=('monthday', 'weekday', 'lastweekday'), | ||
1877 | 227 | description=u""" | ||
1878 | 228 | Specification of a monthly occurence. | ||
1879 | 229 | |||
1880 | 230 | Can be one of three values: 'monthday', 'weekday', 'lastweekday'. | ||
1881 | 231 | |||
1882 | 232 | 'monthday' specifies that the event recurs on the same day of month | ||
1883 | 233 | (e.g., 25th day of a month). | ||
1884 | 234 | |||
1885 | 235 | 'weekday' specifies that the event recurs on the same week | ||
1886 | 236 | within a month on the same weekday, indexed from the | ||
1887 | 237 | first (e.g. 3rd Friday of a month). | ||
1888 | 238 | |||
1889 | 239 | 'lastweekday' specifies that the event recurs on the same week | ||
1890 | 240 | within a month on the same weekday, indexed from the | ||
1891 | 241 | end of month (e.g. 2nd last Friday of a month). | ||
1892 | 242 | """) | ||
1893 | 243 | |||
1894 | 244 | |||
1895 | 245 | class ICalendarEvent(Interface): | ||
1896 | 246 | """A calendar event. | ||
1897 | 247 | |||
1898 | 248 | Calendar events are immutable and comparable. | ||
1899 | 249 | |||
1900 | 250 | Events are compared in chronological order, so lists of events can be | ||
1901 | 251 | sorted. If two events start at the same time, they are ordered according | ||
1902 | 252 | to their titles. | ||
1903 | 253 | |||
1904 | 254 | While `unique_id` is a globally unique ID of a calendar event, you can | ||
1905 | 255 | have several calendar event objects with the same value of `unique_id`, | ||
1906 | 256 | and they will not be equal if any their attributes are different. | ||
1907 | 257 | Semantically these objects are different versions of the same calendar | ||
1908 | 258 | event. | ||
1909 | 259 | |||
1910 | 260 | If you need to modify a calendar event in a calendar, you should do | ||
1911 | 261 | the following: | ||
1912 | 262 | |||
1913 | 263 | calendar.removeEvent(event) | ||
1914 | 264 | replacement_event = event.replace(title=u"New title", ...) | ||
1915 | 265 | calendar.addEvent(replacement_event) | ||
1916 | 266 | |||
1917 | 267 | """ | ||
1918 | 268 | |||
1919 | 269 | id = Int( | ||
1920 | 270 | title=u"An internal ID for the event", | ||
1921 | 271 | required=True, readonly=True, | ||
1922 | 272 | description=u"""An ID for the event, guaranteed to be unique locally | ||
1923 | 273 | but not globally.""") | ||
1924 | 274 | |||
1925 | 275 | calendar = Object( | ||
1926 | 276 | title=u"Calendar", | ||
1927 | 277 | schema=ICalendar, | ||
1928 | 278 | description=u""" | ||
1929 | 279 | The calendar this event belongs to. | ||
1930 | 280 | """) | ||
1931 | 281 | |||
1932 | 282 | unique_id = TextLine( | ||
1933 | 283 | title=u"UID", | ||
1934 | 284 | description=u""" | ||
1935 | 285 | A globally unique id for this calendar event. | ||
1936 | 286 | |||
1937 | 287 | iCalendar (RFC 2445) recommeds using the RFC 822 addr-spec syntax | ||
1938 | 288 | for unique IDs. Put the current timestamp and a random number | ||
1939 | 289 | on the left of the @ sign, and put the hostname on the right. | ||
1940 | 290 | """) | ||
1941 | 291 | |||
1942 | 292 | dtstart = Datetime( | ||
1943 | 293 | title=u"Starting date and time", | ||
1944 | 294 | description=u"""Format: yyyy-mm-dd hh:mm""" | ||
1945 | 295 | ) | ||
1946 | 296 | |||
1947 | 297 | duration = Field(title=u"Duration") | ||
1948 | 298 | # The duration of the event (datetime.timedelta). | ||
1949 | 299 | # You can compute the event end date/time by adding duration to dtstart. | ||
1950 | 300 | # zope.schema does not have TimeInterval. | ||
1951 | 301 | |||
1952 | 302 | title = TextLine(title=u"Name") | ||
1953 | 303 | |||
1954 | 304 | description = Text(title=u"Description") | ||
1955 | 305 | |||
1956 | 306 | location = TextLine( | ||
1957 | 307 | title=u"Location", | ||
1958 | 308 | required=False, | ||
1959 | 309 | description=u"""Where the event will take place.""") | ||
1960 | 310 | |||
1961 | 311 | recurrence = Object( | ||
1962 | 312 | title=u"Recurrence", | ||
1963 | 313 | schema=IRecurrenceRule, | ||
1964 | 314 | required=False, | ||
1965 | 315 | description=u""" | ||
1966 | 316 | The recurrence rule, if this is a recurring event, otherwise None. | ||
1967 | 317 | """) | ||
1968 | 318 | |||
1969 | 319 | def replace(**kw): | ||
1970 | 320 | """Return a calendar event with new specified fields. | ||
1971 | 321 | |||
1972 | 322 | This is useful for editing calendars. For example, to change the | ||
1973 | 323 | title and location of an event in a calendar, you would do | ||
1974 | 324 | |||
1975 | 325 | calendar.removeEvent(event) | ||
1976 | 326 | replacement_event = event.replace(title=u"New title", | ||
1977 | 327 | location=None) | ||
1978 | 328 | calendar.addEvent(replacement_event) | ||
1979 | 329 | |||
1980 | 330 | """ | ||
1981 | 331 | |||
1982 | 332 | def __eq__(other): | ||
1983 | 333 | """See if self == other.""" | ||
1984 | 334 | |||
1985 | 335 | def __ne__(other): | ||
1986 | 336 | """See if self != other.""" | ||
1987 | 337 | |||
1988 | 338 | def __lt__(other): | ||
1989 | 339 | """See if self < other.""" | ||
1990 | 340 | |||
1991 | 341 | def __gt__(other): | ||
1992 | 342 | """See if self > other.""" | ||
1993 | 343 | |||
1994 | 344 | def __le__(other): | ||
1995 | 345 | """See if self <= other.""" | ||
1996 | 346 | |||
1997 | 347 | def __ge__(other): | ||
1998 | 348 | """See if self >= other.""" | ||
1999 | 349 | |||
2000 | 350 | def hasOccurrences(): | ||
2001 | 351 | """Does the event have any occurrences? | ||
2002 | 352 | |||
2003 | 353 | Normally all events have at least one occurrence. However if you have | ||
2004 | 354 | a repeating event that repeats a finite number of times, and all those | ||
2005 | 355 | repetitions are listed as exceptions, then hasOccurrences() will return | ||
2006 | 356 | False. There are other corner cases as well (e.g. a recurring event | ||
2007 | 357 | with until date that is earlier than dtstart). | ||
2008 | 358 | """ | ||
2009 | 359 | |||
2010 | 360 | |||
2011 | 361 | class IExpandedCalendarEvent(ICalendarEvent): | ||
2012 | 362 | """A single occurrence of a recurring calendar event. | ||
2013 | 363 | |||
2014 | 364 | The original event is stored in the `original` attribute. The `dtstart` | ||
2015 | 365 | attribute contains the date and time of this occurrence and may differ | ||
2016 | 366 | from the `dtstart` attribute of the original event. All other attributes | ||
2017 | 367 | are the same. | ||
2018 | 368 | """ | ||
2019 | 369 | |||
2020 | 370 | dtstart = Datetime( | ||
2021 | 371 | title=u"Start", | ||
2022 | 372 | description=u""" | ||
2023 | 373 | Date and time when this occurrence of the event starts. | ||
2024 | 374 | """) | ||
2025 | 375 | |||
2026 | 376 | original = Object( | ||
2027 | 377 | title=u"Original", | ||
2028 | 378 | schema=ICalendarEvent, | ||
2029 | 379 | description=u""" | ||
2030 | 380 | The recurring event that generated this occurrence. | ||
2031 | 381 | """) | ||
2032 | 382 | |||
2033 | 383 | def replace(**kw): | ||
2034 | 384 | """Return a calendar event with new specified fields. | ||
2035 | 385 | |||
2036 | 386 | expanded_event.replace(**kw) | ||
2037 | 387 | |||
2038 | 388 | is (almost) equivalent to | ||
2039 | 389 | |||
2040 | 390 | expanded_event.original.replace(**kw) | ||
2041 | 391 | |||
2042 | 392 | In other words, the returned event will not provide | ||
2043 | 393 | IExpandedCalendarEvent and its dtstart attribute will be the date and | ||
2044 | 394 | time of the original event rather than this specific occurrence. | ||
2045 | 395 | """ | ||
2046 | 396 | |||
2047 | 397 | 0 | ||
2048 | === removed file 'lib/schoolbell/mixins.py' | |||
2049 | --- lib/schoolbell/mixins.py 2005-10-31 18:29:12 +0000 | |||
2050 | +++ lib/schoolbell/mixins.py 1970-01-01 00:00:00 +0000 | |||
2051 | @@ -1,314 +0,0 @@ | |||
2052 | 1 | """ | ||
2053 | 2 | Mixins for implementing calendars. | ||
2054 | 3 | """ | ||
2055 | 4 | |||
2056 | 5 | __metaclass__ = type | ||
2057 | 6 | |||
2058 | 7 | |||
2059 | 8 | class CalendarMixin: | ||
2060 | 9 | """Mixin for implementing ICalendar methods. | ||
2061 | 10 | |||
2062 | 11 | You do not have to use this mixin, however it might make implementation | ||
2063 | 12 | easier, albeit potentially slower. | ||
2064 | 13 | |||
2065 | 14 | A class that uses this mixin must already implement ICalendar.__iter__. | ||
2066 | 15 | |||
2067 | 16 | >>> from schoolbell.interfaces import ICalendar | ||
2068 | 17 | >>> from zope.interface import implements | ||
2069 | 18 | >>> class MyCalendar(CalendarMixin): | ||
2070 | 19 | ... implements(ICalendar) | ||
2071 | 20 | ... def __iter__(self): | ||
2072 | 21 | ... return iter([]) | ||
2073 | 22 | >>> from zope.interface.verify import verifyObject | ||
2074 | 23 | >>> verifyObject(ICalendar, MyCalendar()) | ||
2075 | 24 | True | ||
2076 | 25 | |||
2077 | 26 | """ | ||
2078 | 27 | |||
2079 | 28 | def find(self, unique_id): | ||
2080 | 29 | """Find a calendar event with a given UID. | ||
2081 | 30 | |||
2082 | 31 | This particular implementation simply performs a linear search by | ||
2083 | 32 | iterating over all events and looking at their UIDs. | ||
2084 | 33 | |||
2085 | 34 | >>> from schoolbell.interfaces import ICalendar | ||
2086 | 35 | >>> from zope.interface import implements | ||
2087 | 36 | |||
2088 | 37 | >>> class Event: | ||
2089 | 38 | ... def __init__(self, uid): | ||
2090 | 39 | ... self.unique_id = uid | ||
2091 | 40 | |||
2092 | 41 | >>> class MyCalendar(CalendarMixin): | ||
2093 | 42 | ... implements(ICalendar) | ||
2094 | 43 | ... def __iter__(self): | ||
2095 | 44 | ... return iter([Event(uid) for uid in 'a', 'b']) | ||
2096 | 45 | >>> cal = MyCalendar() | ||
2097 | 46 | |||
2098 | 47 | >>> cal.find('a').unique_id | ||
2099 | 48 | 'a' | ||
2100 | 49 | >>> cal.find('b').unique_id | ||
2101 | 50 | 'b' | ||
2102 | 51 | >>> cal.find('c') | ||
2103 | 52 | Traceback (most recent call last): | ||
2104 | 53 | ... | ||
2105 | 54 | KeyError: 'c' | ||
2106 | 55 | |||
2107 | 56 | """ | ||
2108 | 57 | for event in self: | ||
2109 | 58 | if event.unique_id == unique_id: | ||
2110 | 59 | return event | ||
2111 | 60 | raise KeyError(unique_id) | ||
2112 | 61 | |||
2113 | 62 | def expand(self, first, last): | ||
2114 | 63 | """Return an iterator over all expanded events in a given time period. | ||
2115 | 64 | |||
2116 | 65 | See ICalendar for more details. | ||
2117 | 66 | |||
2118 | 67 | >>> from datetime import datetime, timedelta | ||
2119 | 68 | >>> from schoolbell.interfaces import ICalendar | ||
2120 | 69 | >>> from zope.interface import implements | ||
2121 | 70 | |||
2122 | 71 | >>> class Event: | ||
2123 | 72 | ... def __init__(self, dtstart, duration, title): | ||
2124 | 73 | ... self.dtstart = dtstart | ||
2125 | 74 | ... self.duration = duration | ||
2126 | 75 | ... self.title = title | ||
2127 | 76 | |||
2128 | 77 | >>> class MyCalendar(CalendarMixin): | ||
2129 | 78 | ... implements(ICalendar) | ||
2130 | 79 | ... def __iter__(self): | ||
2131 | 80 | ... return iter([Event(datetime(2004, 12, 14, 12, 30), | ||
2132 | 81 | ... timedelta(hours=1), 'a'), | ||
2133 | 82 | ... Event(datetime(2004, 12, 15, 16, 30), | ||
2134 | 83 | ... timedelta(hours=1), 'b'), | ||
2135 | 84 | ... Event(datetime(2004, 12, 15, 14, 30), | ||
2136 | 85 | ... timedelta(hours=1), 'c'), | ||
2137 | 86 | ... Event(datetime(2004, 12, 16, 17, 30), | ||
2138 | 87 | ... timedelta(hours=1), 'd'), | ||
2139 | 88 | ... ]) | ||
2140 | 89 | >>> cal = MyCalendar() | ||
2141 | 90 | |||
2142 | 91 | We will define a convenience function for showing all events returned | ||
2143 | 92 | by expand: | ||
2144 | 93 | |||
2145 | 94 | >>> def show(first, last): | ||
2146 | 95 | ... events = cal.expand(first, last) | ||
2147 | 96 | ... print '[%s]' % ', '.join([e.title for e in events]) | ||
2148 | 97 | |||
2149 | 98 | Events that fall inside the interval | ||
2150 | 99 | |||
2151 | 100 | >>> show(datetime(2004, 12, 1), datetime(2004, 12, 31)) | ||
2152 | 101 | [a, b, c, d] | ||
2153 | 102 | |||
2154 | 103 | >>> show(datetime(2004, 12, 15), datetime(2004, 12, 16)) | ||
2155 | 104 | [b, c] | ||
2156 | 105 | |||
2157 | 106 | Events that fall partially in the interval | ||
2158 | 107 | |||
2159 | 108 | >>> show(datetime(2004, 12, 15, 17, 0), | ||
2160 | 109 | ... datetime(2004, 12, 16, 18, 0)) | ||
2161 | 110 | [b, d] | ||
2162 | 111 | |||
2163 | 112 | Corner cases: if event.dtstart + event.duration == last, or | ||
2164 | 113 | event.dtstart == first, the event is not included. | ||
2165 | 114 | |||
2166 | 115 | >>> show(datetime(2004, 12, 15, 15, 30), | ||
2167 | 116 | ... datetime(2004, 12, 15, 16, 30)) | ||
2168 | 117 | [] | ||
2169 | 118 | |||
2170 | 119 | TODO: recurring events | ||
2171 | 120 | |||
2172 | 121 | """ | ||
2173 | 122 | for event in self: | ||
2174 | 123 | # TODO: recurring events | ||
2175 | 124 | dtstart = event.dtstart | ||
2176 | 125 | dtend = dtstart + event.duration | ||
2177 | 126 | if dtend > first and dtstart < last: | ||
2178 | 127 | yield event | ||
2179 | 128 | |||
2180 | 129 | |||
2181 | 130 | class EditableCalendarMixin: | ||
2182 | 131 | """Mixin for implementing some IEditCalendar methods. | ||
2183 | 132 | |||
2184 | 133 | This mixin implements `clear` and `update` by using `addEvent` and | ||
2185 | 134 | `removeEvent`. | ||
2186 | 135 | |||
2187 | 136 | >>> class Event: | ||
2188 | 137 | ... def __init__(self, uid): | ||
2189 | 138 | ... self.unique_id = uid | ||
2190 | 139 | |||
2191 | 140 | >>> class SampleCalendar(EditableCalendarMixin): | ||
2192 | 141 | ... def __init__(self): | ||
2193 | 142 | ... self._events = {} | ||
2194 | 143 | ... def __iter__(self): | ||
2195 | 144 | ... return self._events.itervalues() | ||
2196 | 145 | ... def addEvent(self, event): | ||
2197 | 146 | ... self._events[event.unique_id] = event | ||
2198 | 147 | ... def removeEvent(self, event): | ||
2199 | 148 | ... del self._events[event.unique_id] | ||
2200 | 149 | |||
2201 | 150 | >>> cal = SampleCalendar() | ||
2202 | 151 | >>> cal.addEvent(Event('a')) | ||
2203 | 152 | >>> cal.addEvent(Event('b')) | ||
2204 | 153 | >>> cal.addEvent(Event('c')) | ||
2205 | 154 | >>> len(list(cal)) | ||
2206 | 155 | 3 | ||
2207 | 156 | |||
2208 | 157 | >>> cal2 = SampleCalendar() | ||
2209 | 158 | >>> cal2.update(cal) | ||
2210 | 159 | >>> len(list(cal2)) | ||
2211 | 160 | 3 | ||
2212 | 161 | |||
2213 | 162 | >>> cal.clear() | ||
2214 | 163 | >>> list(cal) | ||
2215 | 164 | [] | ||
2216 | 165 | |||
2217 | 166 | """ | ||
2218 | 167 | |||
2219 | 168 | def update(self, calendar): | ||
2220 | 169 | """Add all events from another calendar to this calendar.""" | ||
2221 | 170 | for event in calendar: | ||
2222 | 171 | self.addEvent(event) | ||
2223 | 172 | |||
2224 | 173 | def clear(self): | ||
2225 | 174 | """Remove all events from the calendar.""" | ||
2226 | 175 | for event in list(self): | ||
2227 | 176 | self.removeEvent(event) | ||
2228 | 177 | |||
2229 | 178 | |||
2230 | 179 | class CalendarEventMixin: | ||
2231 | 180 | """Mixin for implementing ICalendarEvent comparison methods. | ||
2232 | 181 | |||
2233 | 182 | Calendar events are equal iff all their attributes are equal. We can get a | ||
2234 | 183 | list of those attributes easily because ICalendarEvent is a schema. | ||
2235 | 184 | |||
2236 | 185 | >>> from schoolbell.interfaces import ICalendarEvent | ||
2237 | 186 | >>> from zope.schema import getFieldNames | ||
2238 | 187 | >>> all_attrs = getFieldNames(ICalendarEvent) | ||
2239 | 188 | >>> 'unique_id' in all_attrs | ||
2240 | 189 | True | ||
2241 | 190 | >>> '__eq__' not in all_attrs | ||
2242 | 191 | True | ||
2243 | 192 | |||
2244 | 193 | We will create a bunch of Event objects that differ in exactly one | ||
2245 | 194 | attribute and compare them. | ||
2246 | 195 | |||
2247 | 196 | >>> class Event(CalendarEventMixin): | ||
2248 | 197 | ... def __init__(self, **kw): | ||
2249 | 198 | ... for attr in all_attrs: | ||
2250 | 199 | ... setattr(self, attr, '%s_default_value' % attr) | ||
2251 | 200 | ... for attr, value in kw.items(): | ||
2252 | 201 | ... setattr(self, attr, value) | ||
2253 | 202 | |||
2254 | 203 | >>> e1 = Event() | ||
2255 | 204 | >>> for attr in all_attrs: | ||
2256 | 205 | ... e2 = Event() | ||
2257 | 206 | ... setattr(e2, attr, 'some other value') | ||
2258 | 207 | ... assert e1 != e2, 'change in %s was not noticed' % attr | ||
2259 | 208 | |||
2260 | 209 | If you have two events with the same values in all ICalendarEvent | ||
2261 | 210 | attributes, they are equal | ||
2262 | 211 | |||
2263 | 212 | >>> e1 = Event() | ||
2264 | 213 | >>> e2 = Event() | ||
2265 | 214 | >>> e1 == e2 | ||
2266 | 215 | True | ||
2267 | 216 | |||
2268 | 217 | even if they have extra attributes | ||
2269 | 218 | |||
2270 | 219 | >>> e1 = Event() | ||
2271 | 220 | >>> e1.annotation = 'a' | ||
2272 | 221 | >>> e2 = Event() | ||
2273 | 222 | >>> e2.annotation = 'b' | ||
2274 | 223 | >>> e1 == e2 | ||
2275 | 224 | True | ||
2276 | 225 | |||
2277 | 226 | Events are ordered by their date and time, title and, finally, UID (to | ||
2278 | 227 | break any ties and provide a stable consistent ordering). | ||
2279 | 228 | |||
2280 | 229 | >>> from datetime import datetime | ||
2281 | 230 | |||
2282 | 231 | >>> e1 = Event(dtstart=datetime(2004, 12, 15)) | ||
2283 | 232 | >>> e2 = Event(dtstart=datetime(2004, 12, 16)) | ||
2284 | 233 | >>> e1 < e2 | ||
2285 | 234 | True | ||
2286 | 235 | |||
2287 | 236 | >>> e1 = Event(dtstart=datetime(2004, 12, 15), title="A") | ||
2288 | 237 | >>> e2 = Event(dtstart=datetime(2004, 12, 15), title="B") | ||
2289 | 238 | >>> e1 < e2 | ||
2290 | 239 | True | ||
2291 | 240 | |||
2292 | 241 | >>> e1 = Event(dtstart=datetime(2004, 12, 1), title="A", unique_id="X") | ||
2293 | 242 | >>> e2 = Event(dtstart=datetime(2004, 12, 1), title="A", unique_id="Y") | ||
2294 | 243 | >>> e1 < e2 | ||
2295 | 244 | True | ||
2296 | 245 | |||
2297 | 246 | """ | ||
2298 | 247 | |||
2299 | 248 | def __eq__(self, other): | ||
2300 | 249 | """Check whether two calendar events are equal.""" | ||
2301 | 250 | return (self.unique_id, self.dtstart, self.duration, self.title, | ||
2302 | 251 | self.location, self.recurrence) \ | ||
2303 | 252 | == (other.unique_id, other.dtstart, other.duration, other.title, | ||
2304 | 253 | other.location, other.recurrence) | ||
2305 | 254 | |||
2306 | 255 | def __ne__(self, other): | ||
2307 | 256 | return not self.__eq__(other) | ||
2308 | 257 | |||
2309 | 258 | def __lt__(self, other): | ||
2310 | 259 | return (self.dtstart, self.title, self.unique_id) \ | ||
2311 | 260 | < (other.dtstart, other.title, other.unique_id) | ||
2312 | 261 | |||
2313 | 262 | def __gt__(self, other): | ||
2314 | 263 | return (self.dtstart, self.title, self.unique_id) \ | ||
2315 | 264 | > (other.dtstart, other.title, other.unique_id) | ||
2316 | 265 | |||
2317 | 266 | def __le__(self, other): | ||
2318 | 267 | return (self.dtstart, self.title, self.unique_id) \ | ||
2319 | 268 | <= (other.dtstart, other.title, other.unique_id) | ||
2320 | 269 | |||
2321 | 270 | def __ge__(self, other): | ||
2322 | 271 | return (self.dtstart, self.title, self.unique_id) \ | ||
2323 | 272 | >= (other.dtstart, other.title, other.unique_id) | ||
2324 | 273 | |||
2325 | 274 | def hasOccurrences(self): | ||
2326 | 275 | raise NotImplementedError # TODO | ||
2327 | 276 | |||
2328 | 277 | def replace(self, **kw): | ||
2329 | 278 | r"""Return a copy of this event with some attributes replaced. | ||
2330 | 279 | |||
2331 | 280 | >>> from schoolbell.interfaces import ICalendarEvent | ||
2332 | 281 | >>> from zope.schema import getFieldNames | ||
2333 | 282 | >>> all_attrs = getFieldNames(ICalendarEvent) | ||
2334 | 283 | >>> class Event(CalendarEventMixin): | ||
2335 | 284 | ... def __init__(self, **kw): | ||
2336 | 285 | ... for attr in all_attrs: | ||
2337 | 286 | ... setattr(self, attr, '%s_default_value' % attr) | ||
2338 | 287 | ... for attr, value in kw.items(): | ||
2339 | 288 | ... setattr(self, attr, value) | ||
2340 | 289 | |||
2341 | 290 | >>> from datetime import datetime, timedelta | ||
2342 | 291 | >>> e1 = Event(dtstart=datetime(2004, 12, 15, 18, 57), | ||
2343 | 292 | ... duration=timedelta(minutes=15), | ||
2344 | 293 | ... title='Work on schoolbell.simple', | ||
2345 | 294 | ... location=None) | ||
2346 | 295 | |||
2347 | 296 | >>> e2 = e1.replace(location=u'Matar\u00f3') | ||
2348 | 297 | >>> e2 == e1 | ||
2349 | 298 | False | ||
2350 | 299 | >>> e2.title == e1.title | ||
2351 | 300 | True | ||
2352 | 301 | >>> e2.location | ||
2353 | 302 | u'Matar\xf3' | ||
2354 | 303 | |||
2355 | 304 | >>> e3 = e2.replace(location=None) | ||
2356 | 305 | >>> e3 == e1 | ||
2357 | 306 | True | ||
2358 | 307 | |||
2359 | 308 | """ | ||
2360 | 309 | # The import is here to avoid cyclic dependencies | ||
2361 | 310 | from schoolbell.simple import SimpleCalendarEvent | ||
2362 | 311 | for attr in ['dtstart', 'duration', 'title', 'description', | ||
2363 | 312 | 'location', 'unique_id', 'recurrence']: | ||
2364 | 313 | kw.setdefault(attr, getattr(self, attr)) | ||
2365 | 314 | return SimpleCalendarEvent(**kw) | ||
2366 | 315 | 0 | ||
2367 | === removed file 'lib/schoolbell/simple.py' | |||
2368 | --- lib/schoolbell/simple.py 2005-10-31 18:29:12 +0000 | |||
2369 | +++ lib/schoolbell/simple.py 1970-01-01 00:00:00 +0000 | |||
2370 | @@ -1,96 +0,0 @@ | |||
2371 | 1 | """ | ||
2372 | 2 | Simple calendar events and calendars. | ||
2373 | 3 | """ | ||
2374 | 4 | |||
2375 | 5 | import datetime | ||
2376 | 6 | import random | ||
2377 | 7 | import email.Utils | ||
2378 | 8 | from zope.interface import implements | ||
2379 | 9 | from schoolbell.interfaces import ICalendar, ICalendarEvent | ||
2380 | 10 | from schoolbell.mixins import CalendarEventMixin, CalendarMixin | ||
2381 | 11 | |||
2382 | 12 | __metaclass__ = type | ||
2383 | 13 | |||
2384 | 14 | |||
2385 | 15 | class SimpleCalendarEvent(CalendarEventMixin): | ||
2386 | 16 | """A simple implementation of ICalendarEvent. | ||
2387 | 17 | |||
2388 | 18 | >>> from datetime import datetime, timedelta | ||
2389 | 19 | >>> from zope.interface.verify import verifyObject | ||
2390 | 20 | >>> e = SimpleCalendarEvent(datetime(2004, 12, 15, 18, 57), | ||
2391 | 21 | ... timedelta(minutes=15), | ||
2392 | 22 | ... 'Work on schoolbell.simple') | ||
2393 | 23 | >>> verifyObject(ICalendarEvent, e) | ||
2394 | 24 | True | ||
2395 | 25 | |||
2396 | 26 | If you do not specify a unique ID, a random one is generated | ||
2397 | 27 | |||
2398 | 28 | >>> e.unique_id is not None | ||
2399 | 29 | True | ||
2400 | 30 | |||
2401 | 31 | """ | ||
2402 | 32 | |||
2403 | 33 | implements(ICalendarEvent) | ||
2404 | 34 | |||
2405 | 35 | def __init__(self, dtstart, duration, title, description=None, location=None, unique_id=None, | ||
2406 | 36 | recurrence=None): | ||
2407 | 37 | self.dtstart = dtstart | ||
2408 | 38 | self.duration = duration | ||
2409 | 39 | self.title = title | ||
2410 | 40 | self.description=description | ||
2411 | 41 | self.location = location | ||
2412 | 42 | self.recurrence = recurrence | ||
2413 | 43 | self.unique_id = unique_id | ||
2414 | 44 | if not self.unique_id: | ||
2415 | 45 | self.unique_id = new_unique_id() | ||
2416 | 46 | |||
2417 | 47 | |||
2418 | 48 | class ImmutableCalendar(CalendarMixin): | ||
2419 | 49 | """A simple read-only calendar. | ||
2420 | 50 | |||
2421 | 51 | >>> from datetime import datetime, timedelta | ||
2422 | 52 | >>> from zope.interface.verify import verifyObject | ||
2423 | 53 | >>> e = SimpleCalendarEvent(datetime(2004, 12, 15, 18, 57), | ||
2424 | 54 | ... timedelta(minutes=15), | ||
2425 | 55 | ... 'Work on schoolbell.simple') | ||
2426 | 56 | >>> calendar = ImmutableCalendar([e]) | ||
2427 | 57 | >>> verifyObject(ICalendar, calendar) | ||
2428 | 58 | True | ||
2429 | 59 | |||
2430 | 60 | >>> [e.title for e in calendar] | ||
2431 | 61 | ['Work on schoolbell.simple'] | ||
2432 | 62 | |||
2433 | 63 | """ | ||
2434 | 64 | |||
2435 | 65 | implements(ICalendar) | ||
2436 | 66 | |||
2437 | 67 | def __init__(self, events=()): | ||
2438 | 68 | self._events = tuple(events) | ||
2439 | 69 | |||
2440 | 70 | def __iter__(self): | ||
2441 | 71 | return iter(self._events) | ||
2442 | 72 | |||
2443 | 73 | |||
2444 | 74 | def new_unique_id(): | ||
2445 | 75 | """Generate a new unique ID for a calendar event. | ||
2446 | 76 | |||
2447 | 77 | UID is randomly generated and follows RFC 822 addr-spec: | ||
2448 | 78 | |||
2449 | 79 | >>> uid = new_unique_id() | ||
2450 | 80 | >>> '@' in uid | ||
2451 | 81 | True | ||
2452 | 82 | |||
2453 | 83 | Note that it does not have the angle brackets | ||
2454 | 84 | |||
2455 | 85 | >>> '<' not in uid | ||
2456 | 86 | True | ||
2457 | 87 | >>> '>' not in uid | ||
2458 | 88 | True | ||
2459 | 89 | |||
2460 | 90 | """ | ||
2461 | 91 | more_uniqueness = '%d.%d' % (datetime.datetime.now().microsecond, | ||
2462 | 92 | random.randrange(10 ** 6, 10 ** 7)) | ||
2463 | 93 | # generate an rfc-822 style id and strip angle brackets | ||
2464 | 94 | unique_id = email.Utils.make_msgid(more_uniqueness)[1:-1] | ||
2465 | 95 | return unique_id | ||
2466 | 96 | |||
2467 | 97 | 0 | ||
2468 | === removed directory 'lib/schoolbell/tests' | |||
2469 | === removed file 'lib/schoolbell/tests/__init__.py' | |||
2470 | --- lib/schoolbell/tests/__init__.py 2005-10-31 18:29:12 +0000 | |||
2471 | +++ lib/schoolbell/tests/__init__.py 1970-01-01 00:00:00 +0000 | |||
2472 | @@ -1,1 +0,0 @@ | |||
2473 | 1 | """Unit tests for SchoolBell""" | ||
2474 | 2 | 0 | ||
2475 | === removed file 'lib/schoolbell/tests/test_icalendar.py' | |||
2476 | --- lib/schoolbell/tests/test_icalendar.py 2005-10-31 18:29:12 +0000 | |||
2477 | +++ lib/schoolbell/tests/test_icalendar.py 1970-01-01 00:00:00 +0000 | |||
2478 | @@ -1,782 +0,0 @@ | |||
2479 | 1 | """ | ||
2480 | 2 | Unit tests for schoolbell.icalendar | ||
2481 | 3 | """ | ||
2482 | 4 | |||
2483 | 5 | import unittest | ||
2484 | 6 | import difflib | ||
2485 | 7 | import time | ||
2486 | 8 | import os | ||
2487 | 9 | from pprint import pformat | ||
2488 | 10 | from textwrap import dedent | ||
2489 | 11 | from datetime import date, timedelta, datetime | ||
2490 | 12 | from StringIO import StringIO | ||
2491 | 13 | |||
2492 | 14 | from zope.testing import doctest | ||
2493 | 15 | |||
2494 | 16 | |||
2495 | 17 | def diff(old, new, oldlabel="expected output", newlabel="actual output"): | ||
2496 | 18 | """Display a unified diff between old text and new text.""" | ||
2497 | 19 | old = old.splitlines() | ||
2498 | 20 | new = new.splitlines() | ||
2499 | 21 | |||
2500 | 22 | diff = ['--- %s' % oldlabel, '+++ %s' % newlabel] | ||
2501 | 23 | |||
2502 | 24 | def dump(tag, x, lo, hi): | ||
2503 | 25 | for i in xrange(lo, hi): | ||
2504 | 26 | diff.append(tag + x[i]) | ||
2505 | 27 | |||
2506 | 28 | differ = difflib.SequenceMatcher(a=old, b=new) | ||
2507 | 29 | for tag, alo, ahi, blo, bhi in differ.get_opcodes(): | ||
2508 | 30 | if tag == 'replace': | ||
2509 | 31 | dump('-', old, alo, ahi) | ||
2510 | 32 | dump('+', new, blo, bhi) | ||
2511 | 33 | elif tag == 'delete': | ||
2512 | 34 | dump('-', old, alo, ahi) | ||
2513 | 35 | elif tag == 'insert': | ||
2514 | 36 | dump('+', new, blo, bhi) | ||
2515 | 37 | elif tag == 'equal': | ||
2516 | 38 | dump(' ', old, alo, ahi) | ||
2517 | 39 | else: | ||
2518 | 40 | raise AssertionError('unknown tag %r' % tag) | ||
2519 | 41 | return "\n".join(diff) | ||
2520 | 42 | |||
2521 | 43 | |||
2522 | 44 | class TimezoneTestMixin: | ||
2523 | 45 | """A mixin for tests that fiddle with timezones.""" | ||
2524 | 46 | |||
2525 | 47 | def setUp(self): | ||
2526 | 48 | self.have_tzset = hasattr(time, 'tzset') | ||
2527 | 49 | self.touched_tz = False | ||
2528 | 50 | self.old_tz = os.getenv('TZ') | ||
2529 | 51 | |||
2530 | 52 | def tearDown(self): | ||
2531 | 53 | if self.touched_tz: | ||
2532 | 54 | self.setTZ(self.old_tz) | ||
2533 | 55 | |||
2534 | 56 | def setTZ(self, tz): | ||
2535 | 57 | self.touched_tz = True | ||
2536 | 58 | if tz is None: | ||
2537 | 59 | os.unsetenv('TZ') | ||
2538 | 60 | else: | ||
2539 | 61 | os.putenv('TZ', tz) | ||
2540 | 62 | time.tzset() | ||
2541 | 63 | |||
2542 | 64 | |||
2543 | 65 | class TestParseDateTime(TimezoneTestMixin, unittest.TestCase): | ||
2544 | 66 | |||
2545 | 67 | def test_timezones(self): | ||
2546 | 68 | # The simple tests are in the doctest of parse_date_time. | ||
2547 | 69 | from schoolbell.icalendar import parse_date_time | ||
2548 | 70 | |||
2549 | 71 | if not self.have_tzset: | ||
2550 | 72 | return # Do not run this test on Windows | ||
2551 | 73 | |||
2552 | 74 | self.setTZ('UTC') | ||
2553 | 75 | dt = parse_date_time('20041029T125031Z') | ||
2554 | 76 | self.assertEquals(dt, datetime(2004, 10, 29, 12, 50, 31)) | ||
2555 | 77 | |||
2556 | 78 | self.setTZ('EET-2EEST') | ||
2557 | 79 | dt = parse_date_time('20041029T095031Z') # daylight savings | ||
2558 | 80 | self.assertEquals(dt, datetime(2004, 10, 29, 12, 50, 31)) | ||
2559 | 81 | dt = parse_date_time('20041129T095031Z') # no daylight savings | ||
2560 | 82 | self.assertEquals(dt, datetime(2004, 11, 29, 11, 50, 31)) | ||
2561 | 83 | |||
2562 | 84 | |||
2563 | 85 | class TestPeriod(unittest.TestCase): | ||
2564 | 86 | |||
2565 | 87 | def test(self): | ||
2566 | 88 | from schoolbell.icalendar import Period | ||
2567 | 89 | dt1 = datetime(2001, 2, 3, 14, 30, 5) | ||
2568 | 90 | dt2 = datetime(2001, 2, 3, 16, 35, 20) | ||
2569 | 91 | td = dt2 - dt1 | ||
2570 | 92 | p1 = Period(dt1, dt2) | ||
2571 | 93 | self.assertEquals(p1.start, dt1) | ||
2572 | 94 | self.assertEquals(p1.end, dt2) | ||
2573 | 95 | self.assertEquals(p1.duration, td) | ||
2574 | 96 | |||
2575 | 97 | p2 = Period(dt1, td) | ||
2576 | 98 | self.assertEquals(p2.start, dt1) | ||
2577 | 99 | self.assertEquals(p2.end, dt2) | ||
2578 | 100 | self.assertEquals(p2.duration, td) | ||
2579 | 101 | |||
2580 | 102 | self.assertEquals(p1, p2) | ||
2581 | 103 | |||
2582 | 104 | p = Period(dt1, timedelta(0)) | ||
2583 | 105 | self.assertEquals(p.start, dt1) | ||
2584 | 106 | self.assertEquals(p.end, dt1) | ||
2585 | 107 | self.assertEquals(p.duration, timedelta(0)) | ||
2586 | 108 | |||
2587 | 109 | self.assertRaises(ValueError, Period, dt2, dt1) | ||
2588 | 110 | self.assertRaises(ValueError, Period, dt1, -td) | ||
2589 | 111 | |||
2590 | 112 | def test_overlap(self): | ||
2591 | 113 | from schoolbell.icalendar import Period | ||
2592 | 114 | p1 = Period(datetime(2004, 1, 1, 12, 0), timedelta(hours=1)) | ||
2593 | 115 | p2 = Period(datetime(2004, 1, 1, 11, 30), timedelta(hours=1)) | ||
2594 | 116 | p3 = Period(datetime(2004, 1, 1, 12, 30), timedelta(hours=1)) | ||
2595 | 117 | p4 = Period(datetime(2004, 1, 1, 11, 0), timedelta(hours=3)) | ||
2596 | 118 | |||
2597 | 119 | self.assert_(p1.overlaps(p2)) | ||
2598 | 120 | self.assert_(p2.overlaps(p1)) | ||
2599 | 121 | |||
2600 | 122 | self.assert_(p1.overlaps(p3)) | ||
2601 | 123 | self.assert_(p3.overlaps(p1)) | ||
2602 | 124 | |||
2603 | 125 | self.assert_(not p2.overlaps(p3)) | ||
2604 | 126 | self.assert_(not p3.overlaps(p2)) | ||
2605 | 127 | |||
2606 | 128 | self.assert_(p1.overlaps(p4)) | ||
2607 | 129 | self.assert_(p4.overlaps(p1)) | ||
2608 | 130 | |||
2609 | 131 | self.assert_(p1.overlaps(p1)) | ||
2610 | 132 | |||
2611 | 133 | |||
2612 | 134 | class TestVEvent(unittest.TestCase): | ||
2613 | 135 | |||
2614 | 136 | def test_add(self): | ||
2615 | 137 | from schoolbell.icalendar import VEvent, ICalParseError | ||
2616 | 138 | vevent = VEvent() | ||
2617 | 139 | value, params = 'bar', {'VALUE': 'TEXT'} | ||
2618 | 140 | vevent.add('foo', value, params) | ||
2619 | 141 | self.assertEquals(vevent._props, {'FOO': [(value, params)]}) | ||
2620 | 142 | value2 = 'guug' | ||
2621 | 143 | vevent.add('fie', value2) | ||
2622 | 144 | self.assertEquals(vevent._props, {'FOO': [(value, params)], | ||
2623 | 145 | 'FIE': [(value2, {})]}) | ||
2624 | 146 | vevent.add('fie', value, params) | ||
2625 | 147 | self.assertEquals(vevent._props, {'FOO': [(value, params)], | ||
2626 | 148 | 'FIE': [(value2, {}), | ||
2627 | 149 | (value, params)]}) | ||
2628 | 150 | |||
2629 | 151 | # adding a singleton property twice | ||
2630 | 152 | vevent.add('uid', '1') | ||
2631 | 153 | self.assertRaises(ICalParseError, vevent.add, 'uid', '2') | ||
2632 | 154 | |||
2633 | 155 | def test_hasProp(self): | ||
2634 | 156 | from schoolbell.icalendar import VEvent | ||
2635 | 157 | vevent = VEvent() | ||
2636 | 158 | vevent.add('foo', 'bar', {}) | ||
2637 | 159 | self.assert_(vevent.hasProp('foo')) | ||
2638 | 160 | self.assert_(vevent.hasProp('Foo')) | ||
2639 | 161 | self.assert_(not vevent.hasProp('baz')) | ||
2640 | 162 | |||
2641 | 163 | def test__getType(self): | ||
2642 | 164 | from schoolbell.icalendar import VEvent | ||
2643 | 165 | vevent = VEvent() | ||
2644 | 166 | vevent.add('x-explicit', '', {'VALUE': 'INTEGER'}) | ||
2645 | 167 | vevent.add('dtstart', 'implicit type', {}) | ||
2646 | 168 | vevent.add('x-default', '', {}) | ||
2647 | 169 | self.assertEquals(vevent._getType('x-explicit'), 'INTEGER') | ||
2648 | 170 | self.assertEquals(vevent._getType('dtstart'), 'DATE-TIME') | ||
2649 | 171 | self.assertEquals(vevent._getType('x-default'), 'TEXT') | ||
2650 | 172 | self.assertEquals(vevent._getType('X-Explicit'), 'INTEGER') | ||
2651 | 173 | self.assertEquals(vevent._getType('DtStart'), 'DATE-TIME') | ||
2652 | 174 | self.assertEquals(vevent._getType('X-Default'), 'TEXT') | ||
2653 | 175 | self.assertRaises(KeyError, vevent._getType, 'nonexistent') | ||
2654 | 176 | |||
2655 | 177 | def test_getOne(self): | ||
2656 | 178 | from schoolbell.icalendar import VEvent | ||
2657 | 179 | vevent = VEvent() | ||
2658 | 180 | |||
2659 | 181 | vevent.add('foo', 'bar', {}) | ||
2660 | 182 | self.assertEquals(vevent.getOne('foo'), 'bar') | ||
2661 | 183 | self.assertEquals(vevent.getOne('Foo'), 'bar') | ||
2662 | 184 | self.assertEquals(vevent.getOne('baz'), None) | ||
2663 | 185 | self.assertEquals(vevent.getOne('baz', 'quux'), 'quux') | ||
2664 | 186 | self.assertEquals(vevent.getOne('dtstart', 'quux'), 'quux') | ||
2665 | 187 | |||
2666 | 188 | vevent.add('int-foo', '42', {'VALUE': 'INTEGER'}) | ||
2667 | 189 | vevent.add('int-bad', 'xyzzy', {'VALUE': 'INTEGER'}) | ||
2668 | 190 | self.assertEquals(vevent.getOne('int-foo'), 42) | ||
2669 | 191 | self.assertEquals(vevent.getOne('Int-Foo'), 42) | ||
2670 | 192 | self.assertRaises(ValueError, vevent.getOne, 'int-bad') | ||
2671 | 193 | |||
2672 | 194 | vevent.add('date-foo', '20030405', {'VALUE': 'DATE'}) | ||
2673 | 195 | vevent.add('date-bad1', '20030405T1234', {'VALUE': 'DATE'}) | ||
2674 | 196 | vevent.add('date-bad2', '2003', {'VALUE': 'DATE'}) | ||
2675 | 197 | vevent.add('date-bad3', '200301XX', {'VALUE': 'DATE'}) | ||
2676 | 198 | self.assertEquals(vevent.getOne('date-Foo'), date(2003, 4, 5)) | ||
2677 | 199 | self.assertRaises(ValueError, vevent.getOne, 'date-bad1') | ||
2678 | 200 | self.assertRaises(ValueError, vevent.getOne, 'date-bad2') | ||
2679 | 201 | self.assertRaises(ValueError, vevent.getOne, 'date-bad3') | ||
2680 | 202 | |||
2681 | 203 | vevent.add('datetime-foo1', '20030405T060708', {'VALUE': 'DATE-TIME'}) | ||
2682 | 204 | vevent.add('datetime-foo2', '20030405T060708', {'VALUE': 'DATE-TIME'}) | ||
2683 | 205 | vevent.add('datetime-bad1', '20030405T010203444444', | ||
2684 | 206 | {'VALUE': 'DATE-TIME'}) | ||
2685 | 207 | vevent.add('datetime-bad2', '2003', {'VALUE': 'DATE-TIME'}) | ||
2686 | 208 | self.assertEquals(vevent.getOne('datetime-foo1'), | ||
2687 | 209 | datetime(2003, 4, 5, 6, 7, 8)) | ||
2688 | 210 | self.assertEquals(vevent.getOne('Datetime-Foo2'), | ||
2689 | 211 | datetime(2003, 4, 5, 6, 7, 8)) | ||
2690 | 212 | self.assertRaises(ValueError, vevent.getOne, 'datetime-bad1') | ||
2691 | 213 | self.assertRaises(ValueError, vevent.getOne, 'datetime-bad2') | ||
2692 | 214 | |||
2693 | 215 | vevent.add('dur-foo1', '+P11D', {'VALUE': 'DURATION'}) | ||
2694 | 216 | vevent.add('dur-foo2', '-P2W', {'VALUE': 'DURATION'}) | ||
2695 | 217 | vevent.add('dur-foo3', 'P1DT2H3M4S', {'VALUE': 'DURATION'}) | ||
2696 | 218 | vevent.add('dur-foo4', 'PT2H', {'VALUE': 'DURATION'}) | ||
2697 | 219 | vevent.add('dur-bad1', 'xyzzy', {'VALUE': 'DURATION'}) | ||
2698 | 220 | self.assertEquals(vevent.getOne('dur-foo1'), timedelta(days=11)) | ||
2699 | 221 | self.assertEquals(vevent.getOne('Dur-Foo2'), -timedelta(weeks=2)) | ||
2700 | 222 | self.assertEquals(vevent.getOne('Dur-Foo3'), | ||
2701 | 223 | timedelta(days=1, hours=2, minutes=3, seconds=4)) | ||
2702 | 224 | self.assertEquals(vevent.getOne('DUR-FOO4'), timedelta(hours=2)) | ||
2703 | 225 | self.assertRaises(ValueError, vevent.getOne, 'dur-bad1') | ||
2704 | 226 | |||
2705 | 227 | vevent.add('unknown', 'magic', {'VALUE': 'UNKNOWN-TYPE'}) | ||
2706 | 228 | self.assertEquals(vevent.getOne('unknown'), 'magic') | ||
2707 | 229 | |||
2708 | 230 | def test_iterDates(self): | ||
2709 | 231 | from schoolbell.icalendar import VEvent | ||
2710 | 232 | vevent = VEvent() | ||
2711 | 233 | vevent.all_day_event = True | ||
2712 | 234 | vevent.dtstart = date(2003, 1, 2) | ||
2713 | 235 | vevent.dtend = date(2003, 1, 5) | ||
2714 | 236 | vevent.duration = timedelta(days=3) | ||
2715 | 237 | vevent.rdates = [] | ||
2716 | 238 | vevent.exdates = [] | ||
2717 | 239 | self.assertEquals(list(vevent.iterDates()), | ||
2718 | 240 | [date(2003, 1, 2), date(2003, 1, 3), date(2003, 1, 4)]) | ||
2719 | 241 | |||
2720 | 242 | vevent.all_day_event = False; | ||
2721 | 243 | self.assertRaises(ValueError, list, vevent.iterDates()) | ||
2722 | 244 | |||
2723 | 245 | def test_iterDates_with_rdate_exdate(self): | ||
2724 | 246 | from schoolbell.icalendar import VEvent | ||
2725 | 247 | vevent = VEvent() | ||
2726 | 248 | vevent.all_day_event = True | ||
2727 | 249 | vevent.dtstart = date(2003, 1, 5) | ||
2728 | 250 | vevent.dtend = date(2003, 1, 6) | ||
2729 | 251 | vevent.duration = timedelta(days=1) | ||
2730 | 252 | vevent.rdates = [date(2003, 1, 2), date(2003, 1, 8), date(2003, 1, 8)] | ||
2731 | 253 | vevent.exdates = [] | ||
2732 | 254 | expected = [date(2003, 1, 2), date(2003, 1, 5), date(2003, 1, 8)] | ||
2733 | 255 | self.assertEquals(list(vevent.iterDates()), expected) | ||
2734 | 256 | |||
2735 | 257 | vevent.exdates = [date(2003, 1, 6)] | ||
2736 | 258 | expected = [date(2003, 1, 2), date(2003, 1, 5), date(2003, 1, 8)] | ||
2737 | 259 | self.assertEquals(list(vevent.iterDates()), expected) | ||
2738 | 260 | |||
2739 | 261 | vevent.exdates = [date(2003, 1, 2), date(2003, 1, 2)] | ||
2740 | 262 | expected = [date(2003, 1, 5), date(2003, 1, 8)] | ||
2741 | 263 | self.assertEquals(list(vevent.iterDates()), expected) | ||
2742 | 264 | |||
2743 | 265 | vevent.exdates = [date(2003, 1, 5)] | ||
2744 | 266 | expected = [date(2003, 1, 2), date(2003, 1, 8)] | ||
2745 | 267 | self.assertEquals(list(vevent.iterDates()), expected) | ||
2746 | 268 | |||
2747 | 269 | vevent.dtend = date(2003, 1, 7) | ||
2748 | 270 | vevent.duration = timedelta(days=2) | ||
2749 | 271 | vevent.exdates = [date(2003, 1, 5), date(2003, 1, 3)] | ||
2750 | 272 | expected = [date(2003, 1, 2), date(2003, 1, 3), | ||
2751 | 273 | date(2003, 1, 8), date(2003, 1, 9)] | ||
2752 | 274 | self.assertEquals(list(vevent.iterDates()), expected) | ||
2753 | 275 | |||
2754 | 276 | def test_validate_error_cases(self): | ||
2755 | 277 | from schoolbell.icalendar import VEvent, ICalParseError | ||
2756 | 278 | |||
2757 | 279 | vevent = VEvent() | ||
2758 | 280 | self.assertRaises(ICalParseError, vevent.validate) | ||
2759 | 281 | |||
2760 | 282 | vevent = VEvent() | ||
2761 | 283 | vevent.add('dtstart', 'xyzzy', {'VALUE': 'TEXT'}) | ||
2762 | 284 | self.assertRaises(ICalParseError, vevent.validate) | ||
2763 | 285 | |||
2764 | 286 | vevent = VEvent() | ||
2765 | 287 | vevent.add('dtstart', '20010203', {'VALUE': 'DATE'}) | ||
2766 | 288 | vevent.add('dtend', '20010203T0000', {'VALUE': 'DATE-TIME'}) | ||
2767 | 289 | self.assertRaises(ICalParseError, vevent.validate) | ||
2768 | 290 | |||
2769 | 291 | vevent = VEvent() | ||
2770 | 292 | vevent.add('dtstart', '20010203', {'VALUE': 'DATE'}) | ||
2771 | 293 | vevent.add('dtend', '20010203', {'VALUE': 'DATE'}) | ||
2772 | 294 | vevent.add('duration', 'P1D', {}) | ||
2773 | 295 | self.assertRaises(ICalParseError, vevent.validate) | ||
2774 | 296 | |||
2775 | 297 | vevent = VEvent() | ||
2776 | 298 | vevent.add('dtstart', '20010203', {'VALUE': 'DATE'}) | ||
2777 | 299 | vevent.add('duration', 'two years', {'VALUE': 'TEXT'}) | ||
2778 | 300 | self.assertRaises(ICalParseError, vevent.validate) | ||
2779 | 301 | |||
2780 | 302 | def test_validate_all_day_events(self): | ||
2781 | 303 | from schoolbell.icalendar import VEvent, ICalParseError | ||
2782 | 304 | |||
2783 | 305 | vevent = VEvent() | ||
2784 | 306 | vevent.add('summary', 'An event', {}) | ||
2785 | 307 | vevent.add('uid', 'unique', {}) | ||
2786 | 308 | vevent.add('dtstart', '20010203', {'VALUE': 'DATE'}) | ||
2787 | 309 | vevent.validate() | ||
2788 | 310 | self.assert_(vevent.all_day_event) | ||
2789 | 311 | self.assertEquals(vevent.summary, 'An event') | ||
2790 | 312 | self.assertEquals(vevent.uid, 'unique') | ||
2791 | 313 | self.assertEquals(vevent.dtend, date(2001, 2, 4)) | ||
2792 | 314 | self.assertEquals(vevent.duration, timedelta(days=1)) | ||
2793 | 315 | |||
2794 | 316 | vevent = VEvent() | ||
2795 | 317 | vevent.add('summary', 'An\\nevent\\; with backslashes', {}) | ||
2796 | 318 | vevent.add('uid', 'unique2', {}) | ||
2797 | 319 | vevent.add('dtstart', '20010203', {'VALUE': 'DATE'}) | ||
2798 | 320 | vevent.add('dtend', '20010205', {'VALUE': 'DATE'}) | ||
2799 | 321 | vevent.validate() | ||
2800 | 322 | self.assertEquals(vevent.summary, 'An\nevent; with backslashes') | ||
2801 | 323 | self.assert_(vevent.all_day_event) | ||
2802 | 324 | self.assertEquals(vevent.dtstart, date(2001, 2, 3)) | ||
2803 | 325 | self.assertEquals(vevent.uid, 'unique2') | ||
2804 | 326 | self.assertEquals(vevent.dtend, date(2001, 2, 5)) | ||
2805 | 327 | self.assertEquals(vevent.duration, timedelta(days=2)) | ||
2806 | 328 | |||
2807 | 329 | vevent = VEvent() | ||
2808 | 330 | vevent.add('dtstart', '20010203', {'VALUE': 'DATE'}) | ||
2809 | 331 | vevent.add('uid', 'unique3', {}) | ||
2810 | 332 | vevent.add('duration', 'P2D') | ||
2811 | 333 | vevent.validate() | ||
2812 | 334 | self.assertEquals(vevent.summary, None) | ||
2813 | 335 | self.assert_(vevent.all_day_event) | ||
2814 | 336 | self.assertEquals(vevent.dtstart, date(2001, 2, 3)) | ||
2815 | 337 | self.assertEquals(vevent.uid, 'unique3') | ||
2816 | 338 | self.assertEquals(vevent.dtend, date(2001, 2, 5)) | ||
2817 | 339 | self.assertEquals(vevent.duration, timedelta(days=2)) | ||
2818 | 340 | |||
2819 | 341 | vevent = VEvent() | ||
2820 | 342 | vevent.add('dtstart', '20010203', {'VALUE': 'DATE'}) | ||
2821 | 343 | vevent.add('uid', 'unique4', {}) | ||
2822 | 344 | vevent.add('dtend', '20010201', {'VALUE': 'DATE'}) | ||
2823 | 345 | self.assertRaises(ICalParseError, vevent.validate) | ||
2824 | 346 | |||
2825 | 347 | vevent = VEvent() | ||
2826 | 348 | vevent.add('dtstart', '20010203', {'VALUE': 'DATE'}) | ||
2827 | 349 | vevent.add('uid', 'unique5', {}) | ||
2828 | 350 | vevent.add('dtend', '20010203', {'VALUE': 'DATE'}) | ||
2829 | 351 | self.assertRaises(ICalParseError, vevent.validate) | ||
2830 | 352 | |||
2831 | 353 | def test_validate_not_all_day_events(self): | ||
2832 | 354 | from schoolbell.icalendar import VEvent, ICalParseError | ||
2833 | 355 | |||
2834 | 356 | vevent = VEvent() | ||
2835 | 357 | vevent.add('dtstart', '20010203T040506') | ||
2836 | 358 | vevent.add('uid', 'unique', {}) | ||
2837 | 359 | vevent.validate() | ||
2838 | 360 | self.assert_(not vevent.all_day_event) | ||
2839 | 361 | self.assertEquals(vevent.dtstart, datetime(2001, 2, 3, 4, 5, 6)) | ||
2840 | 362 | self.assertEquals(vevent.dtend, datetime(2001, 2, 3, 4, 5, 6)) | ||
2841 | 363 | self.assertEquals(vevent.duration, timedelta(days=0)) | ||
2842 | 364 | self.assertEquals(vevent.rdates, []) | ||
2843 | 365 | |||
2844 | 366 | vevent = VEvent() | ||
2845 | 367 | vevent.add('dtstart', '20010203T040000') | ||
2846 | 368 | vevent.add('uid', 'unique', {}) | ||
2847 | 369 | vevent.add('dtend', '20010204T050102') | ||
2848 | 370 | vevent.validate() | ||
2849 | 371 | self.assert_(not vevent.all_day_event) | ||
2850 | 372 | self.assertEquals(vevent.dtstart, datetime(2001, 2, 3, 4, 0, 0)) | ||
2851 | 373 | self.assertEquals(vevent.dtend, datetime(2001, 2, 4, 5, 1, 2)) | ||
2852 | 374 | self.assertEquals(vevent.duration, timedelta(days=1, hours=1, | ||
2853 | 375 | minutes=1, seconds=2)) | ||
2854 | 376 | |||
2855 | 377 | vevent = VEvent() | ||
2856 | 378 | vevent.add('dtstart', '20010203T040000') | ||
2857 | 379 | vevent.add('uid', 'unique', {}) | ||
2858 | 380 | vevent.add('duration', 'P1DT1H1M2S') | ||
2859 | 381 | vevent.validate() | ||
2860 | 382 | self.assert_(not vevent.all_day_event) | ||
2861 | 383 | self.assertEquals(vevent.dtstart, datetime(2001, 2, 3, 4, 0, 0)) | ||
2862 | 384 | self.assertEquals(vevent.dtend, datetime(2001, 2, 4, 5, 1, 2)) | ||
2863 | 385 | self.assertEquals(vevent.duration, timedelta(days=1, hours=1, | ||
2864 | 386 | minutes=1, seconds=2)) | ||
2865 | 387 | |||
2866 | 388 | vevent = VEvent() | ||
2867 | 389 | vevent.add('dtstart', '20010203T010203') | ||
2868 | 390 | vevent.add('uid', 'unique', {}) | ||
2869 | 391 | vevent.add('rdate', '20010205T040506') | ||
2870 | 392 | vevent.add('exdate', '20010206T040506') | ||
2871 | 393 | vevent.validate() | ||
2872 | 394 | self.assertEquals(vevent.rdates, [datetime(2001, 2, 5, 4, 5, 6)]) | ||
2873 | 395 | self.assertEquals(vevent.exdates, [datetime(2001, 2, 6, 4, 5, 6)]) | ||
2874 | 396 | |||
2875 | 397 | vevent = VEvent() | ||
2876 | 398 | vevent.add('dtstart', '20010203T010203') | ||
2877 | 399 | vevent.add('uid', 'unique', {}) | ||
2878 | 400 | vevent.add('exdate', '20010206,20020307', {'VALUE': 'DATE'}) | ||
2879 | 401 | vevent.add('rrule', 'FREQ=DAILY') | ||
2880 | 402 | vevent.validate() | ||
2881 | 403 | self.assertEquals(vevent.exdates, [date(2001, 2, 6), date(2002, 3, 7)]) | ||
2882 | 404 | |||
2883 | 405 | vevent = VEvent() | ||
2884 | 406 | vevent.add('dtstart', '20010203T010203') | ||
2885 | 407 | vevent.add('uid', 'unique', {}) | ||
2886 | 408 | vevent.add('dtend', '20010203T010202') | ||
2887 | 409 | self.assertRaises(ICalParseError, vevent.validate) | ||
2888 | 410 | |||
2889 | 411 | def test_validate_location(self): | ||
2890 | 412 | from schoolbell.icalendar import VEvent | ||
2891 | 413 | vevent = VEvent() | ||
2892 | 414 | vevent.add('dtstart', '20010203T040506') | ||
2893 | 415 | vevent.add('uid', 'unique5', {}) | ||
2894 | 416 | vevent.add('location', 'Somewhere') | ||
2895 | 417 | vevent.validate() | ||
2896 | 418 | self.assertEquals(vevent.location, 'Somewhere') | ||
2897 | 419 | |||
2898 | 420 | # TODO: recurring events | ||
2899 | 421 | ## def test_validate_rrule(self): | ||
2900 | 422 | ## from schoolbell.icalendar import VEvent | ||
2901 | 423 | ## vevent = VEvent() | ||
2902 | 424 | ## vevent.add('dtstart', '20010203T040506') | ||
2903 | 425 | ## vevent.add('uid', 'unique5', {}) | ||
2904 | 426 | ## vevent.add('location', 'Somewhere') | ||
2905 | 427 | ## vevent.add('rrule', 'FREQ=DAILY;COUNT=3') | ||
2906 | 428 | ## vevent.validate() | ||
2907 | 429 | ## | ||
2908 | 430 | ## self.assertEquals(vevent.rrule.interval, 1) | ||
2909 | 431 | ## self.assertEquals(vevent.rrule.count, 3) | ||
2910 | 432 | ## self.assertEquals(vevent.rrule.until, None) | ||
2911 | 433 | ## self.assertEquals(vevent.rrule.exceptions, ()) | ||
2912 | 434 | ## | ||
2913 | 435 | ## def test_validate_rrule_exceptions(self): | ||
2914 | 436 | ## from schoolbell.icalendar import VEvent | ||
2915 | 437 | ## vevent = VEvent() | ||
2916 | 438 | ## vevent.add('dtstart', '20010203T040506') | ||
2917 | 439 | ## vevent.add('uid', 'unique5', {}) | ||
2918 | 440 | ## vevent.add('location', 'Somewhere') | ||
2919 | 441 | ## vevent.add('rrule', 'FREQ=MONTHLY;BYDAY=3MO') | ||
2920 | 442 | ## vevent.add('exdate', '19960402T010000,19960404T010000',) | ||
2921 | 443 | ## vevent.validate() | ||
2922 | 444 | ## | ||
2923 | 445 | ## self.assertEquals(vevent.rrule.interval, 1) | ||
2924 | 446 | ## self.assertEquals(vevent.rrule.count, None) | ||
2925 | 447 | ## self.assertEquals(vevent.rrule.until, None) | ||
2926 | 448 | ## self.assertEquals(vevent.rrule.monthly, 'weekday') | ||
2927 | 449 | ## self.assertEquals(vevent.rrule.exceptions, | ||
2928 | 450 | ## (date(1996, 4, 2), date(1996, 4, 4))) | ||
2929 | 451 | ## self.assert_(not isinstance(vevent.rrule.exceptions[0], datetime)) | ||
2930 | 452 | |||
2931 | 453 | def test_extractListOfDates(self): | ||
2932 | 454 | from schoolbell.icalendar import VEvent, Period, ICalParseError | ||
2933 | 455 | |||
2934 | 456 | vevent = VEvent() | ||
2935 | 457 | vevent.add('rdate', '20010205T040506') | ||
2936 | 458 | vevent.add('rdate', '20010206T040506,20010207T000000') | ||
2937 | 459 | vevent.add('rdate', '20010208', {'VALUE': 'DATE'}) | ||
2938 | 460 | vevent.add('rdate', '20010209T000000/20010210T000000', | ||
2939 | 461 | {'VALUE': 'PERIOD'}) | ||
2940 | 462 | rdates = vevent._extractListOfDates('RDATE', vevent.rdate_types, False) | ||
2941 | 463 | expected = [datetime(2001, 2, 5, 4, 5, 6), | ||
2942 | 464 | datetime(2001, 2, 6, 4, 5, 6), | ||
2943 | 465 | datetime(2001, 2, 7, 0, 0, 0), | ||
2944 | 466 | date(2001, 2, 8), | ||
2945 | 467 | Period(datetime(2001, 2, 9), datetime(2001, 2, 10)), | ||
2946 | 468 | ] | ||
2947 | 469 | self.assertEqual(expected, rdates, | ||
2948 | 470 | diff(pformat(expected), pformat(rdates))) | ||
2949 | 471 | |||
2950 | 472 | vevent = VEvent() | ||
2951 | 473 | vevent.add('rdate', '20010205T040506', {'VALUE': 'TEXT'}) | ||
2952 | 474 | self.assertRaises(ICalParseError, vevent._extractListOfDates, 'RDATE', | ||
2953 | 475 | vevent.rdate_types, False) | ||
2954 | 476 | |||
2955 | 477 | vevent = VEvent() | ||
2956 | 478 | vevent.add('exdate', '20010205T040506/P1D', {'VALUE': 'PERIOD'}) | ||
2957 | 479 | self.assertRaises(ICalParseError, vevent._extractListOfDates, 'EXDATE', | ||
2958 | 480 | vevent.exdate_types, False) | ||
2959 | 481 | |||
2960 | 482 | vevent = VEvent() | ||
2961 | 483 | vevent.add('rdate', '20010208', {'VALUE': 'DATE'}) | ||
2962 | 484 | rdates = vevent._extractListOfDates('RDATE', vevent.rdate_types, True) | ||
2963 | 485 | expected = [date(2001, 2, 8)] | ||
2964 | 486 | self.assertEqual(expected, rdates, | ||
2965 | 487 | diff(pformat(expected), pformat(rdates))) | ||
2966 | 488 | |||
2967 | 489 | vevent = VEvent() | ||
2968 | 490 | vevent.add('rdate', '20010205T040506', {'VALUE': 'DATE-TIME'}) | ||
2969 | 491 | self.assertRaises(ICalParseError, vevent._extractListOfDates, 'RDATE', | ||
2970 | 492 | vevent.rdate_types, True) | ||
2971 | 493 | |||
2972 | 494 | vevent = VEvent() | ||
2973 | 495 | vevent.add('rdate', '20010209T000000/20010210T000000', | ||
2974 | 496 | {'VALUE': 'PERIOD'}) | ||
2975 | 497 | self.assertRaises(ICalParseError, vevent._extractListOfDates, 'RDATE', | ||
2976 | 498 | vevent.rdate_types, True) | ||
2977 | 499 | |||
2978 | 500 | |||
2979 | 501 | class TestICalReader(unittest.TestCase): | ||
2980 | 502 | |||
2981 | 503 | example_ical = dedent("""\ | ||
2982 | 504 | BEGIN:VCALENDAR | ||
2983 | 505 | VERSION | ||
2984 | 506 | :2.0 | ||
2985 | 507 | PRODID | ||
2986 | 508 | :-//Mozilla.org/NONSGML Mozilla Calendar V1.0//EN | ||
2987 | 509 | METHOD | ||
2988 | 510 | :PUBLISH | ||
2989 | 511 | BEGIN:VEVENT | ||
2990 | 512 | UID | ||
2991 | 513 | :956630271 | ||
2992 | 514 | SUMMARY | ||
2993 | 515 | :Christmas Day | ||
2994 | 516 | CLASS | ||
2995 | 517 | :PUBLIC | ||
2996 | 518 | X-MOZILLA-ALARM-DEFAULT-UNITS | ||
2997 | 519 | :minutes | ||
2998 | 520 | X-MOZILLA-ALARM-DEFAULT-LENGTH | ||
2999 | 521 | :15 | ||
3000 | 522 | X-MOZILLA-RECUR-DEFAULT-UNITS | ||
3001 | 523 | :weeks | ||
3002 | 524 | X-MOZILLA-RECUR-DEFAULT-INTERVAL | ||
3003 | 525 | :1 | ||
3004 | 526 | DTSTART | ||
3005 | 527 | ;VALUE=DATE | ||
3006 | 528 | :20031225 | ||
3007 | 529 | DTEND | ||
3008 | 530 | ;VALUE=DATE | ||
3009 | 531 | :20031226 | ||
3010 | 532 | DTSTAMP | ||
3011 | 533 | :20020430T114937Z | ||
3012 | 534 | END:VEVENT | ||
3013 | 535 | END:VCALENDAR | ||
3014 | 536 | BEGIN:VCALENDAR | ||
3015 | 537 | VERSION | ||
3016 | 538 | :2.0 | ||
3017 | 539 | PRODID | ||
3018 | 540 | :-//Mozilla.org/NONSGML Mozilla Calendar V1.0//EN | ||
3019 | 541 | METHOD | ||
3020 | 542 | :PUBLISH | ||
3021 | 543 | BEGIN:VEVENT | ||
3022 | 544 | UID | ||
3023 | 545 | :911737808 | ||
3024 | 546 | SUMMARY | ||
3025 | 547 | :Boxing Day | ||
3026 | 548 | CLASS | ||
3027 | 549 | :PUBLIC | ||
3028 | 550 | X-MOZILLA-ALARM-DEFAULT-UNITS | ||
3029 | 551 | :minutes | ||
3030 | 552 | X-MOZILLA-ALARM-DEFAULT-LENGTH | ||
3031 | 553 | :15 | ||
3032 | 554 | X-MOZILLA-RECUR-DEFAULT-UNITS | ||
3033 | 555 | :weeks | ||
3034 | 556 | X-MOZILLA-RECUR-DEFAULT-INTERVAL | ||
3035 | 557 | :1 | ||
3036 | 558 | DTSTART | ||
3037 | 559 | ;VALUE=DATE | ||
3038 | 560 | :20030501 | ||
3039 | 561 | DTSTAMP | ||
3040 | 562 | :20020430T114937Z | ||
3041 | 563 | END:VEVENT | ||
3042 | 564 | BEGIN:VEVENT | ||
3043 | 565 | UID | ||
3044 | 566 | :wh4t3v3r | ||
3045 | 567 | DTSTART;VALUE=DATE:20031225 | ||
3046 | 568 | SUMMARY:Christmas again! | ||
3047 | 569 | END:VEVENT | ||
3048 | 570 | END:VCALENDAR | ||
3049 | 571 | """) | ||
3050 | 572 | |||
3051 | 573 | def test_iterEvents(self): | ||
3052 | 574 | from schoolbell.icalendar import ICalReader, ICalParseError | ||
3053 | 575 | file = StringIO(self.example_ical) | ||
3054 | 576 | reader = ICalReader(file) | ||
3055 | 577 | result = list(reader.iterEvents()) | ||
3056 | 578 | self.assertEqual(len(result), 3) | ||
3057 | 579 | vevent = result[0] | ||
3058 | 580 | self.assertEqual(vevent.getOne('x-mozilla-recur-default-units'), | ||
3059 | 581 | 'weeks') | ||
3060 | 582 | self.assertEqual(vevent.getOne('dtstart'), date(2003, 12, 25)) | ||
3061 | 583 | self.assertEqual(vevent.dtstart, date(2003, 12, 25)) | ||
3062 | 584 | self.assertEqual(vevent.getOne('dtend'), date(2003, 12, 26)) | ||
3063 | 585 | self.assertEqual(vevent.dtend, date(2003, 12, 26)) | ||
3064 | 586 | vevent = result[1] | ||
3065 | 587 | self.assertEqual(vevent.getOne('dtstart'), date(2003, 05, 01)) | ||
3066 | 588 | self.assertEqual(vevent.dtstart, date(2003, 05, 01)) | ||
3067 | 589 | vevent = result[2] | ||
3068 | 590 | self.assertEqual(vevent.getOne('dtstart'), date(2003, 12, 25)) | ||
3069 | 591 | self.assertEqual(vevent.dtstart, date(2003, 12, 25)) | ||
3070 | 592 | |||
3071 | 593 | reader = ICalReader(StringIO(dedent("""\ | ||
3072 | 594 | BEGIN:VCALENDAR | ||
3073 | 595 | BEGIN:VEVENT | ||
3074 | 596 | UID:hello | ||
3075 | 597 | DTSTART;VALUE=DATE:20010203 | ||
3076 | 598 | BEGIN:VALARM | ||
3077 | 599 | X-PROP:foo | ||
3078 | 600 | END:VALARM | ||
3079 | 601 | END:VEVENT | ||
3080 | 602 | END:VCALENDAR | ||
3081 | 603 | """))) | ||
3082 | 604 | result = list(reader.iterEvents()) | ||
3083 | 605 | self.assertEquals(len(result), 1) | ||
3084 | 606 | vevent = result[0] | ||
3085 | 607 | self.assert_(vevent.hasProp('uid')) | ||
3086 | 608 | self.assert_(vevent.hasProp('dtstart')) | ||
3087 | 609 | self.assert_(not vevent.hasProp('x-prop')) | ||
3088 | 610 | |||
3089 | 611 | reader = ICalReader(StringIO(dedent("""\ | ||
3090 | 612 | BEGIN:VCALENDAR | ||
3091 | 613 | BEGIN:VEVENT | ||
3092 | 614 | DTSTART;VALUE=DATE:20010203 | ||
3093 | 615 | END:VEVENT | ||
3094 | 616 | END:VCALENDAR | ||
3095 | 617 | """))) | ||
3096 | 618 | # missing UID | ||
3097 | 619 | self.assertRaises(ICalParseError, list, reader.iterEvents()) | ||
3098 | 620 | |||
3099 | 621 | reader = ICalReader(StringIO(dedent("""\ | ||
3100 | 622 | BEGIN:VCALENDAR | ||
3101 | 623 | BEGIN:VEVENT | ||
3102 | 624 | DTSTART;VALUE=DATE:20010203 | ||
3103 | 625 | """))) | ||
3104 | 626 | self.assertRaises(ICalParseError, list, reader.iterEvents()) | ||
3105 | 627 | |||
3106 | 628 | reader = ICalReader(StringIO(dedent("""\ | ||
3107 | 629 | BEGIN:VCALENDAR | ||
3108 | 630 | BEGIN:VEVENT | ||
3109 | 631 | DTSTART;VALUE=DATE:20010203 | ||
3110 | 632 | END:VCALENDAR | ||
3111 | 633 | END:VEVENT | ||
3112 | 634 | """))) | ||
3113 | 635 | self.assertRaises(ICalParseError, list, reader.iterEvents()) | ||
3114 | 636 | |||
3115 | 637 | reader = ICalReader(StringIO(dedent("""\ | ||
3116 | 638 | BEGIN:VCALENDAR | ||
3117 | 639 | END:VCALENDAR | ||
3118 | 640 | X-PROP:foo | ||
3119 | 641 | """))) | ||
3120 | 642 | self.assertRaises(ICalParseError, list, reader.iterEvents()) | ||
3121 | 643 | |||
3122 | 644 | reader = ICalReader(StringIO(dedent("""\ | ||
3123 | 645 | BEGIN:VCALENDAR | ||
3124 | 646 | END:VCALENDAR | ||
3125 | 647 | BEGIN:VEVENT | ||
3126 | 648 | END:VEVENT | ||
3127 | 649 | """))) | ||
3128 | 650 | self.assertRaises(ICalParseError, list, reader.iterEvents()) | ||
3129 | 651 | |||
3130 | 652 | reader = ICalReader(StringIO(dedent("""\ | ||
3131 | 653 | BEGIN:VCALENDAR | ||
3132 | 654 | BEGIN:VEVENT | ||
3133 | 655 | DTSTART;VALUE=DATE:20010203 | ||
3134 | 656 | END:VEVENT | ||
3135 | 657 | END:VCALENDAR | ||
3136 | 658 | END:UNIVERSE | ||
3137 | 659 | """))) | ||
3138 | 660 | self.assertRaises(ICalParseError, list, reader.iterEvents()) | ||
3139 | 661 | |||
3140 | 662 | reader = ICalReader(StringIO(dedent("""\ | ||
3141 | 663 | DTSTART;VALUE=DATE:20010203 | ||
3142 | 664 | """))) | ||
3143 | 665 | self.assertRaises(ICalParseError, list, reader.iterEvents()) | ||
3144 | 666 | |||
3145 | 667 | reader = ICalReader(StringIO(dedent("""\ | ||
3146 | 668 | This is just plain text | ||
3147 | 669 | """))) | ||
3148 | 670 | self.assertRaises(ICalParseError, list, reader.iterEvents()) | ||
3149 | 671 | |||
3150 | 672 | reader = ICalReader(StringIO("")) | ||
3151 | 673 | self.assertEquals(list(reader.iterEvents()), []) | ||
3152 | 674 | |||
3153 | 675 | def test_iterRow(self): | ||
3154 | 676 | from schoolbell.icalendar import ICalReader | ||
3155 | 677 | file = StringIO("key1\n" | ||
3156 | 678 | " :value1\n" | ||
3157 | 679 | "key2\n" | ||
3158 | 680 | " ;VALUE=foo\n" | ||
3159 | 681 | " :value2\n" | ||
3160 | 682 | "key3;VALUE=bar:value3\n") | ||
3161 | 683 | reader = ICalReader(file) | ||
3162 | 684 | self.assertEqual(list(reader._iterRow()), | ||
3163 | 685 | [('KEY1', 'value1', {}), | ||
3164 | 686 | ('KEY2', 'value2', {'VALUE': 'FOO'}), | ||
3165 | 687 | ('KEY3', 'value3', {'VALUE': 'BAR'})]) | ||
3166 | 688 | |||
3167 | 689 | file = StringIO("key1:value1\n" | ||
3168 | 690 | "key2;VALUE=foo:value2\n" | ||
3169 | 691 | "key3;VALUE=bar:value3\n") | ||
3170 | 692 | reader = ICalReader(file) | ||
3171 | 693 | self.assertEqual(list(reader._iterRow()), | ||
3172 | 694 | [('KEY1', 'value1', {}), | ||
3173 | 695 | ('KEY2', 'value2', {'VALUE': 'FOO'}), | ||
3174 | 696 | ('KEY3', 'value3', {'VALUE': 'BAR'})]) | ||
3175 | 697 | |||
3176 | 698 | file = StringIO("key1:value:with:colons:in:it\n") | ||
3177 | 699 | reader = ICalReader(file) | ||
3178 | 700 | self.assertEqual(list(reader._iterRow()), | ||
3179 | 701 | [('KEY1', 'value:with:colons:in:it', {})]) | ||
3180 | 702 | |||
3181 | 703 | reader = ICalReader(StringIO("ke\r\n y1\n\t:value\r\n 1 \r\n .")) | ||
3182 | 704 | self.assertEqual(list(reader._iterRow()), | ||
3183 | 705 | [('KEY1', 'value 1 .', {})]) | ||
3184 | 706 | |||
3185 | 707 | reader = ICalReader(StringIO("key;param=\xe2\x98\xbb:\r\n" | ||
3186 | 708 | " value \xe2\x98\xbb\r\n")) | ||
3187 | 709 | self.assertEqual(list(reader._iterRow()), | ||
3188 | 710 | [("KEY", u"value \u263B", {'PARAM': u'\u263B'})]) | ||
3189 | 711 | |||
3190 | 712 | def test_parseRow(self): | ||
3191 | 713 | from schoolbell.icalendar import ICalReader, ICalParseError | ||
3192 | 714 | parseRow = ICalReader._parseRow | ||
3193 | 715 | self.assertEqual(parseRow("key:"), ("KEY", "", {})) | ||
3194 | 716 | self.assertEqual(parseRow("key:value"), ("KEY", "value", {})) | ||
3195 | 717 | self.assertEqual(parseRow("key:va:lu:e"), ("KEY", "va:lu:e", {})) | ||
3196 | 718 | self.assertRaises(ICalParseError, parseRow, "key but no value") | ||
3197 | 719 | self.assertRaises(ICalParseError, parseRow, ":value but no key") | ||
3198 | 720 | self.assertRaises(ICalParseError, parseRow, "bad name:") | ||
3199 | 721 | |||
3200 | 722 | self.assertEqual(parseRow("key;param=:value"), | ||
3201 | 723 | ("KEY", "value", {'PARAM': ''})) | ||
3202 | 724 | self.assertEqual(parseRow("key;param=pvalue:value"), | ||
3203 | 725 | ("KEY", "value", {'PARAM': 'PVALUE'})) | ||
3204 | 726 | self.assertEqual(parseRow('key;param=pvalue;param2=value2:value'), | ||
3205 | 727 | ("KEY", "value", {'PARAM': 'PVALUE', | ||
3206 | 728 | 'PARAM2': 'VALUE2'})) | ||
3207 | 729 | self.assertEqual(parseRow('key;param="pvalue":value'), | ||
3208 | 730 | ("KEY", "value", {'PARAM': 'pvalue'})) | ||
3209 | 731 | self.assertEqual(parseRow('key;param=pvalue;param2="value2":value'), | ||
3210 | 732 | ("KEY", "value", {'PARAM': 'PVALUE', | ||
3211 | 733 | 'PARAM2': 'value2'})) | ||
3212 | 734 | self.assertRaises(ICalParseError, parseRow, "k;:no param") | ||
3213 | 735 | self.assertRaises(ICalParseError, parseRow, "k;a?=b:bad param") | ||
3214 | 736 | self.assertRaises(ICalParseError, parseRow, "k;a=\":bad param") | ||
3215 | 737 | self.assertRaises(ICalParseError, parseRow, "k;a=\"\177:bad param") | ||
3216 | 738 | self.assertRaises(ICalParseError, parseRow, "k;a=\001:bad char") | ||
3217 | 739 | self.assertEqual(parseRow("key;param=a,b,c:value"), | ||
3218 | 740 | ("KEY", "value", {'PARAM': ['A', 'B', 'C']})) | ||
3219 | 741 | self.assertEqual(parseRow('key;param=a,"b,c",d:value'), | ||
3220 | 742 | ("KEY", "value", {'PARAM': ['A', 'b,c', 'D']})) | ||
3221 | 743 | def diff(old, new, oldlabel="expected output", newlabel="actual output"): | ||
3222 | 744 | """Display a unified diff between old text and new text.""" | ||
3223 | 745 | old = old.splitlines() | ||
3224 | 746 | new = new.splitlines() | ||
3225 | 747 | |||
3226 | 748 | diff = ['--- %s' % oldlabel, '+++ %s' % newlabel] | ||
3227 | 749 | |||
3228 | 750 | def dump(tag, x, lo, hi): | ||
3229 | 751 | for i in xrange(lo, hi): | ||
3230 | 752 | diff.append(tag + x[i]) | ||
3231 | 753 | |||
3232 | 754 | differ = difflib.SequenceMatcher(a=old, b=new) | ||
3233 | 755 | for tag, alo, ahi, blo, bhi in differ.get_opcodes(): | ||
3234 | 756 | if tag == 'replace': | ||
3235 | 757 | dump('-', old, alo, ahi) | ||
3236 | 758 | dump('+', new, blo, bhi) | ||
3237 | 759 | elif tag == 'delete': | ||
3238 | 760 | dump('-', old, alo, ahi) | ||
3239 | 761 | elif tag == 'insert': | ||
3240 | 762 | dump('+', new, blo, bhi) | ||
3241 | 763 | elif tag == 'equal': | ||
3242 | 764 | dump(' ', old, alo, ahi) | ||
3243 | 765 | else: | ||
3244 | 766 | raise AssertionError('unknown tag %r' % tag) | ||
3245 | 767 | return "\n".join(diff) | ||
3246 | 768 | |||
3247 | 769 | |||
3248 | 770 | |||
3249 | 771 | def test_suite(): | ||
3250 | 772 | suite = unittest.TestSuite() | ||
3251 | 773 | suite.addTest(doctest.DocTestSuite('schoolbell.icalendar', | ||
3252 | 774 | optionflags=doctest.ELLIPSIS | doctest.REPORT_UDIFF)) | ||
3253 | 775 | suite.addTest(unittest.makeSuite(TestParseDateTime)) | ||
3254 | 776 | suite.addTest(unittest.makeSuite(TestPeriod)) | ||
3255 | 777 | suite.addTest(unittest.makeSuite(TestVEvent)) | ||
3256 | 778 | suite.addTest(unittest.makeSuite(TestICalReader)) | ||
3257 | 779 | return suite | ||
3258 | 780 | |||
3259 | 781 | if __name__ == '__main__': | ||
3260 | 782 | unittest.main(defaultTest='test_suite') | ||
3261 | 783 | 0 | ||
3262 | === removed file 'lib/schoolbell/tests/test_schoolbell.py' | |||
3263 | --- lib/schoolbell/tests/test_schoolbell.py 2005-10-31 18:29:12 +0000 | |||
3264 | +++ lib/schoolbell/tests/test_schoolbell.py 1970-01-01 00:00:00 +0000 | |||
3265 | @@ -1,74 +0,0 @@ | |||
3266 | 1 | """ | ||
3267 | 2 | Unit tests for schoolbell | ||
3268 | 3 | |||
3269 | 4 | When this module grows too big, it will be split into a number of modules in | ||
3270 | 5 | a package called tests. Each of those new modules will be named test_foo.py | ||
3271 | 6 | and will test schoolbell.foo. | ||
3272 | 7 | """ | ||
3273 | 8 | |||
3274 | 9 | import unittest | ||
3275 | 10 | from zope.testing import doctest | ||
3276 | 11 | |||
3277 | 12 | |||
3278 | 13 | def doctest_interfaces(): | ||
3279 | 14 | """Look for syntax errors in interfaces.py | ||
3280 | 15 | |||
3281 | 16 | >>> import schoolbell.interfaces | ||
3282 | 17 | |||
3283 | 18 | """ | ||
3284 | 19 | |||
3285 | 20 | |||
3286 | 21 | def doctest_simple_CalendarEventMixin_replace(): | ||
3287 | 22 | """Make sure CalendarEventMixin.replace does not forget any attributes. | ||
3288 | 23 | |||
3289 | 24 | >>> from schoolbell.interfaces import ICalendarEvent | ||
3290 | 25 | >>> from zope.schema import getFieldNames | ||
3291 | 26 | >>> all_attrs = getFieldNames(ICalendarEvent) | ||
3292 | 27 | |||
3293 | 28 | We will use SimpleCalendarEvent which is a trivial subclass of | ||
3294 | 29 | CalendarEventMixin | ||
3295 | 30 | |||
3296 | 31 | >>> from datetime import datetime, timedelta | ||
3297 | 32 | >>> from schoolbell.simple import SimpleCalendarEvent | ||
3298 | 33 | >>> e1 = SimpleCalendarEvent(datetime(2004, 12, 15, 18, 57), | ||
3299 | 34 | ... timedelta(minutes=15), | ||
3300 | 35 | ... 'Work on schoolbell.simple') | ||
3301 | 36 | |||
3302 | 37 | >>> for attr in all_attrs: | ||
3303 | 38 | ... e2 = e1.replace(**{attr: 'new value'}) | ||
3304 | 39 | ... assert getattr(e2, attr) == 'new value', attr | ||
3305 | 40 | ... assert e2 != e1, attr | ||
3306 | 41 | ... assert e2.replace(**{attr: getattr(e1, attr)}) == e1, attr | ||
3307 | 42 | |||
3308 | 43 | """ | ||
3309 | 44 | |||
3310 | 45 | |||
3311 | 46 | def doctest_weeknum_bounds(): | ||
3312 | 47 | """Unit test for schoolbell.utils.weeknum_bounds. | ||
3313 | 48 | |||
3314 | 49 | Check that weeknum_bounds is the reverse of datetime.isocalendar(). | ||
3315 | 50 | |||
3316 | 51 | >>> from datetime import date | ||
3317 | 52 | >>> from schoolbell.utils import weeknum_bounds | ||
3318 | 53 | >>> d = date(2000, 1, 1) | ||
3319 | 54 | >>> while d < date(2010, 1, 1): | ||
3320 | 55 | ... year, weeknum, weekday = d.isocalendar() | ||
3321 | 56 | ... l, h = weeknum_bounds(year, weeknum) | ||
3322 | 57 | ... assert l <= d <= h | ||
3323 | 58 | ... d += d.resolution | ||
3324 | 59 | |||
3325 | 60 | """ | ||
3326 | 61 | |||
3327 | 62 | |||
3328 | 63 | def test_suite(): | ||
3329 | 64 | suite = unittest.TestSuite() | ||
3330 | 65 | suite.addTest(doctest.DocTestSuite()) | ||
3331 | 66 | suite.addTest(doctest.DocTestSuite('schoolbell.mixins')) | ||
3332 | 67 | suite.addTest(doctest.DocTestSuite('schoolbell.simple')) | ||
3333 | 68 | suite.addTest(doctest.DocTestSuite('schoolbell.utils')) | ||
3334 | 69 | suite.addTest(doctest.DocTestSuite('schoolbell.browser', | ||
3335 | 70 | optionflags=doctest.ELLIPSIS | doctest.REPORT_UDIFF)) | ||
3336 | 71 | return suite | ||
3337 | 72 | |||
3338 | 73 | if __name__ == '__main__': | ||
3339 | 74 | unittest.main(defaultTest='test_suite') | ||
3340 | 75 | 0 | ||
3341 | === removed file 'lib/schoolbell/utils.py' | |||
3342 | --- lib/schoolbell/utils.py 2005-10-31 18:29:12 +0000 | |||
3343 | +++ lib/schoolbell/utils.py 1970-01-01 00:00:00 +0000 | |||
3344 | @@ -1,164 +0,0 @@ | |||
3345 | 1 | """ | ||
3346 | 2 | Utility functions for SchoolBell. | ||
3347 | 3 | |||
3348 | 4 | These include various date manipulation routines. | ||
3349 | 5 | """ | ||
3350 | 6 | |||
3351 | 7 | import calendar | ||
3352 | 8 | from datetime import datetime, date, timedelta, tzinfo | ||
3353 | 9 | |||
3354 | 10 | |||
3355 | 11 | def prev_month(date): | ||
3356 | 12 | """Calculate the first day of the previous month for a given date. | ||
3357 | 13 | |||
3358 | 14 | >>> prev_month(date(2004, 8, 1)) | ||
3359 | 15 | datetime.date(2004, 7, 1) | ||
3360 | 16 | >>> prev_month(date(2004, 8, 31)) | ||
3361 | 17 | datetime.date(2004, 7, 1) | ||
3362 | 18 | >>> prev_month(date(2004, 12, 15)) | ||
3363 | 19 | datetime.date(2004, 11, 1) | ||
3364 | 20 | >>> prev_month(date(2005, 1, 28)) | ||
3365 | 21 | datetime.date(2004, 12, 1) | ||
3366 | 22 | |||
3367 | 23 | """ | ||
3368 | 24 | return (date.replace(day=1) - timedelta(1)).replace(day=1) | ||
3369 | 25 | |||
3370 | 26 | |||
3371 | 27 | def next_month(date): | ||
3372 | 28 | """Calculate the first day of the next month for a given date. | ||
3373 | 29 | |||
3374 | 30 | >>> next_month(date(2004, 8, 1)) | ||
3375 | 31 | datetime.date(2004, 9, 1) | ||
3376 | 32 | >>> next_month(date(2004, 8, 31)) | ||
3377 | 33 | datetime.date(2004, 9, 1) | ||
3378 | 34 | >>> next_month(date(2004, 12, 15)) | ||
3379 | 35 | datetime.date(2005, 1, 1) | ||
3380 | 36 | >>> next_month(date(2004, 2, 28)) | ||
3381 | 37 | datetime.date(2004, 3, 1) | ||
3382 | 38 | >>> next_month(date(2004, 2, 29)) | ||
3383 | 39 | datetime.date(2004, 3, 1) | ||
3384 | 40 | >>> next_month(date(2005, 2, 28)) | ||
3385 | 41 | datetime.date(2005, 3, 1) | ||
3386 | 42 | |||
3387 | 43 | """ | ||
3388 | 44 | return (date.replace(day=28) + timedelta(7)).replace(day=1) | ||
3389 | 45 | |||
3390 | 46 | |||
3391 | 47 | def week_start(date, first_day_of_week=0): | ||
3392 | 48 | """Calculate the first day of the week for a given date. | ||
3393 | 49 | |||
3394 | 50 | Assuming that week starts on Mondays: | ||
3395 | 51 | |||
3396 | 52 | >>> week_start(date(2004, 8, 19)) | ||
3397 | 53 | datetime.date(2004, 8, 16) | ||
3398 | 54 | >>> week_start(date(2004, 8, 15)) | ||
3399 | 55 | datetime.date(2004, 8, 9) | ||
3400 | 56 | >>> week_start(date(2004, 8, 14)) | ||
3401 | 57 | datetime.date(2004, 8, 9) | ||
3402 | 58 | >>> week_start(date(2004, 8, 21)) | ||
3403 | 59 | datetime.date(2004, 8, 16) | ||
3404 | 60 | >>> week_start(date(2004, 8, 22)) | ||
3405 | 61 | datetime.date(2004, 8, 16) | ||
3406 | 62 | >>> week_start(date(2004, 8, 23)) | ||
3407 | 63 | datetime.date(2004, 8, 23) | ||
3408 | 64 | |||
3409 | 65 | Assuming that week starts on Sundays: | ||
3410 | 66 | |||
3411 | 67 | >>> import calendar | ||
3412 | 68 | >>> week_start(date(2004, 8, 19), calendar.SUNDAY) | ||
3413 | 69 | datetime.date(2004, 8, 15) | ||
3414 | 70 | >>> week_start(date(2004, 8, 15), calendar.SUNDAY) | ||
3415 | 71 | datetime.date(2004, 8, 15) | ||
3416 | 72 | >>> week_start(date(2004, 8, 14), calendar.SUNDAY) | ||
3417 | 73 | datetime.date(2004, 8, 8) | ||
3418 | 74 | >>> week_start(date(2004, 8, 21), calendar.SUNDAY) | ||
3419 | 75 | datetime.date(2004, 8, 15) | ||
3420 | 76 | >>> week_start(date(2004, 8, 22), calendar.SUNDAY) | ||
3421 | 77 | datetime.date(2004, 8, 22) | ||
3422 | 78 | >>> week_start(date(2004, 8, 23), calendar.SUNDAY) | ||
3423 | 79 | datetime.date(2004, 8, 22) | ||
3424 | 80 | |||
3425 | 81 | """ | ||
3426 | 82 | assert 0 <= first_day_of_week < 7 | ||
3427 | 83 | delta = date.weekday() - first_day_of_week | ||
3428 | 84 | if delta < 0: | ||
3429 | 85 | delta += 7 | ||
3430 | 86 | return date - timedelta(delta) | ||
3431 | 87 | |||
3432 | 88 | |||
3433 | 89 | def weeknum_bounds(year, weeknum): | ||
3434 | 90 | """Calculate the inclusive date bounds for a (year, weeknum) tuple. | ||
3435 | 91 | |||
3436 | 92 | Week numbers are as defined in ISO 8601 and returned by | ||
3437 | 93 | datetime.date.isocalendar(). | ||
3438 | 94 | |||
3439 | 95 | >>> weeknum_bounds(2003, 52) | ||
3440 | 96 | (datetime.date(2003, 12, 22), datetime.date(2003, 12, 28)) | ||
3441 | 97 | >>> weeknum_bounds(2004, 1) | ||
3442 | 98 | (datetime.date(2003, 12, 29), datetime.date(2004, 1, 4)) | ||
3443 | 99 | >>> weeknum_bounds(2004, 2) | ||
3444 | 100 | (datetime.date(2004, 1, 5), datetime.date(2004, 1, 11)) | ||
3445 | 101 | |||
3446 | 102 | """ | ||
3447 | 103 | # The first week of a year is at least 4 days long, so January 4th | ||
3448 | 104 | # is in the first week. | ||
3449 | 105 | firstweek = week_start(date(year, 1, 4), calendar.MONDAY) | ||
3450 | 106 | # move forward to the right week number | ||
3451 | 107 | weekstart = firstweek + timedelta(weeks=weeknum-1) | ||
3452 | 108 | weekend = weekstart + timedelta(days=6) | ||
3453 | 109 | return (weekstart, weekend) | ||
3454 | 110 | |||
3455 | 111 | |||
3456 | 112 | def check_weeknum(year, weeknum): | ||
3457 | 113 | """Check to see whether a (year, weeknum) tuple refers to a real | ||
3458 | 114 | ISO week number. | ||
3459 | 115 | |||
3460 | 116 | >>> check_weeknum(2004, 1) | ||
3461 | 117 | True | ||
3462 | 118 | >>> check_weeknum(2004, 53) | ||
3463 | 119 | True | ||
3464 | 120 | >>> check_weeknum(2004, 0) | ||
3465 | 121 | False | ||
3466 | 122 | >>> check_weeknum(2004, 54) | ||
3467 | 123 | False | ||
3468 | 124 | >>> check_weeknum(2003, 52) | ||
3469 | 125 | True | ||
3470 | 126 | >>> check_weeknum(2003, 53) | ||
3471 | 127 | False | ||
3472 | 128 | |||
3473 | 129 | """ | ||
3474 | 130 | weekstart, weekend = weeknum_bounds(year, weeknum) | ||
3475 | 131 | isoyear, isoweek, isoday = weekstart.isocalendar() | ||
3476 | 132 | return (year, weeknum) == (isoyear, isoweek) | ||
3477 | 133 | |||
3478 | 134 | class Slots(dict): | ||
3479 | 135 | """A dict with automatic key selection. | ||
3480 | 136 | |||
3481 | 137 | The add method automatically selects the lowest unused numeric key | ||
3482 | 138 | (starting from 0). | ||
3483 | 139 | |||
3484 | 140 | Example: | ||
3485 | 141 | |||
3486 | 142 | >>> s = Slots() | ||
3487 | 143 | >>> s.add("first") | ||
3488 | 144 | >>> s | ||
3489 | 145 | {0: 'first'} | ||
3490 | 146 | |||
3491 | 147 | >>> s.add("second") | ||
3492 | 148 | >>> s | ||
3493 | 149 | {0: 'first', 1: 'second'} | ||
3494 | 150 | |||
3495 | 151 | The keys can be reused: | ||
3496 | 152 | |||
3497 | 153 | >>> del s[0] | ||
3498 | 154 | >>> s.add("third") | ||
3499 | 155 | >>> s | ||
3500 | 156 | {0: 'third', 1: 'second'} | ||
3501 | 157 | |||
3502 | 158 | """ | ||
3503 | 159 | |||
3504 | 160 | def add(self, obj): | ||
3505 | 161 | i = 0 | ||
3506 | 162 | while i in self: | ||
3507 | 163 | i += 1 | ||
3508 | 164 | self[i] = obj |
LAND IT!