File size: 4,459 Bytes
6fbf602
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# ==========================================================================
# core/nodeenv.py — آماده‌سازی Node برای موتور متن سمت سرور
# --------------------------------------------------------------------------
# متن‌ها و استیکرها روی سرور با همان کد پیش‌نمایش (Canvas 2D) کشیده
# می‌شوند. برای این کار به بسته‌ی @napi-rs/canvas نیاز است (موتور Skia، همان
# موتوری که کروم با آن متن می‌کشد). اگر npm نصب نباشد، خود بسته‌ها مستقیم از
# مخزن npm دریافت و باز می‌شوند.
# ==========================================================================
import os
import io
import json
import shutil
import tarfile
import platform
import subprocess
import threading

import requests

from . import config

CANVAS_VERSION = "1.0.10"
NODE_DIR = os.path.join(config.ROOT, "node")
NM = os.path.join(NODE_DIR, "node_modules")
REGISTRIES = ["https://registry.npmjs.org", "https://registry.npmmirror.com"]
STATE = {"ok": False, "error": None, "node": None}
READY = threading.Event()


def node_bin():
    for n in ("node", "nodejs"):
        p = shutil.which(n)
        if p:
            return p
    return None


def _platform_pkg():
    arch = platform.machine().lower()
    if arch in ("x86_64", "amd64"):
        return "canvas-linux-x64-gnu"
    if arch in ("aarch64", "arm64"):
        return "canvas-linux-arm64-gnu"
    return "canvas-linux-x64-gnu"


def _check():
    nb = node_bin()
    if not nb:
        return False, "Node نصب نیست"
    r = subprocess.run([nb, "-e", "const c=require('@napi-rs/canvas');const x=c.createCanvas(4,4).getContext('2d');x.fillRect(0,0,2,2);process.stdout.write('ok')"],
                       cwd=NODE_DIR, capture_output=True, text=True, timeout=60, env=dict(os.environ, NODE_PATH=NM))
    return (r.stdout.strip() == "ok"), (r.stderr or "")[-400:]


def _extract(tgz_bytes, dest):
    if os.path.exists(dest):
        shutil.rmtree(dest, ignore_errors=True)
    os.makedirs(dest, exist_ok=True)
    with tarfile.open(fileobj=io.BytesIO(tgz_bytes), mode="r:gz") as tf:
        for m in tf.getmembers():
            name = m.name.split("/", 1)[1] if "/" in m.name else m.name
            if not name or ".." in name.split("/"):
                continue
            m.name = name
            tf.extract(m, dest)


def _download(pkg, version):
    short = pkg.split("/")[-1]
    last = None
    for reg in REGISTRIES:
        url = f"{reg}/{pkg}/-/{short}-{version}.tgz"
        try:
            r = requests.get(url, timeout=180)
            if r.status_code == 200 and len(r.content) > 1000:
                return r.content
            last = f"HTTP {r.status_code}"
        except Exception as e:
            last = str(e)
    raise RuntimeError(f"دریافت {pkg} ناموفق بود: {last}")


def ensure():
    try:
        nb = node_bin()
        STATE["node"] = nb
        if not nb:
            raise RuntimeError("Node.js پیدا نشد (بسته‌ی nodejs را در packages.txt بگذارید)")
        ok, err = _check()
        if not ok:
            npm = shutil.which("npm")
            done = False
            if npm:
                r = subprocess.run([npm, "install", "--no-audit", "--no-fund", "--omit=dev"], cwd=NODE_DIR,
                                   capture_output=True, text=True, timeout=600)
                done = r.returncode == 0
            if not done:
                os.makedirs(os.path.join(NM, "@napi-rs"), exist_ok=True)
                plat = _platform_pkg()
                _extract(_download("@napi-rs/canvas", CANVAS_VERSION), os.path.join(NM, "@napi-rs", "canvas"))
                _extract(_download(f"@napi-rs/{plat}", CANVAS_VERSION), os.path.join(NM, "@napi-rs", plat))
            ok, err = _check()
        if not ok:
            raise RuntimeError("موتور متن سرور آماده نشد: " + err)
        STATE["ok"] = True
        ver = subprocess.run([nb, "--version"], capture_output=True, text=True).stdout.strip()
        print(f"🟢 [Node] موتور متن سرور آماده است (Node {ver}).", flush=True)
    except Exception as e:
        STATE["error"] = str(e)
        print(f"❌ [Node] {e}", flush=True)
    finally:
        READY.set()


def start_background():
    threading.Thread(target=ensure, daemon=True, name="nodeenv").start()