atlassian-python-api 5.0.0__py3-none-any.whl → 5.0.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.
Files changed (44) hide show
  1. atlassian/VERSION +1 -1
  2. atlassian/__init__.py +13 -2
  3. atlassian/assets.py +10 -3
  4. atlassian/bamboo.py +197 -4
  5. atlassian/bitbucket/__init__.py +87 -1
  6. atlassian/bitbucket/base.py +11 -14
  7. atlassian/bitbucket/cloud/repositories/__init__.py +33 -0
  8. atlassian/bitbucket/cloud/workspaces/__init__.py +15 -7
  9. atlassian/bitbucket/server/__init__.py +11 -0
  10. atlassian/cloud_admin.py +418 -0
  11. atlassian/confluence/__init__.py +13 -1
  12. atlassian/confluence/base.py +80 -14
  13. atlassian/confluence/cloud/__init__.py +233 -11
  14. atlassian/confluence/cloud/classification_levels.py +77 -0
  15. atlassian/confluence/cloud/cloud.py +79 -186
  16. atlassian/confluence/cloud/content_properties.py +71 -0
  17. atlassian/confluence/cloud/databases.py +59 -0
  18. atlassian/confluence/cloud/folders.py +48 -0
  19. atlassian/confluence/cloud/graphql.py +99 -0
  20. atlassian/confluence/cloud/tasks.py +86 -0
  21. atlassian/confluence/cloud/whiteboards.py +95 -0
  22. atlassian/confluence/server/__init__.py +603 -194
  23. atlassian/confluence_base.py +28 -3
  24. atlassian/crowd.py +78 -0
  25. atlassian/jira/__init__.py +21 -0
  26. atlassian/jira/core_methods.py +11698 -0
  27. atlassian/jira/jira_cloud.py +160 -0
  28. atlassian/{jira.py → jira/jira_server.py} +336 -8
  29. atlassian/jira/service_management_methods.py +1381 -0
  30. atlassian/jira/software_methods.py +2114 -0
  31. atlassian/rest_client.py +67 -8
  32. atlassian/service_desk.py +10 -3
  33. atlassian/yogi/__init__.py +17 -0
  34. atlassian/yogi/base.py +11 -0
  35. atlassian/yogi/cloud.py +2367 -0
  36. atlassian/yogi/yogi_confluence_cloud.py +10 -0
  37. atlassian/yogi/yogi_confluence_dc.py +94 -0
  38. atlassian/yogi/yogi_jira_cloud.py +10 -0
  39. atlassian/yogi/yogi_jira_dc.py +64 -0
  40. {atlassian_python_api-5.0.0.dist-info → atlassian_python_api-5.0.2.dist-info}/METADATA +80 -10
  41. {atlassian_python_api-5.0.0.dist-info → atlassian_python_api-5.0.2.dist-info}/RECORD +44 -25
  42. {atlassian_python_api-5.0.0.dist-info → atlassian_python_api-5.0.2.dist-info}/WHEEL +0 -0
  43. {atlassian_python_api-5.0.0.dist-info → atlassian_python_api-5.0.2.dist-info}/licenses/LICENSE +0 -0
  44. {atlassian_python_api-5.0.0.dist-info → atlassian_python_api-5.0.2.dist-info}/top_level.txt +0 -0
@@ -8,6 +8,7 @@ import sys
8
8
  import time
9
9
  import warnings
10
10
  from typing import cast
11
+ from urllib.parse import urljoin
11
12
 
12
13
  import requests
13
14
  from bs4 import BeautifulSoup
@@ -140,7 +141,12 @@ class Server(ConfluenceServerBase):
140
141
 
141
142
  def page_exists(self, space_key, title, **kwargs):
142
143
  """Check if page exists."""
143
- result = self.get_page_by_title(space_key, title, **kwargs)
144
+ try:
145
+ result = self.get_page_by_title(space_key, title, **kwargs)
146
+ except HTTPError as error:
147
+ if error.response is not None and error.response.status_code == 404:
148
+ return False
149
+ raise
144
150
  return len(result.get("results", [])) > 0
145
151
 
146
152
  def blog_post_exists(self, space_key, title, **kwargs):
@@ -207,6 +213,24 @@ class Server(ConfluenceServerBase):
207
213
 
208
214
  raise
209
215
 
216
+ def get_page_child_count(self, page_id, type="page"):
217
+ """Return the number of direct children of ``type`` without listing them.
218
+
219
+ Confluence returns the collection size when the corresponding child
220
+ collection is expanded, so this requires one content request rather
221
+ than paginating all children.
222
+ """
223
+ page = self.get_page_by_id(page_id, expand=f"children.{type}")
224
+ collection = page.get("children", {}).get(type, {})
225
+ size = collection.get("size")
226
+ if size is not None:
227
+ return int(size)
228
+ return len(collection.get("results", []))
229
+
230
+ def page_has_children(self, page_id, type="page"):
231
+ """Return whether a page has at least one direct child of ``type``."""
232
+ return self.get_page_child_count(page_id, type=type) > 0
233
+
210
234
  def get_child_title_list(self, page_id, type="page", start=None, limit=None):
211
235
  """
212
236
  Find a list of Child title
@@ -320,7 +344,7 @@ class Server(ConfluenceServerBase):
320
344
  params["status"] = status
321
345
  if version:
322
346
  params["version"] = version
323
- url = f"rest/api/content/{page_id}"
347
+ url = f"content/{page_id}"
324
348
 
325
349
  try:
326
350
  response = self.get(url, params=params)
@@ -338,45 +362,34 @@ class Server(ConfluenceServerBase):
338
362
  return response
339
363
 
340
364
  def get_tables_from_page(self, page_id):
341
- """
342
- Fetches html tables added to confluence page
343
- :param page_id: integer confluence page_id
344
- :return: json object with page_id, number_of_tables_in_page
345
- and list of list tables_content representing scraped tables
365
+ """Return a consistent table summary for a page.
366
+
367
+ The returned dictionary always contains ``page_id``,
368
+ ``number_of_tables_in_page``, and ``tables_content``. Empty pages and
369
+ pages without tables return a count of zero and an empty list.
346
370
  """
347
371
  try:
348
372
  page_content = self.get_page_by_id(page_id, expand="body.storage")["body"]["storage"]["value"]
349
-
350
- if page_content:
351
- tables_raw = [
352
- [[cell.text for cell in row("th") + row("td")] for row in table("tr")]
353
- for table in BeautifulSoup(page_content, features="lxml")("table")
354
- ]
355
- if len(tables_raw) > 0:
356
- return json.dumps(
357
- {
358
- "page_id": page_id,
359
- "number_of_tables_in_page": len(tables_raw),
360
- "tables_content": tables_raw,
361
- }
362
- )
363
- else:
364
- return {
365
- "No tables found for page: ": page_id,
366
- }
367
- else:
368
- return {"Page content is empty"}
369
373
  except HTTPError as e:
370
374
  if e.response.status_code == 404:
371
- # Raise ApiError as the documented reason is ambiguous
372
- log.error("Couldn't retrieve tables from page", page_id)
373
375
  raise ApiError(
374
376
  "There is no content with the given pageid, pageid params is not an integer "
375
377
  "or the calling user does not have permission to view the page",
376
378
  reason=e,
377
379
  )
378
- except Exception as e:
379
- log.error("Error occured", e)
380
+ raise
381
+
382
+ tables_raw = []
383
+ if page_content:
384
+ tables_raw = [
385
+ [[cell.text for cell in row("th") + row("td")] for row in table("tr")]
386
+ for table in BeautifulSoup(page_content, features="html.parser")("table")
387
+ ]
388
+ return {
389
+ "page_id": page_id,
390
+ "number_of_tables_in_page": len(tables_raw),
391
+ "tables_content": tables_raw,
392
+ }
380
393
 
381
394
  def scrap_regex_from_page(self, page_id, regex):
