terom@29: terom@29: """ terom@29: URL mapping for the irclogs.qmsk.net site terom@29: """ terom@29: terom@36: import re terom@36: terom@29: # our own handlers terom@29: import handlers terom@29: terom@36: # mapper terom@36: from lib import map terom@29: terom@36: class URLError (Exception) : terom@29: """ terom@36: Error with an URL definition terom@29: """ terom@29: terom@36: pass terom@29: terom@36: class Label (object) : terom@36: """ terom@36: Base class for URL labels (i.e. the segments of the URL between /s) terom@36: """ terom@36: terom@36: @staticmethod terom@36: def parse (mask, defaults) : terom@36: """ terom@36: Parse the given label-segment, and return a *Label instance terom@36: """ terom@36: terom@36: # empty? terom@36: if not mask : terom@36: return EmptyLabel() terom@36: terom@36: # simple value? terom@36: match = SimpleValueLabel.EXPR.match(mask) terom@36: terom@36: if match : terom@36: # key terom@36: key = match.group('key') terom@36: terom@36: # default? terom@36: default = defaults.get(key) terom@36: terom@36: # build terom@36: return SimpleValueLabel(key, default) terom@36: terom@36: # static? terom@36: match = StaticLabel.EXPR.match(mask) terom@36: terom@36: if match : terom@36: return StaticLabel(match.group('name')) terom@36: terom@36: # invalid terom@36: raise URLError("Invalid label: %r" % (mask, )) terom@36: terom@36: terom@36: class EmptyLabel (Label) : terom@36: """ terom@36: An empty label, i.e. just a slash in the URL terom@36: """ terom@36: terom@36: def __eq__ (self, other) : terom@36: """ terom@36: Just compares type terom@36: """ terom@36: terom@36: return isinstance(other, EmptyLabel) terom@36: terom@36: def __str__ (self) : terom@36: return '' terom@36: terom@36: class StaticLabel (Label) : terom@36: """ terom@36: A simple literal Label, used for fixed terms in the URL terom@36: """ terom@36: terom@36: EXPR = re.compile(r'^(?P[a-zA-Z_.-]+)$') terom@36: terom@36: def __init__ (self, name) : terom@36: """ terom@36: The given name is the literal name of this label terom@36: """ terom@36: terom@36: self.name = name terom@36: terom@36: def __eq__ (self, other) : terom@36: """ terom@36: Compares names terom@36: """ terom@36: terom@36: return isinstance(other, StaticLabel) and self.name == other.name terom@36: terom@36: def __str__ (self) : terom@36: return self.name terom@36: terom@36: class ValueLabel (Label) : terom@36: """ terom@36: A label with a key and a value terom@36: """ terom@36: terom@36: def __init__ (self, key, default) : terom@36: """ terom@36: Set the key and default value. Default value may be None if there is no default value defined terom@36: """ terom@36: terom@36: self.key = key terom@36: self.default = default terom@36: terom@36: def __eq__ (self, other) : terom@36: """ terom@36: Compares keys terom@36: """ terom@36: terom@36: return isinstance(other, ValueLabel) and self.key == other.key terom@36: terom@36: class SimpleValueLabel (ValueLabel) : terom@36: """ terom@36: A label that has a name and a simple string value terom@36: """ terom@36: terom@36: EXPR = re.compile(r'^\{(?P[a-zA-Z_][a-zA-Z0-9_]*)\}$') terom@36: terom@36: def __init__ (self, key, default) : terom@36: """ terom@36: The given key is the name of this label's value terom@36: """ terom@36: terom@36: super(SimpleValueLabel, self).__init__(key, default) terom@36: terom@36: def __str__ (self) : terom@36: if self.default : terom@36: return '{%s=%s}' % (self.key, self.default) terom@36: terom@36: else : terom@36: return '{%s}' % (self.key, ) terom@36: terom@36: class URL (object) : terom@36: """ terom@36: Represents a specific URL terom@36: """ terom@36: terom@36: def __init__ (self, url_mask, handler, **defaults) : terom@36: """ terom@36: Create an URL with the given url mask, handler, and default values terom@36: """ terom@36: terom@36: # store terom@36: self.url_mask = url_mask terom@36: self.handler = handler terom@36: self.defaults = defaults terom@36: terom@36: # build our labels terom@36: self.label_path = [Label.parse(mask, defaults) for mask in url_mask.split('/')] terom@36: terom@36: def get_label_path (self) : terom@36: """ terom@36: Returns a list containing the labels in this url terom@36: """ terom@36: terom@36: # copy self.label_path terom@36: return list(self.label_path) terom@36: terom@36: def execute (self, request, xxx) : terom@36: """ terom@36: Invoke the handler with the correct parameters terom@36: """ terom@36: terom@36: xxx terom@36: terom@36: def __str__ (self) : terom@36: return '/'.join(str(label) for label in self.label_path) terom@36: terom@36: def __repr__ (self) : terom@36: return "URL(%r, %r)" % (str(self), self.handler) terom@36: terom@36: class URLNode (object) : terom@36: """ terom@36: Represents a node in the URLTree terom@36: """ terom@36: terom@36: def __init__ (self, parent, label) : terom@36: """ terom@36: Initialize with the given parent and label, empty children dict terom@36: """ terom@36: terom@36: # the parent URLNode terom@36: self.parent = parent terom@36: terom@36: # this node's Label terom@36: self.label = label terom@36: terom@36: # list of child URLNodes terom@36: self.children = [] terom@36: terom@36: # this node's URL, set by add_url for an empty label_path terom@36: self.url = None terom@36: terom@36: def _build_child (self, label) : terom@36: """ terom@36: Build, insert and return a new child Node terom@36: """ terom@36: terom@36: # build new child terom@36: child = URLNode(self, label) terom@36: terom@36: # add to children terom@36: self.children.append(child) terom@36: terom@36: # return terom@36: return child terom@36: terom@36: def add_url (self, url, label_path) : terom@36: """ terom@36: Add a URL object to this node under the given path. Uses recursion to process the path. terom@36: terom@36: The label_path argument is a (partial) label path as returned by URL.get_label_path. terom@36: terom@36: If label_path is empty (len zero, or begins with EmptyLabel), then the given url is assigned to this node, if no terom@36: url was assigned before. terom@36: """ terom@36: terom@36: # matches this node? terom@36: if not label_path or isinstance(label_path[0], EmptyLabel) : terom@36: if self.url : terom@36: raise URLError(url, "node already defined") terom@36: terom@36: else : terom@36: # set terom@36: self.url = url terom@36: terom@36: else : terom@36: # pop child label from label_path terom@36: child_label = label_path.pop(0) terom@36: terom@36: # look for the child to recurse into terom@36: child = None terom@36: terom@36: # look for an existing child with that label terom@36: for child in self.children : terom@36: if child.label == child_label : terom@36: # found, use this terom@36: break terom@36: terom@36: else : terom@36: # build a new child terom@36: child = self._build_child(child_label) terom@36: terom@36: # recurse to handle the rest of the label_path terom@36: child.add_url(url, label_path) terom@36: terom@36: def match_label (self, label) : terom@36: """ terom@36: Match our label mask against the given label value. terom@36: terom@36: Returns either False (no match), True (matched, no value) or a (key, value) pair. terom@36: """ terom@36: terom@36: # simple mask terom@36: if self.label.beginswith('{') and self.label.endswith('}') : terom@36: value_name = self.label.strip('{}') terom@36: terom@36: return (value_name, label) terom@36: terom@36: # literal mask terom@36: elif self.label == label : terom@36: return True terom@36: terom@36: else : terom@36: return False terom@36: terom@36: def match (self, path, label_path) : terom@36: """ terom@36: Locate the URL object corresponding to the given label_path value under this node, with the given path terom@36: containing the previously matched label values terom@36: """ terom@36: terom@36: # empty label_path? terom@36: if not label_path or not label_path[0] : terom@36: # we wanted this node terom@36: if self.url : terom@36: # this URL is the best match terom@36: return [self] terom@36: terom@36: elif self.children : terom@36: # continue testing our children terom@36: label = None terom@36: terom@36: else : terom@36: # incomplete URL terom@36: raise URLError(url, "no URL handler defined for this Node") terom@36: terom@36: else : terom@36: # pop our child label from the label path terom@36: label = label_path.pop(0) terom@36: terom@36: # build a list of matching children terom@36: matches = [] terom@36: terom@36: # recurse through our children terom@36: for child in self.children : terom@36: matches.append(child.match(label_path)) terom@36: terom@36: # return the list of matching children terom@36: return matches terom@36: terom@36: def dump (self, indent=0) : terom@36: """ terom@36: Returns a multi-line string representation of this Node terom@36: """ terom@36: terom@36: return '\n'.join([ terom@36: "%-45s%s" % ( terom@36: ' '*indent + str(self.label) + ('/' if self.children else ''), terom@36: (' -> %r' % self.url) if self.url else '' terom@36: ) terom@36: ] + [ terom@36: child.dump(indent + 4) for child in self.children terom@36: ]) terom@36: terom@36: def __str__ (self) : terom@36: return "%s/[%s]" % (self.label, ','.join(str(child) for child in self.children)) terom@36: terom@36: class URLTree (map.Mapper) : terom@36: """ terom@36: Map requests to handlers, using a defined tree of URLs terom@36: """ terom@36: terom@36: def __init__ (self, url_list) : terom@36: """ terom@36: Initialize the tree using the given list of URLs terom@36: """ terom@36: terom@36: # root node terom@36: self.root = URLNode(None, EmptyLabel()) terom@36: terom@36: # just add each URL terom@36: for url in url_list : terom@36: self.add_url(url) terom@36: terom@36: def add_url (self, url) : terom@36: """ terom@36: Adds the given URL to the tree. The URL must begin with a root slash. terom@36: """ terom@36: # get url's label path terom@36: path = url.get_label_path() terom@36: terom@36: # should begin with root terom@36: root_label = path.pop(0) terom@36: assert root_label == self.root.label, "URL must begin with root" terom@36: terom@36: # add to root terom@36: self.root.add_url(url, path) terom@36: terom@36: def match (self, url) : terom@36: """ terom@36: Returns the URL object best corresponding to the given url terom@36: """ terom@36: terom@36: # normalize the URL terom@36: url = os.path.normpath(url) terom@36: terom@36: # split it into labels terom@36: label_path = url.split('/') terom@36: terom@36: # just match starting at root terom@36: return self.root.match(label_path) terom@36: terom@36: def handle_request (self, request) : terom@36: """ terom@36: Looks up the request's URL, and invokes its handler terom@36: """ terom@36: terom@36: # get the request's URL path terom@36: url = self.match(request.get_page_name()) terom@36: terom@36: # XXX: figure out the argument values... terom@36: terom@36: # let the URL handle it terom@36: url.execute(request, xxx) terom@36: terom@36: # urls terom@36: index = URL( '/', handlers.index ) terom@36: channel_view = URL( '/channel/{channel}', handlers.channel_view ) terom@36: channel_last = URL( '/channel/{channel}/last/{count}/{format}', handlers.channel_last, count=100, format="html" ) terom@36: channel_search = URL( '/channel/{channel}/search', handlers.channel_search ) terom@36: terom@36: # mapper terom@36: mapper = URLTree([index, channel_view, channel_last, channel_search]) terom@36: