atlassian-python-api 4.0.7__py3-none-any.whl → 5.0.0__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 (60) hide show
  1. atlassian/VERSION +1 -1
  2. atlassian/__init__.py +18 -1
  3. atlassian/assets.py +1 -1
  4. atlassian/bamboo.py +4 -4
  5. atlassian/bitbucket/__init__.py +3 -3
  6. atlassian/bitbucket/cloud/repositories/pipelines.py +1 -1
  7. atlassian/bitbucket/cloud/workspaces/__init__.py +2 -2
  8. atlassian/bitbucket/cloud/workspaces/projects.py +1 -1
  9. atlassian/bitbucket/server/__init__.py +1 -1
  10. atlassian/bitbucket/server/projects/__init__.py +2 -1
  11. atlassian/bitbucket/server/projects/repos/__init__.py +1 -0
  12. atlassian/confluence/__init__.py +54 -4106
  13. atlassian/confluence/base.py +195 -0
  14. atlassian/confluence/cloud/__init__.py +354 -0
  15. atlassian/confluence/cloud/base.py +25 -0
  16. atlassian/confluence/cloud/cloud.py +2480 -0
  17. atlassian/confluence/server/__init__.py +3988 -0
  18. atlassian/confluence/server/base.py +25 -0
  19. atlassian/confluence/server/confluence_server.py +28 -0
  20. atlassian/confluence_base.py +281 -0
  21. atlassian/confluence_v2.py +7 -0
  22. atlassian/crowd.py +1 -1
  23. atlassian/insight.py +3 -2
  24. atlassian/jira.py +309 -16
  25. atlassian/jira_models.py +10 -0
  26. atlassian/models/__init__.py +5 -0
  27. atlassian/models/jira/__init__.py +109 -0
  28. atlassian/models/jira/adf.py +178 -0
  29. atlassian/models/jira/builders.py +272 -0
  30. atlassian/models/jira/comment.py +52 -0
  31. atlassian/models/jira/fields.py +236 -0
  32. atlassian/models/jira/issues.py +101 -0
  33. atlassian/models/jira/serializer.py +138 -0
  34. atlassian/models/jira/transition.py +78 -0
  35. atlassian/models/jira/update.py +179 -0
  36. atlassian/models/jira/validation.py +56 -0
  37. atlassian/models/py.typed +0 -0
  38. atlassian/rest_client.py +81 -15
  39. atlassian/service_desk.py +41 -1
  40. atlassian/statuspage.py +7 -6
  41. atlassian/tempo/__init__.py +14 -0
  42. atlassian/tempo/cloud/__init__.py +232 -0
  43. atlassian/tempo/cloud/base.py +38 -0
  44. atlassian/tempo/server/__init__.py +78 -0
  45. atlassian/tempo/server/accounts.py +38 -0
  46. atlassian/tempo/server/base.py +50 -0
  47. atlassian/tempo/server/budgets.py +42 -0
  48. atlassian/tempo/server/events.py +52 -0
  49. atlassian/tempo/server/planner.py +42 -0
  50. atlassian/tempo/server/servlet.py +46 -0
  51. atlassian/tempo/server/teams.py +50 -0
  52. atlassian/tempo/server/timesheets.py +54 -0
  53. atlassian/typehints.py +14 -2
  54. atlassian/xray.py +2 -0
  55. {atlassian_python_api-4.0.7.dist-info → atlassian_python_api-5.0.0.dist-info}/METADATA +45 -5
  56. atlassian_python_api-5.0.0.dist-info/RECORD +92 -0
  57. {atlassian_python_api-4.0.7.dist-info → atlassian_python_api-5.0.0.dist-info}/WHEEL +1 -1
  58. atlassian_python_api-4.0.7.dist-info/RECORD +0 -58
  59. {atlassian_python_api-4.0.7.dist-info → atlassian_python_api-5.0.0.dist-info}/licenses/LICENSE +0 -0
  60. {atlassian_python_api-4.0.7.dist-info → atlassian_python_api-5.0.0.dist-info}/top_level.txt +0 -0
@@ -1,4115 +1,63 @@
1
1
  # coding=utf-8
2
- import io
3
- import json
4
- import logging
5
- import os
6
- import re
7
- import time
8
- import warnings
9
- from typing import cast
2
+ """
3
+ Confluence API client package for Atlassian Python API.
10
4
 
11
- import requests
12
- from bs4 import BeautifulSoup
13
- from deprecated import deprecated
14
- from requests import HTTPError
5
+ This package provides both Cloud and Server implementations of the Confluence API.
6
+ """
15
7
 
16
- from atlassian import utils
17
- from atlassian.errors import (
18
- ApiConflictError,
19
- ApiError,
20
- ApiNotAcceptable,
21
- ApiNotFoundError,
22
- ApiPermissionError,
23
- ApiValueError,
24
- JsonRPCError,
25
- JsonRPCRestrictionsError,
26
- )
27
- from atlassian.rest_client import AtlassianRestAPI
28
- import sys
8
+ from urllib.parse import urlparse
29
9
 
30
- if sys.version_info >= (3, 8):
31
- from typing import Literal # Python 3.8+
32
- else:
33
- from typing_extensions import Literal # Python <=3.7
10
+ from ..confluence_base import ConfluenceBase
11
+ from .cloud import Cloud as LegacyConfluenceCloud
12
+ from .server import Server as ConfluenceServer
13
+ from .base import ConfluenceBase as LegacyConfluenceBase
34
14
 
35
- log = logging.getLogger(__name__)
36
15
 
16
+ # Legacy Confluence class for backward compatibility
17
+ class Confluence(LegacyConfluenceBase):
18
+ """Legacy Confluence class for backward compatibility."""
37
19
 
38
- class Confluence(AtlassianRestAPI):
39
- content_types = {
40
- ".gif": "image/gif",
41
- ".png": "image/png",
42
- ".jpg": "image/jpeg",
43
- ".jpeg": "image/jpeg",
44
- ".pdf": "application/pdf",
45
- ".doc": "application/msword",
46
- ".xls": "application/vnd.ms-excel",
47
- ".svg": "image/svg+xml",
48
- }
20
+ def __new__(cls, url, *args, **kwargs):
21
+ api_version = kwargs.get("api_version")
22
+ if api_version in (1, 2):
23
+ from .cloud.cloud import ConfluenceCloud as VersionedConfluenceCloud
49
24
 
