Repository navigation
Expand file tree
/
Copy pathbuild.py
More file actions
1063 lines (932 loc) · 42.2 KB
/
Copy pathbuild.py
File metadata and controls
1063 lines (932 loc) · 42.2 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
r"""
WinZapp build script — PyInstaller variant.
Build modes:
--onedir (default): PyInstaller --onedir -> WinZapp.exe + _internal/
Then assemble staging dir + create installer + portable zip.
--onefile: PyInstaller --onefile -> WinZapp.exe (single file)
All Python deps + external resources (node/, api/, lib/,
sounds/, languages/, data/) are embedded in the exe
and extracted to a temp directory at runtime.
Steps (onedir default):
1. Check required tools (pyinstaller, gcc, windres) and pre-built api/ + client/node/
2. Compile client with PyInstaller -> build/pyinstaller_out/
3. Assemble staging dir -> WinZapp.exe + _internal/ + lib/ + sounds/ + languages/
+ data/ + node/ + api/
4. Compile uninstaller -> build/uninstall.exe
5. Create payload ZIP (ZIP_STORED) from staging/
6. Compile installer stub -> build/installer_stub.exe
7. Append payload ZIP to stub -> dist/WinZappInstaller.exe
8. Create portable dist/WinZapp.zip
Steps (onefile):
1. Check tools (no gcc/windres needed)
2. Compile client with PyInstaller --onefile -> dist/WinZapp.exe
3. Create portable dist/WinZapp.zip from the single .exe
Before running this script, install its Python dependencies, either way:
uv sync
-- or --
python -m venv venv
venv\Scripts\pip install -r requirements.txt -r requirements-dev.txt
The script downloads the checksum-verified portable Node.js runtime (replacing
a client/node/ that is not exactly the homologated version) and runs
setup_api.py automatically when client/api/dist/server.js is absent.
Usage:
uv run build-installer (onedir, default)
uv run build-onefile (single-file exe)
venv\Scripts\python.exe build.py (onedir, default)
venv\Scripts\python.exe build.py --onefile
Whichever interpreter starts it, the build runs under the one
winzapp_tools.build_env.select_build_python() picks: WINZAPP_VENV, then the
running virtual environment, then venv\ or .venv\ in the repository.
"""
import os
import re
import sys
import shutil
import subprocess
import zipfile
import argparse
import io
import glob
import tarfile
import urllib.request
import importlib.util
import sysconfig
import hashlib
import tempfile
# -- Paths -------------------------------------------------------------------
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
CLIENT_DIR = os.path.join(ROOT_DIR, "client")
INSTALLER_DIR = os.path.join(ROOT_DIR, "installer")
BUILD_DIR = os.path.join(ROOT_DIR, "build")
DIST_DIR = os.path.join(ROOT_DIR, "dist")
# External pre-built assets
NODE_DIR = os.path.join(CLIENT_DIR, "node")
API_DIR = os.path.join(CLIENT_DIR, "api")
if ROOT_DIR not in sys.path:
sys.path.insert(0, ROOT_DIR)
from winzapp_tools.build_env import ( # noqa: E402
hand_over_to_build_python,
portable_node_needs_replacing,
portable_node_version,
)
# Before uv, build.py hardcoded venv\ and worked from any interpreter. Now it
# builds with the one running it, so a bare `python build.py` is handed to
# venv\ (or .venv\) here — before anything below reads site-packages.
if __name__ == "__main__":
hand_over_to_build_python(__file__, ROOT_DIR)
def _load_node_download_config():
"""client/node_download_config.py, loaded by path.
Putting client/ on sys.path instead would let its modules (config,
version, updater...) shadow anything this script imports afterwards.
"""
import importlib.util as _ilu
spec = _ilu.spec_from_file_location(
"_winzapp_node_download_config",
os.path.join(CLIENT_DIR, "node_download_config.py"),
)
module = _ilu.module_from_spec(spec)
spec.loader.exec_module(module)
return module
# Keep the build on the exact portable runtime the application downloads for
# end users. build-windows.yml reads the same file.
_node_config = _load_node_download_config()
NODE_VERSION = _node_config.NODE_VERSION
NODE_FILENAME = _node_config.NODE_FILENAME
NODE_SHASUMS_URL = _node_config.NODE_SHASUMS_URL
NODE_TOP_DIR = _node_config.NODE_TOP_DIR
NODE_URL = _node_config.NODE_URL
# The interpreter running this script is the build environment (see
# _hand_over_to_build_python). Invoking PyInstaller as a module keeps it and
# its installed packages in lockstep, under uv and venv alike.
PYTHON_CMD = sys.executable
PYINSTALLER_CMD = [PYTHON_CMD, "-m", "PyInstaller"]
GCC_CMD = "gcc"
WINDRES_CMD = "windres"
# PyInstaller output directories
PYINST_OUTDIR = os.path.join(BUILD_DIR, "pyinstaller_out")
PYINST_APP_DIR = os.path.join(PYINST_OUTDIR, "WinZapp")
PYINST_EXE = os.path.join(PYINST_APP_DIR, "WinZapp.exe")
PYINST_INTERNAL = os.path.join(PYINST_APP_DIR, "_internal")
# Onefile output
ONEFILE_EXE = os.path.join(DIST_DIR, "WinZapp.exe")
# Staging dir (onedir only)
STAGING_DIR = os.path.join(BUILD_DIR, "staging_pyinstaller")
# Installer paths (onedir only)
PAYLOAD_ZIP = os.path.join(BUILD_DIR, "payload_pyinstaller.zip")
INSTALLER_STUB = os.path.join(BUILD_DIR, "installer_stub.exe")
INSTALLER_RES = os.path.join(BUILD_DIR, "installer_res.o")
UNINSTALLER_RES = os.path.join(BUILD_DIR, "uninstaller_res.o")
UNINSTALLER_EXE = os.path.join(BUILD_DIR, "uninstall.exe")
INSTALLER_OUT = os.path.join(DIST_DIR, "WinZappInstaller.exe")
PORTABLE_ZIP = os.path.join(DIST_DIR, "WinZapp.zip")
SETTINGS_DEFAULT = os.path.join(CLIENT_DIR, "data", "settings_default.json")
SITE_PACKAGES = sysconfig.get_paths()["purelib"]
SOUND_LIB_X64 = os.path.join(SITE_PACKAGES, "sound_lib", "lib", "x64")
AO2_LIB = os.path.join(SITE_PACKAGES, "accessible_output2", "lib")
# libopus-0.dll — required by client/core/ogg_opus.py for OGG Opus encoding.
# libopus is a native C library (NOT a Python package). On Windows it ships
# with MSYS2 (mingw-w64-ucrt-x86_64-opus) or can be installed via Chocolatey /
# vcpkg. build.py searches common locations; if not found it auto-downloads the
# DLL from the MSYS2 package mirror and saves it to client/lib/.
def _find_opus_dll_on_disk():
"""Search known filesystem locations for libopus-0.dll / opus.dll."""
candidates = [
os.path.join(CLIENT_DIR, "lib", "libopus-0.dll"),
os.path.join(CLIENT_DIR, "lib", "opus.dll"),
r"C:\msys64\ucrt64\bin\libopus-0.dll", # MSYS2 UCRT64 (CI + local)
r"C:\msys64\mingw64\bin\libopus-0.dll", # MSYS2 MinGW64
r"C:\msys2\ucrt64\bin\libopus-0.dll", # alternate MSYS2 root
r"C:\msys2\mingw64\bin\libopus-0.dll",
r"C:\ProgramData\chocolatey\bin\libopus-0.dll", # Chocolatey
r"C:\ProgramData\scoop\shims\libopus-0.dll", # Scoop
]
for path_dir in os.environ.get("PATH", "").split(os.pathsep):
if path_dir:
candidates.append(os.path.join(path_dir, "libopus-0.dll"))
candidates.append(os.path.join(path_dir, "opus.dll"))
return next((p for p in candidates if os.path.isfile(p)), None)
def _download_opus_dll():
"""Download libopus-0.dll from the MSYS2 package mirror.
Uses the MSYS2 packages API to find the latest package URL, then downloads
and extracts the DLL from the .tar.zst archive into client/lib/.
Requires the ``zstandard`` package (pyproject.toml / requirements.txt).
"""
dst_dir = os.path.join(CLIENT_DIR, "lib")
dst = os.path.join(dst_dir, "libopus-0.dll")
print(" [opus] libopus-0.dll not found locally — downloading from MSYS2...")
try:
import zstandard # pyproject.toml / requirements.txt
except ImportError:
print(" [WARN] 'zstandard' package not installed; cannot auto-download libopus.")
print(" Run: uv sync (or: pip install -r requirements.txt)")
return None
# Query the MSYS2 package API to discover the download URL for the latest
# opus package in the UCRT64 repository.
api_url = (
"https://packages.msys2.org/api/packages/ucrt64/"
"mingw-w64-ucrt-x86_64-opus"
)
try:
req = urllib.request.Request(api_url, headers={"User-Agent": "WinZapp-build"})
with urllib.request.urlopen(req, timeout=30) as resp:
import json
info = json.loads(resp.read())
# The API returns a list; pick the first (most recent).
entry = info[0] if isinstance(info, list) else info
pkg_filename = entry.get("filename") or entry.get("name") or ""
pkg_url = (
entry.get("url")
or entry.get("download_url")
or (
f"https://mirror.msys2.org/mingw/ucrt64/{pkg_filename}"
if pkg_filename else ""
)
)
except Exception as exc:
# API query failed — fall back to a pinned version URL.
print(f" [opus] MSYS2 API unavailable ({exc}); using pinned version 1.5.2.")
pkg_url = (
"https://mirror.msys2.org/mingw/ucrt64/"
"mingw-w64-ucrt-x86_64-opus-1.5.2-1-any.pkg.tar.zst"
)
if not pkg_url:
print(" [WARN] Could not determine libopus package URL.")
return None
print(f" [opus] Downloading {pkg_url} ...")
try:
req = urllib.request.Request(pkg_url, headers={"User-Agent": "WinZapp-build"})
with urllib.request.urlopen(req, timeout=120) as resp:
pkg_data = resp.read()
except Exception as exc:
print(f" [WARN] Download failed: {exc}")
return None
# The .pkg.tar.zst archive is a zstd-compressed tar.
# Inside, the DLL lives at ucrt64/bin/libopus-0.dll
print(" [opus] Extracting libopus-0.dll ...")
try:
dctx = zstandard.ZstdDecompressor()
with dctx.stream_reader(io.BytesIO(pkg_data)) as zst_reader:
with tarfile.open(fileobj=zst_reader) as tar:
dll_member = next(
(m for m in tar.getmembers()
if m.name.endswith("/libopus-0.dll") or m.name == "libopus-0.dll"),
None,
)
if dll_member is None:
print(" [WARN] libopus-0.dll not found inside the package.")
return None
f = tar.extractfile(dll_member)
os.makedirs(dst_dir, exist_ok=True)
with open(dst, "wb") as out:
out.write(f.read())
except Exception as exc:
print(f" [WARN] Extraction failed: {exc}")
return None
print(f" [opus] Saved to {dst}")
return dst
def _find_opus_dll():
"""Find or auto-download libopus-0.dll for bundling."""
found = _find_opus_dll_on_disk()
if found:
return found
# Not found locally — attempt auto-download.
downloaded = _download_opus_dll()
if downloaded:
return downloaded
print(
" [WARN] libopus-0.dll not found and auto-download failed.\n"
" Voice messages will not work in the built app.\n"
" To fix: install MSYS2 and run:\n"
" pacman -S mingw-w64-ucrt-x86_64-opus\n"
" Or copy libopus-0.dll to client/lib/libopus-0.dll"
)
return None
OPUS_DLL = _find_opus_dll()
def _prepare_ffmpeg():
"""Find or download ffmpeg.exe and place it in client/lib/ for bundling."""
lib_dir = os.path.join(CLIENT_DIR, "lib")
os.makedirs(lib_dir, exist_ok=True)
dst = os.path.join(lib_dir, "ffmpeg.exe")
if os.path.isfile(dst):
return dst
import glob as _glob
installer_root = os.path.join(CLIENT_DIR, "api", "node_modules", "@ffmpeg-installer")
hits = _glob.glob(os.path.join(installer_root, "**", "ffmpeg.exe"), recursive=True)
if not hits:
hits = _glob.glob(os.path.join(installer_root, "**", "ffmpeg"), recursive=True)
ffmpeg_src = hits[0] if hits else shutil.which("ffmpeg")
if not (ffmpeg_src and os.path.isfile(ffmpeg_src)):
try:
print(" [INFO] Downloading portable ffmpeg.exe for release bundle...")
import zipfile, tempfile, urllib.request
dl_url = "https://github.com/ffbinaries/ffbinaries-prebuilt/releases/download/v4.4.1/ffmpeg-4.4.1-win-64.zip"
temp_zip = os.path.join(tempfile.gettempdir(), "ffmpeg_build_win.zip")
urllib.request.urlretrieve(dl_url, temp_zip)
with zipfile.ZipFile(temp_zip, "r") as zf:
zf.extract("ffmpeg.exe", lib_dir)
if os.path.isfile(dst):
return dst
except Exception as dl_err:
print(f" [WARN] Failed to download prebuilt ffmpeg: {dl_err}")
if ffmpeg_src and os.path.isfile(ffmpeg_src):
shutil.copy2(ffmpeg_src, dst)
return dst
return None
FFMPEG_EXE = _prepare_ffmpeg()
# Directories inside api/ that must NOT be copied
API_EXCLUDE_DIRS = {
"wppconnect_tokens", "userDataDir", ".git", "__pycache__", "node_modules",
".github", ".husky", ".vscode", "src", "log", "tokens", "uploads",
"WhatsAppImages", "tests", "coverage",
".cache",
}
API_EXCLUDE_FILES = {
".gitignore", "README-SETUP.md", ".babelrc", ".eslintignore", ".eslintrc.js",
".eslintrc.json", ".prettierrc", ".prettierignore", "jest.config.js",
"tsconfig.json", "tsconfig.tsbuildinfo", "README.md", "CHANGELOG.md",
"LICENSE", "LICENSE.header", "license-checker-config.json",
"package-lock.json", "yarn.lock", "pnpm-lock.yaml", ".yarnrc.yml",
".env.example", "nodemon.json", ".npmignore", ".npmrc",
".commitlintrc.json", ".dockerignore", ".release-it.yml",
"Dockerfile", "docker-compose.yml", "requests.http",
"swagger-backup.json",
}
API_EXCLUDE_SUB_DIRS = {"tests", "types"}
# WinZapp's own patches on top of upstream wppconnect-server (same list as
# setup_api.py's custom_files). API_EXCLUDE_DIRS skips all of src/ wholesale
# since only the compiled client/api/dist/server.js runs at build time — but
# the user wants these specific source files copied into the shipped api/
# folder too (alongside .env/start.js/package.json/config.json) so they're
# visible/patchable directly from an extracted install, not just at dev time.
API_CUSTOM_SRC_FILES = [
"src/config.ts",
"src/util/callMediaBridge.ts",
"src/util/createSessionUtil.ts",
"src/util/functions.ts",
"src/util/tokenStore/fileTokenStory.ts",
"src/middleware/statusConnection.ts",
"src/middleware/auth.ts",
"src/middleware/socketAuth.ts",
"src/controller/callController.ts",
"src/controller/deviceController.ts",
"src/controller/messageController.ts",
"src/controller/sessionController.ts",
"src/controller/statusController.ts",
"dist/middleware/auth.js",
]
# -- CLI --------------------------------------------------------------------
parser = argparse.ArgumentParser(
description="WinZapp build script — PyInstaller variant"
)
parser.add_argument(
"--onefile", action="store_true",
help="Build single-file .exe with all resources embedded (default: onedir)"
)
args = parser.parse_args()
ONEFILE = args.onefile
# -- Helpers ----------------------------------------------------------------
def step(msg):
print(f"\n{'-'*60}")
print(f" {msg}")
print('-'*60)
def run(cmd, cwd=None):
print(f" $ {' '.join(str(c) for c in cmd)}")
result = subprocess.run(cmd, cwd=cwd)
if result.returncode != 0:
print(f"\n[ERROR] Command failed with exit code {result.returncode}.")
sys.exit(result.returncode)
def walk_dir(root, exclude_top_dirs=None, exclude_top_files=None, exclude_sub_dirs=None):
exclude_top_dirs = exclude_top_dirs or set()
exclude_top_files = exclude_top_files or set()
exclude_sub_dirs = exclude_sub_dirs or set()
for dirpath, dirs, files in os.walk(root):
rel_dir = os.path.relpath(dirpath, root)
top = rel_dir.split(os.sep)[0] if rel_dir != "." else ""
if top in exclude_top_dirs:
dirs.clear()
continue
dirs[:] = [d for d in dirs if not (
(rel_dir == "." and d in exclude_top_dirs) or
d in exclude_sub_dirs
)]
for fname in files:
if rel_dir == "." and fname in exclude_top_files:
continue
abs_path = os.path.join(dirpath, fname)
rel_path = os.path.relpath(abs_path, root).replace("\\", "/")
yield abs_path, rel_path
def _api_patches_out_of_sync():
"""Return the client/api_patches/ relative paths that differ from (or
are missing in) client/api/ — the same drift tests/test_api_patches_in_sync.py
checks for CI. Patched files a dev edited only in client/api_patches/
(the tracked source of truth) without re-running setup_api.py would
otherwise silently ship whatever client/api/dist/server.js was already
built from — a stale/reverted patch baked into the release with no
warning, since check_tools() below only ever verified dist/server.js
*exists*, never that it matches the current patches.
"""
import importlib.util
spec = importlib.util.spec_from_file_location(
"setup_api", os.path.join(ROOT_DIR, "setup_api.py")
)
setup_api = importlib.util.module_from_spec(spec)
spec.loader.exec_module(setup_api)
out_of_sync = []
for rel_path in setup_api.CUSTOM_ROOT_FILES + setup_api.CUSTOM_SRC_FILES:
patch_path = os.path.join(setup_api.API_PATCHES_DIR, rel_path)
live_path = os.path.join(setup_api.CLIENT_API_DIR, rel_path)
if not os.path.isfile(patch_path):
continue # nothing tracked to compare against for this one
if not os.path.isfile(live_path):
out_of_sync.append(rel_path)
continue
with open(patch_path, "rb") as f:
patch_bytes = f.read()
with open(live_path, "rb") as f:
live_bytes = f.read()
if patch_bytes != live_bytes:
out_of_sync.append(rel_path)
return out_of_sync
def _resync_api_patches(out_of_sync):
"""Re-run setup_api.py so it restores the drifted files from
client/api_patches/ and rebuilds client/api/dist/server.js from them —
a plain file copy alone would leave dist/server.js stale (it's
precompiled JS; only `npm run build` regenerates it from the patched
.ts sources), exactly the gap that made this drift shippable at all.
"""
print(" [WARN] client/api/ has drifted from client/api_patches/ — re-running setup_api.py:")
for rel_path in out_of_sync:
print(f" {rel_path}")
run([PYTHON_CMD, os.path.join(ROOT_DIR, "setup_api.py")])
def _download_portable_node():
"""Download and checksum-verify the runtime bundled into local builds."""
print(f" [bootstrap] Downloading portable Node.js v{NODE_VERSION}...")
# ignore_cleanup_errors: a scanner briefly holding a file in the retired
# runtime must not fail a build whose Node.js was already replaced.
with tempfile.TemporaryDirectory(prefix="winzapp-node-", dir=ROOT_DIR,
ignore_cleanup_errors=True) as tmp:
archive = os.path.join(tmp, NODE_FILENAME)
checksums = os.path.join(tmp, "SHASUMS256.txt")
urllib.request.urlretrieve(NODE_URL, archive)
urllib.request.urlretrieve(NODE_SHASUMS_URL, checksums)
with open(checksums, encoding="utf-8") as fh:
expected = next(
(line.split()[0] for line in fh if line.rstrip().endswith(NODE_FILENAME)),
None,
)
with open(archive, "rb") as fh:
actual = hashlib.sha256(fh.read()).hexdigest()
if not expected or actual.lower() != expected.lower():
raise RuntimeError(
f"Node.js checksum mismatch for {NODE_FILENAME}: "
f"expected {expected or 'missing'}, got {actual}"
)
with zipfile.ZipFile(archive) as zf:
zf.extractall(tmp)
extracted = os.path.join(tmp, NODE_TOP_DIR)
if not os.path.isfile(os.path.join(extracted, "node.exe")):
raise RuntimeError("Node.js archive did not contain node.exe")
retired = None
if os.path.isdir(NODE_DIR):
# Rename first: it fails atomically while node.exe is running,
# where rmtree would delete half the folder and then stop on the
# locked exe, leaving no working Node.js at all.
retired = os.path.join(tmp, "node-previous")
try:
os.rename(NODE_DIR, retired)
except OSError as exc:
raise RuntimeError(
f"Could not replace {NODE_DIR} ({exc}). Is a WinZapp or "
"node.exe started from it still running?"
) from exc
try:
shutil.move(extracted, NODE_DIR)
except OSError:
# Put the previous runtime back rather than leave none at all.
if retired and not os.path.exists(NODE_DIR):
os.rename(retired, NODE_DIR)
raise
print(f" [bootstrap] Portable Node.js ready at {NODE_DIR}")
def ensure_build_assets():
"""Prepare generated runtime inputs that a local build should not require manually."""
# Checked before the bootstrap below, which can spend minutes downloading
# Node.js and running setup_api.py only for check_tools() to then report
# that the onedir build was never possible on this machine.
if not ONEFILE:
missing_native = [t for t in (GCC_CMD, WINDRES_CMD) if shutil.which(t) is None]
if missing_native:
print(
f"\n[ERROR] {', '.join(missing_native)} not found in PATH. The installer "
"build needs MSYS2 UCRT64 (gcc + binutils); use --onefile to build "
"without them."
)
sys.exit(1)
installed = portable_node_version(os.path.join(NODE_DIR, "node.exe"))
if portable_node_needs_replacing(installed, NODE_VERSION):
if installed:
print(
f" [bootstrap] client/node/ is Node.js v{installed}; "
f"the homologated runtime is v{NODE_VERSION}."
)
_download_portable_node()
if not os.path.isfile(os.path.join(API_DIR, "dist", "server.js")):
print(" [bootstrap] WPPConnect API is missing; running setup_api.py...")
run([PYTHON_CMD, os.path.join(ROOT_DIR, "setup_api.py")])
# -- Step 1: Check tools and pre-built assets --------------------------------
def check_tools():
step("1/8 Checking required tools and pre-built assets")
missing = []
if importlib.util.find_spec("PyInstaller") is None:
missing.append(
f"pyinstaller (not installed for {PYTHON_CMD})\n"
" Install with: uv sync\n"
" or: pip install -r requirements.txt -r requirements-dev.txt"
)
if not ONEFILE:
for tool, name in [(GCC_CMD, "gcc"), (WINDRES_CMD, "windres")]:
if shutil.which(tool) is None:
missing.append(f"{name} (not found in PATH)")
node_exe = os.path.join(NODE_DIR, "node.exe")
if not os.path.isfile(node_exe):
missing.append(
f"client/node/node.exe (download portable Node.js for Windows x64 and "
f"extract to {NODE_DIR})"
)
# If client/api/ already exists, catch it having drifted from
# client/api_patches/ (a patch edited but setup_api.py never re-run)
# before checking dist/server.js below — re-running setup_api.py here
# both restores the patches AND rebuilds dist/server.js from them,
# closing the gap that let a stale/reverted patch ship silently.
if os.path.isdir(API_DIR):
out_of_sync = _api_patches_out_of_sync()
if out_of_sync:
_resync_api_patches(out_of_sync)
api_main = os.path.join(API_DIR, "dist", "server.js")
if not os.path.isfile(api_main):
missing.append(
"client/api/dist/server.js -- WPPConnect Server API not built,\n"
" even after running setup_api.py. Check its output above, then\n"
" retry with: uv run setup-api (or: python setup_api.py)"
)
if OPUS_DLL:
print(f" [opus] libopus found: {OPUS_DLL}")
else:
print(
" [WARN] libopus-0.dll not found — voice messages will fail in the built app.\n"
" Install MSYS2 and run: pacman -S mingw-w64-ucrt-x86_64-opus\n"
" Or copy libopus-0.dll to client/lib/"
)
if missing:
print("\n[ERROR] Missing required tools or pre-built assets:")
for m in missing:
print(f" - {m}")
sys.exit(1)
print(" All tools and assets found.")
# -- Step 2: PyInstaller compile --------------------------------------------
# -- Windows VERSIONINFO resource --------------------------------------------
def _app_version_tuple():
"""(major, minor, patch, build) read off client/version.py.
Windows VERSIONINFO wants exactly four 16-bit integers, and WinZapp's own
version string may carry a pre-release suffix ("0.25.0.0beta",
"1.0.0.2154alpha" — see the auto-updater section of CLAUDE.md), which has
no place in the resource. Only the numeric components are read; a missing
or unparseable one becomes 0 rather than failing the build, and each is
clamped to 65535 because an alpha's fourth component is a commit count and
will eventually pass that.
"""
version = ""
version_py = os.path.join(CLIENT_DIR, "version.py")
try:
with io.open(version_py, encoding="utf-8") as fh:
for line in fh:
if line.strip().startswith("__version__"):
version = line.split("=", 1)[1].strip().strip("\"'")
break
except OSError:
pass
parts = []
for chunk in re.split(r"[.\-+]", version):
m = re.match(r"^(\d+)", chunk.strip())
parts.append(min(int(m.group(1)), 65535) if m else 0)
parts = (parts + [0, 0, 0, 0])[:4]
return version or "0.0.0.0", tuple(parts)
def _write_version_file(work_dir):
"""Generate the PyInstaller --version-file that fills in Windows'
Properties > Details for WinZapp.exe (issue #88).
Without it the built exe carries no VERSIONINFO resource at all: Windows
shows blank File description / File version / Product name, which also
makes the process indistinguishable in Task Manager and unhelpful to
anyone reporting a bug ("which version are you running?"). Generated on
every build from client/version.py, so it cannot drift from the version
the app itself displays — that is the "updated automatically as part of
the build process" half of the request.
Note this covers WinZapp.exe only. The onedir installer/uninstaller stubs
are C, compiled through installer/*.rc by windres, and would need their own
(generated) VERSIONINFO block there.
"""
display, (maj, minr, patch, build) = _app_version_tuple()
os.makedirs(work_dir, exist_ok=True)
path = os.path.join(work_dir, "winzapp_version_info.txt")
content = f"""VSVersionInfo(
ffi=FixedFileInfo(
filevers=({maj}, {minr}, {patch}, {build}),
prodvers=({maj}, {minr}, {patch}, {build}),
mask=0x3f,
flags=0x0,
OS=0x40004,
fileType=0x1,
subtype=0x0,
date=(0, 0)
),
kids=[
StringFileInfo([
StringTable(
'040904B0',
[StringStruct('CompanyName', 'WinZapp'),
StringStruct('FileDescription', 'WinZapp - accessible WhatsApp client'),
StringStruct('FileVersion', '{display}'),
StringStruct('InternalName', 'WinZapp'),
StringStruct('LegalCopyright', '© 2026 WinZapp - LGPLv3'),
StringStruct('OriginalFilename', 'WinZapp.exe'),
StringStruct('ProductName', 'WinZapp'),
StringStruct('ProductVersion', '{display}')])
]),
VarFileInfo([VarStruct('Translation', [1033, 1200])])
]
)
"""
with io.open(path, "w", encoding="utf-8") as fh:
fh.write(content)
print(f" [versioninfo] {display} -> {path}")
return path
def pyinstaller_compile():
mode = "onefile" if ONEFILE else "onedir"
step(f"2/8 Compiling client with PyInstaller (--{mode})")
os.makedirs(BUILD_DIR, exist_ok=True)
if ONEFILE:
os.makedirs(DIST_DIR, exist_ok=True)
else:
os.makedirs(PYINST_OUTDIR, exist_ok=True)
if os.path.isdir(PYINST_APP_DIR):
shutil.rmtree(PYINST_APP_DIR)
work_dir = os.path.join(BUILD_DIR, "pyinstaller_work")
collect_all = [
"sound_lib",
"accessible_output2",
"platform_utils",
"libloader",
"wx",
"cryptography",
"requests",
"socketio",
"engineio",
"pyperclip",
"packaging",
"windows_toasts",
"winrt",
"pyaudio",
"aiosqlite",
]
cmd = [
*PYINSTALLER_CMD,
"--onefile" if ONEFILE else "--onedir",
"--windowed",
"--name", "WinZapp",
"--distpath", DIST_DIR if ONEFILE else PYINST_OUTDIR,
"--workpath", work_dir,
"--version-file", _write_version_file(work_dir),
"--noconfirm",
]
for pkg in collect_all:
cmd += ["--collect-all", pkg]
cmd += ["--paths", CLIENT_DIR]
# In onefile mode, embed external resources as --add-data / --add-binary
if ONEFILE:
add_data_pairs = [
(NODE_DIR, "node"),
(API_DIR, "api"),
(SOUND_LIB_X64, "lib"),
(AO2_LIB, "lib"),
(os.path.join(CLIENT_DIR, "sounds"), "sounds"),
(os.path.join(CLIENT_DIR, "languages"), "languages"),
(SETTINGS_DEFAULT, os.path.join("data", "settings_default.json")),
]
wpp_min_version_file = os.path.join(CLIENT_DIR, "wpp_minimum_version.txt")
if os.path.isfile(wpp_min_version_file):
add_data_pairs.append((wpp_min_version_file, "wpp_minimum_version.txt"))
for src, dst in add_data_pairs:
if os.path.exists(src):
cmd += ["--add-data", f"{src};{dst}"]
# libopus DLL must be bundled as a binary so ctypes can load it at runtime
if OPUS_DLL:
cmd += ["--add-binary", f"{OPUS_DLL};lib"]
if FFMPEG_EXE:
cmd += ["--add-binary", f"{FFMPEG_EXE};lib"]
# Multi-account modules that may be reached only via lazy imports — pin them
# as hidden imports so PyInstaller always bundles them even if a top-level
# static import path doesn't reach them (e.g. session_store is imported only
# from the live session flow). Belt-and-suspenders; harmless if already found.
for _hm in ("accounts", "coord_locks", "node_coord", "ipc", "update_coord",
"app_settings", "account_migration", "account_bootstrap",
"account_launcher", "account_ui", "session_store", "window_title"):
cmd += ["--hidden-import", _hm]
cmd.append(os.path.join(CLIENT_DIR, "main.py"))
run(cmd, cwd=CLIENT_DIR)
if ONEFILE:
if not os.path.isfile(ONEFILE_EXE):
print(f"[ERROR] PyInstaller did not produce {ONEFILE_EXE}")
sys.exit(1)
size_mb = os.path.getsize(ONEFILE_EXE) / (1024 * 1024)
print(f" -> {ONEFILE_EXE} ({size_mb:.1f} MB)")
else:
if not os.path.isfile(PYINST_EXE):
print(f"[ERROR] PyInstaller did not produce {PYINST_EXE}")
sys.exit(1)
size_mb = os.path.getsize(PYINST_EXE) / (1024 * 1024)
print(f" -> {PYINST_EXE} ({size_mb:.1f} MB)")
if os.path.isdir(PYINST_INTERNAL):
count = sum(1 for _, _, fs in os.walk(PYINST_INTERNAL) for _ in fs)
print(f" -> {PYINST_INTERNAL} ({count} files)")
# -- Step 3: Assemble staging dir (onedir only) -----------------------------
def assemble_staging():
step("3/8 Assembling staging distribution")
if os.path.isdir(STAGING_DIR):
shutil.rmtree(STAGING_DIR)
os.makedirs(STAGING_DIR)
shutil.copy2(PYINST_EXE, os.path.join(STAGING_DIR, "WinZapp.exe"))
print(f" -> WinZapp.exe")
if os.path.isdir(PYINST_INTERNAL):
dst_internal = os.path.join(STAGING_DIR, "_internal")
shutil.copytree(PYINST_INTERNAL, dst_internal)
count = sum(1 for _, _, fs in os.walk(dst_internal) for _ in fs)
print(f" -> _internal/ ({count} files)")
else:
print(" [WARN] _internal/ directory not found in PyInstaller output")
lib_dir = os.path.join(STAGING_DIR, "lib")
os.makedirs(lib_dir)
dll_count = 0
if os.path.isdir(SOUND_LIB_X64):
for fname in os.listdir(SOUND_LIB_X64):
if fname.lower().endswith(".dll"):
shutil.copy2(os.path.join(SOUND_LIB_X64, fname),
os.path.join(lib_dir, fname))
dll_count += 1
if os.path.isdir(AO2_LIB):
for fname in os.listdir(AO2_LIB):
if fname.lower().endswith(".dll"):
shutil.copy2(os.path.join(AO2_LIB, fname),
os.path.join(lib_dir, fname))
dll_count += 1
# libopus for OGG Opus encoding (client/core/ogg_opus.py)
if OPUS_DLL:
shutil.copy2(OPUS_DLL, os.path.join(lib_dir, "libopus-0.dll"))
dll_count += 1
print(f" -> lib/libopus-0.dll")
else:
print(" [WARN] libopus-0.dll not found — voice message encoding will fail")
# bassopus.dll for sound_lib BASS_PluginLoad
_bassopus_candidates = [
os.path.join(CLIENT_DIR, "lib", "bassopus.dll"),
os.path.join(CLIENT_DIR, "lib", "bass_opus.dll"),
]
_bassopus_copied = False
for _bsrc in _bassopus_candidates:
if os.path.isfile(_bsrc):
shutil.copy2(_bsrc, os.path.join(lib_dir, "bassopus.dll"))
dll_count += 1
print(f" -> lib/bassopus.dll (from {os.path.basename(_bsrc)})")
_bassopus_copied = True
break
if not _bassopus_copied:
print(" [WARN] bassopus.dll not found in client/lib — OGG Opus audio playback will fail")
# Copy ffmpeg binary to staging/lib/ to support audio conversion on remote API setups
if FFMPEG_EXE:
shutil.copy2(FFMPEG_EXE, os.path.join(lib_dir, "ffmpeg.exe"))
print(f" -> lib/ffmpeg.exe")
else:
print(" [WARN] ffmpeg binary not found — remote API setups will not be able to convert audio messages")
print(f" -> lib/ ({dll_count} DLLs total)")
sounds_src = os.path.join(CLIENT_DIR, "sounds")
shutil.copytree(sounds_src, os.path.join(STAGING_DIR, "sounds"))
sounds_count = len(os.listdir(sounds_src))
print(f" -> sounds/ ({sounds_count} files)")
langs_src = os.path.join(CLIENT_DIR, "languages")
shutil.copytree(langs_src, os.path.join(STAGING_DIR, "languages"))
langs_count = len(os.listdir(langs_src))
print(f" -> languages/ ({langs_count} files)")
data_dir = os.path.join(STAGING_DIR, "data")
os.makedirs(data_dir)
shutil.copy2(SETTINGS_DEFAULT, os.path.join(data_dir, "settings_default.json"))
print(f" -> data/settings_default.json")
# wpp_minimum_version.txt (plain text, just the version string) feeds
# MainWindow.ensure_wpp_version() — see its own docstring for why this
# is a dedicated file rather than a bundled .env: only build-windows.yml
# writes it, so it's absent (silently skipped) on any local/dev build.
wpp_min_version_file = os.path.join(CLIENT_DIR, "wpp_minimum_version.txt")
if os.path.isfile(wpp_min_version_file):
shutil.copy2(wpp_min_version_file, os.path.join(STAGING_DIR, "wpp_minimum_version.txt"))
print(f" -> wpp_minimum_version.txt")
changelog_files = glob.glob(os.path.join(CLIENT_DIR, "changelog_*.txt"))
for src in changelog_files:
shutil.copy2(src, os.path.join(STAGING_DIR, os.path.basename(src)))
print(f" -> changelog_*.txt ({len(changelog_files)} files)")
node_dst = os.path.join(STAGING_DIR, "node")
shutil.copytree(NODE_DIR, node_dst,
ignore=shutil.ignore_patterns("corepack"))
node_count = sum(1 for _, _, fs in os.walk(node_dst) for _ in fs)
print(f" -> node/ ({node_count} files)")
git_src = os.path.join(CLIENT_DIR, "git")
if os.path.isdir(git_src):
git_dst = os.path.join(STAGING_DIR, "git")
shutil.copytree(git_src, git_dst)
git_count = sum(1 for _, _, fs in os.walk(git_dst) for _ in fs)
print(f" -> git/ ({git_count} files)")
api_dst = os.path.join(STAGING_DIR, "api")
os.makedirs(api_dst)
api_count = 0
for abs_path, rel_path in walk_dir(API_DIR,
exclude_top_dirs=API_EXCLUDE_DIRS,
exclude_top_files=API_EXCLUDE_FILES,
exclude_sub_dirs=API_EXCLUDE_SUB_DIRS):
dst = os.path.join(api_dst, rel_path.replace("/", os.sep))
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.copy2(abs_path, dst)
api_count += 1
sha_src = os.path.join(API_DIR, ".commit_sha")
if os.path.isfile(sha_src):
shutil.copy2(sha_src, os.path.join(api_dst, ".commit_sha"))
print(" -> api/.commit_sha copied to staging")
custom_src_count = 0
for rel_path in API_CUSTOM_SRC_FILES:
src_path = os.path.join(API_DIR, rel_path.replace("/", os.sep))
if not os.path.isfile(src_path):
print(f" [WARN] custom api source file missing: {rel_path}")
continue
dst = os.path.join(api_dst, rel_path.replace("/", os.sep))
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.copy2(src_path, dst)
api_count += 1
custom_src_count += 1
print(f" -> api/ ({api_count} files, including {custom_src_count} custom src/ patch files)")
patches_dst = os.path.join(STAGING_DIR, "api_patches")
API_PATCHES_DIR = os.path.join(CLIENT_DIR, "api_patches")
if os.path.isdir(API_PATCHES_DIR):
shutil.copytree(API_PATCHES_DIR, patches_dst)
patches_count = sum(len(fs) for _, _, fs in os.walk(patches_dst))
else:
print(f" [WARN] client/api_patches/ not found — falling back to client/api/src/")
os.makedirs(patches_dst)
patches_count = 0
for rel_path in API_CUSTOM_SRC_FILES:
src_path = os.path.join(API_DIR, rel_path.replace("/", os.sep))
if not os.path.isfile(src_path):
continue
dst = os.path.join(patches_dst, rel_path.replace("/", os.sep))
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.copy2(src_path, dst)
patches_count += 1
print(f" -> api_patches/ ({patches_count} reference patch files)")
# -- Step 4-7: Installer (onedir only) -------------------------------------
def compile_uninstaller():
step("4/8 Compiling uninstaller")
run([
WINDRES_CMD, "--codepage", "65001",
os.path.join(INSTALLER_DIR, "uninstaller.rc"),
"-o", UNINSTALLER_RES,
"--include-dir", INSTALLER_DIR,
])
run([
GCC_CMD, "-finput-charset=UTF-8", "-fwide-exec-charset=UTF-16LE",
os.path.join(INSTALLER_DIR, "uninstaller.c"),
UNINSTALLER_RES, "-o", UNINSTALLER_EXE, "-mwindows",
"-I", INSTALLER_DIR,
"-lole32", "-lshell32", "-lcomctl32", "-lshlwapi", "-ladvapi32",
])
print(f" -> {UNINSTALLER_EXE}")
def create_payload_zip():
step("5/8 Creating payload ZIP (ZIP_STORED)")
count = 0
with zipfile.ZipFile(PAYLOAD_ZIP, "w", compression=zipfile.ZIP_STORED) as zf:
for abs_path, rel_path in walk_dir(STAGING_DIR):
zf.write(abs_path, rel_path)
count += 1
zf.write(UNINSTALLER_EXE, "uninstall.exe")
count += 1
size_mb = os.path.getsize(PAYLOAD_ZIP) / (1024 * 1024)
print(f" -> {PAYLOAD_ZIP} ({size_mb:.1f} MB, {count} entries)")
def compile_installer_stub():
step("6/8 Compiling installer stub")
run([
WINDRES_CMD, "--codepage", "65001",
os.path.join(INSTALLER_DIR, "installer.rc"),
"-o", INSTALLER_RES,
"--include-dir", INSTALLER_DIR,
])
run([
GCC_CMD, "-finput-charset=UTF-8", "-fwide-exec-charset=UTF-16LE",
os.path.join(INSTALLER_DIR, "installer.c"),
INSTALLER_RES, "-o", INSTALLER_STUB, "-mwindows",
"-I", INSTALLER_DIR,
"-lole32", "-lshell32", "-lcomctl32", "-lshlwapi", "-ladvapi32", "-luuid",
])
print(f" -> {INSTALLER_STUB}")
def append_zip_to_stub():
step("7/8 Appending payload to installer stub")
os.makedirs(DIST_DIR, exist_ok=True)
with open(INSTALLER_OUT, "wb") as out: