atlassian-python-api 5.0.2__py3-none-any.whl → 5.0.4__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.
@@ -0,0 +1,125 @@
1
+ """Confluence Cloud v2 administrative and workspace operations."""
2
+
3
+
4
+ class AdminManagementOperations:
5
+ """Wrappers for v2 administrative resources not covered by legacy helpers."""
6
+
7
+ @staticmethod
8
+ def _query(**values):
9
+ return {key: value for key, value in values.items() if value is not None}
10
+
11
+ def _v2(self, path):
12
+ return self.url_joiner("api/v2", path)
13
+
14
+ def get_admin_key(self):
15
+ return self.get(self._v2("admin-key"))
16
+
17
+ def enable_admin_key(self):
18
+ return self.post(self._v2("admin-key"))
19
+
20
+ def disable_admin_key(self):
21
+ return self.delete(self._v2("admin-key"))
22
+
23
+ def get_space_permissions(self, cursor=None, limit=None):
24
+ return self.get(self._v2("space-permissions"), params=self._query(cursor=cursor, limit=limit))
25
+
26
+ def get_space_permission_combinations(self, cursor=None, limit=None):
27
+ return self.get(
28
+ self._v2("space-permissions/transition/combinations"),
29
+ params=self._query(cursor=cursor, limit=limit),
30
+ )
31
+
32
+ def generate_space_permission_combinations(self, data=None):
33
+ return self.post(self._v2("space-permissions/transition/combinations"), data=data)
34
+
35
+ def assign_space_permission_roles(self, data=None):
36
+ return self.post(self._v2("space-permissions/transition/role-assignments"), data=data)
37
+
38
+ def remove_space_permission_access(self, data=None):
39
+ return self.post(self._v2("space-permissions/transition/access-removals"), data=data)
40
+
41
+ def get_space_permission_transition_task(self, task_id):
42
+ return self.get(self._v2(f"space-permissions/transition/tasks/{task_id}"))
43
+
44
+ def get_space_roles(
45
+ self,
46
+ space_id=None,
47
+ role_type=None,
48
+ principal_id=None,
49
+ principal_type=None,
50
+ cursor=None,
51
+ limit=None,
52
+ ):
53
+ return self.get(
54
+ self._v2("space-roles"),
55
+ params=self._query(
56
+ **{
57
+ "space-id": space_id,
58
+ "role-type": role_type,
59
+ "principal-id": principal_id,
60
+ "principal-type": principal_type,
61
+ "cursor": cursor,
62
+ "limit": limit,
63
+ }
64
+ ),
65
+ )
66
+
67
+ def create_space_role(self, data=None):
68
+ return self.post(self._v2("space-roles"), data=data)
69
+
70
+ def get_space_role(self, role_id):
71
+ return self.get(self._v2(f"space-roles/{role_id}"))
72
+
73
+ def update_space_role(self, role_id, data=None):
74
+ return self.put(self._v2(f"space-roles/{role_id}"), data=data)
75
+
76
+ def delete_space_role(self, role_id):
77
+ return self.delete(self._v2(f"space-roles/{role_id}"))
78
+
79
+ def get_space_role_mode(self):
80
+ return self.get(self._v2("space-role-mode"))
81
+
82
+ def bulk_get_users(self, data=None):
83
+ return self.post(self._v2("users-bulk"), data=data)
84
+
85
+ def check_user_access_by_email(self, data=None):
86
+ return self.post(self._v2("user/access/check-access-by-email"), data=data)
87
+
88
+ def invite_user_by_email(self, data=None):
89
+ return self.post(self._v2("user/access/invite-by-email"), data=data)
90
+
91
+ def get_data_policy_metadata(self):
92
+ return self.get(self._v2("data-policies/metadata"))
93
+
94
+ def get_data_policy_spaces(self, **filters):
95
+ return self.get(self._v2("data-policies/spaces"), params=self._query(**filters))
96
+
97
+ def get_global_footer_comments(self, **params):
98
+ return self.get(self._v2("footer-comments"), params=self._query(**params))
99
+
100
+ def create_global_footer_comment(self, data=None):
101
+ return self.post(self._v2("footer-comments"), data=data)
102
+
103
+ def get_global_inline_comments(self, **params):
104
+ return self.get(self._v2("inline-comments"), params=self._query(**params))
105
+
106
+ def create_global_inline_comment(self, data=None):
107
+ return self.post(self._v2("inline-comments"), data=data)
108
+
109
+ def get_comment_children_v2(self, comment_id, comment_type="footer-comments", **params):
110
+ return self.get(self._v2(f"{comment_type}/{comment_id}/children"), params=self._query(**params))
111
+
112
+ def get_comment_likes_count_v2(self, comment_id, comment_type="footer-comments"):
113
+ return self.get(self._v2(f"{comment_type}/{comment_id}/likes/count"))
114
+
115
+ def get_comment_likes_users_v2(self, comment_id, comment_type="footer-comments", **params):
116
+ return self.get(self._v2(f"{comment_type}/{comment_id}/likes/users"), params=self._query(**params))
117
+
118
+ def get_comment_operations_v2(self, comment_id, comment_type="footer-comments"):
119
+ return self.get(self._v2(f"{comment_type}/{comment_id}/operations"))
120
+
121
+ def get_comment_versions_v2(self, comment_id, comment_type="footer-comments", **params):
122
+ return self.get(self._v2(f"{comment_type}/{comment_id}/versions"), params=self._query(**params))
123
+
124
+ def get_comment_version_v2(self, comment_id, version_number, comment_type="footer-comments"):
125
+ return self.get(self._v2(f"{comment_type}/{comment_id}/versions/{version_number}"))
@@ -18,6 +18,7 @@ from .folders import FolderOperations
18
18
  from .graphql import GraphQLOperations
