File: loader.py

package info (click to toggle)
python-pyfunceble 4.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,144 kB
  • sloc: python: 27,918; sh: 142; makefile: 48
file content (695 lines) | stat: -rw-r--r-- 22,958 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
"""
The tool to check the availability or syntax of domain, IP or URL.

::


    ██████╗ ██╗   ██╗███████╗██╗   ██╗███╗   ██╗ ██████╗███████╗██████╗ ██╗     ███████╗
    ██╔══██╗╚██╗ ██╔╝██╔════╝██║   ██║████╗  ██║██╔════╝██╔════╝██╔══██╗██║     ██╔════╝
    ██████╔╝ ╚████╔╝ █████╗  ██║   ██║██╔██╗ ██║██║     █████╗  ██████╔╝██║     █████╗
    ██╔═══╝   ╚██╔╝  ██╔══╝  ██║   ██║██║╚██╗██║██║     ██╔══╝  ██╔══██╗██║     ██╔══╝
    ██║        ██║   ██║     ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
    ╚═╝        ╚═╝   ╚═╝      ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝

Provides the configuration loader.

Author:
    Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom

Special thanks:
    https://pyfunceble.github.io/#/special-thanks

Contributors:
    https://pyfunceble.github.io/#/contributors

Project link:
    https://github.com/funilrys/PyFunceble

Project documentation:
    https://docs.pyfunceble.com

Project homepage:
    https://pyfunceble.github.io/

License:
::


    Copyright 2017, 2018, 2019, 2020, 2022, 2023, 2024, 2025 Nissar Chababy

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

import functools
import os
from typing import Any, Optional

try:
    import importlib.resources as package_resources
except ImportError:  # pragma: no cover ## Retro compatibility
    import importlib_resources as package_resources

from box import Box
from dotenv import load_dotenv
from yaml.error import MarkedYAMLError

import PyFunceble.cli.storage
import PyFunceble.storage
from PyFunceble.config.compare import ConfigComparison
from PyFunceble.dataset.user_agent import UserAgentDataset
from PyFunceble.downloader.iana import IANADownloader
from PyFunceble.downloader.public_suffix import PublicSuffixDownloader
from PyFunceble.downloader.user_agents import UserAgentsDownloader
from PyFunceble.helpers.dict import DictHelper
from PyFunceble.helpers.download import DownloadHelper
from PyFunceble.helpers.environment_variable import EnvironmentVariableHelper
from PyFunceble.helpers.file import FileHelper
from PyFunceble.helpers.merge import Merge


class ConfigLoader:
    """
    Provides the interface which loads and updates the configuration (if needed).

    :param merge_upstream:
        Authorizes the merging of the upstream configuration.

        .. note::
            If value is set to :py:class:`None` (default), we fallback to the
            :code:`PYFUNCEBLE_AUTO_CONFIGURATION` environment variable.
    """

    _path_to_config: Optional[str] = None
    _remote_config_location: Optional[str] = None
    path_to_default_config: Optional[str] = None
    _path_to_overwrite_config: Optional[str] = None

    _custom_config: dict = {}
    _merge_upstream: bool = False
    _config_dir: Optional[str] = None
    __config_loaded: bool = False

    file_helper: Optional[FileHelper] = None
    dict_helper: Optional[DictHelper] = None

    def __init__(
        self, merge_upstream: Optional[bool] = None, *, config_dir: Optional[str] = None
    ) -> None:
        with package_resources.path(
            "PyFunceble.data.infrastructure",
            PyFunceble.storage.DISTRIBUTED_CONFIGURATION_FILENAME,
        ) as file_path:
            self.path_to_default_config = str(file_path)

        if config_dir is not None:
            self.config_dir = config_dir
        else:
            self.config_dir = PyFunceble.storage.CONFIG_DIRECTORY

        self.path_to_remote_config = None

        if merge_upstream is not None:
            self.merge_upstream = merge_upstream
        elif EnvironmentVariableHelper("PYFUNCEBLE_AUTO_CONFIGURATION").exists():
            self.merge_upstream = True

        self.file_helper = FileHelper()
        self.dict_helper = DictHelper()

    def __del__(self) -> None:
        self.destroy()

    def reload_config(func):  # pylint: disable=no-self-argument
        """
        Reload the configuration (if it was already loaded) after launching the
        decorated method.
        """

        @functools.wraps(func)
        def wrapper(self, *args, **kwargs):
            result = func(self, *args, **kwargs)  # pylint: disable=not-callable

            if self.is_already_loaded():
                self.reload(keep_custom=True)

            return result

        return wrapper

    @staticmethod
    def conditional_switch(config: dict) -> dict:
        """
        Given the configuration that we are going to load, switches some of
        setting.

        :param config:
            The configuration we are going to load.
        """

        # pylint: disable=too-many-boolean-expressions
        if (
            "cli_testing" in config
            and "ci" in config["cli_testing"]
            and "active" in config["cli_testing"]["ci"]
            and "autocontinue" in config["cli_testing"]
            and bool(config["cli_testing"]["ci"]["active"])
            and not bool(config["cli_testing"]["autocontinue"])
        ):
            # Conditional autocontinue.
            # If we are under continuous integration, the autocontinue should be
            # activated.

            config["cli_testing"]["autocontinue"] = True

        if (
            "lookup" in config
            and "timeout" in config["lookup"]
            and config["lookup"]["timeout"]
            and config["lookup"]["timeout"] < 0
        ):
            # If timeout is set to a negative digit, switch to the default one.
            config["lookup"]["timeout"] = 5

        if (
            "cli_testing" in config
            and "testing_mode" in config["cli_testing"]
            and "platform_contribution" in config["cli_testing"]["testing_mode"]
            and config["cli_testing"]["testing_mode"]["platform_contribution"]
        ):
            # If we are under a special testing mode. We shouldn't generate
            # any files
            config["cli_testing"]["file_generation"]["no_file"] = True
            config["cli_testing"]["display_mode"]["dots"] = True
            config["cli_testing"]["autocontinue"] = False
            config["cli_testing"]["inactive_db"] = False
            config["cli_testing"]["mining"] = False
            config["cli_testing"]["local_network"] = False
            config["cli_testing"]["preload_file"] = False
            config["cli_testing"]["display_mode"]["percentage"] = False
            config["lookup"]["platform"] = False

        return config

    def is_already_loaded(self) -> bool:
        """
        Checks if the configuration was already loaded.
        """

        return bool(PyFunceble.storage.CONFIGURATION)

    def __is_completely_loaded(self) -> bool:
        """
        Checks if the configuration was completely loaded.
        """

        return self.is_already_loaded() and bool(self.__config_loaded)

    @property
    def path_to_config(self) -> Optional[str]:
        """
        Provides the current state of the :code:`_path_to_config` attribute.
        """

        if self._path_to_config is None:
            self._path_to_config = os.path.join(
                self.config_dir,
                PyFunceble.storage.CONFIGURATION_FILENAME,
            )

        return self._path_to_config

    @path_to_config.setter
    def path_to_config(self, value: str) -> None:
        """
        Sets the path to the configuration file.

        :param value:
            The value to set.

        :raise TypeError:
            When value is not a :py:class:`str`.
        """

        if not isinstance(value, str):
            raise TypeError(f"<value> should be {str}, {type(value)} given.")

        self._path_to_config = value

    @property
    def path_to_overwrite_config(self) -> Optional[str]:
        """
        Provides the current state of the :code:`_path_to_overwrite_config` attribute.
        """

        if self._path_to_overwrite_config is None:
            self._path_to_overwrite_config = os.path.join(
                self.config_dir,
                ".PyFunceble.overwrite.yaml",
            )

        return self._path_to_overwrite_config

    @path_to_overwrite_config.setter
    def path_to_overwrite_config(self, value: str) -> None:
        """
        Sets the path to the overwrite configuration file.

        :param value:
            The value to set.

        :raise TypeError:
            When value is not a :py:class:`str`.
        """

        if not isinstance(value, str):
            raise TypeError(f"<value> should be {str}, {type(value)} given.")

        self._path_to_overwrite_config = value

    @property
    def config_dir(self) -> Optional[str]:
        """
        Provides the current state of the :code:`_config_dir` attribute.
        """

        return self._config_dir

    @config_dir.setter
    @reload_config
    def config_dir(self, value: str) -> None:
        """
        Sets the configuration directory.

        :param value:
            The value to set.

        :raise TypeError:
            When value is not a :py:class:`str`.
        """

        if not isinstance(value, str):
            raise TypeError(f"<value> should be {str}, {type(value)} given.")

        self._config_dir = value
        # Reset the path to the configuration file.
        self._path_to_config = None
        self._path_to_overwrite_config = None

    def set_config_dir(self, value: str) -> "ConfigLoader":
        """
        Sets the configuration directory.

        :param value:
            The value to set.
        """

        self.config_dir = value

        return self

    @property
    def custom_config(self) -> dict:
        """
        Provides the current state of the :code:`_custom_config` attribute.
        """

        return self._custom_config

    @custom_config.setter
    @reload_config
    def custom_config(self, value: dict) -> None:
        """
        Sets the custom configuration to set after loading.

        Side Effect:
            Directly inject into the configuration variables if it was already
            loaded.

        :raise TypeError:
            When :code:`value` is not a :py:class:`dict`.
        """

        if not isinstance(value, dict):
            raise TypeError(f"<value> should be {dict}, {type(value)} given.")

        if not self._custom_config:
            self._custom_config = value
        else:
            self._custom_config.update(value)

    def set_custom_config(self, value: dict) -> "ConfigLoader":
        """
        Sets the custom configuration to set after loading.

        Side Effect:
            Directly inject into the configuration variables if it was already
            loaded.
        """

        self.custom_config = value

        return self

    @property
    def merge_upstream(self) -> bool:
        """
        Provides the current state of the :code:`_merge_upstream` attribute.
        """

        return self._merge_upstream

    @merge_upstream.setter
    def merge_upstream(self, value: bool) -> None:
        """
        Updates the value of :code:`_merge_upstream` attribute.

        :raise TypeError:
            When :code:`value` is not a :py:class:`bool`.
        """

        if not isinstance(value, bool):
            raise TypeError(f"<value> should be {bool}, {type(value)} given.")

        self._merge_upstream = value

    def set_merge_upstream(self, value: bool) -> "ConfigLoader":
        """
        Updates the value of :code:`_merge_upstream` attribute.
        """

        self.merge_upstream = value

        return self

    @property
    def remote_config_location(self) -> Optional[str]:
        """
        Provides the current state of the :code:`_remote_config_location` attribute.
        """

        return self._remote_config_location

    @remote_config_location.setter
    def remote_config_location(self, value: Optional[str]) -> None:
        """
        Updates the value of :code:`_remote_config_location` attribute.

        :raise TypeError:
            When :code:`value` is not a :py:class:`str`.
        """

        if value is not None and not isinstance(value, str):
            raise TypeError(f"<value> should be {str}, {type(value)} given.")

        if not value.startswith("http") and not value.startswith("https"):
            self.path_to_remote_config = os.path.realpath(value)
        else:
            self.path_to_remote_config = os.path.join(
                self.config_dir,
                ".PyFunceble.remote.yaml",
            )

        self._remote_config_location = value

    def set_remote_config_location(self, value: Optional[str]) -> "ConfigLoader":
        """
        Updates the value of :code:`_remote_config_location` attribute.
        """

        self.remote_config_location = value

        return self

    def install_missing_infrastructure_files(
        self,
    ) -> "ConfigLoader":  # pragma: no cover ## Copy method already tested
        """
        Installs the missing files (when needed).

        .. note::
            Installed if missing:
                - The configuration file.
                - The directory structure file.
        """

        if not self.is_already_loaded():
            if not self.file_helper.set_path(self.path_to_config).exists():
                self.file_helper.set_path(self.path_to_default_config).copy(
                    self.path_to_config, create_parent=True
                )

        return self

    def download_dynamic_infrastructure_files(
        self,
    ) -> "ConfigLoader":
        """
        Downloads all the dynamically (generated) infrastructure files.

        .. note::
            Downloaded if missing:
                - The IANA dump file.
                - The Public Suffix dump file.
        """

        ## pragma: no cover ## Underlying download methods already tested.

        if not self.is_already_loaded():
            IANADownloader().start()
            PublicSuffixDownloader().start()
            UserAgentsDownloader().start()

    def get_config_file_content(self) -> dict:
        """
        Provides the content of the configuration file or the one already loaded.
        """

        def is_3_x_version(config: dict) -> bool:
            """
            Checks if the given configuration is an old one.

            :param config:
                The config to work with.
            """

            return config and "days_between_inactive_db_clean" in config

        def download_remote_config(src: str, dest: str = None) -> None:
            """
            Downloads the remote configuration.

            :param src:
                The source to download from.
            :param dest:
                The destination to download
            """

            if src and (src.startswith("http") or src.startswith("https")):
                if dest is None:
                    destination = os.path.join(
                        self.config_dir,
                        os.path.basename(dest),
                    )
                else:
                    destination = dest

                DownloadHelper(
                    src,
                    certificate_validation=(
                        PyFunceble.storage.CONFIGURATION.verify_ssl_certificate
                        if PyFunceble.storage.CONFIGURATION
                        else True
                    ),
                    own_proxy_handler=True,
                    proxies=config["proxies"],
                ).download_text(destination=destination)

        try:
            config = self.dict_helper.from_yaml_file(self.path_to_config)
        except (MarkedYAMLError, FileNotFoundError):
            self.file_helper.set_path(self.path_to_default_config).copy(
                self.path_to_config, create_parent=True
            )
            config = self.dict_helper.from_yaml_file(self.path_to_config)

        config_comparer = ConfigComparison(
            local_config=config,
            upstream_config=self.dict_helper.from_yaml_file(
                self.path_to_default_config
            ),
        )

        if (
            not config
            or not isinstance(config, dict)
            or self.merge_upstream
            or is_3_x_version(config)
            or not config_comparer.is_local_identical()
        ):  # pragma: no cover ## Testing the underlying comparison method is sufficient
            config = config_comparer.get_merged()

            self.dict_helper.set_subject(config).to_yaml_file(self.path_to_config)

        if self.file_helper.set_path(self.path_to_overwrite_config).exists():
            # Early load of the overwrite configuration to allow usage of defined
            # proxy settings.
            overwrite_data = self.dict_helper.from_yaml_file(
                self.path_to_overwrite_config
            )

            if isinstance(overwrite_data, dict):
                config = Merge(overwrite_data).into(config)
        else:  # pragma: no cover  ## Just make it visible to end-user.
            self.file_helper.write("")

        # Now we preset the storage to enforce the usage of the configuration
        # in any downloads.
        PyFunceble.storage.CONFIGURATION = Box(
            config,
        )

        if not self.__is_completely_loaded():
            self.install_missing_infrastructure_files()
            self.download_dynamic_infrastructure_files()
            download_remote_config(
                self.remote_config_location, self.path_to_remote_config
            )
            download_remote_config(self.path_to_config)

        if (
            self.path_to_remote_config
            and self.file_helper.set_path(self.path_to_remote_config).exists()
        ):
            remote_data = self.dict_helper.from_yaml_file(self.path_to_remote_config)

            if isinstance(remote_data, dict):
                config = Merge(remote_data).into(config)

        if self.file_helper.set_path(self.path_to_overwrite_config).exists():
            # Load the overwrite configuration again to ensure that user defined
            # settings are always applied - last one wins.
            overwrite_data = self.dict_helper.from_yaml_file(
                self.path_to_overwrite_config
            )

            if isinstance(overwrite_data, dict):
                config = Merge(overwrite_data).into(config)

        return config

    def get_configured_value(self, entry: str) -> Any:
        """
        Provides the currently configured value.

        :param entry:
            An entry to check.

            multilevel should be separated with a point.

        :raise RuntimeError:
            When the configuration is not loaded yet.

        :raise ValueError:
            When the given :code:`entry` is not found.
        """

        if not self.is_already_loaded():
            raise RuntimeError("Configuration not loaded, yet.")

        if entry not in PyFunceble.storage.FLATTEN_CONFIGURATION:
            raise ValueError(f"<entry> ({entry!r}) not in loaded configuration.")

        return PyFunceble.storage.FLATTEN_CONFIGURATION[entry]

    def reload(self, keep_custom: bool = False) -> "ConfigLoader":
        """
        Reloads the configuration.

        :param bool keep_custom:
            If set to :code:`True`, we keep the custom configuration, otherwise
            we delete it.
        """

        self.destroy(keep_custom=keep_custom)
        self.start()

    def start(self) -> "ConfigLoader":
        """
        Starts the loading processIs.
        """

        load_dotenv(os.path.join(self.config_dir, ".env"))
        load_dotenv(os.path.join(self.config_dir, PyFunceble.storage.ENV_FILENAME))

        config = self.get_config_file_content()

        if self.custom_config:
            config = Merge(self.custom_config).into(config)

        config = self.conditional_switch(config)

        PyFunceble.storage.CONFIGURATION = Box(
            config,
        )
        PyFunceble.storage.FLATTEN_CONFIGURATION = DictHelper(
            PyFunceble.storage.CONFIGURATION
        ).flatten()
        PyFunceble.storage.HTTP_CODES = Box(
            config["http_codes"],
        )
        if "platform" in config and config["platform"]:
            PyFunceble.storage.PLATFORM = Box(config["platform"])
        PyFunceble.storage.LINKS = Box(config["links"])

        if "proxy" in config and config["proxy"]:
            PyFunceble.storage.PROXY = Box(config["proxy"])

        if "special_rules" in config and config["special_rules"]:
            PyFunceble.storage.SPECIAL_RULES = config["special_rules"]

        # Early load user agents to allow usage of defined user agents.
        UserAgentDataset().get_latest()

        self.__config_loaded = True

        return self

    def destroy(self, keep_custom: bool = False) -> "ConfigLoader":
        """
        Destroys everything loaded.

        :param bool keep_custom:
            If set to :code:`True`, we keep the custom configuration, otherwise
            we delete it.
        """

        try:
            PyFunceble.storage.CONFIGURATION = Box(
                {},
            )
            PyFunceble.storage.FLATTEN_CONFIGURATION = {}
            PyFunceble.storage.HTTP_CODES = Box({})
            PyFunceble.storage.PLATFORM = Box({})
            PyFunceble.storage.LINKS = Box({})
            PyFunceble.storage.PROXY = Box({})
            PyFunceble.storage.SPECIAL_RULES = Box({})
        except (AttributeError, TypeError):  # pragma: no cover ## Safety.
            pass

        if not keep_custom:
            # This is not a mistake.
            self._custom_config = {}

        self.__config_loaded = False

        return self