forked from atlassian-api/atlassian-python-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfluence.py
More file actions
1964 lines (1739 loc) · 73.8 KB
/
confluence.py
File metadata and controls
1964 lines (1739 loc) · 73.8 KB
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
# coding=utf-8
import logging
import os
import time
from requests import HTTPError
from atlassian import utils
from .errors import (
ApiError,
ApiNotFoundError,
ApiPermissionError,
ApiValueError,
ApiConflictError
)
from .rest_client import AtlassianRestAPI
log = logging.getLogger(__name__)
class Confluence(AtlassianRestAPI):
content_types = {
".gif": "image/gif",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".pdf": "application/pdf",
".doc": "application/msword",
".xls": "application/vnd.ms-excel",
".svg": "image/svg+xml"
}
@staticmethod
def _create_body(body, representation):
if representation not in ['editor', 'export_view', 'view', 'storage', 'wiki']:
raise ValueError("Wrong value for representation, it should be either wiki or storage")
return {
representation: {
'value': body,
'representation': representation}
}
def page_exists(self, space, title):
try:
if self.get_page_by_title(space, title):
log.info('Page "{title}" already exists in space "{space}"'.format(space=space, title=title))
return True
else:
log.info('Page does not exist because did not find by title search')
return False
except (HTTPError, KeyError, IndexError):
log.info('Page "{title}" does not exist in space "{space}"'.format(space=space, title=title))
return False
def get_page_child_by_type(self, page_id, type='page', start=None, limit=None):
"""
Provide content by type (page, blog, comment)
:param page_id: A string containing the id of the type content container.
:param type:
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: how many items should be returned after the start index. Default: Site limit 200.
:return:
"""
params = {}
if start is not None:
params['start'] = int(start)
if limit is not None:
params['limit'] = int(limit)
url = 'rest/api/content/{page_id}/child/{type}'.format(page_id=page_id, type=type)
log.info(url)
try:
response = self.get(url, params=params)
except HTTPError as e:
if e.response.status_code == 404:
# Raise ApiError as the documented reason is ambiguous
raise ApiError(
"There is no content with the given id, "
"or the calling user does not have permission to view the content"
)(e)
raise
return response.get('results')
def get_child_pages(self, page_id):
"""
Get child pages for the provided page_id
:param page_id:
:return:
"""
return self.get_page_child_by_type(page_id=page_id, type='page')
def get_page_id(self, space, title):
"""
Provide content id from search result by title and space
:param space: SPACE key
:param title: title
:return:
"""
return (self.get_page_by_title(space, title) or {}).get('id')
def get_parent_content_id(self, page_id):
"""
Provide parent content id from page id
:type page_id: str
:return:
"""
parent_content_id = ((self.get_page_by_id(page_id=page_id, expand='ancestors').get('ancestors') or {})[-1].get(
'id') or None)
return parent_content_id
def get_page_space(self, page_id):
"""
Provide space key from content id
:param page_id: content ID
:return:
"""
return ((self.get_page_by_id(page_id, expand='space') or {}).get('space') or {}).get('key')
def get_pages_by_title(self, space, title, start=0, limit=200, expand=None):
"""
Provide pages by title search
:param space: Space key
:param title: Title of the page
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: The limit of the number of labels to return, this may be restricted by
fixed system limits. Default: 200.
:param expand: OPTIONAL: expand e.g. history
:return: The JSON data returned from searched results the content endpoint, or the results of the
callback. Will raise requests.HTTPError on bad input, potentially.
If it has IndexError then return the None.
"""
return self.get_page_by_title(space, title, start, limit, expand)
def get_page_by_title(self, space, title, start=0, limit=1, expand=None):
"""
Returns the first page on a piece of Content.
:param space: Space key
:param title: Title of the page
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: The limit of the number of labels to return, this may be restricted by
fixed system limits. Default: 1.
:param expand: OPTIONAL: expand e.g. history
:return: The JSON data returned from searched results the content endpoint, or the results of the
callback. Will raise requests.HTTPError on bad input, potentially.
If it has IndexError then return the None.
"""
url = 'rest/api/content'
params = {}
if start is not None:
params['start'] = int(start)
if limit is not None:
params['limit'] = int(limit)
if expand is not None:
params['expand'] = expand
if space is not None:
params['spaceKey'] = str(space)
if title is not None:
params['title'] = str(title)
if self.advanced_mode:
return self.get(url, params=params)
try:
response = self.get(url, params=params)
except HTTPError as e:
if e.response.status_code == 404:
raise ApiPermissionError(
"The calling user does not have permission to view the content"
)(e)
raise
try:
return response.get('results')[0]
except (IndexError, TypeError) as e:
log.error("Can't find '{title}' page on the {url}!".format(title=title, url=self.url))
log.debug(e)
return None
def get_page_by_id(self, page_id, expand=None, status=None, version=None):
"""
Returns a piece of Content.
Example request URI(s):
http://example.com/confluence/rest/api/content/1234?expand=space,body.view,version,container
http://example.com/confluence/rest/api/content/1234?status=any
:param page_id: Content ID
:param status: (str) list of Content statuses to filter results on. Default value: [current]
:param version: (int)
:param expand: OPTIONAL: A comma separated list of properties to expand on the content.
Default value: history,space,version
We can also specify some extensions such as extensions.inlineProperties
(for getting inline comment-specific properties) or extensions.resolution
for the resolution status of each comment in the results
:return:
"""
params = {}
if expand:
params['expand'] = expand
if status:
params['status'] = status
if version:
params['version'] = version
url = 'rest/api/content/{page_id}'.format(page_id=page_id)
try:
response = self.get(url, params=params)
except HTTPError as e:
if e.response.status_code == 404:
# Raise ApiError as the documented reason is ambiguous
raise ApiError(
"There is no content with the given id, "
"or the calling user does not have permission to view the content"
)(e)
raise
return response
def get_page_labels(self, page_id, prefix=None, start=None, limit=None):
"""
Returns the list of labels on a piece of Content.
:param page_id: A string containing the id of the labels content container.
:param prefix: OPTIONAL: The prefixes to filter the labels with {@see Label.Prefix}.
Default: None.
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: The limit of the number of labels to return, this may be restricted by
fixed system limits. Default: 200.
:return: The JSON data returned from the content/{id}/label endpoint, or the results of the
callback. Will raise requests.HTTPError on bad input, potentially.
"""
url = 'rest/api/content/{id}/label'.format(id=page_id)
params = {}
if prefix:
params['prefix'] = prefix
if start is not None:
params['start'] = int(start)
if limit is not None:
params['limit'] = int(limit)
try:
response = self.get(url, params=params)
except HTTPError as e:
if e.response.status_code == 404:
# Raise ApiError as the documented reason is ambiguous
raise ApiError(
"There is no content with the given id, "
"or the calling user does not have permission to view the content"
)(e)
raise
return response
def get_page_comments(self, content_id, expand=None, parent_version=None, start=0, limit=25, location=None,
depth=None):
"""
:param content_id:
:param expand: extensions.inlineProperties,extensions.resolution
:param parent_version:
:param start:
:param limit:
:param location: inline or not
:param depth:
:return:
"""
params = {'id': content_id, 'start': start, 'limit': limit}
if expand:
params['expand'] = expand
if parent_version:
params['parentVersion'] = parent_version
if location:
params['location'] = location
if depth:
params['depth'] = depth
url = 'rest/api/content/{id}/child/comment'.format(id=content_id)
try:
response = self.get(url, params=params)
except HTTPError as e:
if e.response.status_code == 404:
# Raise ApiError as the documented reason is ambiguous
raise ApiError(
"There is no content with the given id, "
"or the calling user does not have permission to view the content"
)(e)
raise
return response
def get_draft_page_by_id(self, page_id, status='draft'):
"""
Provide content by id with status = draft
:param page_id:
:param status:
:return:
"""
url = 'rest/api/content/{page_id}?status={status}'.format(page_id=page_id, status=status)
try:
response = self.get(url)
except HTTPError as e:
if e.response.status_code == 404:
raise ApiPermissionError(
"The calling user does not have permission to view the content"
)(e)
raise
return response
def get_all_pages_by_label(self, label, start=0, limit=50):
"""
Get all page by label
:param label:
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
fixed system limits. Default: 50
:return:
"""
url = 'rest/api/content/search'
params = {}
if label:
params['cql'] = 'type={type} AND label="{label}"'.format(type='page',
label=label)
if start:
params['start'] = start
if limit:
params['limit'] = limit
try:
response = self.get(url, params=params)
except HTTPError as e:
if e.response.status_code == 400:
raise ApiValueError("The CQL is invalid or missing")(e)
raise
return response.get('results')
def get_all_pages_from_space(self, space, start=0, limit=50, status=None, expand=None, content_type='page'):
"""
Get all pages from space
:param space:
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
fixed system limits. Default: 50
:param status: OPTIONAL: list of statuses the content to be found is in.
Defaults to current is not specified.
If set to 'any', content in 'current' and 'trashed' status will be fetched.
Does not support 'historical' status for now.
:param expand: OPTIONAL: a comma separated list of properties to expand on the content.
Default value: history,space,version.
:param content_type: the content type to return. Default value: page. Valid values: page, blogpost.
:return:
"""
url = 'rest/api/content'
params = {}
if space:
params['spaceKey'] = space
if start:
params['start'] = start
if limit:
params['limit'] = limit
if status:
params['status'] = status
if expand:
params['expand'] = expand
if content_type:
params['type'] = content_type
try:
response = self.get(url, params=params)
except HTTPError as e:
if e.response.status_code == 404:
raise ApiPermissionError(
"The calling user does not have permission to view the content"
)(e)
raise
return response.get('results')
def get_all_pages_from_space_trash(self, space, start=0, limit=500, status='trashed', content_type='page'):
"""
Get list of pages from trash
:param space:
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
fixed system limits. Default: 500
:param status:
:param content_type: the content type to return. Default value: page. Valid values: page, blogpost.
:return:
"""
return self.get_all_pages_from_space(space, start, limit, status, content_type=content_type)
def get_all_draft_pages_from_space(self, space, start=0, limit=500, status='draft'):
"""
Get list of draft pages from space
Use case is cleanup old drafts from Confluence
:param space:
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
10BC0
fixed system limits. Default: 500
:param status:
:return:
"""
return self.get_all_pages_from_space(space, start, limit, status)
def get_all_draft_pages_from_space_through_cql(self, space, start=0, limit=500, status='draft'):
"""
Search list of draft pages by space key
Use case is cleanup old drafts from Confluence
:param space: Space Key
:param status: Can be changed
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
fixed system limits. Default: 500
:return:
"""
url = 'rest/api/content?cql=space=spaceKey={space} and status={status}'.format(space=space,
status=status)
params = {}
if limit:
params['limit'] = limit
if start:
params['start'] = start
try:
response = self.get(url, params=params)
except HTTPError as e:
if e.response.status_code == 404:
raise ApiPermissionError(
"The calling user does not have permission to view the content"
)(e)
raise
return response.get('results')
def get_all_restictions_for_content(self, content_id):
"""keep typo method"""
log.warning("Please, be informed that is deprecated as typo naming")
return self.get_all_restrictions_for_content(content_id=content_id)
def get_all_restrictions_for_content(self, content_id):
"""
Returns info about all restrictions by operation.
:param content_id:
:return: Return the raw json response
"""
url = 'rest/api/content/{}/restriction/byOperation'.format(content_id)
return self.get(url)
def remove_page_from_trash(self, page_id):
"""
This method removes a page from trash
:param page_id:
:return:
"""
return self.remove_page(page_id=page_id, status='trashed')
def remove_page_as_draft(self, page_id):
"""
This method removes a page from trash if it is a draft
:param page_id:
:return:
"""
return self.remove_page(page_id=page_id, status='draft')
def remove_content(self, content_id):
"""
Remove any content
:param content_id:
:return:
"""
try:
response = self.delete('rest/api/content/{}'.format(content_id))
except HTTPError as e:
if e.response.status_code == 404:
# Raise ApiError as the documented reason is ambiguous
raise ApiError(
"There is no content with the given id, or the calling "
"user does not have permission to trash or purge the content"
)(e)
if e.response.status_code == 409:
raise ApiConflictError(
"There is a stale data object conflict when trying to delete a draft"
)(e)
raise
return response
def remove_page(self, page_id, status=None, recursive=False):
"""
This method removes a page, if it has recursive flag, method removes including child pages
:param page_id:
:param status: OPTIONAL: type of page
:param recursive: OPTIONAL: if True - will recursively delete all children pages too
:return:
"""
url = 'rest/api/content/{page_id}'.format(page_id=page_id)
if recursive:
children_pages = self.get_page_child_by_type(page_id)
for children_page in children_pages:
self.remove_page(children_page.get('id'), status, recursive)
params = {}
if status:
params['status'] = status
try:
response = self.delete(url, params=params)
except HTTPError as e:
if e.response.status_code == 404:
# Raise ApiError as the documented reason is ambiguous
raise ApiError(
"There is no content with the given id, or the calling "
"user does not have permission to trash or purge the content"
)(e)
if e.response.status_code == 409:
raise ApiConflictError(
"There is a stale data object conflict when trying to delete a draft"
)(e)
raise
return response
def create_page(self, space, title, body, parent_id=None, type='page',
representation='storage', editor=None):
"""
Create page from scratch
:param space:
:param title:
:param body:
:param parent_id:
:param type:
:param representation: OPTIONAL: either Confluence 'storage' or 'wiki' markup format
:param editor: OPTIONAL: v2 to be created in the new editor
:return:
"""
log.info('Creating {type} "{space}" -> "{title}"'.format(space=space, title=title, type=type))
url = 'rest/api/content/'
data = {
'type': type,
'title': title,
'space': {'key': space},
'body': self._create_body(body, representation)}
if parent_id:
data['ancestors'] = [{'type': type, 'id': parent_id}]
if editor == "v2":
data['metadata'] = {'properties': {'editor': {'value': 'v2'}}}
try:
response = self.post(url, data=data)
except HTTPError as e:
if e.response.status_code == 404:
raise ApiPermissionError(
"The calling user does not have permission to view the content"
)(e)
raise
return response
def move_page(self, space_key, page_id, target_id=None, target_title=None, position="append"):
"""
Move page method
:param space_key:
:param page_id:
:param target_title:
:param target_id:
:param position: topLevel or append , above, below
:return:
"""
url = "/pages/movepage.action"
params = {"spaceKey": space_key, "pageId": page_id}
if target_title:
params["targetTitle"] = target_title
if target_id:
params["targetId"] = target_id
if position:
params["position"] = position
return self.post(url, params=params, headers=self.no_check_headers)
def get_all_spaces(self, start=0, limit=500, expand=None):
"""
Get all spaces with provided limit
:param start: OPTIONAL: The start point of the collection to return. Default: None (0).
:param limit: OPTIONAL: The limit of the number of pages to return, this may be restricted by
fixed system limits. Default: 500
:param expand: OPTIONAL: additional info, e.g. metadata, icon, description, homepage
"""
url = 'rest/api/space'
params = {}
if start:
params['start'] = start
if limit:
params['limit'] = limit
if expand:
params['expand'] = expand
return (self.get(url, params=params) or {}).get('results')
def add_comment(self, page_id, text):
"""
Add comment into page
:param page_id
:param text
"""
data = {'type': 'comment',
'container': {'id': page_id, 'type': 'page', 'status': 'current'},
'body': self._create_body(text, 'storage')}
try:
response = self.post('rest/api/content/', data=data)
except HTTPError as e:
if e.response.status_code == 404:
raise ApiPermissionError(
"The calling user does not have permission to view the content"
)(e)
raise
return response
def attach_content(self, content, name, content_type='application/binary', page_id=None, title=None, space=None,
comment=None):
"""
Attach (upload) a file to a page, if it exists it will update the
automatically version the new file and keep the old one.
:param title: The page name
:type title: ``str``
:param space: The space name
:type space: ``str``
:param page_id: The page id to which we would like to upload the file
:type page_id: ``str``
:param name: The name of the attachment
:type name: ``str``
:param content: Contains the content which should be uplaoded
:type content: ``binary``
:param content_type: Specify the HTTP content type. The default is
:type content_type: ``str``
:param comment: A comment describing this upload/file
:type comment: ``str``
"""
page_id = self.get_page_id(space=space, title=title) if page_id is None else page_id
type = 'attachment'
if page_id is not None:
comment = comment if comment else "Uploaded {filename}.".format(filename=name)
data = {
'type': type,
"fileName": name,
"contentType": content_type,
"comment": comment,
"minorEdit": "true"}
headers = {
'X-Atlassian-Token': 'nocheck',
'Accept': 'application/json'}
path = 'rest/api/content/{page_id}/child/attachment'.format(page_id=page_id)
# Check if there is already a file with the same name
attachments = self.get(path=path, headers=headers, params={'filename': name})
if attachments.get('size'):
path = path + '/' + attachments['results'][0]['id'] + '/data'
try:
response = self.post(path=path, data=data, headers=headers,
files={'file': (name, content, content_type)})
except HTTPError as e:
if e.response.status_code == 403:
# Raise ApiError as the documented reason is ambiguous
raise ApiError(
"Attachments are disabled or the calling user does "
"not have permission to add attachments to this content"
)(e)
if e.response.status_code == 404:
# Raise ApiError as the documented reason is ambiguous
raise ApiError(
"The requested content is not found, the user does not have "
"permission to view it, or the attachments exceeds the maximum "
"configured attachment size"
)(e)
raise
return response
else:
log.warning("No 'page_id' found, not uploading attachments")
return None
def attach_file(self, filename, name=None, content_type=None, page_id=None, title=None, space=None, comment=None):
"""
Attach (upload) a file to a page, if it exists it will update the
automatically version the new file and keep the old one.
:param title: The page name
:type title: ``str``
:param space: The space name
:type space: ``str``
:param page_id: The page id to which we would like to upload the file
:type page_id: ``str``
:param filename: The file to upload (Specifies the content)
:type filename: ``str``
:param name: Specifies name of the attachment. This parameter is optional.
Is no name give the file name is used as name
:type name: ``str``
:param content_type: Specify the HTTP content type. The default is
:type content_type: ``str``
:param comment: A comment describing this upload/file
:type comment: ``str``
"""
# get base name of the file to get the attachment from confluence.
if name is None:
name = os.path.basename(filename)
if content_type is None:
extension = os.path.splitext(filename)[-1]
content_type = self.content_types.get(extension, "application/binary")
with open(filename, 'rb') as infile:
content = infile.read()
return self.attach_content(content, name, content_type, page_id=page_id, title=title, space=space,
comment=comment)
def delete_attachment(self, page_id, filename, version=None):
"""
Remove completely a file if version is None or delete version
:param version:
:param page_id: file version
:param filename:
:return:
"""
params = {'pageId': page_id, 'fileName': filename}
if version:
params['version'] = version
return self.post('json/removeattachment.action', params=params, headers=self.form_token_headers)
def delete_attachment_by_id(self, attachment_id, version):
"""
Remove completely a file if version is None or delete version
:param attachment_id:
:param version: file version
:return:
"""
return self.delete(
'rest/experimental/content/{id}/version/{versionId}'.format(id=attachment_id, versionId=version))
def remove_page_attachment_keep_version(self, page_id, filename, keep_last_versions):
"""
Keep last versions
:param filename:
:param page_id:
:param keep_last_versions:
:return:
"""
attachment = \
self.get_attachments_from_content(page_id=page_id, expand='version', filename=filename).get(
'results')[0]
attachment_versions = self.get_attachment_history(attachment.get("id"))
while len(attachment_versions) > keep_last_versions:
remove_version_attachment_number = attachment_versions[keep_last_versions].get('number')
self.delete_attachment_by_id(attachment_id=attachment.get("id"), version=remove_version_attachment_number)
log.info(
"Removed oldest version for {}, now versions equal more than {}".format(attachment.get('title'),
len(attachment_versions)))
attachment_versions = self.get_attachment_history(attachment.get("id"))
log.info("Kept versions {} for {}".format(keep_last_versions, attachment.get('title')))
def get_attachment_history(self, attachment_id, limit=200, start=0):
"""
Get attachment history
:param attachment_id
:param limit
:param start
:return
"""
params = {'limit': limit, 'start': start}
url = 'rest/experimental/content/{}/version'.format(attachment_id)
return (self.get(url, params=params) or {}).get("results")
# @todo prepare more attachments info
def get_attachments_from_content(self, page_id, start=0, limit=50, expand=None, filename=None, media_type=None):
"""
Get attachments for page
:param page_id:
:param start:
:param limit:
:param expand:
:param filename:
:param media_type:
:return:
"""
params = {}
if start:
params['start'] = start
if limit:
params['limit'] = limit
if expand:
params['expand'] = expand
if filename:
params['filename'] = filename
if media_type:
params['mediaType'] = media_type
url = 'rest/api/content/{id}/child/attachment'.format(id=page_id, params=params)
try:
response = self.get(url, params=params)
except HTTPError as e:
if e.response.status_code == 404:
# Raise ApiError as the documented reason is ambiguous
raise ApiError(
"There is no content with the given id, "
"or the calling user does not have permission to view the content"
)(e)
raise
return response
def set_page_label(self, page_id, label):
"""
Set a label on the page
:param page_id: content_id format
:param label: label to add
:return:
"""
url = 'rest/api/content/{page_id}/label'.format(page_id=page_id)
data = {'prefix': 'global',
'name': label}
try:
response = self.post(path=url, data=data)
except HTTPError as e:
if e.response.status_code == 404:
# Raise ApiError as the documented reason is ambiguous
raise ApiError(
"There is no content with the given id, "
"or the calling user does not have permission to view the content"
)(e)
raise
return response
def remove_page_label(self, page_id, label):
"""
Delete Confluence page label
:param page_id: content_id format
:param label: label name
:return:
"""
url = 'rest/api/content/{page_id}/label'.format(page_id=page_id)
params = {'id': page_id,
'name': label}
try:
response = self.delete(path=url, params=params)
except HTTPError as e:
if e.response.status_code == 403:
raise ApiPermissionError(
"The user has view permission, "
"but no edit permission to the content"
)(e)
if e.response.status_code == 404:
# Raise ApiError as the documented reason is ambiguous
raise ApiError(
"The content or label doesn't exist, "
"or the calling user doesn't have view permission to the content"
)(e)
raise
return response
def history(self, page_id):
url = 'rest/api/content/{0}/history'.format(page_id)
try:
response = self.get(url)
except HTTPError as e:
if e.response.status_code == 404:
# Raise ApiError as the documented reason is ambiguous
raise ApiError(
"There is no content with the given id, "
"or the calling user does not have permission to view the content"
)(e)
raise
return response
def get_content_history(self, content_id):
return self.history(content_id)
def get_content_history_by_version_number(self, content_id, version_number):
"""
Get content history by version number
:param content_id:
:param version_number:
:return:
"""
url = 'rest/experimental/content/{0}/version/{1}'.format(content_id, version_number)
return self.get(url)
def remove_content_history(self, page_id, version_number):
"""
Remove content history. It works as experimental method
:param page_id:
:param version_number: version number
:return:
"""
url = 'rest/experimental/content/{id}/version/{versionNumber}'.format(id=page_id, versionNumber=version_number)
self.delete(url)
def remove_page_history(self, page_id, version_number):
"""
Remove content history. It works as experimental method
:param page_id:
:param version_number: version number
:return:
"""
self.remove_content_history(page_id, version_number)
def remove_content_history_in_cloud(self, page_id, version_id):
"""
Remove content history. It works in CLOUD
:param page_id:
:param version_id:
:return:
"""
url = 'rest/api/content/{id}/version/{versionId}'.format(id=page_id, versionId=version_id)
self.delete(url)
def remove_page_history_keep_version(self, page_id, keep_last_versions):
"""
Keep last versions
:param page_id:
:param keep_last_versions:
:return:
"""
page = self.get_page_by_id(page_id=page_id, expand='version')
page_number = page.get('version').get('number')
while page_number > keep_last_versions:
self.remove_page_history(page_id=page_id, version_number=1)
page = self.get_page_by_id(page_id=page_id, expand='version')
page_number = page.get('version').get('number')
log.info("Removed oldest version for {}, now it's {}".format(page.get('title'), page_number))
log.info("Kept versions {} for {}".format(keep_last_versions, page.get('title')))
def has_unknown_attachment_error(self, page_id):
"""
Check has unknown attachment error on page
:param page_id:
:return:
"""
unknown_attachment_identifier = 'plugins/servlet/confluence/placeholder/unknown-attachment'
result = self.get_page_by_id(page_id, expand='body.view')
if len(result) == 0:
return ""
body = (((result.get('body') or {}).get('view') or {}).get('value') or {})
if unknown_attachment_identifier in body:
return result.get('_links').get('base') + result.get('_links').get('tinyui')
return ""
def is_page_content_is_already_updated(self, page_id, body, title=None):
"""
Compare content and check is already updated or not
:param page_id: Content ID for retrieve storage value
:param body: Body for compare it
:param title: Title to compare
:return: True if the same
"""
confluence_content = self.get_page_by_id(page_id)
if title:
current_title = confluence_content.get('title', None)
if title != current_title:
log.info('Title of {page_id} is different'.format(page_id=page_id))
return False
if self.advanced_mode:
confluence_content = (((self.get_page_by_id(page_id, expand='body.storage').json() or {})
.get('body') or {})
.get('storage') or {})
else:
confluence_content = (((self.get_page_by_id(page_id, expand='body.storage') or {})
.get('body') or {})
.get('storage') or {})
confluence_body_content = confluence_content.get('value')
if confluence_body_content:
# @todo move into utils
confluence_body_content = utils.symbol_normalizer(confluence_body_content)
log.debug('Old Content: """{body}"""'.format(body=confluence_body_content))
log.debug('New Content: """{body}"""'.format(body=body))
if confluence_body_content.strip() == body.strip():
log.warning('Content of {page_id} is exactly the same'.format(page_id=page_id))
return True