-
Notifications
You must be signed in to change notification settings - Fork 103
/
SyncMusic.php
1697 lines (1525 loc) · 46.5 KB
/
SyncMusic.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
/**
* __________ ____ __ __ _
* | _____ | / ___| _ _ _ __ ___| \/ |_ _ ___(_) ___
* | | | | \___ \| | | | '_ \ / __| |\/| | | | / __| |/ __|
* | | | | ___) | |_| | | | | (__| | | | |_| \__ \ | (__
* / | / | |____/ \__, |_| |_|\___|_| |_|\__,_|___/_|\___|
* |___/ |___/ |___/
*
* 此项目使用 GPL v3 协议开放源代码,您可以在遵守本协议的前提下自由修改使用
*
* 作者:Akkariin Meiko | QQ:204034 | Telegram:Akkariins
*
**/
class SyncMusic {
private $server;
private $bindHost;
private $bindPort;
private $adminPass;
private $workersNum;
private $debug;
private $getIpMethod;
private $musicApi;
/**
*
* Construct 定义服务器基础信息
*
*/
public function __construct($bindHost, $bindPort, $adminPass, $workersNum, $debug, $getIpMethod, $musicApi)
{
$this->bindHost = $bindHost;
$this->bindPort = $bindPort;
$this->adminPass = $adminPass;
$this->workersNum = $workersNum;
$this->debug = $debug;
$this->getIpMethod = $getIpMethod;
$this->musicApi = $musicApi;
}
/**
*
* checkDataFolder 检查并创建数据目录
*
*/
public function checkDataFolder()
{
if(!file_exists(ROOT . "/tmp/")) mkdir(ROOT . "/tmp/");
if(!file_exists(ROOT . "/random.txt")) {
$data = @file_get_contents("https://cdn.zerodream.net/download/music/random.txt");
@file_put_contents(ROOT . "/random.txt", $data);
}
}
/**
*
* Init 初始化并配置服务器
*
*/
public function init()
{
$this->checkDataFolder();
$this->server = new Swoole\WebSocket\Server($this->bindHost, $this->bindPort);
$this->server->set([
'task_worker_num' => $this->workersNum,
'worker_num' => 16,
]);
// Table 表,用于储存服务器的信息
$table = new Swoole\Table(1024);
$table->column('music_time', Swoole\Table::TYPE_FLOAT, 8);
$table->column('music_play', Swoole\Table::TYPE_FLOAT, 8);
$table->column('music_long', Swoole\Table::TYPE_FLOAT, 8);
$table->column('downloaded', Swoole\Table::TYPE_FLOAT, 8);
$table->column('needswitch', Swoole\Table::TYPE_STRING, 32768);
$table->column('music_list', Swoole\Table::TYPE_STRING, 32768);
$table->column('music_show', Swoole\Table::TYPE_STRING, 32768);
$table->column('banned_ips', Swoole\Table::TYPE_STRING, 32768);
$table->create();
// Chats 表,用于储存用户的信息
$chats = new Swoole\Table(1024);
$chats->column('ip', Swoole\Table::TYPE_STRING, 256);
$chats->column('last', Swoole\Table::TYPE_FLOAT, 8);
$chats->create();
// 初始化信息
$this->server->table = $table;
$this->server->chats = $chats;
$this->server->started = false;
$this->server->randomed = false;
$this->server->adding = false;
/**
*
* Open Event 当客户端与服务器建立连接时触发此事件
*
*/
$this->server->on('open', function (Swoole\WebSocket\Server $server, $request) {
// 当第一个客户端连接到服务器的时候就触发 Task 去处理事件
if(!$server->started) {
$server->task(["action" => "Start"]);
$server->started = true;
}
// 获取客户端的 IP 地址
if($this->getIpMethod) {
$clientIp = $request->header['x-real-ip'] ?? "127.0.0.1";
} else {
$clientIp = $server->getClientInfo($request->fd)['remote_ip'] ?? "127.0.0.1";
}
// 将客户端 IP 储存到表中
$server->chats->set($request->fd, ["ip" => $clientIp]);
$this->consoleLog("客户端 {$request->fd} [{$clientIp}] 已连接到服务器", 1, true);
$server->push($request->fd, json_encode([
"type" => "msg",
"data" => "你已经成功连接到服务器!"
]));
$musicPlay = $this->getMusicPlay();
$musicList = $this->getMusicShow();
// 如果当前列表中有音乐可播放
if($musicList && !empty($musicList)) {
// 获取音乐的信息和歌词
$musicInfo = $musicList[0];
$lrcs = $this->getMusicLrcs($musicInfo['id']);
// 推送给客户端
$server->push($request->fd, json_encode([
"type" => "music",
"id" => $musicInfo['id'],
"name" => $musicInfo['name'],
"file" => $this->getMusicUrl($musicInfo['id']),
"album" => $musicInfo['album'],
"artists" => $musicInfo['artists'],
"image" => $musicInfo['image'],
"current" => $musicPlay + 1,
"lrcs" => $lrcs,
"user" => $musicInfo['user']
]));
// 播放列表更新
$playList = $this->getPlayList($musicList);
$server->push($request->fd, json_encode([
"type" => "list",
"data" => $playList
]));
}
});
/**
*
* Message Event 当客户端发送数据到服务器时触发此事件
*
*/
$this->server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
$clients = $server->connections;
$clientIp = $this->getClientIp($frame->fd);
$adminIp = $this->getAdminIp();
// 判断客户端是否已被封禁
if($this->isBanned($clientIp)) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "你没有权限发言"
]));
} else {
// 把客户端 IP 地址的 C 段和 D 段打码作为用户名显示
$username = $this->getMarkName($clientIp);
// 解析客户端发过来的消息
$message = $frame->data;
$json = json_decode($message, true);
if($json && isset($json['type'])) {
switch($json['type']) {
case "msg":
// 获取客户端最后发言的时间戳
$lastChat = $this->getLastChat($frame->fd);
//防止客户端刷屏
if($lastChat && time() - $lastChat <= MIN_CHATWAIT) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "发言太快,请稍后再发送"
]));
} else {
// 储存用户的最后发言时间
$this->setLastChat($frame->fd, time());
$this->consoleLog("客户端 {$frame->fd} 发送消息:{$json['data']}", 1, true);
if($json['data'] == "切歌") {
// 如果是切歌的命令,先判断是否是管理员
if($this->isAdmin($clientIp)) {
// 执行切歌操作,这里的 time + 1 是为了防止 bug
$this->setMusicTime(time() + 1);
$this->setMusicPlay(0);
$this->setMusicLong(time());
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "成功切歌"
]));
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "你没有权限这么做"
]));
}
} elseif($json['data'] == "投票切歌") {
// 由所有用户投票切掉当前歌曲
$needSwitch = $this->getNeedSwitch();
$totalUsers = $this->getTotalUsers();
// 判断用户是否已经投过票
if($this->isAlreadySwtich($clientIp)) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "你已经投票过了"
]));
} else {
// 如果是第一次投票
if($needSwitch == 1) {
// 广播给所有客户端
foreach($server->connections as $id) {
$server->push($id, json_encode([
"type" => "msg",
"data" => "有人希望切歌,支持请输入 “投票切歌”"
]));
}
}
// 判断投票的用户数是否超过在线用户数的 30%
if($needSwitch / $totalUsers >= 0.3) {
// 执行切歌操作
$this->setMusicTime(time() + 1);
$this->setMusicPlay(0);
$this->setMusicLong(time());
$this->setNeedSwitch("");
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "成功切歌"
]));
} else {
$this->addNeedSwitch($clientIp);
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "投票成功"
]));
// 广播给所有客户端
foreach($server->connections as $id) {
$server->push($id, json_encode([
"type" => "msg",
"data" => "当前投票人数:{$needSwitch}/{$totalUsers}"
]));
}
}
// 广播给所有客户端
$userNickName = $this->getUserNickname($clientIp);
foreach($clients as $id) {
$showUserName = $this->getClientIp($id) == $adminIp ? $clientIp : $username;
if($userNickName) {
$showUserName = "{$userNickName} ({$showUserName})";
}
$server->push($id, json_encode([
"type" => "chat",
"user" => htmlspecialchars($showUserName),
"time" => date("Y-m-d H:i:s"),
"data" => htmlspecialchars($json['data'])
]));
}
}
} elseif($json['data'] == "禁言列表") {
// 查看已禁言的用户列表,先判断是否是管理员
if($this->isAdmin($clientIp)) {
$server->push($frame->fd, json_encode([
"type" => "chat",
"user" => "System",
"time" => date("Y-m-d H:i:s"),
"data" => htmlspecialchars("禁言 IP 列表:" . $this->getBannedIp())
]));
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "你没有权限这么做"
]));
}
} elseif(mb_substr($json['data'], 0, 3) == "禁言 " && mb_strlen($json['data']) > 3) {
// 如果是禁言客户端的命令,先判断是否是管理员
if($this->isAdmin($clientIp)) {
$banName = trim(mb_substr($json['data'], 3, 99999));
if(!empty($banName)) {
// 判断是否已经被禁言
if($this->isBanned($banName)) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "这个 IP 已经被禁言了"
]));
} else {
$this->banIp($banName);
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "成功禁止此 IP 点歌和发言"
]));
}
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "禁言的 IP 不能为空!"
]));
}
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "你没有权限这么做"
]));
}
} elseif(mb_substr($json['data'], 0, 3) == "解禁 " && mb_strlen($json['data']) > 3) {
// 如果是解禁客户端的命令,先判断是否是管理员
if($this->isAdmin($clientIp)) {
$banName = trim(mb_substr($json['data'], 3, 99999));
if(!empty($banName)) {
// 如果用户没有被封禁
if(!$this->isBanned($banName)) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "这个 IP 没有被禁言"
]));
} else {
$this->unbanIp($banName);
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "成功解禁此 IP 的禁言"
]));
}
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "解禁的 IP 不能为空!"
]));
}
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "你没有权限这么做"
]));
}
} elseif(mb_substr($json['data'], 0, 3) == "换歌 " && mb_strlen($json['data']) > 3) {
// 如果是交换歌曲顺序的命令,先判断是否是管理员
if($this->isAdmin($clientIp)) {
$switchMusic = trim(mb_substr($json['data'], 3, 99999));
if(!empty($switchMusic)) {
$switchMusic = Intval($switchMusic);
// 不可以切换正在播放的歌曲
if($switchMusic == 0) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "正在播放的音乐不能切换"
]));
} else {
// 取得列表
$musicList = $this->getMusicList();
$sourceList = $this->getMusicShow();
// 储存并交换两首音乐
$waitSwitch = $musicList[$switchMusic - 1];
$needSwitch = $musicList[0];
$musicList[0] = $waitSwitch;
$sourceList[1] = $waitSwitch;
$musicList[$switchMusic - 1] = $needSwitch;
$sourceList[$switchMusic] = $needSwitch;
// 播放列表更新
$playList = $this->getPlayList($sourceList);
$this->setMusicList($musicList);
$this->setMusicShow($sourceList);
// 广播给所有客户端
foreach($server->connections as $id) {
$server->push($id, json_encode([
"type" => "list",
"data" => $playList
]));
}
// 发送通知
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "音乐切换成功"
]));
}
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "要切换的歌曲不能为空"
]));
}
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "你没有权限这么做"
]));
}
} elseif(mb_substr($json['data'], 0, 5) == "删除音乐 " && mb_strlen($json['data']) > 5) {
// 如果是删除某首音乐的命令
$deleteMusic = trim(mb_substr($json['data'], 5, 99999));
$deleteMusic = Intval($deleteMusic);
// 判断操作者是否是管理员
if($this->isAdmin($clientIp)) {
// 如果正在播放的音乐是第一首
if($deleteMusic <= 0) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "正在播放的音乐不能删除"
]));
} else {
// 获取播放列表
$musicList = $this->getMusicList();
$sourceList = $this->getMusicShow();
// 从列表中删除这首歌
unset($musicList[$deleteMusic - 1]);
unset($sourceList[$deleteMusic]);
// 重新整理列表
$musicList = array_values($musicList);
$sourceList = array_values($sourceList);
// 播放列表更新
$playList = $this->getPlayList($sourceList);
$this->setMusicList($musicList);
$this->setMusicShow($sourceList);
// 广播给所有客户端
foreach($server->connections as $id) {
$server->push($id, json_encode([
"type" => "list",
"data" => $playList
]));
}
// 发送通知
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "音乐删除成功"
]));
}
} else {
// 如果正在播放的音乐是第一首
if($deleteMusic <= 0) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "正在播放的音乐不能删除"
]));
} else {
// 获取播放列表
$musicList = $this->getMusicList();
$sourceList = $this->getMusicShow();
if(isset($musicList[$deleteMusic - 1]) && $musicList[$deleteMusic - 1]['user'] == $clientIp) {
// 从列表中删除这首歌
unset($musicList[$deleteMusic - 1]);
unset($sourceList[$deleteMusic]);
// 重新整理列表
$musicList = array_values($musicList);
$sourceList = array_values($sourceList);
// 播放列表更新
$playList = $this->getPlayList($sourceList);
$this->setMusicList($musicList);
$this->setMusicShow($sourceList);
// 广播给所有客户端
foreach($server->connections as $id) {
$server->push($id, json_encode([
"type" => "list",
"data" => $playList
]));
}
// 发送通知
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "音乐删除成功"
]));
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "你只能删除自己点的歌"
]));
}
}
}
} elseif(mb_substr($json['data'], 0, 5) == "房管登录 " && mb_strlen($json['data']) > 5) {
// 如果是房管登录操作
$userPass = trim(mb_substr($json['data'], 5, 99999));
// 判断密码是否正确
if($userPass == $this->adminPass) {
$this->setAdminIp($clientIp);
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "房管登录成功"
]));
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "房管密码错误"
]));
}
} elseif(mb_substr($json['data'], 0, 5) == "加黑名单 " && mb_strlen($json['data']) > 5) {
// 如果是房管登录操作
$blackList = trim(mb_substr($json['data'], 5, 99999));
// 判断密码是否正确
if($this->isAdmin($clientIp)) {
$this->addBlackList($blackList);
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "已增加新的黑名单"
]));
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "你没有权限这么做"
]));
}
} elseif(mb_substr($json['data'], 0, 5) == "设置昵称 " && mb_strlen($json['data']) > 5) {
// 如果是设置昵称
$userNick = trim(mb_substr($json['data'], 5, 99999));
// 正则判断用户名是否合法
if(preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z0-9_]+[^_]{3,20}$/u", $userNick)) {
if($this->isBlackList($userNick)) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "不允许的昵称"
]));
} elseif(mb_Strlen($userNick) <= 20) {
$this->setUserNickname($clientIp, $userNick);
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "昵称设置成功"
]));
$server->push($frame->fd, json_encode([
"type" => "setname",
"data" => $userNick
]));
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "昵称最多 20 个字符"
]));
}
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "只允许中英文数字下划线,最少 4 个字"
]));
}
} elseif(mb_substr($json['data'], 0, 3) == "点歌 " && mb_strlen($json['data']) > 3) {
// 如果是点歌命令
$musicName = trim(mb_substr($json['data'], 3, 99999));
if(!empty($musicName)) {
// 判断是否已经有人在点歌中
if(count($this->getUserMusic($clientIp)) > MAX_USERMUSIC) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "你已经点了很多歌了,请先听完再点"
]));
} elseif($this->isLockedSearch()) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "当前有任务正在执行,请稍后再试"
]));
} else {
if(mb_strlen($json['data']) > MAX_CHATLENGTH) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "消息过长,最多 " . MAX_CHATLENGTH . " 字符"
]));
} else {
// 提交任务给服务器
$server->task(["id" => $frame->fd, "action" => "Search", "data" => $musicName]);
// 广播给所有客户端
$userNickName = $this->getUserNickname($clientIp);
foreach($clients as $id) {
$showUserName = $this->getClientIp($id) == $adminIp ? $clientIp : $username;
if($userNickName) {
$showUserName = "{$userNickName} ({$showUserName})";
}
$server->push($id, json_encode([
"type" => "chat",
"user" => htmlspecialchars($showUserName),
"time" => date("Y-m-d H:i:s"),
"data" => htmlspecialchars($json['data'])
]));
}
}
}
} else {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "歌曲名不能为空!"
]));
}
} else {
// 默认消息内容,即普通聊天,广播给所有客户端
if(mb_strlen($json['data']) > MAX_CHATLENGTH) {
$server->push($frame->fd, json_encode([
"type" => "msg",
"data" => "消息过长,最多 " . MAX_CHATLENGTH . " 字符"
]));
} else {
if($this->isAdmin($clientIp)) {
$username = "管理员";
}
$userNickName = $this->getUserNickname($clientIp);
foreach($clients as $id) {
$showUserName = $this->isAdmin($this->getClientIp($id)) ? $clientIp : $username;
if($userNickName) {
$showUserName = "{$userNickName} ({$showUserName})";
}
$server->push($id, json_encode([
"type" => "chat",
"user" => htmlspecialchars($showUserName),
"time" => date("Y-m-d H:i:s"),
"data" => htmlspecialchars($json['data'])
]));
}
}
}
}
break;
case "heartbeat":
// 处理客户端发过来心跳包的操作,返回在线人数给客户端
$server->push($frame->fd, json_encode([
"type" => "online",
"data" => count($server->connections)
]));
break;
default:
// 如果客户端发过来未知的消息类型
$this->consoleLog("客户端 {$frame->fd} 发送了未知消息:{$message}", 2, true);
}
}
}
});
/**
*
* Close Event 当客户端断开与服务器的连接时触发此事件
*
*/
$this->server->on('close', function ($server, $fd) {
$this->consoleLog("客户端 {$fd} 已断开连接", 1, true);
});
/**
*
* Task Event 当服务器运行任务时触发此事件
*
*/
$this->server->on('Task', function (Swoole\Server $server, $task_id, $from_id, $data) {
// 如果是服务器初始化任务
if($data['action'] == "Start") {
// 设定死循环的目的是为了建立一个单独的线程用于执行数据更新
while(true) {
$musicList = $this->getMusicList();
$musicShow = $this->getMusicShow();
// 如果列表为空
if(empty($musicList) || empty($musicShow)) {
$musicList = empty($musicList) ? $this->getSavedMusicList() : $musicList;
$musicShow = empty($musicShow) ? $this->getSavedMusicShow() : $musicShow;
}
// 如果音乐列表不为空
if(!empty($musicList)) {
$musicTime = $this->getMusicTime();
// 如果音乐的结束时间小于当前时间,即播放完毕
if($musicTime < time() + 3) {
$server->randomed = false;
// 获得下一首歌的信息
$musicInfo = $musicList[0];
$sourceList = $musicList;
// 从播放列表里移除第一首,因为已经开始播放了
unset($musicList[0]);
$musicList = array_values($musicList);
$this->consoleLog("正在播放音乐:{$musicInfo['name']}", 1, true);
// 储存信息
$this->setMusicList($musicList);
$this->setMusicShow($sourceList);
$this->setMusicTime(time() + round($musicInfo['time']));
$this->setMusicLong(time());
$this->setMusicPlay(0);
$this->setNeedSwitch("");
// 获得播放列表
$playList = $this->getPlayList($sourceList);
$musicLrc = $this->getMusicLrcs($musicInfo['id']);
// 广播给所有客户端
if($server->connections) {
$currentURL = $this->getMusicUrl($musicInfo['id']);
foreach($server->connections as $id) {
$server->push($id, json_encode([
"type" => "music",
"id" => $musicInfo['id'],
"name" => $musicInfo['name'],
"file" => $currentURL,
"album" => $musicInfo['album'],
"artists" => $musicInfo['artists'],
"image" => $musicInfo['image'],
"lrcs" => $musicLrc,
"user" => $musicInfo['user']
]));
$server->push($id, json_encode([
"type" => "list",
"data" => $playList
]));
}
}
}
} else {
// 如果列表已经空了,先获取当前音乐是否还在播放
$musicTime = $this->getMusicTime();
// 判断音乐的结束时间是否小于当前时间,如果是则表示已经播放完了
if($musicTime && $musicTime < time() + 3) {
// 获取随机的音乐 ID
$rlist = $this->getRandomList();
if($rlist && !$server->randomed) {
// 判断是否还有人在线,如果没人就不播放了,有人才播放
if($server->connections && count($server->connections) > 0) {
// 开始播放随机音乐
$this->searchMusic($server, ["id" => false, "action" => "Search", "data" => $rlist]);
$server->randomed = true;
}
}
}
}
// 记录音乐已经播放的时间
$musicLong = $this->getMusicLong();
if($musicLong && is_numeric($musicLong)) {
$this->setMusicPlay(time() - $musicLong);
}
// 将播放列表储存到硬盘
$this->setSavedMusicList($musicList);
$this->setSavedMusicShow($musicShow);
// 每秒钟执行一次任务
sleep(1);
}
} elseif($data['action'] == "Search") {
// 如果是搜索音乐的任务
$this->searchMusic($server, $data);
}
});
/**
*
* Finish Event 当服务器任务完成时触发此事件
*
*/
$this->server->on('Finish', function (Swoole\Server $server, $task_id, $data) {
if($data['action'] == "msg" && $data['id']) {
$server->push($data['id'], json_encode([
"type" => "msg",
"data" => $data['data']
]));
}
});
}
/**
*
* Run 启动服务器
*
*/
public function run()
{
$this->server->start();
}
/**
*
* SearchMusic 搜索音乐
*
*/
private function searchMusic(Swoole\Server $server, $data)
{
$this->consoleLog("正在点歌:{$data['data']}", 1, true);
$musicList = $this->getMusicList();
$sourceList = $this->getMusicShow();
$this->lockSearch();
// 开始搜索音乐
$json = $this->fetchMusicApi($data['data']);
if($json && !empty($json)) {
if(isset($json[0]['id'])) {
$m = $json[0];
// 判断是否已经点过这首歌了
if($this->isInArray($musicList, $m['id'])) {
$this->unlockSearch();
$this->server->finish(["id" => $data['id'], "action" => "msg", "data" => "这首歌已经在列表里了"]);
} else {
$artists = $this->getArtists($m['artist']);
$musicUrl = $this->getMusicUrl($m['id']);
// 如果能够正确获取到音乐 URL
if($this->isBlackList($m['id']) || $this->isBlackList($m['name']) || $this->isBlackList($artists)) {
$this->unlockSearch();
$this->server->finish(["id" => $data['id'], "action" => "msg", "data" => "这首歌被设置不允许点播"]);
} elseif($musicUrl !== "") {
$musicId = Intval($m['id']);
// 开始下载音乐
$musicData = $this->fetchMusic($m, $musicUrl);
$musicImage = $this->getMusicImage($m['pic_id']);
// 如果音乐的文件大小不为 0
if(strlen($musicData) > 0) {
$musicTime = $this->getMusicLength($m['id']);
// 如果音乐的长度为 0(说明下载失败或其他原因)
if($musicTime == 0) {
$this->unlockSearch();
$this->server->finish(["id" => $data['id'], "action" => "msg", "data" => "歌曲下载失败,错误代码:ERROR_TIME0"]);
} elseif($musicTime > MAX_MUSICLENGTH) {
$this->unlockSearch();
$this->server->finish(["id" => $data['id'], "action" => "msg", "data" => "歌曲太长影响他人体验,不能超过 " . MAX_MUSICLENGTH . " 秒"]);
} else {
// 保存列表
$clientIp = $data['id'] ? $this->getClientIp($data['id']) : "127.0.0.1";
$musicList[] = [
"id" => $musicId,
"name" => $m['name'],
"file" => $musicUrl,
"time" => $musicTime,
"album" => $m['album'],
"artists" => $artists,
"image" => $musicImage,
"user" => $clientIp
];
$sourceList[] = [
"id" => $musicId,
"name" => $m['name'],
"file" => $musicUrl,
"time" => $musicTime,
"album" => $m['album'],
"artists" => $artists,
"image" => $musicImage,
"user" => $clientIp
];
$this->setMusicList($musicList);
$this->setMusicShow($sourceList);
// 播放列表更新
$playList = $this->getPlayList($sourceList);
// 广播给所有客户端
if($data['id'] && $this->server->connections) {
foreach($this->server->connections as $id) {
$this->server->push($id, json_encode([
"type" => "list",
"data" => $playList
]));
}
}
$this->unlockSearch();
$this->server->finish(["id" => $data['id'], "action" => "msg", "data" => "点歌成功"]);
}
} else {
$this->unlockSearch();
$this->server->finish(["id" => $data['id'], "action" => "msg", "data" => "歌曲下载失败,错误代码:ERROR_FILE_EMPTY"]);
}
} else {
$this->unlockSearch();
$this->server->finish(["id" => $data['id'], "action" => "msg", "data" => "歌曲下载失败,错误代码:ERROR_URL_EMPTY"]);
}
}
} else {
$this->unlockSearch();
$this->server->finish(["id" => $data['id'], "action" => "msg", "data" => "歌曲下载失败,错误代码:ERROR_ID_EMPTY"]);
}
} else {
$this->unlockSearch();
$this->server->finish(["id" => $data['id'], "action" => "msg", "data" => "未搜索到此歌曲"]);
}
}
/**
*
* BanIp 封禁指定 IP 地址
*
*/
private function banIp($ip)
{
$bannedIp = $this->getBannedIp() . "{$ip};";
$this->server->table->set(0, ["banned_ips" => $bannedIp]);
}
/**
*
* UnbanIp 解封指定 IP 地址
*
*/
private function unbanIp($ip)
{
$bannedIp = str_replace("{$ip};", "", $this->getBannedIp());
$this->setBannedIp($bannedIp);
}
/**
*
* LockSearch 禁止点歌
*
*/
private function lockSearch()
{
$this->server->table->set(0, ["downloaded" => 1]);
}
/**
*
* UnlockSearch 允许点歌
*
*/
private function unlockSearch()
{
$this->server->table->set(0, ["downloaded" => 0]);
}
/**
*
* AddNewSwitch 增加新的投票成员