File:  [Repository] / documentViewer / documentViewer.py
Revision 1.1: download - view: text, annotated - select for diffs - revision graph
Sun Dec 18 12:35:02 2005 UTC (18 years, 6 months ago) by dwinter
Branches: MAIN
CVS tags: HEAD
fist


genericDigilib="http://nausikaa2.rz-berlin.mpg.de/digitallibrary/"

from OFS.Folder import Folder
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from AccessControl import ClassSecurityInfo
from Globals import package_home

from Ft.Xml.Domlette import NonvalidatingReader
from Ft.Xml.Domlette import PrettyPrint, Print
from Ft.Xml import EMPTY_NAMESPACE

import Ft.Xml.XPath

import os.path
import cgi
import urllib

def getTextFromNode(nodename):
    nodelist=nodename.childNodes
    rc = ""
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
           rc = rc + node.data
    return rc

import socket

def urlopen(url):
        """urlopen mit timeout"""
        socket.setdefaulttimeout(2)
        ret=urllib.urlopen(url)
        socket.setdefaulttimeout(5)
        return ret
    
def getParamFromDigilib(path,param):
    """gibt param von dlInfo aus"""
    imageUrl=genericDigilib+"/dlInfo-xml.jsp?fn="+path

    try:
        dom = NonvalidatingReader.parseUri(imageUrl)
    except:
        return None
    
    
    params=dom.xpath("//document-parameters/parameter[@name='%s']/@value"%param)
    
    if params:
        return params[0].value
    
def parseUrlTextTool(url):
   """parse index meta"""
    
   try:
       dom = NonvalidatingReader.parseUri(url)
   except:
       zLOG.LOG("documentViewer (parseUrlTexttool)", zLOG.INFO,"%s (%s)"%sys.exc_info()[0:2])
       return (None,None,None)
   
   archivePaths=dom.xpath("//resource/archive-path")
   
   if archivePaths and (len(archivePaths)>0):
       archivePath=getTextFromNode(archivePaths[0])
   else:
       archivePath=None
   
    
   images=dom.xpath("//texttool/image")
   
   if images and (len(images)>0):
       image=getTextFromNode(images[0])
   else:
       image=None
       
   if image and archivePath:
       image=os.path.join(archivePath,image)
       image=image.replace("/mpiwg/online",'')
       pt=getParamFromDigilib(image,'pt')

   else:
       image=None
       
   viewerUrls=dom.xpath("//texttool/digiliburlprefix")
   
   if viewerUrls and (len(viewerUrls)>0):
       viewerUrl=getTextFromNode(viewerUrls[0])
   else:
       viewerUrl=None
   
   
   textUrls=dom.xpath("//texttool/text")
   
   if textUrls and (len(textUrls)>0):
       textUrl=getTextFromNode(textUrls[0])
   else:
       textUrl=None
   return viewerUrl,(image,pt),textUrl


