-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathserver.php
1317 lines (1149 loc) · 50.8 KB
/
server.php
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Response;
use Workerman\Timer;
use think\facade\Db;
use think\facade\Cache;
use Channel\Server as ChannelServer;
use think\facade\Config;
use mailer\Mailer;
use app\api\model\LotteryModel;
use app\api\model\LotteryParticipantModel;
require_once __DIR__ . '/vendor/autoload.php';
// 加载 .env 配置
function loadEnv() {
$envFile = __DIR__ . '/.env';
if (!file_exists($envFile)) {
die("未找到 .env 文件\n");
}
$lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$config = [];
foreach ($lines as $line) {
// 跳过注释
if (strpos(trim($line), '#') === 0) {
continue;
}
// 解析配置项
if (strpos($line, '=') !== false) {
list($key, $value) = array_map('trim', explode('=', $line, 2));
// 移除引号
$value = trim($value, '"\'');
$config[$key] = $value;
}
}
return $config;
}
try {
$dotenv = loadEnv();
// 输出调试信息
echo "数据库信息:\n";
echo "DB_HOST: " . ($dotenv['DB_HOST'] ?? 'not set') . "\n";
echo "DB_NAME: " . ($dotenv['DB_NAME'] ?? 'not set') . "\n";
echo "DB_USER: " . ($dotenv['DB_USER'] ?? 'not set') . "\n";
$runInDocker = false;
if (isset($dotenv['IS_DOCKER'])) {
$runInDocker = $dotenv['IS_DOCKER'] === 'true';
} else if (file_exists('/.dockerenv')) {
$runInDocker = true;
} else if (getenv('container') === 'docker') {
$runInDocker = true;
} else if (file_exists('/proc/1/cgroup')) {
$cgroup = file_get_contents('/proc/1/cgroup');
if (strpos($cgroup, 'docker') !== false || strpos($cgroup, 'containerd') !== false) {
$runInDocker = true;
}
} else {
$runInDocker = false;
}
// 定义是否在 Docker 中运行
define('RUN_IN_DOCKER', $runInDocker);
define('APP_HOST', $dotenv['APP_HOST'] ?? 'http://127.0.0.1');
define('CRONTAB_KEY', $dotenv['CRONTAB_KEY'] ?? '');
// 定义数据库配置
define('DB_CONFIG', [
'type' => $dotenv['DB_TYPE'] ?? 'mysql',
'hostname' => $dotenv['DB_HOST'] ?? '127.0.0.1',
'database' => $dotenv['DB_NAME'] ?? '',
'username' => $dotenv['DB_USER'] ?? '',
'password' => $dotenv['DB_PASS'] ?? '',
'hostport' => $dotenv['DB_PORT'] ?? '3306',
'charset' => $dotenv['DB_CHARSET'] ?? 'utf8',
'prefix' => 'rc_',
]);
// 定义 media 配置
define('MEDIA_CONFIG', [
'apiKey' => $dotenv['EMBY_APIKEY'] ?? '',
'urlBase' => $dotenv['EMBY_URLBASE'] ?? '',
]);
if ($dotenv['TG_BOT_TOKEN'] == 'notgbot') {
// 未配置 Telegram 机器人
define('TG_CONFIG', [
'tgBotToken' => '',
'tgBotAdminId' => '',
'tgBotGroupId' => '',
]);
} else {
// 定义 TG 配置
define('TG_CONFIG', [
'tgBotToken' => $dotenv['TG_BOT_TOKEN'] ?? '',
'tgBotAdminId' => $dotenv['TG_BOT_ADMIN_ID'] ?? '',
'tgBotGroupId' => $dotenv['TG_BOT_GROUP_ID'] ?? '',
]);
}
} catch (\Exception $e) {
die("加载配置错误: " . $e->getMessage() . "\n");
}
// 设置为东八区
date_default_timezone_set('Asia/Shanghai');
// 初始化 Channel 服务器(必须在最前面)
$channel_server = new ChannelServer('127.0.0.1', 2206);
// 修改 Channel 服务器的启动回调
$channel_server->onWorkerStart = function($worker) {
// 确保 Channel 服务器完全启动
sleep(1);
echo "成功启动 Channel 服务器\n";
};
// WebSocket 服务器(内部服务,只监听本地)
$ws = new Worker("websocket://127.0.0.1:2346");
$ws->count = 4;
// 修改 Worker 启动时的初始化
$ws->onWorkerStart = function($worker) {
// 等待 Channel 服务器启动
sleep(2); // 给 Channel 服务器足够的启动时间
$retries = 0;
$maxRetries = 5;
$connected = false;
while ($retries < $maxRetries && !$connected) {
try {
// 初始化 Channel 客户端
\Channel\Client::connect('127.0.0.1', 2206);
echo "成功连接到 Channel 服务器\n";
$connected = true;
} catch (\Exception $e) {
$retries++;
echo "尝试 $retries: 连接到 Channel 服务器失败: " . $e->getMessage() . "\n";
if ($retries < $maxRetries) {
$sleepTime = pow(2, $retries);
$sleepTime = min($sleepTime, 30);
echo "将在 $sleepTime 秒后重试...\n";
sleep($sleepTime);
}
}
}
if (!$connected) {
echo "尝试连接 Channel 服务器失败\n";
Worker::stopAll();
return;
}
try {
// 初始化数据库连接
$config = DB_CONFIG;
$dbConfig = [
'default' => 'mysql',
'connections' => [
'mysql' => $config
]
];
Db::setConfig($dbConfig);
// 测试数据库连接
Db::query("SELECT 1");
echo "数据库连接成功\n";
// 初始化 WebSocketServer
global $webSocketServer;
$webSocketServer = \app\websocket\WebSocketServer::getInstance();
// 首次启动时执行全量检查
$workerId = $worker->id;
if($workerId === 0) { // 只在其中一个进程中执行
try {
checkAllExpiredUsers();
} catch (\Exception $e) {
$logFile = __DIR__ . '/runtime/log/timer_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 全量检查错误: " . $e->getMessage() . "\n";
file_put_contents($logFile, $message, FILE_APPEND);
}
try {
checkConfigDatabase();
} catch (\Exception $e) {
$logFile = __DIR__ . '/runtime/log/timer_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 检查数据库系统配置错误: " . $e->getMessage() . "\n";
file_put_contents($logFile, $message, FILE_APPEND);
}
}
// 检查是否启用了Telegram机器人
$token = TG_CONFIG['tgBotToken'];
if (!empty($token)) {
// 初始化机器人菜单
$telegram = new \Telegram\Bot\Api($token);
// 定义命令
$commands = [
// 私聊命令
[
'command' => 'start',
'description' => '开始使用机器人 - 私聊使用'
],
[
'command' => 'bind',
'description' => '绑定账号 - 私聊使用'
],
[
'command' => 'unbind',
'description' => '解绑账号 - 私聊使用'
],
[
'command' => 'sign',
'description' => '每日签到 - 私聊使用'
],
[
'command' => 'notification',
'description' => '通知设置 - 私聊使用'
],
[
'command' => 'push',
'description' => '转账 - 私聊/群组使用'
],
[
'command' => 'coin',
'description' => '查询余额 - 私聊/群组使用'
],
[
'command' => 'ping',
'description' => '测试机器人 - 群组使用'
],
[
'command' => 'lottery',
'description' => '查看抽奖 - 群组使用'
],
[
'command' => 'exitlottery',
'description' => '退出抽奖 - 群组使用'
],
[
'command' => 'bet',
'description' => '参与赌局 - 群组使用'
],
[
'command' => 'watchhistory',
'description' => '查看24小时内服务器播放记录 - 群组使用'
],
[
'command' => 'startlottery',
'description' => '开始抽奖 - 群组使用(管理员)'
],
[
'command' => 'startbet',
'description' => '开始赌局 - 群组使用(管理员)'
],
[
'command' => 'detail',
'description' => '查看用户详细信息 - 群组使用(管理员)'
],
];
// 设置命令
$telegram->setMyCommands([
'commands' => $commands,
'scope' => [
'type' => 'default'
]
]);
echo "成功初始化Telegram机器人命令菜单\n";
} else {
echo "未配置Telegram机器人Token,跳过初始化\n";
}
// 添加定时任务
Timer::add(10, function() use ($worker) {
$workerId = $worker->id;
if($workerId === 0) {
try {
checkExpiredUsers();
} catch (\Exception $e) {
$logFile = __DIR__ . '/runtime/log/timer_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 定时检查用户错误: " . $e->getMessage() . "\n";
file_put_contents($logFile, $message, FILE_APPEND);
}
} else if ($workerId === 1) {
try {
checkLotteryDraw();
} catch (\Exception $e) {
$logFile = __DIR__ . '/runtime/log/lottery_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 定时检查抽奖错误: " . $e->getMessage() . "\n";
file_put_contents($logFile, $message, FILE_APPEND);
}
} else if ($workerId === 2) { // 使用另一个worker处理赌博开奖
Timer::add(10, function() {
try {
checkBetResult();
} catch (\Exception $e) {
$logFile = __DIR__ . '/runtime/log/bet_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 定时检查赌博错误: " . $e->getMessage() . "\n";
file_put_contents($logFile, $message, FILE_APPEND);
}
});
}
});
Timer::add(600, function() use ($worker) {
$workerId = $worker->id;
if($workerId === 0) {
runCrontab();
} else if ($workerId === 1) {
} else if ($workerId === 2) {
}
});
} catch (\Exception $e) {
echo "数据库连接错误: " . $e->getMessage() . "\n";
// 记录错误日志
$logFile = __DIR__ . '/runtime/log/db_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 数据库连接错误: " . $e->getMessage() . "\n";
file_put_contents($logFile, $message, FILE_APPEND);
// 终止进程
Worker::stopAll();
}
};
$ws->onMessage = function($connection, $data) {
global $webSocketServer;
$webSocketServer->onMessage($connection, $data);
};
$ws->onClose = function($connection) {
global $webSocketServer;
$webSocketServer->onClose($connection);
};
// WebSocket 代理服务器(对外服务)
$wsProxy = new Worker('websocket://0.0.0.0:2347');
$wsProxy->count = 4;
// 修改 Worker 启动时的初始化
$wsProxy->onWorkerStart = function($worker) {
// 等待 Channel 服务器启动
sleep(2);
$retries = 0;
$maxRetries = 5;
$connected = false;
while ($retries < $maxRetries && !$connected) {
try {
// 初始化 Channel 客户端
\Channel\Client::connect('127.0.0.1', 2206);
echo "成功连接到 Channel 服务器\n";
$connected = true;
} catch (\Exception $e) {
$retries++;
echo "代理服务器尝试 $retries: 连接到 Channel 服务器失败: " . $e->getMessage() . "\n";
if ($retries < $maxRetries) {
echo "Retrying in 2 seconds...\n";
sleep(2);
}
}
}
if (!$connected) {
echo "代理服务器无法连接到 Channel 服务器\n";
Worker::stopAll();
return;
}
try {
// 初始化数据库连接
$config = DB_CONFIG;
$dbConfig = [
'default' => 'mysql',
'connections' => [
'mysql' => $config
]
];
Db::setConfig($dbConfig);
// 测试数据库连接
Db::query("SELECT 1");
echo "代理服务器已启动\n";
} catch (\Exception $e) {
echo "代理服务器数据库连接错误: " . $e->getMessage() . "\n";
// 记录错误日志
$logFile = __DIR__ . '/runtime/log/db_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 代理服务器数据库连接错误: " . $e->getMessage() . "\n";
file_put_contents($logFile, $message, FILE_APPEND);
// 终止进程
Worker::stopAll();
}
};
$wsProxy->onConnect = function($connection) {
// echo "Income新的连接\n";
};
$wsProxy->onWebSocketConnect = function($connection, $httpBuffer) {
// echo "WebSocket 连接被建立\n";
// 创建到内部服务器的连接
$innerConnection = new AsyncTcpConnection('ws://127.0.0.1:2346');
$connection->innerConnection = $innerConnection;
// 转发消息
$innerConnection->onMessage = function($innerConnection, $data) use ($connection) {
try {
// 记录转发的消息
$logFile = __DIR__ . '/runtime/log/proxy.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 转发到客户端: $data\n";
file_put_contents($logFile, $message, FILE_APPEND);
$connection->send($data);
} catch (\Exception $e) {
// 记录错误
$logFile = __DIR__ . '/runtime/log/proxy_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 转发到客户端错误: " . $e->getMessage() . "\n";
file_put_contents($logFile, $message, FILE_APPEND);
}
};
$connection->onMessage = function($connection, $data) use ($innerConnection) {
try {
// 记录接收到的消息
$logFile = __DIR__ . '/runtime/log/proxy.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 从客户端接收到消息: $data\n";
file_put_contents($logFile, $message, FILE_APPEND);
$innerConnection->send($data);
} catch (\Exception $e) {
// 记录错误
$logFile = __DIR__ . '/runtime/log/proxy_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 发送到内部服务器错误: " . $e->getMessage() . "\n";
file_put_contents($logFile, $message, FILE_APPEND);
}
};
// 处理连接关闭
$innerConnection->onClose = function($innerConnection) use ($connection) {
// echo "连接关闭\n";
$connection->close();
};
$connection->onClose = function($connection) {
// echo "客户端连接关闭\n";
if (isset($connection->innerConnection)) {
$connection->innerConnection->close();
}
};
// 处理错误
$innerConnection->onError = function($connection, $code, $msg) {
$logFile = __DIR__ . '/runtime/log/proxy_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] Inner 连接错误: $code - $msg\n";
file_put_contents($logFile, $message, FILE_APPEND);
};
// 连接到内部服务器
$innerConnection->connect();
};
$wsProxy->onMessage = function($connection, $data) {
// 记录代理服务器收到的消息
$logFile = __DIR__ . '/runtime/log/proxy.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 代理服务器收到消息: $data\n";
file_put_contents($logFile, $message, FILE_APPEND);
};
$wsProxy->onClose = function($connection) {
// echo "连接关闭\n";
};
$wsProxy->onError = function($connection, $code, $msg) {
$logFile = __DIR__ . '/runtime/log/proxy_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 代理服务器错误: $code - $msg\n";
file_put_contents($logFile, $message, FILE_APPEND);
};
// 修改 checkExpiredUsers 函数
function checkExpiredUsers() {
$now = time();
$startTime = date('Y-m-d H:i:s', $now - 60);
$endTime = date('Y-m-d H:i:s', $now + 86400);
// 记录开始检查的时间
$logFile = __DIR__ . '/runtime/log/check_accounts.log';
$time = date('Y-m-d\TH:i:s.v\Z', $now);
$message = "\n定时检测管理站用户: $time\n";
$message .= "查询周期时间: $startTime to $endTime\n";
file_put_contents($logFile, $message, FILE_APPEND);
// 只查询时间段内需要处理的用户
// $embyUserList = Db::name('emby_user')
// ->where('activateTo', 'not null')
// ->where(function ($query) use ($startTime, $endTime, $now) {
// $query->whereTime('activateTo', 'between', [$startTime, $endTime])
// ->whereOr(function ($q) use ($now) {
// $fiveMinBefore = date('Y-m-d H:i:s', $now + 86400 - 300);
// $fiveMinAfter = date('Y-m-d H:i:s', $now + 86400 + 300);
// $q->whereTime('activateTo', 'between', [$fiveMinBefore, $fiveMinAfter]);
// });
// })
// ->select();
$embyUserList = Db::name('emby_user')
->where('activateTo', 'not null')
->whereTime('activateTo', 'between', [$startTime, $endTime])
->select();
if (empty($embyUserList)) {
$message = "未找到需要检查的用户\n";
$message .= "----------------------------------------\n";
file_put_contents($logFile, $message, FILE_APPEND);
return;
}
$expiredCount = 0;
$processedCount = 0;
$autoRenewedCount = 0;
foreach ($embyUserList as $embyUser) {
try {
if ($embyUser['activateTo']) {
$expireTime = strtotime($embyUser['activateTo']);
$autoRenew = 0;
if (!empty($embyUser['userInfo'])) {
$userInfo = json_decode($embyUser['userInfo'], true);
if ($userInfo !== null && isset($userInfo['autoRenew']) && ($userInfo['autoRenew'] == 1 || $userInfo['autoRenew'] == "1")) {
$autoRenew = 1;
}
}
if ($autoRenew == 1) {
$user = Db::name('user')->where('id', $embyUser['userId'])->find();
if ($user && $user['rCoin'] >= 10) {
// 执行自动续期
processAutoRenewal($embyUser, $user);
$autoRenewedCount++;
sendNotification($user['id'], '您的Emby账号已自动续期');
continue;
}
} else {
if ($expireTime < $now) {
$expiredCount++;
// 禁用账号
disableEmbyAccount($embyUser['embyId']);
sendNotification($embyUser['userId'], '您的Emby账号已过期');
$processedCount++;
}
}
}
} catch (\Exception $e) {
// 记录错误日志
$logFile = __DIR__ . '/runtime/log/user_process_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 处理用户 {$embyUser['userId']} 错误: " . $e->getMessage() . "\n";
// 增加详细信息,显示错误
$message .= "用户 Info: " . json_encode($embyUser) . "\n";
$message .= "错误: " . $e->getMessage() . "\n";
$message .= "行数: " . $e->getTraceAsString() . "\n";
file_put_contents($logFile, $message, FILE_APPEND);
}
}
// 修改处理结果记录
$message = "处理小结:\n";
$message .= "- 找到 " . count($embyUserList) . " 个账号\n";
$message .= "- 找到 $expiredCount 个过期账号\n";
$message .= "- 处理 $processedCount 个过期账号\n";
$message .= "- 自动续期 $autoRenewedCount 个账号\n";
$message .= "----------------------------------------\n";
file_put_contents($logFile, $message, FILE_APPEND);
}
// 修改 checkAllExpiredUsers 函数
function checkAllExpiredUsers() {
$now = time();
$time = date('Y-m-d\TH:i:s.v\Z', $now);
$endTime = date('Y-m-d H:i:s', $now + 86400);
// 记录开始全量检查
$logFile = __DIR__ . '/runtime/log/check_accounts.log';
$message = "\n========================================\n";
$message .= "全量检测管理站用户: $time\n";
file_put_contents($logFile, $message, FILE_APPEND);
// 查询所有非永久的用户
$embyUserList = Db::name('emby_user')
->where('activateTo', 'not null')
->where('activateTo', '<', $endTime)
->select();
if (empty($embyUserList)) {
$message = "未找到需要检查的用户\n";
$message .= "========================================\n";
file_put_contents($logFile, $message, FILE_APPEND);
return;
}
$totalCount = count($embyUserList);
$expiredCount = 0;
$processedCount = 0;
$autoRenewedCount = 0;
foreach ($embyUserList as $embyUser) {
try {
if ($embyUser['activateTo']) {
$expireTime = strtotime($embyUser['activateTo']);
// 如果已过期
if ($expireTime < $now) {
// 禁用账号
disableEmbyAccount($embyUser['embyId']);
$processedCount++;
} else if ($expireTime < $now + 86400) {
// 自动续期
$autoRenew = 0;
if (!empty($embyUser['userInfo'])) {
$userInfo = json_decode($embyUser['userInfo'], true);
if ($userInfo !== null && isset($userInfo['autoRenew']) && ($userInfo['autoRenew'] == 1 || $userInfo['autoRenew'] == "1")) {
$autoRenew = 1;
}
}
if ($autoRenew == 1) {
$user = Db::name('user')->where('id', $embyUser['userId'])->find();
if ($user && $user['rCoin'] >= 10) {
// 执行自动续期
processAutoRenewal($embyUser, $user);
$autoRenewedCount++;
}
}
}
}
} catch (\Exception $e) {
// 记录错误日志
$logFile = __DIR__ . '/runtime/log/user_process_error.log';
$time = date('Y-m-d H:i:s');
$message = "[$time] 处理用户 {$embyUser['userId']} 错误: " . $e->getMessage() . "\n";
// 增加详细信息,显示错误
$message .= "用户 Info: " . json_encode($embyUser) . "\n";
$message .= "错误: " . $e->getMessage() . "\n";
$message .= "行数: " . $e->getTraceAsString() . "\n";
file_put_contents($logFile, $message, FILE_APPEND);
}
}
// 修改全量检查结果记录
$message = "全量检查报告:\n";
$message .= "- 找到 $totalCount 个账号\n";
$message .= "- 找到 $expiredCount 个过期账号\n";
$message .= "- 处理 $processedCount 个过期账号\n";
$message .= "- 自动续期 $autoRenewedCount 个账号\n";
$message .= "========================================\n";
file_put_contents($logFile, $message, FILE_APPEND);
}
// 处理自动续期
function processAutoRenewal($embyUser, $user) {
Db::startTrans();
try {
// 扣除用户余额
Db::name('user')->where('id', $user['id'])->update([
'rCoin' => $user['rCoin'] - 10
]);
// 更新到期时间
$newExpireTime = strtotime($embyUser['activateTo']) + 2592000; // 30天
Db::name('emby_user')->where('id', $embyUser['id'])->update([
'activateTo' => date('Y-m-d H:i:s', $newExpireTime)
]);
// 记录财务记录
Db::name('finance_record')->insert([
'userId' => $user['id'],
'action' => 3,
'count' => 10,
'recordInfo' => json_encode([
'message' => '使用余额自动续期Emby账号'
]),
]);
// 发送通知
sendNotification($user['id'], '您的Emby账号已自动续期至 ' . date('Y-m-d H:i:s', $newExpireTime));
Db::commit();
} catch (\Exception $e) {
echo "处理自动续期错误: " . $e->getMessage() . "\n";
echo "Rolling back...\n";
Db::rollback();
throw $e;
}
}
// 禁用Emby账号
function disableEmbyAccount($embyId) {
$apiKey = MEDIA_CONFIG['apiKey'];
$urlBase = MEDIA_CONFIG['urlBase'];
$url = $urlBase . 'Users/' . $embyId . '/Policy?api_key=' . $apiKey;
$data = ['IsDisabled' => true];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'accept: */*',
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (!($httpCode == 200 || $httpCode == 204)) {
echo "处理emby账号 ". $embyId . "过期失败,响应: $response\n";
throw new \Exception("Failed to disable Emby account: $response");
}
}
// 发送通知
function sendNotification($userId, $message) {
// 检查用户是否有tgId
$user = Db::name('telegram_user')->where('userId', $userId)->find();
if ($user && $user['telegramId'] && TG_CONFIG['tgBotToken']) {
// 发送TG消息
sendPrivateMessage($user['telegramId'], $message);
}
}
// 检查抽奖开奖
function checkLotteryDraw() {
$lotteryModel = new \app\api\model\LotteryModel();
$participantModel = new \app\api\model\LotteryParticipantModel();
// Log the start of the lottery check process
$logFile = __DIR__ . '/runtime/log/lottery_draw.log';
$now = date('Y-m-d H:i:s');
file_put_contents($logFile, "[$now] 开始检查抽奖\n", FILE_APPEND);
// 获取所有到期未开奖的抽奖
$lotteries = $lotteryModel
->where('status', 1)
->where('drawTime', '<=', date('Y-m-d H:i:s'))
->select();
if ($lotteries->isEmpty()) {
file_put_contents($logFile, "[$now] 没有需要开奖的抽奖\n", FILE_APPEND);
return;
}
foreach ($lotteries as $lottery) {
try {
// Assuming you have a custom DB transaction handler or use native PHP PDO transactions here
// For example:
// $db->beginTransaction();
$lotteryTime = date('Y-m-d H:i:s');
// 等待随机时间
$waitTime = mt_rand(1, 5);
sleep($waitTime);
file_put_contents($logFile, "[$lotteryTime] 锁定抽奖 #{$lottery['id']} 以进行开奖\n", FILE_APPEND);
$lottery = $lotteryModel->where('id', $lottery['id'])->find();
// 检查是否已经锁定
if ($lottery['status'] == 3) {
file_put_contents($logFile, "[$lotteryTime] 抽奖 #{$lottery['id']} 已经被锁定,跳过\n", FILE_APPEND);
continue;
}
// 锁定抽奖
$lotteryModel->where('id', $lottery['id'])->update(['status' => 3]);
file_put_contents($logFile, "[$lotteryTime] 抽奖 #{$lottery['id']} 已锁定\n", FILE_APPEND);
// 获取所有参与者
$participants = $participantModel
->where('lotteryId', $lottery['id'])
->where('status', 0)
->select()
->toArray();
if (empty($participants)) {
file_put_contents($logFile, "[$lotteryTime] 抽奖 #{$lottery['id']} 没有参与者,标记为已完成\n", FILE_APPEND);
$lotteryModel->where('id', $lottery['id'])->update(['status' => 2]);
file_put_contents($logFile, "[$lotteryTime] 更新抽奖 #{$lottery['id']} 状态为已完成,因为没有参与者\n", FILE_APPEND);
// $db->commit();
continue;
}
file_put_contents($logFile, "[$lotteryTime] 参与者数量:" . count($participants) . "\n", FILE_APPEND);
// 打乱参与者顺序
shuffle($participants);
$winnersList = []; // 用于存储所有获奖者信息
$prizes = is_array($lottery['prizes']) ? $lottery['prizes'] : json_decode($lottery['prizes'], true);
file_put_contents($logFile, "[$lotteryTime] 抽奖 #{$lottery['id']} 的奖项结构:\n" . json_encode($prizes, JSON_PRETTY_PRINT) . "\n", FILE_APPEND);
// 处理每个奖项
foreach ($prizes as $prizeIndex => $prize) {
$winnersList[$prize['name']] = [];
$prizeWinners = array_splice($participants, 0, min($prize['count'], count($participants)));
file_put_contents($logFile, "[$lotteryTime] 抽取 {$prize['name']} 奖品\n", FILE_APPEND);
foreach ($prizeWinners as $winner) {
try {
// Use telegramId and lotteryId for uniqueness
$uniqueIdentifier = ['telegramId' => $winner['telegramId'], 'lotteryId' => $lottery['id']];
$participant = $participantModel->where($uniqueIdentifier)->find();
if ($participant) {
$prizeContent = $prize['contents'][count($winnersList[$prize['name']])] ?? $prize['contents'][0];
$expAwarded = false;
if (preg_match('/「Exp(\d+)」/', $prizeContent, $matches)) {
$exp = intval($matches[1]);
$telegramUserModel = new \app\api\model\TelegramModel();
$tgUser = $telegramUserModel->where('telegramId', $winner['telegramId'])->find();
if (!$tgUser) {
// 如果找不到TG用户,直接标记为未中奖
file_put_contents($logFile, "[$lotteryTime] 找不到用户 {$winner['telegramId']} 的TG账号,标记为未中奖\n", FILE_APPEND);
$participantModel->where($uniqueIdentifier)->update(['status' => 2]);
continue;
}
$userid = $tgUser['userId'];
$userModel = new \app\api\model\UserModel();
$user = $userModel->where('id', $userid)->find();
if ($user && $user['authority'] >= 0) {
$authority = $user['authority'];
if ($authority >= 0) {
if ($authority > 0) {
$authority = $authority + $exp;
}
if ($authority > 100) {
$authority = 100;
}
$userModel->where('id', $userid)->update(['authority' => $authority]);
$expAwarded = true;
file_put_contents($logFile, "[$lotteryTime] 更新用户 {$winner['telegramId']} 的经验为 Exp{$authority}\n", FILE_APPEND);
}
}
// 如果无法兑换经验,需要重新抽取一位获奖者
if (!$expAwarded) {
file_put_contents($logFile, "[$lotteryTime] 用户 {$winner['telegramId']} 无法兑换经验,重新抽取获奖者\n", FILE_APPEND);
// 将当前参与者标记为未中奖
$participantModel->where($uniqueIdentifier)->update(['status' => 2]);
// 从剩余参与者中重新抽取一位
$newWinner = $participantModel
->where('lotteryId', $lottery['id'])
->where('status', 0)
->orderRaw('RAND()')
->find();
if ($newWinner) {
file_put_contents($logFile, "[$lotteryTime] 重新抽取到新获奖者 {$newWinner['telegramId']}\n", FILE_APPEND);
// 递归处理新获奖者
array_splice($participants, array_search($winner, $participants), 1);
array_push($participants, $newWinner->toArray());
continue;
} else {
file_put_contents($logFile, "[$lotteryTime] 无法找到新的合格获奖者,跳过此奖项\n", FILE_APPEND);
continue;
}
}
}
file_put_contents($logFile, "[$lotteryTime] 更新获奖者 {$winner['telegramId']} 的状态\n", FILE_APPEND);
// 更新中奖状态
$participantModel->where($uniqueIdentifier)->update([
'status' => 1,
'prize' => json_encode([
'name' => $prize['name'],
'content' => $prizeContent
])
]);
file_put_contents($logFile, "[$lotteryTime] 成功更新获奖者 {$winner['telegramId']} 的状态,奖品:{$prize['name']}\n", FILE_APPEND);
// 记录获奖者信息
$winnersList[$prize['name']][] = $winner['telegramId'];
file_put_contents($logFile, "[$lotteryTime] {$prize['name']} 的获奖者:{$winner['telegramId']}\n", FILE_APPEND);
// 发送中奖私信通知
file_put_contents($logFile, "[$lotteryTime] 发送私信给 {$winner['telegramId']}\n", FILE_APPEND);
$privateMessage = "🎉 恭喜您!\n\n";
$privateMessage .= "您在「{$lottery['title']}」抽奖活动中获得了:\n";
$privateMessage .= "🎁 {$prize['name']}\n\n";
$privateMessage .= "奖品内容:" . ($prize['contents'][count($winnersList[$prize['name']])-1] ?? $prize['contents'][0]) . "\n\n";
$privateMessage .= "请注意查收您的奖品!";
$token = TG_CONFIG['tgBotToken'];
if (!$token) {
throw new \Exception("Telegram bot token not found in environment variables");
}
$telegram = new \Telegram\Bot\Api($token);
try {
$telegram->sendMessage([
'chat_id' => $winner['telegramId'],
'text' => $privateMessage,
'parse_mode' => 'HTML',
]);
file_put_contents($logFile, "[$lotteryTime] 已发送私信给获奖者 {$winner['telegramId']}\n", FILE_APPEND);
} catch (\Exception $e) {
file_put_contents($logFile, "[$lotteryTime] 发送私信时出错,用户 {$winner['telegramId']}:" . $e->getMessage() . "\n", FILE_APPEND);
}
} else {
file_put_contents($logFile, "[$lotteryTime] 找不到参与者 {$winner['telegramId']} 的记录\n", FILE_APPEND);
}
} catch (\Exception $e) {
file_put_contents($logFile, "[$lotteryTime] 处理获奖者 {$winner['telegramId']} 时出错,奖品:{$prize['name']}:" . $e->getMessage() . "\n", FILE_APPEND);
}
}
}
// 更新未中奖的参与者状态
try {
file_put_contents($logFile, "[$lotteryTime] 更新未中奖参与者的状态\n", FILE_APPEND);
$participantModel
->where('lotteryId', $lottery['id'])
->where('status', 0)
->update(['status' => 2]);
file_put_contents($logFile, "[$lotteryTime] 已更新抽奖 #{$lottery['id']} 的未中奖参与者状态\n", FILE_APPEND);
} catch (\Exception $e) {
file_put_contents($logFile, "[$lotteryTime] 更新抽奖 #{$lottery['id']} 的未中奖参与者状态时出错:" . $e->getMessage() . "\n", FILE_APPEND);
}
// 在群组中公布中奖名单
$groupMessage = "🎉 抽奖结果公布 🎉\n\n";
$groupMessage .= "「{$lottery['title']}」开奖啦!\n\n";
foreach ($winnersList as $prizeName => $winners) {
if (!empty($winners)) {
$groupMessage .= "🎁 {$prizeName}:\n";
foreach ($winners as $telegramId) {
$groupMessage .= "- <a href=\"tg://user?id={$telegramId}\">{$telegramId}</a>\n";
}
$groupMessage .= "\n";
}
}
$groupMessage .= "恭喜以上中奖的小伙伴!🎊\n";
$groupMessage .= "奖品详情已私信通知,请注意查收~";
try {
file_put_contents($logFile, "[$lotteryTime] 准备发送群组消息\n", FILE_APPEND);
// 发送群组消息
$token = TG_CONFIG['tgBotToken'];
if (!$token) {
throw new \Exception("Telegram bot token not found in environment variables");
}
$telegram = new \Telegram\Bot\Api($token);
try {
$telegram->sendMessage([