382
395
  """
@@ -450,16 +463,23 @@ class Server(ConfluenceServerBase):
450
463
  location=None,
451
464
  depth=None,
452
465
  ):
453
- """
454
-
455
- :param content_id:
456
- :param expand: extensions.inlineProperties,extensions.resolution
457
- :param parent_version:
458
- :param start:
459
- :param limit:
460
- :param location: inline or not
461
- :param depth:
462
- :return:
466
+ """Return a page's comments through the separate comments endpoint.
467
+
468
+ Comments are not included in :meth:`get_page_by_id`. To retrieve a
469
+ rendered comment body and author metadata, use
470
+ ``expand='body.view,history,version'``. The initial author is available
471
+ in ``history.createdBy`` and the latest editor in ``version.by``.
472
+
473
+ :param content_id: Page/content ID
474
+ :param expand: Content expansions, for example
475
+ ``body.view,history,version``. Inline-comment metadata can use
476
+ ``extensions.inlineProperties,extensions.resolution``.
477
+ :param parent_version: Filter comments for a parent version
478
+ :param start: Page offset
479
+ :param limit: Number of comments per response page
480
+ :param location: ``inline`` to request inline comments
481
+ :param depth: Nested comment depth
482
+ :return: Paginated Confluence comment response
463
483
  """
464
484
  params = {"id": content_id, "start": start, "limit": limit}
465
485
  if expand:
@@ -610,6 +630,28 @@ class Server(ConfluenceServerBase):
610
630
  url = f"rest/api/content/{content_id}/restriction/byOperation"
611
631
  return self.get(url)
612
632
 
633
+ def set_restrictions_for_content(self, content_id, restrictions):
634
+ """Set page or blog-post restrictions using the REST API.
635
+
636
+ ``restrictions`` is a list of ContentRestriction objects. Each
637
+ supplied operation replaces its existing restrictions; operations not
638
+ present in the list are unchanged. Supplying an empty ``user`` or
639
+ ``group`` list clears that subject type for the operation.
640
+
641
+ Example::
642
+
643
+ [{
644
+ "operation": "read",
645
+ "restrictions": {
646
+ "user": [{"type": "known", "username": "alice"}],
647
+ "group": [{"type": "group", "name": "engineering"}],
648
+ },
649
+ }]
650
+ """
651
+ if not isinstance(restrictions, list):
652
+ raise ApiValueError("restrictions must be a list of ContentRestriction objects")
653
+ return self.put(f"rest/api/content/{content_id}/restriction", data=restrictions)
654
+
613
655
  def get_all_restrictions_from_page_json_rpc(self, page_id):
614
656
  """
615
657
  The JSON-RPC APIs for Confluence are provided here to help you browse and discover APIs you have access to.
@@ -818,6 +860,11 @@ class Server(ConfluenceServerBase):
818
860
  try:
819
861
  response = self.delete(f"rest/api/content/{content_id}")
820
862
  except HTTPError as e:
863
+ if e.response.status_code == 403:
864
+ raise ApiPermissionError(
865
+ "The calling user does not have permission to trash or purge the content",
866
+ reason=e,
867
+ )
821
868
  if e.response.status_code == 404:
822
869
  # Raise ApiError as the documented reason is ambiguous
823
870
  raise ApiError(
@@ -837,15 +884,21 @@ class Server(ConfluenceServerBase):
837
884
 
838
885
  def remove_page(self, page_id, status=None, recursive=False):
839
886
  """
840
- This method removes a page, if it has recursive flag, method removes including child pages
841
- :param page_id:
842
- :param status: OPTIONAL: type of page
843
- :param recursive: OPTIONAL: if True - will recursively delete all children pages too
844
- :return:
887
+ Remove a page and optionally its child pages.
888
+
889
+ :param page_id: page ID
890
+ :param status: optional content status (for example ``"trashed"``)
891
+ :param recursive: if True, remove child pages before this page
892
+ :return: the successful HTTP status code (normally ``204``). When the
893
+ client has ``advanced_mode=True``, return the raw response instead.
845
894
  """
846
895
  url = f"rest/api/content/{page_id}"
847
896
  if recursive:
848
- children_pages = self.get_page_child_by_type(page_id)
897
+ # Fetch every child before deleting any of them. Confluence uses
898
+ # offset pagination for this resource; deleting a child while
899
+ # consuming the generator changes the collection and can make a
900
+ # subsequent offset skip pages shifted earlier in the collection.
901
+ children_pages = list(self.get_page_child_by_type(page_id))
849
902
  for children_page in children_pages:
850
903
  self.remove_page(children_page.get("id"), status, recursive)
851
904
  params = {}
@@ -853,8 +906,13 @@ class Server(ConfluenceServerBase):
853
906
  params["status"] = status
854
907
 
855
908
  try:
856
- response = self.delete(url, params=params)
909
+ response = self.delete(url, params=params, advanced_mode=True)
857
910
  except HTTPError as e:
911
+ if e.response.status_code == 403:
912
+ raise ApiPermissionError(
913
+ "The calling user does not have permission to trash or purge the content",
914
+ reason=e,
915
+ )
858
916
  if e.response.status_code == 404:
859
917
  # Raise ApiError as the documented reason is ambiguous
860
918
  raise ApiError(
@@ -870,7 +928,9 @@ class Server(ConfluenceServerBase):
870
928
 
871
929
  raise
872
930
 
873
- return response
931
+ if self.advanced_mode:
932
+ return response
933
+ return response.status_code
874
934
 
875
935
  def create_page(
876
936
  self,
@@ -883,18 +943,21 @@ class Server(ConfluenceServerBase):
883
943
  editor=None,
884
944
  full_width=False,
885
945
  status="current",
946
+ version_comment=None,
886
947
  ):
887
948
  """
888
949
  Create page from scratch
889
- :param space:
890
- :param title:
891
- :param body:
892
- :param parent_id:
893
- :param type:
950
+ :param space: **space key**, not the display name. Personal-space keys
951
+ commonly look like ``~<account-id>``.
952
+ :param title: page title
953
+ :param body: page body in the selected representation
954
+ :param parent_id: optional parent page ID
955
+ :param type: content type; normally ``"page"``
894
956
  :param representation: OPTIONAL: either Confluence 'storage' or 'wiki' markup format
895
957
  :param editor: OPTIONAL: v2 to be created in the new editor
896
958
  :param full_width: DEFAULT: False
897
959
  :param status: either 'current' or 'draft'
960
+ :param version_comment: optional message recorded with the first page version
898
961
  :return:
