-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbookstack_client.py
More file actions
947 lines (814 loc) · 28.5 KB
/
Copy pathbookstack_client.py
File metadata and controls
947 lines (814 loc) · 28.5 KB
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
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from typing import Any
from urllib.parse import urljoin
import requests
class BookStackError(RuntimeError):
"""Base error for BookStack API failures."""
class InvalidCredentialsError(BookStackError):
pass
class PermissionDeniedError(BookStackError):
pass
class BookNotFoundError(BookStackError):
pass
class ChapterNotFoundError(BookStackError):
pass
class PageNotFoundError(BookStackError):
pass
class ShelfNotFoundError(BookStackError):
pass
class ServiceUnavailableError(BookStackError):
pass
class InvalidResponseError(BookStackError):
pass
class InvalidQueryError(BookStackError):
pass
def _invalid_credentials() -> InvalidCredentialsError:
return InvalidCredentialsError("Invalid credentials")
def _service_unavailable() -> ServiceUnavailableError:
return ServiceUnavailableError("BookStack API unavailable")
def _invalid_response() -> InvalidResponseError:
return InvalidResponseError("Invalid BookStack response")
def normalize_find_match(value: Any) -> str:
match = str(value or "").strip().lower()
if match not in {"exact", "like"}:
raise ValueError("match must be one of: exact, like")
return match
LIST_SORT_FIELDS: dict[str, frozenset[str]] = {
"books": frozenset({"name", "created_at", "updated_at"}),
"chapters": frozenset({"name", "created_at", "updated_at", "priority"}),
"pages": frozenset({"name", "created_at", "updated_at", "priority"}),
"shelves": frozenset({"name", "created_at", "updated_at"}),
}
LIST_SHARED_FILTER_FIELDS = frozenset({"name", "created_at", "updated_at"})
LIST_RESOURCE_FILTER_FIELDS: dict[str, frozenset[str]] = {
"books": LIST_SHARED_FILTER_FIELDS,
"chapters": LIST_SHARED_FILTER_FIELDS | frozenset({"book_id"}),
"pages": LIST_SHARED_FILTER_FIELDS | frozenset({"book_id", "chapter_id"}),
"shelves": LIST_SHARED_FILTER_FIELDS,
}
LIST_SCOPE_FIELDS: dict[str, tuple[str, ...]] = {
"books": (),
"chapters": ("book_id",),
"pages": ("book_id", "chapter_id"),
"shelves": (),
}
LIST_FILTER_OPERATORS = frozenset({"eq", "like"})
LIST_FIELD_PATTERN = re.compile(r"^[a-z_][a-z0-9_]*$")
@dataclass(slots=True)
class BookStackClient:
base_url: str
token_id: str
token_secret: str
timeout_seconds: float = 10.0
verify_ssl: bool = True
@classmethod
def from_credentials(cls, credentials: dict[str, Any]) -> "BookStackClient":
base_url = cls._require_credential(credentials, "base_url")
token_id = cls._require_credential(credentials, "token_id")
token_secret = cls._require_credential(credentials, "token_secret")
return cls(
base_url=base_url,
token_id=token_id,
token_secret=token_secret,
timeout_seconds=cls._parse_timeout(credentials.get("timeout_seconds")),
verify_ssl=cls._parse_verify_ssl(credentials.get("verify_ssl", True)),
)
@staticmethod
def _require_credential(credentials: dict[str, Any], key: str) -> str:
value = credentials.get(key)
if value is None:
raise _invalid_credentials()
text = str(value).strip()
if not text:
raise _invalid_credentials()
return text
@staticmethod
def _parse_timeout(value: Any) -> float:
if value in {None, ""}:
return 10.0
try:
timeout = float(value)
except (TypeError, ValueError) as exc:
raise _invalid_credentials() from exc
if timeout <= 0:
raise _invalid_credentials()
return timeout
@staticmethod
def _parse_verify_ssl(value: Any) -> bool:
if isinstance(value, bool):
return value
if isinstance(value, str):
normalized = value.strip().lower()
if normalized in {"true", "1"}:
return True
if normalized in {"false", "0"}:
return False
raise _invalid_credentials()
if isinstance(value, (int, float)):
if value == 1:
return True
if value == 0:
return False
raise _invalid_credentials()
raise _invalid_credentials()
def _api_url(self, path: str) -> str:
normalized = self.base_url.rstrip("/") + "/"
return urljoin(normalized, f"api/{path.lstrip('/')}")
def _session(self) -> requests.Session:
session = requests.Session()
session.headers.update({"Authorization": f"Token {self.token_id}:{self.token_secret}"})
return session
def _request(
self,
method: str,
path: str,
*,
not_found_error: type[BookStackError] = BookNotFoundError,
not_found_message: str = "Resource not found",
**kwargs: Any,
) -> dict[str, Any]:
try:
response = self._session().request(
method=method,
url=self._api_url(path),
timeout=self.timeout_seconds,
verify=self.verify_ssl,
**kwargs,
)
except (requests.Timeout, requests.ConnectionError, requests.RequestException) as exc:
raise _service_unavailable() from exc
if response.status_code in {401, 403}:
if response.status_code == 401:
raise _invalid_credentials()
raise PermissionDeniedError("Permission denied")
if response.status_code == 404:
raise not_found_error(not_found_message)
if response.status_code in {400, 422}:
raise _invalid_response()
if response.status_code == 429 or response.status_code >= 500:
raise _service_unavailable()
if response.status_code >= 400:
raise _service_unavailable()
if not response.content:
return {}
try:
payload = response.json()
except ValueError as exc:
raise _invalid_response() from exc
if isinstance(payload, dict):
return payload
raise _invalid_response()
def _request_text(
self,
method: str,
path: str,
*,
not_found_error: type[BookStackError] = BookNotFoundError,
not_found_message: str = "Resource not found",
**kwargs: Any,
) -> str:
try:
response = self._session().request(
method=method,
url=self._api_url(path),
timeout=self.timeout_seconds,
verify=self.verify_ssl,
**kwargs,
)
except (requests.Timeout, requests.ConnectionError, requests.RequestException) as exc:
raise _service_unavailable() from exc
if response.status_code in {401, 403}:
if response.status_code == 401:
raise _invalid_credentials()
raise PermissionDeniedError("Permission denied")
if response.status_code == 404:
raise not_found_error(not_found_message)
if response.status_code in {400, 422}:
raise _invalid_response()
if response.status_code == 429 or response.status_code >= 500:
raise _service_unavailable()
if response.status_code >= 400:
raise _service_unavailable()
if not response.content:
return ""
return response.text
def validate_credentials(self) -> None:
self._request("GET", "system")
@staticmethod
def _require_object_list(value: Any) -> list[dict[str, Any]]:
if not isinstance(value, list):
raise _invalid_response()
items: list[dict[str, Any]] = []
for item in value:
if not isinstance(item, dict):
raise _invalid_response()
items.append(item)
return items
@staticmethod
def _normalize_query_value(value: Any) -> Any | None:
if value is None:
return None
if isinstance(value, str) and not value.strip():
return None
return value
@staticmethod
def _build_list_params(**params: Any) -> dict[str, Any]:
return {
key: normalized_value
for key, value in params.items()
if (normalized_value := BookStackClient._normalize_query_value(value)) is not None
}
@staticmethod
def _build_name_filter_params(name: Any, match: str, **params: Any) -> dict[str, Any]:
match = normalize_find_match(match)
normalized_name = BookStackClient._normalize_query_value(name)
if normalized_name is None:
return BookStackClient._build_list_params(**params)
if match == "exact":
filter_key = "filter[name:eq]"
filter_value = normalized_name
else:
filter_key = "filter[name:like]"
filter_value = f"%{normalized_name}%"
return BookStackClient._build_list_params(**{filter_key: filter_value}, **params)
@staticmethod
def _normalize_list_sort(resource: str, sort: Any | None) -> str | None:
if sort is None:
return None
sort_text = str(sort).strip()
if not sort_text:
return None
direction = ""
field = sort_text
if sort_text[0] in {"+", "-"}:
direction = sort_text[0]
field = sort_text[1:]
if not field or not LIST_FIELD_PATTERN.fullmatch(field):
raise InvalidQueryError("sort must use +field, -field, or field format")
if field not in LIST_SORT_FIELDS[resource]:
raise InvalidQueryError(f"unsupported sort field: {field}")
return f"-{field}" if direction == "-" else field
@staticmethod
def _parse_list_filters(resource: str, filters: Any | None, legacy_scope: dict[str, Any]) -> dict[str, Any]:
if filters is None:
return {}
filters_text = str(filters).strip()
if not filters_text:
return {}
try:
parsed = json.loads(filters_text)
except (TypeError, ValueError) as exc:
raise InvalidQueryError("filters must be a valid JSON object string") from exc
if not isinstance(parsed, dict):
raise InvalidQueryError("filters must be a valid JSON object string")
allowed_fields = LIST_RESOURCE_FILTER_FIELDS[resource]
filter_params: dict[str, Any] = {}
for raw_key, value in parsed.items():
if not isinstance(raw_key, str):
raise InvalidQueryError("filters keys must use field:operator format")
if raw_key.startswith("filter["):
raise InvalidQueryError("raw filter keys are not allowed")
if raw_key.count(":") != 1:
raise InvalidQueryError("filters keys must use field:operator format")
field, operator = raw_key.split(":", 1)
if not field or not operator:
raise InvalidQueryError("filters keys must use field:operator format")
if field not in allowed_fields:
raise InvalidQueryError(f"unsupported filter field: {field}")
if operator not in LIST_FILTER_OPERATORS:
raise InvalidQueryError(f"unsupported filter operator: {operator}")
if value is None:
raise InvalidQueryError("filters values cannot be null")
if isinstance(value, list):
raise InvalidQueryError("filters values cannot be lists")
if isinstance(value, dict):
raise InvalidQueryError("filters values cannot be objects")
if not isinstance(value, (str, int, float, bool)):
raise InvalidQueryError("filters values must be string, number, or boolean")
legacy_value = BookStackClient._normalize_query_value(legacy_scope.get(field))
if legacy_value is not None:
if operator != "eq" or legacy_value != value:
raise InvalidQueryError(f"filters conflict with legacy {field}")
continue
normalized_value = BookStackClient._normalize_query_value(value)
if normalized_value is None:
continue
filter_params[f"filter[{field}:{operator}]"] = normalized_value
return filter_params
@classmethod
def _build_list_query_params(
cls,
resource: str,
*,
sort: Any | None = None,
filters: Any | None = None,
legacy_scope: dict[str, Any] | None = None,
**params: Any,
) -> dict[str, Any]:
legacy_scope = legacy_scope or {}
query_params = cls._build_list_params(**params)
normalized_sort = cls._normalize_list_sort(resource, sort)
if normalized_sort is not None:
query_params["sort"] = normalized_sort
query_params.update(cls._parse_list_filters(resource, filters, legacy_scope))
for field in LIST_SCOPE_FIELDS[resource]:
value = cls._normalize_query_value(legacy_scope.get(field))
if value is not None:
query_params[f"filter[{field}:eq]"] = value
return query_params
def _list_endpoint(
self,
path: str,
*,
not_found_error: type[BookStackError] | None = None,
not_found_message: str | None = None,
**params: Any,
) -> dict[str, Any]:
filtered_params = self._build_list_params(**params)
request_kwargs: dict[str, Any] = {}
if filtered_params:
request_kwargs["params"] = filtered_params
if not_found_error is not None:
request_kwargs["not_found_error"] = not_found_error
if not_found_message is not None:
request_kwargs["not_found_message"] = not_found_message
payload = self._request("GET", path, **request_kwargs)
self._require_object_list(payload.get("data"))
return payload
def _search(self, query: str) -> dict[str, Any]:
payload = self._request("GET", "search", params={"query": query})
self._require_object_list(payload.get("data"))
return payload
def search_content(
self,
query: str,
*,
types: list[str] | None = None,
) -> dict[str, Any]:
payload = self._search(query)
data = payload.get("data", [])
if types is None:
return payload
allowed_types = set(types)
filtered_data: list[dict[str, Any]] = []
for item in data:
item_type = item.get("type")
if item_type in allowed_types:
filtered_data.append(item)
return {
**payload,
"data": filtered_data,
}
def search_pages(self, query: str) -> list[dict[str, Any]]:
payload = self._search(query)
data = payload.get("data", [])
page_results: list[dict[str, Any]] = []
for item in data:
if item.get("type") not in {None, "page"}:
continue
page_results.append(item)
return page_results
def list_books(
self,
count: Any | None = None,
offset: Any | None = None,
sort: Any | None = None,
filters: Any | None = None,
) -> dict[str, Any]:
return self._list_endpoint(
"books",
**self._build_list_query_params("books", count=count, offset=offset, sort=sort, filters=filters),
)
def list_shelves(
self,
count: Any | None = None,
offset: Any | None = None,
sort: Any | None = None,
filters: Any | None = None,
) -> dict[str, Any]:
return self._list_endpoint(
"shelves",
**self._build_list_query_params("shelves", count=count, offset=offset, sort=sort, filters=filters),
)
def find_books(
self,
name: Any,
*,
match: str,
count: Any | None = None,
offset: Any | None = None,
) -> dict[str, Any]:
return self._list_endpoint(
"books",
**self._build_name_filter_params(name, match, count=count, offset=offset),
)
def find_shelves(
self,
name: Any,
*,
match: str,
count: Any | None = None,
offset: Any | None = None,
) -> dict[str, Any]:
return self._list_endpoint(
"shelves",
**self._build_name_filter_params(name, match, count=count, offset=offset),
)
def find_chapters(
self,
name: Any,
*,
match: str,
book_id: Any | None = None,
count: Any | None = None,
offset: Any | None = None,
) -> dict[str, Any]:
return self._list_endpoint(
"chapters",
**self._build_name_filter_params(
name,
match,
**self._build_list_params(
**{"filter[book_id:eq]": book_id},
count=count,
offset=offset,
),
),
)
def find_pages(
self,
name: Any,
*,
match: str,
book_id: Any | None = None,
chapter_id: Any | None = None,
count: Any | None = None,
offset: Any | None = None,
) -> dict[str, Any]:
return self._list_endpoint(
"pages",
**self._build_name_filter_params(
name,
match,
**self._build_list_params(
**{
"filter[book_id:eq]": book_id,
"filter[chapter_id:eq]": chapter_id,
},
count=count,
offset=offset,
),
),
)
def list_pages(
self,
book_id: Any | None = None,
chapter_id: Any | None = None,
count: Any | None = None,
offset: Any | None = None,
sort: Any | None = None,
filters: Any | None = None,
) -> dict[str, Any]:
return self._list_endpoint(
"pages",
**self._build_list_query_params(
"pages",
count=count,
offset=offset,
sort=sort,
filters=filters,
legacy_scope={"book_id": book_id, "chapter_id": chapter_id},
),
)
def list_chapters(
self,
book_id: Any | None = None,
count: Any | None = None,
offset: Any | None = None,
sort: Any | None = None,
filters: Any | None = None,
) -> dict[str, Any]:
return self._list_endpoint(
"chapters",
not_found_error=BookNotFoundError,
not_found_message="Book not found",
**self._build_list_query_params(
"chapters",
count=count,
offset=offset,
sort=sort,
filters=filters,
legacy_scope={"book_id": book_id},
),
)
def get_page(self, page_id: Any) -> dict[str, Any]:
return self._request(
"GET",
f"pages/{page_id}",
not_found_error=PageNotFoundError,
not_found_message="Page not found",
)
def get_book(self, book_id: Any) -> dict[str, Any]:
return self._request(
"GET",
f"books/{book_id}",
not_found_error=BookNotFoundError,
not_found_message="Book not found",
)
def get_chapter(self, chapter_id: Any) -> dict[str, Any]:
return self._request(
"GET",
f"chapters/{chapter_id}",
not_found_error=ChapterNotFoundError,
not_found_message="Chapter not found",
)
def export_book_markdown(self, book_id: Any) -> str:
return self._request_text(
"GET",
f"books/{book_id}/export/markdown",
not_found_error=BookNotFoundError,
not_found_message="Book not found",
)
def export_chapter_markdown(self, chapter_id: Any) -> str:
return self._request_text(
"GET",
f"chapters/{chapter_id}/export/markdown",
not_found_error=ChapterNotFoundError,
not_found_message="Chapter not found",
)
def get_shelf(self, shelf_id: Any) -> dict[str, Any]:
return self._request(
"GET",
f"shelves/{shelf_id}",
not_found_error=ShelfNotFoundError,
not_found_message="Shelf not found",
)
@staticmethod
def _build_page_payload(
*,
title: Any | None = None,
markdown: Any | None = None,
tags: Any | None = None,
book_id: Any | None = None,
chapter_id: Any | None = None,
) -> dict[str, Any]:
payload: dict[str, Any] = {}
if title is not None:
payload["name"] = title
if markdown is not None:
payload["markdown"] = markdown
if tags is not None:
payload["tags"] = tags
if book_id is not None:
payload["book_id"] = book_id
if chapter_id is not None:
payload["chapter_id"] = chapter_id
return payload
@staticmethod
def _build_resource_payload(**fields: Any) -> dict[str, Any]:
return {key: value for key, value in fields.items() if value is not None}
@staticmethod
def _build_book_payload(
*,
name: Any | None = None,
description: Any | None = None,
description_html: Any | None = None,
tags: Any | None = None,
) -> dict[str, Any]:
return BookStackClient._build_resource_payload(
name=name,
description=description,
description_html=description_html,
tags=tags,
)
@staticmethod
def _build_chapter_payload(
*,
book_id: Any | None = None,
name: Any | None = None,
description: Any | None = None,
description_html: Any | None = None,
tags: Any | None = None,
priority: Any | None = None,
) -> dict[str, Any]:
return BookStackClient._build_resource_payload(
book_id=book_id,
name=name,
description=description,
description_html=description_html,
tags=tags,
priority=priority,
)
@staticmethod
def _build_shelf_payload(
*,
name: Any | None = None,
description: Any | None = None,
description_html: Any | None = None,
books: Any | None = None,
tags: Any | None = None,
) -> dict[str, Any]:
return BookStackClient._build_resource_payload(
name=name,
description=description,
description_html=description_html,
books=books,
tags=tags,
)
def create_page(
self,
*,
title: Any,
markdown: Any,
tags: Any | None = None,
book_id: Any | None = None,
chapter_id: Any | None = None,
) -> dict[str, Any]:
not_found_error: type[BookStackError]
not_found_message: str
if chapter_id is not None:
not_found_error = ChapterNotFoundError
not_found_message = "Chapter not found"
else:
not_found_error = BookNotFoundError
not_found_message = "Book not found"
return self._request(
"POST",
"pages",
json=self._build_page_payload(
title=title,
markdown=markdown,
tags=tags,
book_id=book_id,
chapter_id=chapter_id,
),
not_found_error=not_found_error,
not_found_message=not_found_message,
)
def update_page(
self,
page_id: Any,
*,
title: Any | None = None,
markdown: Any | None = None,
tags: Any | None = None,
book_id: Any | None = None,
chapter_id: Any | None = None,
) -> dict[str, Any]:
return self._request(
"PUT",
f"pages/{page_id}",
json=self._build_page_payload(
title=title,
markdown=markdown,
tags=tags,
book_id=book_id,
chapter_id=chapter_id,
),
not_found_error=PageNotFoundError,
not_found_message="Page not found",
)
def create_book(
self,
*,
name: Any,
description: Any | None = None,
description_html: Any | None = None,
tags: Any | None = None,
) -> dict[str, Any]:
return self._request(
"POST",
"books",
json=self._build_book_payload(
name=name,
description=description,
description_html=description_html,
tags=tags,
),
)
def update_book(
self,
book_id: Any,
*,
name: Any | None = None,
description: Any | None = None,
description_html: Any | None = None,
tags: Any | None = None,
) -> dict[str, Any]:
return self._request(
"PUT",
f"books/{book_id}",
json=self._build_book_payload(
name=name,
description=description,
description_html=description_html,
tags=tags,
),
not_found_error=BookNotFoundError,
not_found_message="Book not found",
)
def create_chapter(
self,
*,
book_id: Any,
name: Any,
description: Any | None = None,
description_html: Any | None = None,
tags: Any | None = None,
priority: Any | None = None,
) -> dict[str, Any]:
return self._request(
"POST",
"chapters",
json=self._build_chapter_payload(
book_id=book_id,
name=name,
description=description,
description_html=description_html,
tags=tags,
priority=priority,
),
not_found_error=BookNotFoundError,
not_found_message="Book not found",
)
def update_chapter(
self,
chapter_id: Any,
*,
book_id: Any | None = None,
name: Any | None = None,
description: Any | None = None,
description_html: Any | None = None,
tags: Any | None = None,
priority: Any | None = None,
) -> dict[str, Any]:
return self._request(
"PUT",
f"chapters/{chapter_id}",
json=self._build_chapter_payload(
book_id=book_id,
name=name,
description=description,
description_html=description_html,
tags=tags,
priority=priority,
),
not_found_error=ChapterNotFoundError,
not_found_message="Chapter not found",
)
def create_shelf(
self,
*,
name: Any,
description: Any | None = None,
description_html: Any | None = None,
books: Any | None = None,
tags: Any | None = None,
) -> dict[str, Any]:
return self._request(
"POST",
"shelves",
json=self._build_shelf_payload(
name=name,
description=description,
description_html=description_html,
books=books,
tags=tags,
),
)
def update_shelf(
self,
shelf_id: Any,
*,
name: Any | None = None,
description: Any | None = None,
description_html: Any | None = None,
books: Any | None = None,
tags: Any | None = None,
) -> dict[str, Any]:
return self._request(
"PUT",
f"shelves/{shelf_id}",
json=self._build_shelf_payload(
name=name,
description=description,
description_html=description_html,
books=books,
tags=tags,
),
not_found_error=ShelfNotFoundError,
not_found_message="Shelf not found",
)
def list_tag_names(self, count: Any | None = None, offset: Any | None = None) -> dict[str, Any]:
return self._list_endpoint("tags/names", count=count, offset=offset)
def list_tag_values(
self,
name: Any,
*,
count: Any | None = None,
offset: Any | None = None,
) -> dict[str, Any]:
return self._list_endpoint("tags/values-for-name", name=name, count=count, offset=offset)