Skip to content

# Base

The tool to check the availability or syntax of domain, IP or URL.

::

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

Provides the base of all our downloader.

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.

## `DownloaderBase`

Provides the base of all downloader classes.

The interface is actually simple, but the part which may be hard to understand is the "downtime" part. What we do, is that we save the download time inside a JSON file, so this class provides the base around the download mechanism but also the generation or update of that JSON file.

Source code in `PyFunceble/downloader/base.py`

     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

    class DownloaderBase:
        """
        Provides the base of all downloader classes.

        The interface is actually simple, but the part which may be hard to
        understand is the "downtime" part. What we do, is that we save the
        download time inside a JSON file, so this class provides the base around
        the download mechanism but also the generation or update of that JSON file.
        """

        DOWNTIME_INDEX: Optional[str] = None
        """
        Used to set/track the download time of the current file.
        """

        DOWNLOAD_FREQUENCY: int = 1
        """
        The download frequency (in day).

        Example:
            if 1 is given, it's once every 24 hours.

        .. warning::
            A frequency of :code:`0` or a negative number will force the download
            every hour.
        """

        DEFAULT_DOWNLOAD_URL: Optional[str] = None
        """
        The URL to download.
        """

        DEFAULT_FILENAME: Optional[str] = None
        """
        The name of the file to download.
        """

        all_downtimes: Optional[dict] = {}
        """
        Stores the download time of all files (self managed).
        """

        _config_dir: Optional[str] = None
        _destination: Optional[str] = None
        _download_link: Optional[str] = None
        _download_helper: Optional[DownloadHelper] = None

        dict_helper: Optional[DictHelper] = None

        def __init__(self, *, config_dir: Optional[str] = None) -> None:
            self.dict_helper = DictHelper()

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

            self.downtimes_file = FileHelper(
                os.path.join(self.config_dir, ".pyfunceble_intern_downtime.json")
            )

            self.all_downtimes.update(self.get_all_downtimes())

            if self.DEFAULT_DOWNLOAD_URL is not None:
                self.download_link = self.DEFAULT_DOWNLOAD_URL

            if self.DEFAULT_FILENAME is not None:
                self.destination = os.path.join(self.config_dir, self.DEFAULT_FILENAME)

            self._download_helper = DownloadHelper(
                self.download_link,
                own_proxy_handler=True,
                proxies=PyFunceble.storage.PROXY,
                certificate_validation=(
                    PyFunceble.storage.CONFIGURATION.verify_ssl_certificate
                    if PyFunceble.storage.CONFIGURATION
                    else True
                ),
            )

        @property
        def authorized(self) -> bool:
            """
            Provides the authorization to start the download.
            """

            raise NotImplementedError()

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

            return self._config_dir

        @config_dir.setter
        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

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

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

            self.config_dir = value

            return self

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

            return self._destination

        @destination.setter
        def destination(self, value: str) -> None:
            """
            Sets the destination.

            :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._destination = value

        def set_destination(self, value: str) -> "DownloaderBase":
            """
            Sets the destination.

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

            self.destination = value

            return self

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

            return self._download_link

        @download_link.setter
        def download_link(self, value: str) -> None:
            """
            Sets the link to download.

            :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._download_link = value

        def set_download_link(self, value: str) -> "DownloaderBase":
            """
            Sets the link to download.

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

            self.download_link = value

            return self

        def get_all_downtimes(self) -> dict:
            """
            Provides the downloadtime of all files.
            """

            return self.dict_helper.from_json_file(self.downtimes_file.path)

        def is_downtime_set(self) -> bool:
            """
            Checks if the download time of the current object exists.
            """

            return (
                self.DOWNTIME_INDEX in self.all_downtimes
                and self.all_downtimes[self.DOWNTIME_INDEX]
                and all(
                    x in self.all_downtimes[self.DOWNTIME_INDEX]
                    and self.all_downtimes[self.DOWNTIME_INDEX][x]
                    for x in ["iso", "timestamp"]
                )
            )

        def get_current_downtime(self):
            """
            Provides the download times of the current :code:`DOWN_TIME_INDEX`.
            """

            if self.is_downtime_set():
                return self.all_downtimes[self.DOWNTIME_INDEX]
            return None

        def set_current_downtime(self) -> "DownloaderBase":
            """
            Sets the current datetime into our registry.
            """

            current_datetime = datetime.datetime.now(datetime.timezone.utc)
            if epoch := os.environ.get("SOURCE_DATE_EPOCH"):
                current_datetime = datetime.datetime.fromtimestamp(
                    float(epoch), datetime.timezone.utc
                )

            self.all_downtimes[self.DOWNTIME_INDEX] = {
                "iso": current_datetime.isoformat(),
                "timestamp": current_datetime.timestamp(),
            }

            return self

        def save_all_downtimes(self) -> None:
            """
            Saves the current state of the all downtimes.
            """

            self.dict_helper.set_subject(self.all_downtimes).to_json_file(
                self.downtimes_file.path
            )

        def is_last_download_expired(self) -> bool:
            """
            Checks if the last downloaded file is expired (if exists).
            """

            if not FileHelper(self.destination).exists() or not self.is_downtime_set():
                return True

            last_downloaded_time = datetime.datetime.fromtimestamp(
                self.get_current_downtime()["timestamp"], datetime.timezone.utc
            )

            if (
                self.DOWNLOAD_FREQUENCY <= 0
                and (
                    datetime.datetime.now(datetime.timezone.utc) - last_downloaded_time
                ).seconds
                < 3600
            ):
                return False

            if last_downloaded_time + datetime.timedelta(
                days=self.DOWNLOAD_FREQUENCY
            ) <= datetime.datetime.now(datetime.timezone.utc):
                return True

            return False

        def start(self) -> None:
            """
            Starts the download process.
            """

            if self.authorized and self.is_last_download_expired():
                if not hasattr(self, "destination") or not self.destination:
                    raise PyFunceble.downloader.exceptions.NoDownloadDestinationGiven()

                if not hasattr(self, "download_link") or not self.download_link:
                    raise PyFunceble.downloader.exceptions.NoDownloadLinkGiven()

                if self._download_helper.download_text(destination=self.destination):
                    self.set_current_downtime()
                    self.save_all_downtimes()

