From 8787adf725f79eef126a8d2f925d4440f91b8e0e Mon Sep 17 00:00:00 2001
From: Yann Leboulanger <asterix@lagaule.org>
Date: Thu, 10 Nov 2011 20:37:48 +0100
Subject: [PATCH] add a global proxy option that will apply to all account that
 don't have a proxy configured. Fixes #7023

---
 src/common/config.py     |  1 +
 src/common/connection.py | 61 +++++++++-------------------------------
 src/common/helpers.py    | 45 +++++++++++++++++++++++++++++
 src/config.py            | 30 ++++++++++++++++++++
 4 files changed, 90 insertions(+), 47 deletions(-)

diff --git a/src/common/config.py b/src/common/config.py
index ef2020228..97724f9ea 100644
--- a/src/common/config.py
+++ b/src/common/config.py
@@ -290,6 +290,7 @@ class Config:
             'use_stun_server': [opt_bool, False, _('If True, Gajim will try to use a STUN server when using jingle. The one in "stun_server" option, or the one given by the jabber server.')],
             'stun_server': [opt_str, '', _('STUN server to use when using jingle')],
             'show_affiliation_in_groupchat': [opt_bool, True, _('If True, Gajim will show affiliation of groupchat occupants by adding a colored square to the status icon')],
+            'global_proxy': [opt_str, '', _('Proxy used for all outgoing connections if the account does not have a specific proxy configured')],
     }
 
     __options_per_key = {
diff --git a/src/common/connection.py b/src/common/connection.py
index f49b83c44..80e2af7ba 100644
--- a/src/common/connection.py
+++ b/src/common/connection.py
@@ -981,7 +981,7 @@ class Connection(CommonConnection, ConnectionHandlers):
                 if weightsum >= rndint:
                     return host
 
-    def connect(self, data = None):
+    def connect(self, data=None):
         """
         Start a connection to the Jabber server
 
@@ -998,11 +998,19 @@ class Connection(CommonConnection, ConnectionHandlers):
             self.try_connecting_for_foo_secs = gajim.config.get_per('accounts',
                 self.name, 'try_connecting_for_foo_secs')
             use_custom = False
+            proxy = helpers.get_proxy_info(self.name)
 
         elif data:
             hostname = data['hostname']
             self.try_connecting_for_foo_secs = 45
             p = data['proxy']
+            if p and p in gajim.config.get_per('proxies'):
+                proxy = {}
+                proxyptr = gajim.config.get_per('proxies', p)
+                for key in proxyptr.keys():
+                    proxy[key] = proxyptr[key][1]
+            else:
+                proxy = None
             use_srv = True
             use_custom = data['use_custom_host']
             if use_custom:
@@ -1013,7 +1021,7 @@ class Connection(CommonConnection, ConnectionHandlers):
             usessl = gajim.config.get_per('accounts', self.name, 'usessl')
             self.try_connecting_for_foo_secs = gajim.config.get_per('accounts',
                     self.name, 'try_connecting_for_foo_secs')
-            p = gajim.config.get_per('accounts', self.name, 'proxy')
+            proxy = helpers.get_proxy_info(self.name)
             use_srv = gajim.config.get_per('accounts', self.name, 'use_srv')
             use_custom = gajim.config.get_per('accounts', self.name,
                     'use_custom_host')
@@ -1022,52 +1030,10 @@ class Connection(CommonConnection, ConnectionHandlers):
 
         # create connection if it doesn't already exist
         self.connected = 1
-        if p and p in gajim.config.get_per('proxies'):
-            proxy = {}
-            proxyptr = gajim.config.get_per('proxies', p)
-            for key in proxyptr.keys():
-                proxy[key] = proxyptr[key][1]
 
-        elif gajim.config.get_per('accounts', self.name, 'use_env_http_proxy'):
-            try:
-                try:
-                    env_http_proxy = os.environ['HTTP_PROXY']
-                except Exception:
-                    env_http_proxy = os.environ['http_proxy']
-                env_http_proxy = env_http_proxy.strip('"')
-                # Dispose of the http:// prefix
-                env_http_proxy = env_http_proxy.split('://')
-                env_http_proxy = env_http_proxy[len(env_http_proxy)-1]
-                env_http_proxy = env_http_proxy.split('@')
-
-                if len(env_http_proxy) == 2:
-                    login = env_http_proxy[0].split(':')
-                    addr = env_http_proxy[1].split(':')
-                else:
-                    login = ['', '']
-                    addr = env_http_proxy[0].split(':')
-
-                proxy = {'host': addr[0], 'type' : u'http', 'user':login[0]}
-
-                if len(addr) == 2:
-                    proxy['port'] = addr[1]
-                else:
-                    proxy['port'] = 3128
-
-                if len(login) == 2:
-                    proxy['pass'] = login[1]
-                    proxy['useauth'] = True
-                else:
-                    proxy['pass'] = u''
-
-            except Exception:
-                proxy = None
-        else:
-            proxy = None
         h = hostname
         p = 5222
         ssl_p = 5223
-#                       use_srv = False # wants ssl? disable srv lookup
         if use_custom:
             h = custom_h
             p = custom_p
@@ -1082,8 +1048,8 @@ class Connection(CommonConnection, ConnectionHandlers):
         if use_srv:
             # add request for srv query to the resolve, on result '_on_resolve'
             # will be called
-            gajim.resolver.resolve('_xmpp-client._tcp.' + helpers.idn_to_ascii(h),
-                    self._on_resolve)
+            gajim.resolver.resolve('_xmpp-client._tcp.' + helpers.idn_to_ascii(
+                h), self._on_resolve)
         else:
             self._on_resolve('', [])
 
@@ -1094,7 +1060,8 @@ class Connection(CommonConnection, ConnectionHandlers):
             # Add ssl port
             ssl_p = 5223
             if gajim.config.get_per('accounts', self.name, 'use_custom_host'):
-                ssl_p = gajim.config.get_per('accounts', self.name, 'custom_port')
+                ssl_p = gajim.config.get_per('accounts', self.name,
+                    'custom_port')
             for i in self._hosts:
                 i['ssl_port'] = ssl_p
         self._connect_to_next_host()
diff --git a/src/common/helpers.py b/src/common/helpers.py
index 97996f01b..77440d062 100644
--- a/src/common/helpers.py
+++ b/src/common/helpers.py
@@ -1381,3 +1381,48 @@ def replace_dataform_media(form, stanza):
                             uri.setData(data.getData())
                             found = True
     return found
+
+def get_proxy_info(account):
+    p = gajim.config.get_per('accounts', account, 'proxy')
+    if not p:
+        if gajim.config.get_per('accounts', account, 'use_env_http_proxy'):
+            try:
+                try:
+                    env_http_proxy = os.environ['HTTP_PROXY']
+                except Exception:
+                    env_http_proxy = os.environ['http_proxy']
+                env_http_proxy = env_http_proxy.strip('"')
+                # Dispose of the http:// prefix
+                env_http_proxy = env_http_proxy.split('://')[-1]
+                env_http_proxy = env_http_proxy.split('@')
+
+                if len(env_http_proxy) == 2:
+                    login = env_http_proxy[0].split(':')
+                    addr = env_http_proxy[1].split(':')
+                else:
+                    login = ['', '']
+                    addr = env_http_proxy[0].split(':')
+
+                proxy = {'host': addr[0], 'type' : u'http', 'user':login[0]}
+
+                if len(addr) == 2:
+                    proxy['port'] = addr[1]
+                else:
+                    proxy['port'] = 3128
+
+                if len(login) == 2:
+                    proxy['pass'] = login[1]
+                    proxy['useauth'] = True
+                else:
+                    proxy['pass'] = u''
+                return proxy
+
+            except Exception:
+                proxy = None
+        p = gajim.config.get('global_proxy')
+    if p:
+        proxy = {}
+        proxyptr = gajim.config.get_per('proxies', p)
+        for key in proxyptr.keys():
+            proxy[key] = proxyptr[key][1]
+        return proxy
\ No newline at end of file
diff --git a/src/config.py b/src/config.py
index 2057655ca..c900d4337 100644
--- a/src/config.py
+++ b/src/config.py
@@ -551,6 +551,8 @@ class PreferencesWindow:
         else:
             w.set_active(st)
 
+        self.update_proxy_list()
+
         # check if gajm is default
         st = gajim.config.get('check_if_gajim_is_default')
         self.xml.get_object('check_default_client_checkbutton').set_active(st)
@@ -1256,6 +1258,34 @@ class PreferencesWindow:
         if event.keyval == gtk.keysyms.Delete:
             self.on_delete_msg_button_clicked(widget)
 
+    def on_proxies_combobox_changed(self, widget):
+        active = widget.get_active()
+        proxy = widget.get_model()[active][0].decode('utf-8')
+        if proxy == _('None'):
+            proxy = ''
+
+        gajim.config.set('global_proxy', proxy)
+
+    def on_manage_proxies_button_clicked(self, widget):
+        if 'manage_proxies' in gajim.interface.instances:
+            gajim.interface.instances['manage_proxies'].window.present()
+        else:
+            gajim.interface.instances['manage_proxies'] = ManageProxiesWindow()
+
+    def update_proxy_list(self):
+        our_proxy = gajim.config.get('global_proxy')
+        if not our_proxy:
+            our_proxy = _('None')
+        proxy_combobox = self.xml.get_object('proxies_combobox')
+        model = proxy_combobox.get_model()
+        model.clear()
+        l = gajim.config.get_per('proxies')
+        l.insert(0, _('None'))
+        for i in xrange(len(l)):
+            model.append([l[i]])
+            if our_proxy == l[i]:
+                proxy_combobox.set_active(i)
+
     def on_open_advanced_editor_button_clicked(self, widget, data = None):
         if 'advanced_config' in gajim.interface.instances:
             gajim.interface.instances['advanced_config'].window.present()