http_functions.py 7.28 KB
Newer Older
Thilo Molitor's avatar
Thilo Molitor committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
# -*- coding: utf-8 -*-
##
## This file is part of Gajim.
##
## Gajim is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published
## by the Free Software Foundation; version 3 only.
##
## Gajim is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Gajim.  If not, see <http://www.gnu.org/licenses/>.
##

import urllib.request as urllib2
import socket
import re

from gajim.common import app
from gajim.common import helpers
import logging

import os
if os.name == 'nt':
    import certifi

if app.HAVE_PYCURL:
    import pycurl
    from io import StringIO


log = logging.getLogger('gajim.plugin_system.url_image_preview.http_functions')

def get_http_head(account, url):
    # Check if proxy is used
    proxy = helpers.get_proxy_info(account)
    if proxy and proxy['type'] in ('http', 'socks5'):
        return _get_http_head_proxy(url, proxy)
    return _get_http_head_direct(url)

def get_http_file(account, attrs):
    # Check if proxy is used
    proxy = helpers.get_proxy_info(account)
    if proxy and proxy['type'] in ('http', 'socks5'):
        return _get_http_proxy(attrs, proxy)
    else:
        return _get_http_direct(attrs)

def _get_http_head_direct(url):
    log.debug('Head request direct for URL: %s' % url)
    try:
        req = urllib2.Request(url)
        req.get_method = lambda: 'HEAD'
        req.add_header('User-Agent', 'Gajim %s' % app.version)
        if os.name == 'nt':
            f = urllib2.urlopen(req, cafile=certifi.where())
        else:
            f = urllib2.urlopen(req)
    except Exception as ex:
        log.debug('Could not get head response for URL: %s' % url)
        log.debug("%s" % str(ex))
        return ('', 0)
    ctype = f.headers['Content-Type']
    clen = f.headers['Content-Length']
    try:
        clen = int(clen)
70
    except (TypeError, ValueError):
Thilo Molitor's avatar
Thilo Molitor committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
        pass
    return (ctype, clen)

def _get_http_head_proxy(url, proxy):
    log.debug('Head request with proxy for URL: %s' % url)
    if not app.HAVE_PYCURL:
        log.error('PYCURL not installed')
        return ('', 0)

    headers = ''
    try:
        b = StringIO()
        c = pycurl.Curl()
        c.setopt(pycurl.URL, url.encode('utf-8'))
        c.setopt(pycurl.FOLLOWLOCATION, 1)
        # Make a HEAD request:
        c.setopt(pycurl.CUSTOMREQUEST, 'HEAD')
        c.setopt(pycurl.NOBODY, 1)
        c.setopt(pycurl.HEADER, 1)

        c.setopt(pycurl.MAXFILESIZE, 2000000)
        c.setopt(pycurl.WRITEFUNCTION, b.write)
        c.setopt(pycurl.USERAGENT, 'Gajim ' + app.version)

        # set proxy
        c.setopt(pycurl.PROXY, proxy['host'].encode('utf-8'))
        c.setopt(pycurl.PROXYPORT, proxy['port'])
        if proxy['useauth']:
            c.setopt(pycurl.PROXYUSERPWD, proxy['user'].encode('utf-8') +
                        ':' + proxy['pass'].encode('utf-8'))
            c.setopt(pycurl.PROXYAUTH, pycurl.HTTPAUTH_ANY)
        if proxy['type'] == 'http':
            c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_HTTP)
        elif proxy['type'] == 'socks5':
            c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)
        x = c.perform()
        c.close()
        headers = b.getvalue()
    except pycurl.error as ex:
        log.debug('Could not get head response for URL: %s' % url)
        log.debug("%s" % str(ex))
        return ('', 0)

    ctype = ''
    searchObj = re.search(r'^Content-Type: (.*)$', headers, re.M | re.I)
    if searchObj:
        ctype = searchObj.group(1).strip()
    clen = 0
    searchObj = re.search(r'^Content-Length: (.*)$', headers, re.M | re.I)
    if searchObj:
        try:
            clen = int(searchObj.group(1).strip())
        except ValueError:
            pass
    return (ctype, clen)

def _get_http_direct(attrs):
    """
    Download a file. This function should
    be launched in a separated thread.
    """
    log.debug('Get request direct for URL: %s' % attrs['src'])
    mem, alt, max_size = b'', '', 2 * 1024 * 1024
    if 'max_size' in attrs:
        max_size = attrs['max_size']
    try:
        req = urllib2.Request(attrs['src'])
        req.add_header('User-Agent', 'Gajim ' + app.version)
        if os.name == 'nt':
            f = urllib2.urlopen(req, cafile=certifi.where())
        else:
            f = urllib2.urlopen(req)
    except Exception as ex:
        log.debug('Error loading file %s '
                    % attrs['src'] + str(ex))
        pixbuf = None
        alt = attrs.get('alt', 'Broken image')
    else:
        while True:
            try:
                temp = f.read(100)
            except socket.timeout as ex:
                log.debug('Timeout loading image %s '
                            % attrs['src'] + str(ex))
                alt = attrs.get('alt', '')
                if alt:
                    alt += '\n'
                alt += _('Timeout loading image')
                break
            if temp:
                mem += temp
            else:
                break
            if len(mem) > max_size:
                alt = attrs.get('alt', '')
                if alt:
                    alt += '\n'
                alt += _('Image is too big')
                break
    return (mem, alt)

def _get_http_proxy(attrs, proxy):
    """
    Download an image through a proxy.
    This function should be launched in a
    separated thread.
    """
    log.debug('Get request with proxy for URL: %s' % attrs['src'])
    if not app.HAVE_PYCURL:
        log.error('PYCURL not installed')
        return '', _('PyCURL is not installed')
    mem, alt, max_size = '', '', 2 * 1024 * 1024
    if 'max_size' in attrs:
        max_size = attrs['max_size']
    try:
        b = StringIO()
        c = pycurl.Curl()
        c.setopt(pycurl.URL, attrs['src'].encode('utf-8'))
        c.setopt(pycurl.FOLLOWLOCATION, 1)
        c.setopt(pycurl.MAXFILESIZE, max_size)
        c.setopt(pycurl.WRITEFUNCTION, b.write)
        c.setopt(pycurl.USERAGENT, 'Gajim ' + app.version)
        # set proxy
        c.setopt(pycurl.PROXY, proxy['host'].encode('utf-8'))
        c.setopt(pycurl.PROXYPORT, proxy['port'])
        if proxy['useauth']:
            c.setopt(pycurl.PROXYUSERPWD, proxy['user'].encode('utf-8') +
                        ':' + proxy['pass'].encode('utf-8'))
            c.setopt(pycurl.PROXYAUTH, pycurl.HTTPAUTH_ANY)
        if proxy['type'] == 'http':
            c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_HTTP)
        elif proxy['type'] == 'socks5':
            c.setopt(pycurl.PROXYTYPE, pycurl.PROXYTYPE_SOCKS5)
        x = c.perform()
        c.close()
        t = b.getvalue()
        return (t, attrs.get('alt', ''))
    except pycurl.error as ex:
        alt = attrs.get('alt', '')
        if alt:
            alt += '\n'
        if ex[0] == pycurl.E_FILESIZE_EXCEEDED:
            alt += _('Image is too big')
        elif ex[0] == pycurl.E_OPERATION_TIMEOUTED:
            alt += _('Timeout loading image')
        else:
            alt += _('Error loading image')
    except Exception as ex:
        log.debug('Error loading file %s ' % attrs['src'] + str(ex))
        pixbuf = None
        alt = attrs.get('alt', 'Broken image')
    return ('', alt)