1 # -*- coding: utf-8 -*-
 
   3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
 
   4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 
   6 from librarian import ValidationError, NoDublinCore,  ParseError
 
   7 from librarian import RDFNS
 
   8 from librarian import dcparser
 
  10 from xml.parsers.expat import ExpatError
 
  11 from lxml import etree
 
  12 from lxml.etree import XMLSyntaxError, XSLTApplyError
 
  15 from StringIO import StringIO
 
  17 class WLDocument(object):
 
  18     LINE_SWAP_EXPR = re.compile(r'/\s', re.MULTILINE | re.UNICODE);
 
  20     def __init__(self, edoc, parse_dublincore=True):
 
  23         root_elem = edoc.getroot()
 
  25         dc_path = './/' + RDFNS('RDF')
 
  27         if root_elem.tag != 'utwor':
 
  28             raise ValidationError("Invalid root element. Found '%s', should be 'utwor'" % root_elem.tag)
 
  31             self.rdf_elem = root_elem.find(dc_path)
 
  33             if self.rdf_elem is None:
 
  34                 raise NoDublinCore('Document has no DublinCore - which is required.')
 
  36             self.book_info = dcparser.BookInfo.from_element(self.rdf_elem)
 
  41     def from_string(cls, xml, swap_endlines=False, parse_dublincore=True):
 
  42         return cls.from_file(StringIO(xml), swap_endlines, parse_dublincore=parse_dublincore)
 
  45     def from_file(cls, xmlfile, swap_endlines=False, parse_dublincore=True):
 
  47         # first, prepare for parsing
 
  48         if isinstance(xmlfile, basestring):
 
  49             file = open(xmlfile, 'rb')
 
  57         if not isinstance(data, unicode):
 
  58             data = data.decode('utf-8')
 
  61             data = cls.LINE_SWAP_EXPR.sub(u'<br />\n', data)
 
  64             parser = etree.XMLParser(remove_blank_text=False)
 
  65             return cls(etree.parse(StringIO(data), parser), parse_dublincore=parse_dublincore)
 
  66         except (ExpatError, XMLSyntaxError, XSLTApplyError), e:
 
  69     def chunk(self, path):
 
  70         # convert the path to XPath
 
  71         expr = self.path_to_xpath(path)
 
  72         elems = self.edoc.xpath(expr)
 
  79     def path_to_xpath(self, path):
 
  82         for part in path.split('/'):
 
  83             match = re.match(r'([^\[]+)\[(\d+)\]', part)
 
  87                 tag, n = match.groups()
 
  88                 parts.append("*[%d][name() = '%s']" % (int(n)+1, tag) )
 
  93         return '/'.join(parts)
 
  95     def transform(self, stylesheet, **options):
 
  96         return self.edoc.xslt(stylesheet, **options)
 
 100             parent = self.rdf_elem.getparent()
 
 101             parent.replace( self.rdf_elem, self.book_info.to_etree(parent) )
 
 105         return etree.tostring(self.edoc, encoding=unicode, pretty_print=True)
 
 107     def merge_chunks(self, chunk_dict):
 
 110         for key, data in chunk_dict.iteritems():
 
 112                 xpath = self.path_to_xpath(key)
 
 113                 node = self.edoc.xpath(xpath)[0]
 
 114                 repl = etree.fromstring(u"<%s>%s</%s>" %(node.tag, data, node.tag) )
 
 115                 node.getparent().replace(node, repl);
 
 117                 unmerged.append( repr( (key, xpath, e) ) )