File size: 9,641 Bytes
8dab15d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import subprocess
import shlex
import gradio as gr
import shutil
import time
import threading
import re

# Configuration
REPO_DIR = "levanter"
DEFAULT_REPO = "https://github.com/priscy82/levanter.git"
PM2_APP_NAME = "whatsapp-bot"

def run_command(command, cwd=None, timeout=300):
    """Execute a command and capture output with enhanced environment"""
    try:
        env = os.environ.copy()
        # Set critical environment variables
        env['PATH'] = '/usr/local/bin:/usr/bin:/bin'
        env['PM2_HOME'] = '/tmp/.pm2'
        env['NPM_CONFIG_CACHE'] = '/tmp/npm_cache'
        env['YARN_CACHE_FOLDER'] = '/tmp/yarn_cache'
        env['NODE_OPTIONS'] = '--max-old-space-size=512'
        
        # Use shlex to properly handle command parsing
        process = subprocess.run(
            shlex.split(command),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            cwd=cwd,
            timeout=timeout,
            env=env
        )
        output = process.stdout
        if process.stderr:
            output += "\nERROR: " + process.stderr
        return output
    except subprocess.TimeoutExpired:
        return "Command timed out after {} seconds".format(timeout)
    except Exception as e:
        return f"Command failed: {str(e)}"

def clone_and_install(repo_url):
    """Clone repository and install dependencies with robust error handling"""
    # Remove existing repo
    if os.path.exists(REPO_DIR):
        try:
            shutil.rmtree(REPO_DIR)
        except Exception as e:
            return f"❌ Failed to remove existing directory: {str(e)}"
    
    # Clone repo with retries
    clone_attempts = 0
    clone_output = ""
    while clone_attempts < 3:
        clone_cmd = f"git clone {repo_url} {REPO_DIR}"
        clone_output = run_command(clone_cmd)
        if os.path.exists(REPO_DIR):
            break
        clone_attempts += 1
        time.sleep(2)
    
    if not os.path.exists(REPO_DIR):
        return f"❌ Clone failed after 3 attempts!\n{clone_output}"
    
    # Navigate to repo and install dependencies
    os.chdir(REPO_DIR)
    
    # Check for lock files to determine package manager
    package_manager = "yarn" if os.path.exists("yarn.lock") else "npm"
    
    # Install dependencies
    install_output = ""
    if package_manager == "yarn":
        install_output += run_command("yarn install --frozen-lockfile --network-timeout 300000")
    else:
        install_output += run_command("npm install --legacy-peer-deps --no-audit")
    
    # Handle common errors automatically
    if "ERR_PNPM" in install_output or "ERR!" in install_output:
        install_output += "\n⚠️ Detected installation issues. Trying fallback..."
        install_output += run_command("rm -rf node_modules")
        install_output += run_command("rm -f package-lock.json yarn.lock")
        install_output += run_command("npm cache clean --force")
        install_output += run_command("npm install --legacy-peer-deps --force")
    
    os.chdir("..")
    
    return f"βœ… Repository cloned!\n{clone_output}\n\nπŸ’Ώ Dependencies installed ({package_manager})!\n{install_output}"

def start_bot():
    """Start the bot using the appropriate package manager with PM2"""
    if not os.path.exists(REPO_DIR):
        return "❌ Repository not found! Clone first."
    
    os.chdir(REPO_DIR)
    
    # Determine package manager
    package_manager = "yarn" if os.path.exists("yarn.lock") else "npm"
    
    # Start the bot with PM2
    if package_manager == "yarn":
        start_cmd = f"pm2 start yarn --name {PM2_APP_NAME} -- start --watch --restart-delay=5000 --max-memory-restart 300M"
    else:
        start_cmd = f"pm2 start npm --name {PM2_APP_NAME} -- start --watch --restart-delay=5000 --max-memory-restart 300M"
    
    start_output = run_command(start_cmd, timeout=60)
    
    # Save PM2 process list
    run_command("pm2 save")
    
    os.chdir("..")
    
    return f"πŸ€– Bot started with PM2!\n{start_output}"

def stop_bot():
    """Stop the bot"""
    if not os.path.exists(REPO_DIR):
        return "❌ No active bot process"
    
    os.chdir(REPO_DIR)
    stop_output = run_command(f"pm2 stop {PM2_APP_NAME}")
    os.chdir("..")
    return f"πŸ›‘ Bot stopped!\n{stop_output}"

def get_logs():
    """Get bot logs"""
    if not os.path.exists(REPO_DIR):
        return "No logs available"
    
    os.chdir(REPO_DIR)
    logs = run_command(f"pm2 logs {PM2_APP_NAME} --nostream --lines 100")
    os.chdir("..")
    return logs or "No logs available"

