]> code.delx.au - webdl/blob - autosocks.py
Fixed silly bug in removing ffmpeg detection
[webdl] / autosocks.py
1 import logging
2 import os
3 import subprocess
4
5
6 def detect_gnome():
7 """ Gnome via python-gconf """
8 from gconf import client_get_default
9 gconf_client = client_get_default()
10 mode = gconf_client.get_string("/system/proxy/mode")
11 if mode != "manual":
12 return None, None
13 host = gconf_client.get_string("/system/proxy/socks_host")
14 port = gconf_client.get_int("/system/proxy/socks_port")
15 return host, port
16
17 def detect_osx():
18 """ OS X 10.5 and up via PyObjC """
19 from SystemConfiguration import SCDynamicStoreCopyProxies
20 osx_proxy = SCDynamicStoreCopyProxies(None)
21 if osx_proxy.get("SOCKSEnable"):
22 host = osx_proxy.get("SOCKSProxy")
23 port = int(osx_proxy.get("SOCKSPort"))
24 return host, port
25 return None, None
26
27 def detect_kde():
28 """ KDE via command line, why no python bindings for KDE proxy settings? """
29 if os.environ.get("KDE_FULL_SESSION") != "true":
30 return None, None
31 p = subprocess.Popen(
32 [
33 "kreadconfig",
34 "--file",
35 "kioslaverc",
36 "--group",
37 "Proxy Settings",
38 "--key",
39 "socksProxy",
40 ],
41 shell=True,
42 stdout=subprocess.PIPE,
43 )
44 host, port = p.stdout.readline()[:-1].split(":")
45 p.close()
46 port = int(port)
47 return host, port
48
49 def detect_env():
50 """ fallback to environment variables """
51 socks_environ = os.environ.get("SOCKS_SERVER")
52 if not socks_environ:
53 return None, None
54 host, port = socks_environ
55 port = int(port)
56 return host, port
57
58
59 def configure_socks(host, port):
60 """ hijack socket.socket using SocksiPy """
61 try:
62 import socks, socket
63 except ImportError:
64 logging.error("Failed to use configured SOCKS proxy: %s:%s", host, port)
65 logging.error("Try installing SocksiPy: http://socksipy.sf.net")
66 return False
67
68 socket.socket = socks.socksocket
69 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, host, port)
70 return True
71
72
73 def try_autosocks():
74 functions = [
75 detect_gnome,
76 detect_osx,
77 detect_kde,
78 detect_env,
79 ]
80 for func in functions:
81 host, port = None, None
82 try:
83 host, port = func()
84 except Exception as e:
85 pass
86 if host is not None and port is not None:
87 return configure_socks(host, port)
88 return False
89