19
19
  from .tasks import TaskOperations
20
20
  from .whiteboards import WhiteboardOperations
21
+ from .admin_management import AdminManagementOperations
21
22
 
22
23
  log = logging.getLogger(__name__)
23
24
 
@@ -30,6 +31,7 @@ class ConfluenceCloud(
30
31
  TaskOperations,
31
32
  FolderOperations,
32
33
  DatabaseOperations,
34
+ AdminManagementOperations,
33
35
  ):
34
36
  """
35
37
  Confluence Cloud API implementation class
@@ -157,11 +159,7 @@ class ConfluenceCloud(
157
159
  if expand:
158
160
  params["expand"] = ",".join(expand)
159
161
 
160
- try:
161
- return self.get(endpoint, params=params)
162
- except Exception as e:
163
- log.error(f"Failed to retrieve page with ID {page_id}: {e}")
164
- raise
162
+ return self.get(endpoint, params=params)
165
163
 
166
164
  def get_pages(
167
165
  self,
@@ -444,11 +442,7 @@ class ConfluenceCloud(
444
442
  if parent_id:
445
443
  data["parentId"] = parent_id
446
444
 
447
- try:
448
- return self.post(endpoint, data=data)
449
- except Exception as e:
450
- log.error(f"Failed to create page: {e}")
451
- raise
445
+ return self.post(endpoint, data=data)
452
446
 
453
447
  def update_page(
454
448
  self,
@@ -503,12 +497,8 @@ class ConfluenceCloud(
503
497
 
504
498
  # First, get the current page to get its version
505
499
  if version is None:
506
- try:
507
- current_page = self.get_page_by_id(page_id, get_body=False)
508
- version = current_page.get("version", {}).get("number", 1)
509
- except Exception as e:
510
- log.error(f"Failed to retrieve page for update: {e}")
511
- raise
500
+ current_page = self.get_page_by_id(page_id, get_body=False)
501
+ version = current_page.get("version", {}).get("number", 1)
512
502
 
513
503
  # Prepare update data
514
504
  data = {
@@ -528,11 +518,7 @@ class ConfluenceCloud(
528
518
  if representation:
529
519
  data["body"][body_format]["representation"] = representation
530
520
 
531
- try:
532
- return self.put(endpoint, data=data)
533
- except Exception as e:
534
- log.error(f"Failed to update page: {e}")
535
- raise
521
+ return self.put(endpoint, data=data)
536
522
 
537
523
  def delete_page(self, page_id: str) -> bool:
538
524
  """
@@ -7,7 +7,7 @@ import re
7
7
  import sys
8
8
  import time
9
9
  import warnings
10
- from typing import cast
10
+ from typing import Optional, cast
11
11
  from urllib.parse import urljoin
12
12
 
13
13
  import requests
@@ -42,6 +42,25 @@ class Server(ConfluenceServerBase):
42
42
  Confluence Server REST API wrapper
