glpi-python-client 0.6.2__py3-none-any.whl → 0.6.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -131,7 +131,7 @@ from glpi_python_client.rsql import (
131
131
  date_window,
132
132
  )
133
133
 
134
- __version__ = "0.6.2"
134
+ __version__ = "0.6.3"
135
135
 
136
136
  __all__ = [
137
137
  "AsyncGlpiClient",
@@ -6,6 +6,10 @@ payloads and the package's canonical Markdown and typed-record representations.
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
- from glpi_python_client.content.conversion import GlpiContentConverter
9
+ from glpi_python_client.content.conversion import (
10
+ GlpiContentConverter,
11
+ Link,
12
+ RewriteLink,
13
+ )
10
14
 
11
- __all__ = ["GlpiContentConverter"]
15
+ __all__ = ["GlpiContentConverter", "Link", "RewriteLink"]
@@ -40,9 +40,12 @@ import re
40
40
  import string
41
41
  import unicodedata
42
42
  from collections.abc import Callable, Iterator, Mapping, MutableMapping, Sequence
43
+ from contextvars import ContextVar
44
+ from dataclasses import dataclass
43
45
  from functools import cached_property
44
46
  from html import escape, unescape
45
47
  from typing import Any, cast
48
+ from urllib.parse import parse_qs, urlsplit
46
49
 
47
50
  import cmarkgfm
48
51
  import mdformat_tables
@@ -59,7 +62,7 @@ from mdformat.renderer import (
59
62
  )
60
63
  from mdformat.renderer.typing import Postprocess
61
64
 
62
- from glpi_python_client._errors import GlpiContentError
65
+ from glpi_python_client._errors import GlpiContentError, GlpiValidationError
63
66
 
64
67
  #: Element names that make a ``<...>`` sequence markup rather than text: the
65
68
  #: HTML5 elements, then the obsolete ones old editors and mail clients write.
@@ -363,6 +366,97 @@ def _title(title: str) -> str:
363
366
  return ' "' + re.sub(r'[\\"]', r"\\\g<0>", title) + '"' if title else ""
364
367
 
365
368
 
369
+ #: The page GLPI serves a document from. Its editor embeds a pasted image as
370
+ #: ``<img src=".../front/document.send.php?docid=N&itemtype=Ticket&items_id=T">``
371
+ #: inside a link to the same URL, and links an attachment the same way.
372
+ _DOCUMENT_PAGE = "front/document.send.php"
373
+
374
+ #: A document id, as the ``docid`` parameter carries one: ASCII digits only,
375
+ #: since ``int`` also reads other scripts' digits.
376
+ _DOCUMENT_ID = re.compile(r"[0-9]{1,18}")
377
+
378
+ #: An item type, as ``itemtype`` names one: a PHP class name.
379
+ _ITEMTYPE = re.compile(r"[A-Za-z_][A-Za-z0-9_\\]{0,99}")
380
+
381
+
382
+ @dataclass(frozen=True, slots=True)
383
+ class Link:
384
+ """A link or an image the reader meets, as a ``rewrite_link`` callback sees it.
385
+
386
+ Attributes
387
+ ----------
388
+ href : str
389
+ An ``<a>``'s ``href`` or an ``<img>``'s ``src``, character references
390
+ decoded.
391
+ text : str
392
+ An ``<a>``'s displayed text or an ``<img>``'s ``alt``, whitespace
393
+ collapsed.
394
+ title : str
395
+ The ``title``, or ``""``.
396
+ image : bool
397
+ ``True`` for an ``<img>``.
398
+ document_id : int or None
399
+ For a link or an image whose URL is GLPI's document page with a
400
+ ``docid`` (:meth:`GlpiContentConverter.document_id_of`), that id;
401
+ ``None`` otherwise.
402
+ enclosing_href : str or None
403
+ For an ``<img>`` inside a link, that link's ``href``; ``None``
404
+ otherwise. The image is read before the link around it.
405
+ """
406
+
407
+ href: str
408
+ text: str = ""
409
+ title: str = ""
410
+ image: bool = False
411
+ document_id: int | None = None
412
+ enclosing_href: str | None = None
413
+
414
+
415
+ #: A ``rewrite_link`` callback: called with each link and image a read meets,
416
+ #: outside code. ``None`` keeps what the reader writes without one. A ``str`` is
417
+ #: written instead, as literal text. A :class:`Link` is written in the reader's
418
+ #: own spelling: a link's ``href`` and ``title``, around the link's content as
419
+ #: read; an image's ``href`` as its ``src``, ``text`` as its ``alt`` and
420
+ #: ``title``. An empty ``href`` drops a link and keeps its content, and writes an
421
+ #: image as its ``text``.
422
+ RewriteLink = Callable[[Link], "Link | str | None"]
423
+
424
+ _REWRITE: ContextVar[RewriteLink | None] = ContextVar("rewrite_link", default=None)
425
+ """The callback of the read in progress. A context variable rather than state
426
+ on the shared converter: each thread and each task reads with its own."""
427
+
428
+
429
+ class _CallbackRaised(Exception):
430
+ """What a ``rewrite_link`` callback raised, carried past the reader's fallbacks.
431
+
432
+ The reader answers a ``ValueError`` by reading the body as its text; a
433
+ callback's own ``ValueError`` must not pass for markdownify's and quietly
434
+ cost the body its formatting.
435
+ """
436
+
437
+ def __init__(self, error: Exception) -> None:
438
+ super().__init__(error)
439
+ self.error = error
440
+
441
+
442
+ def _rewritten(link: Link) -> Link | str | None:
443
+ """Ask the read's callback about ``link``; ``None`` when there is none."""
444
+
445
+ rewrite = _REWRITE.get()
446
+ if rewrite is None:
447
+ return None
448
+ try:
449
+ answer: object = rewrite(link) # typed as what it is, not what it should be
450
+ except Exception as exc:
451
+ raise _CallbackRaised(exc) from exc
452
+ if answer is None or isinstance(answer, (Link, str)):
453
+ return answer
454
+ error = TypeError(
455
+ f"rewrite_link returned {type(answer).__name__}; expected Link, str or None"
456
+ )
457
+ raise _CallbackRaised(error)
458
+
459
+
366
460
  class _Converter(MarkdownConverter):
367
461
  """``markdownify``, with what CommonMark and the reader's glue need on top.
368
462
 
@@ -520,15 +614,34 @@ class _Converter(MarkdownConverter):
520
614
  body, _, tail = rest.rpartition("```")
521
615
  return f"{head}{fence}{body}{fence}{tail}"
522
616
 
617
+ def _literal(self, text: str, parent_tags: set[str]) -> str:
618
+ """``text`` escaped as the reader escapes a text node: displayed as it is."""
619
+
620
+ return self.escape(" ".join(text.split()), parent_tags)
621
+
523
622
  def convert_a(self, el: Tag, text: str, parent_tags: set[str]) -> str:
524
623
  """A link; ``<url>`` when its text is its URL and reads back unchanged."""
525
624
 
625
+ if "_noformat" in parent_tags:
626
+ return text
526
627
  href = str(el.get("href") or "")
628
+ title = str(el.get("title") or "")
629
+ answer = _rewritten(
630
+ Link(
631
+ href,
632
+ " ".join(el.get_text().split()),
633
+ title,
634
+ document_id=GlpiContentConverter.document_id_of(href),
635
+ )
636
+ )
637
+ if isinstance(answer, str):
638
+ return self._literal(answer, parent_tags)
639
+ if answer is not None:
640
+ href, title = answer.href, answer.title
527
641
  edges = _EDGES.fullmatch(text)
528
- if "_noformat" in parent_tags or not href or edges is None or not edges[2]:
642
+ if not href or edges is None or not edges[2]:
529
643
  return text
530
644
  before, inner, after = edges.groups()
531
- title = str(el.get("title") or "")
532
645
  if not title and el.get_text() == href and _AUTOLINK.fullmatch(href):
533
646
  return f"{before}<{href}>{after}"
534
647
  return f"{before}[{inner}]({_destination(href)}{_title(title)}){after}"
@@ -536,12 +649,37 @@ class _Converter(MarkdownConverter):
536
649
  def convert_img(self, el: Tag, text: str, parent_tags: set[str]) -> str:
537
650
  """An image, wherever it is: a cell or a heading holds one too."""
538
651
 
652
+ src = str(el.get("src") or "")
539
653
  alt = " ".join(str(el.get("alt") or "").split())
654
+ title = str(el.get("title") or "")
655
+ if "_noformat" not in parent_tags:
656
+ around = el.find_parent("a")
657
+ answer = _rewritten(
658
+ Link(
659
+ src,
660
+ alt,
661
+ title,
662
+ image=True,
663
+ document_id=GlpiContentConverter.document_id_of(src),
664
+ enclosing_href=(
665
+ None if around is None else str(around.get("href") or "")
666
+ ),
667
+ )
668
+ )
669
+ if isinstance(answer, str):
670
+ return self._literal(answer, parent_tags)
671
+ if answer is not None and not answer.href:
672
+ return self._literal(answer.text, parent_tags)
673
+ if answer is not None:
674
+ src, alt, title = (
675
+ answer.href,
676
+ " ".join(answer.text.split()),
677
+ answer.title,
678
+ )
540
679
  alt = str(self._inherited("escape")(alt, parent_tags))
541
680
  if alt.startswith("^") and "_noformat" not in parent_tags:
542
681
  alt = "\\" + alt # cmark-gfm reads "![^" as "!" and a link
543
- src = _destination(str(el.get("src") or ""))
544
- return f"![{alt}]({src}{_title(str(el.get('title') or ''))})"
682
+ return f"![{alt}]({_destination(src)}{_title(title)})"
545
683
 
546
684
 
547
685
  class _Node(RenderTreeNode):
@@ -752,11 +890,45 @@ def _text_of(html: str) -> str:
752
890
  return "\n".join(line for line in lines if line)
753
891
 
754
892
 
893
+ def _converted(content: str) -> str:
894
+ """Read HTML, falling back to its text where the conversion cannot."""
895
+
896
+ try:
897
+ try:
898
+ return html_to_markdown(content)
899
+ except (RecursionError, ValueError): # ValueError: markdownify's
900
+ # int() of a colspan or start such as "²" or 5,000 digits
901
+ return html_to_markdown(_plain_text_html(_text_of(content)))
902
+ except ParserRejectedMarkup:
903
+ # html.parser gives up on a few malformed declarations; the
904
+ # body's words are still worth more than an exception.
905
+ text = unescape(_ANY_TAG.sub(" ", content))
906
+ return html_to_markdown(_plain_text_html(" ".join(text.split())))
907
+ except _CallbackRaised:
908
+ raise
909
+ except Exception as exc:
910
+ raise GlpiContentError(
911
+ "Could not convert GLPI HTML content to Markdown "
912
+ f"({type(exc).__name__}: {exc})."
913
+ ) from exc
914
+
915
+
916
+ def _positive(value: object) -> bool:
917
+ """Whether ``value`` is a positive ``int`` and not a ``bool``."""
918
+
919
+ return isinstance(value, int) and not isinstance(value, bool) and value > 0
920
+
921
+
755
922
  class GlpiContentConverter:
756
923
  """Convert content between GLPI HTML payloads and canonical Markdown."""
757
924
 
758
925
  @staticmethod
759
- def from_transport(value: object, *, plain_text_is_markdown: bool = False) -> str:
926
+ def from_transport(
927
+ value: object,
928
+ *,
929
+ plain_text_is_markdown: bool = False,
930
+ rewrite_link: RewriteLink | None = None,
931
+ ) -> str:
760
932
  """Convert one GLPI transport value into Markdown.
761
933
 
762
934
  Parameters
@@ -774,6 +946,12 @@ class GlpiContentConverter:
774
946
  Markdown, but Markdown that opens with an autolink or other
775
947
  angle-bracketed text and carries inline HTML further on is read
776
948
  as HTML, and loses that autolink.
949
+ rewrite_link : callable, optional
950
+ Called with a :class:`Link` for each link and image the read
951
+ meets outside code, an image before the link around it; its
952
+ answer decides what is written (:data:`RewriteLink`). Not called
953
+ for a value passed through as Markdown, nor for a body read as
954
+ its text. Without one, the read is what it always was.
777
955
 
778
956
  Returns
779
957
  -------
@@ -793,6 +971,10 @@ class GlpiContentConverter:
793
971
  limit, where no stack is left even to report the failure as
794
972
  ``GlpiContentError`` (the user guide gives the measured
795
973
  depths).
974
+ Exception
975
+ Whatever ``rewrite_link`` raised, unchanged; ``TypeError`` when it
976
+ answered something other than a :class:`Link`, a ``str`` or
977
+ ``None``.
796
978
  """
797
979
 
798
980
  content = str(value or "").strip()
@@ -808,22 +990,96 @@ class GlpiContentConverter:
808
990
  # 3.11.14/3.12.12/3.13.6 rescans to the end for each (quadratic).
809
991
  head, end, tail = content.rpartition(">")
810
992
  content = head + end + tail.replace("<", "&lt;")
993
+ token = _REWRITE.set(rewrite_link)
811
994
  try:
812
- try:
813
- return html_to_markdown(content)
814
- except (RecursionError, ValueError): # ValueError: markdownify's
815
- # int() of a colspan or start such as "²" or 5,000 digits
816
- return html_to_markdown(_plain_text_html(_text_of(content)))
817
- except ParserRejectedMarkup:
818
- # html.parser gives up on a few malformed declarations; the
819
- # body's words are still worth more than an exception.
820
- text = unescape(_ANY_TAG.sub(" ", content))
821
- return html_to_markdown(_plain_text_html(" ".join(text.split())))
822
- except Exception as exc:
823
- raise GlpiContentError(
824
- "Could not convert GLPI HTML content to Markdown "
825
- f"({type(exc).__name__}: {exc})."
826
- ) from exc
995
+ return _converted(content)
996
+ except _CallbackRaised as raised:
997
+ callback_error = raised.error
998
+ finally:
999
+ _REWRITE.reset(token)
1000
+ raise callback_error # outside the handler: the callback's, as it raised it
1001
+
1002
+ @staticmethod
1003
+ def document_id_of(url: str) -> int | None:
1004
+ """Return the document id a URL to GLPI's document page names.
1005
+
1006
+ ``None`` unless ``url`` -- relative, rooted or absolute, with any
1007
+ path in front -- is ``front/document.send.php`` with exactly one
1008
+ ``docid`` parameter, in any position, made of digits.
1009
+ """
1010
+
1011
+ try:
1012
+ parts = urlsplit(url)
1013
+ except ValueError: # an unclosed "[" in a host, among others
1014
+ return None
1015
+ path = parts.path
1016
+ if path != _DOCUMENT_PAGE and not path.endswith("/" + _DOCUMENT_PAGE):
1017
+ return None
1018
+ values = parse_qs(parts.query).get("docid", [])
1019
+ if len(values) != 1 or not _DOCUMENT_ID.fullmatch(values[0]):
1020
+ return None
1021
+ document_id = int(values[0])
1022
+ return document_id if document_id > 0 else None
1023
+
1024
+ @staticmethod
1025
+ def document_image(
1026
+ document_id: int,
1027
+ *,
1028
+ alt: str = "",
1029
+ itemtype: str | None = None,
1030
+ items_id: int | None = None,
1031
+ ) -> str:
1032
+ """Return the Markdown of an image embedding one of GLPI's documents.
1033
+
1034
+ :meth:`to_transport` renders it as GLPI's editor writes a pasted image
1035
+ -- the ``<img>`` inside a link to the same URL,
1036
+ ``/front/document.send.php?docid=<document_id>``, then
1037
+ ``&itemtype=...&items_id=...`` when given -- and :meth:`from_transport`
1038
+ reads that back as this same Markdown: it is spelled by the reader
1039
+ itself. The URL is rooted, as the editor wrote it on the instance
1040
+ measured; GLPI checks the reader's right to the document when it
1041
+ serves it.
1042
+
1043
+ Parameters
1044
+ ----------
1045
+ document_id : int
1046
+ The document's id.
1047
+ alt : str, optional
1048
+ The image's alternative text.
1049
+ itemtype, items_id : str and int, optional
1050
+ The item the document is attached to, such as ``"Ticket"`` and
1051
+ its id. Both or neither.
1052
+
1053
+ Raises
1054
+ ------
1055
+ GlpiValidationError
1056
+ ``document_id`` or ``items_id`` is not a positive ``int``,
1057
+ ``itemtype`` is not a class name, or only one of the two was
1058
+ given.
1059
+ """
1060
+
1061
+ if not _positive(document_id):
1062
+ raise GlpiValidationError(f"not a GLPI document id: {document_id!r}")
1063
+ url = f"/{_DOCUMENT_PAGE}?docid={document_id}"
1064
+ if (itemtype is None) != (items_id is None):
1065
+ raise GlpiValidationError(
1066
+ "itemtype and items_id go together: give both or neither"
1067
+ )
1068
+ if itemtype is not None:
1069
+ if not _ITEMTYPE.fullmatch(itemtype):
1070
+ raise GlpiValidationError(f"not a GLPI item type: {itemtype!r}")
1071
+ if not _positive(items_id):
1072
+ raise GlpiValidationError(f"not a GLPI item id: {items_id!r}")
1073
+ url += f"&itemtype={itemtype}&items_id={items_id}"
1074
+ native = (
1075
+ f'<p><a href="{escape(url)}" target="_blank">'
1076
+ f'<img src="{escape(url)}" alt="{escape(" ".join(alt.split()))}" /></a></p>'
1077
+ )
1078
+ token = _REWRITE.set(None) # a callback in force for an enclosing read
1079
+ try:
1080
+ return html_to_markdown(native)
1081
+ finally:
1082
+ _REWRITE.reset(token)
827
1083
 
828
1084
  @staticmethod
829
1085
  def to_transport(value: object) -> str:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: glpi-python-client
3
- Version: 0.6.2
3
+ Version: 0.6.3
4
4
  Summary: A typed Python client for GLPI ITSM APIs.
5
5
  Project-URL: Homepage, https://github.com/baraline/glpi_python_client
6
6
  Project-URL: Documentation, https://glpi-python-client.readthedocs.io/en/latest/
@@ -1,4 +1,4 @@
1
- glpi_python_client/__init__.py,sha256=DGjWsC96c-1sfryxVwHThPASrR5sy0IpNiooeAVx5Wk,5538
1
+ glpi_python_client/__init__.py,sha256=IMYtZ6FcQdH6IPopjnPwGlKf-nb6QjjTb1JLgq0AXYY,5538
2
2
  glpi_python_client/_errors.py,sha256=Bc9UvlxulbdcGvzZIKXnJCTL78sW78R6EFg50P-1dpY,7151
3
3
  glpi_python_client/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
4
  glpi_python_client/rsql.py,sha256=3u3lH3_-F1bvHbVzxALXTDPoHyoMATP1f4QPTar_sEU,8974
@@ -94,8 +94,8 @@ glpi_python_client/_sync/clients/commons/_transport.py,sha256=x9xRFSUrJLPyp1DrVh
94
94
  glpi_python_client/_sync/clients/custom/__init__.py,sha256=sxfGlHVulucP7bacWhUMi9qGJZaiZm8lXceY0OGqWio,882
95
95
  glpi_python_client/_sync/clients/custom/_statistics.py,sha256=xrD5C99ieROJx60iUomBHacQ_49HpgQL4XjnfREUQvs,38616
96
96
  glpi_python_client/_sync/clients/custom/_ticket_context.py,sha256=LDUvKNr8VpZonF5bDo8QYYwMEsWmayVU28Ra3GonNmE,3004
97
- glpi_python_client/content/__init__.py,sha256=3H4IbrNhgFO0BJrc0xLoeXrFHUE1nqOaDlNgi2MtK9k,365
98
- glpi_python_client/content/conversion.py,sha256=0IjZ-36WlGMGwo4sHk92bZ3DDsZxVK0YKGCwrFlnRpo,33158
97
+ glpi_python_client/content/__init__.py,sha256=TaZPo8WSvVj4U-hSnxhUcqU8JnCKNZYpfQf4pH45aN4,424
98
+ glpi_python_client/content/conversion.py,sha256=bglYY5IgoTv2SdS0Gton7WgsyzwwQ5GdU_2dLloL2l0,42860
99
99
  glpi_python_client/models/__init__.py,sha256=b6DPZtH0CxyBUnVB0x9vP9AMBIjgubDFm_1TOQuCiVA,5362
100
100
  glpi_python_client/models/_base.py,sha256=pYg69KHuR5TDED5utr4Knr7HncBnLTxXHJZYf6vEUKA,12183
101
101
  glpi_python_client/models/api_schema/__init__.py,sha256=yTxUYih1Xy7NUogzD7UKp2b8HyE4wdeC_FCKS6ZRVVM,1176
@@ -135,7 +135,7 @@ glpi_python_client/models/custom_schema/_ticket_context.py,sha256=jnlfgho-aDbmA9
135
135
  glpi_python_client/testing/__init__.py,sha256=iLtUyJjyv3fEhy3PN25NxNTbtqDl3SoHLbNium0Z80U,568
136
136
  glpi_python_client/testing/fixtures.py,sha256=HKt6MXHgcmLn4L98pSwp-oGlc9C--_vrABNe5G_iBeg,1286
137
137
  glpi_python_client/testing/utils.py,sha256=JyO3w2d-0kYdtC1hEZ2Tu_YjnCz8nUQ_Ck05-1EhsX4,4404
138
- glpi_python_client-0.6.2.dist-info/METADATA,sha256=9wihyUuKVM3_SjCpxgML5kJfV09itUlO6VTUoMwxzgw,8234
139
- glpi_python_client-0.6.2.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
140
- glpi_python_client-0.6.2.dist-info/licenses/LICENSE,sha256=nL8re-TIKkxCoL7OkSBja6EB4NsQR1HoOJgxv_MEhtc,1088
141
- glpi_python_client-0.6.2.dist-info/RECORD,,
138
+ glpi_python_client-0.6.3.dist-info/METADATA,sha256=4RZb8YHJdpzGHRZpengz0BnNOWHWaTzEDFgmc1WyDss,8234
139
+ glpi_python_client-0.6.3.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
140
+ glpi_python_client-0.6.3.dist-info/licenses/LICENSE,sha256=nL8re-TIKkxCoL7OkSBja6EB4NsQR1HoOJgxv_MEhtc,1088
141
+ glpi_python_client-0.6.3.dist-info/RECORD,,