--- documentViewer/documentViewer.py 2011/07/19 09:54:06 1.175.2.4 +++ documentViewer/documentViewer.py 2011/07/20 19:36:57 1.175.2.7 @@ -1,11 +1,9 @@ - from OFS.Folder import Folder from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate from Products.PageTemplates.PageTemplateFile import PageTemplateFile from AccessControl import ClassSecurityInfo from AccessControl import getSecurityManager from Globals import package_home -from Products.zogiLib.zogiLib import browserCheck #from Ft.Xml import EMPTY_NAMESPACE, Parse #import Ft.Xml.Domlette @@ -15,47 +13,19 @@ import xml.etree.ElementTree as ET import os.path import sys import urllib -import urllib2 import logging import math import urlparse import re import string +from SrvTxtUtils import getInt, getText, getHttpData + def logger(txt,method,txt2): """logging""" logging.info(txt+ txt2) -def getInt(number, default=0): - """returns always an int (0 in case of problems)""" - try: - return int(number) - except: - return int(default) - -def getText(node): - """get the cdata content of a node""" - if node is None: - return "" - # ET: - text = node.text or "" - for e in node: - text += gettext(e) - if e.tail: - text += e.tail - - # 4Suite: - #nodelist=node.childNodes - #text = "" - #for n in nodelist: - # if n.nodeType == node.TEXT_NODE: - # text = text + n.data - - return text - -getTextFromNode = getText - def serializeNode(node, encoding="utf-8"): """returns a string containing node as XML""" s = ET.tostring(node) @@ -128,54 +98,28 @@ def browserCheck(self): return bt - def getParentDir(path): """returns pathname shortened by one""" return '/'.join(path.split('/')[0:-1]) +def normalizeBibtype(bt): + """returns normalised bib type for looking up mappings""" + bt = bt.strip().replace(' ', '-').lower() + return bt -def getHttpData(url, data=None, num_tries=3, timeout=10): - """returns result from url+data HTTP request""" - # we do GET (by appending data to url) - if isinstance(data, str) or isinstance(data, unicode): - # if data is string then append - url = "%s?%s"%(url,data) - elif isinstance(data, dict) or isinstance(data, list) or isinstance(data, tuple): - # urlencode - url = "%s?%s"%(url,urllib.urlencode(data)) - - response = None - errmsg = None - for cnt in range(num_tries): - try: - logging.debug("getHttpData(#%s %ss) url=%s"%(cnt+1,timeout,url)) - if sys.version_info < (2, 6): - # set timeout on socket -- ugly :-( - import socket - socket.setdefaulttimeout(float(timeout)) - response = urllib2.urlopen(url) - else: - response = urllib2.urlopen(url,timeout=float(timeout)) - # check result? - break - except urllib2.HTTPError, e: - logging.error("getHttpData: HTTP error(%s): %s"%(e.code,e)) - errmsg = str(e) - # stop trying - break - except urllib2.URLError, e: - logging.error("getHttpData: URLLIB error(%s): %s"%(e.reason,e)) - errmsg = str(e) - # stop trying - #break - - if response is not None: - data = response.read() - response.close() - return data - - raise IOError("ERROR fetching HTTP data from %s: %s"%(url,errmsg)) - #return None +def getBibdataFromDom(dom): + """returns dict with all elements from bib-tag""" + bibinfo = {} + bib = dom.find(".//meta/bib") + if bib is not None: + # put type in @type + type = bib.get('type') + bibinfo['@type'] = normalizeBibtype(type) + # put all subelements in dict + for e in bib: + bibinfo[e.tag] = getText(e) + + return bibinfo ## ## documentViewer class @@ -304,7 +248,7 @@ class documentViewer(Folder): ''' logging.debug("HHHHHHHHHHHHHH:load the rss") - logger("documentViewer (index)", logging.INFO, "mode: %s url:%s start:%s pn:%s"%(mode,url,start,pn)) + logging.debug("documentViewer (index) mode: %s url:%s start:%s pn:%s"%(mode,url,start,pn)) if not hasattr(self, 'template'): # create template folder if it doesn't exist @@ -633,87 +577,22 @@ class documentViewer(Folder): docinfo['indexMetaPath']=self.getIndexMetaPath(path); logging.debug("documentViewer (getbibinfofromindexmeta cutted) path: %s"%(path)) - # put in all raw bib fields as dict "bib" - bib = dom.find(".//bib") - #bib = dom.xpath("//bib/*") - if bib is not None: - bibinfo = {} - for e in bib: - bibinfo[e.tag] = getText(e) - - docinfo['bib'] = bibinfo - - # extract some fields (author, title, year) according to their mapping - metaData=self.metadata.main.meta.bib - bibtype=bib.get("type") - #bibtype=dom.xpath("//bib/@type") - if not bibtype: - bibtype="generic" - - bibtype=bibtype.replace("-"," ") # wrong typesiin index meta "-" instead of " " (not wrong! ROC) + # put all raw bib fields in dict "bib" + bib = getBibdataFromDom(dom) + docinfo['bib'] = bib + bibtype = bib.get('@type', None) docinfo['bib_type'] = bibtype - bibmap=metaData.generateMappingForType(bibtype) - logging.debug("documentViewer (getbibinfofromindexmeta) bibmap:"+repr(bibmap)) - logging.debug("documentViewer (getbibinfofromindexmeta) bibtype:"+repr(bibtype)) - # if there is no mapping bibmap is empty (mapping sometimes has empty fields) - logging.debug("bibmap: %s"%repr(bibmap)) - if len(bibmap) > 0 and bibmap.get('author',None) or bibmap.get('title',None): + if bibtype: + # also store standard mapped metadata for convenience try: - docinfo['author']=getText(bib.find(bibmap['author'][0])) - except: pass - try: - docinfo['title']=getText(bib.find(bibmap['title'][0])) - except: pass - try: - docinfo['year']=getText(bib.find(bibmap['year'][0])) - except: pass - - # ROC: why is this here? - # logging.debug("documentViewer (getbibinfofromindexmeta) using mapping for %s"%bibtype) - # try: - # docinfo['lang']=getTextFromNode(dom.find(".//bib/lang")[0]) - # except: - # docinfo['lang']='' - # try: - # docinfo['city']=getTextFromNode(dom.find(".//bib/city")[0]) - # except: - # docinfo['city']='' - # try: - # docinfo['number_of_pages']=getTextFromNode(dom.find(".//bib/number_of_pages")[0]) - # except: - # docinfo['number_of_pages']='' - # try: - # docinfo['series_volume']=getTextFromNode(dom.find(".//bib/series_volume")[0]) - # except: - # docinfo['series_volume']='' - # try: - # docinfo['number_of_volumes']=getTextFromNode(dom.find(".//bib/number_of_volumes")[0]) - # except: - # docinfo['number_of_volumes']='' - # try: - # docinfo['translator']=getTextFromNode(dom.find(".//bib/translator")[0]) - # except: - # docinfo['translator']='' - # try: - # docinfo['edition']=getTextFromNode(dom.find(".//bib/edition")[0]) - # except: - # docinfo['edition']='' - # try: - # docinfo['series_author']=getTextFromNode(dom.find(".//bib/series_author")[0]) - # except: - # docinfo['series_author']='' - # try: - # docinfo['publisher']=getTextFromNode(dom.find(".//bib/publisher")[0]) - # except: - # docinfo['publisher']='' - # try: - # docinfo['series_title']=getTextFromNode(dom.find(".//bib/series_title")[0]) - # except: - # docinfo['series_title']='' - # try: - # docinfo['isbn_issn']=getTextFromNode(dom.find(".//bib/isbn_issn")[0]) - # except: - # docinfo['isbn_issn']='' + stdbib = self.metadata.getStdMappedHash(bib) + docinfo['std_bib'] = stdbib + docinfo['author'] = stdbib['author'] + docinfo['title'] = stdbib['title'] + docinfo['year'] = stdbib['year'] + except: + pass + return docinfo @@ -858,6 +737,7 @@ class documentViewer(Folder): imageUrl=self.digilibBaseUrl+"/servlet/Scaler?fn="+path docinfo['imageURL'] = imageUrl + #TODO: use getDocinfoFromIndexMeta #path ist the path to the images it assumes that the index.meta file is one level higher. docinfo = self.getBibinfoFromIndexMeta(pathorig,docinfo=docinfo,cut=cut+1) docinfo = self.getAuthinfoFromIndexMeta(pathorig,docinfo=docinfo,cut=cut+1) @@ -892,12 +772,9 @@ class documentViewer(Folder): logging.error("documentViewer (getdocinfo) unknown mode: %s!"%mode) raise ValueError("Unknown mode %s! Has to be one of 'texttool','imagepath','filepath'."%(mode)) - # FIXME: fake texturlpath - if not docinfo.has_key('textURLPath'): - docinfo['textURLPath'] = None - - logging.debug("documentViewer (getdocinfo) docinfo: %s"%docinfo) - #logging.debug("documentViewer (getdocinfo) docinfo: %s"%) + logging.debug("documentViewer (getdocinfo) docinfo: keys=%s"%docinfo.keys()) + #logging.debug("documentViewer (getdocinfo) docinfo: %s"%docinfo) + # store in session self.REQUEST.SESSION['docinfo'] = docinfo return docinfo @@ -913,6 +790,7 @@ class documentViewer(Folder): pageinfo['cols'] = cols grpsize = cols * rows pageinfo['groupsize'] = grpsize + # what does this do? start = getInt(start, default=(math.ceil(float(current)/float(grpsize))*grpsize-(grpsize-1))) # int(current / grpsize) * grpsize +1)) pageinfo['start'] = start @@ -922,7 +800,8 @@ class documentViewer(Folder): pageinfo['end'] = min(pageinfo['end'], np) pageinfo['numgroups'] = int(np / grpsize) if np % grpsize > 0: - pageinfo['numgroups'] += 1 + pageinfo['numgroups'] += 1 + pageinfo['viewMode'] = viewMode pageinfo['tocMode'] = tocMode pageinfo['characterNormalization'] = self.REQUEST.get('characterNormalization','reg') @@ -934,10 +813,12 @@ class documentViewer(Folder): pageinfo['highlightQuery'] = self.REQUEST.get('highlightQuery','') pageinfo['tocPageSize'] = self.REQUEST.get('tocPageSize', '30') pageinfo['queryPageSize'] =self.REQUEST.get('queryPageSize', '10') - pageinfo['tocPN'] = self.REQUEST.get('tocPN', '1') - toc = int (pageinfo['tocPN']) - pageinfo['textPages'] =int (toc) + pageinfo['tocPN'] = self.REQUEST.get('tocPN', '1') + # WTF?: + toc = int(pageinfo['tocPN']) + pageinfo['textPages'] =int(toc) + # What does this do? if 'tocSize_%s'%tocMode in docinfo: tocSize = int(docinfo['tocSize_%s'%tocMode]) tocPageSize = int(pageinfo['tocPageSize']) @@ -946,12 +827,15 @@ class documentViewer(Folder): tocPages=tocSize/tocPageSize+1 else: tocPages=tocSize/tocPageSize - pageinfo['tocPN'] = min (tocPages,toc) + + pageinfo['tocPN'] = min(tocPages,toc) + pageinfo['searchPN'] =self.REQUEST.get('searchPN','1') pageinfo['sn'] =self.REQUEST.get('sn','') return pageinfo + -def changeDocumentViewer(self,title="",digilibBaseUrl=None,thumbrows=2,thumbcols=5,authgroups='mpiwg',RESPONSE=None): + def changeDocumentViewer(self,title="",digilibBaseUrl=None,thumbrows=2,thumbcols=5,authgroups='mpiwg',RESPONSE=None): """init document viewer""" self.title=title self.digilibBaseUrl = digilibBaseUrl