ssb-pubmd 0.1.0__py3-none-any.whl → 0.1.2__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.
ssb_pubmd/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from ssb_pubmd.notebook_client import configure_factbox as Factbox
2
+ from ssb_pubmd.notebook_client import create_highchart as Highchart
3
+
4
+ __all__ = ["Factbox", "Highchart"]
ssb_pubmd/__main__.py CHANGED
@@ -1,23 +1,12 @@
1
1
  import sys
2
2
 
3
- from ssb_pubmd.adapters.cli import CliAdapter
4
- from ssb_pubmd.adapters.cms_client import MimirCmsClient
5
- from ssb_pubmd.adapters.local_storage import LocalStorageAdapter
6
- from ssb_pubmd.adapters.secret_manager_client import GoogleSecretManagerClient
3
+ from ssb_pubmd.cli import run_cli
7
4
  from ssb_pubmd.config import get_config
8
- from ssb_pubmd.enonic_cms_manager import EnonicCmsManager
9
5
 
10
6
 
11
7
  def main() -> None:
12
8
  config = get_config()
13
- cms_manager = EnonicCmsManager(
14
- config=config,
15
- cms_client=MimirCmsClient(config.cms_base_url),
16
- secret_manager_client=GoogleSecretManagerClient(config.gc_secret_resource_name),
17
- content_file_handler=LocalStorageAdapter(config.metadata_file_path),
18
- )
19
- cli_adapter = CliAdapter(cms_manager=cms_manager)
20
- cli_adapter.run(sys.argv)
9
+ run_cli(sys.argv, config)
21
10
 
22
11
 
23
12
  if __name__ == "__main__":
