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