forked from jgoldin-skillz/confluenceDumpWithPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfluenceDumpToHTML.py
More file actions
1416 lines (1177 loc) · 68.7 KB
/
confluenceDumpToHTML.py
File metadata and controls
1416 lines (1177 loc) · 68.7 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This script dumps content from a Confluence instance (Cloud or Data Center) to HTML.
Features:
- Recursive Inventory Scan (Correct Sort Order)
- Multithreaded Downloading
- HTML Processing with BeautifulSoup (Images, Links, Sidebar, Resizer)
- Static Sidebar Injection
- CSS Auto-Discovery
- Label-based Tree Pruning
- Automatic Timestamped Subdirectories
- Manual Overrides (HTML & MHTML) with aggressive cleaning (Data Diet)
"""
import argparse
import os
import sys
import json
import shutil
import glob
import time
import re
import email # Required for MHTML parsing
from datetime import datetime
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
from confluence_dump import myModules
from confluence_dump.utils.config_manager import ConfigManager
from confluence_dump.utils.file_ops import atomic_write_text
# --- External Libraries ---
try:
import pypandoc
except ImportError:
pypandoc = None
try:
from tqdm import tqdm
except ImportError:
def tqdm(iterable, **kwargs):
return iterable
try:
from bs4 import BeautifulSoup, Comment, NavigableString, Tag
except ImportError:
print("Error: beautifulsoup4 not installed", file=sys.stderr)
sys.exit(1)
# --- Global Config & State ---
platform_config = {}
auth_info = {}
all_pages_metadata = []
seen_metadata_ids = set()
global_sidebar_html = ""
# --- Helper Functions ---
def sanitize_filename(filename):
""" Sanitizes a string to be safe for directory names. """
s = re.sub(r'[<>:"/\\|?*]', '_', filename)
return s.strip().strip('.')
def get_run_title(args, base_url, platform_config, auth_info):
if args.command == 'all-spaces':
return "all spaces"
elif args.command == 'space':
return f"Space {args.space_key}"
elif args.command == 'label':
return f"Export {args.label}"
elif args.command in ('single', 'tree'):
try:
context_path = args.context_path
page_data = myModules.get_page_basic(args.pageid, base_url, platform_config, auth_info, context_path)
if page_data and 'title' in page_data:
return page_data['title']
else:
return f"Page {args.pageid}"
except Exception as e:
print(f"Warning: Could not fetch page title: {e}", file=sys.stderr)
return f"Page {args.pageid}"
return "Export"
# --- Content Cleaning (The "Data Diet") ---
def extract_html_from_mhtml(file_path):
""" Extracts the main HTML part from a MHTML file. """
try:
with open(file_path, 'rb') as f:
message = email.message_from_bytes(f.read())
if message.is_multipart():
for part in message.walk():
if part.get_content_type() == "text/html":
charset = part.get_content_charset() or 'utf-8'
return part.get_payload(decode=True).decode(charset, errors='replace')
else:
if message.get_content_type() == "text/html":
charset = message.get_content_charset() or 'utf-8'
return message.get_payload(decode=True).decode(charset, errors='replace')
except Exception as e:
print(f"Error parsing MHTML {file_path}: {e}", file=sys.stderr)
return None
return None
def is_hidden(tag):
""" Helper to detect if a tag is visually hidden via common attributes. Robust version. """
if not isinstance(tag, Tag): return False
if not hasattr(tag, 'attrs') or tag.attrs is None:
return False
classes = tag.get('class', [])
if any(c in ['tf-hidden-column', 'hidden', 'hide', 'invisible', 'aui-hide'] for c in classes):
return True
style = tag.get('style', '')
if 'display: none' in style.replace(' ', '').lower():
return True
if 'display:none' in style.replace(' ', '').lower():
return True
if tag.get('aria-hidden') == 'true':
return True
return False
def clean_manual_html(html_content):
"""
Aggressively cleans manually saved HTML.
Includes smart table column pruning based on headers/colgroups.
"""
if not html_content: return ""
soup = BeautifulSoup(html_content, 'html.parser')
# 1. Identify Content Area
content_node = soup.find('div', id='main-content') or \
soup.find('div', class_='wiki-content') or \
soup.body or \
soup
# 2. Recover CSS rendered as text
for tag in content_node.find_all(['p', 'div']):
text = tag.get_text(strip=True)
if text.startswith('/*') and '{' in text and '}' in text and ('@page' in text or 'size:' in text or 'landscape' in text):
style_tag = soup.new_tag('style', type='text/css')
style_tag.string = tag.get_text(separator='\n').replace('\xa0', ' ')
tag.replace_with(style_tag)
# 3. Remove Junk Tags (excluding 'style' to preserve CSS)
for tag in content_node.find_all(['script', 'meta', 'link', 'noscript', 'iframe', 'svg']):
tag.decompose()
for comment in content_node.find_all(string=lambda text: isinstance(text, Comment)):
comment.extract()
# 3. Smart Table Pruning
for table in content_node.find_all('table'):
indices_to_remove = set()
colgroup = table.find('colgroup')
if colgroup:
cols = colgroup.find_all('col')
for idx, col in enumerate(cols):
if is_hidden(col):
indices_to_remove.add(idx)
thead = table.find('thead')
if thead:
header_rows = thead.find_all('tr')
for tr in header_rows:
cells = tr.find_all(['th', 'td'])
for idx, cell in enumerate(cells):
if is_hidden(cell):
indices_to_remove.add(idx)
# If we found columns to prune, go through ALL rows (head and body)
if indices_to_remove:
for tr in table.find_all('tr'):
cells = tr.find_all(['td', 'th'])
for i in sorted(indices_to_remove, reverse=True):
if i < len(cells):
cells[i].decompose()
# Also remove the <col> tags themselves if marked
if colgroup:
cols = colgroup.find_all('col')
for i in sorted(indices_to_remove, reverse=True):
if i < len(cols): cols[i].decompose()
# 4. General Cleanup (Rows/Divs explicitly hidden)
# Use list() to avoid modification during iteration issues
for tag in list(content_node.find_all(['tr', 'div', 'span'])):
if is_hidden(tag):
tag.decompose()
# 5. Clean Table Headers (The "Rectangle" Fix)
for btn in content_node.find_all('button', class_='headerButton'):
btn.replace_with(btn.get_text(strip=True))
# 6. Remove Specific Confluence UI Artifacts
error_texts = ["Ups, es scheint", "Die Tabelle wird gerade geladen", "Table Filter", "Tabelle filtern", "Diese Seite enthält komplexe Makros"]
for text in error_texts:
for element in content_node.find_all(string=re.compile(re.escape(text))):
wrapper = element.find_parent('div', class_=re.compile(r'(error|warning|message|macro|aui-message|panel|confluence-information-macro)', re.IGNORECASE))
if wrapper:
wrapper.decompose()
elif element.parent:
if element.parent.name in ['p', 'span', 'b', 'strong', 'em', 'i', 'div', 'td', 'th']:
element.parent.decompose()
else:
element.extract()
for tag in content_node.find_all(
class_=re.compile(r'(aui-icon|icon-macro|refresh-macro|macro-placeholder|aui-button|tf-filter-button|table-filter|copy-heading-link-container|aui-inline-dialog-contents|tableFilterCbStyle)')):
tag.decompose()
# 7. Prune Empty Tags
for _ in range(3):
for tag in content_node.find_all(['span', 'div', 'p', 'strong', 'em', 'b', 'i']):
if not tag.get_text(strip=True) and len(tag.find_all()) == 0:
tag.decompose()
return content_node.decode_contents()
# --- Processing Helpers ---
def collect_page_metadata(page_full):
try:
page_id = page_full.get('id')
if not page_id or page_id in seen_metadata_ids:
return
title = page_full.get('title')
ancestors = page_full.get('ancestors', [])
parent_id = ancestors[-1]['id'] if ancestors else None
all_pages_metadata.append({'id': page_id, 'title': title, 'parent_id': parent_id})
seen_metadata_ids.add(page_id)
except Exception as e:
print(f"Warning: Could not collect metadata for index: {e}", file=sys.stderr)
def save_page_attachments(page_id, attachments, base_url, auth_info):
if not attachments or 'results' not in attachments: return
for att in attachments['results']:
download_path = att.get('_links', {}).get('download')
filename = att.get('title')
if download_path and filename:
if download_path.startswith('/'):
full_url = base_url.rstrip('/') + download_path
else:
full_url = base_url.rstrip('/') + '/' + download_path
local_path = os.path.join(myModules.outdir_attachments, filename)
myModules.download_file(full_url, local_path, auth_info)
def convert_rst(page_id, page_body, outdir_pages):
if pypandoc is None: return
page_filename_rst = f"{outdir_pages}{page_id}.rst"
try:
pypandoc.convert_text(page_body, 'rst', format='html', outputfile=page_filename_rst)
except Exception as e:
print(f" Error converting RST for {page_id}: {e}", file=sys.stderr)
# --- Tree Generation ---
def build_tree_structure(target_ids):
tree_map = {}
pages_map = {}
relevant_pages = [p for p in all_pages_metadata if p['id'] in target_ids]
for page in relevant_pages:
pid = page['id']
parent = page['parent_id']
pages_map[pid] = page
if parent not in tree_map: tree_map[parent] = []
tree_map[parent].append(pid)
downloaded_ids = set(pages_map.keys())
root_ids = []
for page in relevant_pages:
parent = page['parent_id']
if parent is None or parent not in downloaded_ids:
root_ids.append(page['id'])
return tree_map, pages_map, root_ids
def generate_tree_html(target_ids):
tree_map, pages_map, root_ids = build_tree_structure(target_ids)
def build_branch(parent_id):
if parent_id not in tree_map: return ""
html = "<ul>\n"
for child_id in tree_map[parent_id]:
if child_id not in pages_map: continue
child = pages_map[child_id]
title = child['title']
link = f'<a href="{child_id}.html">{title}</a>'
if child_id in tree_map:
sub_tree = build_branch(child_id)
html += f'<li class="folder"><details><summary>{link}</summary>{sub_tree}</details></li>\n'
else:
html += f'<li class="leaf">{link}</li>\n'
html += "</ul>\n"
return html
sidebar = '<div class="sidebar-tree"><ul>\n'
for rid in root_ids:
if rid not in pages_map: continue
page = pages_map[rid]
title = page['title']
link = f'<a href="{rid}.html">{title}</a>'
if rid in tree_map:
sub_tree = build_branch(rid)
sidebar += f'<li class="folder"><details open><summary>{link}</summary>{sub_tree}</details></li>\n'
else:
sidebar += f'<li class="leaf">{link}</li>\n'
sidebar += '</ul></div>\n'
return sidebar
def generate_tree_markdown(target_ids):
tree_map, pages_map, root_ids = build_tree_structure(target_ids)
md_lines = []
pages_dir_abs = os.path.abspath(myModules.outdir_pages)
pages_uri = Path(pages_dir_abs).as_uri()
def build_branch_md(parent_id, level):
if parent_id not in tree_map: return
indent = " " * level
for child_id in tree_map[parent_id]:
if child_id not in pages_map: continue
child = pages_map[child_id]
md_lines.append(f"{indent}- [{child['title']}]({pages_uri}/{child_id}.html)")
if child_id in tree_map:
build_branch_md(child_id, level + 1)
for rid in root_ids:
if rid not in pages_map: continue
page = pages_map[rid]
md_lines.append(f"- [{page['title']}]({pages_uri}/{rid}.html)")
if rid in tree_map:
build_branch_md(rid, 1)
return "\n".join(md_lines)
def save_sidebars(outdir, target_ids):
global global_sidebar_html
global_sidebar_html = generate_tree_html(target_ids)
from pathlib import Path
atomic_write_text(Path(outdir) / 'sidebar.html', global_sidebar_html)
sidebar_md = generate_tree_markdown(target_ids)
atomic_write_text(Path(outdir) / 'sidebar.md', sidebar_md)
atomic_write_text(Path(outdir) / 'sidebar_orig.md', sidebar_md)
# --- Core Logic (With Override Hook) ---
def process_page(page_id, global_args, active_css_files=None, exported_page_ids=None, verbose=True, manifest=None):
if verbose: print(f"\nProcessing page ID: {page_id}")
# NEW: ETL-Pipeline Integration
from pathlib import Path
raw_data_dir = Path(global_args.outdir) / 'raw-data'
use_etl = hasattr(global_args, 'use_etl') and global_args.use_etl
if use_etl:
# Phase 1: Extract (Download to raw-data/)
from confluence_dump.api.client import ConfluenceClient
from confluence_dump.api.extractor import PageExtractor
if manifest is None:
print(f" ERROR: Manifest not provided in ETL mode", file=sys.stderr)
return
client = ConfluenceClient(
global_args.base_url,
platform_config,
auth_info,
global_args.context_path
)
extractor = PageExtractor(raw_data_dir, client, manifest)
# Extract page (saves to raw-data/)
success = extractor.extract_page(page_id, force=False, verbose=verbose)
if not success:
return
# Collect metadata for sidebar generation
page_dir = raw_data_dir / page_id
meta_path = page_dir / 'meta.json'
if meta_path.exists():
import json
page_meta = json.loads(meta_path.read_text(encoding='utf-8'))
collect_page_metadata(page_meta)
# Note: Manifest will be saved after all pages are processed
return
# 0. Check for Manual Override
override_path = None
if global_args.manual_overrides_dir and os.path.exists(global_args.manual_overrides_dir):
# Check .mhtml first (preferred for complete snapshots)
cand_mhtml = os.path.join(global_args.manual_overrides_dir, f"{page_id}.mhtml")
cand_html = os.path.join(global_args.manual_overrides_dir, f"{page_id}.html")
if os.path.exists(cand_mhtml):
override_path = cand_mhtml
elif os.path.exists(cand_html):
override_path = cand_html
page_full = None
if override_path:
# CASE A: Manual Override
if verbose: print(f" [OVERRIDE] Using local file: {override_path}")
try:
# Metadata Fetch
page_meta = myModules.get_page_basic(page_id, global_args.base_url, platform_config, auth_info,
global_args.context_path)
if not page_meta:
page_meta = {
'id': page_id,
'title': f'Override {page_id}',
'version': {'by': {'displayName': 'Manual Override'}, 'when': datetime.now().isoformat()}
}
raw_manual_html = ""
if override_path.endswith('.mhtml'):
raw_manual_html = extract_html_from_mhtml(override_path)
if not raw_manual_html:
print(f" Error: Could not extract HTML from MHTML {override_path}", file=sys.stderr)
return
else:
# Read HTML
with open(override_path, 'r', encoding='utf-8', errors='replace') as f:
raw_manual_html = f.read()
# --- NEW: CLEANING STEP ---
# Remove hidden elements and junk before processing
cleaned_manual_html = clean_manual_html(raw_manual_html)
page_full = page_meta
# Inject cleaned content
page_full['body'] = {
'export_view': {'value': cleaned_manual_html},
'view': {'value': cleaned_manual_html},
# Note: Storage format usually not available from override unless fetched separately or mocked
'storage': {'value': ''}
}
if 'version' not in page_full:
page_full['version'] = {'by': {'displayName': 'Manual Override'}, 'when': datetime.now().isoformat()}
except Exception as e:
print(f" Error processing override for {page_id}: {e}", file=sys.stderr)
return
else:
# CASE B: Standard API Call
page_full = myModules.get_page_full(page_id, global_args.base_url, platform_config, auth_info,
global_args.context_path)
if not page_full:
print(f" Warning: Could not fetch page {page_id}. Skipping.", file=sys.stderr)
return
if verbose: collect_page_metadata(page_full)
raw_html = page_full.get('body', {}).get('export_view', {}).get('value')
if not raw_html:
raw_html = page_full.get('body', {}).get('view', {}).get('value', '')
# --- Save Storage XML (Source of Truth) ---
storage_content = page_full.get('body', {}).get('storage', {}).get('value')
if global_args.debug_storage and storage_content:
# FIX: Hier Endung .xml anhängen
storage_filename = os.path.join(myModules.outdir_pages, f"{page_id}.body.storage.xml")
try:
with open(storage_filename, 'w', encoding='utf-8') as f:
f.write(storage_content)
except Exception as e:
print(f" Warning: Could not save storage format for {page_id}: {e}", file=sys.stderr)
# --- Save Debug Views ---
if global_args.debug_views:
# Save raw view (what we normally process)
view_content = page_full.get('body', {}).get('view', {}).get('value')
if view_content:
try:
with open(os.path.join(myModules.outdir_pages, f"{page_id}.body.view.html"), 'w',
encoding='utf-8') as f:
f.write(view_content)
except Exception as e:
print(f" Warning: Could not save view format for {page_id}: {e}", file=sys.stderr)
# Save styled view (Confluence styling included)
styled_content = page_full.get('body', {}).get('styled_view', {}).get('value')
if styled_content:
try:
with open(os.path.join(myModules.outdir_pages, f"{page_id}.body.styled_view.html"), 'w',
encoding='utf-8') as f:
f.write(styled_content)
except Exception as e:
print(f" Warning: Could not save styled_view format for {page_id}: {e}", file=sys.stderr)
# --- Pass storage_content to module (for Anchor repair) ---
processed_html = myModules.process_page_content(
raw_html,
page_full,
global_args.base_url,
auth_info,
active_css_files,
exported_page_ids,
global_sidebar_html,
storage_content=storage_content
)
html_filename = os.path.join(myModules.outdir_pages, f"{page_id}.html")
with open(html_filename, 'w', encoding='utf-8') as f:
f.write(processed_html)
page_attachments = myModules.get_page_attachments(page_id, global_args.base_url, platform_config, auth_info,
global_args.context_path)
save_page_attachments(page_id, page_attachments, global_args.base_url, auth_info)
# --- JSON Optional machen ---
if not global_args.no_metadata_json:
json_filename = os.path.join(myModules.outdir_pages, f"{page_id}.json")
page_full['body_processed'] = processed_html
with open(json_filename, 'w', encoding='utf-8') as f:
json.dump(page_full, f, indent=4, ensure_ascii=False)
if global_args.rst:
convert_rst(page_id, processed_html, myModules.outdir_pages)
# --- Index Generation ---
def build_index_html(output_dir, css_files=None):
""" Generates an index.html file listing all downloaded pages hierarchically. """
print("\nGenerating global index.html...")
tree_map, pages_map, root_ids = build_tree_structure(set(p['id'] for p in all_pages_metadata))
def build_list_html(parent_id):
if parent_id not in tree_map: return ""
html = "<ul>\n"
for child_id in tree_map[parent_id]:
if child_id in pages_map:
child = pages_map[child_id]
html += f'<li><a href="pages/{child_id}.html">{child["title"]}</a>'
html += build_list_html(child_id)
html += '</li>\n'
html += "</ul>\n"
return html
from pathlib import Path
from confluence_dump.build.index_builder import IndexBuilder
builder = IndexBuilder(Path(output_dir))
builder.build_index_html(all_pages_metadata, css_files)
# --- Recursive Inventory & Scanning ---
def recursive_scan(page_id, args, exclude_ids, scanned_count, exclude_label=None):
if page_id in exclude_ids:
print(f" [Excluded by ID] Pruning tree at page {page_id}", file=sys.stderr)
return []
tree_ids = [page_id]
scanned_count[0] += 1
if scanned_count[0] % 10 == 0:
sys.stderr.write(f"\rScanned {scanned_count[0]} pages...")
sys.stderr.flush()
while True:
children_data = myModules.get_child_pages(page_id, args.base_url, platform_config, auth_info, args.context_path)
if not children_data or 'results' not in children_data: break
children = children_data['results']
if not children: break
for child in children:
child_id = child['id']
if exclude_label:
labels = [l['name'] for l in child.get('metadata', {}).get('labels', {}).get('results', [])]
if exclude_label in labels:
print(f" [Excluded by Label '{exclude_label}'] Pruning tree at page {child_id}", file=sys.stderr)
continue
collect_page_metadata(child)
tree_ids.extend(recursive_scan(child_id, args, exclude_ids, scanned_count, exclude_label))
break
return tree_ids
def scan_space_inventory(args, exclude_ids):
print("Phase 1: Recursive Inventory Scan...")
scanned_count = [0]
homepage = myModules.get_space_homepage(args.space_key, args.base_url, platform_config, auth_info,
args.context_path)
if not homepage:
print("Error: Could not find Space Homepage.", file=sys.stderr)
return [], []
root_id = homepage['id']
collect_page_metadata(homepage)
all_ids_ordered = recursive_scan(root_id, args, exclude_ids, scanned_count)
print(f"\nInventory complete. Found {len(all_ids_ordered)} pages.")
return set(all_ids_ordered), all_ids_ordered
def scan_tree_inventory(root_id, args, exclude_ids):
print("Phase 1: Recursive Tree Scan...")
scanned_count = [0]
root_page = myModules.get_page_full(root_id, args.base_url, platform_config, auth_info, args.context_path)
if root_page: collect_page_metadata(root_page)
all_ids_ordered = recursive_scan(root_id, args, exclude_ids, scanned_count)
print(f"\nInventory complete. Found {len(all_ids_ordered)} pages.")
return set(all_ids_ordered), all_ids_ordered
def scan_label_forest_inventory(args, exclude_ids):
print(f"Phase 1: Label Forest Scan (Roots: '{args.label}')...")
scanned_count = [0]
root_pages = []
start = 0
while True:
res = myModules.get_pages_by_label(args.label, start, 200, args.base_url, platform_config, auth_info,
args.context_path)
if not res or not res.get('results'): break
for p in res['results']:
if p['id'] in exclude_ids: continue
root_pages.append(p)
start += 200
full_forest_ids = []
exclude_label = getattr(args, 'exclude_label', None)
for root in root_pages:
collect_page_metadata(root)
branch_ids = recursive_scan(root['id'], args, exclude_ids, scanned_count, exclude_label)
full_forest_ids.extend(branch_ids)
unique_ordered = list(dict.fromkeys(full_forest_ids))
print(f"\nInventory complete. Found {len(unique_ordered)} unique pages.")
return set(unique_ordered), unique_ordered
def run_analysis_phase(args, manifest, verbose: bool = True):
"""
Runs Analysis phase (offline detection of complex macros).
Reads from raw-data/ and updates manifest with needs_mhtml flags.
Args:
args: Command-line arguments
manifest: Manifest instance
verbose: If True, print progress information
Returns:
Statistics dictionary from analysis
"""
from pathlib import Path
from confluence_dump.analysis.mhtml_detector import MHTMLDetector
raw_data_dir = Path(args.outdir) / 'raw-data'
detector = MHTMLDetector(raw_data_dir, manifest)
stats = detector.analyze_all_pages(verbose=verbose)
return stats
def run_playwright_phase(args, manifest, verbose: bool = True):
"""
Runs Playwright phase (selective MHTML download).
Downloads pages marked with needs_mhtml in the manifest.
Args:
args: Command-line arguments
manifest: Manifest instance
verbose: If True, print progress information
Returns:
Statistics dictionary from playwright phase
"""
if getattr(args, 'skip_mhtml', False):
print(" Skipping Playwright phase (--skip-mhtml specified)")
return {'success': 0, 'failed': 0, 'skipped': 0}
mhtml_pages = manifest.get_mhtml_pages()
if not mhtml_pages:
if verbose:
print(" No pages require MHTML download. Skipping phase.")
return {'success': 0, 'failed': 0, 'skipped': 0}
from pathlib import Path
from confluence_dump.playwright.mhtml_downloader import MHTMLDownloader
output_dir = Path(args.outdir)
downloader = MHTMLDownloader(output_dir, args.base_url)
stats = downloader.download_pages(mhtml_pages, manifest.data, verbose=verbose)
return stats
def run_build_phase(args, target_ids, active_css_files, manifest=None):
"""
Runs Transform & Load phases (offline HTML generation).
Reads from raw-data/ and generates final HTML in pages/.
Args:
args: Command-line arguments
target_ids: Set of page IDs to build
active_css_files: List of CSS file paths
manifest: Optional Manifest instance (for needs_mhtml lookup)
"""
from pathlib import Path
from confluence_dump.transform.html_processor import HTMLProcessor
from confluence_dump.transform.sidebar_builder import SidebarBuilder
raw_data_dir = Path(args.outdir) / 'raw-data'
pages_dir = Path(args.outdir) / 'pages'
attachments_dir = Path(args.outdir) / 'attachments'
# Ensure we have metadata (might be empty in build-only mode if not loaded from manifest)
if not all_pages_metadata:
print(" Warning: No page metadata available. Sidebar will be empty.")
# 1. Generate sidebar from metadata
print(" Building sidebar navigation...")
sidebar_builder = SidebarBuilder(pages_dir)
sidebar_html = sidebar_builder.build_sidebar_html(all_pages_metadata, target_ids)
# Save sidebar files
global global_sidebar_html
global_sidebar_html = sidebar_html
from confluence_dump.utils.file_ops import atomic_write_text
atomic_write_text(Path(args.outdir) / 'sidebar.html', sidebar_html)
sidebar_md = sidebar_builder.build_sidebar_markdown(all_pages_metadata, target_ids)
atomic_write_text(Path(args.outdir) / 'sidebar.md', sidebar_md)
atomic_write_text(Path(args.outdir) / 'sidebar_orig.md', sidebar_md)
print(f" ✓ Sidebar generated ({len(all_pages_metadata)} pages)")
# 2. Process all pages (Transform & Load)
print(" Processing HTML content...")
from confluence_dump.build.page_builder import PageBuilder
from confluence_dump.api.manifest import Manifest
# Load manifest for needs_mhtml lookup
manifest_obj = Manifest(raw_data_dir)
builder = PageBuilder(raw_data_dir, Path(args.outdir), manifest_obj)
stats = builder.build_all(target_ids, sidebar_html, active_css_files)
print(f" ✓ Build phase complete: {stats['processed']} pages generated")
if stats['errors'] > 0:
print(f" ⚠ {stats['errors']} pages skipped due to errors")
if stats['attachments_copied'] > 0:
print(f" ✓ {stats['attachments_copied']} attachments copied")
# --- Mode Handlers ---
def run_download_phase(args, all_pages_list, target_ids, active_css_files):
use_etl = hasattr(args, 'use_etl') and args.use_etl
if use_etl:
# ETL Pipeline: Extract → Transform → Load
from pathlib import Path
from confluence_dump.api.manifest import Manifest
raw_data_dir = Path(args.outdir) / 'raw-data'
# Initialize manifest ONCE before download
manifest = Manifest(raw_data_dir)
# Phase 1: Extract (Download)
print(f"Phase 1 (Extract): Downloading {len(all_pages_list)} pages with {args.threads} threads...")
with ThreadPoolExecutor(max_workers=args.threads) as executor:
futures = []
for pid in all_pages_list:
# Pass manifest to each thread
futures.append(executor.submit(process_page, pid, args, active_css_files, target_ids, False, manifest))
for _ in tqdm(as_completed(futures), total=len(futures), desc="Extracting", unit="page"):
pass
# Save manifest AFTER all extractions
manifest.save()
print(f"✓ Extract phase complete. Manifest saved with {len(manifest.data.get('pages', {}))} pages.")
# Phase 2: Analysis (Detect pages needing MHTML)
print(f"\nPhase 2 (Analysis): Detecting complex macros...")
analysis_stats = run_analysis_phase(args, manifest, verbose=True)
# Save manifest with updated needs_mhtml flags
manifest.save()
# Phase 3: Playwright (MHTML Download)
print(f"\nPhase 3 (Playwright): Downloading complex pages as MHTML...")
playwright_stats = run_playwright_phase(args, manifest, verbose=True)
# Phase 4: Transform & Load (Build HTML)
print(f"\nPhase 4 (Transform & Load): Building HTML files...")
run_build_phase(args, target_ids, active_css_files, manifest)
else:
# Legacy mode: Download & process in one step
print(f"Phase 2: Downloading & Processing {len(all_pages_list)} pages with {args.threads} threads...")
with ThreadPoolExecutor(max_workers=args.threads) as executor:
futures = []
for pid in all_pages_list:
futures.append(executor.submit(process_page, pid, args, active_css_files, target_ids, verbose=False))
for _ in tqdm(as_completed(futures), total=len(futures), desc="Downloading", unit="page"):
pass
def handle_space(args, active_css_files, exclude_ids):
print(f"Starting 'space' dump for {args.space_key}")
target_ids, all_pages_list = scan_space_inventory(args, exclude_ids)
save_sidebars(args.outdir, target_ids)
run_download_phase(args, all_pages_list, target_ids, active_css_files)
def handle_tree(args, active_css_files, exclude_ids):
print(f"Starting 'tree' dump for {args.pageid}")
target_ids, all_pages_list = scan_tree_inventory(args.pageid, args, exclude_ids)
save_sidebars(args.outdir, target_ids)
run_download_phase(args, all_pages_list, target_ids, active_css_files)
def handle_label(args, active_css_files, exclude_ids):
print(f"Starting 'label' dump for {args.label}")
target_ids, all_pages_list = scan_label_forest_inventory(args, exclude_ids)
save_sidebars(args.outdir, target_ids)
run_download_phase(args, all_pages_list, target_ids, active_css_files)
def handle_single(args, active_css_files, exclude_ids):
print(f"Starting 'single' dump for {args.pageid}")
use_etl = hasattr(args, 'use_etl') and args.use_etl
if use_etl:
# ETL mode: Use manifest
from pathlib import Path
from confluence_dump.api.manifest import Manifest
raw_data_dir = Path(args.outdir) / 'raw-data'
manifest = Manifest(raw_data_dir)
process_page(args.pageid, args, active_css_files, {args.pageid}, verbose=True, manifest=manifest)
# Save manifest
manifest.save()
print(f"✓ Extract phase complete. Manifest saved.")
# Analysis phase
print(f"\nPhase 2 (Analysis): Detecting complex macros...")
analysis_stats = run_analysis_phase(args, manifest, verbose=True)
manifest.save()
# Playwright phase
print(f"\nPhase 3 (Playwright): Downloading complex pages as MHTML...")
playwright_stats = run_playwright_phase(args, manifest, verbose=True)
# Build phase
print(f"\nPhase 4 (Transform & Load): Building HTML files...")
run_build_phase(args, {args.pageid}, active_css_files, manifest)
else:
# Legacy mode
root = myModules.get_page_full(args.pageid, args.base_url, platform_config, auth_info, args.context_path)
if root: collect_page_metadata(root)
save_sidebars(args.outdir, {args.pageid})
process_page(args.pageid, args, active_css_files, {args.pageid}, verbose=True)
def handle_all_spaces(args, active_css_files, exclude_ids):
print("Starting 'all-spaces' dump...")
spaces = myModules.get_all_spaces(args.base_url, platform_config, auth_info, args.context_path)
if spaces and 'results' in spaces:
for s in spaces['results']:
print(f"\n--- Processing Space: {s['key']} ---")
global all_pages_metadata, global_sidebar_html, seen_metadata_ids
all_pages_metadata = []
seen_metadata_ids = set()
s_args = argparse.Namespace(**vars(args))
s_args.space_key = s['key']
handle_space(s_args, active_css_files, exclude_ids)
# --- Main ---
def main():
# --- EARLY CHECK: Detect redundant parameters in Delta-Sync mode ---
# This must happen BEFORE argparse, because argparse will fail with cryptic errors
# if the user passes commands/parameters that should be loaded from config.json
# Extract --outdir from sys.argv (simple parsing before argparse)
outdir_value = None
for i, arg in enumerate(sys.argv):
if arg in ('-o', '--outdir') and i + 1 < len(sys.argv):
outdir_value = sys.argv[i + 1]
break
# Check if workspace exists (has config.json)
if outdir_value:
workspace_dir = Path(outdir_value)
config_path = workspace_dir / 'config.json'
if config_path.exists() and '--init' not in sys.argv:
# This is a SYNC operation - check for redundant parameters
# Common mistakes: passing commands (space, tree, single, label) or their parameters
forbidden_in_sync = ['space', 'tree', 'single', 'label', 'all-spaces',
'--pageid', '-p', '--space-key', '-sp', '--label', '-l']
found_redundant = []
for arg in sys.argv[1:]: # Skip script name
if arg in forbidden_in_sync:
found_redundant.append(arg)
if found_redundant:
print(f"\n╔════════════════════════════════════════════════════════════════╗", file=sys.stderr)
print(f"║ ERROR: Redundant parameters detected in Delta-Sync mode ║", file=sys.stderr)
print(f"╚════════════════════════════════════════════════════════════════╝", file=sys.stderr)
print(f"\n📋 PROBLEM:", file=sys.stderr)
print(f" You specified download parameters, but this workspace already exists.", file=sys.stderr)
print(f" Detected redundant parameters: {', '.join(found_redundant)}", file=sys.stderr)
print(f"\n🔍 CAUSE:", file=sys.stderr)
print(f" Delta-Sync automatically loads all parameters from the workspace configuration.", file=sys.stderr)
print(f" Manually specifying commands or page IDs would create conflicts.", file=sys.stderr)
print(f"\n✅ SOLUTION OPTIONS:", file=sys.stderr)
print(f" 1. For Delta-Sync: Only specify the workspace directory:", file=sys.stderr)
print(f" python confluenceDumpToHTML.py --use-etl -o \"{workspace_dir}\"", file=sys.stderr)
print(f"\n 2. To rebuild with NEW parameters: Use --init flag:", file=sys.stderr)
print(f" python confluenceDumpToHTML.py --use-etl --init -o \"{workspace_dir}\" [NEW_PARAMETERS]", file=sys.stderr)
print(f"\n 3. To create a completely new export: Use a different directory:", file=sys.stderr)
print(f" python confluenceDumpToHTML.py --use-etl -o \"./output\" [PARAMETERS]", file=sys.stderr)
print(f"\n💡 TIP: The saved configuration can be found at:", file=sys.stderr)
print(f" {config_path}", file=sys.stderr)
sys.exit(1)
# --- Continue with normal argparse ---
parser = argparse.ArgumentParser(
description="Confluence Dump (Cloud/DC) with HTML Processing",
formatter_class=argparse.RawTextHelpFormatter
)
g = parser.add_argument_group('Global Options')
g.add_argument('-o', '--outdir', required=True, help="Output directory (Workspace)")
g.add_argument('--base-url', required=False, help="Confluence Base URL (required for initial download)")
g.add_argument('--profile', required=False, help="cloud or dc (required for initial download)")
g.add_argument('--context-path', default=None, help="Context path (DC only)")
g.add_argument('--css-file', default=None, help="Path to custom CSS file")
g.add_argument('-R', '--rst', action='store_true', help="Also export RST")
g.add_argument('-t', '--threads', type=int, default=1, help="Number of threads for download (Default: 1)")
g.add_argument('--exclude-page-id', action='append', help="Exclude a page ID and its children")
g.add_argument('--no-vpn-reminder', action='store_true', help="Skip the VPN check confirmation for Data Center")
g.add_argument('--manual-overrides-dir', help="Folder containing [pageId].html files to use instead of API")
g.add_argument('--debug-storage', action='store_true', help="Save Confluence Storage Format (.storage.xml)")
g.add_argument('--debug-views', action='store_true', help="Save original/styled HTML views for debugging")
g.add_argument('--no-metadata-json', action='store_true', help="Do not save the JSON metadata file")
g.add_argument('--use-etl', action='store_true', help="Use new ETL pipeline (Extract to raw-data/)")
g.add_argument('--skip-mhtml', action='store_true', help="Skip Playwright MHTML downloads for complex pages")
g.add_argument('--init', action='store_true', help="Reset workspace (delete raw-data/, pages/, attachments/)")
g.add_argument('--build-only', action='store_true', help="Skip download, only rebuild HTML from raw-data/ (offline mode)")
subs = parser.add_subparsers(dest='command', required=False, title="Commands")
p_single = subs.add_parser('single', help="Dump a single page")
p_single.add_argument('-p', '--pageid', required=True, help="Page ID")
p_single.set_defaults(func=handle_single)
p_tree = subs.add_parser('tree', help="Dump a page tree (Recursive)")
p_tree.add_argument('-p', '--pageid', required=True, help="Root Page ID")
p_tree.set_defaults(func=handle_tree)
p_space = subs.add_parser('space', help="Dump an entire space (Recursive from Homepage)")
p_space.add_argument('-sp', '--space-key', required=True, help="Space Key")
p_space.set_defaults(func=handle_space)
p_label = subs.add_parser('label', help="Dump pages by label (Forest Mode)")
p_label.add_argument('-l', '--label', required=True, help="Include Label")
p_label.add_argument('--exclude-label', help="Exclude subtrees with this label")
p_label.set_defaults(func=handle_label)
p_all = subs.add_parser('all-spaces', help="Dump all visible spaces")
p_all.set_defaults(func=handle_all_spaces)