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