paul@10 | 1 | # -*- coding: iso-8859-1 -*- |
paul@10 | 2 | """ |
paul@10 | 3 | MoinMoin - EventAggregator library |
paul@10 | 4 | |
paul@137 | 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@225 | 12 | from MoinMoin.action import cache |
paul@225 | 13 | from MoinMoin import caching |
paul@10 | 14 | from MoinMoin import search, version |
paul@24 | 15 | from MoinMoin import wikiutil |
paul@10 | 16 | import calendar |
paul@217 | 17 | import codecs |
paul@11 | 18 | import datetime |
paul@24 | 19 | import time |
paul@10 | 20 | import re |
paul@122 | 21 | import bisect |
paul@185 | 22 | import operator |
paul@217 | 23 | import urllib |
paul@10 | 24 | |
paul@69 | 25 | try: |
paul@225 | 26 | from cStringIO import StringIO |
paul@225 | 27 | except ImportError: |
paul@225 | 28 | from StringIO import StringIO |
paul@10 | 29 | |
paul@69 | 30 | try: |
paul@69 | 31 | set |
paul@69 | 32 | except NameError: |
paul@69 | 33 | from sets import Set as set |
paul@69 | 34 | |
paul@100 | 35 | try: |
paul@100 | 36 | import pytz |
paul@100 | 37 | except ImportError: |
paul@100 | 38 | pytz = None |
paul@100 | 39 | |
paul@217 | 40 | try: |
paul@217 | 41 | import vCalendar |
paul@217 | 42 | except ImportError: |
paul@217 | 43 | vCalendar = None |
paul@217 | 44 | |
paul@137 | 45 | escape = wikiutil.escape |
paul@137 | 46 | |
paul@234 | 47 | __version__ = "0.7.1" |
paul@10 | 48 | |
paul@22 | 49 | # Date labels. |
paul@22 | 50 | |
paul@22 | 51 | month_labels = ["January", "February", "March", "April", "May", "June", |
paul@22 | 52 | "July", "August", "September", "October", "November", "December"] |
paul@22 | 53 | weekday_labels = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] |
paul@22 | 54 | |
paul@10 | 55 | # Regular expressions where MoinMoin does not provide the required support. |
paul@10 | 56 | |
paul@10 | 57 | category_regexp = None |
paul@47 | 58 | |
paul@47 | 59 | # Page parsing. |
paul@47 | 60 | |
paul@84 | 61 | definition_list_regexp = re.compile(ur'(?P<wholeterm>^(?P<optcomment>#*)\s+(?P<term>.*?):: )(?P<desc>.*?)$', re.UNICODE | re.MULTILINE) |
paul@158 | 62 | category_membership_regexp = re.compile(ur"^\s*(?:(Category\S+)(?:\s+(Category\S+))*)\s*$", re.MULTILINE | re.UNICODE) |
paul@47 | 63 | |
paul@47 | 64 | # Value parsing. |
paul@47 | 65 | |
paul@93 | 66 | country_code_regexp = re.compile(ur'(?:^|\W)(?P<code>[A-Z]{2})(?:$|\W+$)', re.UNICODE) |
paul@202 | 67 | location_normalised_regexp = re.compile( |
paul@202 | 68 | ur"(?:\d+\w*\s+)?" # preceding postcode (optional) |
paul@202 | 69 | ur"(?P<location>" # start of group of interest |
paul@202 | 70 | ur"\w[\w\s-]+?" # area or town |
paul@202 | 71 | ur"(?:,(?:\s*[\w-]+)+)?" # country (optional) |
paul@202 | 72 | ur")$", re.UNICODE) |
paul@92 | 73 | |
paul@217 | 74 | # Month, date, time and datetime parsing. |
paul@217 | 75 | |
paul@92 | 76 | month_regexp_str = ur'(?P<year>[0-9]{4})-(?P<month>[0-9]{2})' |
paul@92 | 77 | date_regexp_str = ur'(?P<year>[0-9]{4})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})' |
paul@92 | 78 | time_regexp_str = ur'(?P<hour>[0-2][0-9]):(?P<minute>[0-5][0-9])(?::(?P<second>[0-6][0-9]))?' |
paul@98 | 79 | timezone_offset_str = ur'(?P<offset>(UTC)?(?:(?P<sign>[-+])(?P<hours>[0-9]{2})(?::?(?P<minutes>[0-9]{2}))?))' |
paul@98 | 80 | timezone_olson_str = ur'(?P<olson>[a-zA-Z]+(?:/[-_a-zA-Z]+){1,2})' |
paul@98 | 81 | timezone_utc_str = ur'UTC' |
paul@98 | 82 | timezone_regexp_str = ur'(?P<zone>' + timezone_offset_str + '|' + timezone_olson_str + '|' + timezone_utc_str + ')' |
paul@92 | 83 | datetime_regexp_str = date_regexp_str + ur'(?:\s+' + time_regexp_str + ur'(?:\s+' + timezone_regexp_str + ur')?)?' |
paul@92 | 84 | |
paul@92 | 85 | month_regexp = re.compile(month_regexp_str, re.UNICODE) |
paul@92 | 86 | date_regexp = re.compile(date_regexp_str, re.UNICODE) |
paul@92 | 87 | time_regexp = re.compile(time_regexp_str, re.UNICODE) |
paul@100 | 88 | timezone_olson_regexp = re.compile(timezone_olson_str, re.UNICODE) |
paul@94 | 89 | timezone_offset_regexp = re.compile(timezone_offset_str, re.UNICODE) |
paul@217 | 90 | datetime_regexp = re.compile(datetime_regexp_str, re.UNICODE) |
paul@217 | 91 | |
paul@217 | 92 | # iCalendar date and datetime parsing. |
paul@217 | 93 | |
paul@217 | 94 | date_icalendar_regexp_str = ur'(?P<year>[0-9]{4})(?P<month>[0-9]{2})(?P<day>[0-9]{2})' |
paul@217 | 95 | datetime_icalendar_regexp_str = date_icalendar_regexp_str + \ |
paul@217 | 96 | ur'(?:' \ |
paul@217 | 97 | ur'T(?P<hour>[0-2][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-6][0-9])' \ |
paul@217 | 98 | ur'(?P<utc>Z)?' \ |
paul@217 | 99 | ur')?' |
paul@217 | 100 | |
paul@217 | 101 | date_icalendar_regexp = re.compile(date_icalendar_regexp_str, re.UNICODE) |
paul@217 | 102 | datetime_icalendar_regexp = re.compile(datetime_icalendar_regexp_str, re.UNICODE) |
paul@217 | 103 | |
paul@219 | 104 | # Content type parsing. |
paul@219 | 105 | |
paul@219 | 106 | encoding_regexp_str = ur'charset=(?P<encoding>[-A-Za-z0-9]+)' |
paul@219 | 107 | encoding_regexp = re.compile(encoding_regexp_str) |
paul@219 | 108 | |
paul@217 | 109 | # Simple content parsing. |
paul@92 | 110 | |
paul@19 | 111 | verbatim_regexp = re.compile(ur'(?:' |
paul@19 | 112 | ur'<<Verbatim\((?P<verbatim>.*?)\)>>' |
paul@19 | 113 | ur'|' |
paul@19 | 114 | ur'\[\[Verbatim\((?P<verbatim2>.*?)\)\]\]' |
paul@19 | 115 | ur'|' |
paul@191 | 116 | ur'!(?P<verbatim3>.*?)(\s|$)?' |
paul@191 | 117 | ur'|' |
paul@19 | 118 | ur'`(?P<monospace>.*?)`' |
paul@19 | 119 | ur'|' |
paul@19 | 120 | ur'{{{(?P<preformatted>.*?)}}}' |
paul@19 | 121 | ur')', re.UNICODE) |
paul@10 | 122 | |
paul@10 | 123 | # Utility functions. |
paul@10 | 124 | |
paul@10 | 125 | def getCategoryPattern(request): |
paul@10 | 126 | global category_regexp |
paul@10 | 127 | |
paul@10 | 128 | try: |
paul@10 | 129 | return request.cfg.cache.page_category_regexact |
paul@10 | 130 | except AttributeError: |
paul@10 | 131 | |
paul@10 | 132 | # Use regular expression from MoinMoin 1.7.1 otherwise. |
paul@10 | 133 | |
paul@10 | 134 | if category_regexp is None: |
paul@10 | 135 | category_regexp = re.compile(u'^%s$' % ur'(?P<all>Category(?P<key>(?!Template)\S+))', re.UNICODE) |
paul@10 | 136 | return category_regexp |
paul@10 | 137 | |
paul@233 | 138 | def getWikiDict(pagename, request): |
paul@233 | 139 | if Page(request, pagename).exists() and request.user.may.read(pagename): |
paul@233 | 140 | if hasattr(request.dicts, "dict"): |
paul@233 | 141 | return request.dicts.dict(pagename) |
paul@233 | 142 | else: |
paul@233 | 143 | return request.dicts[pagename] |
paul@233 | 144 | else: |
paul@233 | 145 | return None |
paul@233 | 146 | |
paul@219 | 147 | def getContentEncoding(content_type): |
paul@219 | 148 | m = encoding_regexp.search(content_type) |
paul@219 | 149 | if m: |
paul@219 | 150 | return m.group("encoding") |
paul@219 | 151 | else: |
paul@219 | 152 | return None |
paul@219 | 153 | |
paul@92 | 154 | def int_or_none(x): |
paul@92 | 155 | if x is None: |
paul@92 | 156 | return x |
paul@92 | 157 | else: |
paul@92 | 158 | return int(x) |
paul@92 | 159 | |
paul@229 | 160 | def to_list(s, sep): |
paul@229 | 161 | return [x.strip() for x in s.split(sep) if x.strip()] |
paul@229 | 162 | |
paul@118 | 163 | def sort_none_first(x, y): |
paul@118 | 164 | if x is None: |
paul@118 | 165 | return -1 |
paul@118 | 166 | elif y is None: |
paul@118 | 167 | return 1 |
paul@118 | 168 | else: |
paul@118 | 169 | return cmp(x, y) |
paul@118 | 170 | |
paul@195 | 171 | def sort_start_first(x, y): |
paul@195 | 172 | x_ts = x.as_limits() |
paul@195 | 173 | if x_ts is not None: |
paul@195 | 174 | x_start, x_end = x_ts |
paul@195 | 175 | y_ts = y.as_limits() |
paul@195 | 176 | if y_ts is not None: |
paul@195 | 177 | y_start, y_end = y_ts |
paul@195 | 178 | start_order = cmp(x_start, y_start) |
paul@195 | 179 | if start_order == 0: |
paul@195 | 180 | return cmp(x_end, y_end) |
paul@195 | 181 | else: |
paul@195 | 182 | return start_order |
paul@195 | 183 | return 0 |
paul@195 | 184 | |
paul@184 | 185 | def sign(x): |
paul@184 | 186 | if x < 0: |
paul@184 | 187 | return -1 |
paul@184 | 188 | else: |
paul@184 | 189 | return 1 |
paul@184 | 190 | |
paul@109 | 191 | # Utility classes and associated functions. |
paul@109 | 192 | |
paul@109 | 193 | class Form: |
paul@109 | 194 | |
paul@109 | 195 | """ |
paul@109 | 196 | A wrapper preserving MoinMoin 1.8.x (and earlier) behaviour in a 1.9.x |
paul@109 | 197 | environment. |
paul@109 | 198 | """ |
paul@109 | 199 | |
paul@109 | 200 | def __init__(self, form): |
paul@109 | 201 | self.form = form |
paul@109 | 202 | |
paul@110 | 203 | def get(self, name, default=None): |
paul@109 | 204 | values = self.form.getlist(name) |
paul@109 | 205 | if not values: |
paul@110 | 206 | return default |
paul@109 | 207 | else: |
paul@109 | 208 | return values |
paul@109 | 209 | |
paul@109 | 210 | def __getitem__(self, name): |
paul@109 | 211 | return self.form.getlist(name) |
paul@109 | 212 | |
paul@109 | 213 | class ActionSupport: |
paul@109 | 214 | |
paul@112 | 215 | """ |
paul@112 | 216 | Work around disruptive MoinMoin changes in 1.9, and also provide useful |
paul@112 | 217 | convenience methods. |
paul@112 | 218 | """ |
paul@109 | 219 | |
paul@109 | 220 | def get_form(self): |
paul@109 | 221 | return get_form(self.request) |
paul@109 | 222 | |
paul@112 | 223 | def _get_selected(self, value, input_value): |
paul@112 | 224 | |
paul@112 | 225 | """ |
paul@112 | 226 | Return the HTML attribute text indicating selection of an option (or |
paul@112 | 227 | otherwise) if 'value' matches 'input_value'. |
paul@112 | 228 | """ |
paul@112 | 229 | |
paul@112 | 230 | return input_value is not None and value == input_value and 'selected="selected"' or '' |
paul@112 | 231 | |
paul@112 | 232 | def _get_selected_for_list(self, value, input_values): |
paul@112 | 233 | |
paul@112 | 234 | """ |
paul@112 | 235 | Return the HTML attribute text indicating selection of an option (or |
paul@112 | 236 | otherwise) if 'value' matches one of the 'input_values'. |
paul@112 | 237 | """ |
paul@112 | 238 | |
paul@112 | 239 | return value in input_values and 'selected="selected"' or '' |
paul@112 | 240 | |
paul@112 | 241 | def _get_input(self, form, name, default=None): |
paul@112 | 242 | |
paul@112 | 243 | """ |
paul@112 | 244 | Return the input from 'form' having the given 'name', returning either |
paul@112 | 245 | the input converted to an integer or the given 'default' (optional, None |
paul@112 | 246 | if not specified). |
paul@112 | 247 | """ |
paul@112 | 248 | |
paul@112 | 249 | value = form.get(name, [None])[0] |
paul@112 | 250 | if not value: # true if 0 obtained |
paul@112 | 251 | return default |
paul@112 | 252 | else: |
paul@112 | 253 | return int(value) |
paul@112 | 254 | |
paul@114 | 255 | def get_month_lists(self, default_as_current=0): |
paul@112 | 256 | |
paul@112 | 257 | """ |
paul@112 | 258 | Return two lists of HTML element definitions corresponding to the start |
paul@112 | 259 | and end month selection controls, with months selected according to any |
paul@112 | 260 | values that have been specified via request parameters. |
paul@112 | 261 | """ |
paul@112 | 262 | |
paul@112 | 263 | _ = self._ |
paul@112 | 264 | form = self.get_form() |
paul@112 | 265 | |
paul@112 | 266 | # Initialise month lists. |
paul@112 | 267 | |
paul@112 | 268 | start_month_list = [] |
paul@112 | 269 | end_month_list = [] |
paul@112 | 270 | |
paul@114 | 271 | start_month = self._get_input(form, "start-month", default_as_current and getCurrentMonth().month() or None) |
paul@112 | 272 | end_month = self._get_input(form, "end-month", start_month) |
paul@112 | 273 | |
paul@112 | 274 | # Prepare month lists, selecting specified months. |
paul@112 | 275 | |
paul@114 | 276 | if not default_as_current: |
paul@114 | 277 | start_month_list.append('<option value=""></option>') |
paul@114 | 278 | end_month_list.append('<option value=""></option>') |
paul@114 | 279 | |
paul@112 | 280 | for month in range(1, 13): |
paul@136 | 281 | month_label = escape(_(getMonthLabel(month))) |
paul@112 | 282 | selected = self._get_selected(month, start_month) |
paul@112 | 283 | start_month_list.append('<option value="%02d" %s>%s</option>' % (month, selected, month_label)) |
paul@112 | 284 | selected = self._get_selected(month, end_month) |
paul@112 | 285 | end_month_list.append('<option value="%02d" %s>%s</option>' % (month, selected, month_label)) |
paul@112 | 286 | |
paul@112 | 287 | return start_month_list, end_month_list |
paul@112 | 288 | |
paul@114 | 289 | def get_year_defaults(self, default_as_current=0): |
paul@112 | 290 | |
paul@112 | 291 | "Return defaults for the start and end years." |
paul@112 | 292 | |
paul@112 | 293 | form = self.get_form() |
paul@112 | 294 | |
paul@114 | 295 | start_year_default = form.get("start-year", [default_as_current and getCurrentYear() or ""])[0] |
paul@114 | 296 | end_year_default = form.get("end-year", [default_as_current and start_year_default or ""])[0] |
paul@112 | 297 | |
paul@112 | 298 | return start_year_default, end_year_default |
paul@112 | 299 | |
paul@127 | 300 | def get_day_defaults(self, default_as_current=0): |
paul@127 | 301 | |
paul@127 | 302 | "Return defaults for the start and end days." |
paul@127 | 303 | |
paul@127 | 304 | form = self.get_form() |
paul@127 | 305 | |
paul@127 | 306 | start_day_default = form.get("start-day", [default_as_current and getCurrentDate().day() or ""])[0] |
paul@127 | 307 | end_day_default = form.get("end-day", [default_as_current and start_day_default or ""])[0] |
paul@127 | 308 | |
paul@127 | 309 | return start_day_default, end_day_default |
paul@127 | 310 | |
paul@109 | 311 | def get_form(request): |
paul@109 | 312 | |
paul@109 | 313 | "Work around disruptive MoinMoin changes in 1.9." |
paul@109 | 314 | |
paul@109 | 315 | if hasattr(request, "values"): |
paul@109 | 316 | return Form(request.values) |
paul@109 | 317 | else: |
paul@109 | 318 | return request.form |
paul@109 | 319 | |
paul@180 | 320 | class send_headers_cls: |
paul@110 | 321 | |
paul@110 | 322 | """ |
paul@110 | 323 | A wrapper to preserve MoinMoin 1.8.x (and earlier) request behaviour in a |
paul@110 | 324 | 1.9.x environment. |
paul@110 | 325 | """ |
paul@110 | 326 | |
paul@110 | 327 | def __init__(self, request): |
paul@110 | 328 | self.request = request |
paul@110 | 329 | |
paul@110 | 330 | def __call__(self, headers): |
paul@110 | 331 | for header in headers: |
paul@110 | 332 | parts = header.split(":") |
paul@110 | 333 | self.request.headers.add(parts[0], ":".join(parts[1:])) |
paul@110 | 334 | |
paul@238 | 335 | def get_send_headers(request): |
paul@238 | 336 | |
paul@238 | 337 | "Return a function that can send response headers." |
paul@238 | 338 | |
paul@238 | 339 | if hasattr(request, "http_headers"): |
paul@238 | 340 | return request.http_headers |
paul@238 | 341 | elif hasattr(request, "emit_http_headers"): |
paul@238 | 342 | return request.emit_http_headers |
paul@238 | 343 | else: |
paul@238 | 344 | return send_headers_cls(request) |
paul@238 | 345 | |
paul@136 | 346 | def escattr(s): |
paul@136 | 347 | return escape(s, 1) |
paul@136 | 348 | |
paul@67 | 349 | # Textual representations. |
paul@67 | 350 | |
paul@67 | 351 | def getSimpleWikiText(text): |
paul@67 | 352 | |
paul@67 | 353 | """ |
paul@67 | 354 | Return the plain text representation of the given 'text' which may employ |
paul@67 | 355 | certain Wiki syntax features, such as those providing verbatim or monospaced |
paul@67 | 356 | text. |
paul@67 | 357 | """ |
paul@67 | 358 | |
paul@67 | 359 | # NOTE: Re-implementing support for verbatim text and linking avoidance. |
paul@67 | 360 | |
paul@67 | 361 | return "".join([s for s in verbatim_regexp.split(text) if s is not None]) |
paul@67 | 362 | |
paul@67 | 363 | def getEncodedWikiText(text): |
paul@67 | 364 | |
paul@67 | 365 | "Encode the given 'text' in a verbatim representation." |
paul@67 | 366 | |
paul@67 | 367 | return "<<Verbatim(%s)>>" % text |
paul@67 | 368 | |
paul@67 | 369 | def getPrettyTitle(title): |
paul@67 | 370 | |
paul@67 | 371 | "Return a nicely formatted version of the given 'title'." |
paul@67 | 372 | |
paul@67 | 373 | return title.replace("_", " ").replace("/", u" ? ") |
paul@67 | 374 | |
paul@67 | 375 | def getMonthLabel(month): |
paul@67 | 376 | |
paul@67 | 377 | "Return an unlocalised label for the given 'month'." |
paul@67 | 378 | |
paul@67 | 379 | return month_labels[month - 1] # zero-based labels |
paul@67 | 380 | |
paul@67 | 381 | def getDayLabel(weekday): |
paul@67 | 382 | |
paul@67 | 383 | "Return an unlocalised label for the given 'weekday'." |
paul@67 | 384 | |
paul@67 | 385 | return weekday_labels[weekday] |
paul@67 | 386 | |
paul@189 | 387 | def getNormalisedLocation(location): |
paul@189 | 388 | |
paul@189 | 389 | """ |
paul@189 | 390 | Attempt to return a normalised 'location' of the form "<town>, <country>" or |
paul@189 | 391 | "<town>". |
paul@189 | 392 | """ |
paul@189 | 393 | |
paul@189 | 394 | match = location_normalised_regexp.search(location) |
paul@189 | 395 | if match: |
paul@202 | 396 | return match.group("location") |
paul@189 | 397 | else: |
paul@189 | 398 | return None |
paul@189 | 399 | |
paul@201 | 400 | def getLocationPosition(location, locations): |
paul@201 | 401 | |
paul@201 | 402 | """ |
paul@201 | 403 | Attempt to return the position of the given 'location' using the 'locations' |
paul@201 | 404 | dictionary provided. If no position can be found, return a latitude of None |
paul@201 | 405 | and a longitude of None. |
paul@201 | 406 | """ |
paul@201 | 407 | |
paul@201 | 408 | latitude, longitude = None, None |
paul@201 | 409 | |
paul@201 | 410 | if location is not None: |
paul@201 | 411 | try: |
paul@201 | 412 | latitude, longitude = map(getMapReference, locations[location].split()) |
paul@201 | 413 | except (KeyError, ValueError): |
paul@201 | 414 | pass |
paul@201 | 415 | |
paul@201 | 416 | return latitude, longitude |
paul@201 | 417 | |
paul@19 | 418 | # Action support functions. |
paul@19 | 419 | |
paul@67 | 420 | def getPageRevision(page): |
paul@67 | 421 | |
paul@67 | 422 | "Return the revision details dictionary for the given 'page'." |
paul@67 | 423 | |
paul@67 | 424 | # From Page.edit_info... |
paul@67 | 425 | |
paul@67 | 426 | if hasattr(page, "editlog_entry"): |
paul@67 | 427 | line = page.editlog_entry() |
paul@67 | 428 | else: |
paul@67 | 429 | line = page._last_edited(page.request) # MoinMoin 1.5.x and 1.6.x |
paul@67 | 430 | |
paul@89 | 431 | # Similar to Page.mtime_usecs behaviour... |
paul@89 | 432 | |
paul@89 | 433 | if line: |
paul@89 | 434 | timestamp = line.ed_time_usecs |
paul@89 | 435 | mtime = wikiutil.version2timestamp(long(timestamp)) # must be long for py 2.2.x |
paul@89 | 436 | comment = line.comment |
paul@89 | 437 | else: |
paul@89 | 438 | mtime = 0 |
paul@89 | 439 | comment = "" |
paul@89 | 440 | |
paul@219 | 441 | # Leave the time zone empty. |
paul@219 | 442 | |
paul@219 | 443 | return {"timestamp" : DateTime(time.gmtime(mtime)[:6] + (None,)), "comment" : comment} |
paul@67 | 444 | |
paul@67 | 445 | # Category discovery and searching. |
paul@67 | 446 | |
paul@19 | 447 | def getCategories(request): |
paul@19 | 448 | |
paul@19 | 449 | """ |
paul@19 | 450 | From the AdvancedSearch macro, return a list of category page names using |
paul@19 | 451 | the given 'request'. |
paul@19 | 452 | """ |
paul@19 | 453 | |
paul@19 | 454 | # This will return all pages with "Category" in the title. |
paul@19 | 455 | |
paul@19 | 456 | cat_filter = getCategoryPattern(request).search |
paul@19 | 457 | return request.rootpage.getPageList(filter=cat_filter) |
paul@19 | 458 | |
paul@19 | 459 | def getCategoryMapping(category_pagenames, request): |
paul@19 | 460 | |
paul@19 | 461 | """ |
paul@19 | 462 | For the given 'category_pagenames' return a list of tuples of the form |
paul@19 | 463 | (category name, category page name) using the given 'request'. |
paul@19 | 464 | """ |
paul@19 | 465 | |
paul@19 | 466 | cat_pattern = getCategoryPattern(request) |
paul@19 | 467 | mapping = [] |
paul@19 | 468 | for pagename in category_pagenames: |
paul@19 | 469 | name = cat_pattern.match(pagename).group("key") |
paul@19 | 470 | if name != "Category": |
paul@19 | 471 | mapping.append((name, pagename)) |
paul@19 | 472 | mapping.sort() |
paul@19 | 473 | return mapping |
paul@19 | 474 | |
paul@67 | 475 | def getCategoryPages(pagename, request): |
paul@29 | 476 | |
paul@67 | 477 | """ |
paul@67 | 478 | Return the pages associated with the given category 'pagename' using the |
paul@67 | 479 | 'request'. |
paul@67 | 480 | """ |
paul@10 | 481 | |
paul@10 | 482 | query = search.QueryParser().parse_query('category:%s' % pagename) |
paul@117 | 483 | results = search.searchPages(request, query, "page_name") |
paul@10 | 484 | |
paul@10 | 485 | cat_pattern = getCategoryPattern(request) |
paul@10 | 486 | pages = [] |
paul@10 | 487 | for page in results.hits: |
paul@10 | 488 | if not cat_pattern.match(page.page_name): |
paul@10 | 489 | pages.append(page) |
paul@10 | 490 | return pages |
paul@10 | 491 | |
paul@168 | 492 | def getAllCategoryPages(category_names, request): |
paul@168 | 493 | |
paul@168 | 494 | """ |
paul@168 | 495 | Return all pages belonging to the categories having the given |
paul@168 | 496 | 'category_names', using the given 'request'. |
paul@168 | 497 | """ |
paul@168 | 498 | |
paul@168 | 499 | pages = [] |
paul@168 | 500 | pagenames = set() |
paul@168 | 501 | |
paul@168 | 502 | for category_name in category_names: |
paul@168 | 503 | |
paul@168 | 504 | # Get the pages and page names in the category. |
paul@168 | 505 | |
paul@168 | 506 | pages_in_category = getCategoryPages(category_name, request) |
paul@168 | 507 | |
paul@168 | 508 | # Visit each page in the category. |
paul@168 | 509 | |
paul@168 | 510 | for page_in_category in pages_in_category: |
paul@168 | 511 | pagename = page_in_category.page_name |
paul@168 | 512 | |
paul@168 | 513 | # Only process each page once. |
paul@168 | 514 | |
paul@168 | 515 | if pagename in pagenames: |
paul@168 | 516 | continue |
paul@168 | 517 | else: |
paul@168 | 518 | pagenames.add(pagename) |
paul@168 | 519 | |
paul@168 | 520 | pages.append(page_in_category) |
paul@168 | 521 | |
paul@168 | 522 | return pages |
paul@168 | 523 | |
paul@168 | 524 | def getPagesFromResults(result_pages, request): |
paul@168 | 525 | |
paul@168 | 526 | "Return genuine pages for the given 'result_pages' using the 'request'." |
paul@168 | 527 | |
paul@168 | 528 | return [Page(request, page.page_name) for page in result_pages] |
paul@168 | 529 | |
paul@168 | 530 | # Interfaces. |
paul@168 | 531 | |
paul@168 | 532 | class ActsAsTimespan: |
paul@168 | 533 | pass |
paul@168 | 534 | |
paul@217 | 535 | # Event resources providing collections of events. |
paul@217 | 536 | |
paul@217 | 537 | class EventResource: |
paul@217 | 538 | |
paul@217 | 539 | "A resource providing event information." |
paul@217 | 540 | |
paul@217 | 541 | def __init__(self, url): |
paul@217 | 542 | self.url = url |
paul@217 | 543 | |
paul@223 | 544 | def getPageURL(self): |
paul@223 | 545 | |
paul@223 | 546 | "Return the URL of this page." |
paul@217 | 547 | |
paul@217 | 548 | return self.url |
paul@217 | 549 | |
paul@217 | 550 | def getFormat(self): |
paul@217 | 551 | |
paul@219 | 552 | "Get the format used by this resource." |
paul@217 | 553 | |
paul@217 | 554 | return "plain" |
paul@217 | 555 | |
paul@219 | 556 | def getMetadata(self): |
paul@219 | 557 | |
paul@219 | 558 | """ |
paul@219 | 559 | Return a dictionary containing items describing the page's "created" |
paul@219 | 560 | time, "last-modified" time, "sequence" (or revision number) and the |
paul@219 | 561 | "last-comment" made about the last edit. |
paul@219 | 562 | """ |
paul@219 | 563 | |
paul@219 | 564 | return {} |
paul@219 | 565 | |
paul@217 | 566 | def getEvents(self): |
paul@217 | 567 | |
paul@217 | 568 | "Return a list of events from this resource." |
paul@217 | 569 | |
paul@217 | 570 | return [] |
paul@217 | 571 | |
paul@217 | 572 | def linkToPage(self, request, text, query_string=None): |
paul@217 | 573 | |
paul@217 | 574 | """ |
paul@217 | 575 | Using 'request', return a link to this page with the given link 'text' |
paul@217 | 576 | and optional 'query_string'. |
paul@217 | 577 | """ |
paul@217 | 578 | |
paul@219 | 579 | return linkToResource(self.url, request, text, query_string) |
paul@217 | 580 | |
paul@217 | 581 | # Formatting-related functions. |
paul@217 | 582 | |
paul@217 | 583 | def formatText(self, text, request, fmt): |
paul@217 | 584 | |
paul@217 | 585 | """ |
paul@217 | 586 | Format the given 'text' using the specified 'request' and formatter |
paul@217 | 587 | 'fmt'. |
paul@217 | 588 | """ |
paul@217 | 589 | |
paul@217 | 590 | # Assume plain text which is then formatted appropriately. |
paul@217 | 591 | |
paul@217 | 592 | return fmt.text(text) |
paul@217 | 593 | |
paul@217 | 594 | class EventCalendar(EventResource): |
paul@217 | 595 | |
paul@217 | 596 | "An iCalendar resource." |
paul@217 | 597 | |
paul@217 | 598 | def __init__(self, url, calendar): |
paul@217 | 599 | EventResource.__init__(self, url) |
paul@217 | 600 | self.calendar = calendar |
paul@217 | 601 | self.events = None |
paul@217 | 602 | |
paul@217 | 603 | def getEvents(self): |
paul@217 | 604 | |
paul@217 | 605 | "Return a list of events from this resource." |
paul@217 | 606 | |
paul@217 | 607 | if self.events is None: |
paul@217 | 608 | self.events = [] |
paul@217 | 609 | |
paul@217 | 610 | _calendar, _empty, calendar = self.calendar |
paul@217 | 611 | |
paul@217 | 612 | for objtype, attrs, obj in calendar: |
paul@217 | 613 | |
paul@217 | 614 | # Read events. |
paul@217 | 615 | |
paul@217 | 616 | if objtype == "VEVENT": |
paul@217 | 617 | details = {} |
paul@217 | 618 | |
paul@217 | 619 | for property, attrs, value in obj: |
paul@217 | 620 | |
paul@217 | 621 | # Convert dates. |
paul@217 | 622 | |
paul@219 | 623 | if property in ("DTSTART", "DTEND", "CREATED", "DTSTAMP", "LAST-MODIFIED"): |
paul@219 | 624 | if property in ("DTSTART", "DTEND"): |
paul@219 | 625 | property = property[2:] |
paul@217 | 626 | if attrs.get("VALUE") == "DATE": |
paul@217 | 627 | value = getDateFromCalendar(value) |
paul@217 | 628 | else: |
paul@217 | 629 | value = getDateTimeFromCalendar(value) |
paul@217 | 630 | |
paul@219 | 631 | # Convert numeric data. |
paul@219 | 632 | |
paul@219 | 633 | elif property == "SEQUENCE": |
paul@219 | 634 | value = int(value) |
paul@219 | 635 | |
paul@219 | 636 | # Convert lists. |
paul@219 | 637 | |
paul@219 | 638 | elif property == "CATEGORIES": |
paul@229 | 639 | value = to_list(value, ",") |
paul@229 | 640 | |
paul@229 | 641 | # Convert positions (using decimal values). |
paul@229 | 642 | |
paul@229 | 643 | elif property == "GEO": |
paul@237 | 644 | try: |
paul@237 | 645 | value = map(getMapReferenceFromDecimal, to_list(value, ";")) |
paul@237 | 646 | except (KeyError, ValueError): |
paul@237 | 647 | continue |
paul@219 | 648 | |
paul@217 | 649 | # Accept other textual data as it is. |
paul@217 | 650 | |
paul@219 | 651 | elif property in ("LOCATION", "SUMMARY", "URL"): |
paul@219 | 652 | pass |
paul@219 | 653 | |
paul@219 | 654 | # Ignore other properties. |
paul@217 | 655 | |
paul@217 | 656 | else: |
paul@217 | 657 | continue |
paul@217 | 658 | |
paul@219 | 659 | property = property.lower() |
paul@217 | 660 | details[property] = value |
paul@217 | 661 | |
paul@219 | 662 | self.events.append(CalendarEvent(self, details)) |
paul@217 | 663 | |
paul@217 | 664 | return self.events |
paul@67 | 665 | |
paul@67 | 666 | class EventPage: |
paul@67 | 667 | |
paul@229 | 668 | "An event page acting as an event resource." |
paul@67 | 669 | |
paul@67 | 670 | def __init__(self, page): |
paul@67 | 671 | self.page = page |
paul@69 | 672 | self.events = None |
paul@67 | 673 | self.body = None |
paul@67 | 674 | self.categories = None |
paul@219 | 675 | self.metadata = None |
paul@67 | 676 | |
paul@67 | 677 | def copyPage(self, page): |
paul@67 | 678 | |
paul@67 | 679 | "Copy the body of the given 'page'." |
paul@67 | 680 | |
paul@67 | 681 | self.body = page.getBody() |
paul@67 | 682 | |
paul@223 | 683 | def getPageURL(self): |
paul@223 | 684 | |
paul@223 | 685 | "Return the URL of this page." |
paul@223 | 686 | |
paul@223 | 687 | request = self.page.request |
paul@117 | 688 | return request.getQualifiedURL(self.page.url(request, relative=0)) |
paul@67 | 689 | |
paul@67 | 690 | def getFormat(self): |
paul@67 | 691 | |
paul@67 | 692 | "Get the format used on this page." |
paul@24 | 693 | |
paul@117 | 694 | return self.page.pi["format"] |
paul@67 | 695 | |
paul@219 | 696 | def getMetadata(self): |
paul@219 | 697 | |
paul@219 | 698 | """ |
paul@219 | 699 | Return a dictionary containing items describing the page's "created" |
paul@219 | 700 | time, "last-modified" time, "sequence" (or revision number) and the |
paul@219 | 701 | "last-comment" made about the last edit. |
paul@219 | 702 | """ |
paul@219 | 703 | |
paul@219 | 704 | request = self.page.request |
paul@219 | 705 | |
paul@219 | 706 | # Get the initial revision of the page. |
paul@219 | 707 | |
paul@219 | 708 | revisions = self.getRevisions() |
paul@219 | 709 | event_page_initial = Page(request, self.getPageName(), rev=revisions[-1]) |
paul@219 | 710 | |
paul@219 | 711 | # Get the created and last modified times. |
paul@219 | 712 | |
paul@219 | 713 | initial_revision = getPageRevision(event_page_initial) |
paul@219 | 714 | |
paul@219 | 715 | if self.metadata is None: |
paul@219 | 716 | self.metadata = {} |
paul@219 | 717 | self.metadata["created"] = initial_revision["timestamp"] |
paul@219 | 718 | latest_revision = self.getPageRevision() |
paul@219 | 719 | self.metadata["last-modified"] = latest_revision["timestamp"] |
paul@219 | 720 | self.metadata["sequence"] = len(revisions) - 1 |
paul@219 | 721 | self.metadata["last-comment"] = latest_revision["comment"] |
paul@219 | 722 | |
paul@219 | 723 | return self.metadata |
paul@219 | 724 | |
paul@67 | 725 | def getRevisions(self): |
paul@67 | 726 | |
paul@67 | 727 | "Return a list of page revisions." |
paul@67 | 728 | |
paul@67 | 729 | return self.page.getRevList() |
paul@67 | 730 | |
paul@67 | 731 | def getPageRevision(self): |
paul@24 | 732 | |
paul@67 | 733 | "Return the revision details dictionary for this page." |
paul@67 | 734 | |
paul@67 | 735 | return getPageRevision(self.page) |
paul@67 | 736 | |
paul@67 | 737 | def getPageName(self): |
paul@67 | 738 | |
paul@67 | 739 | "Return the page name." |
paul@67 | 740 | |
paul@67 | 741 | return self.page.page_name |
paul@24 | 742 | |
paul@67 | 743 | def getPrettyPageName(self): |
paul@67 | 744 | |
paul@67 | 745 | "Return a nicely formatted title/name for this page." |
paul@67 | 746 | |
paul@67 | 747 | return getPrettyPageName(self.page) |
paul@67 | 748 | |
paul@67 | 749 | def getBody(self): |
paul@67 | 750 | |
paul@67 | 751 | "Get the current page body." |
paul@47 | 752 | |
paul@67 | 753 | if self.body is None: |
paul@67 | 754 | self.body = self.page.get_raw_body() |
paul@67 | 755 | return self.body |
paul@67 | 756 | |
paul@69 | 757 | def getEvents(self): |
paul@69 | 758 | |
paul@69 | 759 | "Return a list of events from this page." |
paul@67 | 760 | |
paul@69 | 761 | if self.events is None: |
paul@69 | 762 | details = {} |
paul@69 | 763 | self.events = [Event(self, details)] |
paul@47 | 764 | |
paul@67 | 765 | if self.getFormat() == "wiki": |
paul@67 | 766 | for match in definition_list_regexp.finditer(self.getBody()): |
paul@67 | 767 | |
paul@67 | 768 | # Skip commented-out items. |
paul@47 | 769 | |
paul@67 | 770 | if match.group("optcomment"): |
paul@67 | 771 | continue |
paul@67 | 772 | |
paul@67 | 773 | # Permit case-insensitive list terms. |
paul@67 | 774 | |
paul@67 | 775 | term = match.group("term").lower() |
paul@67 | 776 | desc = match.group("desc") |
paul@67 | 777 | |
paul@67 | 778 | # Special value type handling. |
paul@27 | 779 | |
paul@67 | 780 | # Dates. |
paul@67 | 781 | |
paul@67 | 782 | if term in ("start", "end"): |
paul@123 | 783 | desc = getDateTime(desc) |
paul@67 | 784 | |
paul@67 | 785 | # Lists (whose elements may be quoted). |
paul@67 | 786 | |
paul@67 | 787 | elif term in ("topics", "categories"): |
paul@229 | 788 | desc = map(getSimpleWikiText, to_list(desc, ",")) |
paul@229 | 789 | |
paul@230 | 790 | # Position details. |
paul@229 | 791 | |
paul@229 | 792 | elif term == "geo": |
paul@237 | 793 | try: |
paul@237 | 794 | desc = map(getMapReference, to_list(desc, None)) |
paul@237 | 795 | except (KeyError, ValueError): |
paul@237 | 796 | continue |
paul@67 | 797 | |
paul@67 | 798 | # Labels which may well be quoted. |
paul@67 | 799 | |
paul@92 | 800 | elif term in ("title", "summary", "description", "location"): |
paul@179 | 801 | desc = getSimpleWikiText(desc.strip()) |
paul@67 | 802 | |
paul@67 | 803 | if desc is not None: |
paul@69 | 804 | |
paul@69 | 805 | # Handle apparent duplicates by creating a new set of |
paul@69 | 806 | # details. |
paul@69 | 807 | |
paul@69 | 808 | if details.has_key(term): |
paul@92 | 809 | |
paul@92 | 810 | # Make a new event. |
paul@92 | 811 | |
paul@69 | 812 | details = {} |
paul@69 | 813 | self.events.append(Event(self, details)) |
paul@67 | 814 | |
paul@69 | 815 | details[term] = desc |
paul@69 | 816 | |
paul@69 | 817 | return self.events |
paul@69 | 818 | |
paul@69 | 819 | def setEvents(self, events): |
paul@69 | 820 | |
paul@69 | 821 | "Set the given 'events' on this page." |
paul@69 | 822 | |
paul@69 | 823 | self.events = events |
paul@67 | 824 | |
paul@67 | 825 | def getCategoryMembership(self): |
paul@27 | 826 | |
paul@67 | 827 | "Get the category names from this page." |
paul@67 | 828 | |
paul@67 | 829 | if self.categories is None: |
paul@67 | 830 | body = self.getBody() |
paul@67 | 831 | match = category_membership_regexp.search(body) |
paul@158 | 832 | self.categories = match and [x for x in match.groups() if x] or [] |
paul@67 | 833 | |
paul@67 | 834 | return self.categories |
paul@67 | 835 | |
paul@67 | 836 | def setCategoryMembership(self, category_names): |
paul@10 | 837 | |
paul@67 | 838 | """ |
paul@67 | 839 | Set the category membership for the page using the specified |
paul@67 | 840 | 'category_names'. |
paul@67 | 841 | """ |
paul@67 | 842 | |
paul@67 | 843 | self.categories = category_names |
paul@67 | 844 | |
paul@67 | 845 | def flushEventDetails(self): |
paul@67 | 846 | |
paul@67 | 847 | "Flush the current event details to this page's body text." |
paul@10 | 848 | |
paul@67 | 849 | new_body_parts = [] |
paul@67 | 850 | end_of_last_match = 0 |
paul@67 | 851 | body = self.getBody() |
paul@69 | 852 | |
paul@69 | 853 | events = iter(self.getEvents()) |
paul@69 | 854 | |
paul@69 | 855 | event = events.next() |
paul@69 | 856 | event_details = event.getDetails() |
paul@69 | 857 | replaced_terms = set() |
paul@67 | 858 | |
paul@67 | 859 | for match in definition_list_regexp.finditer(body): |
paul@47 | 860 | |
paul@10 | 861 | # Permit case-insensitive list terms. |
paul@10 | 862 | |
paul@10 | 863 | term = match.group("term").lower() |
paul@10 | 864 | desc = match.group("desc") |
paul@10 | 865 | |
paul@69 | 866 | # Check that the term has not already been substituted. If so, |
paul@69 | 867 | # get the next event. |
paul@69 | 868 | |
paul@69 | 869 | if term in replaced_terms: |
paul@69 | 870 | try: |
paul@69 | 871 | event = events.next() |
paul@69 | 872 | |
paul@69 | 873 | # No more events. |
paul@69 | 874 | |
paul@69 | 875 | except StopIteration: |
paul@69 | 876 | break |
paul@69 | 877 | |
paul@69 | 878 | event_details = event.getDetails() |
paul@69 | 879 | replaced_terms = set() |
paul@69 | 880 | |
paul@75 | 881 | # Add preceding text to the new body. |
paul@75 | 882 | |
paul@75 | 883 | new_body_parts.append(body[end_of_last_match:match.start()]) |
paul@75 | 884 | |
paul@75 | 885 | # Get the matching regions, adding the term to the new body. |
paul@75 | 886 | |
paul@75 | 887 | new_body_parts.append(match.group("wholeterm")) |
paul@75 | 888 | |
paul@10 | 889 | # Special value type handling. |
paul@10 | 890 | |
paul@67 | 891 | if event_details.has_key(term): |
paul@19 | 892 | |
paul@67 | 893 | # Dates. |
paul@47 | 894 | |
paul@67 | 895 | if term in ("start", "end"): |
paul@67 | 896 | desc = desc.replace("YYYY-MM-DD", str(event_details[term])) |
paul@47 | 897 | |
paul@67 | 898 | # Lists (whose elements may be quoted). |
paul@47 | 899 | |
paul@67 | 900 | elif term in ("topics", "categories"): |
paul@92 | 901 | desc = ", ".join([getEncodedWikiText(item) for item in event_details[term]]) |
paul@47 | 902 | |
paul@92 | 903 | # Labels which must be quoted. |
paul@47 | 904 | |
paul@67 | 905 | elif term in ("title", "summary"): |
paul@67 | 906 | desc = getEncodedWikiText(event_details[term]) |
paul@47 | 907 | |
paul@230 | 908 | # Position details. |
paul@230 | 909 | |
paul@230 | 910 | elif term == "geo": |
paul@230 | 911 | desc = " ".join(map(str, event_details[term])) |
paul@230 | 912 | |
paul@67 | 913 | # Text which need not be quoted, but it will be Wiki text. |
paul@55 | 914 | |
paul@92 | 915 | elif term in ("description", "link", "location"): |
paul@67 | 916 | desc = event_details[term] |
paul@55 | 917 | |
paul@69 | 918 | replaced_terms.add(term) |
paul@69 | 919 | |
paul@75 | 920 | # Add the replaced value. |
paul@75 | 921 | |
paul@67 | 922 | new_body_parts.append(desc) |
paul@10 | 923 | |
paul@69 | 924 | # Remember where in the page has been processed. |
paul@69 | 925 | |
paul@69 | 926 | end_of_last_match = match.end() |
paul@69 | 927 | |
paul@69 | 928 | # Write the rest of the page. |
paul@69 | 929 | |
paul@69 | 930 | new_body_parts.append(body[end_of_last_match:]) |
paul@10 | 931 | |
paul@67 | 932 | self.body = "".join(new_body_parts) |
paul@11 | 933 | |
paul@67 | 934 | def flushCategoryMembership(self): |
paul@17 | 935 | |
paul@67 | 936 | "Flush the category membership to the page body." |
paul@11 | 937 | |
paul@67 | 938 | body = self.getBody() |
paul@67 | 939 | category_names = self.getCategoryMembership() |
paul@67 | 940 | match = category_membership_regexp.search(body) |
paul@10 | 941 | |
paul@67 | 942 | if match: |
paul@67 | 943 | self.body = "".join([body[:match.start()], " ".join(category_names), body[match.end():]]) |
paul@10 | 944 | |
paul@67 | 945 | def saveChanges(self): |
paul@10 | 946 | |
paul@67 | 947 | "Save changes to the event." |
paul@10 | 948 | |
paul@67 | 949 | self.flushEventDetails() |
paul@67 | 950 | self.flushCategoryMembership() |
paul@67 | 951 | self.page.saveText(self.getBody(), 0) |
paul@10 | 952 | |
paul@67 | 953 | def linkToPage(self, request, text, query_string=None): |
paul@11 | 954 | |
paul@67 | 955 | """ |
paul@67 | 956 | Using 'request', return a link to this page with the given link 'text' |
paul@67 | 957 | and optional 'query_string'. |
paul@67 | 958 | """ |
paul@11 | 959 | |
paul@67 | 960 | return linkToPage(request, self.page, text, query_string) |
paul@13 | 961 | |
paul@217 | 962 | # Formatting-related functions. |
paul@217 | 963 | |
paul@217 | 964 | def getParserClass(self, request, format): |
paul@217 | 965 | |
paul@217 | 966 | """ |
paul@217 | 967 | Return a parser class using the 'request' for the given 'format', returning |
paul@217 | 968 | a plain text parser if no parser can be found for the specified 'format'. |
paul@217 | 969 | """ |
paul@217 | 970 | |
paul@217 | 971 | try: |
paul@217 | 972 | return wikiutil.searchAndImportPlugin(request.cfg, "parser", format or "plain") |
paul@217 | 973 | except wikiutil.PluginMissingError: |
paul@217 | 974 | return wikiutil.searchAndImportPlugin(request.cfg, "parser", "plain") |
paul@217 | 975 | |
paul@217 | 976 | def formatText(self, text, request, fmt): |
paul@217 | 977 | |
paul@217 | 978 | """ |
paul@217 | 979 | Format the given 'text' using the specified 'request' and formatter |
paul@217 | 980 | 'fmt'. |
paul@217 | 981 | """ |
paul@217 | 982 | |
paul@219 | 983 | fmt.page = self.page |
paul@219 | 984 | |
paul@217 | 985 | # Suppress line anchors. |
paul@217 | 986 | |
paul@217 | 987 | parser_cls = self.getParserClass(request, self.getFormat()) |
paul@217 | 988 | parser = parser_cls(text, request, line_anchors=False) |
paul@217 | 989 | |
paul@217 | 990 | # Fix lists by indicating that a paragraph is already started. |
paul@217 | 991 | |
paul@217 | 992 | return request.redirectedOutput(parser.format, fmt, inhibit_p=True) |
paul@217 | 993 | |
paul@217 | 994 | # Event details. |
paul@217 | 995 | |
paul@130 | 996 | class Event(ActsAsTimespan): |
paul@69 | 997 | |
paul@69 | 998 | "A description of an event." |
paul@69 | 999 | |
paul@69 | 1000 | def __init__(self, page, details): |
paul@69 | 1001 | self.page = page |
paul@69 | 1002 | self.details = details |
paul@69 | 1003 | |
paul@217 | 1004 | # Permit omission of the end of the event by duplicating the start. |
paul@217 | 1005 | |
paul@240 | 1006 | if self.details.has_key("start") and not self.details.get("end"): |
paul@218 | 1007 | end = self.details["start"] |
paul@218 | 1008 | |
paul@218 | 1009 | # Make any end time refer to the day instead. |
paul@218 | 1010 | |
paul@218 | 1011 | if isinstance(end, DateTime): |
paul@218 | 1012 | end = end.as_date() |
paul@218 | 1013 | |
paul@218 | 1014 | self.details["end"] = end |
paul@217 | 1015 | |
paul@170 | 1016 | def __repr__(self): |
paul@170 | 1017 | return "<Event %r %r>" % (self.getSummary(), self.as_limits()) |
paul@170 | 1018 | |
paul@128 | 1019 | def __hash__(self): |
paul@223 | 1020 | |
paul@223 | 1021 | """ |
paul@223 | 1022 | Return a dictionary hash, avoiding mistaken equality of events in some |
paul@223 | 1023 | situations (notably membership tests) by including the URL as well as |
paul@223 | 1024 | the summary. |
paul@223 | 1025 | """ |
paul@223 | 1026 | |
paul@223 | 1027 | return hash(self.getSummary() + self.getEventURL()) |
paul@69 | 1028 | |
paul@69 | 1029 | def getPage(self): |
paul@69 | 1030 | |
paul@69 | 1031 | "Return the page describing this event." |
paul@69 | 1032 | |
paul@69 | 1033 | return self.page |
paul@69 | 1034 | |
paul@69 | 1035 | def setPage(self, page): |
paul@69 | 1036 | |
paul@69 | 1037 | "Set the 'page' describing this event." |
paul@69 | 1038 | |
paul@69 | 1039 | self.page = page |
paul@69 | 1040 | |
paul@223 | 1041 | def getEventURL(self): |
paul@223 | 1042 | |
paul@223 | 1043 | "Return the URL of this event." |
paul@223 | 1044 | |
paul@223 | 1045 | return self.page.getPageURL() |
paul@219 | 1046 | |
paul@219 | 1047 | def linkToEvent(self, request, text, query_string=None): |
paul@219 | 1048 | |
paul@219 | 1049 | """ |
paul@219 | 1050 | Using 'request', return a link to this event with the given link 'text' |
paul@219 | 1051 | and optional 'query_string'. |
paul@219 | 1052 | """ |
paul@219 | 1053 | |
paul@219 | 1054 | return self.page.linkToPage(request, text, query_string) |
paul@219 | 1055 | |
paul@219 | 1056 | def getMetadata(self): |
paul@219 | 1057 | |
paul@219 | 1058 | """ |
paul@219 | 1059 | Return a dictionary containing items describing the event's "created" |
paul@219 | 1060 | time, "last-modified" time, "sequence" (or revision number) and the |
paul@219 | 1061 | "last-comment" made about the last edit. |
paul@219 | 1062 | """ |
paul@219 | 1063 | |
paul@219 | 1064 | # Delegate this to the page. |
paul@219 | 1065 | |
paul@219 | 1066 | return self.page.getMetadata() |
paul@219 | 1067 | |
paul@69 | 1068 | def getSummary(self, event_parent=None): |
paul@69 | 1069 | |
paul@69 | 1070 | """ |
paul@69 | 1071 | Return either the given title or summary of the event according to the |
paul@69 | 1072 | event details, or a summary made from using the pretty version of the |
paul@69 | 1073 | page name. |
paul@69 | 1074 | |
paul@69 | 1075 | If the optional 'event_parent' is specified, any page beneath the given |
paul@69 | 1076 | 'event_parent' page in the page hierarchy will omit this parent information |
paul@69 | 1077 | if its name is used as the summary. |
paul@69 | 1078 | """ |
paul@69 | 1079 | |
paul@69 | 1080 | event_details = self.details |
paul@69 | 1081 | |
paul@69 | 1082 | if event_details.has_key("title"): |
paul@69 | 1083 | return event_details["title"] |
paul@69 | 1084 | elif event_details.has_key("summary"): |
paul@69 | 1085 | return event_details["summary"] |
paul@69 | 1086 | else: |
paul@69 | 1087 | # If appropriate, remove the parent details and "/" character. |
paul@69 | 1088 | |
paul@69 | 1089 | title = self.page.getPageName() |
paul@69 | 1090 | |
paul@74 | 1091 | if event_parent and title.startswith(event_parent): |
paul@69 | 1092 | title = title[len(event_parent.rstrip("/")) + 1:] |
paul@69 | 1093 | |
paul@69 | 1094 | return getPrettyTitle(title) |
paul@69 | 1095 | |
paul@69 | 1096 | def getDetails(self): |
paul@69 | 1097 | |
paul@69 | 1098 | "Return the details for this event." |
paul@69 | 1099 | |
paul@69 | 1100 | return self.details |
paul@69 | 1101 | |
paul@69 | 1102 | def setDetails(self, event_details): |
paul@69 | 1103 | |
paul@69 | 1104 | "Set the 'event_details' for this event." |
paul@69 | 1105 | |
paul@69 | 1106 | self.details = event_details |
paul@69 | 1107 | |
paul@123 | 1108 | # Timespan-related methods. |
paul@123 | 1109 | |
paul@123 | 1110 | def __contains__(self, other): |
paul@123 | 1111 | return self == other |
paul@123 | 1112 | |
paul@224 | 1113 | def __eq__(self, other): |
paul@224 | 1114 | if isinstance(other, Event): |
paul@224 | 1115 | return self.getSummary() == other.getSummary() and self.getEventURL() == other.getEventURL() and self._cmp(other) |
paul@224 | 1116 | else: |
paul@224 | 1117 | return self._cmp(other) == 0 |
paul@224 | 1118 | |
paul@224 | 1119 | def __ne__(self, other): |
paul@224 | 1120 | return not self.__eq__(other) |
paul@224 | 1121 | |
paul@224 | 1122 | def __lt__(self, other): |
paul@224 | 1123 | return self._cmp(other) == -1 |
paul@224 | 1124 | |
paul@224 | 1125 | def __le__(self, other): |
paul@224 | 1126 | return self._cmp(other) in (-1, 0) |
paul@224 | 1127 | |
paul@224 | 1128 | def __gt__(self, other): |
paul@224 | 1129 | return self._cmp(other) == 1 |
paul@224 | 1130 | |
paul@224 | 1131 | def __ge__(self, other): |
paul@224 | 1132 | return self._cmp(other) in (0, 1) |
paul@224 | 1133 | |
paul@224 | 1134 | def _cmp(self, other): |
paul@223 | 1135 | |
paul@223 | 1136 | "Compare this event to an 'other' event purely by their timespans." |
paul@223 | 1137 | |
paul@123 | 1138 | if isinstance(other, Event): |
paul@123 | 1139 | return cmp(self.as_timespan(), other.as_timespan()) |
paul@123 | 1140 | else: |
paul@123 | 1141 | return cmp(self.as_timespan(), other) |
paul@123 | 1142 | |
paul@123 | 1143 | def as_timespan(self): |
paul@123 | 1144 | details = self.details |
paul@123 | 1145 | if details.has_key("start") and details.has_key("end"): |
paul@123 | 1146 | return Timespan(details["start"], details["end"]) |
paul@123 | 1147 | else: |
paul@123 | 1148 | return None |
paul@123 | 1149 | |
paul@128 | 1150 | def as_limits(self): |
paul@170 | 1151 | ts = self.as_timespan() |
paul@170 | 1152 | return ts and ts.as_limits() |
paul@123 | 1153 | |
paul@219 | 1154 | class CalendarEvent(Event): |
paul@219 | 1155 | |
paul@219 | 1156 | "An event from a remote calendar." |
paul@219 | 1157 | |
paul@223 | 1158 | def getEventURL(self): |
paul@223 | 1159 | |
paul@223 | 1160 | "Return the URL of this event." |
paul@223 | 1161 | |
paul@223 | 1162 | return self.details.get("url") or self.page.getPageURL() |
paul@219 | 1163 | |
paul@219 | 1164 | def linkToEvent(self, request, text, query_string=None): |
paul@219 | 1165 | |
paul@219 | 1166 | """ |
paul@219 | 1167 | Using 'request', return a link to this event with the given link 'text' |
paul@219 | 1168 | and optional 'query_string'. |
paul@219 | 1169 | """ |
paul@219 | 1170 | |
paul@223 | 1171 | return linkToResource(self.getEventURL(), request, text, query_string) |
paul@219 | 1172 | |
paul@219 | 1173 | def getMetadata(self): |
paul@219 | 1174 | |
paul@219 | 1175 | """ |
paul@219 | 1176 | Return a dictionary containing items describing the event's "created" |
paul@219 | 1177 | time, "last-modified" time, "sequence" (or revision number) and the |
paul@219 | 1178 | "last-comment" made about the last edit. |
paul@219 | 1179 | """ |
paul@219 | 1180 | |
paul@219 | 1181 | return { |
paul@219 | 1182 | "created" : self.details.get("created") or self.details["dtstamp"], |
paul@219 | 1183 | "last-modified" : self.details.get("last-modified") or self.details["dtstamp"], |
paul@219 | 1184 | "sequence" : self.details.get("sequence") or 0, |
paul@219 | 1185 | "last-comment" : "" |
paul@219 | 1186 | } |
paul@219 | 1187 | |
paul@217 | 1188 | # Obtaining event containers and events from such containers. |
paul@217 | 1189 | |
paul@217 | 1190 | def getEventPages(pages): |
paul@168 | 1191 | |
paul@168 | 1192 | "Return a list of events found on the given 'pages'." |
paul@12 | 1193 | |
paul@217 | 1194 | # Get real pages instead of result pages. |
paul@217 | 1195 | |
paul@217 | 1196 | return map(EventPage, pages) |
paul@217 | 1197 | |
paul@219 | 1198 | def getAllEventSources(request): |
paul@219 | 1199 | |
paul@219 | 1200 | "Return all event sources defined in the Wiki using the 'request'." |
paul@219 | 1201 | |
paul@219 | 1202 | sources_page = getattr(request.cfg, "event_aggregator_sources_page", "EventSourcesDict") |
paul@219 | 1203 | |
paul@219 | 1204 | # Remote sources are accessed via dictionary page definitions. |
paul@219 | 1205 | |
paul@237 | 1206 | return getWikiDict(sources_page, request) |
paul@219 | 1207 | |
paul@217 | 1208 | def getEventResources(sources, calendar_start, calendar_end, request): |
paul@217 | 1209 | |
paul@217 | 1210 | """ |
paul@217 | 1211 | Return resource objects for the given 'sources' using the given |
paul@217 | 1212 | 'calendar_start' and 'calendar_end' to parameterise requests to the sources, |
paul@217 | 1213 | and the 'request' to access configuration settings in the Wiki. |
paul@217 | 1214 | """ |
paul@217 | 1215 | |
paul@219 | 1216 | sources_dict = getAllEventSources(request) |
paul@219 | 1217 | if not sources_dict: |
paul@217 | 1218 | return [] |
paul@217 | 1219 | |
paul@217 | 1220 | # Use dates for the calendar limits. |
paul@217 | 1221 | |
paul@218 | 1222 | if isinstance(calendar_start, Date): |
paul@218 | 1223 | pass |
paul@218 | 1224 | elif isinstance(calendar_start, Month): |
paul@217 | 1225 | calendar_start = calendar_start.as_date(1) |
paul@217 | 1226 | |
paul@218 | 1227 | if isinstance(calendar_end, Date): |
paul@218 | 1228 | pass |
paul@218 | 1229 | elif isinstance(calendar_end, Month): |
paul@217 | 1230 | calendar_end = calendar_end.as_date(-1) |
paul@217 | 1231 | |
paul@217 | 1232 | resources = [] |
paul@217 | 1233 | |
paul@217 | 1234 | for source in sources: |
paul@217 | 1235 | try: |
paul@217 | 1236 | url, format = sources_dict[source].split() |
paul@237 | 1237 | except (KeyError, ValueError): |
paul@237 | 1238 | pass |
paul@237 | 1239 | else: |
paul@217 | 1240 | # Prevent local file access. |
paul@217 | 1241 | |
paul@217 | 1242 | if url.startswith("file:"): |
paul@217 | 1243 | continue |
paul@217 | 1244 | |
paul@217 | 1245 | # Parameterise the URL. |
paul@221 | 1246 | # Where other parameters are used, care must be taken to encode them |
paul@221 | 1247 | # properly. |
paul@221 | 1248 | |
paul@221 | 1249 | url = url.replace("{start}", urllib.quote_plus(calendar_start and str(calendar_start) or "")) |
paul@221 | 1250 | url = url.replace("{end}", urllib.quote_plus(calendar_end and str(calendar_end) or "")) |
paul@217 | 1251 | |
paul@217 | 1252 | # Get a parser. |
paul@217 | 1253 | |
paul@217 | 1254 | if format == "ical" and vCalendar is not None: |
paul@217 | 1255 | parser = vCalendar.parse |
paul@217 | 1256 | resource_cls = EventCalendar |
paul@217 | 1257 | else: |
paul@217 | 1258 | continue |
paul@217 | 1259 | |
paul@225 | 1260 | # See if the URL is cached. |
paul@225 | 1261 | |
paul@225 | 1262 | cache_key = cache.key(request, content=url) |
paul@225 | 1263 | cache_entry = caching.CacheEntry(request, "EventAggregator", cache_key, scope='wiki') |
paul@225 | 1264 | |
paul@226 | 1265 | # If no entry exists, or if the entry is older than a certain age |
paul@226 | 1266 | # (5 minutes by default), create one with the response from the URL. |
paul@226 | 1267 | |
paul@226 | 1268 | now = time.time() |
paul@226 | 1269 | mtime = cache_entry.mtime() |
paul@226 | 1270 | max_cache_age = int(getattr(request.cfg, "event_aggregator_max_cache_age", "300")) |
paul@226 | 1271 | |
paul@226 | 1272 | # NOTE: The URL could be checked and the 'If-Modified-Since' header |
paul@226 | 1273 | # NOTE: (see MoinMoin.action.pollsistersites) could be checked. |
paul@226 | 1274 | |
paul@226 | 1275 | if not cache_entry.exists() or now - mtime >= max_cache_age: |
paul@225 | 1276 | |
paul@225 | 1277 | # Access the remote data source. |
paul@225 | 1278 | |
paul@225 | 1279 | cache_entry.open(mode="w") |
paul@225 | 1280 | f = urllib.urlopen(url) |
paul@225 | 1281 | try: |
paul@225 | 1282 | cache_entry.write(url + "\n") |
paul@225 | 1283 | cache_entry.write((f.headers.get("content-type") or "") + "\n") |
paul@225 | 1284 | cache_entry.write(f.read()) |
paul@225 | 1285 | finally: |
paul@225 | 1286 | cache_entry.close() |
paul@225 | 1287 | f.close() |
paul@225 | 1288 | |
paul@225 | 1289 | # Open the cache entry and read it. |
paul@225 | 1290 | |
paul@225 | 1291 | cache_entry.open() |
paul@217 | 1292 | try: |
paul@225 | 1293 | data = cache_entry.read() |
paul@225 | 1294 | finally: |
paul@225 | 1295 | cache_entry.close() |
paul@225 | 1296 | |
paul@225 | 1297 | # Process the entry, parsing the content. |
paul@225 | 1298 | |
paul@225 | 1299 | f = StringIO(data) |
paul@225 | 1300 | try: |
paul@225 | 1301 | url = f.readline() |
paul@225 | 1302 | encoding = getContentEncoding(f.readline()) |
paul@225 | 1303 | uf = codecs.getreader(encoding or "utf-8")(f) |
paul@225 | 1304 | try: |
paul@225 | 1305 | resources.append(resource_cls(url, parser(uf))) |
paul@225 | 1306 | finally: |
paul@225 | 1307 | uf.close() |
paul@217 | 1308 | finally: |
paul@217 | 1309 | f.close() |
paul@217 | 1310 | |
paul@217 | 1311 | return resources |
paul@217 | 1312 | |
paul@217 | 1313 | def getEventsFromResources(resources): |
paul@217 | 1314 | |
paul@217 | 1315 | "Return a list of events supplied by the given event 'resources'." |
paul@217 | 1316 | |
paul@10 | 1317 | events = [] |
paul@168 | 1318 | |
paul@217 | 1319 | for resource in resources: |
paul@217 | 1320 | |
paul@217 | 1321 | # Get all events described by the resource. |
paul@217 | 1322 | |
paul@217 | 1323 | for event in resource.getEvents(): |
paul@168 | 1324 | |
paul@168 | 1325 | # Remember the event. |
paul@168 | 1326 | |
paul@168 | 1327 | events.append(event) |
paul@168 | 1328 | |
paul@168 | 1329 | return events |
paul@168 | 1330 | |
paul@217 | 1331 | # Event filtering and limits. |
paul@217 | 1332 | |
paul@171 | 1333 | def getEventsInPeriod(events, calendar_period): |
paul@168 | 1334 | |
paul@168 | 1335 | """ |
paul@168 | 1336 | Return a collection containing those of the given 'events' which occur |
paul@171 | 1337 | within the given 'calendar_period'. |
paul@168 | 1338 | """ |
paul@168 | 1339 | |
paul@171 | 1340 | all_shown_events = [] |
paul@168 | 1341 | |
paul@168 | 1342 | for event in events: |
paul@168 | 1343 | |
paul@168 | 1344 | # Test for the suitability of the event. |
paul@168 | 1345 | |
paul@168 | 1346 | if event.as_timespan() is not None: |
paul@168 | 1347 | |
paul@168 | 1348 | # Compare the dates to the requested calendar window, if any. |
paul@168 | 1349 | |
paul@168 | 1350 | if event in calendar_period: |
paul@171 | 1351 | all_shown_events.append(event) |
paul@168 | 1352 | |
paul@168 | 1353 | return all_shown_events |
paul@10 | 1354 | |
paul@171 | 1355 | def getEventLimits(events): |
paul@171 | 1356 | |
paul@171 | 1357 | "Return the earliest and latest of the given 'events'." |
paul@171 | 1358 | |
paul@171 | 1359 | earliest = None |
paul@171 | 1360 | latest = None |
paul@171 | 1361 | |
paul@171 | 1362 | for event in events: |
paul@171 | 1363 | |
paul@171 | 1364 | # Test for the suitability of the event. |
paul@171 | 1365 | |
paul@171 | 1366 | if event.as_timespan() is not None: |
paul@171 | 1367 | ts = event.as_timespan() |
paul@171 | 1368 | if earliest is None or ts.start < earliest: |
paul@171 | 1369 | earliest = ts.start |
paul@171 | 1370 | if latest is None or ts.end > latest: |
paul@171 | 1371 | latest = ts.end |
paul@171 | 1372 | |
paul@171 | 1373 | return earliest, latest |
paul@171 | 1374 | |
paul@29 | 1375 | def setEventTimestamps(request, events): |
paul@29 | 1376 | |
paul@29 | 1377 | """ |
paul@29 | 1378 | Using 'request', set timestamp details in the details dictionary of each of |
paul@67 | 1379 | the 'events'. |
paul@29 | 1380 | |
paul@111 | 1381 | Return the latest timestamp found. |
paul@29 | 1382 | """ |
paul@29 | 1383 | |
paul@29 | 1384 | latest = None |
paul@29 | 1385 | |
paul@69 | 1386 | for event in events: |
paul@69 | 1387 | event_details = event.getDetails() |
paul@219 | 1388 | |
paul@219 | 1389 | # Populate the details with event metadata. |
paul@219 | 1390 | |
paul@219 | 1391 | event_details.update(event.getMetadata()) |
paul@29 | 1392 | |
paul@29 | 1393 | if latest is None or latest < event_details["last-modified"]: |
paul@29 | 1394 | latest = event_details["last-modified"] |
paul@29 | 1395 | |
paul@29 | 1396 | return latest |
paul@29 | 1397 | |
paul@26 | 1398 | def getOrderedEvents(events): |
paul@26 | 1399 | |
paul@26 | 1400 | """ |
paul@26 | 1401 | Return a list with the given 'events' ordered according to their start and |
paul@67 | 1402 | end dates. |
paul@26 | 1403 | """ |
paul@26 | 1404 | |
paul@26 | 1405 | ordered_events = events[:] |
paul@68 | 1406 | ordered_events.sort() |
paul@26 | 1407 | return ordered_events |
paul@26 | 1408 | |
paul@171 | 1409 | def getCalendarPeriod(calendar_start, calendar_end): |
paul@168 | 1410 | |
paul@168 | 1411 | """ |
paul@171 | 1412 | Return a calendar period for the given 'calendar_start' and 'calendar_end'. |
paul@171 | 1413 | These parameters can be given as None. |
paul@168 | 1414 | """ |
paul@168 | 1415 | |
paul@168 | 1416 | # Re-order the window, if appropriate. |
paul@168 | 1417 | |
paul@168 | 1418 | if calendar_start is not None and calendar_end is not None and calendar_start > calendar_end: |
paul@168 | 1419 | calendar_start, calendar_end = calendar_end, calendar_start |
paul@168 | 1420 | |
paul@171 | 1421 | return Timespan(calendar_start, calendar_end) |
paul@168 | 1422 | |
paul@187 | 1423 | def getConcretePeriod(calendar_start, calendar_end, earliest, latest, resolution): |
paul@13 | 1424 | |
paul@13 | 1425 | """ |
paul@13 | 1426 | From the requested 'calendar_start' and 'calendar_end', which may be None, |
paul@13 | 1427 | indicating that no restriction is imposed on the period for each of the |
paul@13 | 1428 | boundaries, use the 'earliest' and 'latest' event months to define a |
paul@13 | 1429 | specific period of interest. |
paul@13 | 1430 | """ |
paul@13 | 1431 | |
paul@13 | 1432 | # Define the period as starting with any specified start month or the |
paul@13 | 1433 | # earliest event known, ending with any specified end month or the latest |
paul@13 | 1434 | # event known. |
paul@13 | 1435 | |
paul@13 | 1436 | first = calendar_start or earliest |
paul@13 | 1437 | last = calendar_end or latest |
paul@13 | 1438 | |
paul@13 | 1439 | # If there is no range of months to show, perhaps because there are no |
paul@13 | 1440 | # events in the requested period, and there was no start or end month |
paul@13 | 1441 | # specified, show only the month indicated by the start or end of the |
paul@13 | 1442 | # requested period. If all events were to be shown but none were found show |
paul@13 | 1443 | # the current month. |
paul@13 | 1444 | |
paul@187 | 1445 | if resolution == "date": |
paul@122 | 1446 | get_current = getCurrentDate |
paul@122 | 1447 | else: |
paul@122 | 1448 | get_current = getCurrentMonth |
paul@122 | 1449 | |
paul@13 | 1450 | if first is None: |
paul@122 | 1451 | first = last or get_current() |
paul@13 | 1452 | if last is None: |
paul@122 | 1453 | last = first or get_current() |
paul@13 | 1454 | |
paul@187 | 1455 | if resolution == "month": |
paul@187 | 1456 | first = first.as_month() |
paul@187 | 1457 | last = last.as_month() |
paul@187 | 1458 | |
paul@13 | 1459 | # Permit "expiring" periods (where the start date approaches the end date). |
paul@13 | 1460 | |
paul@13 | 1461 | return min(first, last), last |
paul@13 | 1462 | |
paul@168 | 1463 | def getCoverage(events, resolution="date"): |
paul@15 | 1464 | |
paul@15 | 1465 | """ |
paul@168 | 1466 | Determine the coverage of the given 'events', returning a collection of |
paul@168 | 1467 | timespans, along with a dictionary mapping locations to collections of |
paul@168 | 1468 | slots, where each slot contains a tuple of the form (timespans, events). |
paul@15 | 1469 | """ |
paul@15 | 1470 | |
paul@118 | 1471 | all_events = {} |
paul@123 | 1472 | full_coverage = TimespanCollection(resolution) |
paul@15 | 1473 | |
paul@15 | 1474 | # Get event details. |
paul@15 | 1475 | |
paul@69 | 1476 | for event in events: |
paul@69 | 1477 | event_details = event.getDetails() |
paul@15 | 1478 | |
paul@168 | 1479 | # Find the coverage of this period for the event. |
paul@168 | 1480 | |
paul@168 | 1481 | # For day views, each location has its own slot, but for month |
paul@168 | 1482 | # views, all locations are pooled together since having separate |
paul@168 | 1483 | # slots for each location can lead to poor usage of vertical space. |
paul@168 | 1484 | |
paul@168 | 1485 | if resolution == "datetime": |
paul@168 | 1486 | event_location = event_details.get("location") |
paul@168 | 1487 | else: |
paul@168 | 1488 | event_location = None |
paul@168 | 1489 | |
paul@168 | 1490 | # Update the overall coverage. |
paul@168 | 1491 | |
paul@168 | 1492 | full_coverage.insert_in_order(event) |
paul@168 | 1493 | |
paul@168 | 1494 | # Add a new events list for a new location. |
paul@168 | 1495 | # Locations can be unspecified, thus None refers to all unlocalised |
paul@168 | 1496 | # events. |
paul@168 | 1497 | |
paul@168 | 1498 | if not all_events.has_key(event_location): |
paul@168 | 1499 | all_events[event_location] = [TimespanCollection(resolution, [event])] |
paul@168 | 1500 | |
paul@168 | 1501 | # Try and fit the event into an events list. |
paul@168 | 1502 | |
paul@168 | 1503 | else: |
paul@168 | 1504 | slot = all_events[event_location] |
paul@168 | 1505 | |
paul@168 | 1506 | for slot_events in slot: |
paul@168 | 1507 | |
paul@168 | 1508 | # Where the event does not overlap with the events in the |
paul@168 | 1509 | # current collection, add it alongside these events. |
paul@168 | 1510 | |
paul@168 | 1511 | if not event in slot_events: |
paul@168 | 1512 | slot_events.insert_in_order(event) |
paul@168 | 1513 | break |
paul@168 | 1514 | |
paul@168 | 1515 | # Make a new element in the list if the event cannot be |
paul@168 | 1516 | # marked alongside existing events. |
paul@15 | 1517 | |
paul@15 | 1518 | else: |
paul@168 | 1519 | slot.append(TimespanCollection(resolution, [event])) |
paul@15 | 1520 | |
paul@15 | 1521 | return full_coverage, all_events |
paul@15 | 1522 | |
paul@122 | 1523 | def getCoverageScale(coverage): |
paul@126 | 1524 | |
paul@126 | 1525 | """ |
paul@126 | 1526 | Return a scale for the given coverage so that the times involved are |
paul@126 | 1527 | exposed. The scale consists of a list of non-overlapping timespans forming |
paul@126 | 1528 | a contiguous period of time. |
paul@126 | 1529 | """ |
paul@126 | 1530 | |
paul@122 | 1531 | times = set() |
paul@122 | 1532 | for timespan in coverage: |
paul@128 | 1533 | start, end = timespan.as_limits() |
paul@128 | 1534 | |
paul@128 | 1535 | # Add either genuine times or dates converted to times. |
paul@128 | 1536 | |
paul@128 | 1537 | if isinstance(start, DateTime): |
paul@128 | 1538 | times.add(start) |
paul@140 | 1539 | else: |
paul@218 | 1540 | times.add(start.as_start_of_day()) |
paul@128 | 1541 | |
paul@128 | 1542 | if isinstance(end, DateTime): |
paul@140 | 1543 | times.add(end) |
paul@140 | 1544 | else: |
paul@140 | 1545 | times.add(end.as_date().next_day()) |
paul@128 | 1546 | |
paul@122 | 1547 | times = list(times) |
paul@135 | 1548 | times.sort(cmp_dates_as_day_start) |
paul@122 | 1549 | |
paul@122 | 1550 | scale = [] |
paul@122 | 1551 | first = 1 |
paul@122 | 1552 | start = None |
paul@122 | 1553 | for time in times: |
paul@122 | 1554 | if not first: |
paul@123 | 1555 | scale.append(Timespan(start, time)) |
paul@122 | 1556 | else: |
paul@122 | 1557 | first = 0 |
paul@122 | 1558 | start = time |
paul@126 | 1559 | |
paul@122 | 1560 | return scale |
paul@122 | 1561 | |
paul@67 | 1562 | # Date-related functions. |
paul@67 | 1563 | |
paul@135 | 1564 | def cmp_dates_as_day_start(a, b): |
paul@135 | 1565 | |
paul@135 | 1566 | """ |
paul@135 | 1567 | Compare dates/datetimes 'a' and 'b' treating dates without time information |
paul@135 | 1568 | as the earliest time in a particular day. |
paul@135 | 1569 | """ |
paul@135 | 1570 | |
paul@135 | 1571 | are_equal = a == b |
paul@135 | 1572 | |
paul@135 | 1573 | if are_equal: |
paul@135 | 1574 | a2 = a.as_datetime_or_date() |
paul@135 | 1575 | b2 = b.as_datetime_or_date() |
paul@135 | 1576 | |
paul@135 | 1577 | if isinstance(a2, Date) and isinstance(b2, DateTime): |
paul@135 | 1578 | return -1 |
paul@135 | 1579 | elif isinstance(a2, DateTime) and isinstance(b2, Date): |
paul@135 | 1580 | return 1 |
paul@135 | 1581 | |
paul@135 | 1582 | return cmp(a, b) |
paul@135 | 1583 | |
paul@168 | 1584 | class Convertible: |
paul@168 | 1585 | |
paul@168 | 1586 | "Support for converting temporal objects." |
paul@168 | 1587 | |
paul@168 | 1588 | def _get_converter(self, resolution): |
paul@168 | 1589 | if resolution == "month": |
paul@168 | 1590 | return lambda x: x and x.as_month() |
paul@168 | 1591 | elif resolution == "date": |
paul@168 | 1592 | return lambda x: x and x.as_date() |
paul@168 | 1593 | elif resolution == "datetime": |
paul@168 | 1594 | return lambda x: x and x.as_datetime_or_date() |
paul@168 | 1595 | else: |
paul@168 | 1596 | return lambda x: x |
paul@168 | 1597 | |
paul@168 | 1598 | class Temporal(Convertible): |
paul@67 | 1599 | |
paul@92 | 1600 | "A simple temporal representation, common to dates and times." |
paul@67 | 1601 | |
paul@67 | 1602 | def __init__(self, data): |
paul@92 | 1603 | self.data = list(data) |
paul@67 | 1604 | |
paul@67 | 1605 | def __repr__(self): |
paul@67 | 1606 | return "%s(%r)" % (self.__class__.__name__, self.data) |
paul@67 | 1607 | |
paul@67 | 1608 | def __hash__(self): |
paul@67 | 1609 | return hash(self.as_tuple()) |
paul@67 | 1610 | |
paul@67 | 1611 | def as_tuple(self): |
paul@92 | 1612 | return tuple(self.data) |
paul@92 | 1613 | |
paul@168 | 1614 | def convert(self, resolution): |
paul@168 | 1615 | return self._get_converter(resolution)(self) |
paul@168 | 1616 | |
paul@92 | 1617 | def __cmp__(self, other): |
paul@129 | 1618 | |
paul@129 | 1619 | """ |
paul@129 | 1620 | The result of comparing this instance with 'other' is derived from a |
paul@129 | 1621 | comparison of the instances' date(time) data at the highest common |
paul@129 | 1622 | resolution, meaning that if a date is compared to a datetime, the |
paul@129 | 1623 | datetime will be considered as a date. Thus, a date and a datetime |
paul@129 | 1624 | referring to the same date will be considered equal. |
paul@129 | 1625 | """ |
paul@129 | 1626 | |
paul@122 | 1627 | if not isinstance(other, Temporal): |
paul@122 | 1628 | return NotImplemented |
paul@122 | 1629 | else: |
paul@122 | 1630 | data = self.as_tuple() |
paul@122 | 1631 | other_data = other.as_tuple() |
paul@122 | 1632 | length = min(len(data), len(other_data)) |
paul@122 | 1633 | return cmp(data[:length], other_data[:length]) |
paul@92 | 1634 | |
paul@212 | 1635 | def __sub__(self, other): |
paul@212 | 1636 | |
paul@212 | 1637 | """ |
paul@212 | 1638 | Return the difference between this object and the 'other' object at the |
paul@212 | 1639 | highest common accuracy of both objects. |
paul@212 | 1640 | """ |
paul@212 | 1641 | |
paul@212 | 1642 | if not isinstance(other, Temporal): |
paul@212 | 1643 | return NotImplemented |
paul@212 | 1644 | else: |
paul@212 | 1645 | data = self.as_tuple() |
paul@212 | 1646 | other_data = other.as_tuple() |
paul@212 | 1647 | if len(data) < len(other_data): |
paul@212 | 1648 | return len(self.until(other)) |
paul@212 | 1649 | else: |
paul@212 | 1650 | return len(other.until(self)) |
paul@212 | 1651 | |
paul@187 | 1652 | def _until(self, start, end, nextfn, prevfn): |
paul@103 | 1653 | |
paul@103 | 1654 | """ |
paul@103 | 1655 | Return a collection of units of time by starting from the given 'start' |
paul@103 | 1656 | and stepping across intervening units until 'end' is reached, using the |
paul@103 | 1657 | given 'nextfn' and 'prevfn' to step from one unit to the next. |
paul@103 | 1658 | """ |
paul@103 | 1659 | |
paul@103 | 1660 | current = start |
paul@103 | 1661 | units = [current] |
paul@103 | 1662 | if current < end: |
paul@103 | 1663 | while current < end: |
paul@103 | 1664 | current = nextfn(current) |
paul@103 | 1665 | units.append(current) |
paul@103 | 1666 | elif current > end: |
paul@103 | 1667 | while current > end: |
paul@103 | 1668 | current = prevfn(current) |
paul@103 | 1669 | units.append(current) |
paul@103 | 1670 | return units |
paul@103 | 1671 | |
paul@140 | 1672 | def ambiguous(self): |
paul@140 | 1673 | |
paul@140 | 1674 | "Only times can be ambiguous." |
paul@140 | 1675 | |
paul@140 | 1676 | return 0 |
paul@140 | 1677 | |
paul@92 | 1678 | class Month(Temporal): |
paul@92 | 1679 | |
paul@92 | 1680 | "A simple year-month representation." |
paul@92 | 1681 | |
paul@92 | 1682 | def __str__(self): |
paul@92 | 1683 | return "%04d-%02d" % self.as_tuple()[:2] |
paul@67 | 1684 | |
paul@93 | 1685 | def as_datetime(self, day, hour, minute, second, zone): |
paul@93 | 1686 | return DateTime(self.as_tuple() + (day, hour, minute, second, zone)) |
paul@93 | 1687 | |
paul@67 | 1688 | def as_date(self, day): |
paul@217 | 1689 | if day < 0: |
paul@217 | 1690 | weekday, ndays = self.month_properties() |
paul@217 | 1691 | day = ndays + 1 + day |
paul@67 | 1692 | return Date(self.as_tuple() + (day,)) |
paul@67 | 1693 | |
paul@92 | 1694 | def as_month(self): |
paul@92 | 1695 | return self |
paul@92 | 1696 | |
paul@67 | 1697 | def year(self): |
paul@67 | 1698 | return self.data[0] |
paul@67 | 1699 | |
paul@67 | 1700 | def month(self): |
paul@67 | 1701 | return self.data[1] |
paul@67 | 1702 | |
paul@67 | 1703 | def month_properties(self): |
paul@67 | 1704 | |
paul@67 | 1705 | """ |
paul@67 | 1706 | Return the weekday of the 1st of the month, along with the number of |
paul@67 | 1707 | days, as a tuple. |
paul@67 | 1708 | """ |
paul@67 | 1709 | |
paul@92 | 1710 | year, month = self.as_tuple()[:2] |
paul@67 | 1711 | return calendar.monthrange(year, month) |
paul@67 | 1712 | |
paul@67 | 1713 | def month_update(self, n=1): |
paul@67 | 1714 | |
paul@67 | 1715 | "Return the month updated by 'n' months." |
paul@67 | 1716 | |
paul@92 | 1717 | year, month = self.as_tuple()[:2] |
paul@67 | 1718 | return Month((year + (month - 1 + n) / 12, (month - 1 + n) % 12 + 1)) |
paul@67 | 1719 | |
paul@187 | 1720 | update = month_update |
paul@187 | 1721 | |
paul@67 | 1722 | def next_month(self): |
paul@67 | 1723 | |
paul@67 | 1724 | "Return the month following this one." |
paul@67 | 1725 | |
paul@67 | 1726 | return self.month_update(1) |
paul@67 | 1727 | |
paul@187 | 1728 | next = next_month |
paul@187 | 1729 | |
paul@67 | 1730 | def previous_month(self): |
paul@67 | 1731 | |
paul@67 | 1732 | "Return the month preceding this one." |
paul@67 | 1733 | |
paul@67 | 1734 | return self.month_update(-1) |
paul@67 | 1735 | |
paul@187 | 1736 | previous = previous_month |
paul@187 | 1737 | |
paul@67 | 1738 | def months_until(self, end): |
paul@92 | 1739 | |
paul@92 | 1740 | "Return the collection of months from this month until 'end'." |
paul@92 | 1741 | |
paul@187 | 1742 | return self._until(self.as_month(), end.as_month(), Month.next_month, Month.previous_month) |
paul@187 | 1743 | |
paul@187 | 1744 | until = months_until |
paul@67 | 1745 | |
paul@67 | 1746 | class Date(Month): |
paul@67 | 1747 | |
paul@67 | 1748 | "A simple year-month-day representation." |
paul@67 | 1749 | |
paul@96 | 1750 | def constrain(self): |
paul@96 | 1751 | year, month, day = self.as_tuple()[:3] |
paul@96 | 1752 | |
paul@96 | 1753 | month = max(min(month, 12), 1) |
paul@96 | 1754 | wd, last_day = calendar.monthrange(year, month) |
paul@96 | 1755 | day = max(min(day, last_day), 1) |
paul@96 | 1756 | |
paul@96 | 1757 | self.data[1:3] = month, day |
paul@96 | 1758 | |
paul@67 | 1759 | def __str__(self): |
paul@67 | 1760 | return "%04d-%02d-%02d" % self.as_tuple()[:3] |
paul@67 | 1761 | |
paul@93 | 1762 | def as_datetime(self, hour, minute, second, zone): |
paul@93 | 1763 | return DateTime(self.as_tuple() + (hour, minute, second, zone)) |
paul@93 | 1764 | |
paul@218 | 1765 | def as_start_of_day(self): |
paul@218 | 1766 | return self.as_datetime(None, None, None, None) |
paul@218 | 1767 | |
paul@92 | 1768 | def as_date(self): |
paul@92 | 1769 | return self |
paul@92 | 1770 | |
paul@130 | 1771 | def as_datetime_or_date(self): |
paul@130 | 1772 | return self |
paul@130 | 1773 | |
paul@67 | 1774 | def as_month(self): |
paul@67 | 1775 | return Month(self.data[:2]) |
paul@67 | 1776 | |
paul@67 | 1777 | def day(self): |
paul@67 | 1778 | return self.data[2] |
paul@67 | 1779 | |
paul@122 | 1780 | def day_update(self, n=1): |
paul@122 | 1781 | |
paul@145 | 1782 | "Return the month updated by 'n' days." |
paul@122 | 1783 | |
paul@122 | 1784 | delta = datetime.timedelta(n) |
paul@122 | 1785 | dt = datetime.date(*self.as_tuple()[:3]) |
paul@122 | 1786 | dt_new = dt + delta |
paul@122 | 1787 | return Date((dt_new.year, dt_new.month, dt_new.day)) |
paul@122 | 1788 | |
paul@187 | 1789 | update = day_update |
paul@187 | 1790 | |
paul@67 | 1791 | def next_day(self): |
paul@67 | 1792 | |
paul@67 | 1793 | "Return the date following this one." |
paul@67 | 1794 | |
paul@92 | 1795 | year, month, day = self.as_tuple()[:3] |
paul@67 | 1796 | _wd, end_day = calendar.monthrange(year, month) |
paul@67 | 1797 | if day == end_day: |
paul@67 | 1798 | if month == 12: |
paul@67 | 1799 | return Date((year + 1, 1, 1)) |
paul@67 | 1800 | else: |
paul@67 | 1801 | return Date((year, month + 1, 1)) |
paul@67 | 1802 | else: |
paul@67 | 1803 | return Date((year, month, day + 1)) |
paul@67 | 1804 | |
paul@187 | 1805 | next = next_day |
paul@187 | 1806 | |
paul@67 | 1807 | def previous_day(self): |
paul@67 | 1808 | |
paul@67 | 1809 | "Return the date preceding this one." |
paul@67 | 1810 | |
paul@92 | 1811 | year, month, day = self.as_tuple()[:3] |
paul@67 | 1812 | if day == 1: |
paul@67 | 1813 | if month == 1: |
paul@67 | 1814 | return Date((year - 1, 12, 31)) |
paul@67 | 1815 | else: |
paul@67 | 1816 | _wd, end_day = calendar.monthrange(year, month - 1) |
paul@67 | 1817 | return Date((year, month - 1, end_day)) |
paul@67 | 1818 | else: |
paul@67 | 1819 | return Date((year, month, day - 1)) |
paul@67 | 1820 | |
paul@187 | 1821 | previous = previous_day |
paul@187 | 1822 | |
paul@67 | 1823 | def days_until(self, end): |
paul@92 | 1824 | |
paul@92 | 1825 | "Return the collection of days from this date until 'end'." |
paul@92 | 1826 | |
paul@187 | 1827 | return self._until(self.as_date(), end.as_date(), Date.next_day, Date.previous_day) |
paul@187 | 1828 | |
paul@187 | 1829 | until = days_until |
paul@92 | 1830 | |
paul@92 | 1831 | class DateTime(Date): |
paul@92 | 1832 | |
paul@92 | 1833 | "A simple date plus time representation." |
paul@92 | 1834 | |
paul@96 | 1835 | def constrain(self): |
paul@96 | 1836 | Date.constrain(self) |
paul@96 | 1837 | |
paul@96 | 1838 | hour, minute, second = self.as_tuple()[3:6] |
paul@96 | 1839 | |
paul@96 | 1840 | if self.has_time(): |
paul@96 | 1841 | hour = max(min(hour, 23), 0) |
paul@96 | 1842 | minute = max(min(minute, 59), 0) |
paul@96 | 1843 | |
paul@96 | 1844 | if second is not None: |
paul@96 | 1845 | second = max(min(second, 60), 0) # support leap seconds |
paul@96 | 1846 | |
paul@96 | 1847 | self.data[3:6] = hour, minute, second |
paul@92 | 1848 | |
paul@92 | 1849 | def __str__(self): |
paul@128 | 1850 | return Date.__str__(self) + self.time_string() |
paul@128 | 1851 | |
paul@128 | 1852 | def time_string(self): |
paul@92 | 1853 | if self.has_time(): |
paul@92 | 1854 | data = self.as_tuple() |
paul@92 | 1855 | time_str = " %02d:%02d" % data[3:5] |
paul@92 | 1856 | if data[5] is not None: |
paul@92 | 1857 | time_str += ":%02d" % data[5] |
paul@92 | 1858 | if data[6] is not None: |
paul@92 | 1859 | time_str += " %s" % data[6] |
paul@128 | 1860 | return time_str |
paul@92 | 1861 | else: |
paul@128 | 1862 | return "" |
paul@92 | 1863 | |
paul@219 | 1864 | def as_HTTP_datetime_string(self): |
paul@219 | 1865 | weekday = calendar.weekday(*self.data[:3]) |
paul@219 | 1866 | return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (( |
paul@219 | 1867 | getDayLabel(weekday), |
paul@219 | 1868 | self.data[2], |
paul@219 | 1869 | getMonthLabel(self.data[1]), |
paul@219 | 1870 | self.data[0] |
paul@219 | 1871 | ) + tuple(self.data[3:6])) |
paul@219 | 1872 | |
paul@93 | 1873 | def as_datetime(self): |
paul@93 | 1874 | return self |
paul@93 | 1875 | |
paul@92 | 1876 | def as_date(self): |
paul@92 | 1877 | return Date(self.data[:3]) |
paul@92 | 1878 | |
paul@128 | 1879 | def as_datetime_or_date(self): |
paul@128 | 1880 | |
paul@128 | 1881 | """ |
paul@128 | 1882 | Return a date for this datetime if fields are missing. Otherwise, return |
paul@128 | 1883 | this datetime itself. |
paul@128 | 1884 | """ |
paul@128 | 1885 | |
paul@128 | 1886 | if not self.has_time(): |
paul@128 | 1887 | return self.as_date() |
paul@128 | 1888 | else: |
paul@128 | 1889 | return self |
paul@128 | 1890 | |
paul@126 | 1891 | def __cmp__(self, other): |
paul@129 | 1892 | |
paul@129 | 1893 | """ |
paul@129 | 1894 | The result of comparing this instance with 'other' is, if both instances |
paul@129 | 1895 | are datetime instances, derived from a comparison of the datetimes |
paul@129 | 1896 | converted to UTC. If one or both datetimes cannot be converted to UTC, |
paul@129 | 1897 | the datetimes are compared using the basic temporal comparison which |
paul@129 | 1898 | compares their raw time data. |
paul@129 | 1899 | """ |
paul@129 | 1900 | |
paul@140 | 1901 | this = self |
paul@140 | 1902 | |
paul@140 | 1903 | if this.has_time(): |
paul@128 | 1904 | if isinstance(other, DateTime): |
paul@140 | 1905 | if other.has_time(): |
paul@140 | 1906 | this_utc = this.to_utc() |
paul@140 | 1907 | other_utc = other.to_utc() |
paul@140 | 1908 | if this_utc is not None and other_utc is not None: |
paul@140 | 1909 | return cmp(this_utc.as_tuple(), other_utc.as_tuple()) |
paul@140 | 1910 | else: |
paul@140 | 1911 | other = other.padded() |
paul@140 | 1912 | else: |
paul@140 | 1913 | this = this.padded() |
paul@128 | 1914 | |
paul@128 | 1915 | return Date.__cmp__(this, other) |
paul@126 | 1916 | |
paul@92 | 1917 | def has_time(self): |
paul@140 | 1918 | |
paul@140 | 1919 | """ |
paul@140 | 1920 | Return whether this object has any time information. Objects without |
paul@140 | 1921 | time information can refer to the very start of a day. |
paul@140 | 1922 | """ |
paul@140 | 1923 | |
paul@92 | 1924 | return self.data[3] is not None and self.data[4] is not None |
paul@92 | 1925 | |
paul@128 | 1926 | def time(self): |
paul@128 | 1927 | return self.data[3:] |
paul@128 | 1928 | |
paul@92 | 1929 | def seconds(self): |
paul@92 | 1930 | return self.data[5] |
paul@92 | 1931 | |
paul@92 | 1932 | def time_zone(self): |
paul@92 | 1933 | return self.data[6] |
paul@92 | 1934 | |
paul@93 | 1935 | def set_time_zone(self, value): |
paul@92 | 1936 | self.data[6] = value |
paul@92 | 1937 | |
paul@140 | 1938 | def padded(self, empty_value=0): |
paul@140 | 1939 | |
paul@140 | 1940 | """ |
paul@140 | 1941 | Return a datetime with missing fields defined as being the given |
paul@140 | 1942 | 'empty_value' or 0 if not specified. |
paul@140 | 1943 | """ |
paul@140 | 1944 | |
paul@140 | 1945 | data = [] |
paul@140 | 1946 | for x in self.data[:6]: |
paul@140 | 1947 | if x is None: |
paul@140 | 1948 | data.append(empty_value) |
paul@140 | 1949 | else: |
paul@140 | 1950 | data.append(x) |
paul@140 | 1951 | |
paul@140 | 1952 | data += self.data[6:] |
paul@92 | 1953 | return DateTime(data) |
paul@92 | 1954 | |
paul@93 | 1955 | def to_utc(self): |
paul@93 | 1956 | |
paul@93 | 1957 | """ |
paul@93 | 1958 | Return this object converted to UTC, or None if such a conversion is not |
paul@93 | 1959 | defined. |
paul@93 | 1960 | """ |
paul@93 | 1961 | |
paul@128 | 1962 | if not self.has_time(): |
paul@128 | 1963 | return None |
paul@128 | 1964 | |
paul@93 | 1965 | offset = self.utc_offset() |
paul@93 | 1966 | if offset: |
paul@93 | 1967 | hours, minutes = offset |
paul@93 | 1968 | |
paul@93 | 1969 | # Invert the offset to get the correction. |
paul@93 | 1970 | |
paul@93 | 1971 | hours, minutes = -hours, -minutes |
paul@93 | 1972 | |
paul@93 | 1973 | # Get the components. |
paul@93 | 1974 | |
paul@128 | 1975 | hour, minute, second, zone = self.time() |
paul@93 | 1976 | date = self.as_date() |
paul@93 | 1977 | |
paul@93 | 1978 | # Add the minutes and hours. |
paul@93 | 1979 | |
paul@93 | 1980 | minute += minutes |
paul@103 | 1981 | if minute < 0 or minute > 59: |
paul@103 | 1982 | hour += minute / 60 |
paul@103 | 1983 | minute = minute % 60 |
paul@103 | 1984 | |
paul@103 | 1985 | # NOTE: This makes various assumptions and probably would not work |
paul@103 | 1986 | # NOTE: for general arithmetic. |
paul@93 | 1987 | |
paul@93 | 1988 | hour += hours |
paul@93 | 1989 | if hour < 0: |
paul@93 | 1990 | date = date.previous_day() |
paul@93 | 1991 | hour += 24 |
paul@93 | 1992 | elif hour > 23: |
paul@93 | 1993 | date = date.next_day() |
paul@93 | 1994 | hour -= 24 |
paul@93 | 1995 | |
paul@93 | 1996 | return date.as_datetime(hour, minute, second, "UTC") |
paul@100 | 1997 | |
paul@100 | 1998 | # Cannot convert. |
paul@100 | 1999 | |
paul@93 | 2000 | else: |
paul@93 | 2001 | return None |
paul@93 | 2002 | |
paul@93 | 2003 | def utc_offset(self): |
paul@93 | 2004 | |
paul@93 | 2005 | "Return the UTC offset in hours and minutes." |
paul@93 | 2006 | |
paul@93 | 2007 | zone = self.time_zone() |
paul@95 | 2008 | if not zone: |
paul@95 | 2009 | return None |
paul@93 | 2010 | |
paul@96 | 2011 | # Support explicit UTC zones. |
paul@96 | 2012 | |
paul@96 | 2013 | if zone == "UTC": |
paul@96 | 2014 | return 0, 0 |
paul@96 | 2015 | |
paul@94 | 2016 | # Attempt to return a UTC offset where an explicit offset has been set. |
paul@93 | 2017 | |
paul@94 | 2018 | match = timezone_offset_regexp.match(zone) |
paul@94 | 2019 | if match: |
paul@94 | 2020 | if match.group("sign") == "-": |
paul@93 | 2021 | sign = -1 |
paul@93 | 2022 | else: |
paul@93 | 2023 | sign = 1 |
paul@93 | 2024 | |
paul@94 | 2025 | hours = int(match.group("hours")) * sign |
paul@94 | 2026 | minutes = int(match.group("minutes") or 0) * sign |
paul@94 | 2027 | return hours, minutes |
paul@94 | 2028 | |
paul@102 | 2029 | # Attempt to handle Olson time zone identifiers. |
paul@102 | 2030 | |
paul@102 | 2031 | dt = self.as_olson_datetime() |
paul@102 | 2032 | if dt: |
paul@102 | 2033 | seconds = dt.utcoffset().seconds |
paul@102 | 2034 | hours = seconds / 3600 |
paul@102 | 2035 | minutes = (seconds % 3600) / 60 |
paul@102 | 2036 | return hours, minutes |
paul@102 | 2037 | |
paul@102 | 2038 | # Otherwise return None. |
paul@102 | 2039 | |
paul@93 | 2040 | return None |
paul@93 | 2041 | |
paul@100 | 2042 | def olson_identifier(self): |
paul@100 | 2043 | |
paul@100 | 2044 | "Return the Olson identifier from any zone information." |
paul@100 | 2045 | |
paul@100 | 2046 | zone = self.time_zone() |
paul@100 | 2047 | if not zone: |
paul@100 | 2048 | return None |
paul@100 | 2049 | |
paul@100 | 2050 | # Attempt to match an identifier. |
paul@100 | 2051 | |
paul@100 | 2052 | match = timezone_olson_regexp.match(zone) |
paul@100 | 2053 | if match: |
paul@100 | 2054 | return match.group("olson") |
paul@100 | 2055 | else: |
paul@100 | 2056 | return None |
paul@100 | 2057 | |
paul@102 | 2058 | def _as_olson_datetime(self, hours=None): |
paul@102 | 2059 | |
paul@102 | 2060 | """ |
paul@102 | 2061 | Return a Python datetime object for this datetime interpreted using any |
paul@102 | 2062 | Olson time zone identifier and the given 'hours' offset, raising one of |
paul@102 | 2063 | the pytz exceptions in case of ambiguity. |
paul@102 | 2064 | """ |
paul@102 | 2065 | |
paul@102 | 2066 | olson = self.olson_identifier() |
paul@102 | 2067 | if olson and pytz: |
paul@102 | 2068 | tz = pytz.timezone(olson) |
paul@102 | 2069 | data = self.padded().as_tuple()[:6] |
paul@102 | 2070 | dt = datetime.datetime(*data) |
paul@102 | 2071 | |
paul@102 | 2072 | # With an hours offset, find a time probably in a previously |
paul@102 | 2073 | # applicable time zone. |
paul@102 | 2074 | |
paul@102 | 2075 | if hours is not None: |
paul@102 | 2076 | td = datetime.timedelta(0, hours * 3600) |
paul@102 | 2077 | dt += td |
paul@102 | 2078 | |
paul@102 | 2079 | ldt = tz.localize(dt, None) |
paul@102 | 2080 | |
paul@102 | 2081 | # With an hours offset, adjust the time to define it within the |
paul@102 | 2082 | # previously applicable time zone but at the presumably intended |
paul@102 | 2083 | # position. |
paul@102 | 2084 | |
paul@102 | 2085 | if hours is not None: |
paul@102 | 2086 | ldt -= td |
paul@102 | 2087 | |
paul@102 | 2088 | return ldt |
paul@102 | 2089 | else: |
paul@102 | 2090 | return None |
paul@102 | 2091 | |
paul@102 | 2092 | def as_olson_datetime(self): |
paul@102 | 2093 | |
paul@102 | 2094 | """ |
paul@102 | 2095 | Return a Python datetime object for this datetime interpreted using any |
paul@102 | 2096 | Olson time zone identifier, choosing the time from the zone before the |
paul@102 | 2097 | period of ambiguity. |
paul@102 | 2098 | """ |
paul@102 | 2099 | |
paul@102 | 2100 | try: |
paul@102 | 2101 | return self._as_olson_datetime() |
paul@102 | 2102 | except (pytz.UnknownTimeZoneError, pytz.AmbiguousTimeError): |
paul@103 | 2103 | |
paul@103 | 2104 | # Try again, using an earlier local time and then stepping forward |
paul@103 | 2105 | # in the chosen zone. |
paul@103 | 2106 | # NOTE: Four hours earlier seems reasonable. |
paul@103 | 2107 | |
paul@103 | 2108 | return self._as_olson_datetime(-4) |
paul@102 | 2109 | |
paul@100 | 2110 | def ambiguous(self): |
paul@100 | 2111 | |
paul@100 | 2112 | "Return whether the time is local and ambiguous." |
paul@100 | 2113 | |
paul@102 | 2114 | try: |
paul@102 | 2115 | self._as_olson_datetime() |
paul@102 | 2116 | except (pytz.UnknownTimeZoneError, pytz.AmbiguousTimeError): |
paul@102 | 2117 | return 1 |
paul@100 | 2118 | |
paul@100 | 2119 | return 0 |
paul@100 | 2120 | |
paul@168 | 2121 | class Timespan(ActsAsTimespan, Convertible): |
paul@122 | 2122 | |
paul@122 | 2123 | """ |
paul@122 | 2124 | A period of time which can be compared against others to check for overlaps. |
paul@122 | 2125 | """ |
paul@122 | 2126 | |
paul@122 | 2127 | def __init__(self, start, end): |
paul@122 | 2128 | self.start = start |
paul@122 | 2129 | self.end = end |
paul@122 | 2130 | |
paul@179 | 2131 | # NOTE: Should perhaps catch ambiguous time problems elsewhere. |
paul@179 | 2132 | |
paul@182 | 2133 | if self.ambiguous() and self.start is not None and self.end is not None and start > end: |
paul@179 | 2134 | self.start, self.end = end, start |
paul@179 | 2135 | |
paul@122 | 2136 | def __repr__(self): |
paul@122 | 2137 | return "%s(%r, %r)" % (self.__class__.__name__, self.start, self.end) |
paul@122 | 2138 | |
paul@122 | 2139 | def __hash__(self): |
paul@122 | 2140 | return hash((self.start, self.end)) |
paul@122 | 2141 | |
paul@130 | 2142 | def as_timespan(self): |
paul@130 | 2143 | return self |
paul@130 | 2144 | |
paul@128 | 2145 | def as_limits(self): |
paul@123 | 2146 | return self.start, self.end |
paul@123 | 2147 | |
paul@179 | 2148 | def ambiguous(self): |
paul@182 | 2149 | return self.start is not None and self.start.ambiguous() or self.end is not None and self.end.ambiguous() |
paul@179 | 2150 | |
paul@168 | 2151 | def convert(self, resolution): |
paul@168 | 2152 | return Timespan(*map(self._get_converter(resolution), self.as_limits())) |
paul@168 | 2153 | |
paul@122 | 2154 | def is_before(self, a, b): |
paul@129 | 2155 | |
paul@129 | 2156 | """ |
paul@129 | 2157 | Return whether 'a' is before 'b'. Since the end datetime of one period |
paul@129 | 2158 | may be the same as the start datetime of another period, and yet the |
paul@129 | 2159 | first period is intended to be concluded by the end datetime and not |
paul@129 | 2160 | overlap with the other period, a different test is employed for datetime |
paul@129 | 2161 | comparisons. |
paul@129 | 2162 | """ |
paul@129 | 2163 | |
paul@140 | 2164 | # Datetimes without times can be equal to dates and be considered as |
paul@178 | 2165 | # occurring before those dates. Generally, datetimes should not be |
paul@178 | 2166 | # produced without time information as getDateTime converts such |
paul@178 | 2167 | # datetimes to dates. |
paul@140 | 2168 | |
paul@140 | 2169 | if isinstance(a, DateTime) and (isinstance(b, DateTime) or not a.has_time()): |
paul@122 | 2170 | return a <= b |
paul@122 | 2171 | else: |
paul@122 | 2172 | return a < b |
paul@122 | 2173 | |
paul@122 | 2174 | def __contains__(self, other): |
paul@129 | 2175 | |
paul@129 | 2176 | """ |
paul@129 | 2177 | This instance is considered to contain 'other' if one is not before or |
paul@129 | 2178 | after the other. If this instance overlaps or coincides with 'other', |
paul@129 | 2179 | then 'other' is regarded as belonging to this instance's time period. |
paul@129 | 2180 | """ |
paul@129 | 2181 | |
paul@123 | 2182 | return self == other |
paul@122 | 2183 | |
paul@122 | 2184 | def __cmp__(self, other): |
paul@122 | 2185 | |
paul@122 | 2186 | """ |
paul@122 | 2187 | Return whether this timespan occupies the same period of time as the |
paul@129 | 2188 | 'other'. Timespans are considered less than others if their end points |
paul@129 | 2189 | precede the other's start point, and are considered greater than others |
paul@129 | 2190 | if their start points follow the other's end point. |
paul@122 | 2191 | """ |
paul@122 | 2192 | |
paul@130 | 2193 | if isinstance(other, ActsAsTimespan): |
paul@130 | 2194 | other = other.as_timespan() |
paul@130 | 2195 | |
paul@123 | 2196 | if self.end is not None and other.start is not None and self.is_before(self.end, other.start): |
paul@122 | 2197 | return -1 |
paul@123 | 2198 | elif self.start is not None and other.end is not None and self.is_before(other.end, self.start): |
paul@122 | 2199 | return 1 |
paul@122 | 2200 | else: |
paul@122 | 2201 | return 0 |
paul@122 | 2202 | |
paul@122 | 2203 | else: |
paul@123 | 2204 | if self.end is not None and self.is_before(self.end, other): |
paul@122 | 2205 | return -1 |
paul@140 | 2206 | elif self.start is not None and self.is_before(other, self.start): |
paul@122 | 2207 | return 1 |
paul@122 | 2208 | else: |
paul@122 | 2209 | return 0 |
paul@122 | 2210 | |
paul@123 | 2211 | class TimespanCollection: |
paul@123 | 2212 | |
paul@129 | 2213 | """ |
paul@171 | 2214 | A class providing a list-like interface supporting membership tests at a |
paul@171 | 2215 | particular resolution in order to maintain a collection of non-overlapping |
paul@171 | 2216 | timespans. |
paul@129 | 2217 | """ |
paul@123 | 2218 | |
paul@123 | 2219 | def __init__(self, resolution, values=None): |
paul@168 | 2220 | self.resolution = resolution |
paul@168 | 2221 | self.values = values or [] |
paul@168 | 2222 | |
paul@168 | 2223 | def as_timespan(self): |
paul@168 | 2224 | return Timespan(*self.as_limits()) |
paul@168 | 2225 | |
paul@168 | 2226 | def as_limits(self): |
paul@168 | 2227 | |
paul@168 | 2228 | "Return the earliest and latest points in time for this collection." |
paul@168 | 2229 | |
paul@168 | 2230 | if not self.values: |
paul@168 | 2231 | return None, None |
paul@123 | 2232 | else: |
paul@168 | 2233 | first, last = self.values[0], self.values[-1] |
paul@168 | 2234 | if isinstance(first, ActsAsTimespan): |
paul@168 | 2235 | first = first.as_timespan().start |
paul@168 | 2236 | if isinstance(last, ActsAsTimespan): |
paul@168 | 2237 | last = last.as_timespan().end |
paul@168 | 2238 | return first, last |
paul@123 | 2239 | |
paul@123 | 2240 | def convert(self, value): |
paul@130 | 2241 | if isinstance(value, ActsAsTimespan): |
paul@171 | 2242 | ts = value.as_timespan() |
paul@171 | 2243 | return ts and ts.convert(self.resolution) |
paul@123 | 2244 | else: |
paul@168 | 2245 | return value.convert(self.resolution) |
paul@123 | 2246 | |
paul@123 | 2247 | def __iter__(self): |
paul@123 | 2248 | return iter(self.values) |
paul@123 | 2249 | |
paul@123 | 2250 | def __len__(self): |
paul@123 | 2251 | return len(self.values) |
paul@123 | 2252 | |
paul@123 | 2253 | def __getitem__(self, i): |
paul@123 | 2254 | return self.values[i] |
paul@123 | 2255 | |
paul@123 | 2256 | def __setitem__(self, i, value): |
paul@123 | 2257 | self.values[i] = value |
paul@123 | 2258 | |
paul@123 | 2259 | def __contains__(self, value): |
paul@123 | 2260 | test_value = self.convert(value) |
paul@123 | 2261 | return test_value in self.values |
paul@123 | 2262 | |
paul@123 | 2263 | def append(self, value): |
paul@123 | 2264 | self.values.append(value) |
paul@123 | 2265 | |
paul@123 | 2266 | def insert(self, i, value): |
paul@123 | 2267 | self.values.insert(i, value) |
paul@123 | 2268 | |
paul@123 | 2269 | def pop(self): |
paul@123 | 2270 | return self.values.pop() |
paul@123 | 2271 | |
paul@124 | 2272 | def insert_in_order(self, value): |
paul@171 | 2273 | bisect.insort_left(self, value) |
paul@168 | 2274 | |
paul@93 | 2275 | def getCountry(s): |
paul@92 | 2276 | |
paul@93 | 2277 | "Find a country code in the given string 's'." |
paul@93 | 2278 | |
paul@93 | 2279 | match = country_code_regexp.search(s) |
paul@92 | 2280 | |
paul@93 | 2281 | if match: |
paul@93 | 2282 | return match.group("code") |
paul@93 | 2283 | else: |
paul@93 | 2284 | return None |
paul@67 | 2285 | |
paul@67 | 2286 | def getDate(s): |
paul@67 | 2287 | |
paul@127 | 2288 | "Parse the string 's', extracting and returning a date object." |
paul@127 | 2289 | |
paul@127 | 2290 | dt = getDateTime(s) |
paul@127 | 2291 | if dt is not None: |
paul@127 | 2292 | return dt.as_date() |
paul@127 | 2293 | else: |
paul@127 | 2294 | return None |
paul@123 | 2295 | |
paul@123 | 2296 | def getDateTime(s): |
paul@67 | 2297 | |
paul@140 | 2298 | """ |
paul@140 | 2299 | Parse the string 's', extracting and returning a datetime object where time |
paul@140 | 2300 | information has been given or a date object where time information is |
paul@140 | 2301 | absent. |
paul@140 | 2302 | """ |
paul@67 | 2303 | |
paul@92 | 2304 | m = datetime_regexp.search(s) |
paul@67 | 2305 | if m: |
paul@92 | 2306 | groups = list(m.groups()) |
paul@92 | 2307 | |
paul@94 | 2308 | # Convert date and time data to integer or None. |
paul@92 | 2309 | |
paul@140 | 2310 | return DateTime(map(int_or_none, groups[:6]) + [m.group("zone")]).as_datetime_or_date() |
paul@67 | 2311 | else: |
paul@67 | 2312 | return None |
paul@67 | 2313 | |
paul@217 | 2314 | def getDateFromCalendar(s): |
paul@217 | 2315 | |
paul@217 | 2316 | """ |
paul@217 | 2317 | Parse the iCalendar format string 's', extracting and returning a date |
paul@217 | 2318 | object. |
paul@217 | 2319 | """ |
paul@217 | 2320 | |
paul@217 | 2321 | dt = getDateTimeFromCalendar(s) |
paul@217 | 2322 | if dt is not None: |
paul@217 | 2323 | return dt.as_date() |
paul@217 | 2324 | else: |
paul@217 | 2325 | return None |
paul@217 | 2326 | |
paul@217 | 2327 | def getDateTimeFromCalendar(s): |
paul@217 | 2328 | |
paul@217 | 2329 | """ |
paul@217 | 2330 | Parse the iCalendar format datetime string 's', extracting and returning a |
paul@217 | 2331 | datetime object where time information has been given or a date object where |
paul@217 | 2332 | time information is absent. |
paul@217 | 2333 | """ |
paul@217 | 2334 | |
paul@217 | 2335 | m = datetime_icalendar_regexp.search(s) |
paul@217 | 2336 | if m: |
paul@217 | 2337 | groups = list(m.groups()) |
paul@217 | 2338 | |
paul@217 | 2339 | # Convert date and time data to integer or None. |
paul@217 | 2340 | |
paul@217 | 2341 | return DateTime(map(int_or_none, groups[:6]) + [m.group("utc") and "UTC" or None]).as_datetime_or_date() |
paul@217 | 2342 | else: |
paul@217 | 2343 | return None |
paul@217 | 2344 | |
paul@88 | 2345 | def getDateStrings(s): |
paul@88 | 2346 | |
paul@88 | 2347 | "Parse the string 's', extracting and returning all date strings." |
paul@88 | 2348 | |
paul@88 | 2349 | start = 0 |
paul@88 | 2350 | m = date_regexp.search(s, start) |
paul@88 | 2351 | l = [] |
paul@88 | 2352 | while m: |
paul@88 | 2353 | l.append("-".join(m.groups())) |
paul@88 | 2354 | m = date_regexp.search(s, m.end()) |
paul@88 | 2355 | return l |
paul@88 | 2356 | |
paul@67 | 2357 | def getMonth(s): |
paul@67 | 2358 | |
paul@88 | 2359 | "Parse the string 's', extracting and returning a month object." |
paul@67 | 2360 | |
paul@67 | 2361 | m = month_regexp.search(s) |
paul@67 | 2362 | if m: |
paul@67 | 2363 | return Month(map(int, m.groups())) |
paul@67 | 2364 | else: |
paul@67 | 2365 | return None |
paul@67 | 2366 | |
paul@122 | 2367 | def getCurrentDate(): |
paul@122 | 2368 | |
paul@122 | 2369 | "Return the current date as a (year, month, day) tuple." |
paul@122 | 2370 | |
paul@122 | 2371 | today = datetime.date.today() |
paul@122 | 2372 | return Date((today.year, today.month, today.day)) |
paul@122 | 2373 | |
paul@67 | 2374 | def getCurrentMonth(): |
paul@67 | 2375 | |
paul@67 | 2376 | "Return the current month as a (year, month) tuple." |
paul@67 | 2377 | |
paul@67 | 2378 | today = datetime.date.today() |
paul@67 | 2379 | return Month((today.year, today.month)) |
paul@67 | 2380 | |
paul@67 | 2381 | def getCurrentYear(): |
paul@67 | 2382 | |
paul@67 | 2383 | "Return the current year." |
paul@67 | 2384 | |
paul@67 | 2385 | today = datetime.date.today() |
paul@67 | 2386 | return today.year |
paul@67 | 2387 | |
paul@184 | 2388 | # Location-related functions. |
paul@184 | 2389 | |
paul@184 | 2390 | class Reference: |
paul@184 | 2391 | |
paul@184 | 2392 | "A map reference." |
paul@184 | 2393 | |
paul@184 | 2394 | def __init__(self, degrees, minutes=0, seconds=0): |
paul@184 | 2395 | self.degrees = degrees |
paul@184 | 2396 | self.minutes = minutes |
paul@184 | 2397 | self.seconds = seconds |
paul@184 | 2398 | |
paul@184 | 2399 | def __repr__(self): |
paul@230 | 2400 | return "Reference(%d, %d, %f)" % (self.degrees, self.minutes, self.seconds) |
paul@230 | 2401 | |
paul@230 | 2402 | def __str__(self): |
paul@230 | 2403 | return "%d:%d:%f" % (self.degrees, self.minutes, self.seconds) |
paul@184 | 2404 | |
paul@184 | 2405 | def __add__(self, other): |
paul@184 | 2406 | if not isinstance(other, Reference): |
paul@184 | 2407 | return NotImplemented |
paul@184 | 2408 | else: |
paul@184 | 2409 | s = sign(self.degrees) |
paul@184 | 2410 | o = sign(other.degrees) |
paul@184 | 2411 | carry, seconds = adc(s * self.seconds, o * other.seconds) |
paul@184 | 2412 | carry, minutes = adc(s * self.minutes, o * other.minutes + carry) |
paul@184 | 2413 | return Reference(self.degrees + other.degrees + carry, minutes, seconds) |
paul@184 | 2414 | |
paul@184 | 2415 | def __sub__(self, other): |
paul@184 | 2416 | if not isinstance(other, Reference): |
paul@184 | 2417 | return NotImplemented |
paul@184 | 2418 | else: |
paul@184 | 2419 | return self.__add__(Reference(-other.degrees, other.minutes, other.seconds)) |
paul@184 | 2420 | |
paul@185 | 2421 | def _compare(self, op, other): |
paul@185 | 2422 | if not isinstance(other, Reference): |
paul@185 | 2423 | return NotImplemented |
paul@185 | 2424 | else: |
paul@185 | 2425 | return op(self.to_degrees(), other.to_degrees()) |
paul@185 | 2426 | |
paul@185 | 2427 | def __eq__(self, other): |
paul@185 | 2428 | return self._compare(operator.eq, other) |
paul@185 | 2429 | |
paul@185 | 2430 | def __ne__(self, other): |
paul@185 | 2431 | return self._compare(operator.ne, other) |
paul@185 | 2432 | |
paul@185 | 2433 | def __lt__(self, other): |
paul@185 | 2434 | return self._compare(operator.lt, other) |
paul@185 | 2435 | |
paul@185 | 2436 | def __le__(self, other): |
paul@185 | 2437 | return self._compare(operator.le, other) |
paul@185 | 2438 | |
paul@185 | 2439 | def __gt__(self, other): |
paul@185 | 2440 | return self._compare(operator.gt, other) |
paul@185 | 2441 | |
paul@185 | 2442 | def __ge__(self, other): |
paul@185 | 2443 | return self._compare(operator.ge, other) |
paul@185 | 2444 | |
paul@184 | 2445 | def to_degrees(self): |
paul@184 | 2446 | return sign(self.degrees) * (abs(self.degrees) + self.minutes / 60.0 + self.seconds / 3600.0) |
paul@184 | 2447 | |
paul@184 | 2448 | def to_pixels(self, scale): |
paul@184 | 2449 | return self.to_degrees() * scale |
paul@184 | 2450 | |
paul@184 | 2451 | def adc(x, y): |
paul@184 | 2452 | result = x + y |
paul@184 | 2453 | return divmod(result, 60) |
paul@184 | 2454 | |
paul@184 | 2455 | def getPositionForReference(latitude, longitude, map_y, map_x, map_x_scale, map_y_scale): |
paul@184 | 2456 | return (longitude - map_x).to_pixels(map_x_scale), (latitude - map_y).to_pixels(map_y_scale) |
paul@184 | 2457 | |
paul@184 | 2458 | def getPositionForCentrePoint(position, map_x_scale, map_y_scale): |
paul@184 | 2459 | x, y = position |
paul@184 | 2460 | return x - map_x_scale / 2.0, y - map_y_scale / 2.0 |
paul@184 | 2461 | |
paul@184 | 2462 | def getMapReference(value): |
paul@184 | 2463 | |
paul@184 | 2464 | "Return a map reference by parsing the given 'value'." |
paul@184 | 2465 | |
paul@230 | 2466 | if value.find(":") != -1: |
paul@230 | 2467 | return getMapReferenceFromDMS(value) |
paul@230 | 2468 | else: |
paul@230 | 2469 | return getMapReferenceFromDecimal(value) |
paul@230 | 2470 | |
paul@230 | 2471 | def getMapReferenceFromDMS(value): |
paul@230 | 2472 | |
paul@230 | 2473 | """ |
paul@230 | 2474 | Return a map reference by parsing the given 'value' expressed as degrees, |
paul@230 | 2475 | minutes, seconds. |
paul@230 | 2476 | """ |
paul@230 | 2477 | |
paul@230 | 2478 | values = value.split(":") |
paul@230 | 2479 | values = map(int, values[:2]) + map(float, values[2:3]) |
paul@230 | 2480 | return Reference(*values) |
paul@184 | 2481 | |
paul@229 | 2482 | def getMapReferenceFromDecimal(value): |
paul@229 | 2483 | |
paul@229 | 2484 | "Return a map reference by parsing the given 'value' in decimal degrees." |
paul@229 | 2485 | |
paul@229 | 2486 | value = float(value) |
paul@229 | 2487 | degrees, remainder = divmod(abs(value * 3600), 3600) |
paul@229 | 2488 | minutes, seconds = divmod(remainder, 60) |
paul@229 | 2489 | return Reference(sign(value) * degrees, minutes, seconds) |
paul@184 | 2490 | |
paul@19 | 2491 | # User interface functions. |
paul@19 | 2492 | |
paul@55 | 2493 | def getParameter(request, name, default=None): |
paul@92 | 2494 | |
paul@92 | 2495 | """ |
paul@92 | 2496 | Using the given 'request', return the value of the parameter with the given |
paul@92 | 2497 | 'name', returning the optional 'default' (or None) if no value was supplied |
paul@92 | 2498 | in the 'request'. |
paul@92 | 2499 | """ |
paul@92 | 2500 | |
paul@110 | 2501 | return get_form(request).get(name, [default])[0] |
paul@23 | 2502 | |
paul@58 | 2503 | def getQualifiedParameter(request, calendar_name, argname, default=None): |
paul@92 | 2504 | |
paul@92 | 2505 | """ |
paul@92 | 2506 | Using the given 'request', 'calendar_name' and 'argname', retrieve the |
paul@92 | 2507 | value of the qualified parameter, returning the optional 'default' (or None) |
paul@92 | 2508 | if no value was supplied in the 'request'. |
paul@92 | 2509 | """ |
paul@92 | 2510 | |
paul@58 | 2511 | argname = getQualifiedParameterName(calendar_name, argname) |
paul@58 | 2512 | return getParameter(request, argname, default) |
paul@58 | 2513 | |
paul@58 | 2514 | def getQualifiedParameterName(calendar_name, argname): |
paul@92 | 2515 | |
paul@92 | 2516 | """ |
paul@92 | 2517 | Return the qualified parameter name using the given 'calendar_name' and |
paul@92 | 2518 | 'argname'. |
paul@92 | 2519 | """ |
paul@92 | 2520 | |
paul@58 | 2521 | if calendar_name is None: |
paul@58 | 2522 | return argname |
paul@58 | 2523 | else: |
paul@58 | 2524 | return "%s-%s" % (calendar_name, argname) |
paul@58 | 2525 | |
paul@122 | 2526 | def getParameterDate(arg): |
paul@122 | 2527 | |
paul@122 | 2528 | "Interpret 'arg', recognising keywords and simple arithmetic operations." |
paul@122 | 2529 | |
paul@122 | 2530 | n = None |
paul@122 | 2531 | |
paul@128 | 2532 | if arg is None: |
paul@128 | 2533 | return None |
paul@128 | 2534 | |
paul@128 | 2535 | elif arg.startswith("current"): |
paul@122 | 2536 | date = getCurrentDate() |
paul@122 | 2537 | if len(arg) > 8: |
paul@122 | 2538 | n = int(arg[7:]) |
paul@122 | 2539 | |
paul@122 | 2540 | elif arg.startswith("yearstart"): |
paul@122 | 2541 | date = Date((getCurrentYear(), 1, 1)) |
paul@122 | 2542 | if len(arg) > 10: |
paul@122 | 2543 | n = int(arg[9:]) |
paul@122 | 2544 | |
paul@122 | 2545 | elif arg.startswith("yearend"): |
paul@122 | 2546 | date = Date((getCurrentYear(), 12, 31)) |
paul@122 | 2547 | if len(arg) > 8: |
paul@122 | 2548 | n = int(arg[7:]) |
paul@122 | 2549 | |
paul@122 | 2550 | else: |
paul@122 | 2551 | date = getDate(arg) |
paul@122 | 2552 | |
paul@122 | 2553 | if n is not None: |
paul@122 | 2554 | date = date.day_update(n) |
paul@122 | 2555 | |
paul@122 | 2556 | return date |
paul@122 | 2557 | |
paul@19 | 2558 | def getParameterMonth(arg): |
paul@67 | 2559 | |
paul@67 | 2560 | "Interpret 'arg', recognising keywords and simple arithmetic operations." |
paul@67 | 2561 | |
paul@19 | 2562 | n = None |
paul@19 | 2563 | |
paul@128 | 2564 | if arg is None: |
paul@128 | 2565 | return None |
paul@128 | 2566 | |
paul@128 | 2567 | elif arg.startswith("current"): |
paul@19 | 2568 | date = getCurrentMonth() |
paul@19 | 2569 | if len(arg) > 8: |
paul@19 | 2570 | n = int(arg[7:]) |
paul@19 | 2571 | |
paul@19 | 2572 | elif arg.startswith("yearstart"): |
paul@67 | 2573 | date = Month((getCurrentYear(), 1)) |
paul@19 | 2574 | if len(arg) > 10: |
paul@19 | 2575 | n = int(arg[9:]) |
paul@19 | 2576 | |
paul@19 | 2577 | elif arg.startswith("yearend"): |
paul@67 | 2578 | date = Month((getCurrentYear(), 12)) |
paul@19 | 2579 | if len(arg) > 8: |
paul@19 | 2580 | n = int(arg[7:]) |
paul@19 | 2581 | |
paul@19 | 2582 | else: |
paul@19 | 2583 | date = getMonth(arg) |
paul@19 | 2584 | |
paul@19 | 2585 | if n is not None: |
paul@67 | 2586 | date = date.month_update(n) |
paul@19 | 2587 | |
paul@19 | 2588 | return date |
paul@19 | 2589 | |
paul@122 | 2590 | def getFormDate(request, calendar_name, argname): |
paul@122 | 2591 | |
paul@122 | 2592 | """ |
paul@122 | 2593 | Return the date from the 'request' for the calendar with the given |
paul@122 | 2594 | 'calendar_name' using the parameter having the given 'argname'. |
paul@122 | 2595 | """ |
paul@122 | 2596 | |
paul@122 | 2597 | arg = getQualifiedParameter(request, calendar_name, argname) |
paul@128 | 2598 | return getParameterDate(arg) |
paul@122 | 2599 | |
paul@19 | 2600 | def getFormMonth(request, calendar_name, argname): |
paul@67 | 2601 | |
paul@67 | 2602 | """ |
paul@67 | 2603 | Return the month from the 'request' for the calendar with the given |
paul@67 | 2604 | 'calendar_name' using the parameter having the given 'argname'. |
paul@67 | 2605 | """ |
paul@67 | 2606 | |
paul@58 | 2607 | arg = getQualifiedParameter(request, calendar_name, argname) |
paul@128 | 2608 | return getParameterMonth(arg) |
paul@19 | 2609 | |
paul@127 | 2610 | def getFormDateTriple(request, yeararg, montharg, dayarg): |
paul@127 | 2611 | |
paul@127 | 2612 | """ |
paul@127 | 2613 | Return the date from the 'request' for the calendar with the given |
paul@127 | 2614 | 'calendar_name' using the parameters having the given 'yeararg', 'montharg' |
paul@127 | 2615 | and 'dayarg' names. |
paul@127 | 2616 | """ |
paul@127 | 2617 | |
paul@127 | 2618 | year = getParameter(request, yeararg) |
paul@127 | 2619 | month = getParameter(request, montharg) |
paul@127 | 2620 | day = getParameter(request, dayarg) |
paul@127 | 2621 | if year and month and day: |
paul@127 | 2622 | return Date((int(year), int(month), int(day))) |
paul@19 | 2623 | else: |
paul@19 | 2624 | return None |
paul@19 | 2625 | |
paul@23 | 2626 | def getFormMonthPair(request, yeararg, montharg): |
paul@67 | 2627 | |
paul@67 | 2628 | """ |
paul@67 | 2629 | Return the month from the 'request' for the calendar with the given |
paul@67 | 2630 | 'calendar_name' using the parameters having the given 'yeararg' and |
paul@67 | 2631 | 'montharg' names. |
paul@67 | 2632 | """ |
paul@67 | 2633 | |
paul@23 | 2634 | year = getParameter(request, yeararg) |
paul@23 | 2635 | month = getParameter(request, montharg) |
paul@23 | 2636 | if year and month: |
paul@67 | 2637 | return Month((int(year), int(month))) |
paul@23 | 2638 | else: |
paul@23 | 2639 | return None |
paul@23 | 2640 | |
paul@122 | 2641 | def getFullDateLabel(request, date): |
paul@122 | 2642 | |
paul@122 | 2643 | """ |
paul@122 | 2644 | Return the full month plus year label using the given 'request' and |
paul@122 | 2645 | 'year_month'. |
paul@122 | 2646 | """ |
paul@122 | 2647 | |
paul@128 | 2648 | if not date: |
paul@128 | 2649 | return "" |
paul@128 | 2650 | |
paul@122 | 2651 | _ = request.getText |
paul@122 | 2652 | year, month, day = date.as_tuple()[:3] |
paul@125 | 2653 | start_weekday, number_of_days = date.month_properties() |
paul@125 | 2654 | weekday = (start_weekday + day - 1) % 7 |
paul@125 | 2655 | day_label = _(getDayLabel(weekday)) |
paul@122 | 2656 | month_label = _(getMonthLabel(month)) |
paul@122 | 2657 | return "%s %s %s %s" % (day_label, day, month_label, year) |
paul@122 | 2658 | |
paul@114 | 2659 | def getFullMonthLabel(request, year_month): |
paul@114 | 2660 | |
paul@114 | 2661 | """ |
paul@114 | 2662 | Return the full month plus year label using the given 'request' and |
paul@114 | 2663 | 'year_month'. |
paul@114 | 2664 | """ |
paul@114 | 2665 | |
paul@128 | 2666 | if not year_month: |
paul@128 | 2667 | return "" |
paul@128 | 2668 | |
paul@114 | 2669 | _ = request.getText |
paul@122 | 2670 | year, month = year_month.as_tuple()[:2] |
paul@114 | 2671 | month_label = _(getMonthLabel(month)) |
paul@114 | 2672 | return "%s %s" % (month_label, year) |
paul@114 | 2673 | |
paul@67 | 2674 | # Page-related functions. |
paul@67 | 2675 | |
paul@19 | 2676 | def getPrettyPageName(page): |
paul@19 | 2677 | |
paul@19 | 2678 | "Return a nicely formatted title/name for the given 'page'." |
paul@19 | 2679 | |
paul@117 | 2680 | title = page.split_title(force=1) |
paul@55 | 2681 | return getPrettyTitle(title) |
paul@55 | 2682 | |
paul@27 | 2683 | def linkToPage(request, page, text, query_string=None): |
paul@27 | 2684 | |
paul@27 | 2685 | """ |
paul@27 | 2686 | Using 'request', return a link to 'page' with the given link 'text' and |
paul@27 | 2687 | optional 'query_string'. |
paul@27 | 2688 | """ |
paul@27 | 2689 | |
paul@27 | 2690 | text = wikiutil.escape(text) |
paul@117 | 2691 | return page.link_to_raw(request, text, query_string) |
paul@27 | 2692 | |
paul@219 | 2693 | def linkToResource(url, request, text, query_string=None): |
paul@219 | 2694 | |
paul@219 | 2695 | """ |
paul@219 | 2696 | Using 'request', return a link to 'url' with the given link 'text' and |
paul@219 | 2697 | optional 'query_string'. |
paul@219 | 2698 | """ |
paul@219 | 2699 | |
paul@219 | 2700 | if query_string: |
paul@219 | 2701 | query_string = wikiutil.makeQueryString(query_string) |
paul@219 | 2702 | url = "%s?%s" % (url, query_string) |
paul@219 | 2703 | |
paul@219 | 2704 | formatter = request.page and getattr(request.page, "formatter", None) or request.html_formatter |
paul@219 | 2705 | |
paul@219 | 2706 | output = [] |
paul@219 | 2707 | output.append(formatter.url(1, url)) |
paul@219 | 2708 | output.append(formatter.text(text)) |
paul@219 | 2709 | output.append(formatter.url(0)) |
paul@219 | 2710 | return "".join(output) |
paul@219 | 2711 | |
paul@88 | 2712 | def getFullPageName(parent, title): |
paul@88 | 2713 | |
paul@88 | 2714 | """ |
paul@88 | 2715 | Return a full page name from the given 'parent' page (can be empty or None) |
paul@88 | 2716 | and 'title' (a simple page name). |
paul@88 | 2717 | """ |
paul@88 | 2718 | |
paul@88 | 2719 | if parent: |
paul@88 | 2720 | return "%s/%s" % (parent.rstrip("/"), title) |
paul@88 | 2721 | else: |
paul@88 | 2722 | return title |
paul@88 | 2723 | |
paul@88 | 2724 | def fillEventPageFromTemplate(template_page, new_page, event_details, category_pagenames): |
paul@88 | 2725 | |
paul@88 | 2726 | """ |
paul@88 | 2727 | Using the given 'template_page', complete the 'new_page' by copying the |
paul@88 | 2728 | template and adding the given 'event_details' (a dictionary of event |
paul@88 | 2729 | fields), setting also the 'category_pagenames' to define category |
paul@88 | 2730 | membership. |
paul@88 | 2731 | """ |
paul@88 | 2732 | |
paul@88 | 2733 | event_page = EventPage(template_page) |
paul@88 | 2734 | new_event_page = EventPage(new_page) |
paul@88 | 2735 | new_event_page.copyPage(event_page) |
paul@88 | 2736 | |
paul@88 | 2737 | if new_event_page.getFormat() == "wiki": |
paul@88 | 2738 | new_event = Event(new_event_page, event_details) |
paul@88 | 2739 | new_event_page.setEvents([new_event]) |
paul@88 | 2740 | new_event_page.setCategoryMembership(category_pagenames) |
paul@88 | 2741 | new_event_page.saveChanges() |
paul@88 | 2742 | |
paul@10 | 2743 | # vim: tabstop=4 expandtab shiftwidth=4 |