Chat.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <?php
  2. # 聊天服务
  3. namespace Community\Src;
  4. use Dever;
  5. use Collection\Lib\Core;
  6. Dever::apply('lib/gateway', 'im_gateway_client');
  7. use Im_gateway_client\Lib\Gateway;
  8. class Chat extends Core
  9. {
  10. public function __construct()
  11. {
  12. parent::__construct();
  13. # 测试用
  14. $uid = Dever::input('uid');
  15. if ($uid == 1) {
  16. $this->uid = 2;
  17. }
  18. }
  19. private function connect()
  20. {
  21. Gateway::$registerAddress = 'dl.shemic.com:1238';
  22. }
  23. # 初始化,绑定client_id
  24. public function init()
  25. {
  26. $this->connect();
  27. $client_id = Dever::input('client_id');
  28. if ($client_id) {
  29. Gateway::bindUid($client_id, $this->uid);
  30. }
  31. return 'ok';
  32. }
  33. # 加入分组
  34. public function joinGroup()
  35. {
  36. }
  37. # 发送消息
  38. public function send()
  39. {
  40. $uid = Dever::input('uid');
  41. $msg = Dever::input('msg');
  42. $pic = Dever::input('pic');
  43. if (!$uid || $uid == $this->uid) {
  44. Dever::alert('你要发给谁?');
  45. }
  46. if (!$msg && !$pic) {
  47. Dever::alert('没有任何消息');
  48. }
  49. Dever::load('community/lib/chat')->add($this->uid, $uid, $this->id, $msg, $pic, $this->day);
  50. $this->connect();
  51. # 谁发给谁,发的什么
  52. $this->push($this->uid, $uid, $msg, $pic);
  53. $data['msg'] = $this->msg($this->uid, $this->uid, $msg, $pic);
  54. return $data;
  55. }
  56. # 获取聊天记录
  57. public function getList()
  58. {
  59. $uid = Dever::input('uid');
  60. if (!$uid || $uid == $this->uid) {
  61. Dever::alert('你要发给谁?');
  62. }
  63. $data = Dever::load('community/lib/chat')->getInfo($this->uid, $uid, $this->id, $this->times);
  64. $info = $this->checkInfo();
  65. if ($info) {
  66. $button = $this->button($info);
  67. $data['bgcolor'] = $button['bgcolor'];
  68. }
  69. return $data;
  70. }
  71. # 发送消息给用户
  72. public function push($from_uid, $uid, $msg, $pic)
  73. {
  74. if (Gateway::isUidOnline($uid)) {
  75. $send = $this->msg($from_uid, $uid, $msg, $pic);
  76. $send = Dever::json_encode($send);
  77. Gateway::sendToUid($uid, $send);
  78. }
  79. return $this;
  80. }
  81. # 获取消息体
  82. public function msg($from_uid, $uid, $msg, $pic)
  83. {
  84. $self = false;
  85. if ($from_uid == $uid) {
  86. $self = true;
  87. }
  88. $send = array();
  89. $send['uid'] = $from_uid;
  90. $send['self'] = $self;
  91. $send['type'] = 'msg';
  92. $send['text'] = $msg;
  93. $send['pic'] = $pic;
  94. $send['date'] = Dever::load('collection/lib/times')->getDate($this->day, time(), $this->times);
  95. return $send;
  96. }
  97. }