start.php
21.1 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
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
<?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';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/device.php';
// 加载配置文件
$config = require __DIR__ . '/config.php';
// Define Heartbeat Interval
define('HEARTBEAT_TIME', $config['heartbeat']['interval']);
// Database Connection
$pdo = null;
try {
$db_config = $config['database'];
$dsn = "mysql:host={$db_config['host']};port={$db_config['port']};dbname={$db_config['database']};charset=utf8mb4";
$pdo = new PDO($dsn, $db_config['username'], $db_config['password'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
echo "✅ Connected to MySQL at {$db_config['host']}:{$db_config['port']}\n";
} catch (Exception $e) {
echo "⚠️ MySQL Connection Failed: " . $e->getMessage() . "\n";
}
// Redis Connection
$redis = null;
try {
$redis_config = $config['redis'];
$params = [
'scheme' => 'tcp',
'host' => $redis_config['host'],
'port' => $redis_config['port'],
];
if (!empty($redis_config['password'])) {
$params['password'] = $redis_config['password'];
}
// Predis Client
$redis = new Predis\Client($params, ['prefix' => $redis_config['prefix']]);
$redis->connect();
echo "✅ Connected to Redis at {$redis_config['host']}:{$redis_config['port']} ({$redis_config['prefix']})\n";
} catch (Exception $e) {
echo "⚠️ Redis Connection Failed: " . $e->getMessage() . "\n";
}
// Initialize Services
$authService = $pdo ? new AuthService($pdo, $config, $redis) : null;
$deviceService = $pdo ? new DeviceService($pdo, $config) : null;
// Create a WebSocket worker
$ws_host = $config['server']['websocket_host'];
$ws_port = $config['server']['websocket_port'];
$ws_worker = new Worker("websocket://{$ws_host}:{$ws_port}");
// Store connections (Memory for now, can move to Redis later)
$clients = []; // ClientID -> Connection
$devices = []; // DeviceID -> Connection
$ws_worker->onWorkerStart = function ($worker) use ($config) {
$ws_host = $config['server']['websocket_host'];
$ws_port = $config['server']['websocket_port'];
echo "Relay Server Started on {$ws_host}:{$ws_port}\n";
// Heartbeat check
$check_interval = $config['heartbeat']['check_interval'];
Timer::add($check_interval, 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, $authService, $deviceService) {
$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'] ?? null;
$secret = $msg['secret'] ?? null;
if (!$deviceId) {
$connection->send(json_encode(['type' => 'error', 'msg' => 'Device ID required']));
return;
}
// 验证设备(如果有 deviceService)
if ($deviceService && $secret) {
if (!$deviceService->verifyDevice($deviceId, $secret)) {
$connection->send(json_encode(['type' => 'error', 'msg' => 'Invalid device credentials']));
$connection->close();
return;
}
// 更新设备状态为在线
$deviceService->updateDeviceStatus($deviceId, 'online');
}
$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 注册 - 验证 Token
$clientId = $msg['id'] ?? null;
$token = $msg['token'] ?? null;
if (!$clientId) {
$connection->send(json_encode(['type' => 'error', 'msg' => 'Client ID required']));
return;
}
// 验证 Token(如果有 authService 和 token)
$user = null;
if ($authService && $token) {
$user = $authService->verifyToken($token);
if (!$user) {
$connection->send(json_encode(['type' => 'error', 'msg' => 'Invalid or expired token']));
$connection->close();
return;
}
$connection->userId = $user['id'];
$connection->userPhone = $user['phone'];
}
$clients[$clientId] = $connection;
$connection->clientId = $clientId;
$connection->role = 'client';
$connection->authVerified = true;
$connection->send(json_encode([
'type' => 'ack',
'status' => 'connected',
'user' => $user
]));
echo "Client Connected: $clientId" . ($user ? " (User: {$user['phone']})" : "") . "\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 ($deviceService && isset($connection->userId)) {
if (!$deviceService->canAccessDevice($connection->userId, $targetDeviceId)) {
$connection->send(json_encode(['type' => 'error', 'msg' => 'No permission to access this device']));
return;
}
}
if ($targetDeviceId && isset($devices[$targetDeviceId])) {
$payload = $msg['payload'];
// Wrap it so device knows who sent it
$forwardMsg = [
'type' => 'cmd:execute',
'fromClientId' => $connection->clientId,
'fromUserId' => $connection->userId ?? null,
'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, $deviceService) {
if (isset($connection->role)) {
if ($connection->role === 'device' && isset($connection->deviceId)) {
unset($devices[$connection->deviceId]);
// 更新设备状态为离线
if ($deviceService) {
$deviceService->updateDeviceStatus($connection->deviceId, 'offline');
}
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_host = $config['server']['http_host'];
$http_port = $config['server']['http_port'];
$http_worker = new Worker("http://{$http_host}:{$http_port}");
$http_worker->count = $config['server']['worker_count'];
$http_worker->onMessage = function ($connection, $request) use ($config, $authService, $deviceService) {
$path = $request->path();
$method = $request->method();
// Helper: JSON Response
$jsonResponse = function ($data, $status = 200) use ($connection) {
$connection->send(new \Workerman\Protocols\Http\Response(
$status,
['Content-Type' => 'application/json', 'Access-Control-Allow-Origin' => '*'],
json_encode($data)
));
};
// CORS Preflight
if ($method === 'OPTIONS') {
$connection->send(new \Workerman\Protocols\Http\Response(200, [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization',
], ''));
return;
}
// ==================== Auth API ====================
// POST /api/auth/login - 微信登录
if ($path === '/api/auth/login' && $method === 'POST') {
if (!$authService) {
$jsonResponse(['ok' => false, 'error' => 'Auth service unavailable'], 500);
return;
}
$body = json_decode($request->rawBody(), true) ?: [];
$code = $body['code'] ?? null;
$phone = $body['phone'] ?? null;
$phoneCode = $body['phoneCode'] ?? null;
if (!$code) {
$jsonResponse(['ok' => false, 'error' => 'code is required'], 400);
return;
}
$result = $authService->wechatLogin($code, $phone, $phoneCode);
$jsonResponse($result, $result['ok'] ? 200 : 400);
return;
}
// POST /api/auth/verify - 验证 Token
if ($path === '/api/auth/verify' && $method === 'POST') {
if (!$authService) {
$jsonResponse(['ok' => false, 'error' => 'Auth service unavailable'], 500);
return;
}
$body = json_decode($request->rawBody(), true) ?: [];
$token = $body['token'] ?? null;
if (!$token) {
$jsonResponse(['ok' => false, 'error' => 'token is required'], 400);
return;
}
$user = $authService->verifyToken($token);
if ($user) {
$jsonResponse(['ok' => true, 'user' => $user]);
} else {
$jsonResponse(['ok' => false, 'error' => 'Invalid or expired token'], 401);
}
return;
}
// POST /api/auth/logout - 注销
if ($path === '/api/auth/logout' && $method === 'POST') {
if (!$authService) {
$jsonResponse(['ok' => false, 'error' => 'Auth service unavailable'], 500);
return;
}
$body = json_decode($request->rawBody(), true) ?: [];
$token = $body['token'] ?? null;
if ($token) {
$authService->logout($token);
}
$jsonResponse(['ok' => true]);
return;
}
// ==================== Device API ====================
// Helper: Get user from token
$getUser = function () use ($request, $authService) {
$authHeader = $request->header('Authorization');
if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
return null;
}
$token = substr($authHeader, 7);
return $authService ? $authService->verifyToken($token) : null;
};
// POST /api/device/bind - 绑定设备
if ($path === '/api/device/bind' && $method === 'POST') {
if (!$deviceService) {
$jsonResponse(['ok' => false, 'error' => 'Device service unavailable'], 500);
return;
}
$user = $getUser();
if (!$user) {
$jsonResponse(['ok' => false, 'error' => 'Unauthorized'], 401);
return;
}
$body = json_decode($request->rawBody(), true) ?: [];
$deviceId = $body['deviceId'] ?? null;
$deviceSecret = $body['deviceSecret'] ?? null;
if (!$deviceId) {
$jsonResponse(['ok' => false, 'error' => 'deviceId is required'], 400);
return;
}
$result = $deviceService->bindDevice($user['id'], $deviceId, $deviceSecret);
$jsonResponse($result, $result['ok'] ? 200 : 400);
return;
}
// POST /api/device/unbind - 解绑设备
if ($path === '/api/device/unbind' && $method === 'POST') {
if (!$deviceService) {
$jsonResponse(['ok' => false, 'error' => 'Device service unavailable'], 500);
return;
}
$user = $getUser();
if (!$user) {
$jsonResponse(['ok' => false, 'error' => 'Unauthorized'], 401);
return;
}
$body = json_decode($request->rawBody(), true) ?: [];
$deviceId = $body['deviceId'] ?? null;
if (!$deviceId) {
$jsonResponse(['ok' => false, 'error' => 'deviceId is required'], 400);
return;
}
$result = $deviceService->unbindDevice($user['id'], $deviceId);
$jsonResponse($result, $result['ok'] ? 200 : 400);
return;
}
// GET /api/device/list - 获取绑定的设备列表
if ($path === '/api/device/list' && $method === 'GET') {
if (!$deviceService) {
$jsonResponse(['ok' => false, 'error' => 'Device service unavailable'], 500);
return;
}
$user = $getUser();
if (!$user) {
$jsonResponse(['ok' => false, 'error' => 'Unauthorized'], 401);
return;
}
$devices = $deviceService->getUserDevices($user['id']);
$jsonResponse(['ok' => true, 'devices' => $devices]);
return;
}
// POST /api/device/primary - 设置主设备
if ($path === '/api/device/primary' && $method === 'POST') {
if (!$deviceService) {
$jsonResponse(['ok' => false, 'error' => 'Device service unavailable'], 500);
return;
}
$user = $getUser();
if (!$user) {
$jsonResponse(['ok' => false, 'error' => 'Unauthorized'], 401);
return;
}
$body = json_decode($request->rawBody(), true) ?: [];
$deviceId = $body['deviceId'] ?? null;
if (!$deviceId) {
$jsonResponse(['ok' => false, 'error' => 'deviceId is required'], 400);
return;
}
$result = $deviceService->setPrimaryDevice($user['id'], $deviceId);
$jsonResponse($result, $result['ok'] ? 200 : 400);
return;
}
// ==================== File API ====================
// 1. Static File Serving (Simple implementation)
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
$max_size = $config['upload']['max_size'];
if ($file['size'] > $max_size) {
$max_mb = round($max_size / 1024 / 1024);
$connection->send(new \Workerman\Protocols\Http\Response(400, [], json_encode(['ok' => false, 'error' => "File too large (Max {$max_mb}MB)"])));
return;
}
// Validate Extension
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed = $config['upload']['allowed_extensions'];
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
$tos_config = $config['tos'];
try {
$client = new TosClient([
'region' => $tos_config['region'],
'endpoint' => $tos_config['endpoint'],
'ak' => $tos_config['ak'],
'sk' => $tos_config['sk'],
]);
// Generate Key
$uuid = bin2hex(random_bytes(8));
$userPhone = $config['upload']['default_user'];
$objectKey = "clawdbot/{$userPhone}/{$uuid}.{$ext}";
$bucket = $tos_config['bucket'];
// 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}.{$tos_config['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;
}
// 3. Generate Pre-Signed URL for Direct Upload
if (strpos($path, '/tos/sign') === 0) {
$query = $request->get();
$filename = $query['filename'] ?? 'file_' . time();
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
// Validation
$allowed = $config['upload']['allowed_extensions'];
if (!in_array($ext, $allowed) && $ext !== '') {
// If no extension providing, we might just allow it or fail.
// Ideally client should provide full filename with extension.
}
// TOS Configuration
$tos_config = $config['tos'];
try {
$client = new TosClient([
'region' => $tos_config['region'],
'endpoint' => $tos_config['endpoint'],
'ak' => $tos_config['ak'],
'sk' => $tos_config['sk'],
]);
$uuid = bin2hex(random_bytes(8));
$userPhone = $config['upload']['default_user'];
// Ensure filename is safe
$safeName = preg_replace('/[^a-zA-Z0-9._-]/', '', $filename);
if (!$safeName)
$safeName = 'unnamed';
$objectKey = "clawdbot/{$userPhone}/direct_{$uuid}_{$safeName}";
$bucket = $tos_config['bucket'];
// Generate Pre-Signed PUT URL (Valid for 15 mins)
// Note: The SDK method name might vary slightly based on version,
// but `preSignedURL` is standard for TOS PHP SDK v2.
$input = new \Tos\Model\PreSignedURLInput(
'PUT',
$tos_config['bucket'],
$objectKey,
300 // 5 minutes validity
);
// Add content-type if known? client will send it.
// For simple PUT, we just sign the method and resource.
$output = $client->preSignedURL($input);
$signedUrl = $output->getSignedUrl();
// Public Access URL (Assuming bucket is public-read or we use signed Get URL)
// For this project, we used public-read ACL in previous code, so we assume public access.
$publicUrl = "https://{$tos_config['bucket']}.{$tos_config['endpoint']}/{$objectKey}";
$connection->send(json_encode([
'ok' => true,
'uploadUrl' => $signedUrl,
'publicUrl' => $publicUrl,
'key' => $objectKey
]));
} catch (Exception $e) {
$connection->send(new \Workerman\Protocols\Http\Response(500, [], json_encode(['ok' => false, 'error' => $e->getMessage()])));
}
return;
}
$connection->send("Moltbot Relay HTTP Server");
};
Worker::runAll();