def get_bot_status():
    """Get bot status with detailed information"""
    if not os.path.exists(REPO_DIR):
        return "Not deployed"
    
    os.chdir(REPO_DIR)
    status = run_command(f"pm2 status {PM2_APP_NAME}")
    os.chdir("..")
    
    # Enhance status output
    if status:
        if "online" in status:
            return f"🟒 Bot is running!\n{status}"
        elif "stopped" in status or "errored" in status:
            return f"πŸ”΄ Bot is stopped!\n{status}"
        elif "restarting" in status:
            return f"🟑 Bot is restarting!\n{status}"
    return "Status unknown"

def run_ssh_command(command):
    """Execute custom command in repo directory"""
    if not os.path.exists(REPO_DIR):
        return "❌ Repository not found! Clone first."
    
    os.chdir(REPO_DIR)
    output = run_command(command)
    os.chdir("..")
    return output

def deploy_sequence(repo_url):
    """Full deployment sequence with error recovery"""
    output = clone_and_install(repo_url)
    if "❌" in output:
        return output
    
    output += "\n\n" + start_bot()
    return output

def monitor_bot():
    """Background thread to monitor and restart bot"""
    while True:
        try:
            if os.path.exists(REPO_DIR):
                status = get_bot_status()
                if "πŸ”΄" in status or "errored" in status:
                    print("Bot crashed! Restarting...")
                    start_bot()
        except Exception as e:
            print(f"Monitor error: {str(e)}")
        time.sleep(30)

# Start monitoring thread
monitor_thread = threading.Thread(target=monitor_bot, daemon=True)
monitor_thread.start()

# Gradio Interface
with gr.Blocks(title="WhatsApp Bot Deployer", theme="soft") as demo:
    gr.Markdown("""
    # πŸ€– WhatsApp Bot Deployment Panel
    **Repository:** https://github.com/priscy82/levanter.git  
    **Node Version:** 23 | **PM2:** Installed | **Auto-Restart:** Enabled
    """)
    
    with gr.Tab("πŸš€ Deploy Bot"):
        repo_input = gr.Textbox(
            label="Git Repository URL",
            value=DEFAULT_REPO,
            interactive=False
        )
        deploy_btn = gr.Button("πŸš€ Clone & Deploy", variant="primary")
        deploy_output = gr.Textbox(label="Deployment Logs", interactive=False, lines=12)
    
    with gr.Tab("βš™οΈ Bot Controls"):
        with gr.Row():
            status_btn = gr.Button("πŸ”„ Refresh Status", variant="secondary")
            start_btn = gr.Button("▢️ Start Bot", variant="primary")
            stop_btn = gr.Button("⏹️ Stop Bot", variant="stop")
            restart_btn = gr.Button("πŸ” Restart Bot", variant="primary")
        
        status_output = gr.Textbox(label="Current Status", interactive=False, lines=4)
        controls_output = gr.Textbox(label="Action Output", interactive=False, lines=4)
        
        gr.Markdown("### πŸ“‹ Log Viewer")
        with gr.Row():
            log_lines = gr.Slider(50, 500, value=100, label="Log Lines")
            log_btn = gr.Button("πŸ“‹ Get Latest Logs")
        log_output = gr.Textbox(label="Bot Logs", interactive=False, lines=18)
    
    with gr.Tab("πŸ’» Terminal"):
        gr.Markdown("### ⚑ Run Custom Commands")
        cmd_input = gr.Textbox(
            label="Enter command", 
            placeholder="npm install package-name",
            lines=1
        )
        run_btn = gr.Button("▢️ Run", variant="primary")
        terminal_output = gr.Textbox(label="Output", interactive=False, lines=12)
        
        gr.Markdown("### πŸš€ Common Commands")
        examples = gr.Examples(
            examples=[
                ["npm install --legacy-peer-deps"],
                ["yarn install --frozen-lockfile"],
                ["git pull"],
                ["node --version"],
                ["npm run build"],
                ["pm2 status"],
                ["pm2 logs"]
            ],
            inputs=cmd_input,
            label="Click to insert command"
        )
    
    # Deployment tab actions
    deploy_btn.click(
        deploy_sequence, 
        inputs=repo_input, 
        outputs=deploy_output
    )
    
    # Status and control actions
    status_btn.click(
        get_bot_status, 
        outputs=status_output
    )
    start_btn.click(
        start_bot, 
        outputs=controls_output
    ).then(
        get_bot_status,
        outputs=status_output
    )
    stop_btn.click(
        stop_bot, 
        outputs=controls_output
    ).then(
        get_bot_status,
        outputs=status_output
    )
    restart_btn.click(
        lambda: run_ssh_command(f"pm2 restart {PM2_APP_NAME}"), 
        outputs=controls_output
    ).then(
        get_bot_status,
        outputs=status_output
    )
    
    # Log actions
    log_btn.click(
        get_logs, 
        outputs=log_output
    )
    
    # Terminal actions
    run_btn.click(
        run_ssh_command, 
        inputs=cmd_input, 
        outputs=terminal_output
    )

if __name__ == "__main__":
    demo.launch(server_port=7860, server_name="0.0.0.0")