899
962
  """
900
963
  log.info('Creating %s "%s" -> "%s"', type, space, title)
@@ -909,6 +972,8 @@ class Server(ConfluenceServerBase):
909
972
  }
910
973
  if parent_id:
911
974
  data["ancestors"] = [{"type": type, "id": parent_id}]
975
+ if version_comment is not None:
976
+ data["version"] = {"message": version_comment}
912
977
  if editor is not None and editor in ["v1", "v2"]:
913
978
  data["metadata"]["properties"]["editor"] = {"value": editor}
914
979
  if full_width is True:
@@ -921,6 +986,13 @@ class Server(ConfluenceServerBase):
921
986
  try:
922
987
  response = self.post(url, data=data)
923
988
  except HTTPError as e:
989
+ if e.response.status_code == 403:
990
+ raise ApiPermissionError(
991
+ f"Cannot create a page in space '{space}'. Use the space key "
992
+ "(not its display name), then verify the API user has "
993
+ "permission to create pages in that space.",
994
+ reason=e,
995
+ )
924
996
  if e.response.status_code == 404:
925
997
  raise ApiPermissionError(
926
998
  "The calling user does not have permission to view the content",
@@ -985,7 +1057,16 @@ class Server(ConfluenceServerBase):
985
1057
  :type content_type: ``str``
986
1058
  :param comment: A comment describing this upload/file
987
1059
  :type comment: ``str``
988
- """
1060
+ :return: The attachment response.
1061
+ :raises ApiNotFoundError: If no page ID is supplied and the title cannot
1062
+ be resolved in the requested space.
1063
+ """
1064
+ # Confluence attachment names are filenames, not paths. Normalize both
1065
+ # POSIX and Windows separators before Confluence can silently collapse
1066
+ # them into an existing basename.
1067
+ name = str(name).replace("\\", "/").rsplit("/", 1)[-1]
1068
+ if not name:
1069
+ raise ApiValueError("Attachment name must contain a filename")
989
1070
  page_id = self.get_page_id(space=space, title=title) if page_id is None else page_id
990
1071
  type = "attachment"
991
1072
  if page_id is not None:
@@ -1002,13 +1083,13 @@ class Server(ConfluenceServerBase):
1002
1083
  "Accept": "application/json",
1003
1084
  }
1004
1085
  path = f"rest/api/content/{page_id}/child/attachment"
1005
- # Check if there is already a file with the same name
1006
- attachments = self.get(path=path, headers=headers, params={"filename": name})
1007
- if attachments.get("size"):
1008
- path = path + "/" + attachments["results"][0]["id"] + "/data"
1009
1086
 
1010
1087
  try:
1011
- response = self.post(
1088
+ # Confluence's multipart PUT endpoint atomically creates an
1089
+ # attachment or adds a revision when the filename already
1090
+ # exists. A GET followed by POST is racy and Cloud may reject
1091
+ # the attachment-data endpoint for a same-name upload.
1092
+ response = self.put(
1012
1093
  path=path,
1013
1094
  data=data,
1014
1095
  headers=headers,
@@ -1035,8 +1116,7 @@ class Server(ConfluenceServerBase):
1035
1116
 
1036
1117
  return response
1037
1118
  else:
1038
- log.warning("No 'page_id' found, not uploading attachments")
1039
- return None
1119
+ raise ApiNotFoundError("No page ID was supplied and the target page could not be found")
1040
1120
 
1041
1121
  def attach_file(
1042
1122
  self,
@@ -1086,7 +1166,9 @@ class Server(ConfluenceServerBase):
1086
1166
  comment=comment,
1087
1167
  )
1088
1168
 
1089
- def download_attachments_from_page(self, page_id, path=None, start=0, limit=50, filename=None, to_memory=False):
1169
+ def download_attachments_from_page(
1170
+ self, page_id, path=None, start=0, limit=50, filename=None, to_memory=False, download_path=None
1171
+ ):
1090
1172
  """
1091
1173
  Downloads attachments from a Confluence page. Supports downloading all files or a specific file.
1092
1174
  Files can either be saved to disk or returned as BytesIO objects for in-memory handling.
@@ -1096,6 +1178,9 @@ class Server(ConfluenceServerBase):
1096
1178
  :param path: str, optional
1097
1179
  Directory where attachments will be saved. If None, defaults to the current working directory.
1098
1180
  Ignored if `to_memory` is True.
1181
+ :param download_path: str, optional
1182
+ Deprecated alias for ``path`` retained for callers of older
1183
+ documentation. Do not pass both names with different values.
1099
1184
  :param start: int, optional
1100
1185
  The start point for paginated attachment fetching. Default is 0. Ignored if `filename` is specified.
1101
1186
  :param limit: int, optional
@@ -1114,6 +1199,11 @@ class Server(ConfluenceServerBase):
1114
1199
  - requests.HTTPError: If the HTTP request to fetch an attachment fails.
1115
1200
  - Exception: For any unexpected errors.
1116
1201
  """
1202
+ if download_path is not None:
1203
+ if path is not None and path != download_path:
1204
+ raise ApiValueError("Specify only one of path or download_path")
1205
+ path = download_path
1206
+
1117
1207
  # Default path to current working directory if not provided
1118
1208
  if not to_memory and path is None:
1119
1209
  path = os.getcwd()
@@ -1124,18 +1214,39 @@ class Server(ConfluenceServerBase):
1124
1214
  # Fetch specific file by filename
1125
1215
  attachments = self.get_attachments_from_content(page_id=page_id, filename=filename)["results"]
1126
1216
  if not attachments:
1127
- return f"No attachment with filename '{filename}' found on the page."
1217
+ return {} if to_memory else {"attachments_downloaded": 0, "path": path}
1128
1218
  else:
1129
- # Fetch all attachments with pagination
1130
- attachments = self.get_attachments_from_content(page_id=page_id, start=start, limit=limit)["results"]
1219
+ # Fetch all attachment pages. Confluence defaults to 50 results,
1220
+ # so a single request silently omits attachments on larger pages.
1221
+ attachments = []
1222
+ current_start = start
1223
+ while True:
1224
+ attachment_page = self.get_attachments_from_content(
1225
+ page_id=page_id, start=current_start, limit=limit
1226
+ )
1227
+ page_results = attachment_page.get("results", [])
1228
+ attachments.extend(page_results)
1229
+
1230
+ total_size = attachment_page.get("totalSize")
1231
+ if not page_results or (total_size is not None and current_start + len(page_results) >= total_size):
1232
+ break
1233
+ if total_size is None and len(page_results) < limit:
1234
+ break
1235
+ current_start += len(page_results)
1131
1236
  if not attachments:
1132
- return "No attachments found on the page."
1237
+ return {} if to_memory else {"attachments_downloaded": 0, "path": path}
1133
1238
 
1134
1239
  # Prepare to handle downloads
1135
1240
  downloaded_files = {}
1136
1241
  for attachment in attachments:
1137
1242
  file_name = attachment["title"] or attachment["id"] # Use attachment ID if title is unavailable
1138
- download_link = attachment["_links"]["download"]
1243
+ if self.cloud:
1244
+ # ``_links.download`` points to the deprecated Cloud
1245
+ # attachment download route. Use the supported REST
1246
+ # content-attachment endpoint instead.
1247
+ download_link = f"rest/api/content/{page_id}/child/attachment/{attachment['id']}/download"
1248
+ else:
1249
+ download_link = attachment["_links"]["download"]
1139
1250
  # Fetch the file content
1140
1251
  response = self.get(str(download_link), not_json_response=True)
1141
1252
 
@@ -1153,8 +1264,6 @@ class Server(ConfluenceServerBase):
1153
1264
  )
1154
1265
  file_name = sanitized
1155
1266
  file_path = os.path.join(path, file_name)
1156
- # Save file to disk
1157
- file_path = os.path.join(path, file_name)
1158
1267
  with open(file_path, "wb") as file:
1159
1268
  file.write(response)
1160
1269
 
@@ -1334,7 +1443,7 @@ class Server(ConfluenceServerBase):
1334
1443
  return response
1335
1444
 
1336
1445
  def history(self, page_id):
1337
- url = f"rest/api/content/{page_id}/history"
1446
+ url = f"content/{page_id}/history"
1338
1447
  try:
1339
1448
  response = self.get(url)
1340
1449
  except HTTPError as e:
@@ -1353,18 +1462,50 @@ class Server(ConfluenceServerBase):
1353
1462
  def get_content_history(self, content_id):
1354
1463
  return self.history(content_id)
1355
1464
 
1356
- def get_content_history_by_version_number(self, content_id, version_number):
1465
+ def iter_page_versions(self, page_id, limit=200, expand=None):
1466
+ """Yield every version of a Server/Data Center page.
1467
+
1468
+ The dedicated ``content/{id}/version`` endpoint is paginated. This
1469
+ method follows its links lazily, avoiding one request per version.
1470
+ """
1471
+ params = {"limit": int(limit)}
1472
+ if expand is not None:
1473
+ params["expand"] = expand
1474
+ return self._get_paged(f"content/{page_id}/version", params=params)
1475
+
1476
+ def get_all_page_versions(self, page_id, limit=200, expand=None):
1477
+ """Return every version of a Server/Data Center page as a list."""
1478
+ return list(self.iter_page_versions(page_id, limit=limit, expand=expand))
1479
+
1480
+ def get_content_history_by_version_number(self, content_id, version_number, expand=None):
1357
1481
  """
1358
1482
  Get content history by version number
1359
1483
  :param content_id:
1360
1484
  :param version_number:
