Annotation of documentViewer/documentViewer.py, revision 1.32
1.18 dwinter 1:
2:
1.1 dwinter 3: from OFS.Folder import Folder
4: from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
1.22 dwinter 5: from Products.PageTemplates.PageTemplateFile import PageTemplateFile
1.1 dwinter 6: from AccessControl import ClassSecurityInfo
1.8 casties 7: from AccessControl import getSecurityManager
1.1 dwinter 8: from Globals import package_home
9:
10: from Ft.Xml.Domlette import NonvalidatingReader
11: from Ft.Xml.Domlette import PrettyPrint, Print
1.11 casties 12: from Ft.Xml import EMPTY_NAMESPACE, Parse
1.1 dwinter 13:
14: import Ft.Xml.XPath
15:
16: import os.path
1.7 casties 17: import sys
1.1 dwinter 18: import cgi
19: import urllib
1.20 dwinter 20: import logging
1.28 casties 21: import math
1.22 dwinter 22:
1.18 dwinter 23: import urlparse
1.1 dwinter 24:
1.22 dwinter 25: def logger(txt,method,txt2):
26: """logging"""
27: logging.info(txt+ txt2)
28:
29:
1.4 casties 30: def getInt(number, default=0):
31: """returns always an int (0 in case of problems)"""
32: try:
33: return int(number)
34: except:
1.29 casties 35: return int(default)
1.4 casties 36:
1.1 dwinter 37: def getTextFromNode(nodename):
1.18 dwinter 38: """get the cdata content of a node"""
1.8 casties 39: if nodename is None:
40: return ""
1.1 dwinter 41: nodelist=nodename.childNodes
42: rc = ""
43: for node in nodelist:
44: if node.nodeType == node.TEXT_NODE:
45: rc = rc + node.data
46: return rc
47:
1.9 casties 48:
49: def getParentDir(path):
50: """returns pathname shortened by one"""
51: return '/'.join(path.split('/')[0:-1])
52:
53:
1.1 dwinter 54: import socket
55:
1.8 casties 56: def urlopen(url,timeout=2):
1.1 dwinter 57: """urlopen mit timeout"""
1.8 casties 58: socket.setdefaulttimeout(timeout)
1.1 dwinter 59: ret=urllib.urlopen(url)
60: socket.setdefaulttimeout(5)
61: return ret
62:
63:
1.3 casties 64: ##
65: ## documentViewer class
66: ##
67: class documentViewer(Folder):
1.1 dwinter 68: """document viewer"""
1.20 dwinter 69: #textViewerUrl="http://127.0.0.1:8080/HFQP/testXSLT/getPage?"
1.18 dwinter 70:
1.1 dwinter 71: meta_type="Document viewer"
72:
73: security=ClassSecurityInfo()
1.3 casties 74: manage_options=Folder.manage_options+(
1.1 dwinter 75: {'label':'main config','action':'changeDocumentViewerForm'},
76: )
77:
1.3 casties 78: # templates and forms
79: viewer_main = PageTemplateFile('zpt/viewer_main', globals())
80: thumbs_main = PageTemplateFile('zpt/thumbs_main', globals())
81: image_main = PageTemplateFile('zpt/image_main', globals())
82: head_main = PageTemplateFile('zpt/head_main', globals())
83: docuviewer_css = PageTemplateFile('css/docuviewer.css', globals())
1.26 casties 84: info_xml = PageTemplateFile('zpt/info_xml', globals())
1.3 casties 85:
1.32 ! dwinter 86: thumbs_main_rss = PageTemplateFile('zpt/thumbs_main_rss', globals())
1.3 casties 87: security.declareProtected('View management screens','changeDocumentViewerForm')
88: changeDocumentViewerForm = PageTemplateFile('zpt/changeDocumentViewer', globals())
89:
1.1 dwinter 90:
1.18 dwinter 91: def __init__(self,id,imageViewerUrl,textViewerUrl=None,title="",digilibBaseUrl=None,thumbcols=2,thumbrows=10,authgroups="mpiwg"):
1.1 dwinter 92: """init document viewer"""
93: self.id=id
94: self.title=title
95: self.imageViewerUrl=imageViewerUrl
1.18 dwinter 96: self.textViewerUrl=textViewerUrl
97:
1.4 casties 98: if not digilibBaseUrl:
1.3 casties 99: self.digilibBaseUrl = self.findDigilibUrl()
1.4 casties 100: else:
101: self.digilibBaseUrl = digilibBaseUrl
102: self.thumbcols = thumbcols
103: self.thumbrows = thumbrows
1.8 casties 104: # authgroups is list of authorized groups (delimited by ,)
105: self.authgroups = [s.strip().lower() for s in authgroups.split(',')]
1.3 casties 106: # add template folder so we can always use template.something
107: self.manage_addFolder('template')
108:
109:
1.32 ! dwinter 110: security.declareProtected('View','thumbs_rss')
! 111: def thumbs_rss(self,mode,url,viewMode="auto",start=None,pn=1):
! 112: '''
! 113: view it
! 114: @param mode: defines how to access the document behind url
! 115: @param url: url which contains display information
! 116: @param viewMode: if images display images, if text display text, default is images (text,images or auto)
! 117:
! 118: '''
! 119: logging.info("HHHHHHHHHHHHHH:load the rss")
! 120: logger("documentViewer (index)", logging.INFO, "mode: %s url:%s start:%s pn:%s"%(mode,url,start,pn))
! 121:
! 122: if not hasattr(self, 'template'):
! 123: # create template folder if it doesn't exist
! 124: self.manage_addFolder('template')
! 125:
! 126: if not self.digilibBaseUrl:
! 127: self.digilibBaseUrl = self.findDigilibUrl() or "http://nausikaa.mpiwg-berlin.mpg.de/digitallibrary"
! 128:
! 129: docinfo = self.getDocinfo(mode=mode,url=url)
! 130: pageinfo = self.getPageinfo(start=start,current=pn,docinfo=docinfo)
! 131: pt = getattr(self.template, 'thumbs_main_rss')
! 132:
! 133: if viewMode=="auto": # automodus gewaehlt
! 134: if docinfo.get("textURL",'') and self.textViewerUrl: #texturl gesetzt und textViewer konfiguriert
! 135: viewMode="text"
! 136: else:
! 137: viewMode="images"
! 138:
! 139: return pt(docinfo=docinfo,pageinfo=pageinfo,viewMode=viewMode)
! 140:
1.3 casties 141: security.declareProtected('View','index_html')
1.21 dwinter 142: def index_html(self,mode,url,viewMode="auto",start=None,pn=1):
1.3 casties 143: '''
144: view it
1.26 casties 145: @param mode: defines how to access the document behind url
1.3 casties 146: @param url: url which contains display information
1.26 casties 147: @param viewMode: if images display images, if text display text, default is images (text,images or auto)
1.18 dwinter 148:
1.3 casties 149: '''
150:
1.22 dwinter 151: logger("documentViewer (index)", logging.INFO, "mode: %s url:%s start:%s pn:%s"%(mode,url,start,pn))
1.1 dwinter 152:
1.3 casties 153: if not hasattr(self, 'template'):
154: # create template folder if it doesn't exist
155: self.manage_addFolder('template')
156:
157: if not self.digilibBaseUrl:
158: self.digilibBaseUrl = self.findDigilibUrl() or "http://nausikaa.mpiwg-berlin.mpg.de/digitallibrary"
159:
1.4 casties 160: docinfo = self.getDocinfo(mode=mode,url=url)
161: pageinfo = self.getPageinfo(start=start,current=pn,docinfo=docinfo)
1.3 casties 162: pt = getattr(self.template, 'viewer_main')
1.21 dwinter 163:
164: if viewMode=="auto": # automodus gewaehlt
165: if docinfo.get("textURL",'') and self.textViewerUrl: #texturl gesetzt und textViewer konfiguriert
166: viewMode="text"
167: else:
168: viewMode="images"
1.22 dwinter 169:
1.18 dwinter 170: return pt(docinfo=docinfo,pageinfo=pageinfo,viewMode=viewMode)
1.1 dwinter 171:
172:
1.4 casties 173: def getLink(self,param=None,val=None):
174: """link to documentviewer with parameter param set to val"""
1.9 casties 175: params=self.REQUEST.form.copy()
1.4 casties 176: if param is not None:
1.7 casties 177: if val is None:
178: if params.has_key(param):
179: del params[param]
1.4 casties 180: else:
1.9 casties 181: params[param] = str(val)
1.7 casties 182:
1.9 casties 183: # quote values and assemble into query string
184: ps = "&".join(["%s=%s"%(k,urllib.quote(v)) for (k, v) in params.items()])
185: url=self.REQUEST['URL1']+"?"+ps
1.4 casties 186: return url
187:
1.32 ! dwinter 188: def getLinkAmp(self,param=None,val=None):
! 189: """link to documentviewer with parameter param set to val"""
! 190: params=self.REQUEST.form.copy()
! 191: if param is not None:
! 192: if val is None:
! 193: if params.has_key(param):
! 194: del params[param]
! 195: else:
! 196: params[param] = str(val)
! 197:
! 198: # quote values and assemble into query string
! 199: logging.info("XYXXXXX: %s"%repr(params.items()))
! 200: ps = "&".join(["%s=%s"%(k,urllib.quote(v)) for (k, v) in params.items()])
! 201: url=self.REQUEST['URL1']+"?"+ps
! 202: return url
1.26 casties 203: def getInfo_xml(self,url,mode):
204: """returns info about the document as XML"""
205:
206: if not self.digilibBaseUrl:
207: self.digilibBaseUrl = self.findDigilibUrl() or "http://nausikaa.mpiwg-berlin.mpg.de/digitallibrary"
208:
209: docinfo = self.getDocinfo(mode=mode,url=url)
210: pt = getattr(self.template, 'info_xml')
211: return pt(docinfo=docinfo)
212:
1.4 casties 213:
1.3 casties 214: def getStyle(self, idx, selected, style=""):
1.4 casties 215: """returns a string with the given style and append 'sel' if path == selected."""
1.22 dwinter 216: #logger("documentViewer (getstyle)", logging.INFO, "idx: %s selected: %s style: %s"%(idx,selected,style))
1.3 casties 217: if idx == selected:
218: return style + 'sel'
219: else:
1.9 casties 220: return style
1.26 casties 221:
1.2 dwinter 222:
1.9 casties 223: def isAccessible(self, docinfo):
1.8 casties 224: """returns if access to the resource is granted"""
225: access = docinfo.get('accessType', None)
1.22 dwinter 226: logger("documentViewer (accessOK)", logging.INFO, "access type %s"%access)
1.17 casties 227: if access is not None and access == 'free':
1.22 dwinter 228: logger("documentViewer (accessOK)", logging.INFO, "access is free")
1.8 casties 229: return True
1.17 casties 230: elif access is None or access in self.authgroups:
1.9 casties 231: # only local access -- only logged in users
232: user = getSecurityManager().getUser()
233: if user is not None:
234: #print "user: ", user
235: return (user.getUserName() != "Anonymous User")
236: else:
237: return False
1.8 casties 238:
1.22 dwinter 239: logger("documentViewer (accessOK)", logging.INFO, "unknown access type %s"%access)
1.8 casties 240: return False
1.9 casties 241:
1.8 casties 242:
1.7 casties 243: def getDirinfoFromDigilib(self,path,docinfo=None):
1.6 casties 244: """gibt param von dlInfo aus"""
1.13 casties 245: num_retries = 3
1.7 casties 246: if docinfo is None:
247: docinfo = {}
248:
1.13 casties 249: infoUrl=self.digilibBaseUrl+"/dirInfo-xml.jsp?mo=dir&fn="+path
1.6 casties 250:
1.22 dwinter 251: logger("documentViewer (getparamfromdigilib)", logging.INFO, "dirInfo from %s"%(infoUrl))
1.6 casties 252:
1.13 casties 253: for cnt in range(num_retries):
1.9 casties 254: try:
1.13 casties 255: # dom = NonvalidatingReader.parseUri(imageUrl)
256: txt=urllib.urlopen(infoUrl).read()
257: dom = Parse(txt)
1.9 casties 258: break
259: except:
1.22 dwinter 260: logger("documentViewer (getdirinfofromdigilib)", logging.ERROR, "error reading %s (try %d)"%(infoUrl,cnt))
1.9 casties 261: else:
1.13 casties 262: raise IOError("Unable to get dir-info from %s"%(infoUrl))
1.6 casties 263:
1.10 casties 264: sizes=dom.xpath("//dir/size")
1.22 dwinter 265: logger("documentViewer (getparamfromdigilib)", logging.INFO, "dirInfo:size"%sizes)
1.6 casties 266:
1.10 casties 267: if sizes:
268: docinfo['numPages'] = int(getTextFromNode(sizes[0]))
1.7 casties 269: else:
270: docinfo['numPages'] = 0
271:
272: return docinfo
1.8 casties 273:
1.6 casties 274:
1.9 casties 275: def getIndexMeta(self, url):
276: """returns dom of index.meta document at url"""
1.12 casties 277: num_retries = 3
1.9 casties 278: dom = None
1.12 casties 279: metaUrl = None
1.9 casties 280: if url.startswith("http://"):
281: # real URL
1.12 casties 282: metaUrl = url
1.9 casties 283: else:
284: # online path
285: server=self.digilibBaseUrl+"/servlet/Texter?fn="
1.13 casties 286: metaUrl=server+url.replace("/mpiwg/online","")
1.9 casties 287: if not metaUrl.endswith("index.meta"):
288: metaUrl += "/index.meta"
1.18 dwinter 289: print metaUrl
1.13 casties 290: for cnt in range(num_retries):
1.9 casties 291: try:
1.12 casties 292: # patch dirk encoding fehler treten dann nicht mehr auf
1.11 casties 293: # dom = NonvalidatingReader.parseUri(metaUrl)
1.12 casties 294: txt=urllib.urlopen(metaUrl).read()
295: dom = Parse(txt)
1.13 casties 296: break
1.9 casties 297: except:
1.22 dwinter 298: logger("ERROR documentViewer (getIndexMata)", logging.INFO,"%s (%s)"%sys.exc_info()[0:2])
1.12 casties 299:
300: if dom is None:
301: raise IOError("Unable to read index meta from %s"%(url))
1.9 casties 302:
303: return dom
1.20 dwinter 304:
305: def getPresentationInfoXML(self, url):
306: """returns dom of info.xml document at url"""
307: num_retries = 3
308: dom = None
309: metaUrl = None
310: if url.startswith("http://"):
311: # real URL
312: metaUrl = url
313: else:
314: # online path
315: server=self.digilibBaseUrl+"/servlet/Texter?fn="
316: metaUrl=server+url.replace("/mpiwg/online","")
317:
318:
319: for cnt in range(num_retries):
320: try:
321: # patch dirk encoding fehler treten dann nicht mehr auf
322: # dom = NonvalidatingReader.parseUri(metaUrl)
323: txt=urllib.urlopen(metaUrl).read()
324: dom = Parse(txt)
325: break
326: except:
1.22 dwinter 327: logger("ERROR documentViewer (getPresentationInfoXML)", logging.INFO,"%s (%s)"%sys.exc_info()[0:2])
1.20 dwinter 328:
329: if dom is None:
330: raise IOError("Unable to read infoXMLfrom %s"%(url))
331:
332: return dom
1.9 casties 333:
334:
1.8 casties 335: def getAuthinfoFromIndexMeta(self,path,docinfo=None,dom=None):
1.9 casties 336: """gets authorization info from the index.meta file at path or given by dom"""
1.22 dwinter 337: logger("documentViewer (getauthinfofromindexmeta)", logging.INFO,"path: %s"%(path))
1.8 casties 338:
339: access = None
340:
341: if docinfo is None:
342: docinfo = {}
343:
344: if dom is None:
1.9 casties 345: dom = self.getIndexMeta(getParentDir(path))
1.18 dwinter 346:
1.8 casties 347: acctype = dom.xpath("//access-conditions/access/@type")
348: if acctype and (len(acctype)>0):
349: access=acctype[0].value
1.9 casties 350: if access in ['group', 'institution']:
1.8 casties 351: access = getTextFromNode(dom.xpath("//access-conditions/access/name")[0]).lower()
352:
353: docinfo['accessType'] = access
354: return docinfo
1.6 casties 355:
1.8 casties 356:
1.3 casties 357: def getBibinfoFromIndexMeta(self,path,docinfo=None,dom=None):
1.9 casties 358: """gets bibliographical info from the index.meta file at path or given by dom"""
1.27 casties 359: logging.debug("documentViewer (getbibinfofromindexmeta) path: %s"%(path))
1.2 dwinter 360:
1.3 casties 361: if docinfo is None:
362: docinfo = {}
363:
364: if dom is None:
1.9 casties 365: dom = self.getIndexMeta(getParentDir(path))
366:
1.27 casties 367: # put in all raw bib fields as dict "bib"
368: bib = dom.xpath("//bib/*")
369: if bib and len(bib)>0:
370: bibinfo = {}
371: for e in bib:
372: bibinfo[e.localName] = getTextFromNode(e)
373: docinfo['bib'] = bibinfo
374:
375: # extract some fields (author, title, year) according to their mapping
1.4 casties 376: metaData=self.metadata.main.meta.bib
377: bibtype=dom.xpath("//bib/@type")
378: if bibtype and (len(bibtype)>0):
379: bibtype=bibtype[0].value
1.2 dwinter 380: else:
1.4 casties 381: bibtype="generic"
1.27 casties 382:
1.4 casties 383: bibtype=bibtype.replace("-"," ") # wrong typesiin index meta "-" instead of " " (not wrong! ROC)
1.27 casties 384: docinfo['bib_type'] = bibtype
1.4 casties 385: bibmap=metaData.generateMappingForType(bibtype)
1.8 casties 386: # if there is no mapping bibmap is empty (mapping sometimes has empty fields)
1.7 casties 387: if len(bibmap) > 0 and len(bibmap['author'][0]) > 0:
1.30 casties 388: try:
389: docinfo['author']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['author'][0])[0])
390: except: pass
391: try:
392: docinfo['title']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['title'][0])[0])
393: except: pass
394: try:
395: docinfo['year']=getTextFromNode(dom.xpath("//bib/%s"%bibmap['year'][0])[0])
396: except: pass
1.27 casties 397: logging.debug("documentViewer (getbibinfofromindexmeta) using mapping for %s"%bibtype)
1.22 dwinter 398: try:
399: docinfo['lang']=getTextFromNode(dom.xpath("//bib/lang")[0])
400: except:
401: docinfo['lang']=''
1.27 casties 402:
1.3 casties 403: return docinfo
404:
405:
1.8 casties 406: def getDocinfoFromTextTool(self,url,dom=None,docinfo=None):
1.3 casties 407: """parse texttool tag in index meta"""
1.22 dwinter 408: logger("documentViewer (getdocinfofromtexttool)", logging.INFO,"url: %s"%(url))
1.3 casties 409: if docinfo is None:
410: docinfo = {}
411:
1.22 dwinter 412: if docinfo.get('lang',None) is None:
413: docinfo['lang']='' # default keine Sprache gesetzt
1.8 casties 414: if dom is None:
1.9 casties 415: dom = self.getIndexMeta(url)
1.8 casties 416:
1.16 casties 417: archivePath = None
418: archiveName = None
419:
1.8 casties 420: archiveNames=dom.xpath("//resource/name")
421: if archiveNames and (len(archiveNames)>0):
422: archiveName=getTextFromNode(archiveNames[0])
1.16 casties 423: else:
1.22 dwinter 424: logger("documentViewer (getdocinfofromtexttool)", logging.WARNING,"resource/name missing in: %s"%(url))
1.3 casties 425:
426: archivePaths=dom.xpath("//resource/archive-path")
427: if archivePaths and (len(archivePaths)>0):
428: archivePath=getTextFromNode(archivePaths[0])
1.8 casties 429: # clean up archive path
430: if archivePath[0] != '/':
431: archivePath = '/' + archivePath
1.16 casties 432: if archiveName and (not archivePath.endswith(archiveName)):
1.8 casties 433: archivePath += "/" + archiveName
1.3 casties 434: else:
1.16 casties 435: # try to get archive-path from url
1.22 dwinter 436: logger("documentViewer (getdocinfofromtexttool)", logging.WARNING,"resource/archive-path missing in: %s"%(url))
1.16 casties 437: if (not url.startswith('http')):
438: archivePath = url.replace('index.meta', '')
439:
440: if archivePath is None:
441: # we balk without archive-path
442: raise IOError("Missing archive-path (for text-tool) in %s"%(url))
1.3 casties 443:
1.9 casties 444: imageDirs=dom.xpath("//texttool/image")
445: if imageDirs and (len(imageDirs)>0):
446: imageDir=getTextFromNode(imageDirs[0])
1.3 casties 447: else:
1.22 dwinter 448: # we balk with no image tag / not necessary anymore because textmode is now standard
449: #raise IOError("No text-tool info in %s"%(url))
450: imageDir=""
451: docinfo['numPages']=1 # im moment einfach auf eins setzen, navigation ueber die thumbs geht natuerlich nicht
452:
453: docinfo['imagePath'] = "" # keine Bilder
454: docinfo['imageURL'] = ""
455:
1.9 casties 456: if imageDir and archivePath:
457: #print "image: ", imageDir, " archivepath: ", archivePath
458: imageDir=os.path.join(archivePath,imageDir)
459: imageDir=imageDir.replace("/mpiwg/online",'')
460: docinfo=self.getDirinfoFromDigilib(imageDir,docinfo=docinfo)
461: docinfo['imagePath'] = imageDir
462: docinfo['imageURL'] = self.digilibBaseUrl+"/servlet/Scaler?fn="+imageDir
1.3 casties 463:
464: viewerUrls=dom.xpath("//texttool/digiliburlprefix")
465: if viewerUrls and (len(viewerUrls)>0):
466: viewerUrl=getTextFromNode(viewerUrls[0])
1.7 casties 467: docinfo['viewerURL'] = viewerUrl
1.3 casties 468:
469: textUrls=dom.xpath("//texttool/text")
470: if textUrls and (len(textUrls)>0):
471: textUrl=getTextFromNode(textUrls[0])
1.19 dwinter 472: if urlparse.urlparse(textUrl)[0]=="": #keine url
473: textUrl=os.path.join(archivePath,textUrl)
1.31 casties 474: # fix URLs starting with /mpiwg/online
475: if textUrl.startswith("/mpiwg/online"):
476: textUrl = textUrl.replace("/mpiwg/online",'',1)
477:
1.7 casties 478: docinfo['textURL'] = textUrl
1.20 dwinter 479:
480: presentationUrls=dom.xpath("//texttool/presentation")
1.22 dwinter 481: docinfo = self.getBibinfoFromIndexMeta(url,docinfo=docinfo,dom=dom) # get info von bib tag
482:
483: if presentationUrls and (len(presentationUrls)>0): # ueberschreibe diese durch presentation informationen
1.30 casties 484: # presentation url ergiebt sich ersetzen von index.meta in der url der fuer die Metadaten
1.20 dwinter 485: # durch den relativen Pfad auf die presentation infos
486: presentationUrl=url.replace('index.meta',getTextFromNode(presentationUrls[0]))
487: docinfo = self.getBibinfoFromTextToolPresentation(presentationUrl,docinfo=docinfo,dom=dom)
1.22 dwinter 488:
1.25 casties 489: docinfo = self.getAuthinfoFromIndexMeta(url,docinfo=docinfo,dom=dom) # get access info
1.3 casties 490: return docinfo
491:
1.20 dwinter 492:
493: def getBibinfoFromTextToolPresentation(self,url,docinfo=None,dom=None):
494: """gets the bibliographical information from the preseantion entry in texttools
495: """
496: dom=self.getPresentationInfoXML(url)
1.29 casties 497: try:
498: docinfo['author']=getTextFromNode(dom.xpath("//author")[0])
499: except:
500: pass
501: try:
502: docinfo['title']=getTextFromNode(dom.xpath("//title")[0])
503: except:
504: pass
505: try:
506: docinfo['year']=getTextFromNode(dom.xpath("//date")[0])
507: except:
508: pass
1.20 dwinter 509: return docinfo
510:
1.3 casties 511: def getDocinfoFromImagePath(self,path,docinfo=None):
512: """path ist the path to the images it assumes that the index.meta file is one level higher."""
1.22 dwinter 513: logger("documentViewer (getdocinfofromimagepath)", logging.INFO,"path: %s"%(path))
1.3 casties 514: if docinfo is None:
515: docinfo = {}
1.6 casties 516: path=path.replace("/mpiwg/online","")
1.3 casties 517: docinfo['imagePath'] = path
1.7 casties 518: docinfo=self.getDirinfoFromDigilib(path,docinfo=docinfo)
519: imageUrl=self.digilibBaseUrl+"/servlet/Scaler?fn="+path
1.3 casties 520: docinfo['imageURL'] = imageUrl
521:
522: docinfo = self.getBibinfoFromIndexMeta(path,docinfo=docinfo)
1.8 casties 523: docinfo = self.getAuthinfoFromIndexMeta(path,docinfo=docinfo)
1.3 casties 524: return docinfo
525:
1.2 dwinter 526:
1.3 casties 527: def getDocinfo(self, mode, url):
528: """returns docinfo depending on mode"""
1.22 dwinter 529: logger("documentViewer (getdocinfo)", logging.INFO,"mode: %s, url: %s"%(mode,url))
1.3 casties 530: # look for cached docinfo in session
1.21 dwinter 531: if self.REQUEST.SESSION.has_key('docinfo'):
1.3 casties 532: docinfo = self.REQUEST.SESSION['docinfo']
533: # check if its still current
534: if docinfo is not None and docinfo.get('mode') == mode and docinfo.get('url') == url:
1.22 dwinter 535: logger("documentViewer (getdocinfo)", logging.INFO,"docinfo in session: %s"%docinfo)
1.3 casties 536: return docinfo
537: # new docinfo
538: docinfo = {'mode': mode, 'url': url}
539: if mode=="texttool": #index.meta with texttool information
540: docinfo = self.getDocinfoFromTextTool(url, docinfo=docinfo)
541: elif mode=="imagepath":
542: docinfo = self.getDocinfoFromImagePath(url, docinfo=docinfo)
543: else:
1.22 dwinter 544: logger("documentViewer (getdocinfo)", logging.ERROR,"unknown mode!")
1.10 casties 545: raise ValueError("Unknown mode %s"%(mode))
546:
1.22 dwinter 547: logger("documentViewer (getdocinfo)", logging.INFO,"docinfo: %s"%docinfo)
1.3 casties 548: self.REQUEST.SESSION['docinfo'] = docinfo
549: return docinfo
1.2 dwinter 550:
551:
1.4 casties 552: def getPageinfo(self, current, start=None, rows=None, cols=None, docinfo=None):
1.3 casties 553: """returns pageinfo with the given parameters"""
554: pageinfo = {}
1.4 casties 555: current = getInt(current)
556: pageinfo['current'] = current
557: rows = int(rows or self.thumbrows)
558: pageinfo['rows'] = rows
559: cols = int(cols or self.thumbcols)
560: pageinfo['cols'] = cols
561: grpsize = cols * rows
562: pageinfo['groupsize'] = grpsize
1.28 casties 563: start = getInt(start, default=(math.ceil(float(current)/float(grpsize))*grpsize-(grpsize-1)))
564: # int(current / grpsize) * grpsize +1))
1.3 casties 565: pageinfo['start'] = start
1.4 casties 566: pageinfo['end'] = start + grpsize
567: if docinfo is not None:
568: np = int(docinfo['numPages'])
569: pageinfo['end'] = min(pageinfo['end'], np)
570: pageinfo['numgroups'] = int(np / grpsize)
571: if np % grpsize > 0:
572: pageinfo['numgroups'] += 1
573:
1.3 casties 574: return pageinfo
575:
1.1 dwinter 576: def text(self,mode,url,pn):
577: """give text"""
578: if mode=="texttool": #index.meta with texttool information
579: (viewerUrl,imagepath,textpath)=parseUrlTextTool(url)
580:
1.9 casties 581: #print textpath
1.1 dwinter 582: try:
583: dom = NonvalidatingReader.parseUri(textpath)
584: except:
585: return None
586:
587: list=[]
588: nodes=dom.xpath("//pb")
589:
590: node=nodes[int(pn)-1]
591:
592: p=node
593:
594: while p.tagName!="p":
595: p=p.parentNode
596:
597:
598: endNode=nodes[int(pn)]
599:
600:
601: e=endNode
602:
603: while e.tagName!="p":
604: e=e.parentNode
605:
606:
607: next=node.parentNode
608:
609: #sammle s
610: while next and (next!=endNode.parentNode):
611: list.append(next)
612: next=next.nextSibling
613: list.append(endNode.parentNode)
614:
615: if p==e:# beide im selben paragraphen
1.2 dwinter 616: pass
617: # else:
618: # next=p
619: # while next!=e:
620: # print next,e
621: # list.append(next)
622: # next=next.nextSibling
623: #
624: # for x in list:
625: # PrettyPrint(x)
626: #
627: # return list
1.3 casties 628: #
629:
630: def findDigilibUrl(self):
631: """try to get the digilib URL from zogilib"""
632: url = self.imageViewerUrl[:-1] + "/getScalerUrl"
1.20 dwinter 633: #print urlparse.urlparse(url)[0]
634: #print urlparse.urljoin(self.absolute_url(),url)
635: logging.info("finddigiliburl: %s"%urlparse.urlparse(url)[0])
636: logging.info("finddigiliburl: %s"%urlparse.urljoin(self.absolute_url(),url))
637:
1.3 casties 638: try:
1.18 dwinter 639: if urlparse.urlparse(url)[0]=='': #relative path
640: url=urlparse.urljoin(self.absolute_url()+"/",url)
641:
1.3 casties 642: scaler = urlopen(url).read()
643: return scaler.replace("/servlet/Scaler?", "")
644: except:
645: return None
646:
1.18 dwinter 647: def changeDocumentViewer(self,imageViewerUrl,textViewerUrl,title="",digilibBaseUrl=None,thumbrows=2,thumbcols=10,authgroups='mpiwg',RESPONSE=None):
1.3 casties 648: """init document viewer"""
649: self.title=title
650: self.imageViewerUrl=imageViewerUrl
1.18 dwinter 651: self.textViewerUrl=textViewerUrl
1.3 casties 652: self.digilibBaseUrl = digilibBaseUrl
1.4 casties 653: self.thumbrows = thumbrows
654: self.thumbcols = thumbcols
1.8 casties 655: self.authgroups = [s.strip().lower() for s in authgroups.split(',')]
1.3 casties 656: if RESPONSE is not None:
657: RESPONSE.redirect('manage_main')
1.1 dwinter 658:
659:
660:
661:
662: # security.declareProtected('View management screens','renameImageForm')
663:
664: def manage_AddDocumentViewerForm(self):
665: """add the viewer form"""
1.3 casties 666: pt=PageTemplateFile('zpt/addDocumentViewer', globals()).__of__(self)
1.1 dwinter 667: return pt()
668:
1.18 dwinter 669: def manage_AddDocumentViewer(self,id,imageViewerUrl="",textViewerUrl="",title="",RESPONSE=None):
1.1 dwinter 670: """add the viewer"""
1.18 dwinter 671: newObj=documentViewer(id,imageViewerUrl,title=title,textViewerUrl=textViewerUrl)
1.1 dwinter 672: self._setObject(id,newObj)
673:
674: if RESPONSE is not None:
675: RESPONSE.redirect('manage_main')
1.3 casties 676:
677:
678: ##
679: ## DocumentViewerTemplate class
680: ##
681: class DocumentViewerTemplate(ZopePageTemplate):
682: """Template for document viewer"""
683: meta_type="DocumentViewer Template"
684:
685:
686: def manage_addDocumentViewerTemplateForm(self):
687: """Form for adding"""
688: pt=PageTemplateFile('zpt/addDocumentViewerTemplate', globals()).__of__(self)
689: return pt()
690:
691: def manage_addDocumentViewerTemplate(self, id='viewer_main', title=None, text=None,
692: REQUEST=None, submit=None):
693: "Add a Page Template with optional file content."
694:
695: self._setObject(id, DocumentViewerTemplate(id))
696: ob = getattr(self, id)
1.23 dwinter 697: txt=file(os.path.join(package_home(globals()),'zpt/viewer_main.zpt'),'r').read()
698: logging.info("txt %s:"%txt)
699: ob.pt_edit(txt,"text/html")
1.3 casties 700: if title:
701: ob.pt_setTitle(title)
702: try:
703: u = self.DestinationURL()
704: except AttributeError:
705: u = REQUEST['URL1']
706:
707: u = "%s/%s" % (u, urllib.quote(id))
708: REQUEST.RESPONSE.redirect(u+'/manage_main')
709: return ''
710:
711:
1.14 casties 712:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>