### `DEFAULT_DOWNLOAD_URL = None` `class-attribute` `instance-attribute`

The URL to download.

### `DEFAULT_FILENAME = None` `class-attribute` `instance-attribute`

The name of the file to download.

### `DOWNLOAD_FREQUENCY = 1` `class-attribute` `instance-attribute`

The download frequency (in day).

Example: if 1 is given, it's once every 24 hours.

.. warning:: A frequency of :code:`0` or a negative number will force the download every hour.

### `DOWNTIME_INDEX = None` `class-attribute` `instance-attribute`

Used to set/track the download time of the current file.

### `all_downtimes = {}` `class-attribute` `instance-attribute`

Stores the download time of all files (self managed).

### `authorized` `property`

Provides the authorization to start the download.

### `config_dir` `property` `writable`

Provides the current state of the :code:`_config_dir` attribute.

### `destination` `property` `writable`

Provides the current state of the :code:`_destination` attribute.

### `download_link` `property` `writable`

Provides the current state of the :code:`_download_link` attribute.

### `get_all_downtimes()`

Provides the downloadtime of all files.

Source code in `PyFunceble/downloader/base.py`

    264
    265
    266
    267
    268
    269

    def get_all_downtimes(self) -> dict:
        """
        Provides the downloadtime of all files.
        """

        return self.dict_helper.from_json_file(self.downtimes_file.path)

### `get_current_downtime()`

Provides the download times of the current :code:`DOWN_TIME_INDEX`.

Source code in `PyFunceble/downloader/base.py`

    286
    287
    288
    289
    290
    291
    292
    293

    def get_current_downtime(self):
        """
        Provides the download times of the current :code:`DOWN_TIME_INDEX`.
        """

        if self.is_downtime_set():
            return self.all_downtimes[self.DOWNTIME_INDEX]
        return None

