source: documentViewer/SrvTxtUtils.py @ 613:c57d80a649ea

Last change on this file since 613:c57d80a649ea was 613:c57d80a649ea, checked in by casties, 11 years ago

CLOSED - # 281: List of thumbnails verschluckt Seite, wenn odd-scan-position gesetzt ist
https://it-dev.mpiwg-berlin.mpg.de/tracs/mpdl-project-software/ticket/281

File size: 8.5 KB
Line 
1"""Utility methods for handling XML, reading HTTP, etc"""
2
3from App.ImageFile import ImageFile
4from App.Common import rfc1123_date
5
6import sys
7import os
8import stat
9import urllib
10import logging
11import time
12import re
13import string
14import datetime
15try:
16    import httplib2
17    httplib = 'httplib2'
18except:
19    logging.warn("Unable to import httplib2! Falling back to urllib2!")
20    import urllib2
21    httplib = 'urllib2'
22
23import xml.etree.ElementTree as ET
24
25srvTxtUtilsVersion = "1.12.1"
26
27map_months = {'en': [u"",
28               u"January",
29               u"February",
30               u"March",
31               u"April",
32               u"May",
33               u"June",
34               u"July",
35               u"August",
36               u"September",
37               u"October",
38               u"November",
39               u"December"],
40              'de': [u"",
41               u"Januar",
42               u"Februar",
43               u"M\u00e4rz",
44               u"April",
45               u"Mai",
46               u"Juni",
47               u"Juli",
48               u"August",
49               u"September",
50               u"Oktober",
51               u"November",
52               u"Dezember"]}
53
54def getInt(number, default=0):
55    """returns always an int (0 in case of problems)"""
56    try:
57        return int(number)
58    except:
59        return int(default)
60
61def getAt(array, idx, default=None):
62    """returns element idx from array or default (in case of problems)"""
63    try:
64        return array[idx]
65    except:
66        return default
67
68def unicodify(s):
69    """decode str (utf-8 or latin-1 representation) into unicode object"""
70    if not s:
71        return u""
72    if isinstance(s, str):
73        try:
74            return s.decode('utf-8')
75        except:
76            return s.decode('latin-1')
77    else:
78        return s
79
80def utf8ify(s):
81    """encode unicode object or string into byte string in utf-8 representation.
82       assumes string objects to be utf-8"""
83    if not s:
84        return ""
85    if isinstance(s, str):
86        return s
87    else:
88        return s.encode('utf-8')
89
90def getText(node, recursive=0):
91    """returns all text content of a (etree) node and its subnodes"""
92    if node is None:
93        return ''
94   
95    # ElementTree:
96    text = node.text or ''
97    for e in node:
98        if recursive:
99            text += getText(e)
100        else:
101            text += e.text or ''
102        if e.tail:
103            text += e.tail
104
105    # 4Suite:
106    #nodelist=node.childNodes
107    #text = ""
108    #for n in nodelist:
109    #    if n.nodeType == node.TEXT_NODE:
110    #       text = text + n.data
111   
112    return text
113
114
115def serialize(node):
116    """returns a string containing an XML snippet of (etree) node"""
117    s = ET.tostring(node, 'UTF-8')
118    # snip off XML declaration
119    if s.startswith('<?xml'):
120        i = s.find('?>')
121        return s[i+3:]
122
123    return s
124
125
126def getMonthName(mon, lang):
127    """returns the name of the month mon in the language lang"""
128    return map_months[lang][mon]
129
130
131def getDateString(date=None, lang='en', withYear=True, monthNames=True, abbrev=False):
132    """Return formatted date string."""
133    if date is None:
134        return None
135   
136    ds = None
137    if callable(date.day):
138        # callable members
139        day = date.day()
140        month = date.month()
141        year = date.year()
142    else:
143        # data members
144        day = date.day
145        month = date.month
146        year = date.year
147       
148    if lang.lower() == 'en':
149        ds = "%s %s"%(getMonthName(month, lang), day)
150        if withYear:
151            ds += ", %s"%year
152           
153    elif lang.lower() == 'de':
154        ds = "%s. %s"%(day, getMonthName(month, lang))
155        if withYear:
156            ds += " %s"%year
157
158    elif lang.lower() == 'iso':
159        ds = date.isoformat()
160           
161    return ds
162       
163
164def getDate(date):
165    """return date object from date or datetime date."""
166    if isinstance(date, datetime.datetime):
167        # strip time
168        return date.date()
169   
170    return date
171
172
173def getDatetime(date):
174    """return datetime object from date or datetime date."""
175    if isinstance(date, datetime.date):
176        # add time 0:00
177        return datetime.datetime.combine(date, datetime.time())
178   
179    return date
180
181
182def getHttpData(url, data=None, num_tries=3, timeout=10, username=None, password=None, cache=None, insecure=False, noExceptions=False):
183    """returns result from url+data HTTP request"""
184    # we do GET (by appending data to url)
185    if isinstance(data, str) or isinstance(data, unicode):
186        # if data is string then append
187        url = "%s?%s"%(url,data)
188    elif isinstance(data, dict) or isinstance(data, list) or isinstance(data, tuple):
189        # urlencode
190        url = "%s?%s"%(url,urllib.urlencode(data))
191
192    errmsg = None
193    if httplib == 'httplib2':
194        # use httplib2
195        for cnt in range(num_tries):
196            try:
197                logging.debug("getHttp(lib2)Data(#%s %ss) url=%s"%(cnt+1,timeout,url))
198                h = httplib2.Http(cache=cache, timeout=float(timeout), disable_ssl_certificate_validation=insecure)
199                if username:
200                    h.add_credentials(username, password)
201                   
202                resp, data = h.request(url)
203                return data
204           
205            except httplib2.HttpLib2Error, e:
206                logging.error("getHttp(lib2)Data: HTTP error(%s): %s"%(e.code,e))
207                errmsg = str(e)
208                # stop trying
209                break
210   
211    else:
212        # use urllib2
213        response = None
214        for cnt in range(num_tries):
215            try:
216                logging.debug("getHttpData(#%s %ss) url=%s"%(cnt+1,timeout,url))
217                if sys.version_info < (2, 6):
218                    # set timeout on socket -- ugly :-(
219                    import socket
220                    socket.setdefaulttimeout(float(timeout))
221                    response = urllib2.urlopen(url)
222                else:
223                    # timeout as parameter
224                    response = urllib2.urlopen(url,timeout=float(timeout))
225                # check result?
226                data = response.read()
227                response.close()
228                return data
229
230            except urllib2.HTTPError, e:
231                logging.error("getHttpData: HTTP error(%s): %s"%(e.code,e))
232                errmsg = str(e)
233                # stop trying
234                break
235            except urllib2.URLError, e:
236                logging.error("getHttpData: URLLIB error(%s): %s"%(e.reason,e))
237                errmsg = str(e)
238                # stop trying
239                #break
240   
241    if noExceptions:
242        return None
243   
244    raise IOError("ERROR fetching HTTP data from %s: %s"%(url,errmsg))
245    #return None
246
247
248def refreshingImageFileIndexHtml(self, REQUEST, RESPONSE):
249    """index_html method for App.ImageFile that updates the file info for each request."""
250    stat_info = os.stat(self.path)
251    self.size = stat_info[stat.ST_SIZE]
252    self.lmt = float(stat_info[stat.ST_MTIME]) or time.time()
253    self.lmh = rfc1123_date(self.lmt)
254    # call original method
255    return ImageFile.index_html(self, REQUEST, RESPONSE)
256
257
258def shortenString(s, l, ellipsis='...'):
259    """returns a string of length l (or l-1) by omitting characters in the middle of s, replacing with ellipsis."""
260    if len(s) <= l:
261        return s
262   
263    l1 = int((l - len(ellipsis)) / 2)
264    return "%s%s%s"%(s[:l1],ellipsis,s[-l1:])
265
266
267def sqlName(s, lc=True, more=''):
268    """returns restricted ASCII-only version of string"""
269    if s is None:
270        return ""
271   
272    if not isinstance(s, basestring):
273        # make string object
274        s = str(s)
275       
276    # remove '
277    s = s.replace("'","")
278    # all else -> "_"
279    s = re.sub('[^A-Za-z0-9_'+more+']','_',s)
280    if lc:
281        return s.lower()
282   
283    return s
284
285
286def getBrowserType(self):
287    """(legacy) check the browsers request to find out the browser type"""
288    bt = {}
289    ua = self.REQUEST.get_header("HTTP_USER_AGENT")
290    bt['ua'] = ua
291    bt['isIE'] = False
292    bt['isN4'] = False
293    if string.find(ua, 'MSIE') > -1:
294        bt['isIE'] = True
295    else:
296        bt['isN4'] = (string.find(ua, 'Mozilla/4.') > -1)
297       
298    try:
299        nav = ua[string.find(ua, '('):]
300        ie = string.split(nav, "; ")[1]
301        if string.find(ie, "MSIE") > -1:
302            bt['versIE'] = string.split(ie, " ")[1]
303    except: pass
304   
305    bt['isMac'] = string.find(ua, 'Macintosh') > -1
306    bt['isWin'] = string.find(ua, 'Windows') > -1
307    bt['isIEWin'] = bt['isIE'] and bt['isWin']
308    bt['isIEMac'] = bt['isIE'] and bt['isMac']
309    bt['staticHTML'] = False
310
311    return bt
312
Note: See TracBrowser for help on using the repository browser.