50
- def __init__(self, url, *args, **kwargs):
51
- if ("atlassian.net" in url or "jira.com" in url) and ("/wiki" not in url):
52
- url = AtlassianRestAPI.url_joiner(url, "/wiki")
53
- if "cloud" not in kwargs:
54
- kwargs["cloud"] = True
55
- super(Confluence, self).__init__(url, *args, **kwargs)
56
-
57
- @staticmethod
58
- def _create_body(body, representation):
59
- if representation not in [
60
- "atlas_doc_format",
61
- "editor",
62
- "export_view",
63
- "view",
64
- "storage",
65
- "wiki",
66
- ]:
67
- raise ValueError("Wrong value for representation, it should be either wiki or storage")
68
-
69
- return {representation: {"value": body, "representation": representation}}
70
-
71
- def _get_paged(
72
- self,
73
- url,
74
- params=None,
75
- data=None,
76
- flags=None,
77
- trailing=None,
78
- absolute=False,
79
- ):
80
- """
81
- Used to get the paged data
82
-
83
- :param url: string: The url to retrieve
84
- :param params: dict (default is None): The parameter's
85
- :param data: dict (default is None): The data
86
- :param flags: string[] (default is None): The flags
87
- :param trailing: bool (default is None): If True, a trailing slash is added to the url
88
- :param absolute: bool (default is False): If True, the url is used absolute and not relative to the root
89
-
90
- :return: A generator object for the data elements
91
- """
92
-
93
- if params is None:
94
- params = {}
95
-
96
- while True:
97
- response = self.get(
98
- url,
99
- trailing=trailing,
100
- params=params,
101
- data=data,
102
- flags=flags,
103
- absolute=absolute,
104
- )
105
- if "results" not in response:
106
- return
107
-
108
- for value in response.get("results", []):
109
- yield value
110
-
111
- # According to Cloud and Server documentation the links are returned the same way:
112
- # https://developer.atlassian.com/cloud/confluence/rest/api-group-content/#api-wiki-rest-api-content-get
113
- # https://developer.atlassian.com/server/confluence/pagination-in-the-rest-api/
114
- url = response.get("_links", {}).get("next")
115
- if url is None:
116
- break
117
- # From now on we have relative URLs with parameters
118
- absolute = False
119
- # Params are now provided by the url
120
- params = {}
121
- # Trailing should not be added as it is already part of the url
122
- trailing = False
123
-
124
- return
125
-
126
- def page_exists(self, space, title, type=None):
127
- """
128
- Check if title exists as page.
129
- :param space: Space key
130
- :param title: Title of the page
131
- :param type: type of the page, 'page' or 'blogpost'. Defaults to 'page'
132
- :return:
133
- """
134
- url = "rest/api/content"
135
- params = {}
136
- if space is not None:
137
- params["spaceKey"] = str(space)
138
- if title is not None:
139
- params["title"] = str(title)
140
- if type is not None:
141
- params["type"] = str(type)
142
-
143
- try:
144
- response = self.get(url, params=params)
145
- except HTTPError as e:
146
- if e.response.status_code == 404:
147
- raise ApiPermissionError(
148
- "The calling user does not have permission to view the content",
149
- reason=e,
150
- )
151
-
152
- raise
153
-
154
- if response.get("results"):
155
- return True
156
- else:
157
- return False
158
-
159
- def share_with_others(self, page_id, group, message):
160
- """
161
- Notify members (currently only groups implemented) about something on that page
162
- """
163
- url = "rest/share-page/latest/share"
164
- params = {
165
- "contextualPageId": page_id,
166
- # "emails": [],
167
- "entityId": page_id,
168
- "entityType": "page",
169
- "groups": group,
170
- "note": message,
171
- # "users":[]
172
- }
173
- r = self.post(url, json=params, headers={"contentType": "application/json; charset=utf-8"}, advanced_mode=True)
174
- if r.status_code != 200:
175
- raise Exception(f"failed sharing content {r.status_code}: {r.text}")
176
-
177
- def get_page_child_by_type(self, page_id, type="page", start=None, limit=None, expand=None):
178
- """
179
- Provide content by type (page, blog, comment)
180
- :param page_id: A string containing the id of the type content container.
181
- :param type:
182
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
183
- :param limit: OPTIONAL: how many items should be returned after the start index. Default: Site limit 200.
184
- :param expand: OPTIONAL: expand e.g. history
185
- :return:
186
- """
187
- params = {}
188
- if start is not None:
189
- params["start"] = int(start)
190
- if limit is not None:
191
- params["limit"] = int(limit)
192
- if expand is not None:
193
- params["expand"] = expand
194
-
195
- url = f"rest/api/content/{page_id}/child/{type}"
196
- log.info(url)
197
-
198
- try:
199
- if not self.advanced_mode and start is None and limit is None:
200
- return self._get_paged(url, params=params)
201
- else:
202
- response = self.get(url, params=params)
203
- if self.advanced_mode:
204
- return response
205
- return response.get("results")
206
- except HTTPError as e:
207
- if e.response.status_code == 404:
208
- # Raise ApiError as the documented reason is ambiguous
209
- raise ApiError(
210
- "There is no content with the given id, "
211
- "or the calling user does not have permission to view the content",
212
- reason=e,
213
- )
214
-
215
- raise
216
-
217
- def get_child_title_list(self, page_id, type="page", start=None, limit=None):
218
- """
219
- Find a list of Child title
220
- :param page_id: A string containing the id of the type content container.
221
- :param type:
222
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
223
- :param limit: OPTIONAL: how many items should be returned after the start index. Default: Site limit 200.
224
- :return:
225
- """
226
- child_page = self.get_page_child_by_type(page_id, type, start, limit)
227
- child_title_list = [child["title"] for child in child_page]
228
- return child_title_list
229
-
230
- def get_child_id_list(self, page_id, type="page", start=None, limit=None):
231
- """
232
- Find a list of Child id
233
- :param page_id: A string containing the id of the type content container.
234
- :param type:
235
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
236
- :param limit: OPTIONAL: how many items should be returned after the start index. Default: Site limit 200.
237
- :return:
238
- """
239
- child_page = self.get_page_child_by_type(page_id, type, start, limit)
240
- child_id_list = [child["id"] for child in child_page]
241
- return child_id_list
242
-
243
- def get_child_pages(self, page_id):
244
- """
245
- Get child pages for the provided page_id
246
- :param page_id:
247
- :return:
248
- """
249
- return self.get_page_child_by_type(page_id=page_id, type="page")
250
-
251
- def get_page_id(self, space, title, type="page"):
252
- """
253
- Provide content id from search result by title and space.
254
- :param space: SPACE key
255
- :param title: title
256
- :param type: type of content: Page or Blogpost. Defaults to page
257
- :return:
258
- """
259
- return (self.get_page_by_title(space, title, type=type) or {}).get("id")
260
-
261
- def get_parent_content_id(self, page_id):
262
- """
263
- Provide parent content id from page id
264
- :type page_id: str
265
- :return:
266
- """
267
- parent_content_id = None
268
- try:
269
- parent_content_id = (self.get_page_by_id(page_id=page_id, expand="ancestors").get("ancestors") or {})[
270
- -1
271
- ].get("id") or None
272
- except Exception as e:
273
- log.error(e)
274
- return parent_content_id
275
-
276
- def get_parent_content_title(self, page_id):
277
- """
278
- Provide parent content title from page id
279
- :type page_id: str
280
- :return:
281
- """
282
- parent_content_title = None
283
- try:
284
- parent_content_title = (self.get_page_by_id(page_id=page_id, expand="ancestors").get("ancestors") or {})[
285
- -1
286
- ].get("title") or None
287
- except Exception as e:
288
- log.error(e)
289
- return parent_content_title
290
-
291
- def get_page_space(self, page_id):
292
- """
293
- Provide space key from content id.
294
- :param page_id: content ID
295
- :return:
296
- """
297
- return ((self.get_page_by_id(page_id, expand="space") or {}).get("space") or {}).get("key") or None
298
-
299
- def get_pages_by_title(self, space, title, start=0, limit=200, expand=None):
300
- """
301
- Provide pages by title search
302
- :param space: Space key
303
- :param title: Title of the page
304
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
305
- :param limit: OPTIONAL: The limit of the number of labels to return, this may be restricted by
306
- fixed system limits. Default: 200.
307
- :param expand: OPTIONAL: expand e.g. history
308
- :return: The JSON data returned from searched results the content endpoint, or the results of the
309
- callback. Will raise requests.HTTPError on bad input, potentially.
310
- If it has IndexError then return the None.
311
- """
312
- return self.get_page_by_title(space, title, start, limit, expand)
313
-
314
- def get_page_by_title(self, space, title, start=0, limit=1, expand=None, type="page"):
315
- """
316
- Returns the first page on a piece of Content.
317
- :param space: Space key
318
- :param title: Title of the page
319
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
320
- :param limit: OPTIONAL: The limit of the number of labels to return, this may be restricted by
321
- fixed system limits. Default: 1.
322
- :param expand: OPTIONAL: expand e.g. history
323
- :param type: OPTIONAL: Type of content: Page or Blogpost. Defaults to page
324
- :return: The JSON data returned from searched results the content endpoint, or the results of the
325
- callback. Will raise requests.HTTPError on bad input, potentially.
326
- If it has IndexError then return the None.
327
- """
328
- url = "rest/api/content"
329
- params = {"type": type}
330
- if start is not None:
331
- params["start"] = int(start)
332
- if limit is not None:
333
- params["limit"] = int(limit)
334
- if expand is not None:
335
- params["expand"] = expand
336
- if space is not None:
337
- params["spaceKey"] = str(space)
338
- if title is not None:
339
- params["title"] = str(title)
340
-
341
- if self.advanced_mode:
342
- return self.get(url, params=params)
343
- try:
344
- response = self.get(url, params=params)
345
- except HTTPError as e:
346
- if e.response.status_code == 404:
347
- raise ApiPermissionError(
348
- "The calling user does not have permission to view the content",
349
- reason=e,
350
- )
351
-
352
- raise
353
- try:
354
- return response.get("results")[0]
355
- except (IndexError, TypeError) as e:
356
- log.error(f"Can't find '{title}' page on {self.url}")
357
- log.debug(e)
358
- return None
359
-
360
- def get_page_by_id(self, page_id, expand=None, status=None, version=None):
361
- """
362
- Returns a piece of Content.
363
- Example request URI(s):
364
- http://example.com/confluence/rest/api/content/1234?expand=space,body.view,version,container
365
- http://example.com/confluence/rest/api/content/1234?status=any
366
- :param page_id: Content ID
367
- :param status: (str) list of Content statuses to filter results on. Default value: [current]
368
- :param version: (int)
369
- :param expand: OPTIONAL: Default value: history,space,version
370
- We can also specify some extensions such as extensions.inlineProperties
371
- (for getting inline comment-specific properties) or extensions. Resolution
372
- for the resolution status of each comment in the results
373
- :return:
374
- """
375
- params = {}
376
- if expand:
377
- params["expand"] = expand
378
- if status:
379
- params["status"] = status
380
- if version:
381
- params["version"] = version
382
- url = f"rest/api/content/{page_id}"
383
-
384
- try:
385
- response = self.get(url, params=params)
386
- except HTTPError as e:
387
- if e.response.status_code == 404:
388
- # Raise ApiError as the documented reason is ambiguous
389
- raise ApiError(
390
- "There is no content with the given id, "
391
- "or the calling user does not have permission to view the content",
392
- reason=e,
393
- )
394
-
395
- raise
396
-
397
- return response
398
-
399
- def get_tables_from_page(self, page_id):
400
- """
401
- Fetches html tables added to confluence page
402
- :param page_id: integer confluence page_id
403
- :return: json object with page_id, number_of_tables_in_page
404
- and list of list tables_content representing scraped tables
405
- """
406
- try:
407
- page_content = self.get_page_by_id(page_id, expand="body.storage")["body"]["storage"]["value"]
408
-
409
- if page_content:
410
- tables_raw = [
411
- [[cell.text for cell in row("th") + row("td")] for row in table("tr")]
412
- for table in BeautifulSoup(page_content, features="lxml")("table")
413
- ]
414
- if len(tables_raw) > 0:
415
- return json.dumps(
416
- {
417
- "page_id": page_id,
418
- "number_of_tables_in_page": len(tables_raw),
419
- "tables_content": tables_raw,
420
- }
421
- )
422
- else:
423
- return {
424
- "No tables found for page: ": page_id,
425
- }
426
- else:
427
- return {"Page content is empty"}
428
- except HTTPError as e:
429
- if e.response.status_code == 404:
430
- # Raise ApiError as the documented reason is ambiguous
431
- log.error("Couldn't retrieve tables from page", page_id)
432
- raise ApiError(
433
- "There is no content with the given pageid, pageid params is not an integer "
434
- "or the calling user does not have permission to view the page",
435
- reason=e,
436
- )
437
- except Exception as e:
438
- log.error("Error occured", e)
439
-
440
- def scrap_regex_from_page(self, page_id, regex):
441
- """
442
- Method scraps regex patterns from a Confluence page_id.
443
-
444
- :param page_id: The ID of the Confluence page.
445
- :param regex: The regex pattern to scrape.
446
- :return: A list of regex matches.
447
- """
448
- regex_output = []
449
- page_output = self.get_page_by_id(page_id, expand="body.storage")["body"]["storage"]["value"]
450
- try:
451
- if page_output is not None:
452
- description_matches = [x.group(0) for x in re.finditer(regex, page_output)]
453
- if description_matches:
454
- regex_output.extend(description_matches)
455
- return regex_output
456
- except HTTPError as e:
457
- if e.response.status_code == 404:
458
- # Raise ApiError as the documented reason is ambiguous
459
- log.error("couldn't find page_id : ", page_id)
460
- raise ApiNotFoundError(
461
- "There is no content with the given page id,"
462
- "or the calling user does not have permission to view the page",
463
- reason=e,
464
- )
465
-
466
- def get_page_labels(self, page_id, prefix=None, start=None, limit=None):
467
- """
468
- Returns the list of labels on a piece of Content.
469
- :param page_id: A string containing the id of the labels content container.
470
- :param prefix: OPTIONAL: The prefixes to filter the labels with {@see Label.Prefix}.
471
- Default: None.
472
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
473
- :param limit: OPTIONAL: The limit of the number of labels to return, this may be restricted by
474
- fixed system limits. Default: 200.
475
- :return: The JSON data returned from the content/{id}/label endpoint, or the results of the
476
- callback. Will raise requests.HTTPError on bad input, potentially.
477
- """
478
- url = f"rest/api/content/{page_id}/label"
479
- params = {}
480
- if prefix:
481
- params["prefix"] = prefix
482
- if start is not None:
483
- params["start"] = int(start)
484
- if limit is not None:
485
- params["limit"] = int(limit)
486
-
487
- try:
488
- response = self.get(url, params=params)
489
- except HTTPError as e:
490
- if e.response.status_code == 404:
491
- # Raise ApiError as the documented reason is ambiguous
492
- raise ApiError(
493
- "There is no content with the given id, "
494
- "or the calling user does not have permission to view the content",
495
- reason=e,
496
- )
497
-
498
- raise
499
-
500
- return response
501
-
502
- def get_page_comments(
503
- self,
504
- content_id,
505
- expand=None,
506
- parent_version=None,
507
- start=0,
508
- limit=25,
509
- location=None,
510
- depth=None,
511
- ):
512
- """
513
-
514
- :param content_id:
515
- :param expand: extensions.inlineProperties,extensions.resolution
516
- :param parent_version:
517
- :param start:
518
- :param limit:
519
- :param location: inline or not
520
- :param depth:
521
- :return:
522
- """
523
- params = {"id": content_id, "start": start, "limit": limit}
524
- if expand:
525
- params["expand"] = expand
526
- if parent_version:
527
- params["parentVersion"] = parent_version
528
- if location:
529
- params["location"] = location
530
- if depth:
531
- params["depth"] = depth
532
- url = f"rest/api/content/{content_id}/child/comment"
533
-
534
- try:
535
- response = self.get(url, params=params)
536
- except HTTPError as e:
537
- if e.response.status_code == 404:
538
- # Raise ApiError as the documented reason is ambiguous
539
- raise ApiError(
540
- "There is no content with the given id, "
541
- "or the calling user does not have permission to view the content",
542
- reason=e,
543
- )
544
-
545
- raise
546
-
547
- return response
548
-
549
- def get_draft_page_by_id(self, page_id, status="draft", expand=None):
550
- """
551
- Gets content by id with status = draft
552
- :param page_id: Content ID
553
- :param status: (str) list of content statuses to filter results on. Default value: [draft]
554
- :param expand: OPTIONAL: Default value: history,space,version
555
- We can also specify some extensions such as extensions.inlineProperties
556
- (for getting inline comment-specific properties) or extensions. Resolution
557
- for the resolution status of each comment in the results
558
- :return:
559
- """
560
- # Version not passed since draft versions don't match the page and
561
- # operate differently between different collaborative modes
562
- return self.get_page_by_id(page_id=page_id, expand=expand, status=status)
563
-
564
- def get_all_pages_by_label(self, label, start=0, limit=50, expand=None):
565
- """
566
- Get all page by label
567
- :param label:
568
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
569
- :param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
570
- fixed system limits. Default: 50
571
- :param expand: OPTIONAL: a comma separated list of properties to expand on the content
572
- :return:
573
- """
574
- url = "rest/api/content/search"
575
- params = {}
576
- if label:
577
- params["cql"] = f'type={"page"} AND label="{label}"'
578
- if start:
579
- params["start"] = start
580
- if limit:
581
- params["limit"] = limit
582
- if expand:
583
- params["expand"] = expand
584
-
585
- try:
586
- response = self.get(url, params=params)
587
- except HTTPError as e:
588
- if e.response.status_code == 400:
589
- raise ApiValueError("The CQL is invalid or missing", reason=e)
590
-
591
- raise
592
-
593
- return response.get("results")
594
-
595
- def get_all_pages_from_space_raw(
596
- self,
597
- space,
598
- start=0,
599
- limit=50,
600
- status=None,
601
- expand=None,
602
- content_type="page",
603
- ):
604
- """
605
- Get all pages from space
606
-
607
- :param space:
608
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
609
- :param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
610
- fixed system limits. Default: 50
611
- :param status: OPTIONAL: list of statuses the content to be found is in.
612
- Defaults to current is not specified.
613
- If set to 'any', content in 'current' and 'trashed' status will be fetched.
614
- Does not support 'historical' status for now.
615
- :param expand: OPTIONAL: a comma separated list of properties to expand on the content.
616
- Default value: history,space,version.
617
- :param content_type: the content type to return. Default value: page. Valid values: page, blogpost.
618
- :return:
619
- """
620
- url = "rest/api/content"
621
- params = {}
622
- if space:
623
- params["spaceKey"] = space
624
- if start:
625
- params["start"] = start
626
- if limit:
627
- params["limit"] = limit
628
- if status:
629
- params["status"] = status
630
- if expand:
631
- params["expand"] = expand
632
- if content_type:
633
- params["type"] = content_type
634
-
635
- try:
636
- response = self.get(url, params=params)
637
- except HTTPError as e:
638
- if e.response.status_code == 404:
639
- raise ApiPermissionError(
640
- "The calling user does not have permission to view the content",
641
- reason=e,
642
- )
643
-
644
- raise
645
-
646
- return response
647
-
648
- def get_all_pages_from_space(
649
- self,
650
- space,
651
- start=0,
652
- limit=50,
653
- status=None,
654
- expand=None,
655
- content_type="page",
656
- ):
657
- """
658
- Retrieve all pages from a Confluence space.
659
-
660
- :param space: The space key to fetch pages from.
661
- :param start: OPTIONAL: The starting point of the collection. Default: 0.
662
- :param limit: OPTIONAL: The maximum number of pages per request. Default: 50.
663
- :param status: OPTIONAL: Filter pages by status ('current', 'trashed', 'any'). Default: None.
664
- :param expand: OPTIONAL: Comma-separated list of properties to expand. Default: history,space,version.
665
- :param content_type: OPTIONAL: The content type to return ('page', 'blogpost'). Default: page.
666
- :return: List containing all pages from the specified space.
667
- """
668
- all_pages = [] # Initialize an empty list to store all pages
669
- while True:
670
- # Fetch a single batch of pages
671
- response = self.get_all_pages_from_space_raw(
672
- space=space,
673
- start=start,
674
- limit=limit,
675
- status=status,
676
- expand=expand,
677
- content_type=content_type,
678
- )
679
-
680
- # Extract results from the response
681
- results = response.get("results", [])
682
- all_pages.extend(results) # Add the current batch of pages to the list
683
-
684
- # Break the loop if no more pages are available
685
- if len(results) <= limit:
686
- break
687
-
688
- # Increment the start index for the next batch
689
- start += limit
690
- return all_pages
691
-
692
- def get_all_pages_from_space_as_generator(
693
- self,
694
- space,
695
- start=0,
696
- limit=50,
697
- status=None,
698
- expand="history,space,version",
699
- content_type="page",
700
- ):
701
- """
702
- Retrieve all pages from a Confluence space using pagination.
703
-
704
- :param space: The space key to fetch pages from.
705
- :param start: OPTIONAL: The starting point of the collection. Default: 0.
706
- :param limit: OPTIONAL: The maximum number of pages per request. Default: 50.
707
- :param status: OPTIONAL: Filter pages by status ('current', 'trashed', 'any'). Default: None.
708
- :param expand: OPTIONAL: Comma-separated list of properties to expand. Default: history,space,version.
709
- :param content_type: OPTIONAL: The content type to return ('page', 'blogpost'). Default: page.
710
- :return: Generator yielding pages one by one.
711
- """
712
- while True:
713
- # Fetch a single batch of pages
714
- response = self.get_all_pages_from_space_raw(
715
- space=space,
716
- start=start,
717
- limit=limit,
718
- status=status,
719
- expand=expand,
720
- content_type=content_type,
721
- )
722
-
723
- # Extract results from the response
724
- results = response.get("results", [])
725
- yield from results # Yield each page individually
726
-
727
- # Break the loop if no more pages are available
728
- if len(results) < limit:
729
- break
730
- start += limit
731
- pass
732
-
733
- def get_all_pages_from_space_trash(self, space, start=0, limit=500, status="trashed", content_type="page"):
734
- """
735
- Get list of pages from trash
736
- :param space:
737
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
738
- :param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
739
- fixed system limits. Default: 500
740
- :param status:
741
- :param content_type: the content type to return. Default value: page. Valid values: page, blogpost.
742
- :return:
743
- """
744
- return self.get_all_pages_from_space(space, start, limit, status, content_type=content_type)
745
-
746
- def get_all_draft_pages_from_space(self, space, start=0, limit=500, status="draft"):
747
- """
748
- Get list of draft pages from space
749
- Use case is cleanup old drafts from Confluence
750
- :param space:
751
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
752
- :param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
753
- fixed system limits. Default: 500
754
- :param status:
755
- :return:
756
- """
757
- return self.get_all_pages_from_space(space, start, limit, status)
758
-
759
- def get_all_draft_pages_from_space_through_cql(self, space, start=0, limit=500, status="draft"):
760
- """
761
- Search list of draft pages by space key
762
- Use case is cleanup old drafts from Confluence
763
- :param space: Space Key
764
- :param status: Can be changed
765
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
766
- :param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
767
- fixed system limits. Default: 500
768
- :return:
769
- """
770
- url = f"rest/api/content?cql=space=spaceKey={space} and status={status}"
771
- params = {}
772
- if limit:
773
- params["limit"] = limit
774
- if start:
775
- params["start"] = start
776
-
777
- try:
778
- response = self.get(url, params=params)
779
- except HTTPError as e:
780
- if e.response.status_code == 404:
781
- raise ApiPermissionError(
782
- "The calling user does not have permission to view the content",
783
- reason=e,
784
- )
785
-
786
- raise
787
-
788
- return response.get("results")
789
-
790
- def get_all_pages_by_space_ids_confluence_cloud(
791
- self,
792
- space_ids,
793
- batch_size=250,
794
- sort=None,
795
- status=None,
796
- title=None,
797
- body_format=None,
798
- ):
799
- """
800
- Get all pages from a set of space ids:
801
- https://developer.atlassian.com/cloud/confluence/rest/v2/api-group-page/#api-pages-get
802
- :param space_ids: A Set of space IDs passed as a filter to Confluence
803
- :param batch_size: OPTIONAL: The batch size of pages to retrieve from confluence per request MAX is 250.
804
- Default: 250
805
- :param sort: OPTIONAL: The order the pages are retrieved in.
806
- Valid values:
807
- id, -id, created-date, -created-date, modified-date, -modified-date, title, -title
808
- :param status: OPTIONAL: Filter pages based on their status.
809
- Valid values: current, archived, deleted, trashed
810
- Default: current,archived
811
- :param title: OPTIONAL: Filter pages based on their title.
812
- :param body_format: OPTIONAL: The format of the body in the response. Valid values: storage, atlas_doc_format
813
- :return:
814
- """
815
- path = "/api/v2/pages"
816
- params = {}
817
- if space_ids:
818
- params["space-id"] = ",".join(space_ids)
819
- if batch_size:
820
- params["limit"] = batch_size
821
- if sort:
822
- params["sort"] = sort
823
- if status:
824
- params["status"] = status
825
- if title:
826
- params["title"] = title
827
- if body_format:
828
- params["body-format"] = body_format
829
-
830
- _all_pages = []
831
- try:
832
- while True:
833
- response = self.get(path, params=params)
834
-
835
- pages = response.get("results")
836
- _all_pages = _all_pages + pages
837
-
838
- links = response.get("_links")
839
- if links is not None and "next" in links:
840
- path = response["_links"]["next"].removeprefix("/wiki/")
841
- params = {}
842
- else:
843
- break
844
- except HTTPError as e:
845
- if e.response.status_code == 400:
846
- raise ApiValueError(
847
- "The configured params cannot be interpreted by Confluence"
848
- "Check the api documentation for valid values for status, expand, and sort params",
849
- reason=e,
850
- )
851
- if e.response.status_code == 401:
852
- raise HTTPError("Unauthorized (401)", response=response)
853
- raise
854
-
855
- return _all_pages
856
-
857
- @deprecated(version="2.4.2", reason="Use get_all_restrictions_for_content()")
858
- def get_all_restictions_for_content(self, content_id):
859
- """Let's use the get_all_restrictions_for_content()"""
860
- return self.get_all_restrictions_for_content(content_id=content_id)
861
-
862
- def get_all_restrictions_for_content(self, content_id):
863
- """
864
- Returns info about all restrictions by operation.
865
- :param content_id:
866
- :return: Return the raw json response
867
- """
868
- url = f"rest/api/content/{content_id}/restriction/byOperation"
869
- return self.get(url)
870
-
871
- def get_all_restrictions_from_page_json_rpc(self, page_id):
872
- """
873
- The JSON-RPC APIs for Confluence are provided here to help you browse and discover APIs you have access to.
874
- JSON-RPC APIs operate differently than REST APIs.
875
- To learn more about how to use these APIs,
876
- please refer to the Confluence JSON-RPC documentation on Atlassian Developers.
877
- """
878
- if self.api_version == "cloud" or self.cloud:
879
- return {}
880
- url = "rpc/json-rpc/confluenceservice-v2"
881
- data = {"jsonrpc": "2.0", "method": "getContentPermissionSets", "id": 9, "params": [page_id]}
882
- return self.post(url, data=data).get("result") or {}
883
-
884
- def update_restrictions_for_page_json_rpc(self, page_id, permission_type, content_permissions):
885
- """
886
- The JSON-RPC APIs for Confluence are provided here to help you browse and discover APIs you have access to.
887
- JSON-RPC APIs operate differently than REST APIs.
888
- To learn more about how to use these APIs,
889
- please refer to the Confluence JSON-RPC documentation on Atlassian Developers.
890
- """
891
- if self.api_version == "cloud" or self.cloud:
892
- return {}
893
- url = "rpc/json-rpc/confluenceservice-v2"
894
- data = {
895
- "jsonrpc": "2.0",
896
- "method": "setContentPermissions",
897
- "id": 9,
898
- "params": [page_id, permission_type, content_permissions],
899
- }
900
- return self.post(url, data=data).get("result") or {}
901
-
902
- def get_users_from_restricts_in_page_by_type(self, page_id: str, restriction_type: Literal["View", "Edit"]):
903
- page_name = self.get_page_by_id(page_id=page_id)["title"]
904
- restrictions_in_page = self.get_all_restrictions_from_page_json_rpc(page_id=page_id)
905
- try:
906
- if len(restrictions_in_page) > 0:
907
- for restriction_type_in_page in restrictions_in_page:
908
- if dict(restriction_type_in_page).get("type") == restriction_type:
909
- users = dict(restriction_type_in_page).get("contentPermissions")
910
- return users
911
- else:
912
- raise JsonRPCRestrictionsError(
913
- f'On page "{page_name}" has no restrictions type of "{restriction_type}"'
914
- )
915
- except JsonRPCError:
916
- raise
917
-
918
- def create_restricts_from_from_user(self, user_name: str, restriction_type: Literal["View", "Edit"]):
919
- content = {"type": restriction_type, "userName": user_name, "groupName": None}
920
-
921
- return content
922
-
923
- def add_user_in_restricted_page(self, user_name: str, page_id: str, restriction_type: Literal["View", "Edit"]):
924
- page_name = self.get_page_by_id(page_id=page_id).get("title")
925
- user_find_view_bool = False
926
- user_find_edit_bool = False
927
- users_content_view: list = self.get_users_from_restricts_in_page_by_type(
928
- page_id=page_id, restriction_type="View"
929
- )
930
- users_content_edit: list = self.get_users_from_restricts_in_page_by_type(
931
- page_id=page_id, restriction_type="Edit"
932
- )
933
- current_user_content_view: dict = self.create_restricts_from_from_user(
934
- user_name=user_name, restriction_type="View"
935
- )
936
- current_user_content_edit: dict = self.create_restricts_from_from_user(
937
- user_name=user_name, restriction_type="Edit"
938
- )
939
- try:
940
- if None not in [users_content_view, users_content_edit]:
941
- if users_content_view is not None:
942
- for user in users_content_view:
943
- if dict(user).get("userName") == current_user_content_view.get("userName"):
944
- user_find_view_bool = True
945
- if users_content_edit is not None:
946
- for user in users_content_edit:
947
- if dict(user).get("userName") == current_user_content_edit.get("userName"):
948
- user_find_edit_bool = True
949
- if restriction_type == "View":
950
- if user_find_view_bool is False:
951
- current_user_content = self.create_restricts_from_from_user(
952
- user_name=user_name, restriction_type=restriction_type
953
- )
954
- users_content_view.append(current_user_content)
955
- self.update_restrictions_for_page_json_rpc(
956
- page_id=page_id,
957
- permission_type=restriction_type,
958
- content_permissions=users_content_view,
959
- )
960
- elif user_find_view_bool:
961
- raise JsonRPCRestrictionsError(
962
- f'User "{user_name}" already have restrictions type of "{restriction_type}" on page "{page_name}"'
963
- )
964
- elif restriction_type == "Edit":
965
- if not user_find_edit_bool:
966
- current_user_content_view = self.create_restricts_from_from_user(
967
- user_name=user_name, restriction_type="View"
968
- )
969
- current_user_content_edit = self.create_restricts_from_from_user(
970
- user_name=user_name, restriction_type=restriction_type
971
- )
972
- users_content_view.append(current_user_content_view)
973
- users_content_edit.append(current_user_content_edit)
974
- self.update_restrictions_for_page_json_rpc(
975
- page_id=page_id, permission_type="View", content_permissions=users_content_view
976
- )
977
- self.update_restrictions_for_page_json_rpc(
978
- page_id=page_id, permission_type=restriction_type, content_permissions=users_content_edit
979
- )
980
- print(
981
- f'User "{user_name}" granted restrictions type of "{restriction_type}" on page "{page_name}"'
982
- )
983
- elif user_find_edit_bool:
984
- raise JsonRPCRestrictionsError(
985
- f'User "{user_name}" already have restrictions type of "{restriction_type}" on page "{page_name}"'
986
- )
987
- except JsonRPCError:
988
- raise
989
-
990
- def remove_user_from_restricted_page(self, user_name: str, page_id: str):
991
- page_name = self.get_page_by_id(page_id=page_id).get("title")
992
- user_find_bool = False
993
- users_content_view: list = self.get_users_from_restricts_in_page_by_type(
994
- page_id=page_id, restriction_type="View"
995
- )
996
- users_content_edit: list = self.get_users_from_restricts_in_page_by_type(
997
- page_id=page_id, restriction_type="Edit"
998
- )
999
- current_user_content_view = self.create_restricts_from_from_user(user_name=user_name, restriction_type="View")
1000
- current_user_content_edit = self.create_restricts_from_from_user(user_name=user_name, restriction_type="Edit")
1001
- for user_index, user_value in enumerate(users_content_view):
1002
- if dict(user_value).get("userName") == current_user_content_view.get("userName"):
1003
- user_find_bool = True
1004
- users_content_view.pop(user_index)
1005
- for user_index, user_value in enumerate(users_content_edit):
1006
- if dict(user_value).get("userName") == current_user_content_edit.get("userName"):
1007
- user_find_bool = True
1008
- users_content_edit.pop(user_index)
1009
- try:
1010
- if user_find_bool:
1011
- self.update_restrictions_for_page_json_rpc(
1012
- page_id=page_id, permission_type="View", content_permissions=users_content_view
1013
- )
1014
- self.update_restrictions_for_page_json_rpc(
1015
- page_id=page_id, permission_type="Edit", content_permissions=users_content_edit
1016
- )
1017
- print(f'User "{user_name}" has been deleted from restrictions on page "{page_name}"')
1018
- elif not user_find_bool:
1019
- raise JsonRPCRestrictionsError(
1020
- f'User "{user_name}" has not founded in restrictions on page "{page_name}"'
1021
- )
1022
- except JsonRPCError:
1023
- raise
1024
-
1025
- def remove_page_from_trash(self, page_id):
1026
- """
1027
- This method removes a page from trash
1028
- :param page_id:
1029
- :return:
1030
- """
1031
- return self.remove_page(page_id=page_id, status="trashed")
1032
-
1033
- def remove_page_as_draft(self, page_id):
1034
- """
1035
- This method removes a page from trash if it is a draft
1036
- :param page_id:
1037
- :return:
1038
- """
1039
- return self.remove_page(page_id=page_id, status="draft")
1040
-
1041
- def remove_content(self, content_id):
1042
- """
1043
- Remove any content
1044
- :param content_id:
1045
- :return:
1046
- """
1047
- try:
1048
- response = self.delete(f"rest/api/content/{content_id}")
1049
- except HTTPError as e:
1050
- if e.response.status_code == 404:
1051
- # Raise ApiError as the documented reason is ambiguous
1052
- raise ApiError(
1053
- "There is no content with the given id, or the calling "
1054
- "user does not have permission to trash or purge the content",
1055
- reason=e,
1056
- )
1057
- if e.response.status_code == 409:
1058
- raise ApiConflictError(
1059
- "There is a stale data object conflict when trying to delete a draft",
1060
- reason=e,
1061
- )
1062
-
1063
- raise
1064
-
1065
- return response
1066
-
1067
- def remove_page(self, page_id, status=None, recursive=False):
1068
- """
1069
- This method removes a page, if it has recursive flag, method removes including child pages
1070
- :param page_id:
1071
- :param status: OPTIONAL: type of page
1072
- :param recursive: OPTIONAL: if True - will recursively delete all children pages too
1073
- :return:
1074
- """
1075
- url = f"rest/api/content/{page_id}"
1076
- if recursive:
1077
- children_pages = self.get_page_child_by_type(page_id)
1078
- for children_page in children_pages:
1079
- self.remove_page(children_page.get("id"), status, recursive)
1080
- params = {}
1081
- if status:
1082
- params["status"] = status
1083
-
1084
- try:
1085
- response = self.delete(url, params=params)
1086
- except HTTPError as e:
1087
- if e.response.status_code == 404:
1088
- # Raise ApiError as the documented reason is ambiguous
1089
- raise ApiError(
1090
- "There is no content with the given id, or the calling "
1091
- "user does not have permission to trash or purge the content",
1092
- reason=e,
1093
- )
1094
- if e.response.status_code == 409:
1095
- raise ApiConflictError(
1096
- "There is a stale data object conflict when trying to delete a draft",
1097
- reason=e,
1098
- )
1099
-
1100
- raise
1101
-
1102
- return response
1103
-
1104
- def create_page(
1105
- self,
1106
- space,
1107
- title,
1108
- body,
1109
- parent_id=None,
1110
- type="page",
1111
- representation="storage",
1112
- editor=None,
1113
- full_width=False,
1114
- status="current",
1115
- ):
1116
- """
1117
- Create page from scratch
1118
- :param space:
1119
- :param title:
1120
- :param body:
1121
- :param parent_id:
1122
- :param type:
1123
- :param representation: OPTIONAL: either Confluence 'storage' or 'wiki' markup format
1124
- :param editor: OPTIONAL: v2 to be created in the new editor
1125
- :param full_width: DEFAULT: False
1126
- :param status: either 'current' or 'draft'
1127
- :return:
1128
- """
1129
- log.info('Creating %s "%s" -> "%s"', type, space, title)
1130
- url = "rest/api/content/"
1131
- data = {
1132
- "type": type,
1133
- "title": title,
1134
- "status": status,
1135
- "space": {"key": space},
1136
- "body": self._create_body(body, representation),
1137
- "metadata": {"properties": {}},
1138
- }
1139
- if parent_id:
1140
- data["ancestors"] = [{"type": type, "id": parent_id}]
1141
- if editor is not None and editor in ["v1", "v2"]:
1142
- data["metadata"]["properties"]["editor"] = {"value": editor}
1143
- if full_width is True:
1144
- data["metadata"]["properties"]["content-appearance-draft"] = {"value": "full-width"}
1145
- data["metadata"]["properties"]["content-appearance-published"] = {"value": "full-width"}
1146
- else:
1147
- data["metadata"]["properties"]["content-appearance-draft"] = {"value": "fixed-width"}
1148
- data["metadata"]["properties"]["content-appearance-published"] = {"value": "fixed-width"}
1149
-
1150
- try:
1151
- response = self.post(url, data=data)
1152
- except HTTPError as e:
1153
- if e.response.status_code == 404:
1154
- raise ApiPermissionError(
1155
- "The calling user does not have permission to view the content",
1156
- reason=e,
1157
- )
1158
-
1159
- raise
1160
-
1161
- return response
1162
-
1163
- def move_page(
1164
- self,
1165
- space_key,
1166
- page_id,
1167
- target_id=None,
1168
- target_title=None,
1169
- position="append",
1170
- ):
1171
- """
1172
- Move page method
1173
- :param space_key:
1174
- :param page_id:
1175
- :param target_title:
1176
- :param target_id:
1177
- :param position: topLevel or append , above, below
1178
- :return:
1179
- """
1180
- url = "/pages/movepage.action"
1181
- params = {"spaceKey": space_key, "pageId": page_id}
1182
- if target_title:
1183
- params["targetTitle"] = target_title
1184
- if target_id:
1185
- params["targetId"] = target_id
1186
- if position:
1187
- params["position"] = position
1188
- return self.post(url, params=params, headers=self.no_check_headers)
1189
-
1190
- def create_or_update_template(
1191
- self,
1192
- name,
1193
- body,
1194
- template_type="page",
1195
- template_id=None,
1196
- description=None,
1197
- labels=None,
1198
- space=None,
1199
- ):
1200
- """
1201
- Creates a new or updates an existing content template.
1202
-
1203
- Note, blueprint templates cannot be created or updated via the REST API.
1204
-
1205
- If you provide a ``template_id`` then this method will update the template with the provided settings.
1206
- If no ``template_id`` is provided, then this method assumes you are creating a new template.
1207
-
1208
- :param str name: If creating, the name of the new template. If updating, the name to change
1209
- the template name to. Set to the current name if this field is not being updated.
1210
- :param dict body: This object is used when creating or updating content.
1211
- {
1212
- "storage": {
1213
- "value": "<string>",
1214
- "representation": "view"
1215
- }
1216
- }
1217
- :param str template_type: OPTIONAL: The type of the new template. Default: "page".
1218
- :param str template_id: OPTIONAL: The ID of the template being updated. REQUIRED if updating a template.
1219
- :param str description: OPTIONAL: A description of the new template. Max length 255.
1220
- :param list labels: OPTIONAL: Labels for the new template. An array like:
1221
- [
1222
- {
1223
- "prefix": "<string>",
1224
- "name": "<string>",
1225
- "id": "<string>",
1226
- "label": "<string>",
1227
- }
1228
- ]
1229
- :param dict space: OPTIONAL: The key for the space of the new template. Only applies to space templates.
1230
- If not specified, the template will be created as a global template.
1231
- :return:
1232
- """
1233
- data = {"name": name, "templateType": template_type, "body": body}
1234
-
1235
- if description:
1236
- data["description"] = description
1237
-
1238
- if labels:
1239
- data["labels"] = labels
1240
-
1241
- if space:
1242
- data["space"] = {"key": space}
1243
-
1244
- if template_id:
1245
- data["templateId"] = template_id
1246
- return self.put("rest/api/template", data=json.dumps(data))
1247
-
1248
- return self.post("rest/api/template", json=data)
1249
-
1250
- @deprecated(version="3.7.0", reason="Use get_content_template()")
1251
- def get_template_by_id(self, template_id):
1252
- """
1253
- Get user template by id. Experimental API
1254
- Use case is get template body and create page from that
1255
- """
1256
- url = f"rest/experimental/template/{template_id}"
1257
-
1258
- try:
1259
- response = self.get(url)
1260
- except HTTPError as e:
1261
- if e.response.status_code == 403:
1262
- # Raise ApiError as the documented reason is ambiguous
1263
- raise ApiError(
1264
- "There is no content with the given id, "
1265
- "or the calling user does not have permission to view the content",
1266
- reason=e,
1267
- )
1268
-
1269
- raise
1270
- return response
1271
-
1272
- def get_content_template(self, template_id):
1273
- """
1274
- Get a content template.
1275
-
1276
- This includes information about the template, like the name, the space or blueprint
1277
- that the template is in, the body of the template, and more.
1278
- :param str template_id: The ID of the content template to be returned
1279
- :return:
1280
- """
1281
- url = f"rest/api/template/{template_id}"
1282
-
1283
- try:
1284
- response = self.get(url)
1285
- except HTTPError as e:
1286
- if e.response.status_code == 403:
1287
- # Raise ApiError as the documented reason is ambiguous
1288
- raise ApiError(
1289
- "There is no content with the given id, "
1290
- "or the calling user does not have permission to view the content",
1291
- reason=e,
1292
- )
1293
-
1294
- raise
1295
-
1296
- return response
1297
-
1298
- @deprecated(version="3.7.0", reason="Use get_blueprint_templates()")
1299
- def get_all_blueprints_from_space(self, space, start=0, limit=None, expand=None):
1300
- """
1301
- Get all users blueprints from space. Experimental API
1302
- :param space: Space Key
1303
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
1304
- :param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
1305
- fixed system limits. Default: 20
1306
- :param expand: OPTIONAL: expand e.g. body
1307
- """
1308
- url = "rest/experimental/template/blueprint"
1309
- params = {}
1310
- if space:
1311
- params["spaceKey"] = space
1312
- if start:
1313
- params["start"] = start
1314
- if limit:
1315
- params["limit"] = limit
1316
- if expand:
1317
- params["expand"] = expand
1318
-
1319
- try:
1320
- response = self.get(url, params=params)
1321
- except HTTPError as e:
1322
- if e.response.status_code == 403:
1323
- raise ApiPermissionError(
1324
- "The calling user does not have permission to view the content",
1325
- reason=e,
1326
- )
1327
-
1328
- raise
1329
-
1330
- return response.get("results") or []
1331
-
1332
- def get_blueprint_templates(self, space=None, start=0, limit=None, expand=None):
1333
- """
1334
- Gets all templates provided by blueprints.
1335
-
1336
- Use this method to retrieve all global blueprint templates or all blueprint templates in a space.
1337
- :param space: OPTIONAL: The key of the space to be queried for templates. If ``space`` is not
1338
- specified, global blueprint templates will be returned.
1339
- :param start: OPTIONAL: The starting index of the returned templates. Default: None (0).
1340
- :param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
1341
- fixed system limits. Default: 25
1342
- :param expand: OPTIONAL: A multi-value parameter indicating which properties of the template to expand.
1343
- """
1344
- url = "rest/api/template/blueprint"
1345
- params = {}
1346
- if space:
1347
- params["spaceKey"] = space
1348
- if start:
1349
- params["start"] = start
1350
- if limit:
1351
- params["limit"] = limit
1352
- if expand:
1353
- params["expand"] = expand
1354
-
1355
- try:
1356
- response = self.get(url, params=params)
1357
- except HTTPError as e:
1358
- if e.response.status_code == 403:
1359
- raise ApiPermissionError(
1360
- "The calling user does not have permission to view the content",
1361
- reason=e,
1362
- )
1363
-
1364
- raise
1365
-
1366
- return response.get("results") or []
1367
-
1368
- @deprecated(version="3.7.0", reason="Use get_content_templates()")
1369
- def get_all_templates_from_space(self, space, start=0, limit=None, expand=None):
1370
- """
1371
- Get all users templates from space. Experimental API
1372
- ref: https://docs.atlassian.com/atlassian-confluence/1000.73.0/com/atlassian/confluence/plugins/restapi\
1373
- /resources/TemplateResource.html
1374
- :param space: Space Key
1375
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
1376
- :param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
1377
- fixed system limits. Default: 20
1378
- :param expand: OPTIONAL: expand e.g. body
1379
- """
1380
- url = "rest/experimental/template/page"
1381
- params = {}
1382
- if space:
1383
- params["spaceKey"] = space
1384
- if start:
1385
- params["start"] = start
1386
- if limit:
1387
- params["limit"] = limit
1388
- if expand:
1389
- params["expand"] = expand
1390
-
1391
- try:
1392
- response = self.get(url, params=params)
1393
- except HTTPError as e:
1394
- if e.response.status_code == 403:
1395
- raise ApiPermissionError(
1396
- "The calling user does not have permission to view the content",
1397
- reason=e,
1398
- )
1399
- raise
1400
-
1401
- return response.get("results") or []
1402
-
1403
- def get_content_templates(self, space=None, start=0, limit=None, expand=None):
1404
- """
1405
- Get all content templates.
1406
- Use this method to retrieve all global content templates or all content templates in a space.
1407
- :param space: OPTIONAL: The key of the space to be queried for templates. If ``space`` is not
1408
- specified, global templates will be returned.
1409
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
1410
- :param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
1411
- fixed system limits. Default: 25
1412
- :param expand: OPTIONAL: A multi-value parameter indicating which properties of the template to expand.
1413
- e.g. ``body``
1414
- """
1415
- url = "rest/api/template/page"
1416
- params = {}
1417
- if space:
1418
- params["spaceKey"] = space
1419
- if start:
1420
- params["start"] = start
1421
- if limit:
1422
- params["limit"] = limit
1423
- if expand:
1424
- params["expand"] = expand
1425
-
1426
- try:
1427
- response = self.get(url, params=params)
1428
- except HTTPError as e:
1429
- if e.response.status_code == 403:
1430
- raise ApiPermissionError(
1431
- "The calling user does not have permission to view the content",
1432
- reason=e,
1433
- )
1434
-
1435
- raise
1436
-
1437
- return response.get("results") or []
1438
-
1439
- def remove_template(self, template_id):
1440
- """
1441
- Deletes a template.
1442
-
1443
- This results in different actions depending on the type of template:
1444
- * If the template is a content template, it is deleted.
1445
- * If the template is a modified space-level blueprint template, it reverts to the template
1446
- inherited from the global-level blueprint template.
1447
- * If the template is a modified global-level blueprint template, it reverts to the default
1448
- global-level blueprint template.
1449
- Note: Unmodified blueprint templates cannot be deleted.
1450
-
1451
- :param str template_id: The ID of the template to be deleted.
1452
- :return:
1453
- """
1454
- return self.delete(f"rest/api/template/{template_id}")
1455
-
1456
- def get_all_spaces(
1457
- self,
1458
- start=0,
1459
- limit=50,
1460
- expand=None,
1461
- space_type=None,
1462
- space_status=None,
1463
- ):
1464
- """
1465
- Get all spaces with provided limit
1466
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
1467
- :param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
1468
- fixed system limits. Default: 500
1469
- :param space_type: OPTIONAL: Filter the list of spaces returned by type (global, personal)
1470
- :param space_status: OPTIONAL: Filter the list of spaces returned by status (current, archived)
1471
- :param expand: OPTIONAL: additional info, e.g. metadata, icon, description, homepage
1472
- """
1473
- url = "rest/api/space"
1474
- params = {}
1475
- if start:
1476
- params["start"] = start
1477
- if limit:
1478
- params["limit"] = limit
1479
- if expand:
1480
- params["expand"] = expand
1481
- if space_type:
1482
- params["type"] = space_type
1483
- if space_status:
1484
- params["status"] = space_status
1485
- return self.get(url, params=params)
1486
-
1487
- def archive_space(self, space_key):
1488
- """
1489
- Archive space
1490
- :param space_key:
1491
- :return:
1492
- """
1493
- url = f"rest/api/space/{space_key}/archive"
1494
- return self.put(url)
1495
-
1496
- def get_trashed_contents_by_space(self, space_key, cursor=None, expand=None, limit=100):
1497
- """
1498
- Get trashed contents by space
1499
- :param space_key:
1500
- :param cursor:
1501
- :param expand:
1502
- :param limit:
1503
- :return:
1504
- """
1505
- url = f"rest/api/space/{space_key}/content/trash"
1506
- params = {"limit": limit}
1507
- if cursor:
1508
- params["cursor"] = cursor
1509
- if expand:
1510
- params["expand"] = expand
1511
- return self.get(url, params=params)
1512
-
1513
- def remove_trashed_contents_by_space(self, space_key):
1514
- """
1515
- Remove all content from the trash in the given space,
1516
- deleting them permanently.Example request URI:
1517
- :param space_key:
1518
- :return:
1519
- """
1520
- url = f"rest/api/space/{space_key}/content/trash"
1521
- return self.delete(url)
1522
-
1523
- def add_comment(self, page_id, text):
1524
- """
1525
- Add comment into page
1526
- :param page_id
1527
- :param text
1528
- """
1529
- data = {
1530
- "type": "comment",
1531
- "container": {"id": page_id, "type": "page", "status": "current"},
1532
- "body": self._create_body(text, "storage"),
1533
- }
1534
-
1535
- try:
1536
- response = self.post("rest/api/content/", data=data)
1537
- except HTTPError as e:
1538
- if e.response.status_code == 404:
1539
- raise ApiPermissionError(
1540
- "The calling user does not have permission to view the content",
1541
- reason=e,
1542
- )
1543
-
1544
- raise
1545
-
1546
- return response
1547
-
1548
- def attach_content(
1549
- self,
1550
- content,
1551
- name,
1552
- content_type="application/binary",
1553
- page_id=None,
1554
- title=None,
1555
- space=None,
1556
- comment=None,
1557
- ):
1558
- """
1559
- Attach (upload) a file to a page, if it exists it will update automatically the
1560
- version the new file and keep the old one.
1561
- :param title: The page name
1562
- :type title: ``str``
1563
- :param space: The space name
1564
- :type space: ``str``
1565
- :param page_id: The page id to which we would like to upload the file
1566
- :type page_id: ``str``
1567
- :param name: The name of the attachment
1568
- :type name: ``str``
1569
- :param content: Contains the content which should be uploaded
1570
- :type content: ``binary``
1571
- :param content_type: Specify the HTTP content type.
1572
- The default is "application/binary"
1573
- :type content_type: ``str``
1574
- :param comment: A comment describing this upload/file
1575
- :type comment: ``str``
1576
- """
1577
- page_id = self.get_page_id(space=space, title=title) if page_id is None else page_id
1578
- type = "attachment"
1579
- if page_id is not None:
1580
- comment = comment if comment else f"Uploaded {name}."
1581
- data = {
1582
- "type": type,
1583
- "fileName": name,
1584
- "contentType": content_type,
1585
- "comment": comment,
1586
- "minorEdit": "true",
1587
- }
1588
- headers = {
1589
- "X-Atlassian-Token": "no-check",
1590
- "Accept": "application/json",
1591
- }
1592
- path = f"rest/api/content/{page_id}/child/attachment"
1593
- # Check if there is already a file with the same name
1594
- attachments = self.get(path=path, headers=headers, params={"filename": name})
1595
- if attachments.get("size"):
1596
- path = path + "/" + attachments["results"][0]["id"] + "/data"
1597
-
1598
- try:
1599
- response = self.post(
1600
- path=path,
1601
- data=data,
1602
- headers=headers,
1603
- files={"file": (name, content, content_type)},
1604
- )
1605
- except HTTPError as e:
1606
- if e.response.status_code == 403:
1607
- # Raise ApiError as the documented reason is ambiguous
1608
- raise ApiError(
1609
- "Attachments are disabled or the calling user does "
1610
- "not have permission to add attachments to this content",
1611
- reason=e,
1612
- )
1613
- if e.response.status_code == 404:
1614
- # Raise ApiError as the documented reason is ambiguous
1615
- raise ApiError(
1616
- "The requested content is not found, the user does not have "
1617
- "permission to view it, or the attachments exceeds the maximum "
1618
- "configured attachment size",
1619
- reason=e,
1620
- )
1621
-
1622
- raise
1623
-
1624
- return response
1625
- else:
1626
- log.warning("No 'page_id' found, not uploading attachments")
1627
- return None
1628
-
1629
- def attach_file(
1630
- self,
1631
- filename,
1632
- name=None,
1633
- content_type=None,
1634
- page_id=None,
1635
- title=None,
1636
- space=None,
1637
- comment=None,
1638
- ):
1639
- """
1640
- Attach (upload) a file to a page, if it exists it will update automatically the
1641
- version the new file and keep the old one.
1642
- :param title: The page name
1643
- :type title: ``str``
1644
- :param space: The space name
1645
- :type space: ``str``
1646
- :param page_id: The page id to which we would like to upload the file
1647
- :type page_id: ``str``
1648
- :param filename: The file to upload (Specifies the content)
1649
- :type filename: ``str``
1650
- :param name: Specifies name of the attachment. This parameter is optional.
1651
- Is no name give the file name is used as name
1652
- :type name: ``str``
1653
- :param content_type: Specify the HTTP content type. The default is
1654
- The default is "application/binary"
1655
- :type content_type: ``str``
1656
- :param comment: A comment describing this upload/file
1657
- :type comment: ``str``
1658
- """
1659
- # get base name of the file to get the attachment from confluence.
1660
- if name is None:
1661
- name = os.path.basename(filename)
1662
- if content_type is None:
1663
- extension = os.path.splitext(filename)[-1]
1664
- content_type = self.content_types.get(extension, "application/binary")
1665
-
1666
- with open(filename, "rb") as infile:
1667
- return self.attach_content(
1668
- infile,
1669
- name,
1670
- content_type,
1671
- page_id=page_id,
1672
- title=title,
1673
- space=space,
1674
- comment=comment,
1675
- )
1676
-
1677
- def download_attachments_from_page(self, page_id, path=None, start=0, limit=50, filename=None, to_memory=False):
1678
- """
1679
- Downloads attachments from a Confluence page. Supports downloading all files or a specific file.
1680
- Files can either be saved to disk or returned as BytesIO objects for in-memory handling.
1681
-
1682
- :param page_id: str
1683
- The ID of the Confluence page to fetch attachments from.
1684
- :param path: str, optional
1685
- Directory where attachments will be saved. If None, defaults to the current working directory.
1686
- Ignored if `to_memory` is True.
1687
- :param start: int, optional
1688
- The start point for paginated attachment fetching. Default is 0. Ignored if `filename` is specified.
1689
- :param limit: int, optional
1690
- The maximum number of attachments to fetch per request. Default is 50. Ignored if `filename` is specified.
1691
- :param filename: str, optional
1692
- The name of a specific file to download. If provided, only this file will be fetched.
1693
- :param to_memory: bool, optional
1694
- If True, attachments are returned as a dictionary of {filename: BytesIO object}.
1695
- If False, files are written to the specified directory on disk.
1696
- :return:
1697
- - If `to_memory` is True, returns a dictionary {filename: BytesIO object}.
1698
- - If `to_memory` is False, returns a summary dict: {"attachments_downloaded": int, "path": str}.
1699
- :raises:
1700
- - FileNotFoundError: If the specified path does not exist.
1701
- - PermissionError: If there are permission issues with the specified path.
1702
- - requests.HTTPError: If the HTTP request to fetch an attachment fails.
1703
- - Exception: For any unexpected errors.
1704
- """
1705
- # Default path to current working directory if not provided
1706
- if not to_memory and path is None:
1707
- path = os.getcwd()
1708
-
1709
- try:
1710
- # Fetch attachments based on the specified parameters
1711
- if filename:
1712
- # Fetch specific file by filename
1713
- attachments = self.get_attachments_from_content(page_id=page_id, filename=filename)["results"]
1714
- if not attachments:
1715
- return f"No attachment with filename '{filename}' found on the page."
1716
- else:
1717
- # Fetch all attachments with pagination
1718
- attachments = self.get_attachments_from_content(page_id=page_id, start=start, limit=limit)["results"]
1719
- if not attachments:
1720
- return "No attachments found on the page."
1721
-
1722
- # Prepare to handle downloads
1723
- downloaded_files = {}
1724
- for attachment in attachments:
1725
- file_name = attachment["title"] or attachment["id"] # Use attachment ID if title is unavailable
1726
- download_link = attachment["_links"]["download"]
1727
- # Fetch the file content
1728
- response = self.get(str(download_link), not_json_response=True)
1729
-
1730
- if to_memory:
1731
- # Store in BytesIO object
1732
- file_obj = io.BytesIO(response)
1733
- downloaded_files[file_name] = file_obj
1734
- else:
1735
- # Sanitize filename if needed
1736
- if re.search(r'[<>:"/\\|?*\x00-\x1F]', file_name):
1737
- sanitized = re.sub(r'[<>:"/\\|?*\x00-\x1F]', "_", file_name)
1738
- warnings.warn(
1739
- f"File name '{file_name}' contained invalid characters and was renamed to '{sanitized}'.",
1740
- UserWarning,
1741
- )
1742
- file_name = sanitized
1743
- file_path = os.path.join(path, file_name)
1744
- # Save file to disk
1745
- file_path = os.path.join(path, file_name)
1746
- with open(file_path, "wb") as file:
1747
- file.write(response)
1748
-
1749
- # Return results based on storage mode
1750
- if to_memory:
1751
- return downloaded_files
1752
- else:
1753
- return {"attachments_downloaded": len(attachments), "path": path}
1754
- except NotADirectoryError:
1755
- raise FileNotFoundError(f"The directory '{path}' does not exist.")
1756
- except PermissionError:
1757
- raise PermissionError(f"Permission denied when trying to save files to '{path}'.")
1758
- except requests.HTTPError as http_err:
1759
- raise requests.HTTPError(
1760
- f"HTTP error occurred while downloading attachments: {http_err}",
1761
- response=http_err.response,
1762
- request=http_err.request,
1763
- )
1764
- except Exception as err:
1765
- raise Exception(f"An unexpected error occurred: {err}")
1766
-
1767
- def delete_attachment(self, page_id, filename, version=None):
1768
- """
1769
- Remove completely a file if version is None or delete version
1770
- :param version:
1771
- :param page_id: file version
1772
- :param filename:
1773
- :return:
1774
- """
1775
- params = {"pageId": page_id, "fileName": filename}
1776
- if version:
1777
- params["version"] = version
1778
- return self.post(
1779
- "json/removeattachment.action",
1780
- params=params,
1781
- headers=self.form_token_headers,
1782
- )
1783
-
1784
- def delete_attachment_by_id(self, attachment_id, version):
1785
- """
1786
- Remove completely a file if version is None or delete version
1787
- :param attachment_id:
1788
- :param version: file version
1789
- :return:
1790
- """
1791
- if self.cloud:
1792
- url = f"rest/api/content/{attachment_id}/version/{version}"
1793
- else:
1794
- url = f"rest/experimental/content/{attachment_id}/version/{version}"
1795
- return self.delete(url)
1796
-
1797
- def remove_page_attachment_keep_version(self, page_id, filename, keep_last_versions):
1798
- """
1799
- Keep last versions
1800
- :param filename:
1801
- :param page_id:
1802
- :param keep_last_versions:
1803
- :return:
1804
- """
1805
- attachment = self.get_attachments_from_content(page_id=page_id, expand="version", filename=filename).get(
1806
- "results"
1807
- )[0]
1808
- attachment_versions = self.get_attachment_history(attachment.get("id"))
1809
- while len(attachment_versions) > keep_last_versions:
1810
- remove_version_attachment_number = attachment_versions[keep_last_versions].get("number")
1811
- self.delete_attachment_by_id(
1812
- attachment_id=attachment.get("id"),
1813
- version=remove_version_attachment_number,
1814
- )
1815
- log.info(
1816
- "Removed oldest version for %s, now versions equal more than %s",
1817
- attachment.get("title"),
1818
- len(attachment_versions),
1819
- )
1820
- attachment_versions = self.get_attachment_history(attachment.get("id"))
1821
- log.info("Kept versions %s for %s", keep_last_versions, attachment.get("title"))
1822
-
1823
- def get_attachment_history(self, attachment_id, limit=200, start=0):
1824
- """
1825
- Get attachment history
1826
- :param attachment_id
1827
- :param limit
1828
- :param start
1829
- :return
1830
- """
1831
- params = {"limit": limit, "start": start}
1832
- if self.cloud:
1833
- url = f"rest/api/content/{attachment_id}/version"
1834
- else:
1835
- url = f"rest/experimental/content/{attachment_id}/version"
1836
- return (self.get(url, params=params) or {}).get("results")
1837
-
1838
- # @todo prepare more attachments info
1839
- def get_attachments_from_content(
1840
- self,
1841
- page_id,
1842
- start=0,
1843
- limit=50,
1844
- expand=None,
1845
- filename=None,
1846
- media_type=None,
1847
- ):
1848
- """
1849
- Get attachments for page
1850
- :param page_id:
1851
- :param start:
1852
- :param limit:
1853
- :param expand:
1854
- :param filename:
1855
- :param media_type:
1856
- :return:
1857
- """
1858
- params = {}
1859
- if start:
1860
- params["start"] = start
1861
- if limit:
1862
- params["limit"] = limit
1863
- if expand:
1864
- params["expand"] = expand
1865
- if filename:
1866
- params["filename"] = filename
1867
- if media_type:
1868
- params["mediaType"] = media_type
1869
- url = f"rest/api/content/{page_id}/child/attachment"
1870
-
1871
- try:
1872
- response = self.get(url, params=params)
1873
- except HTTPError as e:
1874
- if e.response.status_code == 404:
1875
- # Raise ApiError as the documented reason is ambiguous
1876
- raise ApiError(
1877
- "There is no content with the given id, "
1878
- "or the calling user does not have permission to view the content",
1879
- reason=e,
1880
- )
1881
-
1882
- raise
1883
-
1884
- return response
1885
-
1886
- def set_page_label(self, page_id, label):
1887
- """
1888
- Set a label on the page
1889
- :param page_id: content_id format
1890
- :param label: label to add
1891
- :return:
1892
- """
1893
- url = f"rest/api/content/{page_id}/label"
1894
- data = {"prefix": "global", "name": label}
1895
-
1896
- try:
1897
- response = self.post(path=url, data=data)
1898
- except HTTPError as e:
1899
- if e.response.status_code == 404:
1900
- # Raise ApiError as the documented reason is ambiguous
1901
- raise ApiError(
1902
- "There is no content with the given id, "
1903
- "or the calling user does not have permission to view the content",
1904
- reason=e,
1905
- )
1906
-
1907
- raise
1908
-
1909
- return response
1910
-
1911
- def remove_page_label(self, page_id: str, label: str):
1912
- """
1913
- Delete Confluence page label
1914
- :param page_id: content_id format
1915
- :param label: label name
1916
- :return:
1917
- """
1918
- url = f"rest/api/content/{page_id}/label"
1919
- params = {"id": page_id, "name": label}
1920
-
1921
- try:
1922
- response = self.delete(path=url, params=params)
1923
- except HTTPError as e:
1924
- if e.response.status_code == 403:
1925
- raise ApiPermissionError(
1926
- "The user has view permission, " "but no edit permission to the content",
1927
- reason=e,
1928
- )
1929
- if e.response.status_code == 404:
1930
- # Raise ApiError as the documented reason is ambiguous
1931
- raise ApiError(
1932
- "The content or label doesn't exist, "
1933
- "or the calling user doesn't have view permission to the content",
1934
- reason=e,
1935
- )
1936
-
1937
- raise
1938
-
1939
- return response
1940
-
1941
- def history(self, page_id):
1942
- url = f"rest/api/content/{page_id}/history"
1943
- try:
1944
- response = self.get(url)
1945
- except HTTPError as e:
1946
- if e.response.status_code == 404:
1947
- # Raise ApiError as the documented reason is ambiguous
1948
- raise ApiError(
1949
- "There is no content with the given id, "
1950
- "or the calling user does not have permission to view the content",
1951
- reason=e,
1952
- )
1953
-
1954
- raise
1955
-
1956
- return response
1957
-
1958
- def get_content_history(self, content_id):
1959
- return self.history(content_id)
1960
-
1961
- def get_content_history_by_version_number(self, content_id, version_number):
1962
- """
1963
- Get content history by version number
1964
- :param content_id:
1965
- :param version_number:
1966
- :return:
1967
- """
1968
- if self.cloud:
1969
- url = f"rest/api/content/{content_id}/version/{version_number}"
1970
- else:
1971
- url = f"rest/experimental/content/{content_id}/version/{version_number}"
1972
- return self.get(url)
1973
-
1974
- def remove_content_history(self, page_id, version_number):
1975
- """
1976
- Remove content history. It works as experimental method
1977
- :param page_id:
1978
- :param version_number: version number
1979
- :return:
1980
- """
1981
- if self.cloud:
1982
- url = f"rest/api/content/{page_id}/version/{version_number}"
1983
- else:
1984
- url = f"rest/experimental/content/{page_id}/version/{version_number}"
1985
- self.delete(url)
1986
-
1987
- def remove_page_history(self, page_id, version_number):
1988
- """
1989
- Remove content history. It works as experimental method
1990
- :param page_id:
1991
- :param version_number: version number
1992
- :return:
1993
- """
1994
- self.remove_content_history(page_id, version_number)
1995
-
1996
- def remove_content_history_in_cloud(self, page_id, version_id):
1997
- """
1998
- Remove content history. It works in CLOUD
1999
- :param page_id:
2000
- :param version_id:
2001
- :return:
2002
- """
2003
- url = f"rest/api/content/{page_id}/version/{version_id}"
2004
- self.delete(url)
2005
-
2006
- def remove_page_history_keep_version(self, page_id, keep_last_versions):
2007
- """
2008
- Keep last versions
2009
- :param page_id:
2010
- :param keep_last_versions:
2011
- :return:
2012
- """
2013
- page = self.get_page_by_id(page_id=page_id, expand="version")
2014
- page_number = page.get("version").get("number")
2015
- while page_number > keep_last_versions:
2016
- self.remove_page_history(page_id=page_id, version_number=1)
2017
- page = self.get_page_by_id(page_id=page_id, expand="version")
2018
- page_number = page.get("version").get("number")
2019
- log.info("Removed oldest version for %s, now it's %s", page.get("title"), page_number)
2020
- log.info("Kept versions %s for %s", keep_last_versions, page.get("title"))
2021
-
2022
- def has_unknown_attachment_error(self, page_id):
2023
- """
2024
- Check has unknown attachment error on page
2025
- :param page_id:
2026
- :return:
2027
- """
2028
- unknown_attachment_identifier = "plugins/servlet/confluence/placeholder/unknown-attachment"
2029
- result = self.get_page_by_id(page_id, expand="body.view")
2030
- if len(result) == 0:
2031
- return ""
2032
- body = ((result.get("body") or {}).get("view") or {}).get("value") or {}
2033
- if unknown_attachment_identifier in body:
2034
- return result.get("_links").get("base") + result.get("_links").get("tinyui")
2035
- return ""
2036
-
2037
- def is_page_content_is_already_updated(self, page_id, body, title=None):
2038
- """
2039
- Compare content and check is already updated or not
2040
- :param page_id: Content ID for retrieve storage value
2041
- :param body: Body for compare it
2042
- :param title: Title to compare
2043
- :return: True if the same
2044
- """
2045
- confluence_content = self.get_page_by_id(page_id)
2046
- if title:
2047
- current_title = confluence_content.get("title", None)
2048
- if title != current_title:
2049
- log.info("Title of %s is different", page_id)
2050
- return False
2051
-
2052
- if self.advanced_mode:
2053
- confluence_content = (
2054
- (self.get_page_by_id(page_id, expand="body.storage").json() or {}).get("body") or {}
2055
- ).get("storage") or {}
2056
- else:
2057
- confluence_content = ((self.get_page_by_id(page_id, expand="body.storage") or {}).get("body") or {}).get(
2058
- "storage"
2059
- ) or {}
2060
-
2061
- confluence_body_content = confluence_content.get("value")
2062
-
2063
- if confluence_body_content:
2064
- # @todo move into utils
2065
- confluence_body_content = utils.symbol_normalizer(confluence_body_content)
2066
-
2067
- log.debug('Old Content: """%s"""', confluence_body_content)
2068
- log.debug('New Content: """%s"""', body)
2069
-
2070
- if confluence_body_content.strip().lower() == body.strip().lower():
2071
- log.info("Content of %s is exactly the same", page_id)
2072
- return True
2073
- else:
2074
- log.info("Content of %s differs", page_id)
2075
- return False
25
+ return VersionedConfluenceCloud(url, *args, **kwargs)
26
+ return super().__new__(cls)
2076
27
 