43
43
  """
44
44
 
45
+ _api_resources = frozenset(
46
+ {
47
+ "accessmode",
48
+ "admin",
49
+ "audit",
50
+ "content",
51
+ "contentbody",
52
+ "group",
53
+ "health",
54
+ "longtask",
55
+ "metadata",
56
+ "reindex",
57
+ "search",
58
+ "space",
59
+ "template",
60
+ "user",
61
+ }
62
+ )
63
+
45
64
  content_types = {
46
65
  ".gif": "image/gif",
47
66
  ".png": "image/png",
@@ -54,6 +73,7 @@ class Server(ConfluenceServerBase):
54
73
  }
55
74
 
56
75
  def __init__(self, url, *args, **kwargs):
76
+ api_version_is_explicit = "api_version" in kwargs
57
77
  # Set default values only if not provided
58
78
  if "cloud" not in kwargs:
59
79
  kwargs["cloud"] = False
@@ -61,8 +81,56 @@ class Server(ConfluenceServerBase):
61
81
  kwargs["api_version"] = "1.0"
62
82
  if "api_root" not in kwargs:
63
83
  kwargs["api_root"] = "rest/api"
64
- url = url.strip("/") + f"/{kwargs['api_root']}/{kwargs['api_version']}"
65
- super(Server, self).__init__(url, *args, **kwargs)
84
+ super(Server, self).__init__(url.rstrip("/"), *args, **kwargs)
85
+ self._api_version_is_explicit = api_version_is_explicit
86
+
87
+ def _server_api_path(self, path):
88
+ """Prefix unrooted Server REST resources without changing legacy paths."""
89
+ if not isinstance(path, str):
90
+ return path
91
+
92
+ normalized_path = path.lstrip("/")
93
+ resource = normalized_path.split("/", 1)[0].split("?", 1)[0]
94
+ if resource not in self._api_resources:
95
+ return path
96
+
97
+ api_parts = [self.api_root]
98
+ if self._api_version_is_explicit:
99
+ api_parts.append(self.api_version)
100
+ api_parts.append(normalized_path)
101
+ return "/".join(str(part).strip("/") for part in api_parts if part is not None and str(part).strip("/"))
102
+
103
+ def request(
104
+ self,
105
+ method="GET",
106
+ path="/",
107
+ data=None,
108
+ json=None,
109
+ flags=None,
110
+ params=None,
111
+ headers=None,
112
+ files=None,
113
+ trailing=None,
114
+ absolute=False,
115
+ advanced_mode=False,
116
+ allow_redirects=True,
117
+ ):
118
+ if not absolute:
119
+ path = self._server_api_path(path)
120
+ return super(Server, self).request(
121
+ method=method,
122
+ path=path,
123
+ data=data,
124
+ json=json,
125
+ flags=flags,
126
+ params=params,
127
+ headers=headers,
128
+ files=files,
129
+ trailing=trailing,
130
+ absolute=absolute,
131
+ advanced_mode=advanced_mode,
132
+ allow_redirects=allow_redirects,
133
+ )
66
134
 
67
135
  @staticmethod
68
136
  def _create_body(body, representation):
@@ -170,7 +238,8 @@ class Server(ConfluenceServerBase):
170
238
 
171
239
  def get_page_space(self, page_id):
172
240
  """Get space key from page ID."""
173
- page = self.get_content(page_id, expand="space")
241
+ params = {"expand": "space"}
242
+ page = self.get(f"content/{page_id}", params=params)
174
243
  return page.get("space", {}).get("key")
175
244
 
176
245
  def get_page_child_by_type(self, page_id, type="page", start=None, limit=None, expand=None):
@@ -269,13 +338,16 @@ class Server(ConfluenceServerBase):
269
338
 
270
339
  def get_page_id(self, space, title, type="page"):
271
340
  """
272
- Provide content id from search result by title and space.
341
+ Get page ID by searching for it by space key and title - returns the ID from the first result or None if not found.
273
342
  :param space: SPACE key
274
343
  :param title: title
275
344
  :param type: type of content: Page or Blogpost. Defaults to page
276
345
  :return:
277
346
  """
278
- return (self.get_page_by_title(space, title, type=type) or {}).get("id")
347
+ json_response = self.get_page_by_title(space, title, type=type)
348
+ if json_response and "results" in json_response and len(json_response["results"]) > 0:
349
+ return json_response["results"][0]["id"]
350
+ return None
279
351
 
280
352
  def get_parent_content_id(self, page_id):
281
353
  """
@@ -1085,16 +1157,38 @@ class Server(ConfluenceServerBase):
1085
1157
  path = f"rest/api/content/{page_id}/child/attachment"
1086
1158
 
1087
1159
  try:
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(
1093
- path=path,
1094
- data=data,
1095
- headers=headers,
1096
- files={"file": (name, content, content_type)},
1097
- )
1160
+ # Confluence Server doesn't support PUT on the child/attachment endpoint.
1161
+ # We need to check if the attachment exists first, then create or update accordingly.
1162
+ # GET existing attachment to check if it exists
1163
+ existing_attachment = None
1164
+ try:
1165
+ attachments = self.get(path=path, headers=headers)
1166
+ if "results" in attachments:
1167
+ for attachment in attachments["results"]:
1168
+ if attachment.get("title") == name:
1169
+ existing_attachment = attachment
1170
+ break
1171
+ except HTTPError:
1172
+ pass
1173
+
1174
+ if existing_attachment:
1175
+ # Update existing attachment using PUT on the specific attachment ID
1176
+ attachment_id = existing_attachment["id"]
1177
+ update_path = f"rest/api/content/{attachment_id}"
1178
+ response = self.put(
1179
+ path=update_path,
1180
+ data=data,
1181
+ headers=headers,
1182
+ files={"file": (name, content, content_type)},
1183
+ )
1184
+ else:
1185
+ # Create new attachment using POST
1186
+ response = self.post(
1187
+ path=path,
1188
+ data=data,
1189
+ headers=headers,
1190
+ files={"file": (name, content, content_type)},
1191
+ )
1098
1192
  except HTTPError as e:
