openmedialibrary_platform/Shared/lib/python3.7/site-packages/ox/net.py

184 lines
5.9 KiB
Python
Raw Normal View History

2013-10-11 17:28:32 +00:00
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
# GPL 2008
2018-12-15 00:08:54 +00:00
from __future__ import print_function
2013-10-11 17:28:32 +00:00
import gzip
2015-11-04 12:01:55 +00:00
import json
import os
2013-10-11 17:28:32 +00:00
import re
import struct
2019-01-13 08:01:53 +00:00
try:
import requests
USE_REQUESTS = True
except:
USE_REQUESTS = False
2016-02-23 06:06:55 +00:00
from six import BytesIO, PY2
2015-11-04 12:01:55 +00:00
from six.moves import urllib
2013-10-11 17:28:32 +00:00
from chardet.universaldetector import UniversalDetector
DEBUG = False
# Default headers for HTTP requests.
DEFAULT_HEADERS = {
2018-12-15 00:08:54 +00:00
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0',
2013-10-11 17:28:32 +00:00
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
2018-12-15 00:08:54 +00:00
'Accept-Language': 'en-US,en;q=0.8,fr;q=0.6,de;q=0.4',
'Accept-Encoding': 'gzip',
2013-10-11 17:28:32 +00:00
}
2018-12-15 00:08:54 +00:00
def status(url, data=None, headers=None):
2013-10-11 17:28:32 +00:00
try:
f = open_url(url, data, headers)
s = f.code
2014-09-30 16:15:32 +00:00
except urllib.error.HTTPError as e:
2013-10-11 17:28:32 +00:00
s = e.code
return s
2018-12-15 00:08:54 +00:00
def exists(url, data=None, headers=None):
2013-10-11 17:28:32 +00:00
s = status(url, data, headers)
if s >= 200 and s < 400:
return True
return False
2018-12-15 00:08:54 +00:00
def get_headers(url, data=None, headers=None):
2013-10-11 17:28:32 +00:00
try:
f = open_url(url, data, headers)
f.headers['Status'] = "%s" % f.code
headers = f.headers
f.close()
2014-09-30 16:15:32 +00:00
except urllib.error.HTTPError as e:
2013-10-11 17:28:32 +00:00
e.headers['Status'] = "%s" % e.code
headers = e.headers
return dict(headers)
2018-12-15 00:08:54 +00:00
def get_json(url, data=None, headers=None):
return json.loads(read_url(url, data, headers).decode('utf-8')) # pylint: disable=no-member
2015-11-04 12:01:55 +00:00
2018-12-15 00:08:54 +00:00
def open_url(url, data=None, headers=None):
if headers is None:
headers = DEFAULT_HEADERS.copy()
2016-02-23 06:06:55 +00:00
if PY2:
2015-11-04 12:01:55 +00:00
if not isinstance(url, bytes):
url = url.encode('utf-8')
2016-02-23 06:06:55 +00:00
else:
if isinstance(url, bytes):
url = url.decode('utf-8')
2013-10-11 17:28:32 +00:00
url = url.replace(' ', '%20')
2016-02-23 06:06:55 +00:00
if data and not PY2 and not isinstance(data, bytes):
2014-10-04 19:08:57 +00:00
data = data.encode('utf-8')
2014-09-30 16:15:32 +00:00
req = urllib.request.Request(url, data, headers)
return urllib.request.urlopen(req)
2013-10-11 17:28:32 +00:00
2018-12-15 00:08:54 +00:00
def read_url(url, data=None, headers=None, return_headers=False, unicode=False):
2013-10-11 17:28:32 +00:00
if DEBUG:
2014-09-30 16:15:32 +00:00
print('ox.net.read_url', url)
2013-10-11 17:28:32 +00:00
f = open_url(url, data, headers)
result = f.read()
f.close()
if f.headers.get('content-encoding', None) == 'gzip':
2014-09-30 16:15:32 +00:00
result = gzip.GzipFile(fileobj=BytesIO(result)).read()
2013-10-11 17:28:32 +00:00
if unicode:
2014-09-30 16:15:32 +00:00
ctype = f.headers.get('content-type', '').lower()
if 'charset' in ctype:
encoding = ctype.split('charset=')[-1]
else:
encoding = detect_encoding(result)
2013-10-11 17:28:32 +00:00
if not encoding:
encoding = 'latin-1'
result = result.decode(encoding)
if return_headers:
f.headers['Status'] = "%s" % f.code
2014-09-30 16:15:32 +00:00
headers = {}
for key in f.headers:
headers[key.lower()] = f.headers[key]
return headers, result
2013-10-11 17:28:32 +00:00
return result
def detect_encoding(data):
2014-09-30 16:15:32 +00:00
data_lower = data.lower().decode('utf-8', 'ignore')
charset = re.compile('content="text/html; charset=(.*?)"').findall(data_lower)
2013-10-11 17:28:32 +00:00
if not charset:
2014-09-30 16:15:32 +00:00
charset = re.compile('meta charset="(.*?)"').findall(data_lower)
2013-10-11 17:28:32 +00:00
if charset:
return charset[0].lower()
detector = UniversalDetector()
2014-09-30 16:15:32 +00:00
p = 0
l = len(data)
s = 1024
while p < l:
detector.feed(data[p:p+s])
2013-10-11 17:28:32 +00:00
if detector.done:
break
2014-09-30 16:15:32 +00:00
p += s
2013-10-11 17:28:32 +00:00
detector.close()
return detector.result['encoding']
2018-12-15 00:08:54 +00:00
get_url = read_url
2015-11-04 12:01:55 +00:00
2013-10-11 17:28:32 +00:00
def save_url(url, filename, overwrite=False):
if not os.path.exists(filename) or overwrite:
dirname = os.path.dirname(filename)
2015-11-04 12:01:55 +00:00
if dirname and not os.path.exists(dirname):
2013-10-11 17:28:32 +00:00
os.makedirs(dirname)
2019-01-13 08:01:53 +00:00
headers = DEFAULT_HEADERS.copy()
if USE_REQUESTS:
r = requests.get(url, headers=headers, stream=True)
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
else:
data = read_url(url)
with open(filename, 'wb') as f:
f.write(data)
2013-10-11 17:28:32 +00:00
2018-12-15 00:08:54 +00:00
def _get_size(url):
req = urllib.request.Request(url, headers=DEFAULT_HEADERS.copy())
req.get_method = lambda: 'HEAD'
u = urllib.request.urlopen(req)
if u.code != 200 or 'Content-Length' not in u.headers:
raise IOError
return int(u.headers['Content-Length'])
def _get_range(url, start, end):
headers = DEFAULT_HEADERS.copy()
headers['Range'] = 'bytes=%s-%s' % (start, end)
req = urllib.request.Request(url, headers=headers)
u = urllib.request.urlopen(req)
return u.read()
2013-10-11 17:28:32 +00:00
2018-12-15 00:08:54 +00:00
def oshash(url):
2013-10-11 17:28:32 +00:00
try:
longlongformat = 'q' # long long
bytesize = struct.calcsize(longlongformat)
2018-12-15 00:08:54 +00:00
filesize = _get_size(url)
hash_ = filesize
head = _get_range(url, 0, min(filesize, 65536))
2013-10-11 17:28:32 +00:00
if filesize > 65536:
2018-12-15 00:08:54 +00:00
tail = _get_range(url, filesize-65536, filesize)
2013-10-11 17:28:32 +00:00
if filesize < 65536:
2015-11-04 12:01:55 +00:00
f = BytesIO(head)
2018-12-15 00:08:54 +00:00
for _ in range(int(filesize/bytesize)):
2015-11-04 12:01:55 +00:00
buffer = f.read(bytesize)
2018-12-15 00:08:54 +00:00
(l_value,) = struct.unpack(longlongformat, buffer)
hash_ += l_value
hash_ = hash_ & 0xFFFFFFFFFFFFFFFF # cut off 64bit overflow
2013-10-11 17:28:32 +00:00
else:
for offset in range(0, 65536, bytesize):
buffer = head[offset:offset+bytesize]
2018-12-15 00:08:54 +00:00
(l_value,) = struct.unpack(longlongformat, buffer)
hash_ += l_value
hash_ = hash_ & 0xFFFFFFFFFFFFFFFF # cut of 64bit overflow
2013-10-11 17:28:32 +00:00
for offset in range(0, 65536, bytesize):
buffer = tail[offset:offset+bytesize]
2018-12-15 00:08:54 +00:00
(l_value,) = struct.unpack(longlongformat, buffer)
hash_ += l_value
hash_ = hash_ & 0xFFFFFFFFFFFFFFFF
returnedhash = "%016x" % hash_
2013-10-11 17:28:32 +00:00
return returnedhash
2018-12-15 00:08:54 +00:00
except IOError:
2013-10-11 17:28:32 +00:00
return "IOError"