@@ -0,0 +1,185 @@
1
+ from collections.abc import Mapping
2
+ from dataclasses import asdict
3
+ from dataclasses import dataclass
4
+ from typing import Any
5
+ from typing import Literal
6
+ from typing import Protocol
7
+
8
+ import nh3
9
+
10
+
11
+ @dataclass
12
+ class Content:
13
+ title: str
14
+ content_type: str
15
+ publish_folder: str | None = None
16
+ publish_id: str | None = None
17
+
18
+ def to_dict(self) -> dict[str, Any]:
19
+ return asdict(self)
20
+
21
+ def serialize(self) -> dict[str, Any]:
22
+ raise NotImplementedError()
23
+
24
+ class ContentParser(Protocol):
25
+ def parse(self, metadata: Mapping[str, Any], html: str | None) -> Content: ...
26
+
27
+
28
+ @dataclass
29
+ class MimirContent(Content):
30
+ def is_publishable(self) -> bool:
31
+ if self.title == "":
32
+ return False
33
+ if self.publish_id is None and self.publish_folder is None:
34
+ return False
35
+ return True
36
+
37
+ def serialize(self) -> dict[str, Any]:
38
+ if not self.is_publishable():
39
+ raise Exception()
40
+ s: dict[str, Any] = {
41
+ "contentType": "mimir:" + self.content_type,
42
+ "displayName": self.title,
43
+ "parentPath": self.publish_folder,
44
+ "data": {},
45
+ }
46
+ if self.publish_id is not None:
47
+ s["_id"] = self.publish_id
48
+ return s
49
+
50
+
51
+ @dataclass
52
+ class Author:
53
+ name: str
54
+ email: str
55
+
56
+ @dataclass
57
+ class Article(MimirContent):
58
+ content_type: str = "article"
59
+ authors: list[Author] | None = None
60
+ ingress: str = ""
61
+ html_text: str = ""
62
+
63
+ def serialize(self) -> dict[str, Any]:
64
+ s = super().serialize()
65
+ if self.authors:
66
+ s["data"]["authorItemSet"] = [asdict(author) for author in self.authors]
67
+ s["data"]["ingress"] = self.ingress
68
+ s["data"]["articleText"] = self.html_text
69
+ return s
70
+
71
+
72
+ GraphType = Literal["line", "pie", "column", "bar", "area", "barNegative"]
73
+
74
+
75
+ @dataclass
76
+ class Highchart(MimirContent):
77
+ content_type: str = "highchart"
78
+ graph_type: GraphType = "line"
79
+ html_table: str | None = None
80
+ tbml: str | None = None
81
+ xlabel: str = "x"
82
+ ylabel: str = "y"
83
+
84
+ def serialize(self) -> dict[str, Any]:
85
+ s = super().serialize()
86
+
87
+ if self.html_table is not None:
88
+ s["data"]["htmlTable"] = self.html_table
89
+ elif self.tbml is not None:
90
+ s["data"]["dataSource"] = {
91
+ "_selected": "tbprocessor",
92
+ "tbprocessor": {"urlOrId": self.tbml},
93
+ }
94
+
95
+ s["data"]["xAxisTitle"] = self.xlabel
96
+ s["data"]["yAxisTitle"] = self.ylabel
97
+
98
+ return s
99
+
100
+
101
+ @dataclass
102
+ class FactBox(MimirContent):
103
+ content_type: str = "factBox"
104
+ display_type: Literal["default", "sneakPeek", "aiIcon"] = "default"
105
+ html_text: str = ""
106
+
107
+ def serialize(self) -> dict[str, Any]:
108
+ s = super().serialize()
109
+ s["data"]["expansionBoxType"] = self.display_type
110
+ s["data"]["text"] = self.html_text
111
+ return s
112
+
113
+
114
+ BASIC_HTML_TAGS = {
115
+ "p",
116
+ "br",
117
+ "strong",
118
+ "em",
119
+ "b",
120
+ "i",
121
+ "ul",
122
+ "ol",
123
+ "li",
124
+ "blockquote",
125
+ "h1",
126
+ "h2",
127
+ "h3",
128
+ "h4",
129
+ "h5",
130
+ "a",
131
+ }
132
+
133
+
134
+ class MimirContentParser:
135
+ def parse(self, metadata: Mapping[str, Any], html: str | None) -> Content:
136
+ match metadata.get("content_type"):
137
+ case "article":
138
+ return self._parse_article(metadata, html)
139
+ case "factBox":
140
+ return self._parse_factbox(metadata, html)
141
+ case "highchart":
142
+ return self._parse_highchart(metadata, html)
143
+ case _:
144
+ return MimirContent(**metadata)
145
+
146
+ def serialize(self, content: Content) -> dict[str, Any]:
147
+ if isinstance(content, MimirContent):
148
+ return content.serialize()
149
+ else:
150
+ raise Exception()
151
+
152
+ @classmethod
153
+ def _parse_article(cls, metadata: Mapping[str, Any], html: str | None) -> Article:
154
+ article = Article(
155
+ title=metadata["title"],
156
+ publish_folder="/ssb" + metadata["path"],
157
+ publish_id=metadata.get("publish_id"),
158
+ authors=[Author(**data) for data in metadata.get("authors", [])],
159
+ ingress=metadata.get("ingress", ""),
160
+ )
161
+ if html is not None:
162
+ allowed_html_tags = BASIC_HTML_TAGS
163
+ html_text = nh3.clean(html, tags=allowed_html_tags)
164
+ article.html_text = html_text
165
+ return article
166
+
167
+ @classmethod
168
+ def _parse_factbox(cls, metadata: Mapping[str, Any], html: str | None) -> FactBox:
169
+ factbox = FactBox(**metadata)
170
+ if html is not None:
171
+ allowed_html_tags = BASIC_HTML_TAGS - {"h2"}
172
+ html_text = nh3.clean(html, tags=allowed_html_tags)
173
+ factbox.html_text = html_text
174
+ return factbox
175
+
176
+ @classmethod
177
+ def _parse_highchart(
178
+ cls, metadata: Mapping[str, Any], html: str | None
179
+ ) -> Highchart:
180
+ highchart = Highchart(**metadata)
181
+ if html is not None:
182
+ allowed_html_tags = {"table", "tbody", "tr", "td"}
183
+ html_table = nh3.clean(html, tags=allowed_html_tags)
184
+ highchart.html_table = html_table
185
+ return highchart
@@ -0,0 +1,149 @@
1
+
2
+ import json
3
+ import subprocess
4
+ from collections.abc import Iterator
5
+ from typing import Any
6
+ from typing import NamedTuple
7
+ from typing import Protocol
8
+ from typing import TypedDict
9
+
10
+ import pandocfilters as pf # type: ignore
11
+
12
+
13
+ class Element(NamedTuple):
14
+ id: str
15
+ inner_html: str | None
16
+
17
+
18
+ class DocumentProcessor(Protocol):
19
+ def load(self, raw_content: str) -> None: ...
20
+ def extract_metadata(self, target_key: str) -> dict[str, Any]: ...
21
+ def extract_elements(self, target_class: str) -> Iterator[Element]: ...
22
+ def replace_element(self, id_: str, new_html: str) -> None: ...
23
+ def extract_html(self) -> str: ...
24
+
25
+
26
+
27
+ class PandocElement(TypedDict):
28
+ t: str
29
+ c: Any
30
+
31
+
32
+ PandocDocument = TypedDict(
33
+ "PandocDocument",
34
+ {
35
+ "pandoc-api-version": list[int],
36
+ "meta": dict[str, Any],
37
+ "blocks": list[PandocElement],
38
+ },
39
+ )
40
+
41
+
42
+ class PandocDocumentProcessor:
43
+ """
44
+ Processor for a pandoc document, i.e. the JSON-serialized pandoc AST of a document.
45
+
46
+ Example pandoc AST with exactly one div:
47
+
48
+ ```json
49
+ {
50
+ "pandoc-api-version": [1, 23, 1],
51
+ "meta": {},
52
+ "blocks": [
53
+ {
54
+ "t": "Div",
55
+ "c": [
56
+ ["my-highchart", ["ssb"], [["title", "My highchart"]]],
57
+ []
58
+ ]
59
+ }
60
+ ]
61
+ }
62
+ ```
63
+ Html equivalent:
64
+ ```html
65
+ <div id="my-highchart" class="ssb" title="My highchart">
66
+ </div>
67
+ ```
68
+ References:
69
+ - Studying the result of command `pandoc FILE -t json`, where FILE is a minimal example document (e.g. Markdown or html).
70
+ - https://github.com/jgm/pandocfilters has some examples of how to work with the format.
71
+ - Note: no formal specification exists.
72
+ """
73
+
74
+ document: PandocDocument
75
+ _element_index: dict[str, int]
76
+
77
+ def load(self, raw_content: str) -> None:
78
+ self.document: PandocDocument = json.loads(raw_content)
79
+ self._element_index = {}
80
+
81
+ def extract_metadata(self, target_key: str) -> dict[str, Any]:
82
+ def meta_to_dict(meta: Any) -> Any:
83
+ t, c = meta.get("t"), meta.get("c")
84
+ if t == "MetaMap":
85
+ return {k: meta_to_dict(v) for k, v in c.items()}
86
+ elif t == "MetaList":
87
+ return [meta_to_dict(v) for v in c]
88
+ else:
89
+ return pf.stringify(c)
90
+
91
+ return meta_to_dict(self.document["meta"][target_key]) # type: ignore
92
+
93
+ def extract_html(self) -> str:
94
+ return self._document_to_html(self.document)
95
+
96
+ def extract_elements(self, target_class: str) -> Iterator[Element]:
97
+ self._element_index = self._generate_element_index(target_class)
98
+
99
+ for id_, i in self._element_index.items():
100
+ element = self.document["blocks"][i]
101
+ inner_blocks: list[PandocElement] = element["c"][1]
102
+ inner_html = self._blocks_to_html(inner_blocks) if inner_blocks else None
103
+ yield Element(id_, inner_html)
104
+
105
+ def replace_element(self, id_: str, new_html: str) -> None:
106
+ i = self._element_index[id_]
107
+ self.document["blocks"][i] = {
108
+ "t": "RawBlock",
109
+ "c": ["html", new_html],
110
+ }
111
+
112
+ def _generate_element_index(self, target_class: str) -> dict[str, int]:
113
+ index = {}
114
+ for i, element in enumerate(self.document["blocks"]):
115
+ if element["t"] != "Div":
116
+ continue
117
+
118
+ id_: str = element["c"][0][0]
119
+ if not id_:
120
+ continue
121
+
122
+ classes: list[str] = element["c"][0][1]
123
+ if target_class not in classes:
124
+ continue
125
+
126
+ index[id_] = i
127
+
128
+ return index
129
+
130
+ @classmethod
131
+ def _blocks_to_html(cls, blocks: list[PandocElement]) -> str:
132
+ document: PandocDocument = {
133
+ "pandoc-api-version": [1, 23, 1],
134
+ "meta": {},
135
+ "blocks": blocks,
136
+ }
137
+ return cls._document_to_html(document)
138
+
139
+ @classmethod
140
+ def _document_to_html(cls, document: PandocDocument) -> str:
141
+ result = subprocess.run(
142
+ ["pandoc", "-f", "json", "-t", "html"],
143
+ input=json.dumps(document),
144
+ text=True,
145
+ capture_output=True,
146
+ check=True,
147
+ )
148
+ html = result.stdout
149
+ return html
@@ -0,0 +1,117 @@
1
+ import os
2
+ from dataclasses import dataclass
3
+ from typing import Any
4
+ from typing import NamedTuple
5
+ from typing import Protocol
6
+
7
+ import requests
8
+ from dapla_auth_client import AuthClient
9
+
10
+ from ssb_pubmd.adapters.content_parser import Content
11
+ from ssb_pubmd.config import Config
12
+
13
+
14
+ class PublishClientError(Exception): ...
15
+
16
+ class HttpClient(Protocol):
17
+ def post(
18
+ self, url: str, headers: dict[str, str], payload: dict[str, Any]
19
+ ) -> dict[str, str]: ...
20
+
21
+ class RequestsHttpClient:
22
+ def post(
23
+ self, url: str, headers: dict[str, str], payload: dict[str, Any]
24
+ ) -> dict[str, str]:
25
+ response = requests.post(
26
+ url,
27
+ headers=headers,
28
+ json=payload,
29
+ )
30
+ body = response.json()
31
+ if not response.ok:
32
+ raise PublishClientError(
33
+ f"Sync failed. Response message: {body.get('msg', 'no message')}"
34
+ )
35
+ return body # type: ignore
36
+
37
+ class TokenClient(Protocol):
38
+ def get_token(self) -> str: ...
39
+
40
+
41
+ class LocalTokenClient:
42
+ def get_token(self) -> str:
43
+ return os.environ.get("OIDC_TOKEN", "")
44
+
45
+
46
+ class DaplaTokenClient:
47
+ def get_token(self) -> str:
48
+ return AuthClient.fetch_personal_token(audiences=["ssbno"])
49
+
50
+ class Response(NamedTuple):
51
+ publish_path: str
52
+ publish_id: str
53
+ publish_url: str
54
+ publish_html: str
55
+
56
+ class PublishClient(Protocol):
57
+ http_client: HttpClient
58
+
59
+ def send_content(self, content: Content) -> Response: ...
60
+
61
+ DEFAULT_HTTP_CLIENT = RequestsHttpClient()
62
+ DEFULT_TOKEN_CLIENT = LocalTokenClient()
63
+ @dataclass
64
+ class MimirPublishClient:
65
+ base_url: str
66
+ endpoint: str
67
+ preview_base_path: str
68
+ http_client: HttpClient = DEFAULT_HTTP_CLIENT
69
+ token_client: TokenClient = DEFULT_TOKEN_CLIENT
70
+
71
+ def _create_headers(self) -> dict[str, str]:
72
+ return {
73
+ "Authorization": f"Bearer {self.token_client.get_token()}",
74
+ "Content-Type": "application/json",
75
+ }
76
+
77
+ def send_content(self, content: Content) -> Response:
78
+ headers = self._create_headers()
79
+ response_body = self.http_client.post(
80
+ url=f"{self.base_url}{self.endpoint}",
81
+ headers=headers,
82
+ payload=content.serialize(),
83
+ )
84
+
85
+ id_ = response_body.get("_id")
86
+ path = response_body.get("_path")
87
+
88
+ if path is None or id_ is None:
89
+ raise PublishClientError("Sync failed. Could not parse response body.")
90
+
91
+ macro_type = (
92
+ content.content_type
93
+ if content.content_type in ["highchart", "factBox"]
94
+ else None
95
+ )
96
+ if id_ is not None and macro_type is not None:
97
+ html = f"<p>[ {macro_type} {content.content_type}=&quot;{id_}&quot; /]</p>"
98
+ else:
99
+ html = ""
100
+
101
+ return Response(
102
+ publish_path=path,
103
+ publish_id=id_,
104
+ publish_url=self.base_url + self.preview_base_path + path,
105
+ publish_html=html,
106
+ )
107
+
108
+
109
+ def get_publish_client(config: Config) -> PublishClient:
110
+ return MimirPublishClient(
111
+ base_url=config.publish_base_url,
112
+ endpoint="/webapp/pubmd",
113
+ preview_base_path=config.publish_admin_path + "/site/preview/default/draft",
114
+ token_client=DaplaTokenClient()
115
+ if config.use_dapla_token_client
116
+ else DEFULT_TOKEN_CLIENT,
117
+ )
@@ -0,0 +1,42 @@
1
+ import json
2
+ from collections.abc import Mapping
3
+ from pathlib import Path
4
+ from typing import Any
5
+ from typing import Protocol
6
+
7
+
8
+ class Storage(Protocol):
9
+ def update(self, key: str, data: Mapping[str, Any]) -> None: ...
10
+ def get(self, key: str) -> dict[str, Any]: ...
11
+
12
+ class LocalFileStorage:
13
+ path: Path
14
+
15
+ def __init__(self, project_folder: Path) -> None:
16
+ self.path = project_folder / ".ssbno.json"
17
+ if not self.path.exists():
18
+ with self.path.open("w") as f:
19
+ json.dump({}, f)
20
+
21
+ def _load(self) -> dict[str, dict[str, Any]]:
22
+ with self.path.open() as f:
23
+ return json.load(f) # type: ignore
24
+
25
+ def _save(self, data: dict[str, dict[str, Any]]) -> None:
26
+ with self.path.open("w") as f:
27
+ json.dump(data, f, indent=2)
28
+
29
+ def update(self, key: str, data: Mapping[str, Any]) -> None:
30
+ store = self._load()
31
+
32
+ current = store.get(key, {})
33
+ for field, value in data.items():
34
+ if value is not None:
35
+ current[field] = value
36
+
37
+ store[key] = current
38
+ self._save(store)
39
+
40
+ def get(self, key: str) -> dict[str, Any]:
41
+ store = self._load()
42
+ return store.get(key, {}).copy()
ssb_pubmd/cli.py ADDED
@@ -0,0 +1,102 @@
1
+ import subprocess
2
+ import sys
3
+ from importlib import resources
4
+ from pathlib import Path
5
+
6
+ from jinja2 import Template
7
+ from watchfiles import watch
8
+
9
+ from ssb_pubmd import templates
10
+ from ssb_pubmd.adapters.content_parser import MimirContentParser
11
+ from ssb_pubmd.adapters.document_processor import PandocDocumentProcessor
12
+ from ssb_pubmd.adapters.publish_client import PublishClient
13
+ from ssb_pubmd.adapters.publish_client import get_publish_client
14
+ from ssb_pubmd.adapters.storage import LocalFileStorage
15
+ from ssb_pubmd.config import Config
16
+ from ssb_pubmd.domain.document_publisher import sync_document
17
+
18
+
19
+ def run_cli(system_arguments: list[str], config: Config) -> None:
20
+ match system_arguments:
21
+ case [_, "create", filename]:
22
+ _create_template(filename, config)
23
+ case [_, "preview", filename]:
24
+ _preview(filename, config)
25
+ case _:
26
+ print("Usage:")
27
+ print(" ssb-pubmd create FILENAME")
28
+ print(" ssb-pubmd preview FILENAME")
29
+ sys.exit(1)
30
+
31
+
32
+ def _create_template(filename: str, config: Config) -> None:
33
+ destination = Path.cwd() / filename
34
+ if destination.suffix != ".qmd":
35
+ print("The destination file path must have the '.qmd' extension.")
36
+ sys.exit(1)
37
+
38
+ with resources.open_text(templates, "template.qmd") as file:
39
+ raw_template = file.read()
40
+
41
+ rendered_template = Template(raw_template).render(
42
+ filepath=destination,
43
+ cms_admin_url=config.publish_base_url + config.publish_admin_path,
44
+ project_folder=destination.parent.name,
45
+ filename=destination.name,
46
+ )
47
+ destination.write_text(rendered_template)
48
+ print(
49
+ f"Successfully created template file {destination}.\n",
50
+ "Open the file for further instructions.",
51
+ )
52
+
53
+
54
+ def _preview(file_path: str, config: Config) -> None:
55
+ if Path(file_path).suffix != ".qmd":
56
+ print("Only Quarto Markdown (.qmd) files are supported.")
57
+ sys.exit(1)
58
+
59
+ publish_client = get_publish_client(config)
60
+
61
+ _sync_updated_file(file_path, publish_client)
62
+
63
+ print("Watching for file changes...")
64
+ for changes in watch(file_path):
65
+ print("Found changes:")
66
+ print(changes)
67
+ _sync_updated_file(file_path, publish_client)
68
+
69
+ def _sync_updated_file(file_path: str, publish_client: PublishClient) -> None:
70
+ print("Syncing updated document...")
71
+ preview_url = _sync_quarto_file(file_path, publish_client)
72
+ print(f"Content synced successfully. Preview URL: {preview_url}")
73
+
74
+ def _sync_quarto_file(file_path: str, publish_client: PublishClient) -> str:
75
+ pandoc_document = _quarto_to_pandoc(file_path)
76
+ adapters = (
77
+ PandocDocumentProcessor(),
78
+ MimirContentParser(),
79
+ LocalFileStorage(project_folder=Path(file_path).parent),
80
+ publish_client,
81
+ )
82
+ return sync_document(pandoc_document, *adapters)
83
+
84
+
85
+ def _quarto_to_pandoc(file_path: str) -> str:
86
+ result = subprocess.run(
87
+ [
88
+ "quarto",
89
+ "render",
90
+ file_path,
91
+ "--to",
92
+ "json",
93
+ "-M",
94
+ "include:false",
95
+ "--output",
96
+ "-",
97
+ ],
98
+ text=True,
99
+ capture_output=True,
100
+ check=True,
101
+ )
102
+ return result.stdout
ssb_pubmd/config.py CHANGED
@@ -1,27 +1,37 @@
1
+ """App configuration through environment variables."""
2
+
1
3
  import os
