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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cb66da
 
bb5f1a6
 
 
6cb66da
 
 
 
 
 
bb5f1a6
6cb66da
d44e3b5
 
 
6cb66da
 
 
 
bb5f1a6
 
6cb66da
 
 
 
d44e3b5
 
f1ca1c5
d44e3b5
6cb66da
d44e3b5
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
const http = require('http');
const { spawn } = require('child_process');

const PROXY_PORT_HUGGINGFACE = 4444; // Change this to a port different from 1688
const PROXY_PORT_OMNITOOL = 1689; // Change this to a port different from 1688
const CONTAINER_HOST = '127.0.0.1';
const CONTAINER_PORT_OMNITOOL = 1688;
const PROTOCOL = 'https';
let OMNITOOL_READY = false;
let OMNITOOL_PRE_READY = false;
let ALREADY_STARTING = false;

const VERSION = '0.0.5';
console.log(`************ Omnitool Proxy Server v${VERSION} ************`);
let omnitoolLogs = [];

async function startOmnitoolServer()
{
    if (ALREADY_STARTING) return;
    ALREADY_STARTING = true;

    console.log('Starting Omnitool Server...');
    return new Promise((resolve, reject) =>
    {
        const omnitoolStartProcess = spawn('./omnitool_start.sh');

        omnitoolStartProcess.stdout.on('data', (data) =>
        {
            omnitoolLogs.push(data.toString());
            console.log(`omnitool stdout: ${data}`);
            if (data.toString().includes(`Server has started and is ready to accept connections`))
            {
                console.log('Omnitool server started successfully');
                OMNITOOL_PRE_READY = true;
                setTimeout(() =>
                {
                    OMNITOOL_READY = true;
                    resolve();
                }, 1000); // Delay by 1 second
            }
        });

        omnitoolStartProcess.stderr.on('data', (data) =>
        {
            console.error(`omnitool stderr: ${data}`);
            omnitoolLogs.push(data.toString());
            
        });

        omnitoolStartProcess.on('close', (code) =>
        {
            const message = `Omnitool server process exited with code: ${code}`;
            console.log(message);
            omnitoolLogs.push(message);

            if (!OMNITOOL_READY)
            {
                ALREADY_STARTING = false;
                reject(`Omnitool server did not start within the timeout period.`);
            }
        });
    });
}

async function startRequestForwardingServer(proxy_port)
{
    const server = http.createServer((req, res) => handleRoutes(req, res, proxy_port));
    server.listen(proxy_port, '0.0.0.0');
    console.log(`Request forwarding server listening on port ${proxy_port}`);
}

