paul@10 | 1 | # -*- coding: iso-8859-1 -*- |
paul@10 | 2 | """ |
paul@10 | 3 | MoinMoin - EventAggregator library |
paul@10 | 4 | |
paul@126 | 5 | @copyright: 2008, 2009, 2010, 2011 by Paul Boddie <paul@boddie.org.uk> |
paul@10 | 6 | @copyright: 2000-2004 Juergen Hermann <jh@web.de>, |
paul@10 | 7 | 2005-2008 MoinMoin:ThomasWaldmann. |
paul@10 | 8 | @license: GNU GPL (v2 or later), see COPYING.txt for details. |
paul@10 | 9 | """ |
paul@10 | 10 | |
paul@10 | 11 | from MoinMoin.Page import Page |
paul@10 | 12 | from MoinMoin import search, version |
paul@24 | 13 | from MoinMoin import wikiutil |
paul@10 | 14 | import calendar |
paul@11 | 15 | import datetime |
paul@24 | 16 | import time |
paul@10 | 17 | import re |
paul@122 | 18 | import bisect |
paul@122 | 19 | import operator |
paul@10 | 20 | |
paul@69 | 21 | try: |
paul@69 | 22 | set |
paul@69 | 23 | except NameError: |
paul@69 | 24 | from sets import Set as set |
paul@69 | 25 | |
paul@100 | 26 | try: |
paul@100 | 27 | import pytz |
paul@100 | 28 | except ImportError: |
paul@100 | 29 | pytz = None |
paul@100 | 30 | |
paul@109 | 31 | __version__ = "0.7" |
paul@10 | 32 | |
paul@22 | 33 | # Date labels. |
paul@22 | 34 | |
paul@22 | 35 | month_labels = ["January", "February", "March", "April", "May", "June", |
paul@22 | 36 | "July", "August", "September", "October", "November", "December"] |
paul@22 | 37 | weekday_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] |
paul@22 | 38 | |
paul@10 | 39 | # Regular expressions where MoinMoin does not provide the required support. |
paul@10 | 40 | |
paul@10 | 41 | category_regexp = None |
paul@47 | 42 | |
paul@47 | 43 | # Page parsing. |
paul@47 | 44 | |
paul@84 | 45 | definition_list_regexp = re.compile(ur'(?P<wholeterm>^(?P<optcomment>#*)\s+(?P<term>.*?):: )(?P<desc>.*?)$', re.UNICODE | re.MULTILINE) |
paul@47 | 46 | category_membership_regexp = re.compile(ur"^\s*((Category\S+)(\s+Category\S+)*)\s*$", re.MULTILINE | re.UNICODE) |
paul@47 | 47 | |
paul@47 | 48 | # Value parsing. |
paul@47 | 49 | |
paul@93 | 50 | country_code_regexp = re.compile(ur'(?:^|\W)(?P<code>[A-Z]{2})(?:$|\W+$)', re.UNICODE) |
paul@92 | 51 | |
paul@92 | 52 | month_regexp_str = ur'(?P<year>[0-9]{4})-(?P<month>[0-9]{2})' |
paul@92 | 53 | date_regexp_str = ur'(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})' |
paul@92 | 54 | time_regexp_str = ur'(?P<hour>[0-2][0-9]):(?P<minute>[0-5][0-9])(?::(?P<second>[0-6][0-9]))?' |
paul@98 | 55 | timezone_offset_str = ur'(?P<offset>(UTC)?(?:(?P<sign>[-+])(?P<hours>[0-9]{2})(?::?(?P<minutes>[0-9]{2}))?))' |
paul@98 | 56 | timezone_olson_str = ur'(?P<olson>[a-zA-Z]+(?:/[-_a-zA-Z]+){1,2})' |
paul@98 | 57 | timezone_utc_str = ur'UTC' |
paul@98 | 58 | timezone_regexp_str = ur'(?P<zone>' + timezone_offset_str + '|' + timezone_olson_str + '|' + timezone_utc_str + ')' |
paul@92 | 59 | datetime_regexp_str = date_regexp_str + ur'(?:\s+' + time_regexp_str + ur'(?:\s+' + timezone_regexp_str + ur')?)?' |
paul@92 | 60 | |
paul@92 | 61 | month_regexp = re.compile(month_regexp_str, re.UNICODE) |
paul@92 | 62 | date_regexp = re.compile(date_regexp_str, re.UNICODE) |
paul@92 | 63 | time_regexp = re.compile(time_regexp_str, re.UNICODE) |
paul@92 | 64 | datetime_regexp = re.compile(datetime_regexp_str, re.UNICODE) |
paul@100 | 65 | timezone_olson_regexp = re.compile(timezone_olson_str, re.UNICODE) |
paul@94 | 66 | timezone_offset_regexp = re.compile(timezone_offset_str, re.UNICODE) |
paul@92 | 67 | |
paul@19 | 68 | verbatim_regexp = re.compile(ur'(?:' |
paul@19 | 69 | ur'<<Verbatim\((?P<verbatim>.*?)\)>>' |
paul@19 | 70 | ur'|' |
paul@19 | 71 | ur'\[\[Verbatim\((?P<verbatim2>.*?)\)\]\]' |
paul@19 | 72 | ur'|' |
paul@19 | 73 | ur'`(?P<monospace>.*?)`' |
paul@19 | 74 | ur'|' |
paul@19 | 75 | ur'{{{(?P<preformatted>.*?)}}}' |
paul@19 | 76 | ur')', re.UNICODE) |
paul@10 | 77 | |
paul@10 | 78 | # Utility functions. |
paul@10 | 79 | |
paul@10 | 80 | def getCategoryPattern(request): |
paul@10 | 81 | global category_regexp |
paul@10 | 82 | |
paul@10 | 83 | try: |
paul@10 | 84 | return request.cfg.cache.page_category_regexact |
paul@10 | 85 | except AttributeError: |
paul@10 | 86 | |
paul@10 | 87 | # Use regular expression from MoinMoin 1.7.1 otherwise. |
paul@10 | 88 | |
paul@10 | 89 | if category_regexp is None: |
paul@10 | 90 | category_regexp = re.compile(u'^%s$' % ur'(?P<all>Category(?P<key>(?!Template)\S+))', re.UNICODE) |
paul@10 | 91 | return category_regexp |
paul@10 | 92 | |
paul@92 | 93 | def int_or_none(x): |
paul@92 | 94 | if x is None: |
paul@92 | 95 | return x |
paul@92 | 96 | else: |
paul@92 | 97 | return int(x) |
paul@92 | 98 | |
paul@118 | 99 | def sort_none_first(x, y): |
paul@118 | 100 | if x is None: |
paul@118 | 101 | return -1 |
paul@118 | 102 | elif y is None: |
paul@118 | 103 | return 1 |
paul@118 | 104 | else: |
paul@118 | 105 | return cmp(x, y) |
paul@118 | 106 | |
paul@109 | 107 | # Utility classes and associated functions. |
paul@109 | 108 | |
paul@109 | 109 | class Form: |
paul@109 | 110 | |
paul@109 | 111 | """ |
paul@109 | 112 | A wrapper preserving MoinMoin 1.8.x (and earlier) behaviour in a 1.9.x |
paul@109 | 113 | environment. |
paul@109 | 114 | """ |
paul@109 | 115 | |
paul@109 | 116 | def __init__(self, form): |
paul@109 | 117 | self.form = form |
paul@109 | 118 | |
paul@110 | 119 | def get(self, name, default=None): |
paul@109 | 120 | values = self.form.getlist(name) |
paul@109 | 121 | if not values: |
paul@110 | 122 | return default |
paul@109 | 123 | else: |
paul@109 | 124 | return values |
paul@109 | 125 | |
paul@109 | 126 | def __getitem__(self, name): |
paul@109 | 127 | return self.form.getlist(name) |
paul@109 | 128 | |
paul@109 | 129 | class ActionSupport: |
paul@109 | 130 | |
paul@112 | 131 | """ |
paul@112 | 132 | Work around disruptive MoinMoin changes in 1.9, and also provide useful |
paul@112 | 133 | convenience methods. |
paul@112 | 134 | """ |
paul@109 | 135 | |
paul@109 | 136 | def get_form(self): |
paul@109 | 137 | return get_form(self.request) |
paul@109 | 138 | |
paul@112 | 139 | def _get_selected(self, value, input_value): |
paul@112 | 140 | |
paul@112 | 141 | """ |
paul@112 | 142 | Return the HTML attribute text indicating selection of an option (or |
paul@112 | 143 | otherwise) if 'value' matches 'input_value'. |
paul@112 | 144 | """ |
paul@112 | 145 | |
paul@112 | 146 | return input_value is not None and value == input_value and 'selected="selected"' or '' |
paul@112 | 147 | |
paul@112 | 148 | def _get_selected_for_list(self, value, input_values): |
paul@112 | 149 | |
paul@112 | 150 | """ |
paul@112 | 151 | Return the HTML attribute text indicating selection of an option (or |
paul@112 | 152 | otherwise) if 'value' matches one of the 'input_values'. |
paul@112 | 153 | """ |
paul@112 | 154 | |
paul@112 | 155 | return value in input_values and 'selected="selected"' or '' |
paul@112 | 156 | |
paul@112 | 157 | def _get_input(self, form, name, default=None): |
paul@112 | 158 | |
paul@112 | 159 | """ |
paul@112 | 160 | Return the input from 'form' having the given 'name', returning either |
paul@112 | 161 | the input converted to an integer or the given 'default' (optional, None |
paul@112 | 162 | if not specified). |
paul@112 | 163 | """ |
paul@112 | 164 | |
paul@112 | 165 | value = form.get(name, [None])[0] |
paul@112 | 166 | if not value: # true if 0 obtained |
paul@112 | 167 | return default |
paul@112 | 168 | else: |
paul@112 | 169 | return int(value) |
paul@112 | 170 | |
paul@114 | 171 | def get_month_lists(self, default_as_current=0): |
paul@112 | 172 | |
paul@112 | 173 | """ |
paul@112 | 174 | Return two lists of HTML element definitions corresponding to the start |
paul@112 | 175 | and end month selection controls, with months selected according to any |
paul@112 | 176 | values that have been specified via request parameters. |
paul@112 | 177 | """ |
paul@112 | 178 | |
paul@112 | 179 | _ = self._ |
paul@112 | 180 | form = self.get_form() |
paul@112 | 181 | |
paul@112 | 182 | # Initialise month lists. |
paul@112 | 183 | |
paul@112 | 184 | start_month_list = [] |
paul@112 | 185 | end_month_list = [] |
paul@112 | 186 | |
paul@114 | 187 | start_month = self._get_input(form, "start-month", default_as_current and getCurrentMonth().month() or None) |
paul@112 | 188 | end_month = self._get_input(form, "end-month", start_month) |
paul@112 | 189 | |
paul@112 | 190 | # Prepare month lists, selecting specified months. |
paul@112 | 191 | |
paul@114 | 192 | if not default_as_current: |
paul@114 | 193 | start_month_list.append('<option value=""></option>') |
paul@114 | 194 | end_month_list.append('<option value=""></option>') |
paul@114 | 195 | |
paul@112 | 196 | for month in range(1, 13): |
paul@112 | 197 | month_label = _(getMonthLabel(month)) |
paul@112 | 198 | selected = self._get_selected(month, start_month) |
paul@112 | 199 | start_month_list.append('<option value="%02d" %s>%s</option>' % (month, selected, month_label)) |
paul@112 | 200 | selected = self._get_selected(month, end_month) |
paul@112 | 201 | end_month_list.append('<option value="%02d" %s>%s</option>' % (month, selected, month_label)) |
paul@112 | 202 | |
paul@112 | 203 | return start_month_list, end_month_list |
paul@112 | 204 | |
paul@114 | 205 | def get_year_defaults(self, default_as_current=0): |
paul@112 | 206 | |
paul@112 | 207 | "Return defaults for the start and end years." |
paul@112 | 208 | |
paul@112 | 209 | form = self.get_form() |
paul@112 | 210 | |
paul@114 | 211 | start_year_default = form.get("start-year", [default_as_current and getCurrentYear() or ""])[0] |
paul@114 | 212 | end_year_default = form.get("end-year", [default_as_current and start_year_default or ""])[0] |
paul@112 | 213 | |
paul@112 | 214 | return start_year_default, end_year_default |
paul@112 | 215 | |
paul@127 | 216 | def get_day_defaults(self, default_as_current=0): |
paul@127 | 217 | |
paul@127 | 218 | "Return defaults for the start and end days." |
paul@127 | 219 | |
paul@127 | 220 | form = self.get_form() |
paul@127 | 221 | |
paul@127 | 222 | start_day_default = form.get("start-day", [default_as_current and getCurrentDate().day() or ""])[0] |
paul@127 | 223 | end_day_default = form.get("end-day", [default_as_current and start_day_default or ""])[0] |
paul@127 | 224 | |
paul@127 | 225 | return start_day_default, end_day_default |
paul@127 | 226 | |
paul@109 | 227 | def get_form(request): |
paul@109 | 228 | |
paul@109 | 229 | "Work around disruptive MoinMoin changes in 1.9." |
paul@109 | 230 | |
paul@109 | 231 | if hasattr(request, "values"): |
paul@109 | 232 | return Form(request.values) |
paul@109 | 233 | else: |
paul@109 | 234 | return request.form |
paul@109 | 235 | |
paul@110 | 236 | class send_headers: |
paul@110 | 237 | |
paul@110 | 238 | """ |
paul@110 | 239 | A wrapper to preserve MoinMoin 1.8.x (and earlier) request behaviour in a |
paul@110 | 240 | 1.9.x environment. |
paul@110 | 241 | """ |
paul@110 | 242 | |
paul@110 | 243 | def __init__(self, request): |
paul@110 | 244 | self.request = request |
paul@110 | 245 | |
paul@110 | 246 | def __call__(self, headers): |
paul@110 | 247 | for header in headers: |
paul@110 | 248 | parts = header.split(":") |
paul@110 | 249 | self.request.headers.add(parts[0], ":".join(parts[1:])) |
paul@110 | 250 | |
paul@67 | 251 | # Textual representations. |
paul@67 | 252 | |
paul@67 | 253 | def getHTTPTimeString(tmtuple): |
paul@67 | 254 | return "%s, %02d %s %04d %02d:%02d:%02d GMT" % ( |
paul@129 | 255 | getDayLabel(tmtuple.tm_wday), |
paul@67 | 256 | tmtuple.tm_mday, |
paul@129 | 257 | getMonthLabel(tmtuple.tm_mon), |
paul@67 | 258 | tmtuple.tm_year, |
paul@67 | 259 | tmtuple.tm_hour, |
paul@67 | 260 | tmtuple.tm_min, |
paul@67 | 261 | tmtuple.tm_sec |
paul@67 | 262 | ) |
paul@67 | 263 | |
paul@67 | 264 | def getSimpleWikiText(text): |
paul@67 | 265 | |
paul@67 | 266 | """ |
paul@67 | 267 | Return the plain text representation of the given 'text' which may employ |
paul@67 | 268 | certain Wiki syntax features, such as those providing verbatim or monospaced |
paul@67 | 269 | text. |
paul@67 | 270 | """ |
paul@67 | 271 | |
paul@67 | 272 | # NOTE: Re-implementing support for verbatim text and linking avoidance. |
paul@67 | 273 | |
paul@67 | 274 | return "".join([s for s in verbatim_regexp.split(text) if s is not None]) |
paul@67 | 275 | |
paul@67 | 276 | def getEncodedWikiText(text): |
paul@67 | 277 | |
paul@67 | 278 | "Encode the given 'text' in a verbatim representation." |
paul@67 | 279 | |
paul@67 | 280 | return "<<Verbatim(%s)>>" % text |
paul@67 | 281 | |
paul@67 | 282 | def getPrettyTitle(title): |
paul@67 | 283 | |
paul@67 | 284 | "Return a nicely formatted version of the given 'title'." |
paul@67 | 285 | |
paul@67 | 286 | return title.replace("_", " ").replace("/", u" ? ") |
paul@67 | 287 | |
paul@67 | 288 | def getMonthLabel(month): |
paul@67 | 289 | |
paul@67 | 290 | "Return an unlocalised label for the given 'month'." |
paul@67 | 291 | |
paul@67 | 292 | return month_labels[month - 1] # zero-based labels |
paul@67 | 293 | |
paul@67 | 294 | def getDayLabel(weekday): |
paul@67 | 295 | |
paul@67 | 296 | "Return an unlocalised label for the given 'weekday'." |
paul@67 | 297 | |
paul@67 | 298 | return weekday_labels[weekday] |
paul@67 | 299 | |
paul@19 | 300 | # Action support functions. |
paul@19 | 301 | |
paul@67 | 302 | def getPageRevision(page): |
paul@67 | 303 | |
paul@67 | 304 | "Return the revision details dictionary for the given 'page'." |
paul@67 | 305 | |
paul@67 | 306 | # From Page.edit_info... |
paul@67 | 307 | |
paul@67 | 308 | if hasattr(page, "editlog_entry"): |
paul@67 | 309 | line = page.editlog_entry() |
paul@67 | 310 | else: |
paul@67 | 311 | line = page._last_edited(page.request) # MoinMoin 1.5.x and 1.6.x |
paul@67 | 312 | |
paul@89 | 313 | # Similar to Page.mtime_usecs behaviour... |
paul@89 | 314 | |
paul@89 | 315 | if line: |
paul@89 | 316 | timestamp = line.ed_time_usecs |
paul@89 | 317 | mtime = wikiutil.version2timestamp(long(timestamp)) # must be long for py 2.2.x |
paul@89 | 318 | comment = line.comment |
paul@89 | 319 | else: |
paul@89 | 320 | mtime = 0 |
paul@89 | 321 | comment = "" |
paul@89 | 322 | |
paul@89 | 323 | return {"timestamp" : time.gmtime(mtime), "comment" : comment} |
paul@67 | 324 | |
paul@67 | 325 | # Category discovery and searching. |
paul@67 | 326 | |
paul@19 | 327 | def getCategories(request): |
paul@19 | 328 | |
paul@19 | 329 | """ |
paul@19 | 330 | From the AdvancedSearch macro, return a list of category page names using |
paul@19 | 331 | the given 'request'. |
paul@19 | 332 | """ |
paul@19 | 333 | |
paul@19 | 334 | # This will return all pages with "Category" in the title. |
paul@19 | 335 | |
paul@19 | 336 | cat_filter = getCategoryPattern(request).search |
paul@19 | 337 | return request.rootpage.getPageList(filter=cat_filter) |
paul@19 | 338 | |
paul@19 | 339 | def getCategoryMapping(category_pagenames, request): |
paul@19 | 340 | |
paul@19 | 341 | """ |
paul@19 | 342 | For the given 'category_pagenames' return a list of tuples of the form |
paul@19 | 343 | (category name, category page name) using the given 'request'. |
paul@19 | 344 | """ |
paul@19 | 345 | |
paul@19 | 346 | cat_pattern = getCategoryPattern(request) |
paul@19 | 347 | mapping = [] |
paul@19 | 348 | for pagename in category_pagenames: |
paul@19 | 349 | name = cat_pattern.match(pagename).group("key") |
paul@19 | 350 | if name != "Category": |
paul@19 | 351 | mapping.append((name, pagename)) |
paul@19 | 352 | mapping.sort() |
paul@19 | 353 | return mapping |
paul@19 | 354 | |
paul@67 | 355 | def getCategoryPages(pagename, request): |
paul@29 | 356 | |
paul@67 | 357 | """ |
paul@67 | 358 | Return the pages associated with the given category 'pagename' using the |
paul@67 | 359 | 'request'. |
paul@67 | 360 | """ |
paul@10 | 361 | |
paul@10 | 362 | query = search.QueryParser().parse_query('category:%s' % pagename) |
paul@117 | 363 | results = search.searchPages(request, query, "page_name") |
paul@10 | 364 | |
paul@10 | 365 | cat_pattern = getCategoryPattern(request) |
paul@10 | 366 | pages = [] |
paul@10 | 367 | for page in results.hits: |
paul@10 | 368 | if not cat_pattern.match(page.page_name): |
paul@10 | 369 | pages.append(page) |
paul@10 | 370 | return pages |
paul@10 | 371 | |
paul@67 | 372 | # The main activity functions. |
paul@67 | 373 | |
paul@67 | 374 | class EventPage: |
paul@67 | 375 | |
paul@67 | 376 | "An event page." |
paul@67 | 377 | |
paul@67 | 378 | def __init__(self, page): |
paul@67 | 379 | self.page = page |
paul@69 | 380 | self.events = None |
paul@67 | 381 | self.body = None |
paul@67 | 382 | self.categories = None |
paul@67 | 383 | |
paul@67 | 384 | def copyPage(self, page): |
paul@67 | 385 | |
paul@67 | 386 | "Copy the body of the given 'page'." |
paul@67 | 387 | |
paul@67 | 388 | self.body = page.getBody() |
paul@67 | 389 | |
paul@67 | 390 | def getPageURL(self, request): |
paul@67 | 391 | |
paul@67 | 392 | "Using 'request', return the URL of this page." |
paul@24 | 393 | |
paul@117 | 394 | return request.getQualifiedURL(self.page.url(request, relative=0)) |
paul@67 | 395 | |
paul@67 | 396 | def getFormat(self): |
paul@67 | 397 | |
paul@67 | 398 | "Get the format used on this page." |
paul@24 | 399 | |
paul@117 | 400 | return self.page.pi["format"] |
paul@67 | 401 | |
paul@67 | 402 | def getRevisions(self): |
paul@67 | 403 | |
paul@67 | 404 | "Return a list of page revisions." |
paul@67 | 405 | |
paul@67 | 406 | return self.page.getRevList() |
paul@67 | 407 | |
paul@67 | 408 | def getPageRevision(self): |
paul@24 | 409 | |
paul@67 | 410 | "Return the revision details dictionary for this page." |
paul@67 | 411 | |
paul@67 | 412 | return getPageRevision(self.page) |
paul@67 | 413 | |
paul@67 | 414 | def getPageName(self): |
paul@67 | 415 | |
paul@67 | 416 | "Return the page name." |
paul@67 | 417 | |
paul@67 | 418 | return self.page.page_name |
paul@24 | 419 | |
paul@67 | 420 | def getPrettyPageName(self): |
paul@67 | 421 | |
paul@67 | 422 | "Return a nicely formatted title/name for this page." |
paul@67 | 423 | |
paul@67 | 424 | return getPrettyPageName(self.page) |
paul@67 | 425 | |
paul@67 | 426 | def getBody(self): |
paul@67 | 427 | |
paul@67 | 428 | "Get the current page body." |
paul@47 | 429 | |
paul@67 | 430 | if self.body is None: |
paul@67 | 431 | self.body = self.page.get_raw_body() |
paul@67 | 432 | return self.body |
paul@67 | 433 | |
paul@69 | 434 | def getEvents(self): |
paul@69 | 435 | |
paul@69 | 436 | "Return a list of events from this page." |
paul@67 | 437 | |
paul@69 | 438 | if self.events is None: |
paul@69 | 439 | details = {} |
paul@69 | 440 | self.events = [Event(self, details)] |
paul@47 | 441 | |
paul@67 | 442 | if self.getFormat() == "wiki": |
paul@67 | 443 | for match in definition_list_regexp.finditer(self.getBody()): |
paul@67 | 444 | |
paul@67 | 445 | # Skip commented-out items. |
paul@47 | 446 | |
paul@67 | 447 | if match.group("optcomment"): |
paul@67 | 448 | continue |
paul@67 | 449 | |
paul@67 | 450 | # Permit case-insensitive list terms. |
paul@67 | 451 | |
paul@67 | 452 | term = match.group("term").lower() |
paul@67 | 453 | desc = match.group("desc") |
paul@67 | 454 | |
paul@67 | 455 | # Special value type handling. |
paul@27 | 456 | |
paul@67 | 457 | # Dates. |
paul@67 | 458 | |
paul@67 | 459 | if term in ("start", "end"): |
paul@123 | 460 | desc = getDateTime(desc) |
paul@67 | 461 | |
paul@67 | 462 | # Lists (whose elements may be quoted). |
paul@67 | 463 | |
paul@67 | 464 | elif term in ("topics", "categories"): |
paul@84 | 465 | desc = [getSimpleWikiText(value.strip()) for value in desc.split(",") if value.strip()] |
paul@67 | 466 | |
paul@67 | 467 | # Labels which may well be quoted. |
paul@67 | 468 | |
paul@92 | 469 | elif term in ("title", "summary", "description", "location"): |
paul@67 | 470 | desc = getSimpleWikiText(desc) |
paul@67 | 471 | |
paul@67 | 472 | if desc is not None: |
paul@69 | 473 | |
paul@69 | 474 | # Handle apparent duplicates by creating a new set of |
paul@69 | 475 | # details. |
paul@69 | 476 | |
paul@69 | 477 | if details.has_key(term): |
paul@92 | 478 | |
paul@92 | 479 | # Make a new event. |
paul@92 | 480 | |
paul@69 | 481 | details = {} |
paul@69 | 482 | self.events.append(Event(self, details)) |
paul@67 | 483 | |
paul@69 | 484 | details[term] = desc |
paul@69 | 485 | |
paul@69 | 486 | return self.events |
paul@69 | 487 | |
paul@69 | 488 | def setEvents(self, events): |
paul@69 | 489 | |
paul@69 | 490 | "Set the given 'events' on this page." |
paul@69 | 491 | |
paul@69 | 492 | self.events = events |
paul@67 | 493 | |
paul@67 | 494 | def getCategoryMembership(self): |
paul@27 | 495 | |
paul@67 | 496 | "Get the category names from this page." |
paul@67 | 497 | |
paul@67 | 498 | if self.categories is None: |
paul@67 | 499 | body = self.getBody() |
paul@67 | 500 | match = category_membership_regexp.search(body) |
paul@67 | 501 | self.categories = match.findall().split() |
paul@67 | 502 | |
paul@67 | 503 | return self.categories |
paul@67 | 504 | |
paul@67 | 505 | def setCategoryMembership(self, category_names): |
paul@10 | 506 | |
paul@67 | 507 | """ |
paul@67 | 508 | Set the category membership for the page using the specified |
paul@67 | 509 | 'category_names'. |
paul@67 | 510 | """ |
paul@67 | 511 | |
paul@67 | 512 | self.categories = category_names |
paul@67 | 513 | |
paul@67 | 514 | def flushEventDetails(self): |
paul@67 | 515 | |
paul@67 | 516 | "Flush the current event details to this page's body text." |
paul@10 | 517 | |
paul@67 | 518 | new_body_parts = [] |
paul@67 | 519 | end_of_last_match = 0 |
paul@67 | 520 | body = self.getBody() |
paul@69 | 521 | |
paul@69 | 522 | events = iter(self.getEvents()) |
paul@69 | 523 | |
paul@69 | 524 | event = events.next() |
paul@69 | 525 | event_details = event.getDetails() |
paul@69 | 526 | replaced_terms = set() |
paul@67 | 527 | |
paul@67 | 528 | for match in definition_list_regexp.finditer(body): |
paul@47 | 529 | |
paul@10 | 530 | # Permit case-insensitive list terms. |
paul@10 | 531 | |
paul@10 | 532 | term = match.group("term").lower() |
paul@10 | 533 | desc = match.group("desc") |
paul@10 | 534 | |
paul@69 | 535 | # Check that the term has not already been substituted. If so, |
paul@69 | 536 | # get the next event. |
paul@69 | 537 | |
paul@69 | 538 | if term in replaced_terms: |
paul@69 | 539 | try: |
paul@69 | 540 | event = events.next() |
paul@69 | 541 | |
paul@69 | 542 | # No more events. |
paul@69 | 543 | |
paul@69 | 544 | except StopIteration: |
paul@69 | 545 | break |
paul@69 | 546 | |
paul@69 | 547 | event_details = event.getDetails() |
paul@69 | 548 | replaced_terms = set() |
paul@69 | 549 | |
paul@75 | 550 | # Add preceding text to the new body. |
paul@75 | 551 | |
paul@75 | 552 | new_body_parts.append(body[end_of_last_match:match.start()]) |
paul@75 | 553 | |
paul@75 | 554 | # Get the matching regions, adding the term to the new body. |
paul@75 | 555 | |
paul@75 | 556 | new_body_parts.append(match.group("wholeterm")) |
paul@75 | 557 | |
paul@10 | 558 | # Special value type handling. |
paul@10 | 559 | |
paul@67 | 560 | if event_details.has_key(term): |
paul@19 | 561 | |
paul@67 | 562 | # Dates. |
paul@47 | 563 | |
paul@67 | 564 | if term in ("start", "end"): |
paul@67 | 565 | desc = desc.replace("YYYY-MM-DD", str(event_details[term])) |
paul@47 | 566 | |
paul@67 | 567 | # Lists (whose elements may be quoted). |
paul@47 | 568 | |
paul@67 | 569 | elif term in ("topics", "categories"): |
paul@92 | 570 | desc = ", ".join([getEncodedWikiText(item) for item in event_details[term]]) |
paul@47 | 571 | |
paul@92 | 572 | # Labels which must be quoted. |
paul@47 | 573 | |
paul@67 | 574 | elif term in ("title", "summary"): |
paul@67 | 575 | desc = getEncodedWikiText(event_details[term]) |
paul@47 | 576 | |
paul@67 | 577 | # Text which need not be quoted, but it will be Wiki text. |
paul@55 | 578 | |
paul@92 | 579 | elif term in ("description", "link", "location"): |
paul@67 | 580 | desc = event_details[term] |
paul@55 | 581 | |
paul@69 | 582 | replaced_terms.add(term) |
paul@69 | 583 | |
paul@75 | 584 | # Add the replaced value. |
paul@75 | 585 | |
paul@67 | 586 | new_body_parts.append(desc) |
paul@10 | 587 | |
paul@69 | 588 | # Remember where in the page has been processed. |
paul@69 | 589 | |
paul@69 | 590 | end_of_last_match = match.end() |
paul@69 | 591 | |
paul@69 | 592 | # Write the rest of the page. |
paul@69 | 593 | |
paul@69 | 594 | new_body_parts.append(body[end_of_last_match:]) |
paul@10 | 595 | |
paul@67 | 596 | self.body = "".join(new_body_parts) |
paul@11 | 597 | |
paul@67 | 598 | def flushCategoryMembership(self): |
paul@17 | 599 | |
paul@67 | 600 | "Flush the category membership to the page body." |
paul@11 | 601 | |
paul@67 | 602 | body = self.getBody() |
paul@67 | 603 | category_names = self.getCategoryMembership() |
paul@67 | 604 | match = category_membership_regexp.search(body) |
paul@10 | 605 | |
paul@67 | 606 | if match: |
paul@67 | 607 | self.body = "".join([body[:match.start()], " ".join(category_names), body[match.end():]]) |
paul@10 | 608 | |
paul@67 | 609 | def saveChanges(self): |
paul@10 | 610 | |
paul@67 | 611 | "Save changes to the event." |
paul@10 | 612 | |
paul@67 | 613 | self.flushEventDetails() |
paul@67 | 614 | self.flushCategoryMembership() |
paul@67 | 615 | self.page.saveText(self.getBody(), 0) |
paul@10 | 616 | |
paul@67 | 617 | def linkToPage(self, request, text, query_string=None): |
paul@11 | 618 | |
paul@67 | 619 | """ |
paul@67 | 620 | Using 'request', return a link to this page with the given link 'text' |
paul@67 | 621 | and optional 'query_string'. |
paul@67 | 622 | """ |
paul@11 | 623 | |
paul@67 | 624 | return linkToPage(request, self.page, text, query_string) |
paul@13 | 625 | |
paul@130 | 626 | class ActsAsTimespan: |
paul@130 | 627 | pass |
paul@130 | 628 | |
paul@130 | 629 | class Event(ActsAsTimespan): |
paul@69 | 630 | |
paul@69 | 631 | "A description of an event." |
paul@69 | 632 | |
paul@69 | 633 | def __init__(self, page, details): |
paul@69 | 634 | self.page = page |
paul@69 | 635 | self.details = details |
paul@69 | 636 | |
paul@128 | 637 | def __hash__(self): |
paul@128 | 638 | return hash(self.getSummary()) |
paul@128 | 639 | |
paul@69 | 640 | def getPage(self): |
paul@69 | 641 | |
paul@69 | 642 | "Return the page describing this event." |
paul@69 | 643 | |
paul@69 | 644 | return self.page |
paul@69 | 645 | |
paul@69 | 646 | def setPage(self, page): |
paul@69 | 647 | |
paul@69 | 648 | "Set the 'page' describing this event." |
paul@69 | 649 | |
paul@69 | 650 | self.page = page |
paul@69 | 651 | |
paul@69 | 652 | def getSummary(self, event_parent=None): |
paul@69 | 653 | |
paul@69 | 654 | """ |
paul@69 | 655 | Return either the given title or summary of the event according to the |
paul@69 | 656 | event details, or a summary made from using the pretty version of the |
paul@69 | 657 | page name. |
paul@69 | 658 | |
paul@69 | 659 | If the optional 'event_parent' is specified, any page beneath the given |
paul@69 | 660 | 'event_parent' page in the page hierarchy will omit this parent information |
paul@69 | 661 | if its name is used as the summary. |
paul@69 | 662 | """ |
paul@69 | 663 | |
paul@69 | 664 | event_details = self.details |
paul@69 | 665 | |
paul@69 | 666 | if event_details.has_key("title"): |
paul@69 | 667 | return event_details["title"] |
paul@69 | 668 | elif event_details.has_key("summary"): |
paul@69 | 669 | return event_details["summary"] |
paul@69 | 670 | else: |
paul@69 | 671 | # If appropriate, remove the parent details and "/" character. |
paul@69 | 672 | |
paul@69 | 673 | title = self.page.getPageName() |
paul@69 | 674 | |
paul@74 | 675 | if event_parent and title.startswith(event_parent): |
paul@69 | 676 | title = title[len(event_parent.rstrip("/")) + 1:] |
paul@69 | 677 | |
paul@69 | 678 | return getPrettyTitle(title) |
paul@69 | 679 | |
paul@69 | 680 | def getDetails(self): |
paul@69 | 681 | |
paul@69 | 682 | "Return the details for this event." |
paul@69 | 683 | |
paul@69 | 684 | return self.details |
paul@69 | 685 | |
paul@69 | 686 | def setDetails(self, event_details): |
paul@69 | 687 | |
paul@69 | 688 | "Set the 'event_details' for this event." |
paul@69 | 689 | |
paul@69 | 690 | self.details = event_details |
paul@69 | 691 | |
paul@123 | 692 | # Timespan-related methods. |
paul@123 | 693 | |
paul@123 | 694 | def __contains__(self, other): |
paul@123 | 695 | return self == other |
paul@123 | 696 | |
paul@123 | 697 | def __cmp__(self, other): |
paul@123 | 698 | if isinstance(other, Event): |
paul@123 | 699 | return cmp(self.as_timespan(), other.as_timespan()) |
paul@123 | 700 | else: |
paul@123 | 701 | return cmp(self.as_timespan(), other) |
paul@123 | 702 | |
paul@123 | 703 | def as_timespan(self): |
paul@123 | 704 | details = self.details |
paul@123 | 705 | if details.has_key("start") and details.has_key("end"): |
paul@123 | 706 | return Timespan(details["start"], details["end"]) |
paul@123 | 707 | else: |
paul@123 | 708 | return None |
paul@123 | 709 | |
paul@128 | 710 | def as_limits(self): |
paul@128 | 711 | return self.as_timespan().as_limits() |
paul@123 | 712 | |
paul@122 | 713 | def getEvents(request, category_names, calendar_start=None, calendar_end=None, resolution="month"): |
paul@10 | 714 | |
paul@10 | 715 | """ |
paul@10 | 716 | Using the 'request', generate a list of events found on pages belonging to |
paul@10 | 717 | the specified 'category_names', using the optional 'calendar_start' and |
paul@122 | 718 | 'calendar_end' values to indicate a window of interest. |
paul@122 | 719 | |
paul@122 | 720 | The optional 'resolution' determines the unit of time used in providing the |
paul@122 | 721 | results: |
paul@10 | 722 | |
paul@122 | 723 | * a list of events |
paul@122 | 724 | * a dictionary mapping time units to event lists (within the window of |
paul@124 | 725 | interest), usable as a kind of index to groups of events |
paul@122 | 726 | * a list of all events within the window of interest |
paul@122 | 727 | * the earliest time value of an event within the window of interest |
paul@122 | 728 | * the latest time value of an event within the window of interest. |
paul@10 | 729 | """ |
paul@10 | 730 | |
paul@122 | 731 | # Dates need to comply with the requested resolution. |
paul@122 | 732 | # Here, None values need to be preserved when converting. |
paul@122 | 733 | |
paul@122 | 734 | if resolution == "month": |
paul@122 | 735 | convert = lambda x: x and x.as_month() |
paul@122 | 736 | get_values = lambda x, y: x.months_until(y) |
paul@122 | 737 | else: |
paul@122 | 738 | convert = lambda x: x and x.as_date() |
paul@122 | 739 | get_values = lambda x, y: x.days_until(y) |
paul@122 | 740 | |
paul@12 | 741 | # Re-order the window, if appropriate. |
paul@12 | 742 | |
paul@12 | 743 | if calendar_start is not None and calendar_end is not None and calendar_start > calendar_end: |
paul@122 | 744 | calendar_start, calendar_end = map(convert, (calendar_end, calendar_start)) |
paul@122 | 745 | |
paul@122 | 746 | # Otherwise, just convert the calendar limits. |
paul@122 | 747 | |
paul@122 | 748 | else: |
paul@122 | 749 | calendar_start, calendar_end = map(convert, (calendar_start, calendar_end)) |
paul@12 | 750 | |
paul@123 | 751 | calendar_period = Timespan(calendar_start, calendar_end) |
paul@123 | 752 | |
paul@10 | 753 | events = [] |
paul@10 | 754 | shown_events = {} |
paul@10 | 755 | all_shown_events = [] |
paul@17 | 756 | processed_pages = set() |
paul@10 | 757 | |
paul@10 | 758 | earliest = None |
paul@10 | 759 | latest = None |
paul@10 | 760 | |
paul@10 | 761 | for category_name in category_names: |
paul@10 | 762 | |
paul@10 | 763 | # Get the pages and page names in the category. |
paul@10 | 764 | |
paul@67 | 765 | pages_in_category = getCategoryPages(category_name, request) |
paul@10 | 766 | |
paul@10 | 767 | # Visit each page in the category. |
paul@10 | 768 | |
paul@10 | 769 | for page_in_category in pages_in_category: |
paul@10 | 770 | pagename = page_in_category.page_name |
paul@10 | 771 | |
paul@17 | 772 | # Only process each page once. |
paul@17 | 773 | |
paul@17 | 774 | if pagename in processed_pages: |
paul@17 | 775 | continue |
paul@17 | 776 | else: |
paul@17 | 777 | processed_pages.add(pagename) |
paul@17 | 778 | |
paul@10 | 779 | # Get a real page, not a result page. |
paul@10 | 780 | |
paul@67 | 781 | event_page = EventPage(Page(request, pagename)) |
paul@10 | 782 | |
paul@69 | 783 | # Get all events described in the page. |
paul@10 | 784 | |
paul@69 | 785 | for event in event_page.getEvents(): |
paul@69 | 786 | event_details = event.getDetails() |
paul@10 | 787 | |
paul@69 | 788 | # Remember the event. |
paul@69 | 789 | |
paul@69 | 790 | events.append(event) |
paul@10 | 791 | |
paul@69 | 792 | # Test for the suitability of the event. |
paul@69 | 793 | |
paul@123 | 794 | if event.as_timespan() is not None: |
paul@128 | 795 | start, end = map(convert, event.as_timespan().as_limits()) |
paul@10 | 796 | |
paul@122 | 797 | # Compare the dates to the requested calendar window, if any. |
paul@10 | 798 | |
paul@123 | 799 | if event in calendar_period: |
paul@10 | 800 | |
paul@69 | 801 | all_shown_events.append(event) |
paul@10 | 802 | |
paul@122 | 803 | if earliest is None or start < earliest: |
paul@122 | 804 | earliest = start |
paul@122 | 805 | if latest is None or end > latest: |
paul@122 | 806 | latest = end |
paul@10 | 807 | |
paul@122 | 808 | # Store the event in the time-specific dictionary. |
paul@10 | 809 | |
paul@122 | 810 | first = max(start, calendar_start or start) |
paul@122 | 811 | last = min(end, calendar_end or end) |
paul@10 | 812 | |
paul@122 | 813 | for event_time_value in get_values(first, last): |
paul@122 | 814 | if not shown_events.has_key(event_time_value): |
paul@122 | 815 | shown_events[event_time_value] = [] |
paul@122 | 816 | shown_events[event_time_value].append(event) |
paul@10 | 817 | |
paul@10 | 818 | return events, shown_events, all_shown_events, earliest, latest |
paul@10 | 819 | |
paul@29 | 820 | def setEventTimestamps(request, events): |
paul@29 | 821 | |
paul@29 | 822 | """ |
paul@29 | 823 | Using 'request', set timestamp details in the details dictionary of each of |
paul@67 | 824 | the 'events'. |
paul@29 | 825 | |
paul@111 | 826 | Return the latest timestamp found. |
paul@29 | 827 | """ |
paul@29 | 828 | |
paul@29 | 829 | latest = None |
paul@29 | 830 | |
paul@69 | 831 | for event in events: |
paul@69 | 832 | event_details = event.getDetails() |
paul@69 | 833 | event_page = event.getPage() |
paul@29 | 834 | |
paul@29 | 835 | # Get the initial revision of the page. |
paul@29 | 836 | |
paul@67 | 837 | revisions = event_page.getRevisions() |
paul@67 | 838 | event_page_initial = Page(request, event_page.getPageName(), rev=revisions[-1]) |
paul@29 | 839 | |
paul@29 | 840 | # Get the created and last modified times. |
paul@29 | 841 | |
paul@30 | 842 | initial_revision = getPageRevision(event_page_initial) |
paul@30 | 843 | event_details["created"] = initial_revision["timestamp"] |
paul@67 | 844 | latest_revision = event_page.getPageRevision() |
paul@30 | 845 | event_details["last-modified"] = latest_revision["timestamp"] |
paul@29 | 846 | event_details["sequence"] = len(revisions) - 1 |
paul@30 | 847 | event_details["last-comment"] = latest_revision["comment"] |
paul@29 | 848 | |
paul@29 | 849 | if latest is None or latest < event_details["last-modified"]: |
paul@29 | 850 | latest = event_details["last-modified"] |
paul@29 | 851 | |
paul@29 | 852 | return latest |
paul@29 | 853 | |
paul@26 | 854 | def getOrderedEvents(events): |
paul@26 | 855 | |
paul@26 | 856 | """ |
paul@26 | 857 | Return a list with the given 'events' ordered according to their start and |
paul@67 | 858 | end dates. |
paul@26 | 859 | """ |
paul@26 | 860 | |
paul@26 | 861 | ordered_events = events[:] |
paul@68 | 862 | ordered_events.sort() |
paul@26 | 863 | return ordered_events |
paul@26 | 864 | |
paul@13 | 865 | def getConcretePeriod(calendar_start, calendar_end, earliest, latest): |
paul@13 | 866 | |
paul@13 | 867 | """ |
paul@13 | 868 | From the requested 'calendar_start' and 'calendar_end', which may be None, |
paul@13 | 869 | indicating that no restriction is imposed on the period for each of the |
paul@13 | 870 | boundaries, use the 'earliest' and 'latest' event months to define a |
paul@13 | 871 | specific period of interest. |
paul@13 | 872 | """ |
paul@13 | 873 | |
paul@13 | 874 | # Define the period as starting with any specified start month or the |
paul@13 | 875 | # earliest event known, ending with any specified end month or the latest |
paul@13 | 876 | # event known. |
paul@13 | 877 | |
paul@13 | 878 | first = calendar_start or earliest |
paul@13 | 879 | last = calendar_end or latest |
paul@13 | 880 | |
paul@13 | 881 | # If there is no range of months to show, perhaps because there are no |
paul@13 | 882 | # events in the requested period, and there was no start or end month |
paul@13 | 883 | # specified, show only the month indicated by the start or end of the |
paul@13 | 884 | # requested period. If all events were to be shown but none were found show |
paul@13 | 885 | # the current month. |
paul@13 | 886 | |
paul@122 | 887 | if isinstance(first, Date): |
paul@122 | 888 | get_current = getCurrentDate |
paul@122 | 889 | else: |
paul@122 | 890 | get_current = getCurrentMonth |
paul@122 | 891 | |
paul@13 | 892 | if first is None: |
paul@122 | 893 | first = last or get_current() |
paul@13 | 894 | if last is None: |
paul@122 | 895 | last = first or get_current() |
paul@13 | 896 | |
paul@13 | 897 | # Permit "expiring" periods (where the start date approaches the end date). |
paul@13 | 898 | |
paul@13 | 899 | return min(first, last), last |
paul@13 | 900 | |
paul@122 | 901 | def getCoverage(start, end, events, resolution="date"): |
paul@15 | 902 | |
paul@15 | 903 | """ |
paul@15 | 904 | Within the period defined by the 'start' and 'end' dates, determine the |
paul@122 | 905 | coverage of the days in the period by the given 'events', returning a |
paul@122 | 906 | collection of timespans, along with a dictionary mapping locations to |
paul@122 | 907 | collections of slots, where each slot contains a tuple of the form |
paul@122 | 908 | (timespans, events). |
paul@15 | 909 | """ |
paul@15 | 910 | |
paul@118 | 911 | all_events = {} |
paul@123 | 912 | full_coverage = TimespanCollection(resolution) |
paul@123 | 913 | coverage_period = full_coverage.convert(Timespan(start, end)) |
paul@15 | 914 | |
paul@15 | 915 | # Get event details. |
paul@15 | 916 | |
paul@69 | 917 | for event in events: |
paul@69 | 918 | event_details = event.getDetails() |
paul@15 | 919 | |
paul@15 | 920 | # Test for the event in the period. |
paul@15 | 921 | |
paul@123 | 922 | if event in coverage_period: |
paul@15 | 923 | |
paul@15 | 924 | # Find the coverage of this period for the event. |
paul@15 | 925 | |
paul@118 | 926 | event_location = event_details.get("location") |
paul@15 | 927 | |
paul@15 | 928 | # Update the overall coverage. |
paul@15 | 929 | |
paul@124 | 930 | full_coverage.insert_in_order(event) |
paul@15 | 931 | |
paul@118 | 932 | # Add a new events list for a new location. |
paul@118 | 933 | # Locations can be unspecified, thus None refers to all unlocalised |
paul@118 | 934 | # events. |
paul@15 | 935 | |
paul@118 | 936 | if not all_events.has_key(event_location): |
paul@123 | 937 | all_events[event_location] = [TimespanCollection(resolution, [event])] |
paul@15 | 938 | |
paul@118 | 939 | # Try and fit the event into an events list. |
paul@15 | 940 | |
paul@15 | 941 | else: |
paul@118 | 942 | slot = all_events[event_location] |
paul@118 | 943 | |
paul@123 | 944 | for slot_events in slot: |
paul@118 | 945 | |
paul@130 | 946 | # Where the event does not overlap with the events in the |
paul@130 | 947 | # current collection, add it alongside these events. |
paul@118 | 948 | |
paul@123 | 949 | if not event in slot_events: |
paul@124 | 950 | slot_events.insert_in_order(event) |
paul@118 | 951 | break |
paul@118 | 952 | |
paul@118 | 953 | # Make a new element in the list if the event cannot be |
paul@118 | 954 | # marked alongside existing events. |
paul@118 | 955 | |
paul@118 | 956 | else: |
paul@123 | 957 | slot.append(TimespanCollection(resolution, [event])) |
paul@15 | 958 | |
paul@15 | 959 | return full_coverage, all_events |
paul@15 | 960 | |
paul@122 | 961 | def getCoverageScale(coverage): |
paul@126 | 962 | |
paul@126 | 963 | """ |
paul@126 | 964 | Return a scale for the given coverage so that the times involved are |
paul@126 | 965 | exposed. The scale consists of a list of non-overlapping timespans forming |
paul@126 | 966 | a contiguous period of time. |
paul@126 | 967 | """ |
paul@126 | 968 | |
paul@122 | 969 | times = set() |
paul@122 | 970 | for timespan in coverage: |
paul@128 | 971 | start, end = timespan.as_limits() |
paul@128 | 972 | |
paul@128 | 973 | # Add either genuine times or dates converted to times. |
paul@128 | 974 | |
paul@128 | 975 | if isinstance(start, DateTime): |
paul@128 | 976 | times.add(start) |
paul@128 | 977 | |
paul@128 | 978 | if isinstance(end, DateTime): |
paul@128 | 979 | if end.has_time(): |
paul@128 | 980 | times.add(end) |
paul@128 | 981 | else: |
paul@128 | 982 | times.add(end.as_date().next_day()) |
paul@128 | 983 | |
paul@122 | 984 | times = list(times) |
paul@122 | 985 | times.sort() |
paul@122 | 986 | |
paul@122 | 987 | scale = [] |
paul@122 | 988 | first = 1 |
paul@122 | 989 | start = None |
paul@122 | 990 | for time in times: |
paul@122 | 991 | if not first: |
paul@123 | 992 | scale.append(Timespan(start, time)) |
paul@122 | 993 | else: |
paul@122 | 994 | first = 0 |
paul@122 | 995 | start = time |
paul@126 | 996 | |
paul@122 | 997 | return scale |
paul@122 | 998 | |
paul@67 | 999 | # Date-related functions. |
paul@67 | 1000 | |
paul@67 | 1001 | class Period: |
paul@67 | 1002 | |
paul@67 | 1003 | "A simple period of time." |
paul@67 | 1004 | |
paul@67 | 1005 | def __init__(self, data): |
paul@67 | 1006 | self.data = data |
paul@67 | 1007 | |
paul@67 | 1008 | def months(self): |
paul@67 | 1009 | return self.data[0] * 12 + self.data[1] |
paul@67 | 1010 | |
paul@92 | 1011 | class Temporal: |
paul@67 | 1012 | |
paul@92 | 1013 | "A simple temporal representation, common to dates and times." |
paul@67 | 1014 | |
paul@67 | 1015 | def __init__(self, data): |
paul@92 | 1016 | self.data = list(data) |
paul@67 | 1017 | |
paul@67 | 1018 | def __repr__(self): |
paul@67 | 1019 | return "%s(%r)" % (self.__class__.__name__, self.data) |
paul@67 | 1020 | |
paul@67 | 1021 | def __hash__(self): |
paul@67 | 1022 | return hash(self.as_tuple()) |
paul@67 | 1023 | |
paul@67 | 1024 | def as_tuple(self): |
paul@92 | 1025 | return tuple(self.data) |
paul@92 | 1026 | |
paul@92 | 1027 | def __cmp__(self, other): |
paul@129 | 1028 | |
paul@129 | 1029 | """ |
paul@129 | 1030 | The result of comparing this instance with 'other' is derived from a |
paul@129 | 1031 | comparison of the instances' date(time) data at the highest common |
paul@129 | 1032 | resolution, meaning that if a date is compared to a datetime, the |
paul@129 | 1033 | datetime will be considered as a date. Thus, a date and a datetime |
paul@129 | 1034 | referring to the same date will be considered equal. |
paul@129 | 1035 | """ |
paul@129 | 1036 | |
paul@122 | 1037 | if not isinstance(other, Temporal): |
paul@122 | 1038 | return NotImplemented |
paul@122 | 1039 | else: |
paul@122 | 1040 | data = self.as_tuple() |
paul@122 | 1041 | other_data = other.as_tuple() |
paul@122 | 1042 | length = min(len(data), len(other_data)) |
paul@122 | 1043 | return cmp(data[:length], other_data[:length]) |
paul@92 | 1044 | |
paul@103 | 1045 | def until(self, start, end, nextfn, prevfn): |
paul@103 | 1046 | |
paul@103 | 1047 | """ |
paul@103 | 1048 | Return a collection of units of time by starting from the given 'start' |
paul@103 | 1049 | and stepping across intervening units until 'end' is reached, using the |
paul@103 | 1050 | given 'nextfn' and 'prevfn' to step from one unit to the next. |
paul@103 | 1051 | """ |
paul@103 | 1052 | |
paul@103 | 1053 | current = start |
paul@103 | 1054 | units = [current] |
paul@103 | 1055 | if current < end: |
paul@103 | 1056 | while current < end: |
paul@103 | 1057 | current = nextfn(current) |
paul@103 | 1058 | units.append(current) |
paul@103 | 1059 | elif current > end: |
paul@103 | 1060 | while current > end: |
paul@103 | 1061 | current = prevfn(current) |
paul@103 | 1062 | units.append(current) |
paul@103 | 1063 | return units |
paul@103 | 1064 | |
paul@92 | 1065 | class Month(Temporal): |
paul@92 | 1066 | |
paul@92 | 1067 | "A simple year-month representation." |
paul@92 | 1068 | |
paul@92 | 1069 | def __str__(self): |
paul@92 | 1070 | return "%04d-%02d" % self.as_tuple()[:2] |
paul@67 | 1071 | |
paul@93 | 1072 | def as_datetime(self, day, hour, minute, second, zone): |
paul@93 | 1073 | return DateTime(self.as_tuple() + (day, hour, minute, second, zone)) |
paul@93 | 1074 | |
paul@67 | 1075 | def as_date(self, day): |
paul@67 | 1076 | return Date(self.as_tuple() + (day,)) |
paul@67 | 1077 | |
paul@92 | 1078 | def as_month(self): |
paul@92 | 1079 | return self |
paul@92 | 1080 | |
paul@67 | 1081 | def year(self): |
paul@67 | 1082 | return self.data[0] |
paul@67 | 1083 | |
paul@67 | 1084 | def month(self): |
paul@67 | 1085 | return self.data[1] |
paul@67 | 1086 | |
paul@67 | 1087 | def month_properties(self): |
paul@67 | 1088 | |
paul@67 | 1089 | """ |
paul@67 | 1090 | Return the weekday of the 1st of the month, along with the number of |
paul@67 | 1091 | days, as a tuple. |
paul@67 | 1092 | """ |
paul@67 | 1093 | |
paul@92 | 1094 | year, month = self.as_tuple()[:2] |
paul@67 | 1095 | return calendar.monthrange(year, month) |
paul@67 | 1096 | |
paul@67 | 1097 | def month_update(self, n=1): |
paul@67 | 1098 | |
paul@67 | 1099 | "Return the month updated by 'n' months." |
paul@67 | 1100 | |
paul@92 | 1101 | year, month = self.as_tuple()[:2] |
paul@67 | 1102 | return Month((year + (month - 1 + n) / 12, (month - 1 + n) % 12 + 1)) |
paul@67 | 1103 | |
paul@67 | 1104 | def next_month(self): |
paul@67 | 1105 | |
paul@67 | 1106 | "Return the month following this one." |
paul@67 | 1107 | |
paul@67 | 1108 | return self.month_update(1) |
paul@67 | 1109 | |
paul@67 | 1110 | def previous_month(self): |
paul@67 | 1111 | |
paul@67 | 1112 | "Return the month preceding this one." |
paul@67 | 1113 | |
paul@67 | 1114 | return self.month_update(-1) |
paul@67 | 1115 | |
paul@67 | 1116 | def __sub__(self, start): |
paul@67 | 1117 | |
paul@67 | 1118 | """ |
paul@67 | 1119 | Return the difference in years and months between this month and the |
paul@67 | 1120 | 'start' month as a period. |
paul@67 | 1121 | """ |
paul@67 | 1122 | |
paul@67 | 1123 | return Period([(x - y) for x, y in zip(self.data, start.data)]) |
paul@67 | 1124 | |
paul@67 | 1125 | def months_until(self, end): |
paul@92 | 1126 | |
paul@92 | 1127 | "Return the collection of months from this month until 'end'." |
paul@92 | 1128 | |
paul@92 | 1129 | return self.until(self.as_month(), end.as_month(), Month.next_month, Month.previous_month) |
paul@67 | 1130 | |
paul@67 | 1131 | class Date(Month): |
paul@67 | 1132 | |
paul@67 | 1133 | "A simple year-month-day representation." |
paul@67 | 1134 | |
paul@96 | 1135 | def constrain(self): |
paul@96 | 1136 | year, month, day = self.as_tuple()[:3] |
paul@96 | 1137 | |
paul@96 | 1138 | month = max(min(month, 12), 1) |
paul@96 | 1139 | wd, last_day = calendar.monthrange(year, month) |
paul@96 | 1140 | day = max(min(day, last_day), 1) |
paul@96 | 1141 | |
paul@96 | 1142 | self.data[1:3] = month, day |
paul@96 | 1143 | |
paul@67 | 1144 | def __str__(self): |
paul@67 | 1145 | return "%04d-%02d-%02d" % self.as_tuple()[:3] |
paul@67 | 1146 | |
paul@93 | 1147 | def as_datetime(self, hour, minute, second, zone): |
paul@93 | 1148 | return DateTime(self.as_tuple() + (hour, minute, second, zone)) |
paul@93 | 1149 | |
paul@92 | 1150 | def as_date(self): |
paul@92 | 1151 | return self |
paul@92 | 1152 | |
paul@130 | 1153 | def as_datetime_or_date(self): |
paul@130 | 1154 | return self |
paul@130 | 1155 | |
paul@67 | 1156 | def as_month(self): |
paul@67 | 1157 | return Month(self.data[:2]) |
paul@67 | 1158 | |
paul@67 | 1159 | def day(self): |
paul@67 | 1160 | return self.data[2] |
paul@67 | 1161 | |
paul@122 | 1162 | def day_update(self, n=1): |
paul@122 | 1163 | |
paul@122 | 1164 | "Return the month updated by 'n' months." |
paul@122 | 1165 | |
paul@122 | 1166 | delta = datetime.timedelta(n) |
paul@122 | 1167 | dt = datetime.date(*self.as_tuple()[:3]) |
paul@122 | 1168 | dt_new = dt + delta |
paul@122 | 1169 | return Date((dt_new.year, dt_new.month, dt_new.day)) |
paul@122 | 1170 | |
paul@67 | 1171 | def next_day(self): |
paul@67 | 1172 | |
paul@67 | 1173 | "Return the date following this one." |
paul@67 | 1174 | |
paul@92 | 1175 | year, month, day = self.as_tuple()[:3] |
paul@67 | 1176 | _wd, end_day = calendar.monthrange(year, month) |
paul@67 | 1177 | if day == end_day: |
paul@67 | 1178 | if month == 12: |
paul@67 | 1179 | return Date((year + 1, 1, 1)) |
paul@67 | 1180 | else: |
paul@67 | 1181 | return Date((year, month + 1, 1)) |
paul@67 | 1182 | else: |
paul@67 | 1183 | return Date((year, month, day + 1)) |
paul@67 | 1184 | |
paul@67 | 1185 | def previous_day(self): |
paul@67 | 1186 | |
paul@67 | 1187 | "Return the date preceding this one." |
paul@67 | 1188 | |
paul@92 | 1189 | year, month, day = self.as_tuple()[:3] |
paul@67 | 1190 | if day == 1: |
paul@67 | 1191 | if month == 1: |
paul@67 | 1192 | return Date((year - 1, 12, 31)) |
paul@67 | 1193 | else: |
paul@67 | 1194 | _wd, end_day = calendar.monthrange(year, month - 1) |
paul@67 | 1195 | return Date((year, month - 1, end_day)) |
paul@67 | 1196 | else: |
paul@67 | 1197 | return Date((year, month, day - 1)) |
paul@67 | 1198 | |
paul@67 | 1199 | def days_until(self, end): |
paul@92 | 1200 | |
paul@92 | 1201 | "Return the collection of days from this date until 'end'." |
paul@92 | 1202 | |
paul@92 | 1203 | return self.until(self.as_date(), end.as_date(), Date.next_day, Date.previous_day) |
paul@92 | 1204 | |
paul@92 | 1205 | class DateTime(Date): |
paul@92 | 1206 | |
paul@92 | 1207 | "A simple date plus time representation." |
paul@92 | 1208 | |
paul@96 | 1209 | def constrain(self): |
paul@96 | 1210 | Date.constrain(self) |
paul@96 | 1211 | |
paul@96 | 1212 | hour, minute, second = self.as_tuple()[3:6] |
paul@96 | 1213 | |
paul@96 | 1214 | if self.has_time(): |
paul@96 | 1215 | hour = max(min(hour, 23), 0) |
paul@96 | 1216 | minute = max(min(minute, 59), 0) |
paul@96 | 1217 | |
paul@96 | 1218 | if second is not None: |
paul@96 | 1219 | second = max(min(second, 60), 0) # support leap seconds |
paul@96 | 1220 | |
paul@96 | 1221 | self.data[3:6] = hour, minute, second |
paul@92 | 1222 | |
paul@92 | 1223 | def __str__(self): |
paul@128 | 1224 | return Date.__str__(self) + self.time_string() |
paul@128 | 1225 | |
paul@128 | 1226 | def time_string(self): |
paul@92 | 1227 | if self.has_time(): |
paul@92 | 1228 | data = self.as_tuple() |
paul@92 | 1229 | time_str = " %02d:%02d" % data[3:5] |
paul@92 | 1230 | if data[5] is not None: |
paul@92 | 1231 | time_str += ":%02d" % data[5] |
paul@92 | 1232 | if data[6] is not None: |
paul@92 | 1233 | time_str += " %s" % data[6] |
paul@128 | 1234 | return time_str |
paul@92 | 1235 | else: |
paul@128 | 1236 | return "" |
paul@92 | 1237 | |
paul@93 | 1238 | def as_datetime(self): |
paul@93 | 1239 | return self |
paul@93 | 1240 | |
paul@92 | 1241 | def as_date(self): |
paul@92 | 1242 | return Date(self.data[:3]) |
paul@92 | 1243 | |
paul@128 | 1244 | def as_datetime_or_date(self): |
paul@128 | 1245 | |
paul@128 | 1246 | """ |
paul@128 | 1247 | Return a date for this datetime if fields are missing. Otherwise, return |
paul@128 | 1248 | this datetime itself. |
paul@128 | 1249 | """ |
paul@128 | 1250 | |
paul@128 | 1251 | if not self.has_time(): |
paul@128 | 1252 | return self.as_date() |
paul@128 | 1253 | else: |
paul@128 | 1254 | return self |
paul@128 | 1255 | |
paul@126 | 1256 | def __cmp__(self, other): |
paul@129 | 1257 | |
paul@129 | 1258 | """ |
paul@129 | 1259 | The result of comparing this instance with 'other' is, if both instances |
paul@129 | 1260 | are datetime instances, derived from a comparison of the datetimes |
paul@129 | 1261 | converted to UTC. If one or both datetimes cannot be converted to UTC, |
paul@129 | 1262 | the datetimes are compared using the basic temporal comparison which |
paul@129 | 1263 | compares their raw time data. |
paul@129 | 1264 | """ |
paul@129 | 1265 | |
paul@128 | 1266 | this = self.as_datetime_or_date() |
paul@128 | 1267 | |
paul@128 | 1268 | if isinstance(this, DateTime) and isinstance(other, DateTime): |
paul@128 | 1269 | other = other.as_datetime_or_date() |
paul@128 | 1270 | if isinstance(other, DateTime): |
paul@128 | 1271 | this_utc = this.to_utc() |
paul@128 | 1272 | other_utc = other.to_utc() |
paul@128 | 1273 | if this_utc is not None and other_utc is not None: |
paul@128 | 1274 | return cmp(this_utc.as_tuple(), other_utc.as_tuple()) |
paul@128 | 1275 | |
paul@128 | 1276 | return Date.__cmp__(this, other) |
paul@126 | 1277 | |
paul@92 | 1278 | def has_time(self): |
paul@92 | 1279 | return self.data[3] is not None and self.data[4] is not None |
paul@92 | 1280 | |
paul@128 | 1281 | def time(self): |
paul@128 | 1282 | return self.data[3:] |
paul@128 | 1283 | |
paul@92 | 1284 | def seconds(self): |
paul@92 | 1285 | return self.data[5] |
paul@92 | 1286 | |
paul@92 | 1287 | def time_zone(self): |
paul@92 | 1288 | return self.data[6] |
paul@92 | 1289 | |
paul@93 | 1290 | def set_time_zone(self, value): |
paul@92 | 1291 | self.data[6] = value |
paul@92 | 1292 | |
paul@92 | 1293 | def padded(self): |
paul@92 | 1294 | |
paul@92 | 1295 | "Return a datetime with missing fields defined as being zero." |
paul@92 | 1296 | |
paul@92 | 1297 | data = map(lambda x: x or 0, self.data[:6]) + self.data[6:] |
paul@92 | 1298 | return DateTime(data) |
paul@92 | 1299 | |
paul@93 | 1300 | def to_utc(self): |
paul@93 | 1301 | |
paul@93 | 1302 | """ |
paul@93 | 1303 | Return this object converted to UTC, or None if such a conversion is not |
paul@93 | 1304 | defined. |
paul@93 | 1305 | """ |
paul@93 | 1306 | |
paul@128 | 1307 | if not self.has_time(): |
paul@128 | 1308 | return None |
paul@128 | 1309 | |
paul@93 | 1310 | offset = self.utc_offset() |
paul@93 | 1311 | if offset: |
paul@93 | 1312 | hours, minutes = offset |
paul@93 | 1313 | |
paul@93 | 1314 | # Invert the offset to get the correction. |
paul@93 | 1315 | |
paul@93 | 1316 | hours, minutes = -hours, -minutes |
paul@93 | 1317 | |
paul@93 | 1318 | # Get the components. |
paul@93 | 1319 | |
paul@128 | 1320 | hour, minute, second, zone = self.time() |
paul@93 | 1321 | date = self.as_date() |
paul@93 | 1322 | |
paul@93 | 1323 | # Add the minutes and hours. |
paul@93 | 1324 | |
paul@93 | 1325 | minute += minutes |
paul@103 | 1326 | if minute < 0 or minute > 59: |
paul@103 | 1327 | hour += minute / 60 |
paul@103 | 1328 | minute = minute % 60 |
paul@103 | 1329 | |
paul@103 | 1330 | # NOTE: This makes various assumptions and probably would not work |
paul@103 | 1331 | # NOTE: for general arithmetic. |
paul@93 | 1332 | |
paul@93 | 1333 | hour += hours |
paul@93 | 1334 | if hour < 0: |
paul@93 | 1335 | date = date.previous_day() |
paul@93 | 1336 | hour += 24 |
paul@93 | 1337 | elif hour > 23: |
paul@93 | 1338 | date = date.next_day() |
paul@93 | 1339 | hour -= 24 |
paul@93 | 1340 | |
paul@93 | 1341 | return date.as_datetime(hour, minute, second, "UTC") |
paul@100 | 1342 | |
paul@100 | 1343 | # Cannot convert. |
paul@100 | 1344 | |
paul@93 | 1345 | else: |
paul@93 | 1346 | return None |
paul@93 | 1347 | |
paul@93 | 1348 | def utc_offset(self): |
paul@93 | 1349 | |
paul@93 | 1350 | "Return the UTC offset in hours and minutes." |
paul@93 | 1351 | |
paul@93 | 1352 | zone = self.time_zone() |
paul@95 | 1353 | if not zone: |
paul@95 | 1354 | return None |
paul@93 | 1355 | |
paul@96 | 1356 | # Support explicit UTC zones. |
paul@96 | 1357 | |
paul@96 | 1358 | if zone == "UTC": |
paul@96 | 1359 | return 0, 0 |
paul@96 | 1360 | |
paul@94 | 1361 | # Attempt to return a UTC offset where an explicit offset has been set. |
paul@93 | 1362 | |
paul@94 | 1363 | match = timezone_offset_regexp.match(zone) |
paul@94 | 1364 | if match: |
paul@94 | 1365 | if match.group("sign") == "-": |
paul@93 | 1366 | sign = -1 |
paul@93 | 1367 | else: |
paul@93 | 1368 | sign = 1 |
paul@93 | 1369 | |
paul@94 | 1370 | hours = int(match.group("hours")) * sign |
paul@94 | 1371 | minutes = int(match.group("minutes") or 0) * sign |
paul@94 | 1372 | return hours, minutes |
paul@94 | 1373 | |
paul@102 | 1374 | # Attempt to handle Olson time zone identifiers. |
paul@102 | 1375 | |
paul@102 | 1376 | dt = self.as_olson_datetime() |
paul@102 | 1377 | if dt: |
paul@102 | 1378 | seconds = dt.utcoffset().seconds |
paul@102 | 1379 | hours = seconds / 3600 |
paul@102 | 1380 | minutes = (seconds % 3600) / 60 |
paul@102 | 1381 | return hours, minutes |
paul@102 | 1382 | |
paul@102 | 1383 | # Otherwise return None. |
paul@102 | 1384 | |
paul@93 | 1385 | return None |
paul@93 | 1386 | |
paul@100 | 1387 | def olson_identifier(self): |
paul@100 | 1388 | |
paul@100 | 1389 | "Return the Olson identifier from any zone information." |
paul@100 | 1390 | |
paul@100 | 1391 | zone = self.time_zone() |
paul@100 | 1392 | if not zone: |
paul@100 | 1393 | return None |
paul@100 | 1394 | |
paul@100 | 1395 | # Attempt to match an identifier. |
paul@100 | 1396 | |
paul@100 | 1397 | match = timezone_olson_regexp.match(zone) |
paul@100 | 1398 | if match: |
paul@100 | 1399 | return match.group("olson") |
paul@100 | 1400 | else: |
paul@100 | 1401 | return None |
paul@100 | 1402 | |
paul@102 | 1403 | def _as_olson_datetime(self, hours=None): |
paul@102 | 1404 | |
paul@102 | 1405 | """ |
paul@102 | 1406 | Return a Python datetime object for this datetime interpreted using any |
paul@102 | 1407 | Olson time zone identifier and the given 'hours' offset, raising one of |
paul@102 | 1408 | the pytz exceptions in case of ambiguity. |
paul@102 | 1409 | """ |
paul@102 | 1410 | |
paul@102 | 1411 | olson = self.olson_identifier() |
paul@102 | 1412 | if olson and pytz: |
paul@102 | 1413 | tz = pytz.timezone(olson) |
paul@102 | 1414 | data = self.padded().as_tuple()[:6] |
paul@102 | 1415 | dt = datetime.datetime(*data) |
paul@102 | 1416 | |
paul@102 | 1417 | # With an hours offset, find a time probably in a previously |
paul@102 | 1418 | # applicable time zone. |
paul@102 | 1419 | |
paul@102 | 1420 | if hours is not None: |
paul@102 | 1421 | td = datetime.timedelta(0, hours * 3600) |
paul@102 | 1422 | dt += td |
paul@102 | 1423 | |
paul@102 | 1424 | ldt = tz.localize(dt, None) |
paul@102 | 1425 | |
paul@102 | 1426 | # With an hours offset, adjust the time to define it within the |
paul@102 | 1427 | # previously applicable time zone but at the presumably intended |
paul@102 | 1428 | # position. |
paul@102 | 1429 | |
paul@102 | 1430 | if hours is not None: |
paul@102 | 1431 | ldt -= td |
paul@102 | 1432 | |
paul@102 | 1433 | return ldt |
paul@102 | 1434 | else: |
paul@102 | 1435 | return None |
paul@102 | 1436 | |
paul@102 | 1437 | def as_olson_datetime(self): |
paul@102 | 1438 | |
paul@102 | 1439 | """ |
paul@102 | 1440 | Return a Python datetime object for this datetime interpreted using any |
paul@102 | 1441 | Olson time zone identifier, choosing the time from the zone before the |
paul@102 | 1442 | period of ambiguity. |
paul@102 | 1443 | """ |
paul@102 | 1444 | |
paul@102 | 1445 | try: |
paul@102 | 1446 | return self._as_olson_datetime() |
paul@102 | 1447 | except (pytz.UnknownTimeZoneError, pytz.AmbiguousTimeError): |
paul@103 | 1448 | |
paul@103 | 1449 | # Try again, using an earlier local time and then stepping forward |
paul@103 | 1450 | # in the chosen zone. |
paul@103 | 1451 | # NOTE: Four hours earlier seems reasonable. |
paul@103 | 1452 | |
paul@103 | 1453 | return self._as_olson_datetime(-4) |
paul@102 | 1454 | |
paul@100 | 1455 | def ambiguous(self): |
paul@100 | 1456 | |
paul@100 | 1457 | "Return whether the time is local and ambiguous." |
paul@100 | 1458 | |
paul@102 | 1459 | try: |
paul@102 | 1460 | self._as_olson_datetime() |
paul@102 | 1461 | except (pytz.UnknownTimeZoneError, pytz.AmbiguousTimeError): |
paul@102 | 1462 | return 1 |
paul@100 | 1463 | |
paul@100 | 1464 | return 0 |
paul@100 | 1465 | |
paul@130 | 1466 | class Timespan(ActsAsTimespan): |
paul@122 | 1467 | |
paul@122 | 1468 | """ |
paul@122 | 1469 | A period of time which can be compared against others to check for overlaps. |
paul@122 | 1470 | """ |
paul@122 | 1471 | |
paul@122 | 1472 | def __init__(self, start, end): |
paul@122 | 1473 | self.start = start |
paul@122 | 1474 | self.end = end |
paul@122 | 1475 | |
paul@122 | 1476 | def __repr__(self): |
paul@122 | 1477 | return "%s(%r, %r)" % (self.__class__.__name__, self.start, self.end) |
paul@122 | 1478 | |
paul@122 | 1479 | def __hash__(self): |
paul@122 | 1480 | return hash((self.start, self.end)) |
paul@122 | 1481 | |
paul@130 | 1482 | def as_timespan(self): |
paul@130 | 1483 | return self |
paul@130 | 1484 | |
paul@128 | 1485 | def as_limits(self): |
paul@123 | 1486 | return self.start, self.end |
paul@123 | 1487 | |
paul@122 | 1488 | def is_before(self, a, b): |
paul@129 | 1489 | |
paul@129 | 1490 | """ |
paul@129 | 1491 | Return whether 'a' is before 'b'. Since the end datetime of one period |
paul@129 | 1492 | may be the same as the start datetime of another period, and yet the |
paul@129 | 1493 | first period is intended to be concluded by the end datetime and not |
paul@129 | 1494 | overlap with the other period, a different test is employed for datetime |
paul@129 | 1495 | comparisons. |
paul@129 | 1496 | """ |
paul@129 | 1497 | |
paul@128 | 1498 | if isinstance(a, DateTime) and a.has_time() and isinstance(b, DateTime) and b.has_time(): |
paul@122 | 1499 | return a <= b |
paul@122 | 1500 | else: |
paul@122 | 1501 | return a < b |
paul@122 | 1502 | |
paul@122 | 1503 | def __contains__(self, other): |
paul@129 | 1504 | |
paul@129 | 1505 | """ |
paul@129 | 1506 | This instance is considered to contain 'other' if one is not before or |
paul@129 | 1507 | after the other. If this instance overlaps or coincides with 'other', |
paul@129 | 1508 | then 'other' is regarded as belonging to this instance's time period. |
paul@129 | 1509 | """ |
paul@129 | 1510 | |
paul@123 | 1511 | return self == other |
paul@122 | 1512 | |
paul@122 | 1513 | def __cmp__(self, other): |
paul@122 | 1514 | |
paul@122 | 1515 | """ |
paul@122 | 1516 | Return whether this timespan occupies the same period of time as the |
paul@129 | 1517 | 'other'. Timespans are considered less than others if their end points |
paul@129 | 1518 | precede the other's start point, and are considered greater than others |
paul@129 | 1519 | if their start points follow the other's end point. |
paul@122 | 1520 | """ |
paul@122 | 1521 | |
paul@130 | 1522 | if isinstance(other, ActsAsTimespan): |
paul@130 | 1523 | other = other.as_timespan() |
paul@130 | 1524 | |
paul@123 | 1525 | if self.end is not None and other.start is not None and self.is_before(self.end, other.start): |
paul@122 | 1526 | return -1 |
paul@123 | 1527 | elif self.start is not None and other.end is not None and self.is_before(other.end, self.start): |
paul@122 | 1528 | return 1 |
paul@122 | 1529 | else: |
paul@122 | 1530 | return 0 |
paul@122 | 1531 | |
paul@122 | 1532 | # Points in time are not considered to represent an upper bound on a |
paul@122 | 1533 | # non-inclusive timespan. |
paul@122 | 1534 | |
paul@122 | 1535 | else: |
paul@123 | 1536 | if self.end is not None and self.is_before(self.end, other): |
paul@122 | 1537 | return -1 |
paul@123 | 1538 | elif self.start is not None and self.start > other: |
paul@122 | 1539 | return 1 |
paul@122 | 1540 | else: |
paul@122 | 1541 | return 0 |
paul@122 | 1542 | |
paul@123 | 1543 | class TimespanCollection: |
paul@123 | 1544 | |
paul@129 | 1545 | """ |
paul@130 | 1546 | A collection of timespans providing a list-like interface supporting |
paul@130 | 1547 | membership tests at a particular resolution. |
paul@129 | 1548 | """ |
paul@123 | 1549 | |
paul@123 | 1550 | def __init__(self, resolution, values=None): |
paul@123 | 1551 | |
paul@123 | 1552 | # Timespans need to be given converted start and end dates/times. |
paul@123 | 1553 | |
paul@123 | 1554 | if resolution == "date": |
paul@123 | 1555 | self.convert_time = lambda x: x.as_date() |
paul@130 | 1556 | elif resolution == "datetime": |
paul@130 | 1557 | self.convert_time = lambda x: x.as_datetime_or_date() |
paul@123 | 1558 | else: |
paul@123 | 1559 | self.convert_time = lambda x: x |
paul@123 | 1560 | |
paul@123 | 1561 | self.values = values or [] |
paul@123 | 1562 | |
paul@123 | 1563 | def convert(self, value): |
paul@130 | 1564 | if isinstance(value, ActsAsTimespan): |
paul@123 | 1565 | value = value.as_timespan() |
paul@128 | 1566 | start, end = map(self.convert_time, value.as_limits()) |
paul@123 | 1567 | return Timespan(start, end) |
paul@123 | 1568 | else: |
paul@123 | 1569 | return self.convert_time(value) |
paul@123 | 1570 | |
paul@123 | 1571 | def __iter__(self): |
paul@123 | 1572 | return iter(self.values) |
paul@123 | 1573 | |
paul@123 | 1574 | def __len__(self): |
paul@123 | 1575 | return len(self.values) |
paul@123 | 1576 | |
paul@123 | 1577 | def __getitem__(self, i): |
paul@123 | 1578 | return self.values[i] |
paul@123 | 1579 | |
paul@123 | 1580 | def __setitem__(self, i, value): |
paul@123 | 1581 | self.values[i] = value |
paul@123 | 1582 | |
paul@123 | 1583 | def __contains__(self, value): |
paul@123 | 1584 | test_value = self.convert(value) |
paul@123 | 1585 | return test_value in self.values |
paul@123 | 1586 | |
paul@123 | 1587 | def append(self, value): |
paul@123 | 1588 | self.values.append(value) |
paul@123 | 1589 | |
paul@123 | 1590 | def insert(self, i, value): |
paul@123 | 1591 | self.values.insert(i, value) |
paul@123 | 1592 | |
paul@123 | 1593 | def pop(self): |
paul@123 | 1594 | return self.values.pop() |
paul@123 | 1595 | |
paul@124 | 1596 | def insert_in_order(self, value): |
paul@124 | 1597 | bisect.insort_left(self, value) |
paul@124 | 1598 | |
paul@93 | 1599 | def getCountry(s): |
paul@92 | 1600 | |
paul@93 | 1601 | "Find a country code in the given string 's'." |
paul@93 | 1602 | |
paul@93 | 1603 | match = country_code_regexp.search(s) |
paul@92 | 1604 | |
paul@93 | 1605 | if match: |
paul@93 | 1606 | return match.group("code") |
paul@93 | 1607 | else: |
paul@93 | 1608 | return None |
paul@67 | 1609 | |
paul@67 | 1610 | def getDate(s): |
paul@127 | 1611 | |
paul@127 | 1612 | "Parse the string 's', extracting and returning a date object." |
paul@127 | 1613 | |
paul@127 | 1614 | dt = getDateTime(s) |
paul@127 | 1615 | if dt is not None: |
paul@127 | 1616 | return dt.as_date() |
paul@127 | 1617 | else: |
paul@127 | 1618 | return None |
paul@123 | 1619 | |
paul@123 | 1620 | def getDateTime(s): |
paul@67 | 1621 | |
paul@92 | 1622 | "Parse the string 's', extracting and returning a datetime object." |
paul@67 | 1623 | |
paul@92 | 1624 | m = datetime_regexp.search(s) |
paul@67 | 1625 | if m: |
paul@92 | 1626 | groups = list(m.groups()) |
paul@92 | 1627 | |
paul@94 | 1628 | # Convert date and time data to integer or None. |
paul@92 | 1629 | |
paul@94 | 1630 | return DateTime(map(int_or_none, groups[:6]) + [m.group("zone")]) |
paul@67 | 1631 | else: |
paul@67 | 1632 | return None |
paul@67 | 1633 | |
paul@88 | 1634 | def getDateStrings(s): |
paul@88 | 1635 | |
paul@88 | 1636 | "Parse the string 's', extracting and returning all date strings." |
paul@88 | 1637 | |
paul@88 | 1638 | start = 0 |
paul@88 | 1639 | m = date_regexp.search(s, start) |
paul@88 | 1640 | l = [] |
paul@88 | 1641 | while m: |
paul@88 | 1642 | l.append("-".join(m.groups())) |
paul@88 | 1643 | m = date_regexp.search(s, m.end()) |
paul@88 | 1644 | return l |
paul@88 | 1645 | |
paul@67 | 1646 | def getMonth(s): |
paul@67 | 1647 | |
paul@88 | 1648 | "Parse the string 's', extracting and returning a month object." |
paul@67 | 1649 | |
paul@67 | 1650 | m = month_regexp.search(s) |
paul@67 | 1651 | if m: |
paul@67 | 1652 | return Month(map(int, m.groups())) |
paul@67 | 1653 | else: |
paul@67 | 1654 | return None |
paul@67 | 1655 | |
paul@122 | 1656 | def getCurrentDate(): |
paul@122 | 1657 | |
paul@122 | 1658 | "Return the current date as a (year, month, day) tuple." |
paul@122 | 1659 | |
paul@122 | 1660 | today = datetime.date.today() |
paul@122 | 1661 | return Date((today.year, today.month, today.day)) |
paul@122 | 1662 | |
paul@67 | 1663 | def getCurrentMonth(): |
paul@67 | 1664 | |
paul@67 | 1665 | "Return the current month as a (year, month) tuple." |
paul@67 | 1666 | |
paul@67 | 1667 | today = datetime.date.today() |
paul@67 | 1668 | return Month((today.year, today.month)) |
paul@67 | 1669 | |
paul@67 | 1670 | def getCurrentYear(): |
paul@67 | 1671 | |
paul@67 | 1672 | "Return the current year." |
paul@67 | 1673 | |
paul@67 | 1674 | today = datetime.date.today() |
paul@67 | 1675 | return today.year |
paul@67 | 1676 | |
paul@19 | 1677 | # User interface functions. |
paul@19 | 1678 | |
paul@55 | 1679 | def getParameter(request, name, default=None): |
paul@92 | 1680 | |
paul@92 | 1681 | """ |
paul@92 | 1682 | Using the given 'request', return the value of the parameter with the given |
paul@92 | 1683 | 'name', returning the optional 'default' (or None) if no value was supplied |
paul@92 | 1684 | in the 'request'. |
paul@92 | 1685 | """ |
paul@92 | 1686 | |
paul@110 | 1687 | return get_form(request).get(name, [default])[0] |
paul@23 | 1688 | |
paul@58 | 1689 | def getQualifiedParameter(request, calendar_name, argname, default=None): |
paul@92 | 1690 | |
paul@92 | 1691 | """ |
paul@92 | 1692 | Using the given 'request', 'calendar_name' and 'argname', retrieve the |
paul@92 | 1693 | value of the qualified parameter, returning the optional 'default' (or None) |
paul@92 | 1694 | if no value was supplied in the 'request'. |
paul@92 | 1695 | """ |
paul@92 | 1696 | |
paul@58 | 1697 | argname = getQualifiedParameterName(calendar_name, argname) |
paul@58 | 1698 | return getParameter(request, argname, default) |
paul@58 | 1699 | |
paul@58 | 1700 | def getQualifiedParameterName(calendar_name, argname): |
paul@92 | 1701 | |
paul@92 | 1702 | """ |
paul@92 | 1703 | Return the qualified parameter name using the given 'calendar_name' and |
paul@92 | 1704 | 'argname'. |
paul@92 | 1705 | """ |
paul@92 | 1706 | |
paul@58 | 1707 | if calendar_name is None: |
paul@58 | 1708 | return argname |
paul@58 | 1709 | else: |
paul@58 | 1710 | return "%s-%s" % (calendar_name, argname) |
paul@58 | 1711 | |
paul@122 | 1712 | def getParameterDate(arg): |
paul@122 | 1713 | |
paul@122 | 1714 | "Interpret 'arg', recognising keywords and simple arithmetic operations." |
paul@122 | 1715 | |
paul@122 | 1716 | n = None |
paul@122 | 1717 | |
paul@128 | 1718 | if arg is None: |
paul@128 | 1719 | return None |
paul@128 | 1720 | |
paul@128 | 1721 | elif arg.startswith("current"): |
paul@122 | 1722 | date = getCurrentDate() |
paul@122 | 1723 | if len(arg) > 8: |
paul@122 | 1724 | n = int(arg[7:]) |
paul@122 | 1725 | |
paul@122 | 1726 | elif arg.startswith("yearstart"): |
paul@122 | 1727 | date = Date((getCurrentYear(), 1, 1)) |
paul@122 | 1728 | if len(arg) > 10: |
paul@122 | 1729 | n = int(arg[9:]) |
paul@122 | 1730 | |
paul@122 | 1731 | elif arg.startswith("yearend"): |
paul@122 | 1732 | date = Date((getCurrentYear(), 12, 31)) |
paul@122 | 1733 | if len(arg) > 8: |
paul@122 | 1734 | n = int(arg[7:]) |
paul@122 | 1735 | |
paul@122 | 1736 | else: |
paul@122 | 1737 | date = getDate(arg) |
paul@122 | 1738 | |
paul@122 | 1739 | if n is not None: |
paul@122 | 1740 | date = date.day_update(n) |
paul@122 | 1741 | |
paul@122 | 1742 | return date |
paul@122 | 1743 | |
paul@19 | 1744 | def getParameterMonth(arg): |
paul@67 | 1745 | |
paul@67 | 1746 | "Interpret 'arg', recognising keywords and simple arithmetic operations." |
paul@67 | 1747 | |
paul@19 | 1748 | n = None |
paul@19 | 1749 | |
paul@128 | 1750 | if arg is None: |
paul@128 | 1751 | return None |
paul@128 | 1752 | |
paul@128 | 1753 | elif arg.startswith("current"): |
paul@19 | 1754 | date = getCurrentMonth() |
paul@19 | 1755 | if len(arg) > 8: |
paul@19 | 1756 | n = int(arg[7:]) |
paul@19 | 1757 | |
paul@19 | 1758 | elif arg.startswith("yearstart"): |
paul@67 | 1759 | date = Month((getCurrentYear(), 1)) |
paul@19 | 1760 | if len(arg) > 10: |
paul@19 | 1761 | n = int(arg[9:]) |
paul@19 | 1762 | |
paul@19 | 1763 | elif arg.startswith("yearend"): |
paul@67 | 1764 | date = Month((getCurrentYear(), 12)) |
paul@19 | 1765 | if len(arg) > 8: |
paul@19 | 1766 | n = int(arg[7:]) |
paul@19 | 1767 | |
paul@19 | 1768 | else: |
paul@19 | 1769 | date = getMonth(arg) |
paul@19 | 1770 | |
paul@19 | 1771 | if n is not None: |
paul@67 | 1772 | date = date.month_update(n) |
paul@19 | 1773 | |
paul@19 | 1774 | return date |
paul@19 | 1775 | |
paul@122 | 1776 | def getFormDate(request, calendar_name, argname): |
paul@122 | 1777 | |
paul@122 | 1778 | """ |
paul@122 | 1779 | Return the date from the 'request' for the calendar with the given |
paul@122 | 1780 | 'calendar_name' using the parameter having the given 'argname'. |
paul@122 | 1781 | """ |
paul@122 | 1782 | |
paul@122 | 1783 | arg = getQualifiedParameter(request, calendar_name, argname) |
paul@128 | 1784 | return getParameterDate(arg) |
paul@122 | 1785 | |
paul@19 | 1786 | def getFormMonth(request, calendar_name, argname): |
paul@67 | 1787 | |
paul@67 | 1788 | """ |
paul@67 | 1789 | Return the month from the 'request' for the calendar with the given |
paul@67 | 1790 | 'calendar_name' using the parameter having the given 'argname'. |
paul@67 | 1791 | """ |
paul@67 | 1792 | |
paul@58 | 1793 | arg = getQualifiedParameter(request, calendar_name, argname) |
paul@128 | 1794 | return getParameterMonth(arg) |
paul@19 | 1795 | |
paul@127 | 1796 | def getFormDateTriple(request, yeararg, montharg, dayarg): |
paul@127 | 1797 | |
paul@127 | 1798 | """ |
paul@127 | 1799 | Return the date from the 'request' for the calendar with the given |
paul@127 | 1800 | 'calendar_name' using the parameters having the given 'yeararg', 'montharg' |
paul@127 | 1801 | and 'dayarg' names. |
paul@127 | 1802 | """ |
paul@127 | 1803 | |
paul@127 | 1804 | year = getParameter(request, yeararg) |
paul@127 | 1805 | month = getParameter(request, montharg) |
paul@127 | 1806 | day = getParameter(request, dayarg) |
paul@127 | 1807 | if year and month and day: |
paul@127 | 1808 | return Date((int(year), int(month), int(day))) |
paul@127 | 1809 | else: |
paul@127 | 1810 | return None |
paul@127 | 1811 | |
paul@23 | 1812 | def getFormMonthPair(request, yeararg, montharg): |
paul@67 | 1813 | |
paul@67 | 1814 | """ |
paul@67 | 1815 | Return the month from the 'request' for the calendar with the given |
paul@67 | 1816 | 'calendar_name' using the parameters having the given 'yeararg' and |
paul@67 | 1817 | 'montharg' names. |
paul@67 | 1818 | """ |
paul@67 | 1819 | |
paul@23 | 1820 | year = getParameter(request, yeararg) |
paul@23 | 1821 | month = getParameter(request, montharg) |
paul@23 | 1822 | if year and month: |
paul@67 | 1823 | return Month((int(year), int(month))) |
paul@23 | 1824 | else: |
paul@23 | 1825 | return None |
paul@23 | 1826 | |
paul@122 | 1827 | def getFullDateLabel(request, date): |
paul@122 | 1828 | |
paul@122 | 1829 | """ |
paul@122 | 1830 | Return the full month plus year label using the given 'request' and |
paul@122 | 1831 | 'year_month'. |
paul@122 | 1832 | """ |
paul@122 | 1833 | |
paul@128 | 1834 | if not date: |
paul@128 | 1835 | return "" |
paul@128 | 1836 | |
paul@122 | 1837 | _ = request.getText |
paul@122 | 1838 | year, month, day = date.as_tuple()[:3] |
paul@125 | 1839 | start_weekday, number_of_days = date.month_properties() |
paul@125 | 1840 | weekday = (start_weekday + day - 1) % 7 |
paul@125 | 1841 | day_label = _(getDayLabel(weekday)) |
paul@122 | 1842 | month_label = _(getMonthLabel(month)) |
paul@122 | 1843 | return "%s %s %s %s" % (day_label, day, month_label, year) |
paul@122 | 1844 | |
paul@114 | 1845 | def getFullMonthLabel(request, year_month): |
paul@114 | 1846 | |
paul@114 | 1847 | """ |
paul@114 | 1848 | Return the full month plus year label using the given 'request' and |
paul@114 | 1849 | 'year_month'. |
paul@114 | 1850 | """ |
paul@114 | 1851 | |
paul@128 | 1852 | if not year_month: |
paul@128 | 1853 | return "" |
paul@128 | 1854 | |
paul@114 | 1855 | _ = request.getText |
paul@122 | 1856 | year, month = year_month.as_tuple()[:2] |
paul@114 | 1857 | month_label = _(getMonthLabel(month)) |
paul@114 | 1858 | return "%s %s" % (month_label, year) |
paul@114 | 1859 | |
paul@67 | 1860 | # Page-related functions. |
paul@67 | 1861 | |
paul@19 | 1862 | def getPrettyPageName(page): |
paul@19 | 1863 | |
paul@19 | 1864 | "Return a nicely formatted title/name for the given 'page'." |
paul@19 | 1865 | |
paul@117 | 1866 | title = page.split_title(force=1) |
paul@55 | 1867 | return getPrettyTitle(title) |
paul@55 | 1868 | |
paul@27 | 1869 | def linkToPage(request, page, text, query_string=None): |
paul@27 | 1870 | |
paul@27 | 1871 | """ |
paul@27 | 1872 | Using 'request', return a link to 'page' with the given link 'text' and |
paul@27 | 1873 | optional 'query_string'. |
paul@27 | 1874 | """ |
paul@27 | 1875 | |
paul@27 | 1876 | text = wikiutil.escape(text) |
paul@117 | 1877 | return page.link_to_raw(request, text, query_string) |
paul@27 | 1878 | |
paul@88 | 1879 | def getFullPageName(parent, title): |
paul@88 | 1880 | |
paul@88 | 1881 | """ |
paul@88 | 1882 | Return a full page name from the given 'parent' page (can be empty or None) |
paul@88 | 1883 | and 'title' (a simple page name). |
paul@88 | 1884 | """ |
paul@88 | 1885 | |
paul@88 | 1886 | if parent: |
paul@88 | 1887 | return "%s/%s" % (parent.rstrip("/"), title) |
paul@88 | 1888 | else: |
paul@88 | 1889 | return title |
paul@88 | 1890 | |
paul@88 | 1891 | def fillEventPageFromTemplate(template_page, new_page, event_details, category_pagenames): |
paul@88 | 1892 | |
paul@88 | 1893 | """ |
paul@88 | 1894 | Using the given 'template_page', complete the 'new_page' by copying the |
paul@88 | 1895 | template and adding the given 'event_details' (a dictionary of event |
paul@88 | 1896 | fields), setting also the 'category_pagenames' to define category |
paul@88 | 1897 | membership. |
paul@88 | 1898 | """ |
paul@88 | 1899 | |
paul@88 | 1900 | event_page = EventPage(template_page) |
paul@88 | 1901 | new_event_page = EventPage(new_page) |
paul@88 | 1902 | new_event_page.copyPage(event_page) |
paul@88 | 1903 | |
paul@88 | 1904 | if new_event_page.getFormat() == "wiki": |
paul@88 | 1905 | new_event = Event(new_event_page, event_details) |
paul@88 | 1906 | new_event_page.setEvents([new_event]) |
paul@88 | 1907 | new_event_page.setCategoryMembership(category_pagenames) |
paul@88 | 1908 | new_event_page.saveChanges() |
paul@88 | 1909 | |
paul@10 | 1910 | # vim: tabstop=4 expandtab shiftwidth=4 |