1361
1485
  :return:
1362
1486
  """
1363
- if self.cloud:
1364
- url = f"rest/api/content/{content_id}/version/{version_number}"
1365
- else:
1366
- url = f"rest/experimental/content/{content_id}/version/{version_number}"
1367
- return self.get(url)
1487
+ # The experimental endpoint was retired by recent Server/Data Center
1488
+ # releases. Cloud and Server/Data Center now expose this operation at
1489
+ # the same REST API path.
1490
+ params = {"expand": expand} if expand is not None else {}
1491
+ return self.get(f"content/{content_id}/version/{version_number}", params=params)
1492
+
1493
+ def get_page_version_contributors(self, page_id, version_number):
1494
+ """Return every known contributor to a page revision.
1495
+
1496
+ Collaborative-editing revisions expose a ``collaborators`` collection.
1497
+ Older Confluence releases expose only ``by``; in that case the saving
1498
+ author is returned as a one-item list.
1499
+ """
1500
+ version = self.get_content_history_by_version_number(page_id, version_number, expand="collaborators")
1501
+ collaborators = version.get("collaborators") or version.get("version", {}).get("collaborators")
1502
+ if isinstance(collaborators, dict):
1503
+ collaborators = collaborators.get("users") or collaborators.get("results") or []
1504
+ if isinstance(collaborators, list):
1505
+ return collaborators
1506
+
1507
+ author = version.get("by") or version.get("version", {}).get("by")
1508
+ return [author] if author else []
1368
1509
 
1369
1510
  def remove_content_history(self, page_id, version_number):
1370
1511
  """
@@ -1373,11 +1514,7 @@ class Server(ConfluenceServerBase):
1373
1514
  :param version_number: version number
1374
1515
  :return:
1375
1516
  """
1376
- if self.cloud:
1377
- url = f"rest/api/content/{page_id}/version/{version_number}"
1378
- else:
1379
- url = f"rest/experimental/content/{page_id}/version/{version_number}"
1380
- self.delete(url)
1517
+ return self.delete(f"content/{page_id}/version/{version_number}")
1381
1518
 
1382
1519
  def remove_page_history(self, page_id, version_number):
1383
1520
  """
@@ -1395,23 +1532,41 @@ class Server(ConfluenceServerBase):
1395
1532
  :param version_id:
1396
1533
  :return:
1397
1534
  """
1398
- url = f"rest/api/content/{page_id}/version/{version_id}"
1399
- self.delete(url)
1535
+ return self.remove_content_history(page_id, version_id)
1400
1536
 
1401
1537
  def remove_page_history_keep_version(self, page_id, keep_last_versions):
1402
1538
  """
1403
- Keep last versions
1404
- :param page_id:
1405
- :param keep_last_versions:
1406
- :return:
1539
+ Remove the oldest page versions while retaining the requested number of
1540
+ newest versions.
1541
+
1542
+ Confluence version numbers are immutable: deleting version 1 does not
1543
+ cause version 2 to become version 1. Delete each obsolete version
1544
+ number exactly once rather than repeatedly deleting version 1.
1545
+
1546
+ :param page_id: Page whose history should be pruned.
1547
+ :param keep_last_versions: Number of latest versions to retain. Must be
1548
+ a positive integer.
1407
1549
  """
1550
+ if not isinstance(keep_last_versions, int) or isinstance(keep_last_versions, bool) or keep_last_versions < 1:
1551
+ raise ValueError("keep_last_versions must be a positive integer")
1552
+
1408
1553
  page = self.get_page_by_id(page_id=page_id, expand="version")
1409
- page_number = page.get("version").get("number")
1410
- while page_number > keep_last_versions:
1411
- self.remove_page_history(page_id=page_id, version_number=1)
1412
- page = self.get_page_by_id(page_id=page_id, expand="version")
1413
- page_number = page.get("version").get("number")
1414
- log.info("Removed oldest version for %s, now it's %s", page.get("title"), page_number)
1554
+ page_number = page.get("version", {}).get("number")
1555
+ if not isinstance(page_number, int):
1556
+ raise ValueError("Page response does not contain a valid version number")
1557
+
1558
+ for version_number in range(1, max(page_number - keep_last_versions, 0) + 1):
1559
+ try:
1560
+ self.remove_page_history(page_id=page_id, version_number=version_number)
1561
+ except HTTPError as error:
1562
+ # Version numbers are immutable and may contain gaps when a
1563
+ # previous run already deleted an older version. That is a
1564
+ # successful pruning outcome, not a fatal error.
1565
+ if error.response is None or error.response.status_code != 404:
1566
+ raise
1567
+ log.debug("Version %s for %s is already absent", version_number, page_id)
1568
+ continue
1569
+ log.info("Removed version %s for %s", version_number, page.get("title"))
1415
1570
  log.info("Kept versions %s for %s", keep_last_versions, page.get("title"))
1416
1571
 
1417
1572
  def has_unknown_attachment_error(self, page_id):
@@ -1480,7 +1635,13 @@ class Server(ConfluenceServerBase):
1480
1635
  version_comment=None,
1481
1636
  full_width=False,
1482
1637
  ):
1483
- """Duplicate update_page. Left for the people who used it before. Use update_page instead"""
1638
+ """Backward-compatible alias for :meth:`update_page`.
1639
+
1640
+ ``body`` is sent unchanged. In particular, callers updating a table
1641
+ that contains Confluence image macros must retain the original storage
1642
+ markup. ``pandas.read_html`` cannot preserve those macros and its
1643
+ subsequent ``to_html`` output may replace image cells with ``NaN``.
1644
+ """
1484
1645
  return self.update_page(
1485
1646
  page_id=page_id,
1486
1647
  title=title,
@@ -1506,19 +1667,29 @@ class Server(ConfluenceServerBase):
1506
1667
  full_width=False,
1507
1668
  ):
1508
1669
  """
1509
- Update page if already exist
1510
- :param page_id:
1511
- :param title:
1512
- :param body:
1513
- :param parent_id:
1514
- :param type:
1515
- :param representation: OPTIONAL: either Confluence 'storage' or 'wiki' markup format
1670
+ Update an existing page.
1671
+
1672
+ ``body`` must be Confluence storage XHTML when ``representation`` is
1673
+ ``"storage"`` (the default), not arbitrary browser HTML. Escape only
1674
+ dynamic text or attribute values; do not escape the complete markup or
1675
+ Confluence macros. A literal ``&`` in text must be ``&amp;``. Existing
1676
+ entities such as ``&quot;`` must not be escaped a second time.
1677
+
1678
+ :param page_id: existing Confluence page ID
1679
+ :param title: page title
1680
+ :param body: storage XHTML or wiki markup matching ``representation``
1681
+ :param parent_id: optional parent page ID; omit to retain the parent
1682
+ :param type: content type; normally ``"page"``
1683
+ :param representation: ``"storage"`` for editable storage XHTML or
1684
+ ``"wiki"`` for legacy wiki markup
1516
1685
  :param minor_edit: Indicates whether to notify watchers about changes.
1517
1686
  If False then notifications will be sent.
1518
1687
  :param version_comment: Version comment
1519
1688
  :param always_update: Whether always to update (suppress content check)
1520
1689
  :param full_width: OPTIONAL: Default False