2077
- def update_existing_page(
2078
- self,
2079
- page_id,
2080
- title,
2081
- body,
2082
- type="page",
2083
- representation="storage",
2084
- minor_edit=False,
2085
- version_comment=None,
2086
- full_width=False,
2087
- ):
2088
- """Duplicate update_page. Left for the people who used it before. Use update_page instead"""
2089
- return self.update_page(
2090
- page_id=page_id,
2091
- title=title,
2092
- body=body,
2093
- type=type,
2094
- representation=representation,
2095
- minor_edit=minor_edit,
2096
- version_comment=version_comment,
2097
- full_width=full_width,
2098
- )
2099
-
2100
- def update_page(
2101
- self,
2102
- page_id,
2103
- title,
2104
- body=None,
2105
- parent_id=None,
2106
- type="page",
2107
- representation="storage",
2108
- minor_edit=False,
2109
- version_comment=None,
2110
- always_update=False,
2111
- full_width=False,
2112
- ):
2113
- """
2114
- Update page if already exist
2115
- :param page_id:
2116
- :param title:
2117
- :param body:
2118
- :param parent_id:
2119
- :param type:
2120
- :param representation: OPTIONAL: either Confluence 'storage' or 'wiki' markup format
2121
- :param minor_edit: Indicates whether to notify watchers about changes.
2122
- If False then notifications will be sent.
2123
- :param version_comment: Version comment
2124
- :param always_update: Whether always to update (suppress content check)
2125
- :param full_width: OPTIONAL: Default False
2126
- :return:
2127
- """
2128
- # update current page
2129
- params = {"status": "current"}
2130
- log.info('Updating %s "%s" with %s', type, title, parent_id)
2131
-
2132
- if not always_update and body is not None and self.is_page_content_is_already_updated(page_id, body, title):
2133
- return self.get_page_by_id(page_id)
2134
-
2135
- try:
2136
- if self.advanced_mode:
2137
- version = self.history(page_id).json()["lastUpdated"]["number"] + 1
2138
- else:
2139
- version = self.history(page_id)["lastUpdated"]["number"] + 1
2140
- except (IndexError, TypeError) as e:
2141
- log.error("Can't find '%s' %s!", title, type)
2142
- log.debug(e)
2143
- return None
2144
-
2145
- data = {
2146
- "id": page_id,
2147
- "type": type,
2148
- "title": title,
2149
- "version": {"number": version, "minorEdit": minor_edit},
2150
- "metadata": {"properties": {}},
2151
- }
2152
- if body is not None:
2153
- data["body"] = self._create_body(body, representation)
2154
-
2155
- if parent_id:
2156
- data["ancestors"] = [{"type": "page", "id": parent_id}]
2157
- if version_comment:
2158
- data["version"]["message"] = version_comment
2159
-
2160
- if full_width is True:
2161
- data["metadata"]["properties"]["content-appearance-draft"] = {"value": "full-width"}
2162
- data["metadata"]["properties"]["content-appearance-published"] = {"value": "full-width"}
2163
- else:
2164
- data["metadata"]["properties"]["content-appearance-draft"] = {"value": "fixed-width"}
2165
- data["metadata"]["properties"]["content-appearance-published"] = {"value": "fixed-width"}
2166
- try:
2167
- response = self.put(
2168
- f"rest/api/content/{page_id}",
2169
- data=data,
2170
- params=params,
2171
- )
2172
- except HTTPError as e:
2173
- if e.response.status_code == 400:
2174
- raise ApiValueError(
2175
- "No space or no content type, or setup a wrong version "
2176
- "type set to content, or status param is not draft and "
2177
- "status content is current",
2178
- reason=e,
2179
- )
2180
- if e.response.status_code == 404:
2181
- raise ApiNotFoundError("Can not find draft with current content", reason=e)
2182
-
2183
- raise
2184
-
2185
- return response
2186
-
2187
- def _insert_to_existing_page(
2188
- self,
2189
- page_id,
2190
- title,
2191
- insert_body,
2192
- parent_id=None,
2193
- type="page",
2194
- representation="storage",
2195
- minor_edit=False,
2196
- version_comment=None,
2197
- top_of_page=False,
2198
- ):
2199
- """
2200
- Insert body to a page if already exist
2201
- :param parent_id:
2202
- :param page_id:
2203
- :param title:
2204
- :param insert_body:
2205
- :param type:
2206
- :param representation: OPTIONAL: either Confluence 'storage' or 'wiki' markup format
2207
- :param minor_edit: Indicates whether to notify watchers about changes.
2208
- If False then notifications will be sent.
2209
- :param top_of_page: Option to add the content to the end of page body
2210
- :return:
2211
- """
2212
- log.info('Updating %s "%s"', type, title)
2213
- # update current page
2214
- params = {"status": "current"}
2215
-
2216
- if self.is_page_content_is_already_updated(page_id, insert_body, title):
2217
- return self.get_page_by_id(page_id)
2218
- else:
2219
- version = self.history(page_id)["lastUpdated"]["number"] + 1
2220
- previous_body = (
2221
- (self.get_page_by_id(page_id, expand="body.storage").get("body") or {}).get("storage").get("value")
2222
- )
2223
- previous_body = previous_body.replace("&oacute;", "ó")
2224
- body = insert_body + previous_body if top_of_page else previous_body + insert_body
2225
- data = {
2226
- "id": page_id,
2227
- "type": type,
2228
- "title": title,
2229
- "body": self._create_body(body, representation),
2230
- "version": {"number": version, "minorEdit": minor_edit},
2231
- }
2232
-
2233
- if parent_id:
2234
- data["ancestors"] = [{"type": "page", "id": parent_id}]
2235
- if version_comment:
2236
- data["version"]["message"] = version_comment
2237
-
2238
- try:
2239
- response = self.put(
2240
- f"rest/api/content/{page_id}",
2241
- data=data,
2242
- params=params,
2243
- )
2244
- except HTTPError as e:
2245
- if e.response.status_code == 400:
2246
- raise ApiValueError(
2247
- "No space or no content type, or setup a wrong version "
2248
- "type set to content, or status param is not draft and "
2249
- "status content is current",
2250
- reason=e,
2251
- )
2252
- if e.response.status_code == 404:
2253
- raise ApiNotFoundError("Can not find draft with current content", reason=e)
2254
-
2255
- raise
2256
-
2257
- return response
2258
-
2259
- def append_page(
2260
- self,
2261
- page_id,
2262
- title,
2263
- append_body,
2264
- parent_id=None,
2265
- type="page",
2266
- representation="storage",
2267
- minor_edit=False,
2268
- ):
2269
- """
2270
- Append body to page if already exist
2271
- :param parent_id:
2272
- :param page_id:
2273
- :param title:
2274
- :param append_body:
2275
- :param type:
2276
- :param representation: OPTIONAL: either Confluence 'storage' or 'wiki' markup format
2277
- :param minor_edit: Indicates whether to notify watchers about changes.
2278
- If False then notifications will be sent.
2279
- :return:
2280
- """
2281
- log.info('Updating %s "%s"', type, title)
2282
-
2283
- return self._insert_to_existing_page(
2284
- page_id,
2285
- title,
2286
- append_body,
2287
- parent_id=parent_id,
2288
- type=type,
2289
- representation=representation,
2290
- minor_edit=minor_edit,
2291
- top_of_page=False,
2292
- )
2293
-
2294
- def prepend_page(
2295
- self,
2296
- page_id,
2297
- title,
2298
- prepend_body,
2299
- parent_id=None,
2300
- type="page",
2301
- representation="storage",
2302
- minor_edit=False,
2303
- ):
2304
- """
2305
- Append body to page if already exist
2306
- :param parent_id:
2307
- :param page_id:
2308
- :param title:
2309
- :param prepend_body:
2310
- :param type:
2311
- :param representation: OPTIONAL: either Confluence 'storage' or 'wiki' markup format
2312
- :param minor_edit: Indicates whether to notify watchers about changes.
2313
- If False then notifications will be sent.
2314
- :return:
2315
- """
2316
- log.info('Updating %s "%s"', type, title)
2317
-
2318
- return self._insert_to_existing_page(
2319
- page_id,
2320
- title,
2321
- prepend_body,
2322
- parent_id=parent_id,
2323
- type=type,
2324
- representation=representation,
2325
- minor_edit=minor_edit,
2326
- top_of_page=True,
2327
- )
2328
-
2329
- def update_or_create(
2330
- self,
2331
- parent_id,
2332
- title,
2333
- body,
2334
- representation="storage",
2335
- minor_edit=False,
2336
- version_comment=None,
2337
- editor=None,
2338
- full_width=False,
2339
- ):
2340
- """
2341
- Update page or create a page if it is not exists
2342
- :param parent_id:
2343
- :param title:
2344
- :param body:
2345
- :param representation: OPTIONAL: either Confluence 'storage' or 'wiki' markup format
2346
- :param minor_edit: Update page without notification
2347
- :param version_comment: Version comment
2348
- :param editor: OPTIONAL: v2 to be created in the new editor
2349
- :param full_width: OPTIONAL: Default is False
2350
- :return:
2351
- """
2352
- space = self.get_page_space(parent_id)
2353
-
2354
- if self.page_exists(space, title):
2355
- page_id = self.get_page_id(space, title)
2356
- parent_id = parent_id if parent_id is not None else self.get_parent_content_id(page_id)
2357
- result = self.update_page(
2358
- parent_id=parent_id,
2359
- page_id=page_id,
2360
- title=title,
2361
- body=body,
2362
- representation=representation,
2363
- minor_edit=minor_edit,
2364
- version_comment=version_comment,
2365
- full_width=full_width,
2366
- )
2367
- else:
2368
- result = self.create_page(
2369
- space=space,
2370
- parent_id=parent_id,
2371
- title=title,
2372
- body=body,
2373
- representation=representation,
2374
- editor=editor,
2375
- full_width=full_width,
2376
- )
2377
-
2378
- log.info(
2379
- "You may access your page at: %s%s",
2380
- self.url,
2381
- ((result or {}).get("_links") or {}).get("tinyui"),
2382
- )
2383
- return result
2384
-
2385
- def convert_wiki_to_storage(self, wiki):
2386
- """
2387
- Convert to Confluence XHTML format from wiki style
2388
- :param wiki:
2389
- :return:
2390
- """
2391
- data = {"value": wiki, "representation": "wiki"}
2392
- return self.post("rest/api/contentbody/convert/storage", data=data)
2393
-
2394
- def convert_storage_to_view(self, storage):
2395
- """
2396
- Convert from Confluence XHTML format to view format
2397
- :param storage:
2398
- :return:
2399
- """
2400
- data = {"value": storage, "representation": "storage"}
2401
- return self.post("rest/api/contentbody/convert/view", data=data)
2402
-
2403
- def set_page_property(self, page_id, data):
2404
- """
2405
- Set the page (content) property e.g. add hash parameters
2406
- :param page_id: content_id format
2407
- :param data: data should be as json data
2408
- :return:
2409
- """
2410
- url = f"rest/api/content/{page_id}/property"
2411
- json_data = data
2412
-
2413
- try:
2414
- response = self.post(path=url, data=json_data)
2415
- except HTTPError as e:
2416
- if e.response.status_code == 400:
2417
- raise ApiValueError(
2418
- "The given property has a different content id to the one in the "
2419
- "path, or the content already has a value with the given key, or "
2420
- "the value is missing, or the value is too long",
2421
- reason=e,
2422
- )
2423
- if e.response.status_code == 403:
2424
- raise ApiPermissionError(
2425
- "The user does not have permission to " "edit the content with the given id",
2426
- reason=e,
2427
- )
2428
- if e.response.status_code == 413:
2429
- raise ApiValueError("The value is too long", reason=e)
2430
-
2431
- raise
2432
-
2433
- return response
2434
-
2435
- def update_page_property(self, page_id, data):
2436
- """
2437
- Update the page (content) property.
2438
- Use json data or independent keys
2439
- :param data:
2440
- :param page_id: content_id format
2441
- :data: property data in json format
2442
- :return:
2443
- """
2444
- url = f"rest/api/content/{page_id}/property/{data.get('key')}"
2445
- try:
2446
- response = self.put(path=url, data=data)
2447
- except HTTPError as e:
2448
- if e.response.status_code == 400:
2449
- raise ApiValueError(
2450
- "The given property has a different content id to the one in the "
2451
- "path, or the content already has a value with the given key, or "
2452
- "the value is missing, or the value is too long",
2453
- reason=e,
2454
- )
2455
- if e.response.status_code == 403:
2456
- raise ApiPermissionError(
2457
- "The user does not have permission to " "edit the content with the given id",
2458
- reason=e,
2459
- )
2460
- if e.response.status_code == 404:
2461
- raise ApiNotFoundError(
2462
- "There is no content with the given id, or no property with the given key, "
2463
- "or if the calling user does not have permission to view the content.",
2464
- reason=e,
2465
- )
2466
- if e.response.status_code == 409:
2467
- raise ApiConflictError(
2468
- "The given version is does not match the expected " "target version of the updated property",
2469
- reason=e,
2470
- )
2471
- if e.response.status_code == 413:
2472
- raise ApiValueError("The value is too long", reason=e)
2473
- raise
2474
- return response
2475
-
2476
- def delete_page_property(self, page_id, page_property):
2477
- """
2478
- Delete the page (content) property e.g. delete key of hash
2479
- :param page_id: content_id format
2480
- :param page_property: key of property
2481
- :return:
2482
- """
2483
- url = f"rest/api/content/{page_id}/property/{str(page_property)}"
2484
- try:
2485
- response = self.delete(path=url)
2486
- except HTTPError as e:
2487
- if e.response.status_code == 404:
2488
- # Raise ApiError as the documented reason is ambiguous
2489
- raise ApiError(
2490
- "There is no content with the given id, "
2491
- "or the calling user does not have permission to view the content",
2492
- reason=e,
2493
- )
2494
-
2495
- raise
2496
-
2497
- return response
2498
-
2499
- def get_page_property(self, page_id, page_property_key):
2500
- """
2501
- Get the page (content) property e.g. get key of hash
2502
- :param page_id: content_id format
2503
- :param page_property_key: key of property
2504
- :return:
2505
- """
2506
- url = f"rest/api/content/{page_id}/property/{str(page_property_key)}"
2507
- try:
2508
- response = self.get(path=url)
2509
- except HTTPError as e:
2510
- if e.response.status_code == 404:
2511
- # Raise ApiError as the documented reason is ambiguous
2512
- raise ApiError(
2513
- "There is no content with the given id, or no property with the "
2514
- "given key, or the calling user does not have permission to view "
2515
- "the content",
2516
- reason=e,
2517
- )
2518
-
2519
- raise
2520
-
2521
- return response
2522
-
2523
- def get_page_properties(self, page_id):
2524
- """
2525
- Get the page (content) properties
2526
- :param page_id: content_id format
2527
- :return: get properties
2528
- """
2529
- url = f"rest/api/content/{page_id}/property"
2530
-
2531
- try:
2532
- response = self.get(path=url)
2533
- except HTTPError as e:
2534
- if e.response.status_code == 404:
2535
- # Raise ApiError as the documented reason is ambiguous
2536
- raise ApiError(
2537
- "There is no content with the given id, "
2538
- "or the calling user does not have permission to view the content",
2539
- reason=e,
2540
- )
2541
-
2542
- raise
2543
-
2544
- return response
2545
-
2546
- def get_page_ancestors(self, page_id):
2547
- """
2548
- Provide the ancestors from the page (content) id
2549
- :param page_id: content_id format
2550
- :return: get properties
2551
- """
2552
- url = f"rest/api/content/{page_id}?expand=ancestors"
2553
-
2554
- try:
2555
- response = self.get(path=url)
2556
- except HTTPError as e:
2557
- if e.response.status_code == 404:
2558
- raise ApiPermissionError(
2559
- "The calling user does not have permission to view the content",
2560
- reason=e,
2561
- )
2562
-
2563
- raise
2564
-
2565
- return response.get("ancestors")
2566
-
2567
- def clean_all_caches(self):
2568
- """Clean all caches from cache management"""
2569
- headers = self.form_token_headers
2570
- return self.delete("rest/cacheManagement/1.0/cacheEntries", headers=headers)
2571
-
2572
- def clean_package_cache(self, cache_name="com.gliffy.cache.gon"):
2573
- """Clean caches from cache management
2574
- e.g.
2575
- com.gliffy.cache.gon
2576
- org.hibernate.cache.internal.StandardQueryCache_v5
2577
- """
2578
- headers = self.form_token_headers
2579
- data = {"cacheName": cache_name}
2580
- return self.delete("rest/cacheManagement/1.0/cacheEntries", data=data, headers=headers)
2581
-
2582
- def get_all_groups(self, start=0, limit=1000):
2583
- """
2584
- Get all groups from Confluence User management
2585
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
2586
- :param limit: OPTIONAL: The limit of the number of groups to return, this may be restricted by
2587
- fixed system limits. Default: 1000
2588
- :return:
2589
- """
2590
- url = f"rest/api/group?limit={limit}&start={start}"
2591
-
2592
- try:
2593
- response = self.get(url)
2594
- except HTTPError as e:
2595
- if e.response.status_code == 403:
2596
- raise ApiPermissionError(
2597
- "The calling user does not have permission to view groups",
2598
- reason=e,
2599
- )
2600
-
2601
- raise
2602
-
2603
- return response.get("results")
2604
-
2605
- def create_group(self, name):
2606
- """
2607
- Create a group by given group parameter
2608
-
2609
- :param name: str
2610
- :return: New group params
2611
- """
2612
- url = "rest/api/admin/group"
2613
- data = {"name": name, "type": "group"}
2614
- return self.post(url, data=data)
2615
-
2616
- def remove_group(self, name):
2617
- """
2618
- Delete a group by given group parameter
2619
- If you delete a group and content is restricted to that group, the content will be hidden from all users
2620
-
2621
- :param name: str
2622
- :return:
2623
- """
2624
- log.info("Removing group: %s during Confluence remove_group method execution", name)
2625
- url = f"rest/api/admin/group/{name}"
2626
-
2627
- try:
2628
- response = self.delete(url)
2629
- except HTTPError as e:
2630
- if e.response.status_code == 404:
2631
- # Raise ApiError as the documented reason is ambiguous
2632
- raise ApiError(
2633
- "There is no group with the given name, "
2634
- "or the calling user does not have permission to delete it",
2635
- reason=e,
2636
- )
2637
- raise
2638
-
2639
- return response
2640
-
2641
- def get_group_members(self, group_name="confluence-users", start=0, limit=1000, expand=None):
2642
- """
2643
- Get a paginated collection of users in the given group
2644
- :param group_name
2645
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
2646
- :param limit: OPTIONAL: The limit of the number of users to return, this may be restricted by
2647
- fixed system limits. Default: 1000
2648
- :param expand: OPTIONAL: A comma separated list of properties to expand on the content. status
2649
- :return:
2650
- """
2651
- url = f"rest/api/group/{group_name}/member?limit={limit}&start={start}&expand={expand}"
2652
-
2653
- try:
2654
- response = self.get(url)
2655
- except HTTPError as e:
2656
- if e.response.status_code == 403:
2657
- raise ApiPermissionError(
2658
- "The calling user does not have permission to view users",
2659
- reason=e,
2660
- )
2661
-
2662
- raise
2663
-
2664
- return response.get("results")
2665
-
2666
- def get_all_members(self, group_name="confluence-users", expand=None):
2667
- """
2668
- Get collection of all users in the given group
2669
- :param group_name
2670
- :param expand: OPTIONAL: A comma separated list of properties to expand on the content. status
2671
- :return:
2672
- """
2673
- limit = 50
2674
- flag = True
2675
- step = 0
2676
- members = []
2677
- while flag:
2678
- values = self.get_group_members(
2679
- group_name=group_name,
2680
- start=len(members),
2681
- limit=limit,
2682
- expand=expand,
2683
- )
2684
- step += 1
2685
- if len(values) == 0:
2686
- flag = False
2687
- else:
2688
- members.extend(values)
2689
- if not members:
2690
- print(f"Did not get members from {group_name} group, please check permissions or connectivity")
2691
- return members
2692
-
2693
- def get_space(self, space_key, expand="description.plain,homepage", params=None):
2694
- """
2695
- Get information about a space through space key
2696
- :param space_key: The unique space key name
2697
- :param expand: OPTIONAL: additional info from description, homepage
2698
- :param params: OPTIONAL: dictionary of additional URL parameters
2699
- :return: Returns the space along with its ID
2700
- """
2701
- url = f"rest/api/space/{space_key}"
2702
- params = params or {}
2703
- if expand:
2704
- params["expand"] = expand
2705
- try:
2706
- response = self.get(url, params=params)
2707
- except HTTPError as e:
2708
- if e.response.status_code == 404:
2709
- # Raise ApiError as the documented reason is ambiguous
2710
- raise ApiError(
2711
- "There is no space with the given key, "
2712
- "or the calling user does not have permission to view the space",
2713
- reason=e,
2714
- )
2715
- raise
2716
- return response
2717
-
2718
- def get_space_content(
2719
- self,
2720
- space_key,
2721
- depth="all",
2722
- start=0,
2723
- limit=500,
2724
- content_type=None,
2725
- expand="body.storage",
2726
- ):
2727
- """
2728
- Get space content.
2729
- You can specify which type of content want to receive, or get all content types.
2730
- Use expand to get specific content properties or page
2731
- :param content_type:
2732
- :param space_key: The unique space key name
2733
- :param depth: OPTIONAL: all|root
2734
- Gets all space pages or only root pages
2735
- :param start: OPTIONAL: The start point of the collection to return. Default: 0.
2736
- :param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
2737
- fixed system limits. Default: 500
2738
- :param expand: OPTIONAL: by default expands page body in confluence storage format.
2739
- See atlassian documentation for more information.
2740
- :return: Returns the space along with its ID
2741
- """
2742
-
2743
- content_type = f"{'/' + content_type if content_type else ''}"
2744
- url = f"rest/api/space/{space_key}/content{content_type}"
2745
- params = {
2746
- "depth": depth,
2747
- "start": start,
2748
- "limit": limit,
2749
- }
2750
- if expand:
2751
- params["expand"] = expand
2752
- try:
2753
- response = self.get(url, params=params)
2754
- except HTTPError as e:
2755
- if e.response.status_code == 404:
2756
- # Raise ApiError as the documented reason is ambiguous
2757
- raise ApiError(
2758
- "There is no space with the given key, "
2759
- "or the calling user does not have permission to view the space",
2760
- reason=e,
2761
- )
2762
- raise
2763
- return response
2764
-
2765
- def get_home_page_of_space(self, space_key):
2766
- """
2767
- Get information about a space through space key
2768
- :param space_key: The unique space key name
2769
- :return: Returns homepage
2770
- """
2771
- return self.get_space(space_key, expand="homepage").get("homepage")
2772
-
2773
- def create_space(self, space_key, space_name):
2774
- """
2775
- Create space
2776
- :param space_key:
2777
- :param space_name:
2778
- :return:
2779
- """
2780
- data = {"key": space_key, "name": space_name}
2781
- self.post("rest/api/space", data=data)
2782
-
2783
- def delete_space(self, space_key):
2784
- """
2785
- Delete space
2786
- :param space_key:
2787
- :return:
2788
- """
2789
- url = f"rest/api/space/{space_key}"
2790
-
2791
- try:
2792
- response = self.delete(url)
2793
- except HTTPError as e:
2794
- if e.response.status_code == 404:
2795
- # Raise ApiError as the documented reason is ambiguous
2796
- raise ApiError(
2797
- "There is no space with the given key, "
2798
- "or the calling user does not have permission to delete it",
2799
- reason=e,
2800
- )
2801
-
2802
- raise
2803
-
2804
- return response
2805
-
2806
- def get_space_property(self, space_key, expand=None):
2807
- url = f"rest/api/space/{space_key}/property"
2808
- params = {}
2809
- if expand:
2810
- params["expand"] = expand
2811
-
2812
- try:
2813
- response = self.get(url, params=params)
2814
- except HTTPError as e:
2815
- if e.response.status_code == 404:
2816
- # Raise ApiError as the documented reason is ambiguous
2817
- raise ApiError(
2818
- "There is no space with the given key, "
2819
- "or the calling user does not have permission to view the space",
2820
- reason=e,
2821
- )
2822
-
2823
- raise
2824
-
2825
- return response
2826
-
2827
- def get_user_details_by_username(self, username, expand=None):
2828
- """
2829
- Get information about a user through username
2830
- :param username: The username
2831
- :param expand: OPTIONAL expand for get status of user.
2832
- Possible param is "status". Results are "Active, Deactivated"
2833
- :return: Returns the user details
2834
- """
2835
- url = "rest/api/user"
2836
- params = {"username": username}
2837
- if expand:
2838
- params["expand"] = expand
2839
-
2840
- try:
2841
- response = self.get(url, params=params)
2842
- except HTTPError as e:
2843
- if e.response.status_code == 403:
2844
- raise ApiPermissionError(
2845
- "The calling user does not have permission to view users",
2846
- reason=e,
2847
- )
2848
- if e.response.status_code == 404:
2849
- raise ApiNotFoundError(
2850
- "The user with the given username or userkey does not exist",
2851
- reason=e,
2852
- )
2853
-
2854
- raise
2855
-
2856
- return response
2857
-
2858
- def get_user_details_by_accountid(self, accountid, expand=None):
2859
- """
2860
- Get information about a user through accountid
2861
- :param accountid: The account id
2862
- :param expand: OPTIONAL expand for get status of user.
2863
- Possible param is "status". Results are "Active, Deactivated"
2864
- :return: Returns the user details
2865
- """
2866
- url = "rest/api/user"
2867
- params = {"accountId": accountid}
2868
- if expand:
2869
- params["expand"] = expand
2870
-
2871
- try:
2872
- response = self.get(url, params=params)
2873
- except HTTPError as e:
2874
- if e.response.status_code == 403:
2875
- raise ApiPermissionError(
2876
- "The calling user does not have permission to view users",
2877
- reason=e,
2878
- )
2879
- if e.response.status_code == 404:
2880
- raise ApiNotFoundError(
2881
- "The user with the given account does not exist",
2882
- reason=e,
2883
- )
2884
-
2885
- raise
2886
-
2887
- return response
2888
-
2889
- def get_user_details_by_userkey(self, userkey, expand=None):
2890
- """
2891
- Get information about a user through user key
2892
- :param userkey: The user key
2893
- :param expand: OPTIONAL expand for get status of user.
2894
- Possible param is "status". Results are "Active, Deactivated"
2895
- :return: Returns the user details
2896
- """
2897
- url = "rest/api/user"
2898
- params = {"key": userkey}
2899
- if expand:
2900
- params["expand"] = expand
2901
-
2902
- try:
2903
- response = self.get(url, params=params)
2904
- except HTTPError as e:
2905
- if e.response.status_code == 403:
2906
- raise ApiPermissionError(
2907
- "The calling user does not have permission to view users",
2908
- reason=e,
2909
- )
2910
- if e.response.status_code == 404:
2911
- raise ApiNotFoundError(
2912
- "The user with the given username or userkey does not exist",
2913
- reason=e,
2914
- )
2915
-
2916
- raise
2917
-
2918
- return response
2919
-
2920
- def cql(
2921
- self,
2922
- cql,
2923
- start=0,
2924
- limit=None,
2925
- expand=None,
2926
- include_archived_spaces=None,
2927
- excerpt=None,
2928
- ):
2929
- """
2930
- Get results from cql search result with all related fields
2931
- Search for entities in Confluence using the Confluence Query Language (CQL)
2932
- :param cql:
2933
- :param start: OPTIONAL: The start point of the collection to return. Default: 0.
2934
- :param limit: OPTIONAL: The limit of the number of issues to return, this may be restricted by
2935
- fixed system limits. Default by built-in method: 25
2936
- :param excerpt: the excerpt strategy to apply to the result, one of : indexed, highlight, none.
2937
- This defaults to highlight
2938
- :param expand: OPTIONAL: the properties to expand on the search result,
2939
- this may cause database requests for some properties
2940
- :param include_archived_spaces: OPTIONAL: whether to include content in archived spaces in the result,
2941
- this defaults to false
2942
- :return:
2943
- """
2944
- params = {}
2945
- if start is not None:
2946
- params["start"] = int(start)
2947
- if limit is not None:
2948
- params["limit"] = int(limit)
2949
- if cql is not None:
2950
- params["cql"] = cql
2951
- if expand is not None:
2952
- params["expand"] = expand
2953
- if include_archived_spaces is not None:
2954
- params["includeArchivedSpaces"] = include_archived_spaces
2955
- if excerpt is not None:
2956
- params["excerpt"] = excerpt
2957
-
2958
- try:
2959
- response = self.get("rest/api/search", params=params)
2960
- except HTTPError as e:
2961
- if e.response.status_code == 400:
2962
- raise ApiValueError("The query cannot be parsed", reason=e)
2963
-
2964
- raise
2965
-
2966
- return response
2967
-
2968
- def get_page_as_pdf(self, page_id):
2969
- """
2970
- Export page as standard pdf exporter
2971
- :param page_id: Page ID
2972
- :return: PDF File
2973
- """
2974
- headers = self.form_token_headers
2975
- url = f"spaces/flyingpdf/pdfpageexport.action?pageId={page_id}"
2976
- if self.api_version == "cloud" or self.cloud:
2977
- url = self.get_pdf_download_url_for_confluence_cloud(url)
2978
- if not url:
2979
- log.error("Failed to get download PDF url.")
2980
- raise ApiNotFoundError("Failed to export page as PDF", reason="Failed to get download PDF url.")
2981
- # To download the PDF file, the request should be with no headers of authentications.
2982
- return requests.get(url, timeout=75).content
2983
- return self.get(url, headers=headers, not_json_response=True)
2984
-
2985
- def get_page_as_word(self, page_id):
2986
- """
2987
- Export page as standard word exporter.
2988
- :param page_id: Page ID
2989
- :return: Word File
2990
- """
2991
- headers = self.form_token_headers
2992
- url = f"exportword?pageId={page_id}"
2993
- return self.get(url, headers=headers, not_json_response=True)
2994
-
2995
- def get_space_export(self, space_key: str, export_type: str) -> str:
2996
- """
2997
- Export a Confluence space to a file of the specified type.
2998
- (!) This method was developed for Confluence Cloud and may not work with Confluence on-prem.
2999
- (!) This is an experimental method that does not trigger an officially supported REST endpoint.
3000
- It may break if Atlassian changes the space export front-end logic.
3001
-
3002
- :param space_key: The key of the space to export.
3003
- :param export_type: The type of export to perform. Valid values are: 'html', 'csv', 'xml', 'pdf'.
3004
- :return: The URL to download the exported file.
3005
- """
3006
-
3007
- def get_atl_request(link: str):
3008
- # Nested function used to get atl_token used for XSRF protection.
3009
- # This is only applicable to html/csv/xml space exports
3010
- try:
3011
- response = self.get(link, advanced_mode=True)
3012
- parsed_html = BeautifulSoup(response.text, "html.parser")
3013
- atl_token = parsed_html.find("input", {"name": "atl_token"}).get("value") # type: ignore[union-attr]
3014
- return atl_token
3015
- except Exception as e:
3016
- raise ApiError("Problems with getting the atl_token for get_space_export method :", reason=e)
3017
-
3018
- # Checks if space_ke parameter is valid and if api_token has relevant permissions to space
3019
- self.get_space(space_key=space_key, expand="permissions")
3020
-
3021
- try:
3022
- log.info(
3023
- "Initiated experimental get_space_export method for export type: "
3024
- + export_type
3025
- + " from Confluence space: "
3026
- + space_key
3027
- )
3028
- if export_type == "csv":
3029
- form_data = dict(
3030
- atl_token=get_atl_request(f"spaces/exportspacecsv.action?key={space_key}"),
3031
- exportType="TYPE_CSV",
3032
- contentOption="all",
3033
- includeComments="true",
3034
- confirm="Export",
3035
- )
3036
- elif export_type == "html":
3037
- form_data = {
3038
- "atl_token": get_atl_request(f"spaces/exportspacehtml.action?key={space_key}"),
3039
- "exportType": "TYPE_HTML",
3040
- "contentOption": "visibleOnly",
3041
- "includeComments": "true",
3042
- "confirm": "Export",
3043
- }
3044
- elif export_type == "xml":
3045
- form_data = {
3046
- "atl_token": get_atl_request(f"spaces/exportspacexml.action?key={space_key}"),
3047
- "exportType": "TYPE_XML",
3048
- "contentOption": "all",
3049
- "includeComments": "true",
3050
- "confirm": "Export",
3051
- }
3052
- elif export_type == "pdf":
3053
- url = "spaces/flyingpdf/doflyingpdf.action?key=" + space_key
3054
- log.info("Initiated PDF space export")
3055
- return self.get_pdf_download_url_for_confluence_cloud(url)
3056
- else:
3057
- raise ValueError("Invalid export_type parameter value. Valid values are: 'html/csv/xml/pdf'")
3058
- url = self.url_joiner(url=self.url, path=f"spaces/doexportspace.action?key={space_key}")
3059
-
3060
- # Sending a POST request that triggers the space export.
3061
- response = self.session.post(url, headers=self.form_token_headers, data=form_data)
3062
- parsed_html = BeautifulSoup(response.text, "html.parser")
3063
- # Getting the poll URL to get the export progress status
3064
- try:
3065
- poll_url = cast("str", parsed_html.find("meta", {"name": "ajs-pollURI"}).get("content")) # type: ignore[union-attr]
3066
- except Exception as e:
3067
- raise ApiError("Problems with getting the poll_url for get_space_export method :", reason=e)
3068
- running_task = True
3069
- while running_task:
3070
- try:
3071
- progress_response = self.get(poll_url) or {}
3072
- log.info(f"Space {space_key} export status: {progress_response.get('message', 'None')}")
3073
- if progress_response is not {} and progress_response.get("complete"):
3074
- parsed_html = BeautifulSoup(progress_response.get("message"), "html.parser")
3075
- download_url = cast("str", parsed_html.find("a", {"class": "space-export-download-path"}).get("href")) # type: ignore
3076
- if self.url in download_url:
3077
- return download_url
3078
- else:
3079
- combined_url = self.url + download_url
3080
- # Ensure only one /wiki is included in the path
3081
- if combined_url.count("/wiki") > 1:
3082
- combined_url = combined_url.replace("/wiki/wiki", "/wiki")
3083
- return combined_url
3084
- time.sleep(30)
3085
- except Exception as e:
3086
- raise ApiError(
3087
- "Encountered error during space export status check from space " + space_key, reason=e
3088
- )
3089
-
3090
- return "None" # Return None if the while loop does not return a value
3091
- except Exception as e:
3092
- raise ApiError("Encountered error during space export from space " + space_key, reason=e)
3093
-
3094
- def export_page(self, page_id):
3095
- """
3096
- Alias method for export page as pdf
3097
- :param page_id: Page ID
3098
- :return: PDF File
3099
- """
3100
- return self.get_page_as_pdf(page_id)
3101
-
3102
- def get_descendant_page_id(self, space, parent_id, title):
3103
- """
3104
- Provide space, parent_id and title of the descendant page, it will return the descendant page_id
3105
- :param space: str
3106
- :param parent_id: int
3107
- :param title: str
3108
- :return: page_id of the page whose title is passed in argument
3109
- """
3110
- page_id = ""
3111
-
3112
- url = f'rest/api/content/search?cql=parent={parent_id}%20AND%20space="{space}"'
3113
-
3114
- try:
3115
- response = self.get(url, {})
3116
- except HTTPError as e:
3117
- if e.response.status_code == 400:
3118
- raise ApiValueError("The CQL is invalid or missing", reason=e)
3119
-
3120
- raise
3121
-
3122
- for each_page in response.get("results", []):
3123
- if each_page.get("title") == title:
3124
- page_id = each_page.get("id")
3125
- break
3126
- return page_id
3127
-
3128
- def reindex(self):
3129
- """
3130
- It is not public method for reindex Confluence
3131
- :return:
3132
- """
3133
- url = "rest/prototype/1/index/reindex"
3134
- return self.post(url)
3135
-
3136
- def reindex_get_status(self):
3137
- """
3138
- Get reindex status of Confluence
3139
- :return:
3140
- """
3141
- url = "rest/prototype/1/index/reindex"
3142
- return self.get(url)
3143
-
3144
- def health_check(self):
3145
- """
3146
- Get health status
3147
- https://confluence.atlassian.com/jirakb/how-to-retrieve-health-check-results-using-rest-api-867195158.html
3148
- :return:
3149
- """
3150
- # check as Troubleshooting & Support Tools Plugin
3151
- response = self.get("rest/troubleshooting/1.0/check/")
3152
- if not response:
3153
- # check as support tools
3154
- response = self.get("rest/supportHealthCheck/1.0/check/")
3155
- return response
3156
-
3157
- def synchrony_enable(self):
3158
- """
3159
- Enable Synchrony
3160
- :return:
3161
- """
3162
- headers = {"X-Atlassian-Token": "no-check"}
3163
- url = "rest/synchrony-interop/enable"
3164
- return self.post(url, headers=headers)
3165
-
3166
- def synchrony_disable(self):
3167
- """
3168
- Disable Synchrony
3169
- :return:
3170
- """
3171
- headers = {"X-Atlassian-Token": "no-check"}
3172
- url = "rest/synchrony-interop/disable"
3173
- return self.post(url, headers=headers)
3174
-
3175
- def check_access_mode(self):
3176
- return self.get("rest/api/accessmode")
3177
-
3178
- def anonymous(self):
3179
- """
3180
- Get information about how anonymous is represented in confluence
3181
- :return:
3182
- """
3183
- try:
3184
- response = self.get("rest/api/user/anonymous")
3185
- except HTTPError as e:
3186
- if e.response.status_code == 403:
3187
- raise ApiPermissionError(
3188
- "The calling user does not have permission to use Confluence",
3189
- reason=e,
3190
- )
3191
-
3192
- raise
3193
-
3194
- return response
3195
-
3196
- def get_plugins_info(self):
3197
- """
3198
- Provide plugins info
3199
- :return a json of installed plugins
3200
- """
3201
- url = "rest/plugins/1.0/"
3202
- return self.get(url, headers=self.no_check_headers, trailing=True)
3203
-
3204
- def get_plugin_info(self, plugin_key):
3205
- """
3206
- Provide plugin info
3207
- :return a json of installed plugins
3208
- """
3209
- url = f"rest/plugins/1.0/{plugin_key}-key"
3210
- return self.get(url, headers=self.no_check_headers, trailing=True)
3211
-
3212
- def get_plugin_license_info(self, plugin_key):
3213
- """
3214
- Provide plugin license info
3215
- :return a json specific License query
3216
- """
3217
- url = f"rest/plugins/1.0/{plugin_key}-key/license"
3218
- return self.get(url, headers=self.no_check_headers, trailing=True)
3219
-
3220
- def upload_plugin(self, plugin_path):
3221
- """
3222
- Provide plugin path for upload into Jira e.g. useful for auto deploy
3223
- :param plugin_path:
3224
- :return:
3225
- """
3226
- files = {"plugin": open(plugin_path, "rb")}
3227
- upm_token = self.request(
3228
- method="GET",
3229
- path="rest/plugins/1.0/",
3230
- headers=self.no_check_headers,
3231
- trailing=True,
3232
- ).headers["upm-token"]
3233
- url = f"rest/plugins/1.0/?token={upm_token}"
3234
- return self.post(url, files=files, headers=self.no_check_headers)
3235
-
3236
- def disable_plugin(self, plugin_key):
3237
- """
3238
- Disable a plugin
3239
- :param plugin_key:
3240
- :return:
3241
- """
3242
- app_headers = {
3243
- "X-Atlassian-Token": "no-check",
3244
- "Content-Type": "application/vnd.atl.plugins+json",
3245
- }
3246
- url = f"rest/plugins/1.0/{plugin_key}-key"
3247
- data = {"status": "disabled"}
3248
- return self.put(url, data=data, headers=app_headers)
3249
-
3250
- def enable_plugin(self, plugin_key):
3251
- """
3252
- Enable a plugin
3253
- :param plugin_key:
3254
- :return:
3255
- """
3256
- app_headers = {
3257
- "X-Atlassian-Token": "no-check",
3258
- "Content-Type": "application/vnd.atl.plugins+json",
3259
- }
3260
- url = f"rest/plugins/1.0/{plugin_key}-key"
3261
- data = {"status": "enabled"}
3262
- return self.put(url, data=data, headers=app_headers)
3263
-
3264
- def delete_plugin(self, plugin_key):
3265
- """
3266
- Delete plugin
3267
- :param plugin_key:
3268
- :return:
3269
- """
3270
- url = f"rest/plugins/1.0/{plugin_key}-key"
3271
- return self.delete(url)
3272
-
3273
- def check_plugin_manager_status(self):
3274
- url = "rest/plugins/latest/safe-mode"
3275
- return self.request(method="GET", path=url, headers=self.safe_mode_headers)
3276
-
3277
- def update_plugin_license(self, plugin_key, raw_license):
3278
- """
3279
- Update license for plugin
3280
- :param plugin_key:
3281
- :param raw_license:
3282
- :return:
3283
- """
3284
- app_headers = {
3285
- "X-Atlassian-Token": "no-check",
3286
- "Content-Type": "application/vnd.atl.plugins+json",
3287
- }
3288
- url = f"/plugins/1.0/{plugin_key}/license"
3289
- data = {"rawLicense": raw_license}
3290
- return self.put(url, data=data, headers=app_headers)
3291
-
3292
- def check_long_tasks_result(self, start=None, limit=None, expand=None):
3293
- """
3294
- Get result of long tasks
3295
- :param start: OPTIONAL: The start point of the collection to return. Default: None (0).
3296
- :param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
3297
- fixed system limits. Default: 50
3298
- :param expand:
3299
- :return:
3300
- """
3301
- params = {}
3302
- if expand:
3303
- params["expand"] = expand
3304
- if start:
3305
- params["start"] = start
3306
- if limit:
3307
- params["limit"] = limit
3308
- return self.get("rest/api/longtask", params=params)
3309
-
3310
- def check_long_task_result(self, task_id, expand=None):
3311
- """
3312
- Get result of long tasks
3313
- :param task_id: task id
3314
- :param expand:
3315
- :return:
3316
- """
3317
- params = None
3318
- if expand:
3319
- params = {"expand": expand}
3320
-
3321
- try:
3322
- response = self.get(f"rest/api/longtask/{task_id}", params=params)
3323
- except HTTPError as e:
3324
- if e.response.status_code == 404:
3325
- # Raise ApiError as the documented reason is ambiguous
3326
- raise ApiError(
3327
- "There is no task with the given key, " "or the calling user does not have permission to view it",
3328
- reason=e,
3329
- )
3330
-
3331
- raise
3332
-
3333
- return response
3334
-
3335
- def get_pdf_download_url_for_confluence_cloud(self, url):
3336
- """
3337
- Confluence cloud does not return the PDF document when the PDF
3338
- export is initiated. Instead, it starts a process in the background
3339
- and provides a link to download the PDF once the process completes.
3340
- This functions polls the long-running task page and returns the
3341
- download url of the PDF.
3342
- This method is used in get_space_export() method for space-> PDF export.
3343
- :param url: URL to initiate PDF export
3344
- :return: Download url for PDF file
3345
- """
3346
- try:
3347
- running_task = True
3348
- headers = self.form_token_headers
3349
- log.info("Initiate PDF export from Confluence Cloud")
3350
- response = self.get(url, headers=headers, not_json_response=True)
3351
- response_string = response.decode(encoding="utf-8", errors="ignore")
3352
- task_id = response_string.split('name="ajs-taskId" content="')[1].split('">')[0]
3353
- poll_url = f"/services/api/v1/task/{task_id}/progress"
3354
- while running_task:
3355
- log.info("Check if export task has completed.")
3356
- progress_response = self.get(poll_url)
3357
- percentage_complete = int(progress_response.get("progress", 0))
3358
- task_state = progress_response.get("state")
3359
- if task_state == "FAILED":
3360
- log.error("PDF conversion not successful.")
3361
- return None
3362
- elif percentage_complete == 100:
3363
- running_task = False
3364
- log.info(f"Task completed - {task_state}")
3365
- log.debug("Extract task results to download PDF.")
3366
- task_result_url = progress_response.get("result")
3367
- else:
3368
- log.info(f"{percentage_complete}% - {task_state}")
3369
- time.sleep(3)
3370
- log.debug("Task successfully done, querying the task result for the download url")
3371
- # task result url starts with /wiki, remove it.
3372
- task_content = self.get(task_result_url[5:], not_json_response=True)
3373
- download_url = task_content.decode(encoding="utf-8", errors="strict")
3374
- log.debug("Successfully got the download url")
3375
- return download_url
3376
- except IndexError as e:
3377
- log.error(e)
3378
- return None
3379
-
3380
- def audit(
3381
- self,
3382
- start_date=None,
3383
- end_date=None,
3384
- start=None,
3385
- limit=None,
3386
- search_string=None,
3387
- ):
3388
- """
3389
- Fetch a paginated list of AuditRecord instances dating back to a certain time
3390
- :param start_date:
3391
- :param end_date:
3392
- :param start:
3393
- :param limit:
3394
- :param search_string:
3395
- :return:
3396
- """
3397
- url = "rest/api/audit"
3398
- params = {}
3399
- if start_date:
3400
- params["startDate"] = start_date
3401
- if end_date:
3402
- params["endDate"] = end_date
3403
- if start:
3404
- params["start"] = start
3405
- if limit:
3406
- params["limit"] = limit
3407
- if search_string:
3408
- params["searchString"] = search_string
3409
- return self.get(url, params=params)
3410
-
3411
- """
3412
- ##############################################################################################
3413
- # Confluence whiteboards (cloud only!) #
3414
- ##############################################################################################
3415
- """
3416
-
3417
- def create_whiteboard(self, spaceId, title=None, parentId=None):
3418
- url = "/api/v2/whiteboards"
3419
- data = {"spaceId": spaceId}
3420
- if title is not None:
3421
- data["title"] = title
3422
- if parentId is not None:
3423
- data["parentId"] = parentId
3424
- return self.post(url, data=data)
3425
-
3426
- def get_whiteboard(self, whiteboard_id):
3427
- try:
3428
- url = "/api/v2/whiteboards/%s" % (whiteboard_id)
3429
- return self.get(url)
3430
- except HTTPError as e:
3431
- # Default 404 error handling is ambiguous
3432
- if e.response.status_code == 404:
3433
- raise ApiValueError(
3434
- "Whiteboard not found. Check confluence instance url and/or if whiteboard id exists", reason=e
3435
- )
3436
-
3437
- raise
3438
-
3439
- def delete_whiteboard(self, whiteboard_id):
3440
- try:
3441
- url = "/api/v2/whiteboards/%s" % (whiteboard_id)
3442
- return self.delete(url)
3443
- except HTTPError as e:
3444
- # # Default 404 error handling is ambiguous
3445
- if e.response.status_code == 404:
3446
- raise ApiValueError(
3447
- "Whiteboard not found. Check confluence instance url and/or if whiteboard id exists", reason=e
3448
- )
3449
-
3450
- raise
3451
-
3452
- """
3453
- ##############################################################################################
3454
- # Team Calendars REST API implements (https://jira.atlassian.com/browse/CONFSERVER-51003) #
3455
- ##############################################################################################
3456
- """
3457
-
3458
- def team_calendars_get_sub_calendars(self, include=None, viewing_space_key=None, calendar_context=None):
3459
- """
3460
- Get subscribed calendars
3461
- :param include:
3462
- :param viewing_space_key:
3463
- :param calendar_context:
3464
- :return:
3465
- """
3466
- url = "rest/calendar-services/1.0/calendar/subcalendars"
3467
- params = {}
3468
- if include:
3469
- params["include"] = include
3470
- if viewing_space_key:
3471
- params["viewingSpaceKey"] = viewing_space_key
3472
- if calendar_context:
3473
- params["calendarContext"] = calendar_context
3474
- return self.get(url, params=params)
3475
-
3476
- def team_calendars_get_sub_calendars_watching_status(self, include=None):
3477
- url = "rest/calendar-services/1.0/calendar/subcalendars/watching/status"
3478
- params = {}
3479
- if include:
3480
- params["include"] = include
3481
- return self.get(url, params=params)
3482
-
3483
- def team_calendar_events(self, sub_calendar_id, start, end, user_time_zone_id=None):
3484
- """
3485
- Get calendar event status
3486
- :param sub_calendar_id:
3487
- :param start:
3488
- :param end:
3489
- :param user_time_zone_id:
3490
- :return:
3491
- """
3492
- url = "rest/calendar-services/1.0/calendar/events"
3493
- params = {}
3494
- if sub_calendar_id:
3495
- params["subCalendarId"] = sub_calendar_id
3496
- if user_time_zone_id:
3497
- params["userTimeZoneId"] = user_time_zone_id
3498
- if start:
3499
- params["start"] = start
3500
- if end:
3501
- params["end"] = end
3502
- return self.get(url, params=params)
3503
-
3504
- def get_mobile_parameters(self, username):
3505
- """
3506
- Get mobile paramaters
3507
- :param username:
3508
- :return:
3509
- """
3510
- url = f"rest/mobile/1.0/profile/{username}"
3511
- return self.get(url)
3512
-
3513
- def avatar_upload_for_user(self, user_key, data):
3514
- """
3515
-
3516
- :param user_key:
3517
- :param data: json like {"avatarDataURI":"image in base64"}
3518
- :return:
3519
- """
3520
- url = f"rest/user-profile/1.0/{user_key}/avatar/upload"
3521
- return self.post(url, data=data)
3522
-
3523
- def avatar_set_default_for_user(self, user_key):
3524
- """
3525
- :param user_key:
3526
- :return:
3527
- """
3528
- url = f"rest/user-profile/1.0/{user_key}/avatar/default"
3529
- return self.get(url)
3530
-
3531
- def add_user(self, email, fullname, username, password):
3532
- """
3533
- That method related to creating user via json rpc for Confluence Server
3534
- """
3535
- params = {"email": email, "fullname": fullname, "name": username}
3536
- url = "rpc/json-rpc/confluenceservice-v2"
3537
- data = {
3538
- "jsonrpc": "2.0",
3539
- "method": "addUser",
3540
- "params": [params, password],
3541
- }
3542
- self.post(url, data=data)
3543
-
3544
- def change_user_password(self, username, password):
3545
- """
3546
- That method related to changing user password via json rpc for Confluence Server
3547
- """
3548
- params = {"name": username}
3549
- url = "rpc/json-rpc/confluenceservice-v2"
3550
- data = {
3551
- "jsonrpc": "2.0",
3552
- "method": "changeUserPassword",
3553
- "params": [params, password],
3554
- }
3555
- self.post(url, data=data)
3556
-
3557
- def change_my_password(self, oldpass, newpass):
3558
- """
3559
- That method related to changing calling user's own password via json rpc for Confluence Server
3560
- """
3561
- url = "rpc/json-rpc/confluenceservice-v2"
3562
- data = {
3563
- "jsonrpc": "2.0",
3564
- "method": "changeMyPassword",
3565
- "params": [oldpass, newpass],
3566
- }
3567
- self.post(url, data=data)
3568
-
3569
- def add_user_to_group(self, username, group_name):
3570
- """
3571
- Add given user to a group
3572
-
3573
- :param username: str - username of user to add to group
3574
- :param group_name: str - name of group to add user to
3575
- :return: Current state of the group
3576
- """
3577
- url = f"rest/api/user/{username}/group/{group_name}"
3578
- return self.put(url)
3579
-
3580
- def remove_user_from_group(self, username, group_name):
3581
- """
3582
- Remove the given {@link User} identified by username from the given {@link Group} identified by groupName.
3583
- This method is idempotent i.e. if the membership is not present then no action will be taken.
3584
-
3585
- :param username: str - username of user to add to group
3586
- :param group_name: str - name of group to add user to
3587
- :return: Current state of the group
3588
- """
3589
- url = f"rest/api/user/{username}/group/{group_name}"
3590
- return self.delete(url)
3591
-
3592
- # Space Permissions
3593
- def get_all_space_permissions(self, space_key):
3594
- """
3595
- Returns list of permissions granted to users and groups in the particular space.
3596
- :param space_key:
3597
- :return:
3598
- """
3599
- url = f"rest/api/space/{space_key}/permissions"
3600
- return self.get(url)
3601
-
3602
- def set_permissions_to_multiple_items_for_space(self, space_key, user_key=None, group_name=None, operations=None):
3603
- """
3604
- Sets permissions to multiple users/groups in the given space.
3605
- Request should contain all permissions that user/group/anonymous user will have in a given space.
3606
- If permission is absent in the request, but was granted before, it will be revoked.
3607
- If empty list of permissions passed to user/group/anonymous user,
3608
- then all their existing permissions will be revoked.
3609
- If user/group/anonymous user not mentioned in the request, their permissions will not be revoked.
3610
-
3611
- Maximum 40 different users/groups/anonymous user could be passed in the request.
3612
- :param space_key:
3613
- :param user_key:
3614
- :param group_name:
3615
- :param operations:
3616
- :return:
3617
- """
3618
- url = f"rest/api/space/{space_key}/permissions"
3619
- params = []
3620
-
3621
- if user_key:
3622
- params.append({"userKey": user_key, "operations": operations or []})
3623
-
3624
- if group_name:
3625
- params.append({"groupName": group_name, "operations": operations or []})
3626
-
3627
- if not user_key and not group_name:
3628
- params.append({"operations": operations or []})
3629
- payload_json = json.dumps(params)
3630
- return self.post(url, data=payload_json)
3631
-
3632
- def get_permissions_granted_to_anonymous_for_space(self, space_key):
3633
- """
3634
- Get permissions granted to anonymous user for the given space
3635
- :param space_key:
3636
- :return:
3637
- """
3638
- url = f"rest/api/space/{space_key}/permissions/anonymous"
3639
- return self.get(url)
3640
-
3641
- def set_permissions_to_anonymous_for_space(self, space_key, operations=None):
3642
- """
3643
- Grant permissions to anonymous user in the given space. Operation doesn't override existing permissions,
3644
- will only add those one that weren't granted before. Multiple permissions could be passed in one request.
3645
- Supported targetType and operationKey pairs:
3646
-
3647
- space read
3648
- space administer
3649
- space export
3650
- space restrict
3651
- space delete_own
3652
- space delete_mail
3653
- page create
3654
- page delete
3655
- blogpost create
3656
- blogpost delete
3657
- comment create
3658
- comment delete
3659
- attachment create
3660
- attachment delete
3661
- :param space_key:
3662
- :param operations:
3663
- :return:
3664
- """
3665
- url = f"rest/api/space/{space_key}/permissions/anonymous"
3666
- data = {"operations": operations or []}
3667
- return self.put(url, data=data)
3668
-
3669
- def remove_permissions_from_anonymous_for_space(self, space_key, operations=None):
3670
- """
3671
- Revoke permissions from anonymous user in the given space.
3672
- If anonymous user doesn't have permissions that we are trying to revoke,
3673
- those permissions will be silently skipped. Multiple permissions could be passed in one request.
3674
- Supported targetType and operationKey pairs:
3675
-
3676
- space read
3677
- space administer
3678
- space export
3679
- space restrict
3680
- space delete_own
3681
- space delete_mail
3682
- page create
3683
- page delete
3684
- blogpost create
3685
- blogpost delete
3686
- comment create
3687
- comment delete
3688
- attachment create
3689
- attachment delete
3690
- :param space_key:
3691
- :param operations:
3692
- :return:
3693
- """
3694
- url = f"rest/api/space/{space_key}/permissions/anonymous/revoke"
3695
- data = {"operations": operations or []}
3696
- return self.put(url, data=data)
3697
-
3698
- def get_permissions_granted_to_group_for_space(self, space_key, group_name):
3699
- """
3700
- Get permissions granted to group for the given space
3701
- :param space_key:
3702
- :param group_name:
3703
- :return:
3704
- """
3705
- url = f"rest/api/space/{space_key}/permissions/group/{group_name}"
3706
- return self.get(url)
3707
-
3708
- def set_permissions_to_group_for_space(self, space_key, group_name, operations=None):
3709
- """
3710
- Grant permissions to group in the given space.
3711
- Operation doesn't override existing permissions, will only add those one that weren't granted before.
3712
- Multiple permissions could be passed in one request. Supported targetType and operationKey pairs:
3713
-
3714
- space read
3715
- space administer
3716
- space export
3717
- space restrict
3718
- space delete_own
3719
- space delete_mail
3720
- page create
3721
- page delete
3722
- blogpost create
3723
- blogpost delete
3724
- comment create
3725
- comment delete
3726
- attachment create
3727
- attachment delete
3728
- :param space_key:
3729
- :param group_name:
3730
- :param operations:
3731
- :return:
3732
- """
3733
- url = f"rest/api/space/{space_key}/permissions/group/{group_name}"
3734
- data = {"operations": operations or []}
3735
- return self.put(url, data=data)
3736
-
3737
- def remove_permissions_from_group_for_space(self, space_key, group_name, operations=None):
3738
- """
3739
- Revoke permissions from a group in the given space.
3740
- If group doesn't have permissions that we are trying to revoke,
3741
- those permissions will be silently skipped. Multiple permissions could be passed in one request.
3742
- Supported targetType and operationKey pairs:
3743
-
3744
- space read
3745
- space administer
3746
- space export
3747
- space restrict
3748
- space delete_own
3749
- space delete_mail
3750
- page create
3751
- page delete
3752
- blogpost create
3753
- blogpost delete
3754
- comment create
3755
- comment delete
3756
- attachment create
3757
- attachment delete
3758
- :param space_key:
3759
- :param group_name:
3760
- :param operations:
3761
- :return:
3762
- """
3763
- url = f"rest/api/space/{space_key}/permissions/group/{group_name}/revoke"
3764
- data = {"operations": operations or []}
3765
- return self.put(url, data=data)
3766
-
3767
- def get_permissions_granted_to_user_for_space(self, space_key, user_key):
3768
- """
3769
- Get permissions granted to user for the given space
3770
- :param space_key:
3771
- :param user_key:
3772
- :return:
3773
- """
3774
- url = f"rest/api/space/{space_key}/permissions/user/{user_key}"
3775
- return self.get(url)
3776
-
3777
- def set_permissions_to_user_for_space(self, space_key, user_key, operations=None):
3778
- """
3779
- Grant permissions to user in the given space.
3780
- Operation doesn't override existing permissions, will only add those one that weren't granted before.
3781
- Multiple permissions could be passed in one request. Supported targetType and operationKey pairs:
3782
-
3783
- space read
3784
- space administer
3785
- space export
3786
- space restrict
3787
- space delete_own
3788
- space delete_mail
3789
- page create
3790
- page delete
3791
- blogpost create
3792
- blogpost delete
3793
- comment create
3794
- comment delete
3795
- attachment create
3796
- attachment delete
3797
- :param space_key:
3798
- :param user_key:
3799
- :param operations:
3800
- :return:
3801
- """
3802
- url = f"rest/api/space/{space_key}/permissions/user/{user_key}"
3803
- data = {"operations": operations or []}
3804
- return self.put(url, data=data)
3805
-
3806
- def remove_permissions_from_user_for_space(self, space_key, user_key, operations=None):
3807
- """
3808
- Revoke permissions from a user in the given space.
3809
- If user doesn't have permissions that we are trying to revoke,
3810
- those permissions will be silently skipped. Multiple permissions could be passed in one request.
3811
- Supported targetType and operationKey pairs:
3812
-
3813
- space read
3814
- space administer
3815
- space export
3816
- space restrict
3817
- space delete_own
3818
- space delete_mail
3819
- page create
3820
- page delete
3821
- blogpost create
3822
- blogpost delete
3823
- comment create
3824
- comment delete
3825
- attachment create
3826
- attachment delete
3827
- :param space_key:
3828
- :param user_key:
3829
- :param operations:
3830
- :return:
3831
- """
3832
- url = f"rest/api/space/{space_key}/permissions/user/{user_key}/revoke"
3833
- data = {"operations": operations or []}
3834
- return self.put(url, params=data)
3835
-
3836
- def add_space_permissions(
3837
- self,
3838
- space_key,
3839
- subject_type,
3840
- subject_id,
3841
- operation_key,
3842
- operation_target,
3843
- ):
3844
- """
3845
- Add permissions to a space
3846
-
3847
- :param space_key: str - key of space to add permissions to
3848
- :param subject_type: str - type of subject to add permissions for
3849
- :param subject_id: str - id of subject to add permissions for
3850
- :param operation_key: str - key of operation to add permissions for
3851
- :param operation_target: str - target of operation to add permissions for
3852
- :return: Current permissions of space
3853
- """
3854
- url = f"rest/api/space/{space_key}/permission"
3855
- data = {
3856
- "subject": {"type": subject_type, "identifier": subject_id},
3857
- "operation": {"key": operation_key, "target": operation_target},
3858
- "_links": {},
3859
- }
3860
-
3861
- return self.post(url, data=data, headers=self.experimental_headers)
3862
-
3863
- def add_space_permission_json_rpc(self, space_key, user, permission):
3864
- """
3865
- The JSON-RPC APIs for Confluence are provided here to help you browse and discover APIs you have access to.
3866
- JSON-RPC APIs operate differently than REST APIs.
3867
- To learn more about how to use these APIs,
3868
- please refer to the Confluence JSON-RPC documentation on Atlassian Developers.
3869
- """
3870
- if self.api_version == "cloud" or self.cloud:
3871
- return {}
3872
- url = "rpc/json-rpc/confluenceservice-v2"
3873
- data = {
3874
- "jsonrpc": "2.0",
3875
- "method": "addPermissionToSpace",
3876
- "id": 9,
3877
- "params": [permission, user, space_key],
3878
- }
3879
- return self.post(url, data=data).get("result") or {}
3880
-
3881
- def remove_space_permission(self, space_key, user, permission):
3882
- """
3883
- The JSON-RPC APIs for Confluence are provided here to help you browse and discover APIs you have access to.
3884
- JSON-RPC APIs operate differently than REST APIs.
3885
- To learn more about how to use these APIs,
3886
- please refer to the Confluence JSON-RPC documentation on Atlassian Developers.
3887
- """
3888
- if self.api_version == "cloud" or self.cloud:
3889
- return {}
3890
- url = "rpc/json-rpc/confluenceservice-v2"
3891
- data = {
3892
- "jsonrpc": "2.0",
3893
- "method": "removePermissionFromSpace",
3894
- "id": 9,
3895
- "params": [permission, user, space_key],
3896
- }
3897
- return self.post(url, data=data).get("result") or {}
3898
-
3899
- def get_space_permissions(self, space_key):
3900
- """
3901
- The JSON-RPC APIs for Confluence are provided here to help you browse and discover APIs you have access to.
3902
- JSON-RPC APIs operate differently than REST APIs.
3903
- To learn more about how to use these APIs,
3904
- please refer to the Confluence JSON-RPC documentation on Atlassian Developers.
3905
- """
3906
- if self.api_version == "cloud" or self.cloud:
3907
- return self.get_space(space_key=space_key, expand="permissions")
3908
- url = "rpc/json-rpc/confluenceservice-v2"
3909
- data = {
3910
- "jsonrpc": "2.0",
3911
- "method": "getSpacePermissionSets",
3912
- "id": 7,
3913
- "params": [space_key],
3914
- }
3915
- return self.post(url, data=data).get("result") or {}
3916
-
3917
- def get_subtree_of_content_ids(self, page_id):
3918
- """
3919
- Get subtree of page ids
3920
- :param page_id:
3921
- :return: Set of page ID
3922
- """
3923
- output = list()
3924
- output.append(page_id)
3925
- children_pages = self.get_page_child_by_type(page_id)
3926
- for page in children_pages:
3927
- child_subtree = self.get_subtree_of_content_ids(page.get("id"))
3928
- if child_subtree:
3929
- output.extend([p for p in child_subtree])
3930
- return set(output)
3931
-
3932
- def set_inline_tasks_checkbox(self, page_id, task_id, status):
3933
- """
3934
- Set inline task element value
3935
- status is CHECKED or UNCHECKED
3936
- :return:
3937
- """
3938
- url = f"rest/inlinetasks/1/task/{page_id}/{task_id}/"
3939
- data = {"status": status, "trigger": "VIEW_PAGE"}
3940
- return self.post(url, json=data)
3941
-
3942
- def get_jira_metadata(self, page_id):
3943
- """
3944
- Get linked Jira ticket metadata
3945
- PRIVATE method
3946
- :param page_id: Page Id
3947
- :return:
3948
- """
3949
- url = "rest/jira-metadata/1.0/metadata"
3950
- params = {"pageId": page_id}
3951
- return self.get(url, params=params)
3952
-
3953
- def get_jira_metadata_aggregated(self, page_id):
3954
- """
3955
- Get linked Jira ticket aggregated metadata
3956
- PRIVATE method
3957
- :param page_id: Page Id
3958
- :return:
3959
- """
3960
- url = "rest/jira-metadata/1.0/metadata/aggregate"
3961
- params = {"pageId": page_id}
3962
- return self.get(url, params=params)
3963
-
3964
- def clean_jira_metadata_cache(self, global_id):
3965
- """
3966
- Clean cache for linked Jira app link
3967
- PRIVATE method
3968
- :param global_id: ID of Jira app link
3969
- :return:
3970
- """
3971
- url = "rest/jira-metadata/1.0/metadata/cache"
3972
- params = {"globalId": global_id}
3973
- return self.delete(url, params=params)
3974
-
3975
- # Collaborative editing
3976
- def collaborative_editing_get_configuration(self):
3977
- """
3978
- Get collaborative editing configuration
3979
- Related to the on-prem setup Confluence Data Center
3980
- :return:
3981
- """
3982
- if self.cloud:
3983
- return ApiNotAcceptable
3984
- url = "rest/synchrony-interop/configuration"
3985
- return self.get(url, headers=self.no_check_headers)
3986
-
3987
- def collaborative_editing_disable(self):
3988
- """
3989
- Disable collaborative editing
3990
- Related to the on-prem setup Confluence Data Center
3991
- :return:
3992
- """
3993
- if self.cloud:
3994
- return ApiNotAcceptable
3995
- url = "rest/synchrony-interop/disable"
3996
- return self.post(url, headers=self.no_check_headers)
3997
-
3998
- def collaborative_editing_enable(self):
3999
- """
4000
- Disable collaborative editing
4001
- Related to the on-prem setup Confluence Data Center
4002
- :return:
4003
- """
4004
- if self.cloud:
4005
- return ApiNotAcceptable
4006
- url = "rest/synchrony-interop/enable"
4007
- return self.post(url, headers=self.no_check_headers)
4008
-
4009
- def collaborative_editing_restart(self):
4010
- """
4011
- Disable collaborative editing
4012
- Related to the on-prem setup Confluence Data Center
4013
- :return:
4014
- """
4015
- if self.cloud:
4016
- return ApiNotAcceptable
4017
- url = "rest/synchrony-interop/restart"
4018
- return self.post(url, headers=self.no_check_headers)
4019
-
4020
- def collaborative_editing_shared_draft_status(self):
4021
- """
4022
- Status of collaborative editing
4023
- Related to the on-prem setup Confluence Data Center
4024
- :return: false or true parameter in json
4025
- {
4026
- "sharedDraftsEnabled": false
4027
- }
4028
- """
4029
- if self.cloud:
4030
- return ApiNotAcceptable
4031
- url = "rest/synchrony-interop/status"
4032
- return self.get(url, headers=self.no_check_headers)
4033
-
4034
- def collaborative_editing_synchrony_status(self):
4035
- """
4036
- Status of collaborative editing
4037
- Related to the on-prem setup Confluence Data Center
4038
- :return: stopped or running parameter in json
4039
- {
4040
- "status": "stopped"
4041
- }
4042
- """
4043
- if self.cloud:
4044
- return ApiNotAcceptable
4045
- url = "rest/synchrony-interop/synchrony-status"
4046
- return self.get(url, headers=self.no_check_headers)
4047
-
4048
- def synchrony_get_configuration(self):
4049
- """
4050
- Status of collaborative editing
4051
- Related to the on-prem setup Confluence Data Center
4052
- :return:
4053
- """
4054
- if self.cloud:
4055
- return ApiNotAcceptable
4056
- url = "rest/synchrony/1.0/config/status"
4057
- return self.get(url, headers=self.no_check_headers)
4058
-
4059
- def synchrony_remove_draft(self, page_id):
4060
- """
4061
- Status of collaborative editing
4062
- Related to the on-prem setup Confluence Data Center
4063
- :return:
4064
- """
4065
- if self.cloud:
4066
- return ApiNotAcceptable
4067
- url = f"rest/synchrony/1.0/content/{page_id}/changes/unpublished"
4068
- return self.delete(url)
4069
-
4070
- def get_license_details(self):
4071
- """
4072
- Returns the license detailed information
4073
- """
4074
- url = "rest/license/1.0/license/details"
4075
- return self.get(url)
4076
-
4077
- def get_license_user_count(self):
4078
- """
4079
- Returns the total used seats in the license
4080
- """
4081
- url = "rest/license/1.0/license/userCount"
4082
- return self.get(url)
4083
-
4084
- def get_license_remaining(self):
4085
- """
4086
- Returns the available license seats remaining
4087
- """
4088
- url = "rest/license/1.0/license/remainingSeats"
4089
- return self.get(url)
4090
-
4091
- def get_license_max_users(self):
4092
- """
4093
- Returns the license max users
4094
- """
4095
- url = "rest/license/1.0/license/maxUsers"
4096
- return self.get(url)
4097
-
4098
- def raise_for_status(self, response):
4099
- """
4100
- Checks the response for an error status and raises an exception with the error message provided by the server
4101
- :param response:
4102
- :return:
4103
- """
4104
- if response.status_code == 401 and response.headers.get("Content-Type") != "application/json;charset=UTF-8":
4105
- raise HTTPError("Unauthorized (401)", response=response)
4106
-
4107
- if 400 <= response.status_code < 600:
4108
- try:
4109
- j = response.json()
4110
- error_msg = j["message"]
4111
- except Exception as e:
4112
- log.error(e)
4113
- response.raise_for_status()
4114
- else:
4115
- raise HTTPError(error_msg, response=response)
28
+ def __init__(self, url, *args, **kwargs):
29
+ if type(self) is not Confluence:
30
+ return
31
+ # Detect which implementation to use
32
+ # Priority: explicit cloud= kwarg > URL-based heuristic
33
+ is_cloud = kwargs.get("cloud")
34
+ if is_cloud is None:
35
+ hostname = urlparse(url).hostname or ""
36
+ is_cloud = (
37
+ hostname == "atlassian.net"
38
+ or hostname.endswith(".atlassian.net")
39
+ or hostname == "jira.com"
40
+ or hostname.endswith(".jira.com")
41
+ or hostname == "api.atlassian.com"
42
+ or hostname.endswith(".api.atlassian.com")
43
+ )
44
+ if is_cloud:
45
+ impl = LegacyConfluenceCloud(url, *args, **kwargs)
46
+ else:
47
+ impl = ConfluenceServer(url, *args, **kwargs)
48
+ self._impl = impl
49
+
50
+ def __getattr__(self, attr):
51
+ # Delegate all unknown attributes to the true client
52
+ return getattr(self._impl, attr)
53
+
54
+
55
+ __all__ = [
56
+ "ConfluenceCloud",
57
+ "ConfluenceServer",
58
+ "ConfluenceBase",
59
+ ]
60
+
61
+ # ``ConfluenceCloud`` is the established Cloud REST client. The separate v2
62
+ # implementation is intentionally exported as ``atlassian.ConfluenceV2``.
63
+ ConfluenceCloud = LegacyConfluenceCloud