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
|
"""
The tool to check the availability or syntax of domain, IP or URL.
::
██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗
██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝
██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗
██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝
██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝
Provides the base of all our printers.
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 copy
import functools
import string
from typing import Any, Callable, Dict, List, Optional
class PrinterBase:
"""
Provides the base of all printer class.
Printer classes are classes which derivate from this class. their objectives
should be the same: Unify and simplify the way to print something to a given
destination.
"""
STD_UNKNOWN: str = "Unknown"
STD_LENGTH: Dict[str, int] = {
"idna_subject": 100,
"status": 11,
"status_source": 10,
"http_status_code": 10,
"percentage": 12,
"expiration_date": 17,
"amount": 12,
"checker_type": 13,
"days": 2,
"hours": 2,
"minutes": 2,
"seconds": 6,
"registrar": 30,
"tested_at": 19,
}
TEMPLATES: Dict[str, string.Template] = {
"all": string.Template(
"$idna_subject $status $status_source $expiration_date $registrar "
"$http_status_code $checker_type $tested_at"
),
"less": string.Template("$idna_subject $status $status_source $tested_at"),
"simple": string.Template("$idna_subject $status"),
"percentage": string.Template("$status $percentage $amount"),
"hosts": string.Template("$ip $idna_subject"),
"plain": string.Template("$idna_subject"),
"execution_time": string.Template(
"\nExecution Time: $days:$hours:$minutes:$seconds\n"
),
"registrar": string.Template("$registrar $percentage $amount"),
}
HEADERS: Dict[str, str] = {
"idna_subject": "Subject",
"status": "Status",
"status_source": "Source",
"http_status_code": "HTTP Code",
"expiration_date": "Expiration Date",
"percentage": "Percentage",
"amount": "Amount",
"ip": "IP",
"checker_type": "Checker",
"days": "Days",
"hours": "Hours",
"minutes": "Minutes",
"seconds": "Seconds",
"registrar": "Registrar",
"tested_at": "Tested At",
}
extra_formatters: Dict[str, Callable[..., Any]] = {}
_template_to_use: Optional[str] = None
_dataset: Optional[Dict[str, str]] = None
_skip_column: Optional[List[str]] = []
def __init__(
self,
template_to_use: Optional[str] = None,
*,
dataset: Optional[Dict[str, str]] = None,
skip_column: Optional[List[str]] = None,
extra_formatters: Optional[Dict[str, Callable[..., Any]]] = None,
) -> None:
if template_to_use is not None:
self.template_to_use = template_to_use
if dataset is not None:
self.dataset = dataset
if skip_column is not None:
self.skip_column = skip_column
if extra_formatters is not None:
self.extra_formatters.update(extra_formatters)
def ensure_template_to_use_is_given(func): # pylint: disable=no-self-argument
"""
Ensures that the template to use is given before launching the
decorated method.
:raise TypeError:
When the current :code:`self.template_to_use` is not set.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if not isinstance(self.template_to_use, str):
raise TypeError("<self.template_to_use> is not given.")
return func(self, *args, **kwargs) # pylint: disable=not-callable
return wrapper
def ensure_dataset_is_given(func): # pylint: disable=no-self-argument
"""
Ensures that the dataset to write is given before launching the
decorated method.
:raise TypeError:
When the current :code:`self.template_to_use` is not set.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if not isinstance(self.dataset, dict):
raise TypeError("<self.dataset> is not given.")
return func(self, *args, **kwargs) # pylint: disable=not-callable
return wrapper
@property
def skip_column(self) -> Optional[List[str]]:
"""
Provides the current state of the :code:`_skip_column` attribute.
"""
return self._skip_column
@skip_column.setter
def skip_column(self, value: List[str]) -> None:
"""
Sets the columns to skip.
:param value:
The value to set.
:raise TypeError:
When the given :code:`value` is not a :py:class:`list`.
"""
if not isinstance(value, list):
raise TypeError(f"<value> should be {list}, {type(value)} given.")
if any(not isinstance(x, str) for x in value):
raise TypeError(f"<value> should be a list of {str}, {type(value)} given.")
self._skip_column = value
def set_skip_column(self, value: List[str]) -> "PrinterBase":
"""
Sets the columns to skip.
:param value:
The value to set.
"""
self.skip_column = value
return self
@property
def template_to_use(self) -> Optional[str]:
"""
Provides the current state of the :code:`_template_to_use` attribute.
"""
return self._template_to_use
@template_to_use.setter
def template_to_use(self, value: str) -> None:
"""
Sets the template to use.
:param value:
The value to set.
:raise TypeError:
When the given :code:`value` is not a :py:class:`str`.
:raise ValueError:
When the given :code:`value` is not supported.
"""
if not isinstance(value, str):
raise TypeError(f"<value> should be {str}, {type(value)} given.")
if value not in self.TEMPLATES:
raise ValueError(
f"<value> ({value!r}) is not supported "
f"({list(self.TEMPLATES.keys())!r})."
)
self._template_to_use = value
def set_template_to_use(self, value: str) -> "PrinterBase":
"""
Sets the template to use.
:param value:
The value to set.
"""
self.template_to_use = value
return self
@property
def dataset(self) -> Optional[Dict[str, str]]:
"""
Provides the current state of the :code:`_dataset` attribute.
"""
return self._dataset
@dataset.setter
def dataset(self, value: Dict[str, str]) -> None:
"""
Sets the dataset to apply to the template.
:param value:
The value to set.
:raise TypeError:
When the given :code:`value` is not a :py:class:`dict`
:raise ValueError:
When the given :code:`value` is empty.
"""
if not isinstance(value, dict):
raise TypeError(f"<value> should be {dict}, {type(value)} given.")
if not value:
raise ValueError("<value> should not be empty.")
self._dataset = copy.deepcopy(value)
def set_dataset(self, value: Dict[str, str]) -> "PrinterBase":
"""
Sets the dataset to apply to the template.
:param value:
The value to set.
"""
self.dataset = value
return self
@ensure_template_to_use_is_given
def get_header_to_print(self) -> str:
"""
Provides the template header to print.
"""
ignore_header = ["simple", "hosts", "plain", "execution_time"]
to_print_data = [dict(), dict()] # pylint: disable=use-dict-literal
if self.template_to_use not in ignore_header:
for key, value in self.HEADERS.items():
if key not in self.TEMPLATES[self.template_to_use].template:
continue
if key in self.skip_column:
self.TEMPLATES[self.template_to_use].template = (
self.TEMPLATES[self.template_to_use]
.template.replace(f"${key} ", "")
.replace(f" ${key}", "")
)
continue
to_print_data[0][key] = f"{value:<{self.STD_LENGTH[key]}}"
for key, value in to_print_data[0].items():
to_print_data[1][key] = "-" * len(value)
to_print = [
self.TEMPLATES[self.template_to_use].safe_substitute(
**to_print_data[0]
),
self.TEMPLATES[self.template_to_use].safe_substitute(
**to_print_data[1]
),
]
return "\n".join(to_print)
return ""
@ensure_template_to_use_is_given
@ensure_dataset_is_given
def get_line_to_print(self) -> str:
"""
Provides the line to print.
"""
to_print = {}
ignore_length = ["simple", "hosts", "plain", "execution_time"]
for key, value in self.dataset.items():
if key not in self.HEADERS or key in self.skip_column:
continue
if not value and value != 0:
value = self.STD_UNKNOWN
if key in self.extra_formatters:
value = self.extra_formatters[key](value)
if self.template_to_use not in ignore_length:
to_print[key] = f"{value:<{self.STD_LENGTH[key]}}"
else:
to_print[key] = value
missings = [
x[1:]
for x in self.TEMPLATES[self.template_to_use].template.split()
if x.startswith("$") and x[1:] not in to_print
]
for missing in missings:
try:
to_print[missing] = f"{self.STD_UNKNOWN:<{self.STD_LENGTH[missing]}}"
except KeyError:
# Example: execution time
pass
return self.TEMPLATES[self.template_to_use].safe_substitute(**to_print)
def print_header(self) -> None:
"""
Prints the header.
"""
header = self.get_header_to_print()
if header:
print(f"\n\n{header}")
def print_interpolated_line(self) -> None:
"""
Prints the line where we are suppose to write it.
"""
raise NotImplementedError()
|