-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb-cloner.py
More file actions
942 lines (789 loc) · 37.4 KB
/
Copy pathweb-cloner.py
File metadata and controls
942 lines (789 loc) · 37.4 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
import tkinter as tk
from tkinter import filedialog, messagebox, IntVar, Checkbutton, ttk
import requests
from bs4 import BeautifulSoup
import os
import shutil
import mimetypes
import re
import threading
from urllib.parse import urlparse, urljoin, unquote
import time
import customtkinter as ctk
import webbrowser
from PIL import Image, ImageTk
# Control variables for pause and cancel
PAUSED = False
CANCELLED = False
# Initial CustomTkinter configuration
ctk.set_appearance_mode("dark") # Start in dark mode
ctk.set_default_color_theme("blue") # Base themes: blue, dark-blue, green
# Custom colors for dark mode (Premium Dark)
DARK_COLORS = {
"fg_color": "#0F0F0F", # Deeper, cleaner black
"text_color": "#F0F0F0", # Soft white
"button_color": "#007AFF", # Professional Blue
"button_text_color": "#FFFFFF",
"progress_color": "#34C759", # iOS Green
"accent_color": "#007AFF",
"hover_color": "#0051A8", # Darker blue
"border_color": "#2C2C2E", # Subtle border
"entry_bg_color": "#1C1C1E", # Darker entry
"checkbox_color": "#007AFF",
"warning_color": "#FFCC00",
"error_color": "#FF3B30",
"success_color": "#34C759"
}
# Custom colors for light mode (Premium Light)
LIGHT_COLORS = {
"fg_color": "#F2F2F7", # Very light gray
"text_color": "#1C1C1E", # Deep gray for better readability
"button_color": "#007AFF", # Consistent blue
"button_text_color": "#FFFFFF",
"progress_color": "#34C759",
"accent_color": "#007AFF",
"hover_color": "#0051A8",
"border_color": "#C7C7CC",
"entry_bg_color": "#FFFFFF",
"checkbox_color": "#007AFF",
"warning_color": "#FF9500",
"error_color": "#FF3B30",
"success_color": "#34C759"
}
# Variable for current theme control
current_theme = "dark"
# Translation dictionaries
translations = {
'en': {
'title': 'Website Cloner',
'window_title': 'Website Cloner',
'url_label': 'URL to clone:',
'url_placeholder': 'Enter the URL of the website to clone',
'url_to_clone': 'URL to clone:',
'base_url_label': 'New base URL (absolute or relative):',
'base_url_placeholder': 'Enter the base URL of the website',
'new_base_url': 'New base URL (absolute or relative):',
'output_folder_label': 'Output folder name:',
'output_folder_placeholder': 'Enter the name of the output folder',
'output_folder': 'Output folder name:',
'include_images': 'Include images',
'create_zip': 'Create ZIP file',
'keep_folder': 'Keep uncompressed folder',
'appearance_mode': 'Appearance Mode:',
'ready_to_clone': 'Ready to clone',
'clone_site': '🔄 Clone Site',
'clone_button': '🔄 Clone Site',
'pause': '⏸️ Pause',
'resume': '▶️ Resume',
'cancel': '❌ Cancel',
'downloading_main': 'Downloading main page...',
'analyzing_html': 'Analyzing HTML structure...',
'processing_styles': 'Processing internal styles...',
'identifying_resources': 'Identifying resources...',
'downloading_resources': 'Downloading resources ({0}/{1})...',
'compressing_site': 'Compressing cloned site...',
'completed': 'Completed!',
'paused': '⏸️ Paused',
'resumed': '▶️ Resumed',
'process_paused': 'Process paused... 🔄',
'cancelling_process': 'Cancelling process...',
'process_cancelled': 'Process cancelled.',
'error_occurred': 'An error occurred while cloning the site.',
'success_message': 'The site has been cloned and saved as \'{0}.zip\'.',
'success_message_no_zip': 'The site has been cloned and saved in \'{0}\'.',
'url_required': 'Both URL fields are required.',
'crawl_depth': 'Crawling Depth (Levels):',
'max_pages': 'Maximum Pages:',
'cloning_page': 'Cloning page {0} of {1}...',
'discovery_links': 'Discovering links...',
'output_option_required': 'You must select at least one output option: Create ZIP or Keep folder.',
'settings': '⚙️ Settings',
'settings_button': '⚙️ Settings',
'theme': 'Theme',
'theme_menu': 'Theme',
'light': 'Light',
'dark': 'Dark',
'light_theme': 'Light',
'dark_theme': 'Dark',
'light_mode': '☀️', # Sun icon for light mode
'dark_mode': '🌙', # Moon icon for dark mode
'theme_toggle_dark': '🌙',
'theme_toggle_light': '☀️',
'default_folder': 'cloned_site',
'cleanup_cancelled': 'Cleaning up cancelled process...',
'about': 'About',
'about_title': 'About Web Cloner',
'about_message': "© zainsardar-tech\n\nA high-performance utility designed for seamless website cloning, resource optimization, and architectural analysis. Built for developers and researchers to analyze and replicate web structures with precision.",
'github_profile': 'GitHub Profile',
'error': 'Error',
'success': 'Success',
'confirm': 'Confirm',
'cancel_confirm': 'Are you sure you want to cancel the cloning process?',
'cloning_error': 'An error occurred during cloning',
'process_error': 'Process error',
'both_created': 'The site has been cloned. Files are available at:\nZIP: {0}\nFolder: {1}',
'zip_created': 'The site has been cloned and saved as {0}',
'folder_kept': 'The site has been cloned and saved in {0}'
}
}
# Global variable for current language
current_language = 'en'
def apply_theme_colors():
"""Apply the colors of the current theme to the interface"""
colors = DARK_COLORS if current_theme == "dark" else LIGHT_COLORS
# Apply custom colors to different elements
app.configure(fg_color=colors["fg_color"])
main_scrollable_frame.configure(fg_color=colors["fg_color"])
# Configure main buttons
btn_clone.configure(
fg_color=colors["button_color"],
text_color=colors.get("button_text_color", colors["fg_color"]),
hover_color=colors["hover_color"]
)
btn_pause.configure(
fg_color=colors["button_color"],
text_color=colors.get("button_text_color", colors["fg_color"]),
hover_color=colors["hover_color"]
)
btn_cancel.configure(
fg_color=colors["button_color"],
text_color=colors.get("button_text_color", colors["fg_color"]),
hover_color=colors["hover_color"]
)
# Configure progress bar
progress_bar.configure(
progress_color=colors["progress_color"]
)
# Configure theme toggle button
theme_toggle_button.configure(
text="",
image=light_icon if current_theme == "dark" else dark_icon,
fg_color="transparent",
hover_color=colors["hover_color"]
)
# Apply text color to labels
# Update configuration labels
for label in [url_label, base_url_label, output_folder_label, depth_label, max_pages_label, depth_value_label]:
label.configure(text_color=colors["text_color"])
# Configure Info button
about_button.configure(
fg_color=colors["button_color"],
text_color=colors.get("button_text_color", colors["fg_color"]),
hover_color=colors["hover_color"]
)
# Configure checkboxes
include_images_check.configure(
text_color=colors["text_color"],
fg_color=colors.get("checkbox_color", colors["button_color"]),
hover_color=colors["hover_color"]
)
create_zip_check.configure(
text_color=colors["text_color"],
fg_color=colors.get("checkbox_color", colors["button_color"]),
hover_color=colors["hover_color"]
)
keep_folder_check.configure(
text_color=colors["text_color"],
fg_color=colors.get("checkbox_color", colors["button_color"]),
hover_color=colors["hover_color"]
)
# Configure input fields
for entry in [entry_url, entry_base_url, entry_output_folder, max_pages_entry]:
entry.configure(
fg_color=colors.get("entry_bg_color", colors["fg_color"]),
text_color=colors["text_color"],
border_color=colors["border_color"]
)
def toggle_theme():
"""Alterna entre el tema claro y oscuro"""
global current_theme
# Cambiar el tema actual
current_theme = "light" if current_theme == "dark" else "dark"
# Configurar el modo de apariencia de CustomTkinter
ctk.set_appearance_mode(current_theme)
# Aplicar colores personalizados
apply_theme_colors()
def update_language():
"""Update all UI text from the English translation dictionary"""
# Current language is always 'en' now
lang = 'en'
# Update window title
app.title(translations[lang]['window_title'])
# Update labels and placeholder of fields
url_label.configure(text=translations[lang]['url_label'])
entry_url.configure(placeholder_text=translations[lang]['url_placeholder'])
base_url_label.configure(text=translations[lang]['base_url_label'])
entry_base_url.configure(placeholder_text=translations[lang]['base_url_placeholder'])
output_folder_label.configure(text=translations[lang]['output_folder_label'])
entry_output_folder.configure(placeholder_text=translations[lang]['output_folder_placeholder'])
# Update buttons
btn_clone.configure(text=translations[lang]['clone_button'])
btn_pause.configure(text=translations[lang]['pause'])
btn_cancel.configure(text=translations[lang]['cancel'])
# Update advanced labels
depth_label.configure(text=translations[lang]['crawl_depth'])
max_pages_label.configure(text=translations[lang]['max_pages'])
# Update checkbox
include_images_check.configure(text=translations[lang]['include_images'])
create_zip_check.configure(text=translations[lang]['create_zip'])
keep_folder_check.configure(text=translations[lang]['keep_folder'])
# Update progress label
progress_label.configure(text=translations[lang]['ready_to_clone'])
# Update main title
title_label.configure(text=translations[lang]['title'])
def extract_css_urls(css_content, base_url):
# This function extracts image URLs from CSS rules
extracted_urls = []
# Patterns for url() in CSS
patterns = [
r'url\(["\']?(.*?)["\']?\)', # url('example.jpg'), url("example.jpg"), url(example.jpg)
r'@import\s+["\']([^"\']+)["\']', # @import 'example.css', @import "example.css"
r'@import\s+url\(["\']?([^"\'()]+)["\']?\)' # @import url('example.css'), @import url("example.css"), @import url(example.css)
]
for pattern in patterns:
for match in re.finditer(pattern, css_content):
url = match.group(1).strip()
if url and not url.startswith(('data:', 'javascript:', '#')):
absolute_url = urljoin(base_url, url)
extracted_urls.append(absolute_url)
return extracted_urls
def normalize_url(url):
"""Normalizes URLs by ensuring they have the correct protocol"""
if not url:
return url
# If the URL already has a protocol, return it as is
if url.startswith(('http://', 'https://')):
return url
# Try HTTPS first (preferred)
https_url = f"https://{url}"
try:
# Make a HEAD request to verify if the site is available with HTTPS
response = requests.head(https_url, timeout=5)
if response.status_code < 400: # Any code less than 400 is considered successful
return https_url
except Exception:
pass
# If HTTPS is not available or gave an error, use HTTP
return f"http://{url}"
def get_unique_folder_name(base_name):
"""Generates a unique folder name to avoid overwriting existing files"""
if not os.path.exists(base_name):
return base_name
counter = 1
while True:
new_name = f"{base_name}_{counter}"
if not os.path.exists(new_name):
return new_name
counter += 1
def fetch_and_clone_website(source_url, base_url, output_folder='cloned_site', include_images=True, create_zip=True, keep_folder=True, progress_callback=None, depth=0, max_pages=10):
global PAUSED, CANCELLED
current_output_folder = None
try:
unique_output_folder = get_unique_folder_name(output_folder)
current_output_folder = unique_output_folder
os.makedirs(unique_output_folder, exist_ok=True)
# BFS Queue: (url, current_depth)
queue = [(source_url, 0)]
visited = {source_url}
pages_cloned = 0
total_resources_discovered = []
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
while queue and pages_cloned < max_pages:
if CANCELLED: break
current_url, current_depth = queue.pop(0)
pages_cloned += 1
if progress_callback:
progress_callback(10 + int((pages_cloned/max_pages)*10),
translations[current_language]['cloning_page'].format(pages_cloned, len(visited)))
try:
response = requests.get(current_url, headers=headers, timeout=10)
if response.status_code != 200: continue
soup = BeautifulSoup(response.text, 'html.parser')
# IMPORTANT: Remove <base> tags to avoid overriding local relative paths
for base in soup.find_all('base'):
base.decompose()
# Determine local file path for this page
parsed_current = urlparse(current_url)
local_path = parsed_current.path
if not local_path or local_path.endswith('/'):
local_path += "index.html"
elif not local_path.endswith('.html'):
local_path += ".html"
full_local_path = os.path.join(unique_output_folder, local_path.lstrip('/'))
os.makedirs(os.path.dirname(full_local_path), exist_ok=True)
html_dir = os.path.dirname(full_local_path)
# Discover links and rewrite them relatively
for link in soup.find_all('a', href=True):
full_link = urljoin(current_url, link['href'])
parsed_link = urlparse(full_link)
if parsed_link.netloc == urlparse(source_url).netloc:
clean_link = full_link.split('#')[0].rstrip('/')
# Link discovery
if clean_link not in visited and len(visited) < max_pages and current_depth < depth:
visited.add(clean_link)
queue.append((clean_link, current_depth + 1))
# Rewrite to local relative path
target_link_path = parsed_link.path
if not target_link_path or target_link_path.endswith('/'): target_link_path += "index.html"
elif not target_link_path.endswith('.html'): target_link_path += ".html"
abs_target_path = os.path.join(unique_output_folder, target_link_path.lstrip('/'))
rel_link = os.path.relpath(abs_target_path, html_dir)
link['href'] = rel_link
# Deep attribute scanning for resources
asset_attrs = ['src', 'href', 'data-src', 'data-bg', 'srcset', 'poster']
for tag in soup.find_all(True):
for attr in asset_attrs:
if tag.has_attr(attr):
val = tag[attr]
if isinstance(val, list): val = val[0] # Handle srcset lists
resource_url = urljoin(current_url, val)
if not resource_url.startswith(('http://', 'https://')): continue
if resource_url.startswith(('mailto:', 'tel:', 'javascript:', 'data:')): continue
# Only process assets, not internal page links (already handled)
if tag.name == 'a' and attr == 'href': continue
# IMPORTANT: Strip integrity and crossorigin to avoid SRI blockers
if tag.has_attr('integrity'): del tag['integrity']
if tag.has_attr('crossorigin'): del tag['crossorigin']
# Save resource and get final absolute path
abs_res_path = save_resource(resource_url, unique_output_folder, current_url)
if abs_res_path:
# Rewrite to relative path from current HTML
rel_resource_path = os.path.relpath(abs_res_path, html_dir)
tag[attr] = rel_resource_path
# Save the page
with open(full_local_path, 'w', encoding='utf-8') as f:
f.write(str(soup))
except Exception as e:
print(f"Error cloning {current_url}: {e}")
continue
# Finishing up
zip_file_path = None
if create_zip:
if progress_callback: progress_callback(95, translations[current_language]['compressing_site'])
shutil.make_archive(unique_output_folder, 'zip', unique_output_folder)
zip_file_path = f"{unique_output_folder}.zip"
if not keep_folder:
shutil.rmtree(unique_output_folder)
unique_output_folder = None
if progress_callback: progress_callback(100, translations[current_language]['completed'])
return True, unique_output_folder, zip_file_path
if progress_callback: progress_callback(100, translations[current_language]['completed'])
return True, unique_output_folder, zip_file_path
except Exception as e:
import traceback
traceback.print_exc()
return False, None, current_output_folder
def save_resource(resource_url, output_dir, source_url):
"""Downloads a resource and returns its absolute local path"""
try:
parsed_url = urlparse(resource_url)
if not parsed_url.scheme:
resource_url = urljoin(source_url, resource_url)
parsed_url = urlparse(resource_url)
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(resource_url, stream=True, headers=headers, timeout=10)
response.raise_for_status()
# Isolate external assets
source_domain = urlparse(source_url).netloc
res_domain = parsed_url.netloc
path = unquote(parsed_url.path).lstrip('/')
if not path or path.endswith('/'): path += "index.html"
if res_domain and res_domain != source_domain:
# Save external assets in a dedicated folder
resource_rel_path = os.path.join("_external", res_domain, path)
else:
resource_rel_path = path
# Determine extension from MIME type if missing
content_type = response.headers.get('Content-Type', '').split(';')[0].strip()
mime_map = {
'text/css': '.css',
'application/javascript': '.js',
'text/javascript': '.js',
'image/jpeg': '.jpg',
'image/png': '.png',
'image/gif': '.gif',
'image/svg+xml': '.svg',
'image/webp': '.webp',
'image/avif': '.avif'
}
current_ext = os.path.splitext(resource_rel_path)[1].lower()
if not current_ext and content_type in mime_map:
resource_rel_path += mime_map[content_type]
final_abs_path = os.path.join(output_dir, resource_rel_path)
os.makedirs(os.path.dirname(final_abs_path), exist_ok=True)
if 'text/' in content_type or resource_rel_path.endswith(('.css', '.js', '.svg')):
with open(final_abs_path, 'w', encoding='utf-8') as f:
f.write(response.text)
if resource_rel_path.endswith('.css'):
for css_res in extract_css_urls(response.text, resource_url):
save_resource(css_res, output_dir, resource_url)
else:
with open(final_abs_path, 'wb') as f:
shutil.copyfileobj(response.raw, f)
return final_abs_path
except Exception as e:
print(f"Fail: {resource_url} - {e}")
return None
def update_progress(value, message):
"""Function to update the progress bar and message with improved formatting"""
colors = DARK_COLORS if current_theme == "dark" else LIGHT_COLORS
# Update process in the UI
if value == -1: # Special value for paused state
progress_label.configure(
text=message,
text_color=colors["warning_color"]
)
elif value == 0: # Special value for cancelled state
progress_label.configure(
text=message,
text_color=colors["error_color"]
)
progress_bar.set(0)
else:
normalized_value = value / 100
progress_bar.set(normalized_value)
progress_label.configure(
text=message,
text_color=colors["success_color"] if value >= 100 else colors["text_color"]
)
# Force update to avoid freezing
app.update()
def toggle_pause():
"""Function to toggle the pause state"""
global PAUSED
PAUSED = not PAUSED
if PAUSED:
btn_pause.configure(text=translations[current_language]['resume'])
else:
btn_pause.configure(text=translations[current_language]['pause'])
def cancel_process():
"""Function to cancel the cloning process"""
global CANCELLED
# Ask for confirmation before cancelling
if messagebox.askyesno(
translations[current_language]['confirm'],
translations[current_language]['cancel_confirm']
):
CANCELLED = True
update_progress(0, translations[current_language]['cleanup_cancelled'])
# Reset UI
btn_clone.configure(state="normal")
btn_pause.configure(state="disabled")
btn_cancel.configure(state="disabled")
def cleanup_cancelled_files(folder_path, zip_path):
"""Limpia los archivos creados por un proceso cancelado"""
if folder_path and os.path.exists(folder_path):
try:
update_progress(0, translations[current_language]['cleanup_cancelled'])
shutil.rmtree(folder_path)
except Exception as e:
print(f"Error cleaning up folder: {e}")
if zip_path and os.path.exists(zip_path):
try:
update_progress(0, translations[current_language]['cleanup_cancelled'])
os.remove(zip_path)
except Exception as e:
print(f"Error cleaning up ZIP file: {e}")
def clone_site_thread():
"""Function to run the cloning process in a separate thread"""
global PAUSED, CANCELLED
# Get values from UI
url = entry_url.get().strip()
base_url = entry_base_url.get().strip() or url
output_folder = entry_output_folder.get().strip() or "cloned_site"
# Visual validation
if not url:
messagebox.showerror(
translations[current_language]['error'],
translations[current_language]['url_required']
)
return
# Validate the output options
if create_zip_var.get() == 0 and keep_folder_var.get() == 0:
messagebox.showerror(
translations[current_language]['error'],
translations[current_language]['output_option_required']
)
return
# Normalize URLs if needed
url = normalize_url(url)
base_url = normalize_url(base_url) if base_url else url
# Update UI for cloning state
btn_clone.configure(state="disabled")
btn_pause.configure(state="normal")
btn_cancel.configure(state="normal")
# Reset control flags
PAUSED = False
CANCELLED = False
# Execute the cloning process in a separate thread to not block the interface
threading.Thread(target=lambda: execute_cloning(url, base_url, output_folder), daemon=True).start()
def execute_cloning(url, base_url, output_folder):
"""Function to execute the actual cloning process"""
try:
success, zip_path, folder_path = fetch_and_clone_website(
url,
base_url,
output_folder,
include_images_var.get(),
create_zip_var.get(),
keep_folder_var.get(),
update_progress,
int(crawl_depth_var.get()),
int(max_pages_entry.get())
)
# Process is completed
app.after(0, lambda: complete_cloning(success, zip_path, folder_path))
except Exception as e:
# Handle errors
error_message = str(e)
app.after(0, lambda: handle_error(error_message))
def complete_cloning(success, zip_path, folder_path):
"""Function to handle the completion of the cloning process"""
# Reset UI
btn_clone.configure(state="normal")
btn_pause.configure(state="disabled")
btn_cancel.configure(state="disabled")
# Show success message if completed successfully
if success:
if create_zip_var.get() and keep_folder_var.get():
# Both ZIP and folder
messagebox.showinfo(
translations[current_language]['success'],
translations[current_language]['both_created'].format(
zip_path + ".zip" if zip_path else "",
folder_path if folder_path else ""
)
)
elif create_zip_var.get():
# Only ZIP
messagebox.showinfo(
translations[current_language]['success'],
translations[current_language]['zip_created'].format(
zip_path + ".zip" if zip_path else ""
)
)
elif keep_folder_var.get():
# Only folder
messagebox.showinfo(
translations[current_language]['success'],
translations[current_language]['folder_kept'].format(
folder_path if folder_path else ""
)
)
def handle_error(error_message):
"""Function to handle errors during the cloning process"""
# Reset UI
btn_clone.configure(state="normal")
btn_pause.configure(state="disabled")
btn_cancel.configure(state="disabled")
# Show error message
messagebox.showerror(
translations[current_language]['error'],
f"{translations[current_language]['cloning_error']}: {error_message}"
)
# Reset progress bar
update_progress(0, translations[current_language]['process_error'])
# Interconnection between checkboxes for mandatory selection logic
def update_checkbox_states(*args):
"""Function to handle the logic of the output checkboxes"""
create_zip_value = create_zip_var.get()
keep_folder_value = keep_folder_var.get()
# If both are disabled, force at least one to be active
# The last one that was disabled is reactivated
if create_zip_value == 0 and keep_folder_value == 0:
# We use the last checkbox that was attempted to be disabled
if args and args[0] == 'create_zip':
keep_folder_var.set(1)
else:
create_zip_var.set(1)
def show_about_dialog():
"""Show the About dialog with program information and support links"""
# Create a custom about dialog window
about_window = ctk.CTkToplevel(app)
about_window.title(translations[current_language]['about_title'])
about_window.geometry("500x350") # Increased size for better text display
about_window.resizable(False, False)
# Center the window
about_window.update_idletasks()
x = app.winfo_x() + (app.winfo_width() // 2) - (about_window.winfo_width() // 2)
y = app.winfo_y() + (app.winfo_height() // 2) - (about_window.winfo_height() // 2)
about_window.geometry(f"+{x}+{y}")
# Focus and grab (with delay to avoid 'not viewable' error)
about_window.focus_set()
about_window.after(100, lambda: about_window.grab_set())
# Main frame
main_frame = ctk.CTkFrame(about_window)
main_frame.pack(fill="both", expand=True, padx=20, pady=20)
# App info
colors = DARK_COLORS if current_theme == "dark" else LIGHT_COLORS
info_label = ctk.CTkLabel(
main_frame,
text=translations[current_language]['about_message'],
font=ctk.CTkFont(size=14),
justify="center",
text_color=colors["text_color"],
wraplength=460 # Set wraplength to ensure text wraps properly
)
info_label.pack(pady=20)
# Function to open URLs
def open_url(url):
webbrowser.open(url)
# Support buttons
buttons_frame = ctk.CTkFrame(main_frame, fg_color="transparent")
buttons_frame.pack(pady=10)
# LinkedIn button
linkedin_button = ctk.CTkButton(
buttons_frame,
text="🔗 LinkedIn",
command=lambda: open_url("https://linkedin.com/in/zain-sardar"),
width=120,
height=35,
fg_color="#0A66C2",
hover_color="#0850A0"
)
linkedin_button.pack(side="left", padx=5)
# WhatsApp button
whatsapp_button = ctk.CTkButton(
buttons_frame,
text="💬 WhatsApp",
command=lambda: open_url("https://wa.me/923246270322?text=Hi%20Zain%2C%20I%20have%20a%20query%20about%20Web%20Cloner"),
width=130,
height=35,
fg_color="#25D366",
hover_color="#1DA851"
)
whatsapp_button.pack(side="left", padx=5)
# GitHub Profile button
github_button = ctk.CTkButton(
buttons_frame,
text=translations[current_language]['github_profile'],
command=lambda: open_url("https://github.com/zainsardar-tech"),
width=140,
height=35
)
github_button.pack(side="left", padx=5)
# Credits label
credits_label = ctk.CTkLabel(
main_frame,
text="© zainsardar-tech | zasolpk.com",
font=ctk.CTkFont(size=11),
text_color="gray"
)
credits_label.pack(pady=(5,0))
# Close button
close_button = ctk.CTkButton(
main_frame,
text="OK",
command=about_window.destroy,
width=100,
height=35
)
close_button.pack(pady=10)
# Main application window using CustomTkinter
app = ctk.CTk()
app.title(translations[current_language]['window_title'])
app.geometry("750x650")
# Set application icon
try:
_icon_img = Image.open("/home/zainsardar/.gemini/antigravity/brain/7133e1f2-d8ee-4229-a774-836aaea64667/web_cloner_app_icon_1773926029286.png")
_icon_img = _icon_img.resize((64, 64), Image.LANCZOS)
_icon_photo = ImageTk.PhotoImage(_icon_img)
app.wm_iconphoto(True, _icon_photo)
except Exception:
pass
# Main container
main_scrollable_frame = ctk.CTkScrollableFrame(app, fg_color="transparent")
main_scrollable_frame.pack(fill="both", expand=True, padx=20, pady=20)
# Load icons for theme toggle
light_icon = ctk.CTkImage(light_image=Image.open("light_icon.png"), dark_image=Image.open("light_icon.png"), size=(30, 30))
dark_icon = ctk.CTkImage(light_image=Image.open("dark_icon.png"), dark_image=Image.open("dark_icon.png"), size=(30, 30))
# 1. Header Card
header_card = ctk.CTkFrame(main_scrollable_frame, height=80, corner_radius=15)
header_card.pack(fill="x", pady=(0, 20))
title_label = ctk.CTkLabel(header_card, text=translations[current_language]['title'],
font=ctk.CTkFont(size=32, weight="bold"))
title_label.pack(side="left", padx=30, pady=20)
top_actions_frame = ctk.CTkFrame(header_card, fg_color="transparent")
top_actions_frame.pack(side="right", padx=30)
appearance_mode_menu = ctk.CTkButton(top_actions_frame, text="",
image=dark_icon,
width=40, height=40,
fg_color="transparent",
command=toggle_theme)
appearance_mode_menu.pack(side="left", padx=5)
# Rename to avoid breaking other logic if it expects 'theme_toggle_button'
theme_toggle_button = appearance_mode_menu
about_button = ctk.CTkButton(top_actions_frame, text="Info", width=60,
command=show_about_dialog)
about_button.pack(side="left", padx=5)
# 2. Configuration Card
config_card = ctk.CTkFrame(main_scrollable_frame, corner_radius=15)
config_card.pack(fill="x", pady=10)
url_label = ctk.CTkLabel(config_card, text=f"🔗 {translations[current_language]['url_label']}", font=ctk.CTkFont(size=14, weight="bold"))
url_label.pack(anchor="w", padx=30, pady=(20, 5))
entry_url = ctk.CTkEntry(config_card, placeholder_text=translations[current_language]['url_placeholder'], height=45, corner_radius=10)
entry_url.pack(fill="x", padx=30, pady=(0, 15))
base_url_label = ctk.CTkLabel(config_card, text=f"🌐 {translations[current_language]['base_url_label']}", font=ctk.CTkFont(size=14, weight="bold"))
base_url_label.pack(anchor="w", padx=30, pady=(5, 5))
entry_base_url = ctk.CTkEntry(config_card, placeholder_text=translations[current_language]['base_url_placeholder'], height=45, corner_radius=10)
entry_base_url.pack(fill="x", padx=30, pady=(0, 15))
output_folder_label = ctk.CTkLabel(config_card, text=f"📂 {translations[current_language]['output_folder_label']}", font=ctk.CTkFont(size=14, weight="bold"))
output_folder_label.pack(anchor="w", padx=30, pady=(5, 5))
entry_output_folder = ctk.CTkEntry(config_card, placeholder_text=translations[current_language]['output_folder_placeholder'], height=45, corner_radius=10)
entry_output_folder.pack(fill="x", padx=30, pady=(0, 25))
# 3. Options Card
options_card = ctk.CTkFrame(main_scrollable_frame, corner_radius=15)
options_card.pack(fill="x", pady=10)
options_title = ctk.CTkLabel(options_card, text="⚙️ Output Configuration", font=ctk.CTkFont(size=14, weight="bold"))
options_title.pack(anchor="w", padx=30, pady=(15, 10))
check_container = ctk.CTkFrame(options_card, fg_color="transparent")
check_container.pack(fill="x", padx=30, pady=(0, 15))
include_images_var = tk.IntVar(value=1)
include_images_check = ctk.CTkCheckBox(check_container, text=translations[current_language]['include_images'], variable=include_images_var)
include_images_check.pack(side="left", padx=(0, 20))
create_zip_var = tk.IntVar(value=1)
create_zip_check = ctk.CTkCheckBox(check_container, text=translations[current_language]['create_zip'], variable=create_zip_var,
command=lambda: update_checkbox_states('create_zip'))
create_zip_check.pack(side="left", padx=20)
keep_folder_var = tk.IntVar(value=1)
keep_folder_check = ctk.CTkCheckBox(check_container, text=translations[current_language]['keep_folder'], variable=keep_folder_var,
command=lambda: update_checkbox_states('keep_folder'))
keep_folder_check.pack(side="left", padx=20)
# 3b. Advance Options (Depth/Limit)
advance_options_frame = ctk.CTkFrame(options_card, fg_color="transparent")
advance_options_frame.pack(fill="x", padx=30, pady=(0, 20))
depth_label = ctk.CTkLabel(advance_options_frame, text=translations[current_language]['crawl_depth'], font=ctk.CTkFont(size=12))
depth_label.pack(side="left", padx=(0, 10))
crawl_depth_var = tk.StringVar(value="0")
depth_slider = ctk.CTkSlider(advance_options_frame, from_=0, to=3, number_of_steps=3, width=100,
command=lambda v: crawl_depth_var.set(str(int(v))))
depth_slider.set(0)
depth_slider.pack(side="left", padx=10)
depth_value_label = ctk.CTkLabel(advance_options_frame, textvariable=crawl_depth_var, width=20)
depth_value_label.pack(side="left")
max_pages_label = ctk.CTkLabel(advance_options_frame, text=translations[current_language]['max_pages'], font=ctk.CTkFont(size=12))
max_pages_label.pack(side="left", padx=(30, 10))
max_pages_entry = ctk.CTkEntry(advance_options_frame, width=60, placeholder_text="10")
max_pages_entry.insert(0, "10")
max_pages_entry.pack(side="left")
# 4. Progress & Actions Card
actions_card = ctk.CTkFrame(main_scrollable_frame, corner_radius=15)
actions_card.pack(fill="x", pady=10)
progress_bar = ctk.CTkProgressBar(actions_card, height=18, corner_radius=10)
progress_bar.pack(fill="x", padx=30, pady=(25, 10))
progress_bar.set(0)
progress_label = ctk.CTkLabel(actions_card, text=translations[current_language]['ready_to_clone'], font=ctk.CTkFont(size=13))
progress_label.pack(pady=(0, 20))
btn_container = ctk.CTkFrame(actions_card, fg_color="transparent")
btn_container.pack(fill="x", padx=30, pady=(0, 25))
btn_clone = ctk.CTkButton(btn_container, text=translations[current_language]['clone_button'], command=clone_site_thread, height=55, font=ctk.CTkFont(size=16, weight="bold"), corner_radius=12)
btn_clone.pack(side="left", fill="x", expand=True, padx=(0, 5))
btn_pause = ctk.CTkButton(btn_container, text=translations[current_language]['pause'], command=toggle_pause, height=55, state="disabled", corner_radius=12)
btn_pause.pack(side="left", fill="x", expand=True, padx=5)
btn_cancel = ctk.CTkButton(btn_container, text=translations[current_language]['cancel'], command=cancel_process, height=55, state="disabled", corner_radius=12)
btn_cancel.pack(side="left", fill="x", expand=True, padx=(5, 0))
# Apply initial theme
apply_theme_colors()
if __name__ == "__main__":
update_language()
app.mainloop()