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
|
"""
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 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 datetime
import os
from typing import Optional
import PyFunceble.downloader.exceptions
import PyFunceble.exceptions
import PyFunceble.storage
from PyFunceble.helpers.dict import DictHelper
from PyFunceble.helpers.download import DownloadHelper
from PyFunceble.helpers.file import FileHelper
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.
"""
all_downtimes: Optional[dict] = {}
"""
Stores the download time of all files (self managed).
"""
_destination: Optional[str] = None
_download_link: Optional[str] = None
dict_helper: DictHelper = DictHelper()
def __init__(self) -> None:
self.downtimes_file = FileHelper(
os.path.join(
PyFunceble.storage.CONFIG_DIRECTORY, PyFunceble.storage.DOWN_FILENAME
)
)
self.all_downtimes.update(self.get_all_downtimes())
@property
def authorized(self) -> bool:
"""
Provides the authorization to start the download.
"""
raise NotImplementedError()
@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 DownloadHelper(self.download_link).download_text(
destination=self.destination
):
self.set_current_downtime()
self.save_all_downtimes()
|