Merge remote-tracking branch 'David-Development/rtl2.py'
[youtube-dl] / youtube_dl / compat.py
index cd46693b34f4746284e74b36af3bddd7ba8155ee..4453b34fceea50861ccedec0ec177a12f424274d 100644 (file)
@@ -1,11 +1,10 @@
 from __future__ import unicode_literals
 
-import ctypes
 import getpass
 import optparse
 import os
-import platform
 import re
+import socket
 import subprocess
 import sys
 
@@ -299,7 +298,9 @@ else:
 
 # Old 2.6 and 2.7 releases require kwargs to be bytes
 try:
-    (lambda x: x)(**{'x': 0})
+    def _testfunc(x):
+        pass
+    _testfunc(**{'x': 0})
 except TypeError:
     def compat_kwargs(kwargs):
         return dict((bytes(k), v) for k, v in kwargs.items())
@@ -307,6 +308,32 @@ else:
     compat_kwargs = lambda kwargs: kwargs
 
 
+if sys.version_info < (2, 7):
+    def compat_socket_create_connection(address, timeout, source_address=None):
+        host, port = address
+        err = None
+        for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
+            af, socktype, proto, canonname, sa = res
+            sock = None
+            try:
+                sock = socket.socket(af, socktype, proto)
+                sock.settimeout(timeout)
+                if source_address:
+                    sock.bind(source_address)
+                sock.connect(sa)
+                return sock
+            except socket.error as _:
+                err = _
+                if sock is not None:
+                    sock.close()
+        if err is not None:
+            raise err
+        else:
+            raise socket.error("getaddrinfo returns an empty list")
+else:
+    compat_socket_create_connection = socket.create_connection
+
+
 # Fix https://github.com/rg3/youtube-dl/issues/4223
 # See http://bugs.python.org/issue9161 for what is broken
 def workaround_optparse_bug9161():
@@ -328,22 +355,6 @@ def workaround_optparse_bug9161():
         optparse.OptionGroup.add_option = _compat_add_option
 
 
-if platform.python_implementation() == 'PyPy':
-    # PyPy expects byte strings as Windows function names
-    # https://github.com/rg3/youtube-dl/pull/4392
-    def compat_WINFUNCTYPE(*args, **kwargs):
-        real = ctypes.WINFUNCTYPE(*args, **kwargs)
-
-        def resf(tpl, *args, **kwargs):
-            funcname, dll = tpl
-            return real((str(funcname), dll), *args, **kwargs)
-
-        return resf
-else:
-    def compat_WINFUNCTYPE(*args, **kwargs):
-        return ctypes.WINFUNCTYPE(*args, **kwargs)
-
-
 __all__ = [
     'compat_HTTPError',
     'compat_chr',
@@ -358,6 +369,7 @@ __all__ = [
     'compat_ord',
     'compat_parse_qs',
     'compat_print',
+    'compat_socket_create_connection',
     'compat_str',
     'compat_subprocess_get_DEVNULL',
     'compat_urllib_error',
@@ -367,7 +379,6 @@ __all__ = [
     'compat_urllib_request',
     'compat_urlparse',
     'compat_urlretrieve',
-    'compat_WINFUNCTYPE',
     'compat_xml_parse_error',
     'shlex_quote',
     'subprocess_check_output',