1099
1193
  if e.response.status_code == 403:
1100
1194
  # Raise ApiError as the documented reason is ambiguous
@@ -1298,6 +1392,36 @@ class Server(ConfluenceServerBase):
1298
1392
  url = f"rest/experimental/content/{attachment_id}/version/{version}"
1299
1393
  return self.delete(url)
1300
1394
 
1395
+ def move_or_update_attachment_json_rpc(
1396
+ self,
1397
+ originalContentId: str,
1398
+ originalName: str,
1399
+ newContentEntityId: Optional[str] = None,
1400
+ newName: Optional[str] = None,
1401
+ ):
1402
+ """
1403
+ Move attachment from source confluence page to destination confluence page optionally with new title
1404
+ OR
1405
+ Just update attachment from source confluence page with new title
1406
+ via JSON-RPC.
1407
+ :param str originalContentId: confluence source page id
1408
+ :param str newContentEntityId: confluence destination page id
1409
+ :param str originalName: source attachment title
1410
+ :param str newName: new attachment title
1411
+ """
1412
+ if self.api_version == "cloud" or self.cloud:
1413
+ return {}
1414
+ url = "rpc/json-rpc/confluenceservice-v2"
1415
+ data = {
1416
+ "jsonrpc": "2.0",
1417
+ "method": "moveAttachment",
1418
+ "id": 9,
1419
+ "params": [originalContentId, originalName, newContentEntityId, newName],
1420
+ }
1421
+
1422
+ response = self.post(url, data=data)
1423
+ return (response or {}).get("result") or {}
1424
+
1301
1425
  def remove_page_attachment_keep_version(self, page_id, filename, keep_last_versions):
1302
1426
  """
1303
1427
  Keep last versions
@@ -4,7 +4,7 @@ Confluence base module for shared functionality between API versions
4
4
 
5
5
  import logging
6
6
  from typing import Dict, List, Optional, Union
7
- from urllib.parse import urlparse
7
+ from urllib.parse import parse_qsl, urlparse
8
8
 
9
9
  from atlassian.rest_client import AtlassianRestAPI
10
10
 
@@ -259,21 +259,32 @@ class ConfluenceBase(AtlassianRestAPI):
259
259
  if not next_url:
260
260
  break
261
261
 
262
- # Use the next URL directly
263
- # Check if the response has a base URL provided (common in Confluence v2 API)
264
- base_url = response.get("_links", {}).get("base")
265
- if base_url and next_url.startswith("/"):
266
- # Construct the full URL using the base URL from the response
267
- url = f"{base_url}{next_url}"
262
+ if isinstance(next_url, dict):
263
+ next_url = next_url.get("href")
264
+ if not next_url:
265
+ break
266
+
267
+ # Cursor links are commonly relative and include the endpoint
268
+ # path (for example ``/wiki/api/v2/spaces?cursor=...``). The
269
+ # endpoint used for the first request is already resolved
270
+ # against the tenant or API-gateway context, so rebuilding it
271
+ # from ``_links.base`` can duplicate ``/wiki`` or drop an
272
+ # ``/ex/confluence/{cloud_id}`` prefix. Keep the resolved
273
+ # endpoint and advance only its query parameters.
274
+ parsed_next = urlparse(next_url)
275
+ if parsed_next.scheme:
276
+ url = next_url
268
277
  absolute = True
278
+ params = {}
279
+ elif parsed_next.query:
280
+ params = dict(parse_qsl(parsed_next.query, keep_blank_values=True))
269
281
  else:
282
+ # A relative link without a query is unusual for cursor
283
+ # pagination; retain the previous behavior as a safe
284
+ # fallback for such responses.
270
285
  url = next_url
271
- # Check if the URL is absolute (has http:// or https://) or contains the server's domain
272
- if next_url.startswith(("http://", "https://")) or self.url.split("/")[2] in next_url:
273
- absolute = True
274
- else:
275
- absolute = False
276
- params = {}
286
+ absolute = False
287
+ params = {}
277
288
  trailing = False
278
289
 
279
290
  return