class documentViewer(ZopePageTemplate):
    """document viewer"""

    meta_type="Document viewer"
    
    security=ClassSecurityInfo()
    manage_options=ZopePageTemplate.manage_options+(
        {'label':'main config','action':'changeDocumentViewerForm'},
        )

    _default_content_fn = os.path.join(package_home(globals()),'zpt','documentViewer_template.zpt')
    
    def __init__(self,id,imageViewerUrl,title=""):
        """init document viewer"""
        self.id=id
        self.title=title
        self.imageViewerUrl=imageViewerUrl
        
    security.declareProtected('View management screens','changeDocumentViewerForm')    
    def changeDocumentViewerForm(self):
        """change it"""
        pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','changeDocumentViewer.zpt')).__of__(self)
        return pt()
  
  
    def changeDocumentViewer(self,imageViewerUrl,title="",RESPONSE=None):
        """init document viewer"""
        self.title=title
        self.imageViewerUrl=imageViewerUrl
        
        if RESPONSE is not None:
            RESPONSE.redirect('manage_main')
    
    
    def imageLink(self,nr):
        """link hinter den images"""
        paramsTmp=cgi.parse_qs(self.REQUEST['QUERY_STRING'])
        params={}
        for x in paramsTmp.iteritems():
                params[x[0]]=x[1][0]
    
        params['pn']=nr
        newUrl=self.REQUEST['URL']+"?"+urllib.urlencode(params)
        return newUrl
        
        
    def thumbruler(self,cols,rows,start,maximum):
        """ruler for thumbs"""
        ret=""
        paramsTmp=cgi.parse_qs(self.REQUEST['QUERY_STRING'])
        params={}
        for x in paramsTmp.iteritems():

            if not x[0]=="start":
                params[x[0]]=x[1][0]

        newUrlSelect=self.REQUEST['URL']+"?"+urllib.urlencode(params)    
        if start>0:
            newStart=max(start-cols*rows,0)
            params['start']=newStart
            newUrl=self.REQUEST['URL']+"?"+urllib.urlencode(params)
            ret+="""<a href="%s">prev</a>"""%newUrl


        ret+="""<select onChange="location.href='%s&start='+this.options[this.selectedIndex].value" """%newUrlSelect
        nr,rest=divmod(maximum,cols*rows)
        if rest > 0:
            nr+=1
        for i in range(nr):
            nr=i*cols*rows
           
            if (start >= nr) and (start < nr+cols*rows):  
                ret+="""<option value="%s" selected>%s</option>"""%(nr,nr)
            else:
                ret+="""<option value="%s">%s</option>"""%(nr,nr)
        ret+="</select>"
        
        if start<maximum:
            newStart=min(start+cols*rows,maximum)
            params['start']=newStart
            newUrl=self.REQUEST['URL']+"?"+urllib.urlencode(params)
            ret+="""<a href="%s">next</a>"""%newUrl
        
        return ret
        
    def textToolThumb(self,url,start=0):
        """understands the texttool format
        @param url: url to index.meta with texttool tag
        """
        (viewerUrl,imagepath,textpath)=parseUrlTextTool(url)
        
        imageUrl=genericDigilib+"/servlet/Scaler?fn=%s"%imagepath[0]
        
        pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','thumbs.zpt')).__of__(self)
        return pt(imageUrl=imageUrl,pt=imagepath[1],start=start)
    
    def text(self,mode,url,pn):
        """give text"""
        if mode=="texttool": #index.meta with texttool information
            (viewerUrl,imagepath,textpath)=parseUrlTextTool(url)
        
        print textpath
        try:
            dom = NonvalidatingReader.parseUri(textpath)
        except:
            return None
    
        list=[]
        nodes=dom.xpath("//pb")

        node=nodes[int(pn)-1]
        
        p=node
        
        while p.tagName!="p":
            p=p.parentNode
        
        
        endNode=nodes[int(pn)]
        
        
        e=endNode
        
        while e.tagName!="p":
            e=e.parentNode
        
        
        next=node.parentNode
        
        #sammle s
        while next and (next!=endNode.parentNode):
            list.append(next)    
            next=next.nextSibling    
        list.append(endNode.parentNode)
        
        if p==e:# beide im selben paragraphen
        
    else:
            next=p
            while next!=e:
                print next,e
                list.append(next)
                next=next.nextSibling
            
        for x in list:
            PrettyPrint(x)

        return list
    
    def image(self,mode,url,pn):
        """give image out"""
        if mode=="texttool": #index.meta with texttool information
            (viewerUrl,imagepath,textpath)=parseUrlTextTool(url)
            url=viewerUrl+"pn=%s&fn=%s"%(pn,imagepath[0])
            ret="""<iframe height="100%%" width="100%%" src="%s"/>"""%url
            return url
        
    def thumbs(self,mode,url,start):
        """give thumbs out"""
        if mode=="texttool": #index.meta with texttool information
            return self.textToolThumb(url,int(start))
        
    security.declareProtected('View','index_html')
    
    
    def index_html(self,mode,url,start=0,pn=0):
        '''
        view it
        @param mode: defines which type of document is behind url
        @param url: url which contains display information
        '''
        
    
        pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','documentViewer_template.zpt')).__of__(self)
        return pt(mode=mode,url=url,start=start,pn=pn)
        
        
        
#    security.declareProtected('View management screens','renameImageForm')

def manage_AddDocumentViewerForm(self):
    """add the viewer form"""
    pt=PageTemplateFile(os.path.join(package_home(globals()),'zpt','addDocumentViewer.zpt')).__of__(self)
    return pt()
  
def manage_AddDocumentViewer(self,id,imageViewerUrl="",title="",RESPONSE=None):
    """add the viewer"""
    newObj=documentViewer(id,imageViewerUrl,title)
    self._setObject(id,newObj)
    
    if RESPONSE is not None:
        RESPONSE.redirect('manage_main')
    

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