-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdev-server.js
More file actions
180 lines (157 loc) · 5.65 KB
/
Copy pathdev-server.js
File metadata and controls
180 lines (157 loc) · 5.65 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
import http from 'http';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import https from 'https';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Load .env file
function loadEnv() {
const envPath = path.join(__dirname, '.env');
if (fs.existsSync(envPath)) {
const envContent = fs.readFileSync(envPath, 'utf-8');
envContent.split('\n').forEach(line => {
const [key, ...value] = line.split('=');
if (key && value) {
process.env[key.trim()] = value.join('=').trim();
}
});
console.log('✅ Loaded environment variables from .env');
}
}
loadEnv();
const PORT = process.env.PORT || 8000;
// Simple static file server mapping
const MIME_TYPES = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.woff': 'application/font-woff',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.wasm': 'application/wasm'
};
const server = http.createServer(async (req, res) => {
const parsedUrl = url.parse(req.url, true);
let pathname = parsedUrl.pathname;
// Handle API routes
if (pathname === '/api/chat' && req.method === 'POST') {
let body = '';
req.on('data', chunk => { body += chunk.toString(); });
req.on('end', async () => {
try {
const payload = JSON.parse(body);
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
res.statusCode = 500;
res.end(JSON.stringify({ reply: 'مفتاح API غير موجود' }));
return;
}
const { message, context = {} } = payload;
const systemPrompt = `
أنت FlowAI، مساعد ذكي متكامل لنظام BookFlow لإدارة المواعيد.
مهمتك هي مساعدة ${context.name || 'المستخدم'} في إدارة عمله.
سياق العمل الحالي:
- اسم النشاط: ${context.businessName || 'غير محدد'}
- نوع النشاط: ${context.type || 'عام'}
- مواعيد اليوم: ${context.todayAppointments || 0}
- بانتظار التأكيد: ${context.pendingAppointments || 0}
- إجمالي العملاء: ${context.totalClients || 0}
تعليمات الرد:
1. رد بلهجة مصرية احترافية، ودودة، وذكية.
2. اجعل الإجابات قصيرة ومباشرة.
3. استخدم الرموز تعبيرية (Emojis) بشكل مناسب.
`;
const requestBody = JSON.stringify({
contents: [
{ role: 'user', parts: [{ text: systemPrompt }] },
{ role: 'user', parts: [{ text: message }] }
],
generationConfig: {
temperature: 0.7,
topK: 40,
topP: 0.95,
maxOutputTokens: 1024,
}
});
const options = {
hostname: 'generativelanguage.googleapis.com',
path: '/v1beta/models/gemini-1.5-flash:generateContent?key=' + apiKey,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(requestBody)
}
};
const apiReq = https.request(options, (apiRes) => {
let data = '';
apiRes.on('data', chunk => data += chunk);
apiRes.on('end', () => {
try {
const json = JSON.parse(data);
if (json.error) {
res.statusCode = 500;
res.end(JSON.stringify({ reply: 'خطأ: ' + json.error.message }));
return;
}
const reply = json.candidates?.[0]?.content?.parts?.[0]?.text || 'عذراً، لم أستطع معالجة طلبك.';
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ reply }));
} catch (e) {
res.statusCode = 500;
res.end(JSON.stringify({ reply: 'خطأ في معالجة الرد' }));
}
});
});
apiReq.on('error', (e) => {
res.statusCode = 500;
res.end(JSON.stringify({ reply: 'خطأ في الاتصال: ' + e.message }));
});
apiReq.write(requestBody);
apiReq.end();
} catch (err) {
console.error('API Error:', err);
res.statusCode = 500;
res.end(JSON.stringify({ error: 'Internal Server Error' }));
}
});
return;
}
// Handle static files
if (pathname === '/') pathname = '/index.html';
if (pathname === '/app') pathname = '/app.html';
let filePath = path.join(__dirname, pathname);
if (!fs.existsSync(filePath) && !path.extname(filePath)) {
if (fs.existsSync(filePath + '.html')) {
filePath += '.html';
}
}
const extname = String(path.extname(filePath)).toLowerCase();
const contentType = MIME_TYPES[extname] || 'application/octet-stream';
fs.readFile(filePath, (error, content) => {
if (error) {
if (error.code == 'ENOENT') {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('<h1>404 Not Found</h1>', 'utf-8');
} else {
res.writeHead(500);
res.end('Sorry, check with the site admin for error: ' + error.code + ' ..\n');
}
} else {
res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'no-cache' });
res.end(content, 'utf-8');
}
});
});
server.listen(PORT, () => {
console.log(`🚀 Server running at http://localhost:${PORT}/`);
console.log(`Press Ctrl+C to stop`);
});