/
AtlassianConfluenceCloud.py
1402 lines (1083 loc) · 47.7 KB
/
AtlassianConfluenceCloud.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
import json
import urllib.parse
from typing import Callable, Dict, Tuple, List
from CommonServerUserPython import * # noqa
import requests
import urllib3
# Disable insecure warnings
urllib3.disable_warnings() # pylint: disable=no-member
''' CONSTANTS '''
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' # ISO8601 format with UTC, default in XSOAR
LOGGING_INTEGRATION_NAME = "[Atlassian Confluence Cloud]"
HTTP_ERROR = {
401: "An error occurred while validating the credentials, please check the username or password.",
404: "The resource cannot be found.",
500: "The server encountered an internal error for Atlassian Confluence Cloud "
"and was unable to complete your request."
}
URL_SUFFIX = {
"CONTENT_SEARCH": "/wiki/rest/api/content/search",
"GROUP": "/wiki/rest/api/group",
"CONTENT": "/wiki/rest/api/content",
"USER": "/wiki/rest/api/search/user?cql=type=user",
"SPACE": "/wiki/rest/api/space",
"PRIVATE_SPACE": "/wiki/rest/api/space/_private"
}
MESSAGES = {
"REQUIRED_URL_FIELD": "Site Name can not be empty.",
"NO_RECORDS_FOUND": "No {} were found for the given argument(s).",
"LIMIT": "{} is an invalid value for limit. Limit must be between 0 and int32.",
"START": "{} is an invalid value for start. Start must be between 0 and int32.",
"INVALID_ACCESS_TYPE": "Invalid value for access type. Access type parameter must be one of 'user', 'admin', "
"or 'site-admin' ",
"REQUIRED_ARGUMENT": "Invalid argument value. {} is a required argument.",
"INVALID_CONTENT_TYPE": "Invalid value for content type. Content type parameter can be 'page' or 'blogpost' ",
"HR_DELETE_CONTENT": "Content with Id {} is deleted successfully.",
"INVALID_STATUS": "Invalid value for status. Status must be one of 'current', 'draft' or 'trashed'.",
"BAD_REQUEST": "Bad request: An error occurred while fetching the data.",
"REQUIRED_SORT_KEY": "If 'sort_order' is specified, 'sort_key' is required.",
"INVALID_STATUS_SEARCH": "Invalid value for status. Status must be one of 'current', 'any', 'archived', 'draft' "
"or 'trashed'.",
"INVALID_PERMISSION": "If the 'permission_account_id' or 'permission_group_name' arguments are given, "
"the 'permission_operations' argument must also be given.",
"INVALID_PERMISSIONS_OPERATION": "If the 'permission_operations' argument is given, "
"'permission_account_id' or 'permission_group_name' argument must also be given.",
"PERMISSION_FORMAT": "Please provide the permission in the valid JSON format. "
"Format accepted - 'operation1:targetType1,operation2:targetType2'",
"ADVANCE_PERMISSION_FORMAT": "Please provide the 'advanced_permissions' in the valid JSON format. ",
"INVALID_SPACE_STATUS": "Invalid value for status. Status must be one of 'current' or 'archived'.",
"INVALID_CONTENT_TYPE_UPDATE_CONTENT": "Invalid value for content type. Content type parameter can be 'page', "
"'blogpost', 'comment' or 'attachment'.",
"INVALID_BODY_REPRESENTATION": "Invalid value for body_representation. Body representation must be one of "
"'editor', 'editor2' or 'storage'.",
"INVALID_DELETION_TYPE": "Invalid value for deletion_type. Deletion type must be one of 'move to trash', "
"'permanent delete' or 'permanent delete draft'.",
"INVALID_TITLE_LENGTH": "Title cannot be longer than 255 characters.",
"INVALID_SPACE_NAME_LENGTH": "Space name cannot be longer than 200 characters.",
"INVALID_SPACE_KEY": "Space Key cannot be longer than 255 characters and should contain alphanumeric characters "
"only.",
"PRIVATE_SPACE_PERMISSION": "Permission can not be granted for a private space."
}
OUTPUT_PREFIX = {
"GROUP": "ConfluenceCloud.Group",
"USER": "ConfluenceCloud.User",
"CONTENT": "ConfluenceCloud.Content",
"COMMENT": "ConfluenceCloud.Comment",
"SPACE": "ConfluenceCloud.Space",
"PAGETOKEN": "ConfluenceCloud.PageToken.Content"
}
DEFAULT_LIMIT = "50"
DEFAULT_START = "0"
LEGAL_ACCESS_TYPES = ["user", "site-admin", "admin"]
LEGAL_CONTENT_STATUS = ['current', 'trashed', 'draft', 'archived', 'any']
LEGAL_CONTENT_TYPES = ["page", "blogpost"]
LEGAL_CONTENT_TYPE_UPDATE_COMMAND = ["page", "blogpost", "comment", "attachment"]
DEFAULT_EXPANDED_FIELD_CONTENT = "childTypes.all,space,version,history,ancestors,container,body"
DEFAULT_EXPANDED_FIELD_SPACE = "history"
LEGAL_SPACE_STATUS = ['current', 'archived']
LEGAL_BODY_REPRESENTATION = ['editor', 'editor2', 'storage']
LEGAL_DELETION_TYPES = {
"move to trash": "current",
"permanent delete": "trashed",
"permanent delete draft": "draft"
}
''' CLIENT CLASS '''
class Client(BaseClient):
"""Client class to interact with the service API
This Client implements API calls, and does not contain any XSOAR logic.
Should only do requests and return data.
It inherits from BaseClient defined in CommonServer Python.
Most calls use _http_request() that handles proxy, SSL verification, etc.
For this implementation, no special attributes defined
"""
def http_request(self, *args, **kwargs) -> requests.Response:
"""
Function to make http requests using inbuilt _http_request() method.
"""
kwargs['ok_codes'] = (200, 201, 204)
kwargs['error_handler'] = self.exception_handler
kwargs['resp_type'] = 'response'
return super()._http_request(*args, **kwargs)
@staticmethod
def exception_handler(response: requests.models.Response):
"""
Handle error in the response and display error message based on status code.
:type response: ``requests.models.Response``
:param response: response from API.
:raises: raise DemistoException based on status code of response.
"""
err_msg = ""
if response.status_code in HTTP_ERROR:
err_msg = HTTP_ERROR[response.status_code]
elif response.status_code > 500:
err_msg = HTTP_ERROR[500]
elif response.status_code not in HTTP_ERROR:
try:
# Try to parse json error response
error_entry = response.json()
demisto.error(f"{LOGGING_INTEGRATION_NAME} {error_entry}")
errors = error_entry.get('data', {}).get('errors', [])
if errors:
err_msg = get_error_message(errors)
elif response.status_code == 400:
err_msg = MESSAGES['BAD_REQUEST']
else:
err_msg = error_entry.get('message', '')
except ValueError:
err_msg = '{}'.format(response.text)
raise DemistoException(err_msg)
''' HELPER FUNCTIONS '''
def get_error_message(errors):
err_msg = ""
for error in errors:
if error.get('message').get('key'):
err_msg += f"{error.get('message').get('key')} \n"
if error.get('message').get('translation'):
err_msg += f"{error.get('message').get('translation')} \n"
return err_msg
def strip_args(args: dict):
"""
Strips argument dictionary values.
:type args: dict
:param args: argument dictionary
"""
for key, value in args.items():
if isinstance(value, str):
args[key] = value.strip()
def validate_url(url: str):
"""
To Validate url parameter.
:type url: str
:param url: url to validate.
"""
if not url:
raise ValueError(MESSAGES["REQUIRED_URL_FIELD"])
def remove_empty_elements_for_context(src):
"""
Recursively remove empty lists, empty dicts, empty string or None elements from a dictionary.
:type src: ``dict``
:param src: Input dictionary.
:return: Dictionary with all empty lists,empty string and empty dictionaries removed.
:rtype: ``dict``
"""
def empty(x):
return x is None or x == '' or x == {} or x == []
if not isinstance(src, (dict, list)):
return src
elif isinstance(src, list):
return [v for v in (remove_empty_elements_for_context(v) for v in src) if not empty(v)]
else:
return {k: v for k, v in ((k, remove_empty_elements_for_context(v))
for k, v in src.items()) if not empty(v)}
def validated_required_args_for_permission(permission_account_id, permission_group_name, permission_operations):
"""
Raise value-error when null-values or whitespaces are provided for permission arguments.
:type permission_account_id: ``str``
:param permission_account_id: Account ID
:type permission_group_name: ``str``
:param permission_group_name: Name of the group
:type permission_operations: ``str``
:param permission_operations: Permissions to be granted
:return: None
"""
if (permission_account_id or permission_group_name) and not permission_operations:
raise ValueError(MESSAGES["INVALID_PERMISSION"])
if permission_operations and (not permission_group_name and not permission_account_id):
raise ValueError(MESSAGES["INVALID_PERMISSIONS_OPERATION"])
def prepare_permission_object(permission_account_id: str, permission_group_name: str, attr: List) -> Dict:
"""
Prepare permission object from the user provided values
:type permission_account_id: ``str``
:param permission_account_id: Account ID of the user to whom permission should be granted.
:type permission_group_name: ``str``
:param permission_group_name: Group name to whom permission should be granted.
:type attr: ``List``
:param attr: Operation and Target Type specified by user
:rtype: ``Dict``
:return: Returns permission object
"""
permission_object = {
"subjects": {
"user": {
"results": [
{
"accountId": permission_account_id
}
]
},
"group": {
"results": [
{
"name": permission_group_name
}
]
}
},
"operation": {
"operation": attr[0],
"targetType": attr[1]
},
"anonymousAccess": False,
"unlicensedAccess": False
}
return permission_object
def validate_permissions(args: Dict[str, Any]) -> List:
"""
Validates the permission argument provided by user and prepare permission object accordingly
:type args: ``dict``
:param args: Input dictionary.
:return: Permission object.
:rtype: ``List``
"""
space_permission = []
permission_account_id = args.get('permission_account_id', '')
permission_group_name = args.get('permission_group_name', '')
permission_operations = args.get('permission_operations', '')
validated_required_args_for_permission(permission_account_id, permission_group_name, permission_operations)
if permission_operations:
# create a list of all the permission provided by user
permissions = [permission.strip() for permission in permission_operations.split(",") if permission.strip()]
# separate target_type and operation for the single permission
for permission in permissions:
if permission:
attr = [operation.strip() for operation in permission.split(":") if operation.strip()]
# if target_type or operation is missing then raise ValueError
if len(attr) != 2:
raise ValueError(MESSAGES["PERMISSION_FORMAT"])
permission_object = prepare_permission_object(permission_account_id, permission_group_name, attr)
space_permission.append(permission_object)
return space_permission
def validate_list_command_args(args: Dict[str, str]) -> Tuple[Optional[int], Optional[int]]:
"""
Validate arguments for all list commands, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Tuple``
"""
limit = arg_to_number(args.get('limit', DEFAULT_LIMIT))
if limit < 0 or limit > 2147483647: # type:ignore
raise ValueError(MESSAGES["LIMIT"].format(limit))
offset = arg_to_number(args.get('offset', DEFAULT_START))
if offset < 0 or offset > 2147483647: # type:ignore
raise ValueError(MESSAGES["START"].format(offset))
return limit, offset
def validate_list_group_args(args: Dict[str, str]):
"""
Validate arguments for confluence-cloud-group-list command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
"""
access_type = args.get("access_type", "").lower()
if access_type and access_type not in LEGAL_ACCESS_TYPES:
raise ValueError(MESSAGES["INVALID_ACCESS_TYPE"])
return access_type
def prepare_group_args(args: Dict[str, str]) -> Dict[str, str]:
"""
Prepare params for list group command
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
"""
limit, offset = validate_list_command_args(args)
access_type = validate_list_group_args(args)
return assign_params(limit=limit, start=offset, accessType=access_type)
def prepare_hr_for_groups(groups: List[Dict[str, Any]]) -> str:
"""
Prepare human readable for list groups command.
:type groups: ``List[Dict[str, Any]]``
:param groups:The group data.
:rtype: ``str``
:return: Human readable.
"""
hr_list = []
for group in groups:
hr_record = {
'ID': group.get('id', ''),
'Name': group.get('name', '')
}
hr_list.append(hr_record)
return tableToMarkdown('Group(s)', hr_list, ['ID', 'Name'],
removeNull=True)
def prepare_content_create_params(args) -> Dict[str, Any]:
"""
Prepare json object for content create command
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Body parameters to send in request
:rtype: ``Dict[str, Any]``
"""
body_representation = args.get('body_representation', '')
params = {
"title": args['title'],
"type": args['type'].lower(),
"space": {
"key": args.get('space_key', '')
},
"status": args.get('status', 'current'),
"body": {
body_representation: {
"value": args.get('body_value', ''),
"representation": body_representation
}
},
"ancestors": [
{
"id": args.get('ancestor_id', '')
}
]
}
return remove_empty_elements_for_context(params)
def validate_create_content_args(args: Dict[str, str], is_update: bool = False):
"""
Validate arguments for confluence-cloud-content-create command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:type is_update: ``bool``
:param is_update: Whether command is update content or not.
:return: None
:rtype: ``None``
"""
title = args['title']
if not title:
raise ValueError(MESSAGES['REQUIRED_ARGUMENT'].format("title"))
if len(title) > 255:
raise ValueError(MESSAGES["INVALID_TITLE_LENGTH"])
content_type = args['type'].lower()
if not content_type:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("type"))
if not is_update and content_type not in LEGAL_CONTENT_TYPES:
raise ValueError(MESSAGES["INVALID_CONTENT_TYPE"])
if is_update and content_type not in LEGAL_CONTENT_TYPE_UPDATE_COMMAND:
raise ValueError(MESSAGES["INVALID_CONTENT_TYPE_UPDATE_CONTENT"])
space_key = args.get('space_key', '')
if not is_update and not space_key:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("space_key"))
body_value = args.get('body_value', '')
body_representation = args.get('body_representation', '')
if content_type == "comment":
if body_value and body_representation:
if body_representation not in LEGAL_BODY_REPRESENTATION:
raise ValueError(MESSAGES["INVALID_BODY_REPRESENTATION"])
else:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("'body_value' and 'body_representation'"))
def prepare_hr_for_content_create(content: Dict[str, Any], content_type: str) -> str:
"""
Prepare human readable for content create, comment create and content update command.
:type content: ``Dict[str, Any]``
:param content:The content data.
:type content_type: ``str``
:param content_type: Type of the content.
:rtype: ``str``
:return: Human readable.
"""
hr_record = {
'ID': content.get('id', ''),
'Title': f"[{content.get('title', '')}]"
f"({content.get('_links', {}).get('base', '')}{content.get('_links', {}).get('webui', '')})",
'Type': content.get('type', ''),
'Status': content.get('status', ''),
'Space Name': content.get('space', {}).get('name', ''),
'Created By': content.get('history', {}).get('createdBy', {}).get('displayName', ''),
'Created At': content.get('history', {}).get('createdDate', '')
}
return tableToMarkdown(f'{content_type}', hr_record,
['ID', 'Title', 'Type', 'Status', 'Space Name', 'Created By', 'Created At'],
removeNull=True)
def prepare_hr_for_content_search(contents: list, url_prefix: str) -> str:
"""
Prepare human readable for content search and content list command.
:type contents: ``list``
:param contents: List of content.
:type url_prefix: ``str``
:param url_prefix: Url prefix the content.
:rtype: ``str``
:return: Human readable.
"""
hr_list = []
for content in contents:
hr_record = {
'ID': content.get('id', ''),
'Title': f"[{content.get('title', '')}]"
f"({url_prefix}{content.get('_links', {}).get('webui', '')})",
'Type': content.get('type', ''),
'Status': content.get('status', ''),
'Space Name': content.get('space', {}).get('name', ''),
'Created By': content.get('history', {}).get('createdBy', {}).get('displayName', ''),
'Created At': content.get('history', {}).get('createdDate', ''),
'Version': content.get('version', {}).get('number', '')
}
hr_list.append(hr_record)
hr = tableToMarkdown('Content(s)', hr_list,
['ID', 'Title', 'Type', 'Status', 'Space Name', 'Created By', 'Created At', 'Version'],
removeNull=True)
return hr
def validate_delete_content_args(args: Dict[str, str]):
"""
Validate arguments for confluence-cloud-content-delete command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: None
"""
content_id = args["content_id"]
if not content_id:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("content_id"))
status = args.get("deletion_type", "").lower()
if status:
if status not in LEGAL_DELETION_TYPES.keys():
raise ValueError(MESSAGES["INVALID_DELETION_TYPE"])
def prepare_comment_create_params(args) -> Dict[str, Any]:
"""
Prepare json object for comment create command
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Body parameters to send in request
:rtype: ``Dict[str, Any]``
"""
body_representation = args['body_representation']
container_type = args.get('container_type', '')
params = {
"type": "comment",
"status": args.get('status', 'current'),
"container": {
"id": args['container_id'],
"type": container_type
},
"body": {
body_representation: {
"value": args['body_value'],
"representation": body_representation
}
},
"ancestors": [
{
"id": args.get('ancestor_id', '')
}
]
}
params = remove_empty_elements_for_context(params)
params["container"]["type"] = container_type
return params
def validate_comment_args(args: Dict[str, str]):
"""
Validate arguments for confluence-cloud-comment-create command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: None
"""
body_value = args['body_value']
if not body_value:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("Comment body_value"))
body_representation = args['body_representation']
if not body_representation:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("body_representation"))
if body_representation not in LEGAL_BODY_REPRESENTATION:
raise ValueError(MESSAGES["INVALID_BODY_REPRESENTATION"])
container_id = args['container_id']
if not container_id:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("container_id"))
def prepare_hr_for_users(users: List[Dict[str, Any]]) -> str:
"""
Prepare human readable for list users command.
:type users: ``List[Dict[str, Any]]``
:param users: The user data.
:rtype: ``str``
:return: Human readable.
"""
hr_list = []
for user in users:
hr_record = {
'Account ID': user['user'].get('accountId', ''),
'Name': user['user'].get('displayName', ''),
'User Type': user['user'].get('type', '')
}
hr_list.append(hr_record)
return tableToMarkdown('User(s)', hr_list, ['Account ID', 'Name', 'User Type'], removeNull=True)
def prepare_expand_argument(expand: str, default_fields: str) -> str:
"""
The 'expand' command argument specifies which properties should be expanded.
In this integration, several of the most significant characteristics are extended by default.
Other attributes that users want to expand can still be provided.
This method combines the default expand fields with the expand fields specified by the user.
:type expand: ``str``
:param expand: The expand argument passed by the user.
:type default_fields: ``str``
:param default_fields: The default fields.
:return: expand argument value to send in request
:rtype: ``str``
"""
default_expand_fields = default_fields.split(",")
custom_expand_fields = set(expand.split(","))
expand_fields = ""
for expand_field in custom_expand_fields:
if expand_field.strip() not in default_expand_fields:
expand_fields += f',{expand_field.strip()}'
return default_fields + expand_fields
def validate_query_argument(args: Dict[str, str]):
"""
Validate query argument of content search command
:param args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: None
"""
query = args['query']
if not query:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("query"))
def prepare_search_content_argument(args: Dict[str, str]) -> Dict[str, Any]:
"""
Prepare params for confluence-cloud-content-search command.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, Any]``
"""
limit, offset = validate_list_command_args(args)
validate_query_argument(args)
params = {'cql': args['query'],
'cursor': args.get('next_page_token'),
'expand': DEFAULT_EXPANDED_FIELD_CONTENT,
'limit': limit
}
expand = args.get('expand', '')
if expand:
params['expand'] = prepare_expand_argument(expand, DEFAULT_EXPANDED_FIELD_CONTENT)
content_status = argToList(args.get('content_status', ''))
params["cqlcontext"] = json.dumps({"contentStatuses": content_status})
return assign_params(**params)
def prepare_cursor_for_content(response_json: Dict[str, str]) -> str:
"""
Split query string parameters from a link and extract value of parameter 'cursor'.
:type response_json: ``Dict[str, str]``
:param response_json: API response.
:return: Next Page Token(Cursor).
:rtype: ``str``
"""
next_cursor = ""
next_record = response_json.get('_links', {}).get('next', '') # type:ignore
if next_record:
next_cursor_split = next_record.split('?')
parsed_next_cursor = urllib.parse.parse_qs(next_cursor_split[1])
next_cursor = parsed_next_cursor.get('cursor', [])[0]
return next_cursor
def validate_list_content_args(args):
"""
Validate arguments for confluence_cloud_content_list command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: None
"""
sort_order = args.get('sort_order', '').lower()
sort_key = args.get('sort_key', '')
if sort_order and not sort_key:
raise ValueError(MESSAGES['REQUIRED_SORT_KEY'])
content_type = args.get('type', 'page').lower()
if content_type not in LEGAL_CONTENT_TYPES:
raise ValueError(MESSAGES['INVALID_CONTENT_TYPE'])
status = args.get('status', '').lower()
if status and status not in LEGAL_CONTENT_STATUS:
raise ValueError(MESSAGES['INVALID_STATUS_SEARCH'])
def prepare_list_content_argument(args: Dict[str, str]) -> Dict[str, Any]:
"""
Prepare params for confluence_cloud_content_list command.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, Any]``
"""
validate_list_content_args(args)
limit, offset = validate_list_command_args(args)
params = {'limit': limit,
'start': offset,
'spaceKey': args.get('space_key', ''),
'type': args.get('type', 'page').lower()
}
sort_order = args.get('sort_order', '').lower()
sort_key = args.get('sort_key', '')
if sort_order and sort_key:
params['orderby'] = f'{sort_key} {sort_order}'
elif sort_key:
params['orderby'] = f'{sort_key}'
content_creation_date = arg_to_datetime(args.get('creation_date'))
if content_creation_date:
params['postingDay'] = content_creation_date.date() # type: ignore
params['status'] = args.get('status', '').lower()
params['expand'] = DEFAULT_EXPANDED_FIELD_CONTENT
expand = args.get('expand', '')
if expand:
params['expand'] = prepare_expand_argument(expand, DEFAULT_EXPANDED_FIELD_CONTENT)
return assign_params(**params)
def validate_create_space_args(args: Dict[str, str]):
"""
Validate arguments for confluence-cloud-space-create command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: None
"""
unique_key = args.get('unique_key')
if not unique_key:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("unique_key"))
if len(unique_key) > 255 or not unique_key.isalnum():
raise ValueError(MESSAGES["INVALID_SPACE_KEY"])
name = args.get('name')
if not name:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("name"))
if len(name) > 200:
raise ValueError(MESSAGES["INVALID_SPACE_NAME_LENGTH"])
is_private_space = argToBoolean(args.get('is_private_space', False))
if is_private_space:
if args.get('advanced_permissions') or args.get('permission_operations'):
raise ValueError(MESSAGES["PRIVATE_SPACE_PERMISSION"])
if args.get('advanced_permissions'):
try:
json.loads(args['advanced_permissions'])
except (json.JSONDecodeError, json.decoder.JSONDecodeError, AttributeError):
raise ValueError(MESSAGES["ADVANCE_PERMISSION_FORMAT"])
def prepare_create_space_args(args: Dict[str, str]) -> Tuple[dict, Union[bool, str]]:
"""
Prepare json object for confluence-cloud-space-create command.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, Any]``
"""
is_private_space = argToBoolean(args.get('is_private_space', False))
if args.get('advanced_permissions'):
permissions = json.loads(args['advanced_permissions'])
else:
permissions = validate_permissions(args)
params = {
"key": args['unique_key'],
"name": args['name'],
"description": {
"plain": {
"value": args.get('description', ''),
"representation": "plain"
}
},
"permissions": permissions
}
params = remove_empty_elements_for_context(params)
return params, is_private_space
def prepare_hr_for_space_create(space: Dict[str, Any]) -> str:
"""
Prepare human readable for create space command.
:type space: ``List[Dict[str, Any]]``
:param space: The space data.
:rtype: ``str``
:return: Human readable.
"""
hr_record = {
'ID': space.get('id', ''),
'Name': f"[{space.get('name', '')}]"
f"({space.get('_links', {}).get('base', '')}{space.get('_links', {}).get('webui', '')})",
'Type': space.get('type', ''),
'Status': space.get('status', ''),
}
return tableToMarkdown('Space', hr_record,
['ID', 'Name', 'Type', 'Status'],
removeNull=True)
def validate_status_argument(args: Dict[str, str]):
"""
Validates the status argument of confluence-cloud-space-list command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: None
"""
status = args.get('status')
if status and status.lower() not in LEGAL_SPACE_STATUS:
raise ValueError(MESSAGES["INVALID_SPACE_STATUS"])
def prepare_list_space_args(args: Dict[str, str]) -> Dict[str, Any]:
"""
Prepare params for confluence-cloud-space-list command.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Parameters to send in request
:rtype: ``Dict[str, Any]``
"""
validate_status_argument(args)
limit, offset = validate_list_command_args(args)
params = {'limit': limit, 'start': offset,
'spaceKey': argToList(args.get('space_key')),
'spaceId': argToList(args.get('space_id')),
'type': args.get('type'),
'status': args.get('status')
}
favourite = args.get('favourite', '')
if favourite:
favourite = "true" if argToBoolean(favourite) else "false"
params['favourite'] = favourite
params['expand'] = DEFAULT_EXPANDED_FIELD_SPACE
expand = args.get('expand', '')
if expand:
params['expand'] = prepare_expand_argument(expand, DEFAULT_EXPANDED_FIELD_SPACE)
return assign_params(**params)
def prepare_hr_for_space_list(spaces: List[Dict[str, Any]], url_prefix: str) -> str:
"""
Prepare human readable for list space command.
:param url_prefix:
:type spaces: ``List[Dict[str, Any]]``
:param spaces: The space data.
:rtype: ``str``
:return: Human readable.
"""
hr_list = []
for space in spaces:
hr_record = {
'ID': space.get('id', ''),
'Space Key': space.get('key', ''),
'Name': f"[{space.get('name', '')}]"
f"({url_prefix}{space.get('_links', {}).get('webui', '')})",
'Type': space.get('type', ''),
'Status': space.get('status', ''),
'Created By': space.get('history', {}).get('createdBy', {}).get('displayName', ''),
'Created At': space.get('history', {}).get('createdDate', '')
}
hr_list.append(hr_record)
hr = tableToMarkdown('Space(s)', hr_list,
['ID', 'Space Key', 'Name', 'Type', 'Status', 'Created By', 'Created At'], removeNull=True)
return hr
def validate_update_content_args(args: Dict[str, str]):
"""
Validate arguments for confluence-cloud-content-update command, raise ValueError on invalid arguments.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: None
"""
validate_create_content_args(args, is_update=True)
content_id = args["content_id"]
if not content_id:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("content_id"))
version = args["version"]
if not version:
raise ValueError(MESSAGES["REQUIRED_ARGUMENT"].format("version"))
''' COMMAND FUNCTIONS '''
def test_module(client: Client) -> str:
"""Tests API connectivity and authentication'
Returning 'ok' indicates that the integration works like it is supposed to.
Connection to the service is successful.
Raises exceptions if something goes wrong.
:type client: ``Client``
:param client: client to use
:return: 'ok' if test passed, anything else will fail the test.
:rtype: ``str``
"""
params: Dict = {
"cql": "type=page",
"limit": 1
}
client.http_request(method='GET', url_suffix=URL_SUFFIX["CONTENT_SEARCH"], params=params)
return 'ok'
def confluence_cloud_user_list_command(client: Client, args: Dict[str, str]) -> CommandResults:
"""
Returns a list of users.
:type client: ``Client``
:param client: Client object to be used.
:type args: ``Dict[str, str]``
:param args: The command arguments provided by the user.
:return: Standard command result or no records found message.
:rtype: ``CommandResults``
"""
limit, offset = validate_list_command_args(args)
params = assign_params(limit=limit, start=offset)
response = client.http_request(method="GET", url_suffix=URL_SUFFIX["USER"], params=params)