Debian Codegraph @

doc/s5/ep2008/atom.py

raw
1 # ET is 80's!
2 #import elementtree as etree
3 # LXML is 00's!
4 from lxml import etree
5 from lxml.etree import tostring
6 #from dateutil.parser import parse as parse_date
7 from datetime import datetime
8 import uuid
9 import cgi
10 import copy
11
12 __all__ = [
13 'ATOM', 'atom_ns', 'Element', 'tostring']
14
15 ATOM_NAMESPACE = atom_ns = 'http://www.w3.org/2005/Atom'
16 app_ns = 'http://www.w3.org/2007/app'
17 xhtml_ns = 'http://www.w3.org/1999/xhtml'
18
19 nsmap = {'': atom_ns, 'app': app_ns}
20
21 _rel_alternate_xpath = etree.XPath(
22 "./atom:link[not(@rel) or @rel = 'alternate']",
23 namespaces=dict(atom=atom_ns))
24 _rel_other_xpath = etree.XPath(
25 "./atom:link[@rel = $rel]",
26 namespaces=dict(atom=atom_ns))
27
28
29
30 class AtomLookup(etree.CustomElementClassLookup):
31 _elements = {}
32 _app_elements = {}
33
34 def lookup(self, node_type, document, namespace, name):
35 if node_type == 'element':
36 if namespace == atom_ns:
37 return self._elements.get(name, AtomElement)
38 elif namespace == app_ns:
39 return self._app_elements.get(name, APPElement)
40 ## FIXME: is this default good?
41 return AtomElement
42 # Otherwise normal lookup
43 return None
44
45 atom_parser = etree.XMLParser()
46 atom_parser.setElementClassLookup(AtomLookup())
47
48 def parse(input):
49 return etree.parse(input, atom_parser)
50
51 def ATOM(atom):
52 """
53 Parse an Atom document
54 """
55 return etree.XML(atom, atom_parser)
56
57 def Element(tag, *args, **kw):
58 """
59 Create an Atom element. Adds the Atom namespace if no namespace
60 is given.
61 """
62 if '{' not in tag:
63 # No namespace means the atom namespace
64 tag = '{%s}%s' % (atom_ns, tag)
65 return atom_parser.makeelement(tag, *args, **kw)
66
67 def _strftime(d):
68 """
69 Format a date the way Atom likes it (RFC3339?)
70 """
71 return d.strftime('%Y-%m-%dT%H:%M:%SZ%z')
72
73 ## try:
74 ## from lxml import builder
75 ## except ImportError:
76 ## pass
77 ## else:
78 ## E = builder.ElementMaker(parser=atom_parser,
79 ## typemap={datetime: lambda e, v: _strftime(v)})
80 from lxml import builder
81 E = builder.ElementMaker(#parser=atom_parser,
82 typemap={datetime: lambda e, v: _strftime(v)})
83 __all__.append('E')
84
85 class NoDefault:
86 pass
87
88 class _LiveList(list):
89 """
90 This list calls on_add or on_remove whenever the list is modified.
91 """
92 on_add = on_remove = None
93 name = None
94 def __init__(self, *args, **kw):
95 on_add = on_remove = name = None
96 if 'on_add' in kw:
97 on_add = kw.pop('on_add')
98 if 'on_remove' in kw:
99 on_remove = kw.pop('on_remove')
100 if 'name' in kw:
101 name = kw.pop('name')
102 list.__init__(self, *args, **kw)
103 self.on_add = on_add
104 self.on_remove = on_remove
105 self.name = name
106 def _make_list(self, obj):
107 if not isinstance(obj, (list, tuple)):
108 obj = list(obj)
109 return obj
110 def _do_add(self, items):
111 if self.on_add is not None:
112 for item in items:
113 self.on_add(self, item)
114 def _do_remove(self, items):
115 if self.on_remove is not None:
116 for item in items:
117 self.on_remove(self, item)
118 def __setslice__(self, i, j, other):
119 other = self._make_list(other)
120 old = self[i:j]
121 list.__setslice__(self, i, j, other)
122 self._do_remove(old)
123 self._do_add(other)
124 def __delslice__(self, i, j):
125 old = self[i:j]
126 list.__delslice__(self, i, j)
127 self._do_remove(old)
128 def __iadd__(self, other):
129 other = self._make_list(other)
130 list.__iadd__(self, other)
131 self._do_add(other)
132 def __imul__(self, n):
133 while n > 0:
134 self += self
135 n -= 1
136 def append(self, item):
137 list.append(self, item)
138 self._do_add([item])
139 def insert(self, i, item):
140 list.insert(self, i, item)
141 self._do_add([item])
142 def pop(self, i=-1):
143 item = self[i]
144 result = list.pop(self, i)
145 self._do_remove([item])
146 return result
147 def remove(self, item):
148 list.remove(self, item)
149 self._do_remove([item])
150 def extend(self, other):
151 for item in other:
152 self.append(item)
153 def __repr__(self):
154 name = self.name
155 if name is None:
156 name = '_LiveList'
157 return '%s(%s)' % (name, list.__repr__(self))
158
159 class _findall_property(object):
160 """
161 Returns a LiveList of all the objects with the given tag. You can
162 append or remove items to the list to add or remove them from the
163 containing tag.
164 """
165
166 def __init__(self, tag, ns=atom_ns):
167 self.tag = tag
168 self.ns = ns
169 self.__doc__ = 'Return live list of all the <atom:%s> element' % self.tag
170 def __get__(self, obj, type=None):
171 if obj is None:
172 return self
173 def add(lst, item):
174 # FIXME: shouldn't just be an append
175 obj.append(item)
176 def remove(lst, item):
177 obj.remove(item)
178 return _LiveList(obj._atom_iter(self.tag, ns=self.ns),
179 on_add=add, on_remove=remove,
180 name='live_%s_list' % self.tag)
181 def __set__(self, obj, value):
182 cur = self.__get__(obj)
183 cur[:] = value
184
185 class _text_element_property(object):
186 """
187 Creates an attribute that returns the text content of the given
188 subelement. E.g., ``title = _text_element_property('title')``
189 will make ``obj.title`` return the contents of the ``<title>``.
190 Similarly setting the attribute sets the text content of the
191 attribute.
192 """
193
194 def __init__(self, tag, strip=True):
195 self.tag = tag
196 self.strip = strip
197 self.__doc__ = 'Access the <atom:%s> element as text' % self.tag
198 def __get__(self, obj, type=None):
199 if obj is None:
200 return self
201 v = obj._atom_findtext(self.tag)
202 if self.strip:
203 if v is not None:
204 v = v.strip()
205 else:
206 return ''
207 return v
208 def __set__(self, obj, value):
209 el = obj._get_or_create(self.tag)
210 el.text = value
211 def __delete__(self, obj):
212 el = obj._atom_get(self.tag)
213 if el:
214 # FIXME: should it be an error if it doesn't exist?
215 obj.remove(el)
216
217 class _element_property(object):
218 """
219 Returns a single subelement based on tag. Setting the attribute
220 removes the element and adds a new one. Deleting it removes the
221 element.
222
223 """
224 def __init__(self, tag):
225 self.tag = tag
226 self.__doc__ = 'Get the <atom:%s> element' % self.tag
227 def __get__(self, obj, type=None):
228 if obj is None:
229 return self
230 return obj._atom_get(self.tag)
231 def __set__(self, obj, value):
232 el = obj._atom_get(self.tag)
233 if el is not None:
234 parent = el.getparent()
235 index = parent.index(el)
236 parent[index] = value
237 else:
238 obj.append(value)
239 def __delete__(self):
240 el = obj._atom_get(self.tag)
241 if el is not None:
242 obj.remove(el)
243
244 class _attr_element_property(object):
245 """
246 Get/set the value of the attribute on this element.
247 """
248
249 def __init__(self, attr, default=NoDefault):
250 self.attr = attr
251 self.default = default
252 self.__doc__ = 'Access the %s attribute' % self.attr
253 def __get__(self, obj, type=None):
254 if obj is None:
255 return self
256 try:
257 return obj.attrib[self.attr]
258 except KeyError:
259 if self.default is not NoDefault:
260 return self.default
261 raise AttributeError(self.attr)
262 def __set__(self, obj, value):
263 if value is None:
264 self.__delete__(obj)
265 else:
266 obj.attrib[self.attr] = value
267 def __delete__(self, obj):
268 if self.attr in obj.attrib:
269 del obj.attrib[self.attr]
270
271 class _date_element_property(object):
272 """
273 Get/set the parsed date value of the text content of a tag.
274 """
275
276 def __init__(self, tag, ns=atom_ns):
277 self.tag = tag
278 self.ns = ns
279 self.__doc__ = 'Access the date in %s' % self.tag
280 def __get__(self, obj, type=None):
281 if obj is None:
282 return self
283 el = obj._atom_get(self.tag, ns=self.ns)
284 if el is None:
285 return None
286 return el.date
287 def __set__(self, obj, value):
288 el = obj._get_or_create(self.tag, ns=self.ns)
289 el.date = value
290 def __delete__(self):
291 el = obj._atom_get(self.tag)
292 if el is not None:
293 obj.remove(el)
294
295 class _date_text_property(object):
296
297 def __get__(self, obj, type=None):
298 if obj is None:
299 return self
300 return parse_date(obj.text)
301 def __set__(self, obj, value):
302 if not value:
303 obj.text = None
304 return
305 if isinstance(value, datetime):
306 value = _strftime(value)
307 obj.text = value
308 def __del__(self, obj):
309 obj.text = None
310
311 class AtomElement(etree.ElementBase):
312 def _get_or_create(self, tag, ns=atom_ns):
313 el = self.find('{%s}%s' % (ns, tag))
314 if el is None:
315 el = self.makeelement('{%s}%s' % (ns, tag))
316 self.append(el)
317 return el
318
319 def _atom_get(self, tag, ns=atom_ns):
320 for item in self._atom_iter(tag, ns=ns):
321 return item
322 return None
323
324 def _atom_iter(self, tag, ns=atom_ns):
325 return self.getiterator('{%s}%s' % (ns, tag))
326
327 def _atom_findtext(self, tag, ns=atom_ns):
328 return self.findtext('{%s}%s' % (ns, tag))
329
330 def _get_parent(self, tag, ns=atom_ns):
331 parent = self
332 while 1:
333 if parent.tag == '{%s}%s' % (ns, tag):
334 return parent
335 parent = parent.getparent()
336 if parent is None:
337 return None
338
339 @property
340 def feed(self):
341 return self._get_parent('feed')
342
343 def rel_links(self, rel='alternate'):
344 """
345 Return all the links with the given ``rel`` attribute. The
346 default relation is ``'alternate'``, and as specified for Atom
347 links with no ``rel`` attribute are assumed to mean alternate.
348 """
349 if rel is None:
350 return self._atom_iter('link')
351 return [
352 el for el in self._atom_iter('link')
353 if el.get('rel') == rel
354 or rel == 'alternate' and not el.get('rel')]
355
356 def __repr__(self):
357 tag = self.tag
358 if '}' in tag:
359 tag = tag.split('}', 1)[1]
360 return '<%s.%s atom:%s at %s>' % (
361 self.__class__.__module__,
362 self.__class__.__name__,
363 tag,
364 hex(abs(id(self)))[2:])
365
366 class Feed(AtomElement):
367 """
368 For ``<feed>`` elements.
369 """
370
371 @property
372 def feed(self):
373 return self
374
375 entries = _findall_property('entry')
376 title = _text_element_property('title')
377 author = _element_property('author')
378
379 class Entry(AtomElement):
380 """
381 For ``<entry>`` elements.
382 """
383
384 @property
385 def entry(self):
386 return self
387 id = _text_element_property('id')
388 title = _text_element_property('title')
389 published = _date_element_property('published')
390 updated = _date_element_property('updated')
391 edited = _date_element_property('edited', ns=app_ns)
392 def update_edited(self):
393 """
394 Set app:edited to current time
395 """
396 self.edited = datetime.utcnow()
397 def update_updated(self):
398 """
399 Set atom:updated to the current time
400 """
401 self.updated = datetime.utcnow()
402 def make_id(self):
403 """
404 Create an artificial id for this entry
405 """
406 assert not self.id, (
407 "You cannot make an id if one already exists")
408 self.id = 'uuid:%s' % uuid.uuid4()
409 def author__get(self):
410 el = self._atom_get('author')
411 if el is None:
412 if self.feed is not None:
413 return self.feed.author
414 return el
415 def author__set(self, value):
416 el = self._atom_get('author')
417 if el is not None:
418 self.remove(el)
419 self.append(value)
420 def author__del(self):
421 el = self._atom_get('author')
422 if el is not None:
423 self.remove(el)
424 author = property(author__get, author__set, author__del)
425
426 categories = _findall_property('category')
427
428 class _EntryElement(AtomElement):
429 @property
430 def entry(self):
431 return self._get_parent('entry')
432
433 class Category(_EntryElement):
434 """
435 For ``<category>`` elements.
436 """
437 term = _attr_element_property('term')
438 scheme = _attr_element_property('scheme', None)
439 label = _attr_element_property('label', None)
440
441 def as_string(self):
442 """
443 Returns the string representation of the category, using the
444 GData convention of ``{scheme}term``
445 """
446 if self.scheme is not None:
447 return '{%s}%s' % (self.scheme, self.term)
448 else:
449 return self.term
450
451 class PersonElement(_EntryElement):
452 """
453 Represents authors and contributors
454 """
455
456 email = _text_element_property('email')
457 uri = _text_element_property('uri')
458 name = _text_element_property('name')
459
460 class DateElement(_EntryElement):
461 """
462 For elements that contain a date in their text content.
463 """
464 date = _date_text_property()
465
466 class TextElement(_EntryElement):
467
468 type = _attr_element_property('type', None)
469 src = _attr_element_property('src', None)
470
471 def _html__get(self):
472 """
473 Gives the parsed HTML of element's content. May return an
474 HtmlElement (from lxml.html) or an XHTML tree. If the element
475 is ``type="text"`` then it is returned as quoted HTML.
476
477 You can also set this attribute to either an lxml.html
478 element, an XHTML element, or an HTML string.
479
480 Raises AttributeError if this is not HTML content.
481 """
482 ## FIXME: should this handle text/html types?
483 if self.type == 'html':
484 content = self.text
485 elif self.type == 'text':
486 content = cgi.escape(self.text)
487 elif self.type == 'xhtml':
488 div = copy.deepcopy(self[0])
489 # Now remove the namespaces:
490 for el in div.getiterator():
491 if el.tag.startswith('{'):
492 el.tag = el.tag.split('}', 1)[1]
493 if div.tag.startswith('{'):
494 div.tag = el.tag.split('}', 1)[1]
495 from lxml.html import tostring
496 content = tostring(div)
497 else:
498 raise AttributeError(
499 "Not an HTML or text content (type=%r)" % self.type)
500 from lxml.html import fromstring
501 return fromstring(content)
502
503 def _html__set(self, value):
504 if value is None:
505 del self.html
506 return
507 if isinstance(value, basestring):
508 # Some HTML text
509 self.type = 'html'
510 self.text = value
511 return
512 if value.tag.startswith('{%s}' % xhtml_ns):
513 if value.tag != '{%s}div' % xhtml_ns:
514 # Need to wrap it in a <div>
515 el = self.makeelement('{%s}div' % xhtml_ns)
516 el.append(value)
517 value = el
518 self[:] = []
519 self.type = 'xhtml'
520 self.append(value)
521 return
522 from lxml import html
523 if isinstance(value, html.HtmlElement):
524 value = tostring(value)
525 self[:] = []
526 self.type = 'html'
527 self.text = value
528 return
529 raise TypeError(
530 "Unknown HTML type: %s" % type(value))
531
532 def _html__del(self):
533 self.text = None
534
535 html = property(_html__get, _html__set, _html__del, doc=_html__get.__doc__)
536
537 def _binary__get(self):
538 """
539 Gets/sets the binary content, which is base64 encoded in the
540 text.
541 """
542 text = self.text
543 if text is None:
544 raise AttributeError(
545 "No text (maybe in src?)")
546 text = text.decode('base64')
547 return text
548
549 def _binary__set(self, value):
550 if isinstance(value, unicode):
551 ## FIXME: is this kosher?
552 value = value.encode('utf8')
553 if not isinstance(value, str):
554 raise TypeError(
555 "Must set .binary to a str or unicode object (not %s)"
556 % type(value))
557 value = value.encode('base64')
558 self.text = value
559
560 def _binary__del(self):
561 self.text = None
562
563 binary = property(_binary__get, _binary__set, _binary__del, doc=_binary__get.__doc__)
564
565
566 class LinkElement(_EntryElement):
567 """
568 For ``<link>`` elements.
569 """
570 href = _attr_element_property('href', None)
571 rel = _attr_element_property('rel', None)
572 type = _attr_element_property('type', None)
573 title = _attr_element_property('title', None)
574
575 def __repr__(self):
576 return '<%s.%s at %s rel=%r href=%r>' % (
577 self.__class__.__module__,
578 self.__class__.__name__,
579 hex(abs(id(self)))[2:],
580 self.rel, self.href)
581
582 AtomLookup._elements.update(dict(
583 feed=Feed,
584 entry=Entry,
585 category=Category,
586 author=PersonElement,
587 contributor=PersonElement,
588 published=DateElement,
589 updated=DateElement,
590 content=TextElement,
591 summary=TextElement,
592 title=TextElement,
593 rights=TextElement,
594 subtitle=TextElement,
595 link=LinkElement,
596 ))
597
598 class APPElement(etree.ElementBase):
599 def __repr__(self):
600 tag = self.tag
601 if '}' in tag:
602 tag = tag.split('}', 1)[1]
603 return '<%s.%s app:%s at %s>' % (
604 self.__class__.__module__,
605 self.__class__.__name__,
606 tag,
607 hex(abs(id(self)))[2:])
608
609 class Service(APPElement):
610 workspaces = _findall_property('workspace', ns=app_ns)
611
612 class Workspace(APPElement):
613 collections = _findall_property('collection', ns=app_ns)
614
615 class Collection(APPElement):
616 pass
617
618 class Edited(APPElement):
619 date = _date_text_property()
620
621 AtomLookup._app_elements.update(dict(
622 service=Service,
623 workspace=Workspace,
624 collection=Collection,
625 edited=Edited,
626 ))