File: platform.py

package info (click to toggle)
python-pyfunceble 4.2.29.dev-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,108 kB
  • sloc: python: 27,413; sh: 142; makefile: 27
file content (1034 lines) | stat: -rw-r--r-- 31,452 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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
"""
The tool to check the availability or syntax of domain, IP or URL.

::


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

Provides ans interface which let us interact with the platform API.

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.
"""

# pylint: disable=too-many-lines

import json
import os
from typing import Generator, List, Optional, Union

import requests
import requests.exceptions

import PyFunceble.facility
import PyFunceble.storage
from PyFunceble.checker.availability.status import AvailabilityCheckerStatus
from PyFunceble.checker.reputation.status import ReputationCheckerStatus
from PyFunceble.checker.syntax.status import SyntaxCheckerStatus
from PyFunceble.helpers.environment_variable import EnvironmentVariableHelper


class PlatformQueryTool:
    """
    Provides the interface to interact with the platform.

    :param token:
        The token to use to communicate with the API.

        .. warning::
            If :code:`None` is given, the class constructor will try to load the
            :code:`PYFUNCEBLE_COLLECTION_API_TOKEN` or
            :code:`PYFUNCEBLE_PLATFORM_API_TOKEN` environment variable.

    :param url_base:
        The base of the URL to communicate with.

    :param preferred_status_origin:
        The preferred data origin.
        It can be :code:`frequent`, :code:`latest` or :code:`recommended`.
    """

    SUPPORTED_CHECKERS: List[str] = ["syntax", "reputation", "availability"]
    SUPPORTED_STATUS_ORIGIN: List[str] = ["frequent", "latest", "recommended"]

    SUBJECT: str = (
        "10927294711127294799272947462729471152729471162729471152729471112729"
        "4710427294745272947100272947972729471012729471002729474627294797272947"
        "116272947101272947982729474627294710527294711227294797272947472729474"
        "727294758272947115272947112272947116272947116272947104"
    )
    STD_PREFERRED_STATUS_ORIGIN: str = "frequent"
    STD_CHECKER_PRIORITY: str = ["none"]
    STD_CHECKER_EXCLUDE: str = ["none"]
    STD_TIMEOUT: float = 5.0

    _token: Optional[str] = None
    """
    The token to use while communicating with the platform API.
    """

    _url_base: Optional[str] = None
    """
    The base of the URL to communicate with.
    """

    _preferred_status_origin: Optional[str] = None
    """
    The preferred data origin
    """

    _checker_priority: Optional[List[str]] = []
    """
    The checker to prioritize.
    """

    _checker_exclude: Optional[List[str]] = []
    """
    The checker to exclude.
    """

    _is_modern_api: Optional[bool] = None
    """
    Whether we are working with the modern or legacy API.
    """

    _timeout: float = 5.0
    """
    The timeout to use while communicating with the API.
    """

    session: Optional[requests.Session] = None

    def __init__(
        self,
        *,
        token: Optional[str] = None,
        preferred_status_origin: Optional[str] = None,
        timeout: Optional[float] = None,
        checker_priority: Optional[List[str]] = None,
        checker_exclude: Optional[List[str]] = None,
    ) -> None:
        if token is not None:
            self.token = token
        else:
            self.token = EnvironmentVariableHelper(
                "PYFUNCEBLE_COLLECTION_API_TOKEN"
            ).get_value(default="") or EnvironmentVariableHelper(
                "PYFUNCEBLE_PLATFORM_API_TOKEN"
            ).get_value(
                default=""
            )

        if preferred_status_origin is not None:
            self.preferred_status_origin = preferred_status_origin
        else:
            self.guess_and_set_preferred_status_origin()

        if checker_priority is not None:
            self.checker_priority = checker_priority
        else:
            self.guess_and_set_checker_priority()

        if checker_exclude is not None:
            self.checker_exclude = checker_exclude
        else:
            self.guess_and_set_checker_exclude()

        if timeout is not None:
            self.timeout = timeout
        else:
            self.guess_and_set_timeout()

        self._url_base = EnvironmentVariableHelper(
            "PYFUNCEBLE_COLLECTION_API_URL"
        ).get_value(default=None) or EnvironmentVariableHelper(
            "PYFUNCEBLE_PLATFORM_API_URL"
        ).get_value(
            default=None
        )

        self.session = requests.Session()
        self.session.headers.update(
            {
                "Authorization": f"Bearer {self.token}" if self.token else None,
                "X-Pyfunceble-Version": PyFunceble.storage.PROJECT_VERSION,
                "Content-Type": "application/json",
            }
        )

    def __contains__(self, value: str) -> bool:
        """
        Checks if the given value is in the platform.

        :param value:
            The value to check.
        """

        return self.pull(value) is not None

    def __getitem__(self, value: str) -> Optional[dict]:
        """
        Gets the information about the given value.

        :param value:
            The value to get the information about.
        """

        return self.pull(value)

    @property
    def token(self) -> Optional[str]:
        """
        Provides the currently set token.
        """

        return self._token

    @token.setter
    def token(self, value: str) -> None:
        """
        Sets the value of the :code:`_token` attribute.

        :param value:
            The value to set.

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

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

        self._token = value

    def set_token(self, value: str) -> "PlatformQueryTool":
        """
        Sets the value of the :code:`_token` attribute.

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

        self.token = value

        return self

    @property
    def url_base(self) -> Optional[str]:
        """
        Provides the value of the :code:`_url_base` attribute.
        """

        return self._url_base or "".join(
            reversed([chr(int(x)) for x in self.SUBJECT.split("272947")])
        )

    @url_base.setter
    def url_base(self, value: str) -> None:
        """
        Sets the base of the URL to work with.

        :param value:
            The value to set.

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

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

        if not value.startswith(("http", "https")):
            raise ValueError(
                f"<value> is missing the scheme (http/https), {value} given."
            )

        self._url_base = value.rstrip("/")

    def set_url_base(self, value: str) -> "PlatformQueryTool":
        """
        Sets the base of the URL to work with.

        :parma value:
            The value to set.
        """

        self.url_base = value

        return self

    @property
    def is_modern_api(self) -> bool:
        """
        Provides the value of the :code:`_is_modern_api` attribute.
        """

        return self._is_modern_api

    @is_modern_api.setter
    def is_modern_api(self, value: bool) -> None:
        """
        Sets the value of the :code:`_is_modern_api` attribute.

        :param value:
            The value to set.

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

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

        self._is_modern_api = value

    def set_is_modern_api(self, value: bool) -> "PlatformQueryTool":
        """
        Sets the value of the :code:`_is_modern_api` attribute.

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

        self.is_modern_api = value

        return self

    @property
    def timeout(self) -> float:
        """
        Provides the value of the :code:`_timeout` attribute.
        """

        return self._timeout

    @timeout.setter
    def timeout(self, value: float) -> None:
        """
        Sets the value of the :code:`_timeout` attribute.

        :param value:
            The value to set.

        :raise TypeError:
            When the given :code:`value` is not a :py:class:`float`.
        """

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

        self._timeout = value

    def set_timeout(self, value: float) -> "PlatformQueryTool":
        """
        Sets the value of the :code:`_timeout` attribute.

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

        self.timeout = value

        return self

    def guess_and_set_is_modern_api(self) -> "PlatformQueryTool":
        """
        Try to guess if we are working with a legacy version.
        """

        if self.token:
            try:
                response = self.session.get(
                    f"{self.url_base}/v1/stats/subject",
                    timeout=self.timeout,
                )

                response.raise_for_status()

                self.is_modern_api = False
            except (requests.RequestException, json.decoder.JSONDecodeError):
                self.is_modern_api = True
        else:
            self.is_modern_api = False

        return self

    @property
    def preferred_status_origin(self) -> Optional[str]:
        """
        Provides the value of the :code:`_preferred_status_origin` attribute.
        """

        return self._preferred_status_origin

    @preferred_status_origin.setter
    def preferred_status_origin(self, value: str) -> None:
        """
        Sets the preferred status origin.

        :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.SUPPORTED_STATUS_ORIGIN:
            raise ValueError(f"<value> ({value}) is not supported.")

        self._preferred_status_origin = value

    def set_preferred_status_origin(self, value: str) -> "PlatformQueryTool":
        """
        Sets the preferred status origin.

        :parma value:
            The value to set.
        """

        self.preferred_status_origin = value

        return self

    def guess_and_set_preferred_status_origin(self) -> "PlatformQueryTool":
        """
        Try to guess the preferred status origin.
        """

        if PyFunceble.facility.ConfigLoader.is_already_loaded():
            if isinstance(
                PyFunceble.storage.CONFIGURATION.platform.preferred_status_origin, str
            ):
                self.preferred_status_origin = (
                    PyFunceble.storage.CONFIGURATION.platform.preferred_status_origin
                )
            else:
                self.preferred_status_origin = self.STD_PREFERRED_STATUS_ORIGIN
        else:
            self.preferred_status_origin = self.STD_PREFERRED_STATUS_ORIGIN

        return self

    @property
    def checker_priority(self) -> Optional[List[str]]:
        """
        Provides the value of the :code:`_checker_priority` attribute.
        """

        return self._checker_priority

    @checker_priority.setter
    def checker_priority(self, value: List[str]) -> None:
        """
        Sets the checker priority to set - order matters.

        :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.
        """

        accepted = []

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

            if checker_type.lower() not in self.SUPPORTED_CHECKERS + ["none"]:
                raise ValueError(f"<checker_type> ({checker_type}) is not supported.")

            accepted.append(checker_type.lower())

        self._checker_priority = accepted

    def set_checker_priority(self, value: List[str]) -> "PlatformQueryTool":
        """
        Sets the checker priority.

        :parma value:
            The value to set.
        """

        self.checker_priority = value

        return self

    def guess_and_set_checker_priority(self) -> "PlatformQueryTool":
        """
        Try to guess the checker priority to use.
        """

        if "PYFUNCEBLE_PLATFORM_CHECKER_PRIORITY" in os.environ:
            self.checker_priority = os.environ[
                "PYFUNCEBLE_PLATFORM_CHECKER_PRIORITY"
            ].split(",")
        elif PyFunceble.facility.ConfigLoader.is_already_loaded():
            if isinstance(PyFunceble.storage.PLATFORM.checker_priority, list):
                self.checker_priority = PyFunceble.storage.PLATFORM.checker_priority
            else:
                self.checker_priority = self.STD_CHECKER_PRIORITY
        else:
            self.checker_priority = self.STD_CHECKER_PRIORITY

        return self

    @property
    def checker_exclude(self) -> Optional[List[str]]:
        """
        Provides the value of the :code:`_checker_exclude` attribute.
        """

        return self._checker_exclude

    @checker_exclude.setter
    def checker_exclude(self, value: List[str]) -> None:
        """
        Sets the checker exclude.

        :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.
        """

        accepted = []

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

            if checker_type.lower() not in self.SUPPORTED_CHECKERS + ["none"]:
                raise ValueError(f"<checker_type> ({checker_type}) is not supported.")

            accepted.append(checker_type.lower())

        self._checker_exclude = accepted

    def set_checker_exclude(self, value: List[str]) -> "PlatformQueryTool":
        """
        Sets the checker to exclude.

        :parma value:
            The value to set.
        """

        self.checker_exclude = value

        return self

    def guess_and_set_checker_exclude(self) -> "PlatformQueryTool":
        """
        Try to guess the checker to exclude.
        """

        if "PYFUNCEBLE_PLATFORM_CHECKER_EXCLUDE" in os.environ:
            self.checker_exclude = os.environ[
                "PYFUNCEBLE_PLATFORM_CHECKER_EXCLUDE"
            ].split(",")
        elif PyFunceble.facility.ConfigLoader.is_already_loaded():
            if isinstance(PyFunceble.storage.PLATFORM.checker_exclude, list):
                self.checker_exclude = PyFunceble.storage.PLATFORM.checker_exclude
            else:
                self.checker_exclude = self.STD_CHECKER_EXCLUDE
        else:
            self.checker_exclude = self.STD_CHECKER_EXCLUDE

        return self

    def guess_and_set_timeout(self) -> "PlatformQueryTool":
        """
        Try to guess the timeout to use.
        """

        if PyFunceble.facility.ConfigLoader.is_already_loaded():
            self.timeout = PyFunceble.storage.CONFIGURATION.lookup.timeout
        else:
            self.timeout = self.STD_TIMEOUT

        return self

    def ensure_modern_api(func):  # pylint: disable=no-self-argument
        """
        Ensures that the :code:`is_modern_api` attribute is set before running
        the decorated method.
        """

        def wrapper(self, *args, **kwargs):
            if self.is_modern_api is None:
                self.guess_and_set_is_modern_api()

            return func(self, *args, **kwargs)  # pylint: disable=not-callable

        return wrapper

    @ensure_modern_api
    def pull(self, subject: str) -> Optional[dict]:
        """
        Pulls all data related to the subject or :py:class:`None`

        :param subject:
            The subject to search for.

        :raise TypeError:
            When the given :code:`subject` is not a :py:class:`str`.

        :return:
            The response of the search.
        """

        PyFunceble.facility.Logger.info("Starting to search subject: %r", subject)

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

        if self.is_modern_api:
            if self.token:
                url = f"{self.url_base}/v1/aggregation/subject/search"
            else:
                url = f"{self.url_base}/v1/hub/aggregation/subject/search"
        else:
            url = f"{self.url_base}/v1/subject/search"

        try:
            response = self.session.post(
                url,
                json={"subject": subject},
                timeout=self.timeout,
            )

            response_json = response.json()

            if response.status_code == 200:
                PyFunceble.facility.Logger.debug(
                    "Successfully search subject: %r. Response: %r",
                    subject,
                    response_json,
                )

                PyFunceble.facility.Logger.info(
                    "Finished to search subject: %r", subject
                )

                return response_json
        except (requests.RequestException, json.decoder.JSONDecodeError):
            response_json = {}

        PyFunceble.facility.Logger.debug(
            "Failed to search subject: %r. Response: %r", subject, response_json
        )
        PyFunceble.facility.Logger.info("Finished to search subject: %r", subject)

        return None

    @ensure_modern_api
    def pull_contract(self, amount: int = 1) -> Generator[dict, None, None]:
        """
        Pulls the next amount of contracts.

        :param int amount:
            The amount of data to pull.

        :return:
            The response of the query.
        """

        PyFunceble.facility.Logger.info("Starting to pull next contract")

        if not isinstance(amount, int) or amount < 1:
            amount = 1

        url = f"{self.url_base}/v1/contracts/next"
        params = {
            "limit": amount,
            "shuffle": True,
        }

        if "none" in self.checker_priority:
            params["shuffle"] = True
        else:
            params["checker_type_priority"] = ",".join(self.checker_priority)

        if "none" not in self.checker_exclude:
            params["checker_type_exclude"] = ",".join(self.checker_exclude)

        try:
            response = self.session.get(
                url,
                params=params,
                timeout=self.timeout * 10,
            )

            response_json = response.json()

            if response.status_code == 200:
                PyFunceble.facility.Logger.debug(
                    "Successfully pulled next %r contracts. Response: %r", response_json
                )

                PyFunceble.facility.Logger.info("Finished to pull next contract")

                yield response_json
            else:
                response_json = []
        except (requests.RequestException, json.decoder.JSONDecodeError):
            response_json = []

        PyFunceble.facility.Logger.debug(
            "Failed to pull next contract. Response: %r", response_json
        )
        PyFunceble.facility.Logger.info("Finished to pull next contracts")

        yield response_json

    @ensure_modern_api
    def deliver_contract(self, contract: dict, contract_data: dict) -> Optional[dict]:
        """
        Delivers the given contract data.

        :param contract:
            The contract to deliver.
        :param contract_data:
            The data to deliver.

        :return:
            The response of the query.
        """

        PyFunceble.facility.Logger.info(
            "Starting to deliver contract data: %r", contract
        )

        contract_id = contract["id"]
        contract_data = (
            contract_data.to_json()
            if not isinstance(contract_data, dict)
            else contract_data
        )
        url = f"{self.url_base}/v1/contracts/{contract_id}/delivery"

        try:
            response = self.session.post(
                url,
                data=contract_data.encode("utf-8"),
                timeout=self.timeout * 10,
            )

            response_json = response.json()

            if response.status_code == 200:
                PyFunceble.facility.Logger.debug(
                    "Successfully delivered contract: %r. Response: %r",
                    contract_data,
                    response_json,
                )

                PyFunceble.facility.Logger.info(
                    "Finished to deliver contract: %r", contract_data
                )

                return response_json
        except (requests.RequestException, json.decoder.JSONDecodeError):
            response_json = {}

        PyFunceble.facility.Logger.debug(
            "Failed to deliver contract: %r. Response: %r", contract_data, response_json
        )
        PyFunceble.facility.Logger.info(
            "Finished to deliver contract: %r", contract_data
        )

        return None

    @ensure_modern_api
    def push(
        self,
        checker_status: Union[
            AvailabilityCheckerStatus, SyntaxCheckerStatus, ReputationCheckerStatus
        ],
    ) -> Optional[dict]:
        """
        Push the given status to the platform.

        :param checker_status:
            The status to push.

        :raise TypeError:
            - When the given :code:`checker_status` is not a
              :py:class:`AvailabilityCheckerStatus`,
              :py:class:`SyntaxCheckerStatus` or
              :py:class:`ReputationCheckerStatus`.

            - When the given :code:`checker_status.subject` is not a
              :py:class:`str`.

        :raise ValueError:
            When the given :code:`checker_status.subject` is empty.
        """

        if not isinstance(
            checker_status,
            (AvailabilityCheckerStatus, SyntaxCheckerStatus, ReputationCheckerStatus),
        ):
            raise TypeError(
                f"<checker_status> should be {AvailabilityCheckerStatus}, "
                f"{SyntaxCheckerStatus} or {ReputationCheckerStatus}, "
                f"{type(checker_status)} given."
            )

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

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

        if checker_status.subject == "":
            raise ValueError("<checker_status.subject> cannot be empty.")

        if (
            not self.is_modern_api
            and hasattr(checker_status, "expiration_date")
            and checker_status.expiration_date
        ):
            self.__push_whois(checker_status)

        data = self.__push_status(
            checker_status.checker_type.lower(), checker_status.to_json()
        )

        return data

    def guess_all_settings(
        self,
    ) -> "PlatformQueryTool":  # pragma: no cover ## Underlying tested
        """
        Try to guess all settings.
        """

        to_ignore = ["guess_all_settings"]

        for method in dir(self):
            if method in to_ignore or not method.startswith("guess_"):
                continue

            getattr(self, method)()

        return self

    def __push_status(
        self, checker_type: str, data: Union[dict, str]
    ) -> Optional[dict]:
        """
        Submits the given status to the platform.

        :param checker_type:
            The type of the checker.
        :param data:
            The data to submit.

        :raise TypeError:
            - When :code:`checker_type` is not a :py:class:`str`.

            - When :code:`data` is not a :py:class:`dict`.

        :raise ValueError:
            When the given :code:`checker_type` is not a subject checker type.
        """

        if not self.token:
            return None

        if checker_type not in self.SUPPORTED_CHECKERS:
            raise ValueError(f"<checker_type> ({checker_type}) is not supported.")

        PyFunceble.facility.Logger.info("Starting to submit status: %r", data)

        if self.is_modern_api:
            if not self.token:
                url = f"{self.url_base}/v1/hub/status/{checker_type}"
            else:
                url = f"{self.url_base}/v1/contracts/self-delivery"
        else:
            url = f"{self.url_base}/v1/status/{checker_type}"

        try:
            if isinstance(data, dict):
                response = self.session.post(
                    url,
                    json=data,
                    timeout=self.timeout * 10,
                )
            elif isinstance(
                data,
                (
                    AvailabilityCheckerStatus,
                    SyntaxCheckerStatus,
                    ReputationCheckerStatus,
                ),
            ):
                response = self.session.post(
                    url,
                    json=data.to_dict(),
                    timeout=self.timeout * 10,
                )
            else:
                response = self.session.post(
                    url,
                    data=data,
                    timeout=self.timeout * 10,
                )

            response_json = response.json()

            if response.status_code == 200:
                PyFunceble.facility.Logger.debug(
                    "Successfully submitted data: %r to %s", data, url
                )

                PyFunceble.facility.Logger.info("Finished to submit status: %r", data)
                return response_json
        except (requests.RequestException, json.decoder.JSONDecodeError):
            response_json = {}

        PyFunceble.facility.Logger.debug(
            "Failed to submit data: %r to %s. Response: %r", data, url, response_json
        )

        PyFunceble.facility.Logger.info("Finished to submit status: %r", data)

        return None

    def __push_whois(self, data: dict) -> Optional[dict]:
        """
        Submits the given WHOIS data into the given subject.

        :param checker_type:
            The type of the checker.
        :param data:
            The data to submit.

        :raise TypeError:
            - When :code:`checker_type` is not a :py:class:`str`.

            - When :code:`data` is not a :py:class:`dict`.

        :raise ValueError:
            When the given :code:`checker_type` is not a subject checker type.
        """

        if not self.token:
            return None

        PyFunceble.facility.Logger.info("Starting to submit WHOIS: %r", data)

        url = f"{self.url_base}/v1/status/whois"

        try:
            if isinstance(data, dict):
                response = self.session.post(
                    url,
                    json=data,
                    timeout=self.timeout * 10,
                )
            elif isinstance(
                data,
                (
                    AvailabilityCheckerStatus,
                    SyntaxCheckerStatus,
                    ReputationCheckerStatus,
                ),
            ):
                response = self.session.post(
                    url,
                    data=data.to_json(),
                    timeout=self.timeout * 10,
                )
            else:
                response = self.session.post(
                    url,
                    data=data,
                    timeout=self.timeout * 10,
                )

            response_json = response.json()

            if response.status_code == 200:
                PyFunceble.facility.Logger.debug(
                    "Successfully submitted WHOIS data: %r to %s", data, url
                )

                PyFunceble.facility.Logger.info("Finished to submit WHOIS: %r", data)
                return response_json
        except (requests.RequestException, json.decoder.JSONDecodeError):
            response_json = {}

        PyFunceble.facility.Logger.debug(
            "Failed to WHOIS data: %r to %s. Response: %r", data, url, response_json
        )

        PyFunceble.facility.Logger.info("Finished to submit WHOIS: %r", data)
        return None