1521
- :return:
1690
+ :return: The updated page response.
1691
+ :raises ApiNotFoundError: If the page cannot be found while retrieving
1692
+ its current version.
1522
1693
  """
1523
1694
  # update current page
1524
1695
  params = {"status": "current"}
@@ -1533,9 +1704,7 @@ class Server(ConfluenceServerBase):
1533
1704
  else:
1534
1705
  version = self.history(page_id)["lastUpdated"]["number"] + 1
1535
1706
  except (IndexError, TypeError) as e:
1536
- log.error("Can't find '%s' %s!", title, type)
1537
- log.debug(e)
1538
- return None
1707
+ raise ApiNotFoundError(f"Can't find '{title}' {type}!") from e
1539
1708
 
1540
1709
  data = {
1541
1710
  "id": page_id,
@@ -1560,16 +1729,17 @@ class Server(ConfluenceServerBase):
1560
1729
  data["metadata"]["properties"]["content-appearance-published"] = {"value": "fixed-width"}
1561
1730
  try:
1562
1731
  response = self.put(
1563
- f"rest/api/content/{page_id}",
1732
+ f"content/{page_id}",
1564
1733
  data=data,
1565
1734
  params=params,
1566
1735
  )
1567
1736
  except HTTPError as e:
1568
1737
  if e.response.status_code == 400:
1569
1738
  raise ApiValueError(
1570
- "No space or no content type, or setup a wrong version "
1571
- "type set to content, or status param is not draft and "
1572
- "status content is current",
1739
+ "Confluence rejected the page update. Verify that the page "
1740
+ "is current and that body is valid storage XHTML: preserve "
1741
+ "Confluence macros, escape dynamic '&' as '&amp;', and do "
1742
+ "not escape the complete document or existing entities.",
1573
1743
  reason=e,
1574
1744
  )
1575
1745
  if e.response.status_code == 404:
@@ -1662,23 +1832,27 @@ class Server(ConfluenceServerBase):
1662
1832
  minor_edit=False,
1663
1833
  ):
1664
1834
  """
1665
- Append body to page if already exist
1666
- :param parent_id:
1667
- :param page_id:
1668
- :param title:
1669
- :param append_body:
1670
- :param type:
1671
- :param representation: OPTIONAL: either Confluence 'storage' or 'wiki' markup format
1672
- :param minor_edit: Indicates whether to notify watchers about changes.
1673
- If False then notifications will be sent.
1674
- :return:
1835
+ Append content to an existing page.
1836
+
1837
+ ``append_body`` is normally a string of Confluence storage XHTML. A
1838
+ ``list`` or ``dict`` is supported with ``representation="storage"``
1839
+ and is appended as pretty-printed JSON in a Confluence code block.
1840
+
1841
+ :param parent_id: optional parent page ID
1842
+ :param page_id: page ID
1843
+ :param title: page title
1844
+ :param append_body: storage XHTML, or a list/dict to render as JSON
1845
+ :param type: content type; normally ``"page"``
1846
+ :param representation: ``"storage"`` or legacy ``"wiki"`` markup
1847
+ :param minor_edit: whether to suppress watcher notifications
1848
+ :return: the updated page response
1675
1849
  """
1676
1850
  log.info('Updating %s "%s"', type, title)
1677
1851
 
1678
1852
  return self._insert_to_existing_page(
1679
1853
  page_id,
1680
1854
  title,
1681
- append_body,
1855
+ self._coerce_structured_storage_body(append_body, representation),
1682
1856
  parent_id=parent_id,
1683
1857
  type=type,
1684
1858
  representation=representation,
@@ -1713,7 +1887,7 @@ class Server(ConfluenceServerBase):
1713
1887
  return self._insert_to_existing_page(
1714
1888
  page_id,
1715
1889
  title,
1716
- prepend_body,
1890
+ self._coerce_structured_storage_body(prepend_body, representation),
1717
1891
  parent_id=parent_id,
1718
1892
  type=type,
1719
1893
  representation=representation,
@@ -1721,33 +1895,73 @@ class Server(ConfluenceServerBase):
1721
1895
  top_of_page=True,
1722
1896
  )
1723
1897
 
1898
+ @staticmethod
1899
+ def _coerce_structured_storage_body(body, representation):
1900
+ """Render structured input as a safe JSON code block for storage pages."""
1901
+ if isinstance(body, str):
1902
+ return body
1903
+ if not isinstance(body, (list, dict)):
1904
+ raise ApiValueError("Page content must be a string, list, or dictionary")
1905
+ if representation != "storage":
1906
+ raise ApiValueError("Lists and dictionaries require representation='storage'")
1907
+
1908
+ # Split a CDATA terminator so arbitrary JSON cannot close the storage
1909
+ # macro's plain-text body.
1910
+ cdata_end = "]]" + ">"
1911
+ cdata_escape = "]]" + "]]><![CDATA[>"
1912
+ json_body = json.dumps(body, ensure_ascii=False, indent=2).replace(cdata_end, cdata_escape)
1913
+ return (
1914
+ '<ac:structured-macro ac:name="code">'
1915
+ '<ac:parameter ac:name="language">json</ac:parameter>'
1916
+ f"<ac:plain-text-body><![CDATA[{json_body}]]></ac:plain-text-body>"
1917
+ "</ac:structured-macro>"
1918
+ )
1919
+
1724
1920
  def update_or_create(
1725
1921
  self,
1726
- parent_id,
1727
- title,
1728
- body,
1922
+ parent_id=None,
1923
+ title=None,
1924
+ body=None,
1729
1925
  representation="storage",
1730
1926
  minor_edit=False,
1731
1927
  version_comment=None,
1732
1928
  editor=None,
1733
1929
  full_width=False,
1930
+ space=None,
1734
1931
  ):
1735
1932
  """
1736
1933
  Update page or create a page if it is not exists
1737
- :param parent_id:
1738
- :param title:
1739
- :param body:
1934
+ :param parent_id: optional parent page ID. Omit for a top-level page.
1935
+ :param title: page title
1936
+ :param body: page body
1740
1937
  :param representation: OPTIONAL: either Confluence 'storage' or 'wiki' markup format
1741
1938
  :param minor_edit: Update page without notification
1742
1939
  :param version_comment: Version comment
1743
1940
  :param editor: OPTIONAL: v2 to be created in the new editor
1744
1941
  :param full_width: OPTIONAL: Default is False
1942
+ :param space: space key. Required when ``parent_id`` is omitted.
1745
1943
  :return:
1746
- """
1747
- space = self.get_page_space(parent_id)
1748
1944
 
1749
- if self.page_exists(space, title):
1750
- page_id = self.get_page_id(space, title)
1945
+ Note:
1946
+ Confluence does not update archived pages through this workflow.
1947
+ Restore the page to the current state before calling this method.
1948
+ """
1949
+ if title is None or body is None:
1950
+ raise ApiValueError("title and body are required")
1951
+ if space is None:
1952
+ if parent_id is None:
1953
+ raise ApiValueError("space is required when parent_id is omitted")
1954
+ space = self.get_page_space(parent_id)
1955
+
1956
+ # A title is only unique among siblings. Searching the whole space
1957
+ # when a parent is supplied could update and move a same-titled page
1958
+ # from another branch (#956).
1959
+ if parent_id is not None:
1960
+ page_id = self.get_descendant_page_id(space, parent_id, title) or None
1961
+ else:
1962
+ page_id = self.get_page_id(space, title) if self.page_exists(space, title) else None
1963
+
1964
+ if page_id is not None:
1751
1965
  parent_id = parent_id if parent_id is not None else self.get_parent_content_id(page_id)
1752
1966
  result = self.update_page(
1753
1967
  parent_id=parent_id,
@@ -1760,14 +1974,19 @@ class Server(ConfluenceServerBase):
1760
1974
  full_width=full_width,
1761
1975
  )
1762
1976
  else:
1977
+ create_kwargs = {
1978
+ "space": space,
1979
+ "parent_id": parent_id,
1980
+ "title": title,
1981
+ "body": body,
1982
+ "representation": representation,
1983
+ "editor": editor,
1984
+ "full_width": full_width,
1985
+ }
1986
+ if version_comment is not None:
1987
+ create_kwargs["version_comment"] = version_comment
1763
1988
  result = self.create_page(
1764
- space=space,
1765
- parent_id=parent_id,
1766
- title=title,
1767
- body=body,
1768
- representation=representation,
1769
- editor=editor,
1770
- full_width=full_width,
1989
+ **create_kwargs,
1771
1990
  )
1772
1991
 
