1 # -*- coding: utf-8 -*-
 
   3 #    This file is part of Librarian.
 
   5 #    Copyright © 2008,2009,2010 Fundacja Nowoczesna Polska <fundacja@nowoczesnapolska.org.pl>
 
   7 #    For full list of contributors see AUTHORS file. 
 
   9 #    This program is free software: you can redistribute it and/or modify
 
  10 #    it under the terms of the GNU Affero General Public License as published by
 
  11 #    the Free Software Foundation, either version 3 of the License, or
 
  12 #    (at your option) any later version.
 
  14 #    This program is distributed in the hope that it will be useful,
 
  15 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  16 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  17 #    GNU Affero General Public License for more details.
 
  19 #    You should have received a copy of the GNU Affero General Public License
 
  20 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
  22 from xml.parsers.expat import ExpatError
 
  23 from datetime import date
 
  26 from librarian import ValidationError, NoDublinCore, ParseError, DCNS, RDFNS
 
  28 import lxml.etree as etree # ElementTree API using libxml2
 
  29 from lxml.etree import XMLSyntaxError
 
  36     """Single person with last name and a list of first names."""
 
  37     def __init__(self, last_name, *first_names):
 
  38         self.last_name = last_name
 
  39         self.first_names = first_names
 
  42     def from_text(cls, text):
 
  43         parts = [ token.strip() for token in text.split(',') ]
 
  48             raise ValueError("Invalid person name. There should be at most one comma: \"%s\"." % text)
 
  51             if len(parts[1]) == 0:
 
  52                 # there is no non-whitespace data after the comma
 
  53                 raise ValueError("Found a comma, but no names given: \"%s\" -> %r." % (text, parts))
 
  54             names = [ name for name in parts[1].split() if len(name) ] # all non-whitespace tokens
 
  55         return cls(surname, *names)
 
  57     def __eq__(self, right):
 
  58         return self.last_name == right.last_name and self.first_names == right.first_names
 
  61     def __unicode__(self):
 
  62         if len(self.first_names) > 0:
 
  63             return '%s, %s' % (self.last_name, ' '.join(self.first_names))
 
  68         return 'Person(last_name=%r, first_names=*%r)' % (self.last_name, self.first_names)
 
  73             t = time.strptime(text, '%Y-%m-%d')
 
  75             t = time.strptime(text, '%Y')
 
  76         return date(t[0], t[1], t[2])
 
  78         raise ValueError("Unrecognized date format. Try YYYY-MM-DD or YYYY.")
 
  81     return Person.from_text(text)
 
  84     if isinstance(text, unicode):
 
  87         return text.decode('utf-8')
 
  90     def __init__(self, uri, attr_name, type=as_unicode, multiple=False, salias=None, **kwargs):
 
  94         self.multiple = multiple
 
  97         self.required = kwargs.get('required', True) and not kwargs.has_key('default')
 
  98         self.default = kwargs.get('default', [] if multiple else [None])
 
 100     def validate_value(self, val):
 
 103                 if self.validator is None:
 
 105                 return [ self.validator(v) if v is not None else v for v in val ]
 
 107                 raise ValidationError("Mulitply values not allowed for field '%s'" % self.uri)
 
 109                 raise ValidationError("Field %s has no value to assign. Check your defaults." % self.uri)
 
 111                 if self.validator is None or val[0] is None:
 
 113                 return self.validator(val[0])
 
 114         except ValueError, e:
 
 115             raise ValidationError("Field '%s' - invald value: %s" % (self.uri, e.message))
 
 117     def validate(self, fdict):
 
 118         if not fdict.has_key(self.uri):
 
 119             if not self.required:
 
 122                 raise ValidationError("Required field %s not found" % self.uri)
 
 126         return self.validate_value(f)
 
 131 class BookInfo(object):    
 
 133         Field( DCNS('creator'), 'author', as_person),
 
 134         Field( DCNS('title'), 'title'),
 
 135         Field( DCNS('subject.period'), 'epochs', salias='epoch', multiple=True),
 
 136         Field( DCNS('subject.type'), 'kinds', salias='kind', multiple=True),
 
 137         Field( DCNS('subject.genre'), 'genres', salias='genre', multiple=True),
 
 138         Field( DCNS('date'), 'created_at', as_date),
 
 139         Field( DCNS('date.pd'), 'released_to_public_domain_at', as_date, required=False),
 
 140         Field( DCNS('contributor.editor'), 'editors', \
 
 141             as_person, salias='editor', multiple=True, default=[]),
 
 142         Field( DCNS('contributor.translator'), 'translators', \
 
 143             as_person,  salias='translator', multiple=True, default=[]),
 
 144         Field( DCNS('contributor.technical_editor'), 'technical_editors',
 
 145             as_person, salias='technical_editor', multiple=True, default=[]),
 
 146         Field( DCNS('publisher'), 'publisher'),
 
 147         Field( DCNS('source'), 'source_name', required=False),
 
 148         Field( DCNS('source.URL'), 'source_url', required=False),
 
 149         Field( DCNS('identifier.url'), 'url'),
 
 150         Field( DCNS('relation.hasPart'), 'parts', multiple=True, required=False),
 
 151         Field( DCNS('rights.license'), 'license', required=False),
 
 152         Field( DCNS('rights'), 'license_description'),
 
 156     def from_string(cls, xml):
 
 157         from StringIO import StringIO
 
 158         return cls.from_file(StringIO(xml))
 
 161     def from_file(cls, xmlfile):
 
 164             iter = etree.iterparse(xmlfile, ['start', 'end'])            
 
 165             for (event, element) in iter:
 
 166                 if element.tag == RDFNS('RDF') and event == 'start':
 
 171                 raise NoDublinCore("DublinCore section not found. \
 
 172                     Check if there are rdf:RDF and rdf:Description tags.")
 
 174             # continue 'till the end of RDF section
 
 175             for (event, element) in iter:
 
 176                 if element.tag == RDFNS('RDF') and event == 'end':
 
 179             # if there is no end, Expat should yell at us with an ExpatError
 
 181             # extract data from the element and make the info
 
 182             return cls.from_element(desc_tag)
 
 183         except XMLSyntaxError, e:
 
 185         except ExpatError, e:
 
 189     def from_element(cls, rdf_tag):
 
 190         # the tree is already parsed, so we don't need to worry about Expat errors
 
 192         desc = rdf_tag.find(".//" + RDFNS('Description') )
 
 195             raise NoDublinCore("No DublinCore section found.")
 
 197         for e in desc.getchildren():
 
 198             fv = field_dict.get(e.tag, [])
 
 200             field_dict[e.tag] = fv
 
 202         return cls( desc.attrib, field_dict )
 
 204     def __init__(self, rdf_attrs, dc_fields):
 
 205         """rdf_attrs should be a dictionary-like object with any attributes of the RDF:Description.
 
 206         dc_fields - dictionary mapping DC fields (with namespace) to list of text values for the 
 
 209         self.about = rdf_attrs.get(RDFNS('about'))
 
 212         for field in self.FIELDS:
 
 213             value = field.validate( dc_fields )
 
 214             setattr(self, 'prop_' + field.name, value)
 
 215             self.fmap[field.name] = field
 
 216             if field.salias: self.fmap[field.salias] = field
 
 218     def __getattribute__(self, name):
 
 220             field = object.__getattribute__(self, 'fmap')[name]
 
 221             value = object.__getattribute__(self, 'prop_'+field.name)
 
 222             if field.name == name:
 
 224             else: # singular alias
 
 225                 if not field.multiple:
 
 226                     raise "OUCH!! for field %s" % name
 
 229         except (KeyError, AttributeError):
 
 230             return object.__getattribute__(self, name)
 
 232     def __setattr__(self, name, newvalue):
 
 234             field = object.__getattribute__(self, 'fmap')[name]
 
 235             if field.name == name:
 
 236                 object.__setattr__(self, 'prop_'+field.name, newvalue)
 
 237             else: # singular alias
 
 238                 if not field.multiple:
 
 239                     raise "OUCH! while setting field %s" % name
 
 241                 object.__setattr__(self, 'prop_'+field.name, [newvalue])
 
 242         except (KeyError, AttributeError):
 
 243             return object.__setattr__(self, name, newvalue)
 
 245     def update(self, field_dict):
 
 246         """Update using field_dict. Verify correctness, but don't check if all 
 
 247         required fields are present."""
 
 248         for field in self.FIELDS:
 
 249             if field_dict.has_key(field.name):
 
 250                 setattr(self, field.name, field_dict[field.name])
 
 252     def to_etree(self, parent = None):
 
 253         """XML representation of this object."""
 
 254         #etree._namespace_map[str(self.RDF)] = 'rdf'
 
 255         #etree._namespace_map[str(self.DC)] = 'dc'
 
 258             root = etree.Element(RDFNS('RDF'))
 
 260             root = parent.makeelement(RDFNS('RDF'))
 
 262         description = etree.SubElement(root, RDFNS('Description'))
 
 265             description.set(RDFNS('about'), self.about)
 
 267         for field in self.FIELDS:
 
 268             v = getattr(self, field.name, None)
 
 271                     if len(v) == 0: continue
 
 273                         e = etree.Element(field.uri)
 
 275                         description.append(e)
 
 277                     e = etree.Element(field.uri)
 
 279                     description.append(e)
 
 286         rdf['about'] = { 'uri': RDFNS('about'), 'value': self.about }
 
 289         for field in self.FIELDS:
 
 290             v = getattr(self, field.name, None)
 
 293                     if len(v) == 0: continue
 
 294                     v = [ unicode(x) for x in v if v is not None ]
 
 298                 dc[field.name] = {'uri': field.uri, 'value': v}
 
 303         result = {'about': self.about}
 
 304         for field in self.FIELDS:
 
 305             v = getattr(self, field.name, None)
 
 309                     if len(v) == 0: continue
 
 310                     v = [ unicode(x) for x in v if v is not None ]
 
 313                 result[field.name] = v
 
 316                 v = getattr(self, field.salias)
 
 317                 if v is not None: result[field.salias] = unicode(v)
 
 321 def parse(file_name):
 
 322     return BookInfo.from_file(file_name)