async function handleRoutes(req, res, proxy_port)
{
    const localUrl = req.headers['host'];
    let htmlContent = '';
    const hostname = localUrl.split(':')[0];
    const hostport = localUrl.split(':')[1] || PROXY_PORT_HUGGINGFACE;
    const newUrl = `${PROTOCOL}://${hostname}:${PROXY_PORT_OMNITOOL}`;

    //console.log(`hostname = ${hostname}, hostport = ${hostport}, newUrl = ${newUrl}`);

    if (!OMNITOOL_READY)
    {
        if (req.method === 'GET')
        {
           

            switch (req.url)
            {
                case '/start-omnitool-server':
                    {

                        console.log(`Omnitool Server:ALREADY_STARTING =  ${ALREADY_STARTING}`);
                        if (ALREADY_STARTING) 
                        {
                            res.writeHead(200, { 'Content-Type': 'text/html' });
                            res.end("Omnitool server already starting");
                            return;
                        }
                        try
                        {
                            await startOmnitoolServer();
                            res.writeHead(200, { 'Content-Type': 'text/html' });
                            res.end("Omnitool server started successfully");
                        }
                        catch (error)
                        {
                            console.error(error);
                            ALREADY_STARTING = false;
                            res.writeHead(500, { 'Content-Type': 'text/html' });
                            res.end(`Error starting Omnitool server: ${error}`);
                        }

                        return;
                    }

                case '/omnitool-logs':
                    {
                        res.writeHead(200, { 'Content-Type': 'application/json' });
                        const reply = { logs: omnitoolLogs, ready: OMNITOOL_PRE_READY };
                        res.end(JSON.stringify(reply));
                        return;
                    }

                case '/':
                    {

                        if (hostport === PROXY_PORT_OMNITOOL.toString())
                        {
                            console.log(`Serving the page with START OMNITOOL SERVER button`);
                            htmlContent = `
                                    <html>
                                        <head>
                                            <title>Proxy Server</title>
                                            <style>
                                                #logContainer {
                                                    height: 400px; /* Fixed height */
                                                    overflow-y: scroll; /* Enable vertical scrolling */
                                                    background-color: black;
                                                    color: lime;
                                                    font-family: 'Courier New', Courier, monospace;
                                                    padding: 10px;
                                                    white-space: pre-wrap; /* Keep whitespaces */
                                                    border: 1px solid #ddd;
                                                }
                                            </style>
                                        </head>
                                        <body>
                                            <button id="startServerButton" onclick="startServer()">Start Omnitool Server</button>
                                            <div id="logContainer"></div>
                                            <script>

                                                function startServer() {
                                                    document.getElementById('startServerButton').disabled = true;
                                                    fetch('/start-omnitool-server')
                                                        .then(response => response.json())
                                                        .then(data => {
                                                            startLogPolling();
                                                        });
                                                }
                                                                            
                                                function startLogPolling() {
                                                    const interval = setInterval(() => {
                                                        fetch('/omnitool-logs')
                                                            .then(response => response.json())
                                                            .then(data => {
                                                                const logContainer = document.getElementById('logContainer');
                                                                logContainer.innerText = data.logs.join("");
                                                                if (data.ready) {
                                                                    data.logs.push("Omnitool is ready! REFRESHING PAGE...");
                                                                    logContainer.innerText = data.logs.join("");
                                                                    clearInterval(interval);
                                                                    setTimeout(function() {
                                                                        window.location.reload(1);
                                                                    }, 1500); // Refreshes after 1.5 seconds
                                                                }
                                                                scrollToBottom(logContainer);
                                                            });
                                                    }, 500); // Adjust to 500 for efficiency
                                                }
                            
                                                function scrollToBottom(element) {
                                                    element.scrollTop = element.scrollHeight;
                                                }
                            
                                                startLogPolling();
                                            </script>
                                        </body>
                                    </html>`;
                        }
                        else
                        {
                            console.log(`Serving the page with START OMNITOOL SERVER button and GOTO ${newUrl} button`);
                            htmlContent = `
                                    <html>
                                        <head>
                                            <title>Proxy Server</title>
                                            <style>
                                                #logContainer {
                                                    height: 400px; /* Fixed height */
                                                    overflow-y: scroll; /* Enable vertical scrolling */
                                                    background-color: black;
                                                    color: lime;
                                                    font-family: 'Courier New', Courier, monospace;
                                                    padding: 10px;
                                                    white-space: pre-wrap; /* Keep whitespaces */
                                                    border: 1px solid #ddd;
                                                }
                                                .highlight-button {
                                                    animation: pulseAnimation 1s infinite;
                                                    background-color: yellow;
                                                    color: black;
                                                    font-weight: bold;
                                                }                    
                                                @keyframes pulseAnimation {
                                                    0% { transform: scale(1); }
                                                    50% { transform: scale(1.1); }
                                                    100% { transform: scale(1); }
                                                }
                                            </style>
                                        </head>
                                        <body>
                                            <button id="startServerButton" onclick="startServer()">Start Omnitool Server</button>
                                            <button id="exitIframeButton" onclick="exitIframe()">GOTO ${newUrl}</button>
                                            <div id="logContainer"></div>
                                            <script>
                                                function exitIframe() {
                                                    window.open('${newUrl}', '_blank');
                                                }
                                                    
                                                function startServer() {
                                                    document.getElementById('startServerButton').disabled = true;
                                                    fetch('/start-omnitool-server')
                                                        .then(response => response.json())
                                                        .then(data => {
                                                            startLogPolling();
                                                        });
                                                }
                            
                                                function highlightExitButton() {
                                                    const exitButton = document.getElementById('exitIframeButton');
                                                    exitButton.classList.add('highlight-button');
                                                }
                                                
                                                function startLogPolling() {
                                                    const interval = setInterval(() => {
                                                        fetch('/omnitool-logs')
                                                            .then(response => response.json())
                                                            .then(data => {
                                                                const logContainer = document.getElementById('logContainer');
                                                                logContainer.innerText = data.logs.join("");
                                                                if (data.ready) {
                                                                    data.logs.push("Omnitool is ready! REFRESHING PAGE...");
                                                                    logContainer.innerText = data.logs.join("");
                                                                    clearInterval(interval);
                                                                    highlightExitButton();
                                                                }
                                                                scrollToBottom(logContainer);
                                                            });
                                                    }, 250); // Adjust to 500 for efficiency
                                                }
                            
                                                function scrollToBottom(element) {
                                                    element.scrollTop = element.scrollHeight;
                                                }
                            
                                                startLogPolling();
                                            </script>
                                        </body>
                                    </html>`;

                        }
                        res.writeHead(200, { 'Content-Type': 'text/html' });
                        res.end(htmlContent);
                        return;

                    }


                default:
                    console.log(`Doing nothing with this request: ${req.url}`);
                    res.writeHead(200, { 'Content-Type': 'text/html' });
                    res.end(`
                        <html>
                            <head>
                                <title>Page Refresh</title>
                                <script>
                                    setTimeout(function() {
                                        window.location.reload(1);
                                    }, 5000); // Refreshes after 5 seconds
                                </script>
                            </head>
                            <body>
                                <p>Doing nothing with this request: ${req.url}</p>
                                <p>The page will refresh automatically in 5 seconds.</p>
                            </body>
                        </html>`);
                    return;

            }
        }

        // we are dropping anything that isn't a GET request
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(`
            <html>
                <head>
                    <title>Page Refresh</title>
                    <script>
                        setTimeout(function() {
                            window.location.reload(1);
                        }, 1000); // Refreshes after 1 seconds
                    </script>
                </head>
                <body>
                    <p>Doing nothing with this request: ${req.url}</p>
                    <p>The page will refresh automatically in 1 seconds.</p>
                </body>
            </html>`);
        return;
    }
    if (OMNITOOL_READY)
    {

        if (proxy_port === PROXY_PORT_HUGGINGFACE)
        {
            htmlContent = `
            <html>
                <head>
                    <title>Proxy Server</title>
                    <style>
                        #logContainer {
                            height: 400px; /* Fixed height */
                            overflow-y: scroll; /* Enable vertical scrolling */
                            background-color: black;
                            color: lime;
                            font-family: 'Courier New', Courier, monospace;
                            padding: 10px;
                            white-space: pre-wrap; /* Keep whitespaces */
                            border: 1px solid #ddd;
                        }
                        .highlight-button {
                            animation: pulseAnimation 1s infinite;
                            background-color: yellow;
                            color: black;
                            font-weight: bold;
                        }                    
                        @keyframes pulseAnimation {
                            0% { transform: scale(1); }
                            50% { transform: scale(1.1); }
                            100% { transform: scale(1); }
                        }
                    </style>
                </head>
                <body>
                    <button id="exitIframeButton" onclick="exitIframe()">GOTO ${newUrl}</button>
                    <div id="logContainer"></div>
                    <script>
                        function exitIframe() {
                            window.open('${newUrl}', '_blank');
                        }
                            
                        function highlightExitButton() {
                            const exitButton = document.getElementById('exitIframeButton');
                            exitButton.classList.add('highlight-button');
                        }
                        
                        highlightExitButton();
                        element.scrollTop = element.scrollHeight;
    
                    </script>
                </body>
            </html>`;
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(htmlContent);
            return;
        }


        if (proxy_port === PROXY_PORT_OMNITOOL)
        {
            // Proxy logic...
            const options = { hostname: CONTAINER_HOST, port: CONTAINER_PORT_OMNITOOL, path: req.url, method: req.method, headers: req.headers, };
            const proxy = http.request(options, (proxyRes) =>
            {
                res.writeHead(proxyRes.statusCode, proxyRes.headers);
                proxyRes.pipe(res, { end: true });
            });
            req.pipe(proxy, { end: true });
            return;
        }
    }
    /*
    // Proxy logic...
    const options = { hostname: CONTAINER_HOST, port: CONTAINER_PORT_OMNITOOL, path: req.url, method: req.method, headers: req.headers, };
    const proxy = http.request(options, (proxyRes) =>
    {
        res.writeHead(proxyRes.statusCode, proxyRes.headers);
        proxyRes.pipe(res, { end: true });
    });
    req.pipe(proxy, { end: true });
    */
    return;
}

// Main function to start everything
async function startManagementServer()
{
    try
    {
        await startRequestForwardingServer(PROXY_PORT_HUGGINGFACE);
        await startRequestForwardingServer(PROXY_PORT_OMNITOOL);
    } catch (error)
    {
        console.error('Failed to start servers:', error);
    }
}

// main
// Start the servers
startManagementServer();