Esempio n. 1
0
    def __init__(self,
                 con_pool_size=1,
                 proxy_url=None,
                 urllib3_proxy_kwargs=None,
                 connect_timeout=5.,
                 read_timeout=5.):
        if urllib3_proxy_kwargs is None:
            urllib3_proxy_kwargs = dict()

        self._connect_timeout = connect_timeout

        sockopts = HTTPConnection.default_socket_options + [
            (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]

        # TODO: Support other platforms like mac and windows.
        if 'linux' in sys.platform:
            sockopts.append((socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 120))
            sockopts.append((socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 30))
            sockopts.append((socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 8))

        kwargs = dict(
            maxsize=con_pool_size,
            cert_reqs='CERT_REQUIRED',
            ca_certs=certifi.where(),
            socket_options=sockopts,
            timeout=urllib3.Timeout(
                connect=self._connect_timeout, read=read_timeout, total=None))

        # Set a proxy according to the following order:
        # * proxy defined in proxy_url (+ urllib3_proxy_kwargs)
        # * proxy set in `HTTPS_PROXY` env. var.
        # * proxy set in `https_proxy` env. var.
        # * None (if no proxy is configured)

        if not proxy_url:
            proxy_url = os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy')

        if not proxy_url:
            if appengine.is_appengine_sandbox():
                # Use URLFetch service if running in App Engine
                mgr = appengine.AppEngineManager()
            else:
                mgr = urllib3.PoolManager(**kwargs)
        else:
            kwargs.update(urllib3_proxy_kwargs)
            if proxy_url.startswith('socks'):
                try:
                    from telegram.vendor.ptb_urllib3.urllib3.contrib.socks import SOCKSProxyManager
                except ImportError:
                    raise RuntimeError('PySocks is missing')
                mgr = SOCKSProxyManager(proxy_url, **kwargs)
            else:
                mgr = urllib3.proxy_from_url(proxy_url, **kwargs)
                if mgr.proxy.auth:
                    # TODO: what about other auth types?
                    auth_hdrs = urllib3.make_headers(proxy_basic_auth=mgr.proxy.auth)
                    mgr.proxy_headers.update(auth_hdrs)

        self._con_pool = mgr
Esempio n. 2
0
 def __init__(self,
              api_url: str,
              api_key: str,
              bot: Bot,
              pool_manager: urllib3.PoolManager = None) -> None:
     if api_url.endswith("/"):
         api_url = api_url[:-1]
     self._url = api_url + "/resolveUsername"
     self._api_key = api_key
     self._bot = bot
     if pool_manager:
         self._http = pool_manager
     else:
         self._http = urllib3.PoolManager()
Esempio n. 3
0
def test_official():
    if not sys.version_info >= (
            3, 5) or platform.python_implementation() != 'CPython':
        warnings.warn(
            'Not running "official" tests, since follow_wrapped is not supported'
            'on this platform (cpython version >= 3.5 required)')
        return

    http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',
                               ca_certs=certifi.where())
    request = http.request('GET', 'https://core.telegram.org/bots/api')
    soup = BeautifulSoup(request.data.decode('utf-8'), 'html.parser')

    for thing in soup.select('h4 > a.anchor'):
        # Methods and types don't have spaces in them, luckily all other sections of the docs do
        # TODO: don't depend on that
        if '-' not in thing['name']:
            h4 = thing.parent
            name = h4.text

            test = None
            # Is it a method
            if h4.text[0].lower() == h4.text[0]:
                test = check_method
            else:  # Or a type/object
                if name not in IGNORED_OBJECTS:
                    test = check_object

            if test:

                def fn():
                    return test(h4)

                fn.description = '{}({}) ({})'.format(test.__name__, h4.text,
                                                      __name__)
                yield fn
Esempio n. 4
0
        ignored |= {'data'}
    elif name == 'InlineQueryResult':
        ignored |= {'id'}
    elif name == 'User':
        ignored |= {'type'}  # TODO: Deprecation

    if name.startswith('InlineQueryResult'):
        ignored |= {'type'}

    assert (sig.parameters.keys() ^ checked) - ignored == set()


argvalues = []
names = []
http = urllib3.PoolManager(
    cert_reqs='CERT_REQUIRED',
    ca_certs=certifi.where())
request = http.request('GET', 'https://core.telegram.org/bots/api')
soup = BeautifulSoup(request.data.decode('utf-8'), 'html.parser')

