|
| 1 | +# encoding: utf-8 |
| 2 | + |
| 3 | +""" |
| 4 | +lxml custom element classes for core properties-related XML elements. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import ( |
| 8 | + absolute_import, division, print_function, unicode_literals |
| 9 | +) |
| 10 | + |
| 11 | +import re |
| 12 | + |
| 13 | +from datetime import datetime, timedelta |
| 14 | +from lxml import etree |
| 15 | +from .ns import nsdecls, qn |
| 16 | +from .xmlchemy import BaseOxmlElement, ZeroOrOne |
| 17 | + |
| 18 | +class CT_CustomProperties(BaseOxmlElement): |
| 19 | + """ |
| 20 | + ``<cp:customProperties>`` element, the root element of the Custom Properties |
| 21 | + part stored as ``/docProps/custom.xml``. String elements are |
| 22 | + limited in length to 255 unicode characters. |
| 23 | + """ |
| 24 | + |
| 25 | + _customProperties_tmpl = ( |
| 26 | + '<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" %s/>\n' % nsdecls('vt') |
| 27 | + ) |
| 28 | + |
| 29 | + @classmethod |
| 30 | + def new(cls): |
| 31 | + """ |
| 32 | + Return a new ``<property>`` element |
| 33 | + """ |
| 34 | + xml = cls._customProperties_tmpl |
| 35 | + customProperties = ct_parse_xml(xml) |
| 36 | + return customProperties |
| 37 | + |
| 38 | + def _datetime_of_element(self, property_name): |
| 39 | + element = getattr(self, property_name) |
| 40 | + if element is None: |
| 41 | + return None |
| 42 | + datetime_str = element.text |
| 43 | + try: |
| 44 | + return self._parse_W3CDTF_to_datetime(datetime_str) |
| 45 | + except ValueError: |
| 46 | + # invalid datetime strings are ignored |
| 47 | + return None |
| 48 | + |
| 49 | + def _get_or_add(self, prop_name): |
| 50 | + """ |
| 51 | + Return element returned by 'get_or_add_' method for *prop_name*. |
| 52 | + """ |
| 53 | + get_or_add_method_name = 'get_or_add_%s' % prop_name |
| 54 | + get_or_add_method = getattr(self, get_or_add_method_name) |
| 55 | + element = get_or_add_method() |
| 56 | + return element |
| 57 | + |
| 58 | + @classmethod |
| 59 | + def _offset_dt(cls, dt, offset_str): |
| 60 | + """ |
| 61 | + Return a |datetime| instance that is offset from datetime *dt* by |
| 62 | + the timezone offset specified in *offset_str*, a string like |
| 63 | + ``'-07:00'``. |
| 64 | + """ |
| 65 | + match = cls._offset_pattern.match(offset_str) |
| 66 | + if match is None: |
| 67 | + raise ValueError( |
| 68 | + "'%s' is not a valid offset string" % offset_str |
| 69 | + ) |
| 70 | + sign, hours_str, minutes_str = match.groups() |
| 71 | + sign_factor = -1 if sign == '+' else 1 |
| 72 | + hours = int(hours_str) * sign_factor |
| 73 | + minutes = int(minutes_str) * sign_factor |
| 74 | + td = timedelta(hours=hours, minutes=minutes) |
| 75 | + return dt + td |
| 76 | + |
| 77 | + _offset_pattern = re.compile('([+-])(\d\d):(\d\d)') |
| 78 | + |
| 79 | + @classmethod |
| 80 | + def _parse_W3CDTF_to_datetime(cls, w3cdtf_str): |
| 81 | + # valid W3CDTF date cases: |
| 82 | + # yyyy e.g. '2003' |
| 83 | + # yyyy-mm e.g. '2003-12' |
| 84 | + # yyyy-mm-dd e.g. '2003-12-31' |
| 85 | + # UTC timezone e.g. '2003-12-31T10:14:55Z' |
| 86 | + # numeric timezone e.g. '2003-12-31T10:14:55-08:00' |
| 87 | + templates = ( |
| 88 | + '%Y-%m-%dT%H:%M:%S', |
| 89 | + '%Y-%m-%d', |
| 90 | + '%Y-%m', |
| 91 | + '%Y', |
| 92 | + ) |
| 93 | + # strptime isn't smart enough to parse literal timezone offsets like |
| 94 | + # '-07:30', so we have to do it ourselves |
| 95 | + parseable_part = w3cdtf_str[:19] |
| 96 | + offset_str = w3cdtf_str[19:] |
| 97 | + dt = None |
| 98 | + for tmpl in templates: |
| 99 | + try: |
| 100 | + dt = datetime.strptime(parseable_part, tmpl) |
| 101 | + except ValueError: |
| 102 | + continue |
| 103 | + if dt is None: |
| 104 | + tmpl = "could not parse W3CDTF datetime string '%s'" |
| 105 | + raise ValueError(tmpl % w3cdtf_str) |
| 106 | + if len(offset_str) == 6: |
| 107 | + return cls._offset_dt(dt, offset_str) |
| 108 | + return dt |
| 109 | + |
| 110 | + def _set_element_datetime(self, prop_name, value): |
| 111 | + """ |
| 112 | + Set date/time value of child element having *prop_name* to *value*. |
| 113 | + """ |
| 114 | + if not isinstance(value, datetime): |
| 115 | + tmpl = ( |
| 116 | + "property requires <type 'datetime.datetime'> object, got %s" |
| 117 | + ) |
| 118 | + raise ValueError(tmpl % type(value)) |
| 119 | + element = self._get_or_add(prop_name) |
| 120 | + dt_str = value.strftime('%Y-%m-%dT%H:%M:%SZ') |
| 121 | + element.text = dt_str |
| 122 | + if prop_name in ('created', 'modified'): |
| 123 | + # These two require an explicit 'xsi:type="dcterms:W3CDTF"' |
| 124 | + # attribute. The first and last line are a hack required to add |
| 125 | + # the xsi namespace to the root element rather than each child |
| 126 | + # element in which it is referenced |
| 127 | + self.set(qn('xsi:foo'), 'bar') |
| 128 | + element.set(qn('xsi:type'), 'dcterms:W3CDTF') |
| 129 | + del self.attrib[qn('xsi:foo')] |
| 130 | + |
| 131 | + def _set_element_text(self, prop_name, value): |
| 132 | + """ |
| 133 | + Set string value of *name* property to *value*. |
| 134 | + """ |
| 135 | + value = str(value) |
| 136 | + if len(value) > 255: |
| 137 | + tmpl = ( |
| 138 | + "exceeded 255 char limit for property, got:\n\n'%s'" |
| 139 | + ) |
| 140 | + raise ValueError(tmpl % value) |
| 141 | + element = self._get_or_add(prop_name) |
| 142 | + element.text = value |
| 143 | + |
| 144 | + def _text_of_element(self, property_name): |
| 145 | + """ |
| 146 | + Return the text in the element matching *property_name*, or an empty |
| 147 | + string if the element is not present or contains no text. |
| 148 | + """ |
| 149 | + element = getattr(self, property_name) |
| 150 | + if element is None: |
| 151 | + return '' |
| 152 | + if element.text is None: |
| 153 | + return '' |
| 154 | + return element.text |
| 155 | + |
0 commit comments