summaryrefslogtreecommitdiff
path: root/src/leap/bitmask/gui/eip_preferenceswindow.py
blob: 9f8c4ff4144e0674ec45d40c3a4ca71126681b8e (plain)
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
70
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
# -*- coding: utf-8 -*-
# eip_preferenceswindow.py
# Copyright (C) 2013 LEAP
#
# This program 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, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

"""
EIP Preferences window
"""
import os
import logging

from functools import partial
from PySide import QtGui

from leap.bitmask.config.leapsettings import LeapSettings
from leap.bitmask.config.providerconfig import ProviderConfig
from leap.bitmask.gui.ui_eippreferences import Ui_EIPPreferences
from leap.bitmask.services.eip.eipconfig import EIPConfig, VPNGatewaySelector

logger = logging.getLogger(__name__)


class EIPPreferencesWindow(QtGui.QDialog):
    """
    Window that displays the EIP preferences.
    """
    def __init__(self, parent):
        """
        :param parent: parent object of the EIPPreferencesWindow.
        :parent type: QWidget
        """
        QtGui.QDialog.__init__(self, parent)
        self.AUTOMATIC_GATEWAY_LABEL = self.tr("Automatic")

        self._settings = LeapSettings()

        # Load UI
        self.ui = Ui_EIPPreferences()
        self.ui.setupUi(self)
        self.ui.lblProvidersGatewayStatus.setVisible(False)
        self.ui.lblAutoStartEIPStatus.setVisible(False)

        # Connections
        self.ui.cbProvidersGateway.currentIndexChanged[unicode].connect(
            self._populate_gateways)

        self.ui.cbGateways.currentIndexChanged[unicode].connect(
            lambda x: self.ui.lblProvidersGatewayStatus.setVisible(False))

        self.ui.cbProvidersEIP.currentIndexChanged[unicode].connect(
            lambda x: self.ui.lblAutoStartEIPStatus.setVisible(False))

        self.ui.cbAutoStartEIP.toggled.connect(
            lambda x: self.ui.lblAutoStartEIPStatus.setVisible(False))

        self.ui.pbSaveAutoStartEIP.clicked.connect(self._save_auto_start_eip)

        self._add_configured_providers()

        # Load auto start EIP settings
        self.ui.cbAutoStartEIP.setChecked(self._settings.get_autostart_eip())
        default_provider = self._settings.get_defaultprovider()
        idx = self.ui.cbProvidersEIP.findText(default_provider)
        self.ui.cbProvidersEIP.setCurrentIndex(idx)

    def _save_auto_start_eip(self):
        """
        SLOT
        TRIGGER:
            self.ui.cbAutoStartEIP.toggled

        Saves the automatic start of EIP user preference.
        """
        default_provider = self.ui.cbProvidersEIP.currentText()
        enabled = self.ui.cbAutoStartEIP.isChecked()

        self._settings.set_autostart_eip(enabled)
        self._settings.set_defaultprovider(default_provider)

        self.ui.lblAutoStartEIPStatus.show()
        logger.debug('Auto start EIP saved: {0} {1}.'.format(
            default_provider, enabled))

    def _set_providers_gateway_status(self, status, success=False,
                                      error=False):
        """
        Sets the status label for the gateway change.

        :param status: status message to display, can be HTML
        :type status: str
        :param success: is set to True if we should display the
                        message as green
        :type success: bool
        :param error: is set to True if we should display the
                        message as red
        :type error: bool
        """
        if success:
            status = "<font color='green'><b>%s</b></font>" % (status,)
        elif error:
            status = "<font color='red'><b>%s</b></font>" % (status,)

        self.ui.lblProvidersGatewayStatus.setVisible(True)
        self.ui.lblProvidersGatewayStatus.setText(status)

    def _add_configured_providers(self):
        """
        Add the client's configured providers to the providers combo boxes.
        """
        self.ui.cbProvidersGateway.clear()
        self.ui.cbProvidersEIP.clear()
        providers = self._settings.get_configured_providers()
        if not providers:
            self.ui.gbAutomaticEIP.setEnabled(False)
            self.ui.gbGatewaySelector.setEnabled(False)
            return

        for provider in providers:
            self.ui.cbProvidersGateway.addItem(provider)
            self.ui.cbProvidersEIP.addItem(provider)

    def _save_selected_gateway(self, provider):
        """
        SLOT
        TRIGGERS:
            self.ui.pbSaveGateway.clicked

        Saves the new gateway setting to the configuration file.

        :param provider: the provider config that we need to save.
        :type provider: str
        """
        gateway = self.ui.cbGateways.currentText()

        if gateway == self.AUTOMATIC_GATEWAY_LABEL:
            gateway = self._settings.GATEWAY_AUTOMATIC
        else:
            idx = self.ui.cbGateways.currentIndex()
            gateway = self.ui.cbGateways.itemData(idx)

        self._settings.set_selected_gateway(provider, gateway)

        msg = self.tr(
            "Gateway settings for provider '{0}' saved.").format(provider)
        self._set_providers_gateway_status(msg, success=True)

    def _populate_gateways(self, domain):
        """
        SLOT
        TRIGGERS:
            self.ui.cbProvidersGateway.currentIndexChanged[unicode]

        Loads the gateways that the provider provides into the UI for
        the user to select.

        :param domain: the domain of the provider to load gateways from.
        :type domain: str
        """
        # We hide the maybe-visible status label after a change
        self.ui.lblProvidersGatewayStatus.setVisible(False)

        if not domain:
            return

        try:
            # disconnect previously connected save method
            self.ui.pbSaveGateway.clicked.disconnect()
        except RuntimeError:
            pass  # Signal was not connected

        # set the proper connection for the 'save' button
        save_gateway = partial(self._save_selected_gateway, domain)
        self.ui.pbSaveGateway.clicked.connect(save_gateway)

        eip_config = EIPConfig()
        provider_config = ProviderConfig.get_provider_config(domain)

        eip_config_path = os.path.join("leap", "providers",
                                       domain, "eip-service.json")
        api_version = provider_config.get_api_version()
        eip_config.set_api_version(api_version)
        eip_loaded = eip_config.load(eip_config_path)

        if not eip_loaded or provider_config is None:
            self._set_providers_gateway_status(
                self.tr("There was a problem with configuration files."),
                error=True)
            return

        gateways = VPNGatewaySelector(eip_config).get_gateways_list()
        logger.debug(gateways)

        self.ui.cbGateways.clear()
        self.ui.cbGateways.addItem(self.AUTOMATIC_GATEWAY_LABEL)

        # Add the available gateways and
        # select the one stored in configuration file.
        selected_gateway = self._settings.get_selected_gateway(domain)
        index = 0
        for idx, (gw_name, gw_ip) in enumerate(gateways):
            gateway = "{0} ({1})".format(gw_name, gw_ip)
            self.ui.cbGateways.addItem(gateway, gw_ip)
            if gw_ip == selected_gateway:
                index = idx + 1

        self.ui.cbGateways.setCurrentIndex(index)