Annotation of documentViewer/documentViewer.py, revision 1.27

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>