start.php
8.78 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
<?php
use Workerman\Worker;
use Workerman\Timer;
use Tos\TosClient;
use Tos\Exception\TosClientException;
use Tos\Exception\TosServerException;
use Tos\Model\PutObjectInput;
require_once __DIR__ . '/vendor/autoload.php';
// Define Heartbeat Interval
define('HEARTBEAT_TIME', 30);
// Create a WebSocket worker
$ws_worker = new Worker("websocket://0.0.0.0:8888");
// Emulate simple routing/state for now
// In production, use Redis for distributed state
$ws_worker->count = 1; // Single process for dev simplicity
// Redis Connection
$redis = null;
try {
$redis_host = getenv('REDIS_HOST') ?: '127.0.0.1';
$redis_port = getenv('REDIS_PORT') ?: 6379;
$redis_auth = getenv('REDIS_PASSWORD');
$redis_prefix = getenv('REDIS_PREFIX') ?: 'ai_';
$params = [
'scheme' => 'tcp',
'host' => $redis_host,
'port' => $redis_port,
];
if ($redis_auth) {
$params['password'] = $redis_auth;
}
// Predis Client
$redis = new Predis\Client($params, ['prefix' => $redis_prefix]);
$redis->connect();
echo "✅ Connected to Redis at $redis_host ($redis_prefix)\n";
} catch (Exception $e) {
echo "⚠️ Redis Connection Failed: " . $e->getMessage() . "\n";
}
// Store connections (Memory for now, can move to Redis later)
$clients = []; // ClientID -> Connection
$devices = []; // DeviceID -> Connection
$ws_worker->onWorkerStart = function ($worker) {
echo "Relay Server Started on 0.0.0.0:8888\n";
// Heartbeat check
Timer::add(10, function () use ($worker) {
$time_now = time();
foreach ($worker->connections as $connection) {
// Check if connection is alive possibly?
// Workerman handles basic disconnects, but we can enforce ping logic here if needed
}
});
};
$ws_worker->onConnect = function ($connection) {
echo "New connection: " . $connection->id . "\n";
$connection->authVerified = false;
};
$ws_worker->onMessage = function ($connection, $data) use (&$clients, &$devices) {
$msg = json_decode($data, true);
if (!$msg || !isset($msg['type'])) {
return;
}
// 1. Authenticate / Register
if ($msg['type'] === 'register') {
if ($msg['role'] === 'device') {
// Device 注册
$deviceId = $msg['id']; // TODO: Add secret validation
$devices[$deviceId] = $connection;
$connection->deviceId = $deviceId;
$connection->role = 'device';
$connection->authVerified = true;
$connection->send(json_encode(['type' => 'ack', 'status' => 'registered']));
echo "Device Registered: $deviceId\n";
} elseif ($msg['role'] === 'client') {
// Mini Program 注册
// TODO: Validate Token
$clientId = $msg['id'];
$clients[$clientId] = $connection;
$connection->clientId = $clientId;
$connection->role = 'client';
$connection->authVerified = true;
$connection->send(json_encode(['type' => 'ack', 'status' => 'connected']));
echo "Client Connected: $clientId\n";
}
return;
}
if (!$connection->authVerified) {
$connection->close();
return;
}
// 2. Proxy Logic
// Client -> Device
if ($msg['type'] === 'proxy' && $connection->role === 'client') {
$targetDeviceId = $msg['targetDeviceId'] ?? null;
if ($targetDeviceId && isset($devices[$targetDeviceId])) {
$payload = $msg['payload'];
// Wrap it so device knows who sent it
$forwardMsg = [
'type' => 'cmd:execute',
'fromClientId' => $connection->clientId,
'payload' => $payload
];
$devices[$targetDeviceId]->send(json_encode($forwardMsg));
echo "Forwarded msg from Client {$connection->clientId} to Device {$targetDeviceId}\n";
} else {
$connection->send(json_encode(['type' => 'error', 'msg' => 'Device offline or not found']));
}
}
// Device -> Client
if ($msg['type'] === 'proxy_response' && $connection->role === 'device') {
$targetClientId = $msg['targetClientId'] ?? null;
if ($targetClientId && isset($clients[$targetClientId])) {
$payload = $msg['payload'];
$forwardMsg = [
'type' => 'response',
'fromDeviceId' => $connection->deviceId,
'payload' => $payload
];
$clients[$targetClientId]->send(json_encode($forwardMsg));
echo "Forwarded response from Device {$connection->deviceId} to Client {$targetClientId}\n";
}
}
};
$ws_worker->onClose = function ($connection) use (&$clients, &$devices) {
if (isset($connection->role)) {
if ($connection->role === 'device' && isset($connection->deviceId)) {
unset($devices[$connection->deviceId]);
echo "Device disconnected: {$connection->deviceId}\n";
} elseif ($connection->role === 'client' && isset($connection->clientId)) {
unset($clients[$connection->clientId]);
echo "Client disconnected: {$connection->clientId}\n";
}
}
};
// ---------------------------------------------------------
// [New] HTTP Server for file uploads and static serving
// ---------------------------------------------------------
$http_worker = new Worker("http://0.0.0.0:8889");
$http_worker->count = 1; // Single process for uploads
$http_worker->onMessage = function ($connection, $request) {
// 1. Static File Serving (Simple implementation)
$path = $request->path();
if (strpos($path, '/uploads/') === 0) {
$file = __DIR__ . $path;
if (is_file($file)) {
$connection->send(new \Workerman\Protocols\Http\Response(
200,
['Content-Type' => mime_content_type($file)],
file_get_contents($file)
));
return;
}
}
// 2. Upload Handler
if ($path === '/upload') {
$files = $request->file();
if (empty($files['file'])) {
$connection->send(new \Workerman\Protocols\Http\Response(400, [], json_encode(['ok' => false, 'error' => 'No file'])));
return;
}
$file = $files['file'];
// Validate Size (50MB)
if ($file['size'] > 50 * 1024 * 1024) {
$connection->send(new \Workerman\Protocols\Http\Response(400, [], json_encode(['ok' => false, 'error' => 'File too large (Max 50MB)'])));
return;
}
// Validate Extension
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
// Supported: PDF, Excel, Image, Video
$allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'pdf', 'xls', 'xlsx'];
if (!in_array($ext, $allowed)) {
$connection->send(new \Workerman\Protocols\Http\Response(400, [], json_encode(['ok' => false, 'error' => 'File type not allowed'])));
return;
}
// TOS Configuration (Keys from hsobs.php)
$ak = 'AKLTZjkyMzliYjQ5N2IyNDFjNDliMTBiY2E2ZmU5ODhjNTM';
$sk = 'WldKbE5XUmpPRGxqWmpZM05EUTBObUpqTTJSa01qVTNNMkprWmpsbU9Uaw==';
$endpoint = 'tos-cn-shanghai.volces.com';
$region = 'cn-shanghai';
$bucket = 'ocxun';
try {
$client = new TosClient([
'region' => $region,
'endpoint' => $endpoint,
'ak' => $ak,
'sk' => $sk,
]);
// Generate Key
$uuid = bin2hex(random_bytes(8));
// TODO: 暂时使用 'guest',等待后续对接用户手机号功能
$userPhone = 'guest';
$objectKey = "clawdbot/{$userPhone}/{$uuid}.{$ext}";
// Read file content
$contentFn = fopen($file['tmp_name'], 'r');
// Upload using Object Input
$input = new PutObjectInput($bucket, $objectKey, $contentFn);
$input->setACL('public-read');
$client->putObject($input);
if (is_resource($contentFn)) {
fclose($contentFn);
}
// Generate URL
$url = "https://{$bucket}.{$endpoint}/{$objectKey}";
$connection->send(json_encode([
'ok' => true,
'url' => $url
]));
} catch (Exception $e) {
$connection->send(new \Workerman\Protocols\Http\Response(500, [], json_encode(['ok' => false, 'error' => 'Upload failed: ' . $e->getMessage()])));
}
return;
}
$connection->send("Moltbot Relay HTTP Server");
};
Worker::runAll();