2
4
  from dataclasses import dataclass
3
5
  from pathlib import Path
4
6
 
5
- APP_NAME = "SSB_PUBMD"
6
-
7
7
 
8
8
  @dataclass
9
9
  class Config:
10
- metadata_file_path: Path
11
- cms_base_url: str
12
- gc_secret_resource_name: str
10
+ publish_base_url: str
11
+ publish_admin_path: str
12
+ use_dapla_token_client: bool
13
+
14
+
15
+ _TEST_CONFIG = Config(
16
+ publish_base_url="https://i.test.ssb.no",
17
+ publish_admin_path="/xp/admin",
18
+ use_dapla_token_client=True,
19
+ )
20
+
21
+ _LOCAL_CONFIG = Config(
22
+ publish_base_url="http://localhost:8080",
23
+ publish_admin_path="/admin",
24
+ use_dapla_token_client=False,
25
+ )
13
26
 
14
27
 
15
28
  def get_config(metadata_file_path: Path | None = None) -> Config:
16
- user_data_dir = Path.home() / ".local" / "share" / APP_NAME
17
- if not metadata_file_path:
18
- user_data_dir.mkdir(parents=True, exist_ok=True)
19
- metadata_file_path = user_data_dir / "metadata.json"
20
- if not metadata_file_path.exists():
21
- with open(metadata_file_path, "x") as metadata_file:
22
- metadata_file.write("{}\n")
23
- return Config(
24
- metadata_file_path=metadata_file_path,
25
- cms_base_url=os.environ[f"{APP_NAME}_BASE_URL"],
26
- gc_secret_resource_name=os.environ[f"{APP_NAME}_GC_SECRET_RESOURCE_NAME"],
27
- )
29
+ if os.environ.get("SSB_PUBMD_ENVIRONMENT") == "local":
30
+ config = _LOCAL_CONFIG
31
+ else:
32
+ config = _TEST_CONFIG
33
+
34
+ if os.environ.get("SSB_PUBMD_TOKEN_CLIENT") == "local":
35
+ config.use_dapla_token_client = False
36
+
37
+ return config