1773
1992
  log.info(
@@ -1799,14 +2018,20 @@ class Server(ConfluenceServerBase):
1799
2018
  """
1800
2019
  Set the page (content) property e.g. add hash parameters
1801
2020
  :param page_id: content_id format
1802
- :param data: data should be as json data
2021
+ :param data: property dictionary, or a JSON string representing one
1803
2022
  :return:
1804
2023
  """
1805
- url = f"rest/api/content/{page_id}/property"
1806
- json_data = data
2024
+ url = f"content/{page_id}/property"
2025
+ if isinstance(data, str):
2026
+ try:
2027
+ data = json.loads(data)
2028
+ except json.JSONDecodeError as error:
2029
+ raise ApiValueError("Page property data must be valid JSON", reason=error)
2030
+ if not isinstance(data, dict):
2031
+ raise ApiValueError("Page property data must be a dictionary")
1807
2032
 
1808
2033
  try:
1809
- response = self.post(path=url, data=json_data)
2034
+ response = self.post(path=url, data=data)
1810
2035
  except HTTPError as e:
1811
2036
  if e.response.status_code == 400:
1812
2037
  raise ApiValueError(
@@ -1831,12 +2056,20 @@ class Server(ConfluenceServerBase):
1831
2056
  """
1832
2057
  Update the page (content) property.
1833
2058
  Use json data or independent keys
1834
- :param data:
2059
+ :param data: property dictionary, or a JSON string representing one
1835
2060
  :param page_id: content_id format
1836
2061
  :data: property data in json format
1837
2062
  :return:
1838
2063
  """
1839
- url = f"rest/api/content/{page_id}/property/{data.get('key')}"
2064
+ if isinstance(data, str):
2065
+ try:
2066
+ data = json.loads(data)
2067
+ except json.JSONDecodeError as error:
2068
+ raise ApiValueError("Page property data must be valid JSON", reason=error)
2069
+ if not isinstance(data, dict):
2070
+ raise ApiValueError("Page property data must be a dictionary")
2071
+
2072
+ url = f"content/{page_id}/property/{data.get('key')}"
1840
2073
  try:
1841
2074
  response = self.put(path=url, data=data)
1842
2075
  except HTTPError as e:
@@ -1875,7 +2108,7 @@ class Server(ConfluenceServerBase):
1875
2108
  :param page_property: key of property
1876
2109
  :return:
1877
2110
  """
1878
- url = f"rest/api/content/{page_id}/property/{str(page_property)}"
2111
+ url = f"content/{page_id}/property/{str(page_property)}"
1879
2112
  try:
1880
2113
  response = self.delete(path=url)
1881
2114
  except HTTPError as e:
@@ -1898,7 +2131,7 @@ class Server(ConfluenceServerBase):
1898
2131
  :param page_property_key: key of property
1899
2132
  :return:
1900
2133
  """
1901
- url = f"rest/api/content/{page_id}/property/{str(page_property_key)}"
2134
+ url = f"content/{page_id}/property/{str(page_property_key)}"
1902
2135
  try:
1903
2136
  response = self.get(path=url)
1904
2137
  except HTTPError as e:
@@ -1915,16 +2148,28 @@ class Server(ConfluenceServerBase):
1915
2148
 
1916
2149
  return response
1917
2150
 
1918
- def get_page_properties(self, page_id):
1919
- """
1920
- Get the page (content) properties
1921
- :param page_id: content_id format
1922
- :return: get properties
2151
+ def get_page_properties(self, page_id, limit=100, expand=None):
2152
+ """Return every property attached to a page.
2153
+
2154
+ Confluence paginates this endpoint and otherwise returns only its small
2155
+ server-defined default page (commonly ten properties). Pagination is
2156
+ handled internally; ``limit`` controls the size of each HTTP request,
2157
+ not the number of properties returned.
2158
+
2159
+ :param page_id: content ID
2160
+ :param limit: maximum properties requested per API call
2161
+ :param expand: optional property fields to expand
2162
+ :return: list of page property objects
1923
2163
  """
1924
- url = f"rest/api/content/{page_id}/property"
2164
+ if limit <= 0:
2165
+ raise ValueError("limit must be greater than zero")
2166
+
2167
+ params = {"limit": limit}
2168
+ if expand:
2169
+ params["expand"] = expand
1925
2170
 
1926
2171
  try:
1927
- response = self.get(path=url)
2172
+ return list(self._get_paged(f"content/{page_id}/property", params=params))
1928
2173
  except HTTPError as e:
1929
2174
  if e.response.status_code == 404:
1930
2175
  # Raise ApiError as the documented reason is ambiguous
@@ -1936,8 +2181,6 @@ class Server(ConfluenceServerBase):
1936
2181
 
1937
2182
  raise
1938
2183
 
1939
- return response
1940
-
1941
2184
  def get_page_ancestors(self, page_id):
1942
2185
  """
1943
2186
  Provide the ancestors from the page (content) id
@@ -1967,6 +2210,7 @@ class Server(ConfluenceServerBase):
1967
2210
  expand=None,
1968
2211
  space_type=None,
1969
2212
  space_status=None,
2213
+ label=None,
1970
2214
  ):
1971
2215
  """
1972
2216
  Get all spaces with provided limit
@@ -1975,6 +2219,7 @@ class Server(ConfluenceServerBase):
1975
2219
  fixed system limits. Default: 500
1976
2220
  :param space_type: OPTIONAL: Filter the list of spaces returned by type (global, personal)
1977
2221
  :param space_status: OPTIONAL: Filter the list of spaces returned by status (current, archived)
2222
+ :param label: OPTIONAL: Filter the list of spaces by a category label.
1978
2223
  :param expand: OPTIONAL: additional info, e.g. metadata, icon, description, homepage
1979
2224
  """
1980
2225
  url = "rest/api/space"
@@ -1989,8 +2234,35 @@ class Server(ConfluenceServerBase):
1989
2234
  params["type"] = space_type
1990
2235
  if space_status:
1991
2236
  params["status"] = space_status
2237
+ if label:
2238
+ params["label"] = label
1992
2239
  return self.get(url, params=params)
1993
2240
 
2241
+ def get_space_names(self, start=0, limit=50, space_type=None, space_status=None, label=None):
2242
+ """Return every visible Server/Data Center space name.
2243
+
2244
+ Only the space directory metadata endpoint is requested; no page or
2245
+ space content is downloaded.
2246
+ """
2247
+ names = []
2248
+ current_start = start
2249
+ while True:
2250
+ response = self.get_all_spaces(
2251
+ start=current_start,
2252
+ limit=limit,
2253
+ space_type=space_type,
2254
+ space_status=space_status,
2255
+ label=label,
2256
+ )
2257
+ spaces = response.get("results", [])
2258
+ names.extend(space["name"] for space in spaces if space.get("name"))
2259
+ total_size = response.get("totalSize")
2260
+ if not spaces or (total_size is not None and current_start + len(spaces) >= total_size):
2261
+ return names
2262
+ if total_size is None and len(spaces) < limit:
2263
+ return names
2264
+ current_start += len(spaces)
2265
+
1994
2266
  def archive_space(self, space_key):
1995
2267
  """
1996
2268
  Archive space
@@ -2067,14 +2339,23 @@ class Server(ConfluenceServerBase):
2067
2339
  return self.post("space", data=data, **kwargs)
2068
2340
 
2069
2341
  def update_space(self, space_key, data, **kwargs):
2070
- """Update existing space."""
2342
+ """Update an existing Server/Data Center space with a REST payload."""
2071
2343
  return self.put(f"space/{space_key}", data=data, **kwargs)
2072
2344
 
2073
- def delete_space(self, space_key, **kwargs):
2345
+ def set_space_homepage(self, space_key, homepage_id):
2346
+ """Set a Server/Data Center space's homepage to an existing page.
2347
+
2348
+ ``homepage_id`` must identify a page in the target space. The caller
2349
+ needs permission to administer the space and view the chosen page.
2074
2350
  """
2075
- Delete space
2076
- :param space_key:
2077
- :return:
2351
+ return self.update_space(space_key, {"homepage": {"id": homepage_id}})
2352
+
2353
+ def delete_space(self, space_key, **kwargs):
2354
+ """Delete a space by key.
2355
+
2356
+ Raises:
2357
+ ApiNotFoundError: If Confluence responds with HTTP 404. Confluence
2358
+ may use this status to avoid revealing an inaccessible space.
2078
2359
  """
2079
2360
  url = f"space/{space_key}"
2080
2361
 
@@ -2082,7 +2363,7 @@ class Server(ConfluenceServerBase):
2082
2363
  response = self.delete(url, **kwargs)
2083
2364
  except HTTPError as e:
2084
2365
  if e.response.status_code == 404:
2085
- raise ApiError(
2366
+ raise ApiNotFoundError(
2086
2367
  "There is no space with the given key, "
2087
2368
  "or the calling user does not have permission to delete it",
2088
2369
  reason=e,
@@ -2320,6 +2601,14 @@ class Server(ConfluenceServerBase):
2320
2601
 
2321
2602
  raise
2322
2603
 
2604
+ returned_limit = response.get("limit") if isinstance(response, dict) else None
2605
+ if limit is not None and isinstance(returned_limit, int) and returned_limit < limit:
2606
+ warnings.warn(
2607
+ f"Confluence capped get_group_members limit from {limit} to {returned_limit}; "
2608
+ "use get_all_members to retrieve every member.",
2609
+ UserWarning,
2610
+ )
2611
+
2323
2612
  return response
2324
2613
 
2325
2614
  # Label Management
@@ -2493,7 +2782,10 @@ class Server(ConfluenceServerBase):
2493
2782
 
2494
2783
  if template_id:
2495
2784
  data["templateId"] = template_id
2496
- return self.put("rest/api/template", data=json.dumps(data))
2785
+ # ``AtlassianRestAPI.put`` serializes ``data`` to JSON. Passing a
2786
+ # pre-serialized value here turns the complete template into a JSON
2787
+ # string, which Confluence rejects with JsonMappingException.
2788
+ return self.put("rest/api/template", data=data)
2497
2789
 
2498
2790
  return self.post("rest/api/template", json=data)
2499
2791
 
@@ -2545,6 +2837,25 @@ class Server(ConfluenceServerBase):
2545
2837
 
2546
2838
  return response
2547
2839
 
2840
+ def create_page_from_template(self, space, title, template_id, parent_id=None, replacements=None, **kwargs):
2841
+ """Create a page from a Server/Data Center content template.
2842
+
2843
+ Template bodies are read from the ``storage`` representation so that
2844
+ Confluence macros are retained. ``replacements`` maps literal template
2845
+ placeholders (for example ``{"{{REPORT_DATE}}": "2026-08-15"}``) to
2846
+ their replacement values.
2847
+ """
2848
+ template = self.get_content_template(template_id)
2849
+ try:
2850
+ body = template["body"]["storage"]["value"]
2851
+ except (KeyError, TypeError) as error:
2852
+ raise ApiValueError("The template does not contain a storage body", reason=error)
2853
+
2854
+ for placeholder, value in (replacements or {}).items():
2855
+ body = body.replace(str(placeholder), str(value))
2856
+
2857
+ return self.create_page(space, title, body, parent_id=parent_id, representation="storage", **kwargs)
2858
+
2548
2859
  @deprecated(version="3.7.0", reason="Use get_blueprint_templates()")
2549
2860
  def get_all_blueprints_from_space(self, space, start=0, limit=None, expand=None):
2550
2861
  """
@@ -2869,24 +3180,23 @@ class Server(ConfluenceServerBase):
2869
3180
  :return:
2870
3181
  """
2871
3182
  limit = 50
2872
- flag = True
2873
- step = 0
2874
3183
  members = []
2875
- while flag:
2876
- values = self.get_group_members(
3184
+ while True:
3185
+ response = self.get_group_members(
2877
3186
  group_name=group_name,
2878
3187
  start=len(members),
2879
3188
  limit=limit,
2880
3189
  expand=expand,
2881
3190
  )
2882
- step += 1
2883
- if len(values) == 0:
2884
- flag = False
2885
- else:
2886
- members.extend(values)
2887
- if not members:
2888
- print(f"Did not get members from {group_name} group, please check permissions or connectivity")
2889
- return members
3191
+ values = response.get("results", []) if isinstance(response, dict) else response or []
3192
+ members.extend(values)
3193
+
3194
+ total_count = response.get("totalSize", response.get("totalCount")) if isinstance(response, dict) else None
3195
+ returned_limit = response.get("limit", limit) if isinstance(response, dict) else limit
3196
+ if not values or (total_count is not None and len(members) >= total_count):
3197
+ return members
3198
+ if total_count is None and len(values) < returned_limit:
3199
+ return members
2890
3200
 
2891
3201
  # Generic
2892
3202
  def cql(
@@ -2937,6 +3247,39 @@ class Server(ConfluenceServerBase):
2937
3247
 
2938
3248
  return response
2939
3249
 
3250
+ def iter_cql(
3251
+ self,
3252
+ cql,
3253
+ start=0,
3254
+ limit=None,
3255
+ expand=None,
3256
+ include_archived_spaces=None,
3257
+ excerpt=None,
3258
+ ):
3259
+ """Yield every result of a CQL search, following Confluence pagination.
3260
+
3261
+ Unlike :meth:`cql`, this does not materialize all results in memory.
3262
+ """
3263
+ params = {"start": int(start)} if start is not None else {}
3264
+ if limit is not None:
3265
+ params["limit"] = int(limit)
3266
+ if cql is not None:
3267
+ params["cql"] = cql
3268
+ if expand is not None:
3269
+ params["expand"] = expand
3270
+ if include_archived_spaces is not None:
3271
+ params["includeArchivedSpaces"] = include_archived_spaces
3272
+ if excerpt is not None:
3273
+ params["excerpt"] = excerpt
3274
+ return self._get_paged("rest/api/search", params=params)
3275
+
3276
+ def cql_all(self, *args, **kwargs):
3277
+ """Return all paginated CQL results as a list.
3278
+
3279
+ Prefer :meth:`iter_cql` for large result sets.
3280
+ """
3281
+ return list(self.iter_cql(*args, **kwargs))
3282
+
2940
3283
  def get_page_as_pdf(self, page_id):
2941
3284
  """
2942
3285
  Export page as standard pdf exporter
@@ -2945,13 +3288,48 @@ class Server(ConfluenceServerBase):
2945
3288
  """
2946
3289
  headers = self.form_token_headers
2947
3290
  url = f"spaces/flyingpdf/pdfpageexport.action?pageId={page_id}"
2948
- return self.get(url, headers=headers, not_json_response=True)
3291
+ response = self.get(url, headers=headers, advanced_mode=True)
3292
+ content = response.content
3293
+ if not content.startswith(b"%PDF-"):
3294
+ raise ApiError(
3295
+ "Confluence returned non-PDF content while exporting the page. "
3296
+ "Check the page permissions and authentication configuration."
3297
+ )
3298
+ return content
2949
3299
 
2950
- def get_page_as_word(self, page_id):
3300
+ def iter_page_tree_as_pdf(self, page_id):
3301
+ """Yield ``(page_id, pdf_bytes)`` for a page and all descendant pages.
3302
+
3303
+ Confluence exposes single-page PDF export but does not provide a
3304
+ supported REST operation for one merged arbitrary subtree PDF. Results
3305
+ are yielded in depth-first page-tree order so callers can stream files
3306
+ to disk or merge them with their preferred PDF library.
2951
3307
  """
2952
- Export page as standard word exporter.
3308
+ pending_page_ids = [page_id]
3309
+ while pending_page_ids:
3310
+ current_page_id = pending_page_ids.pop()
3311
+ yield current_page_id, self.get_page_as_pdf(current_page_id)
3312
+ children = list(self.get_page_child_by_type(current_page_id, type="page"))
3313
+ pending_page_ids.extend(child["id"] for child in reversed(children))
3314
+
3315
+ def export_page_tree_as_pdf(self, page_id):
3316
+ """Return individual PDFs for a page subtree keyed by page ID.
3317
+
3318
+ Prefer :meth:`iter_page_tree_as_pdf` for large hierarchies to avoid
3319
+ keeping every PDF in memory.
3320
+ """
3321
+ return dict(self.iter_page_tree_as_pdf(page_id))
3322
+
3323
+ def get_page_as_word(self, page_id):
3324
+ """Export a page through Confluence's legacy Word exporter.
3325
+
3326
+ Returns the response bytes exactly as provided by Confluence. The
3327
+ exporter does not produce a DOCX file (nor necessarily a binary DOC
3328
+ file); its output is a Word-readable multipart HTML document. There is
3329
+ no supported Confluence REST endpoint for DOCX export.
3330
+
2953
3331
  :param page_id: Page ID
2954
- :return: Word File
3332
+ :return: Legacy Word-export bytes
2955
3333
  """
2956
3334
  headers = self.form_token_headers
2957
3335
  url = f"exportword?pageId={page_id}"
@@ -2969,20 +3347,25 @@ class Server(ConfluenceServerBase):
2969
3347
  :return: The URL to download the exported file.
2970
3348
  """
2971
3349
 
3350
+ # Space export is a browser workflow, not a REST resource. ``self.url``
3351
+ # normally ends in ``/rest/api/<version>``, so derive the Confluence UI
3352
+ # context before requesting its action endpoints.
3353
+ ui_base_url = self.url.split("/rest/api/", 1)[0]
3354
+
3355
+ def ui_url(path: str) -> str:
3356
+ return self.url_joiner(ui_base_url, path)
3357
+
2972
3358
  def get_atl_request(link: str):
2973
3359
  # Nested function used to get atl_token used for XSRF protection.
2974
3360
  # This is only applicable to html/csv/xml space exports
2975
3361
  try:
2976
- response = self.get(link, advanced_mode=True)
3362
+ response = self.get(ui_url(link), absolute=True, advanced_mode=True)
2977
3363
  parsed_html = BeautifulSoup(response.text, "html.parser")
2978
3364
  atl_token = parsed_html.find("input", {"name": "atl_token"}).get("value") # type: ignore[union-attr]
2979
3365
  return atl_token
2980
3366
  except Exception as e:
2981
3367
  raise ApiError("Problems with getting the atl_token for get_space_export method :", reason=e)
2982
3368
 
2983
- # Checks if space_ke parameter is valid and if api_token has relevant permissions to space
2984
- self.get_space(space_key=space_key, expand="permissions")
2985
-
2986
3369
  try:
2987
3370
  log.info(
2988
3371
  "Initiated experimental get_space_export method for export type: "
@@ -3020,10 +3403,18 @@ class Server(ConfluenceServerBase):
3020
3403
  raise ValueError("PDF space export is not supported yet for Server/Data Center")
3021
3404
  else:
3022
3405
  raise ValueError("Invalid export_type parameter value. Valid values are: 'html/csv/xml/pdf'")
3023
- url = self.url_joiner(url=self.url, path=f"spaces/doexportspace.action?key={space_key}")
3406
+ url = ui_url(f"spaces/doexportspace.action?key={space_key}")
3024
3407
 
3025
3408
  # Sending a POST request that triggers the space export.
3026
- response = self.session.post(url, headers=self.form_token_headers, data=form_data)
3409
+ response = self.session.post(
3410
+ url,
3411
+ headers=self.form_token_headers,
3412
+ data=form_data,
3413
+ timeout=self.timeout,
3414
+ verify=self.verify_ssl,
3415
+ proxies=self.proxies,
3416
+ )
3417
+ response.raise_for_status()
3027
3418
  parsed_html = BeautifulSoup(response.text, "html.parser")
3028
3419
  # Getting the poll URL to get the export progress status
3029
3420
  try:
@@ -3035,21 +3426,15 @@ class Server(ConfluenceServerBase):
3035
3426
  running_task = True
3036
3427
  while running_task:
3037
3428
  try:
3038
- progress_response = self.get(poll_url) or {}
3429
+ progress_url = urljoin(ui_base_url + "/", poll_url)
3430
+ progress_response = self.get(progress_url, absolute=True) or {}
3039
3431
  log.info(f"Space {space_key} export status: {progress_response.get('message', 'None')}")
3040
3432
  if progress_response is not {} and progress_response.get("complete"):
3041
3433
  parsed_html = BeautifulSoup(progress_response.get("message"), "html.parser")
3042
3434
  download_url = cast(
3043
3435
  "str", parsed_html.find("a", {"class": "space-export-download-path"}).get("href")
3044
3436
  ) # type: ignore
3045
- if self.url in download_url:
3046
- return download_url
3047
- else:
3048
- combined_url = self.url + download_url
3049
- # Ensure only one /wiki is included in the path
3050
- if combined_url.count("/wiki") > 1:
3051
- combined_url = combined_url.replace("/wiki/wiki", "/wiki")
3052
- return combined_url
3437
+ return urljoin(ui_base_url + "/", download_url)
3053
3438
  time.sleep(30)
3054
3439
  except Exception as e:
3055
3440
  raise ApiError(
@@ -3060,6 +3445,22 @@ class Server(ConfluenceServerBase):
3060
3445
  except Exception as e:
3061
3446
  raise ApiError("Encountered error during space export from space " + space_key, reason=e)
3062
3447
 
3448
+ def iter_space_exports(self, space_keys, export_type: str):
3449
+ """Yield exported-space download URLs one space at a time.
3450
+
3451
+ The underlying Confluence export is an asynchronous browser workflow.
3452
+ Confluence limits concurrent exports, so this iterator intentionally
3453
+ waits for each export to finish before starting the next one. It is a
3454
+ safer alternative to invoking :meth:`get_space_export` concurrently
3455
+ from multiple threads.
3456
+
3457
+ :param space_keys: Iterable of Confluence space keys.
3458
+ :param export_type: Export type accepted by :meth:`get_space_export`.
3459
+ :return: Iterator of ``(space_key, download_url)`` tuples.
3460
+ """
3461
+ for space_key in space_keys:
3462
+ yield space_key, self.get_space_export(space_key, export_type)
3463
+
3063
3464
  def export_page(self, page_id):
3064
3465
  """
3065
3466
  Alias method for export page as pdf
@@ -3963,6 +4364,8 @@ class Server(ConfluenceServerBase):
3963
4364
  """
3964
4365
  Returns the license detailed information
3965
4366
  """
4367
+ if self.cloud:
4368
+ raise ApiNotAcceptable("Confluence Cloud does not provide license details through this API")
3966
4369
  url = "rest/license/1.0/license/details"
3967
4370
  return self.get(url)
3968
4371
 
@@ -3970,6 +4373,8 @@ class Server(ConfluenceServerBase):
3970
4373
  """
3971
4374
  Returns the total used seats in the license
3972
4375
  """
4376
+ if self.cloud:
4377
+ raise ApiNotAcceptable("Confluence Cloud does not provide license details through this API")
3973
4378
  url = "rest/license/1.0/license/userCount"
3974
4379
  return self.get(url)
3975
4380
 
@@ -3977,6 +4382,8 @@ class Server(ConfluenceServerBase):
3977
4382
  """
3978
4383
  Returns the available license seats remaining
3979
4384
  """
4385
+ if self.cloud:
4386
+ raise ApiNotAcceptable("Confluence Cloud does not provide license details through this API")
3980
4387
  url = "rest/license/1.0/license/remainingSeats"
3981
4388
  return self.get(url)
3982
4389
 
@@ -3984,5 +4391,7 @@ class Server(ConfluenceServerBase):
3984
4391
  """
3985
4392
  Returns the license max users
3986
4393
  """
4394
+ if self.cloud:
4395
+ raise ApiNotAcceptable("Confluence Cloud does not provide license details through this API")
3987
4396
  url = "rest/license/1.0/license/maxUsers"
3988
4397
  return self.get(url)