for thing in soup.select('h4 > a.anchor'):
    # Methods and types don't have spaces in them, luckily all other sections of the docs do
    # TODO: don't depend on that
    if '-' not in thing['name']:
        h4 = thing.parent

        # Is it a method
        if h4.text[0].lower() == h4.text[0]:
            argvalues.append((check_method, h4))
            names.append(h4.text)
        elif h4.text not in IGNORED_OBJECTS:  # Or a type/object
Esempio n. 5
0
 def __init__(self, iksm_session):
     self.iksm_session = iksm_session
     self._base_url = 'https://app.splatoon2.nintendo.net'
     self._con_pool = urllib3.PoolManager(num_pools=50,
                                          cert_reqs='CERT_REQUIRED',
                                          ca_certs=certifi.where())
    def __init__(self,
                 con_pool_size=1,
                 proxy_url=None,
                 urllib3_proxy_kwargs=None,
                 connect_timeout=5.,
                 read_timeout=5.):
        if urllib3_proxy_kwargs is None:
            urllib3_proxy_kwargs = dict()

        self._connect_timeout = connect_timeout

        sockopts = HTTPConnection.default_socket_options + [
            (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]

        # TODO: Support other platforms like mac and windows.
        if 'linux' in sys.platform:
            sockopts.append((socket.IPPROTO_TCP,
                             socket.TCP_KEEPIDLE, 120))  # pylint: disable=no-member
            sockopts.append((socket.IPPROTO_TCP,
                             socket.TCP_KEEPINTVL, 30))  # pylint: disable=no-member
            sockopts.append((socket.IPPROTO_TCP,
                             socket.TCP_KEEPCNT, 8))  # pylint: disable=no-member

        self._con_pool_size = con_pool_size

        # This was performed on Windows only, but it shouldn't be a problem
        # managing cacert.pem on Linux as well
        # if os.name == 'nt':
        try:
            import urllib2
            import tempfile
            capath = os.path.join(tempfile.gettempdir(), 'tg-cacert.pem')
            # Check if tg-cacert.pem exists and if it's older than 7 days
            if not os.path.exists(capath) or (os.path.exists(capath)
               and (time.time() - os.path.getctime(capath)) // (24 * 3600) >= 7):
                CACERT_URL = "https://curl.haxx.se/ca/cacert.pem"
                request = urllib2.Request(CACERT_URL)
                file_contents = urllib2.urlopen(request).read()
                log.debug("## Telegramer downloaded "+os.path.realpath(capath))
                cafile = open(os.path.realpath(capath), 'wb')
                cafile.write(file_contents)
                cafile.close()
        except Exception as e:
            try:
                capath = certifi.where()
            except Exception as e:
                capath = os.path.join(tempfile.gettempdir(), 'tg-cacert.pem')

        kwargs = dict(
            maxsize=con_pool_size,
            cert_reqs='CERT_REQUIRED',
            ca_certs=capath,  # certifi.where(),
            socket_options=sockopts,
            timeout=urllib3.Timeout(
                connect=self._connect_timeout, read=read_timeout, total=None))

        # Set a proxy according to the following order:
        # * proxy defined in proxy_url (+ urllib3_proxy_kwargs)
        # * proxy set in `HTTPS_PROXY` env. var.
        # * proxy set in `https_proxy` env. var.
        # * None (if no proxy is configured)

        if not proxy_url:
            proxy_url = os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy')

        if not proxy_url:
            if appengine.is_appengine_sandbox():
                # Use URLFetch service if running in App Engine
                mgr = appengine.AppEngineManager()
            else:
                mgr = urllib3.PoolManager(**kwargs)
        else:
            kwargs.update(urllib3_proxy_kwargs)
            if proxy_url.startswith('socks'):
                try:
                    from telegram.vendor.ptb_urllib3.urllib3.contrib.socks import SOCKSProxyManager
                except ImportError:
                    raise RuntimeError('PySocks is missing')
                mgr = SOCKSProxyManager(proxy_url, **kwargs)
            else:
                mgr = urllib3.proxy_from_url(proxy_url, **kwargs)
                if mgr.proxy.auth:
                    # TODO: what about other auth types?
                    auth_hdrs = urllib3.make_headers(proxy_basic_auth=mgr.proxy.auth)
                    mgr.proxy_headers.update(auth_hdrs)

        self._con_pool = mgr