### `is_downtime_set()`

Checks if the download time of the current object exists.

Source code in `PyFunceble/downloader/base.py`

    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284

    def is_downtime_set(self) -> bool:
        """
        Checks if the download time of the current object exists.
        """

        return (
            self.DOWNTIME_INDEX in self.all_downtimes
            and self.all_downtimes[self.DOWNTIME_INDEX]
            and all(
                x in self.all_downtimes[self.DOWNTIME_INDEX]
                and self.all_downtimes[self.DOWNTIME_INDEX][x]
                for x in ["iso", "timestamp"]
            )
        )

### `is_last_download_expired()`

Checks if the last downloaded file is expired (if exists).

Source code in `PyFunceble/downloader/base.py`

    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

    def is_last_download_expired(self) -> bool:
        """
        Checks if the last downloaded file is expired (if exists).
        """

        if not FileHelper(self.destination).exists() or not self.is_downtime_set():
            return True

        last_downloaded_time = datetime.datetime.fromtimestamp(
            self.get_current_downtime()["timestamp"], datetime.timezone.utc
        )

        if (
            self.DOWNLOAD_FREQUENCY <= 0
            and (
                datetime.datetime.now(datetime.timezone.utc) - last_downloaded_time
            ).seconds
            < 3600
        ):
            return False

        if last_downloaded_time + datetime.timedelta(
            days=self.DOWNLOAD_FREQUENCY
        ) <= datetime.datetime.now(datetime.timezone.utc):
            return True

        return False

### `save_all_downtimes()`

Saves the current state of the all downtimes.

Source code in `PyFunceble/downloader/base.py`

    313
    314
    315
    316
    317
    318
    319
    320

    def save_all_downtimes(self) -> None:
        """
        Saves the current state of the all downtimes.
        """

        self.dict_helper.set_subject(self.all_downtimes).to_json_file(
            self.downtimes_file.path
        )

### `set_config_dir(value)`

Sets the configuration directory.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`value` | `str` | The value to set. | required

Source code in `PyFunceble/downloader/base.py`

    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188

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

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

        self.config_dir = value

        return self

### `set_current_downtime()`

Sets the current datetime into our registry.

Source code in `PyFunceble/downloader/base.py`

    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311

    def set_current_downtime(self) -> "DownloaderBase":
        """
        Sets the current datetime into our registry.
        """

        current_datetime = datetime.datetime.now(datetime.timezone.utc)
        if epoch := os.environ.get("SOURCE_DATE_EPOCH"):
            current_datetime = datetime.datetime.fromtimestamp(
                float(epoch), datetime.timezone.utc
            )

        self.all_downtimes[self.DOWNTIME_INDEX] = {
            "iso": current_datetime.isoformat(),
            "timestamp": current_datetime.timestamp(),
        }

        return self

### `set_destination(value)`

Sets the destination.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`value` | `str` | The value to set. | required

Source code in `PyFunceble/downloader/base.py`

    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225

    def set_destination(self, value: str) -> "DownloaderBase":
        """
        Sets the destination.

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

        self.destination = value

        return self

### `set_download_link(value)`

Sets the link to download.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`value` | `str` | The value to set. | required

Source code in `PyFunceble/downloader/base.py`

    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262

    def set_download_link(self, value: str) -> "DownloaderBase":
        """
        Sets the link to download.

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

        self.download_link = value

        return self

### `start()`

Starts the download process.

Source code in `PyFunceble/downloader/base.py`

    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364

    def start(self) -> None:
        """
        Starts the download process.
        """

        if self.authorized and self.is_last_download_expired():
            if not hasattr(self, "destination") or not self.destination:
                raise PyFunceble.downloader.exceptions.NoDownloadDestinationGiven()

            if not hasattr(self, "download_link") or not self.download_link:
                raise PyFunceble.downloader.exceptions.NoDownloadLinkGiven()

            if self._download_helper.download_text(destination=self.destination):
                self.set_current_downtime()
                self.save_all_downtimes()