File: feature_flags_fetcher.py

package info (click to toggle)
python-proton-vpn-api-core 0.39.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 892 kB
  • sloc: python: 6,582; makefile: 8
file content (206 lines) | stat: -rw-r--r-- 6,488 bytes parent folder | download
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
"""
Copyright (c) 2024 Proton AG

This file is part of Proton VPN.

Proton VPN 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.

Proton VPN 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 ProtonVPN.  If not, see <https://www.gnu.org/licenses/>.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from pathlib import Path

from proton.utils.environment import VPNExecutionEnvironment
from proton.vpn.session.utils import RefreshCalculator, rest_api_request
from proton.vpn.core.cache_handler import CacheHandler

if TYPE_CHECKING:
    from proton.vpn.session.api import VPNSession


REFRESH_INTERVAL = 2 * 60 * 60  # 2 hours

DEFAULT = {
    "toggles": [
        {
            "name": "LinuxBetaToggle",
            "enabled": True,
            "impressionData": False,
            "variant": {
                "name": "disabled",
                "enabled": False
            }
        },
        {
            "name": "WireGuardExperimental",
            "enabled": True,
            "impressionData": False,
            "variant": {
                "name": "disabled",
                "enabled": False
            }
        },
        {
            "name": "TimestampedLogicals",
            "enabled": False,
            "impressionData": False,
            "variant": {
                "name": "disabled",
                "enabled": False
            }
        },
        {
            "name": "IPv6Support",
            "enabled": False,
            "impressionData": False,
            "variant": {
                "name": "disabled",
                "enabled": False
            }
        },
        {
            "name": "CertificateBasedOpenVPN",
            "enabled": False,
            "impressionData": False,
            "variant": {
                "name": "disabled",
                "enabled": False
            }
        },
        {
            "name": "LinuxDeferredUI",
            "enabled": False,
            "impressionData": False,
            "variant": {
                "name": "disabled",
                "enabled": False
            }
        },
        {
            "name": "CustomDNS",
            "enabled": False,
            "impressionData": False,
            "variant": {
                "name": "disabled",
                "enabled": False
            }
        },
        {
            "name": "SwitchDefaultProtocolToWireguard",
            "enabled": False,
            "impressionData": False,
            "variant": {
                "name": "disabled",
                "enabled": False
            }
        },
    ],
    "ExpirationTime": 0
}


class FeatureFlags:  # pylint: disable=too-few-public-methods
    """Contains a record of available features."""
    def __init__(self, api_data: dict):
        self._api_data = api_data
        self._expiration_time = api_data.get(
            "ExpirationTime",
            RefreshCalculator.get_expiration_time(
                refresh_interval=REFRESH_INTERVAL
            )
        )

    def get(self, feature_flag_name: str) -> bool:
        """Get a feature flag by its name.
        Always returns `False` if the feature flag is not found.
        """
        return self._search_for_feature_flag(feature_flag_name)

    def _search_for_feature_flag(self, feature_name: str) -> dict:
        feature_flag_dict = {}

        for feature in self._api_data.get("toggles", {}):
            if feature["name"] == feature_name:
                feature_flag_dict = feature
                break

        return feature_flag_dict.get("enabled", False)

    @property
    def is_expired(self) -> bool:
        """Returns if data has expired"""
        return RefreshCalculator.get_is_expired(self._expiration_time)

    @property
    def seconds_until_expiration(self) -> int:
        """Returns amount of seconds until it expires."""
        return RefreshCalculator.get_seconds_until_expiration(self._expiration_time)

    @staticmethod
    def get_refresh_interval_in_seconds() -> int:
        """Returns refresh interval in seconds."""
        return RefreshCalculator(REFRESH_INTERVAL).get_refresh_interval_in_seconds()

    @staticmethod
    def default() -> FeatureFlags:
        """Returns a feature object with default values"""
        return FeatureFlags(DEFAULT)


class FeatureFlagsFetcher:
    """Fetches and caches features from Proton's REST API."""
    ROUTE = "/feature/v2/frontend"
    CACHE_PATH = Path(VPNExecutionEnvironment().path_cache) / "features.json"

    def __init__(
        self, session: "VPNSession",
        refresh_calculator: RefreshCalculator = None,
        cache_handler: CacheHandler = None
    ):
        """
        :param session: session used to retrieve the client configuration.
        """
        self._features = None
        self._session = session
        self._refresh_calculator = refresh_calculator or RefreshCalculator
        self._cache_file = cache_handler or CacheHandler(self.CACHE_PATH)

    def clear_cache(self):
        """Discards the cache, if existing."""
        self._features = None
        self._cache_file.remove()

    async def fetch(self) -> FeatureFlags:
        """
        Fetches the client configuration from the REST API.
        :returns: the fetched client configuration.
        """
        response = await rest_api_request(
            self._session,
            self.ROUTE,
        )
        response["ExpirationTime"] = self._refresh_calculator\
            .get_expiration_time(refresh_interval=REFRESH_INTERVAL)
        self._cache_file.save(response)
        self._features = FeatureFlags(response)
        return self._features

    def load_from_cache(self) -> FeatureFlags:
        """
        Loads the client configuration from persistence.
        :returns: the persisted client configuration. If no persistence
            was found then the default client configuration is returned.
        """
        cache = self._cache_file.load()
        self._features = FeatureFlags(cache) if cache else FeatureFlags.default()
        return self._features