Easemob.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use Redis;
  5. use think\Db;
  6. use app\common\library\Easemob as Easemoblib;
  7. /**
  8. * 环信接口
  9. */
  10. class Easemob extends Api
  11. {
  12. protected $noNeedLogin = ["callback",'index'];
  13. protected $noNeedRight = ['*'];
  14. protected $appKey;
  15. protected $redis;
  16. public function __construct() {
  17. parent::__construct();
  18. //初始化配置
  19. $easemob_config = config('easemob');
  20. $this->appKey = $easemob_config['appkey'];
  21. //redis
  22. $redis = new Redis();
  23. $redisconfig = config("redis");
  24. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  25. if ($redisconfig['redis_pwd']) {
  26. $redis->auth($redisconfig['redis_pwd']);
  27. }
  28. if($redisconfig['redis_selectdb'] > 0){
  29. $redis->select($redisconfig['redis_selectdb']);
  30. }
  31. $this->redis = $redis;
  32. }
  33. /**
  34. * 回调
  35. * https://docs-im-beta.easemob.com/document/server-side/callback_configurations.html
  36. *
  37. * 群组和聊天室操作:
  38. *
  39. * muc:presence 有新成员加入了聊天室
  40. *{"callId":"1101231101159883#demo_1215090885268604500","channel_channel":"1101231101159883#demo_230909515202562@admin.conference.easemob.com","eventType":"chat","channel_user":"1101231101159883#demo_9@easemob.com","chat_type":"muc","security":"845b22a4edcb4fde2185ff7f0374f051","is_downgrade":false,"content_type":"muc:presence","payload":{"muc_id":"1101231101159883#demo_230909515202562@conference.easemob.com","is_chatroom":true,"operation":"presence"},"group_id":"230909515202562","writed_channel":false,"host":"msync@ebs-ali-beijing-msync105","appkey":"1101231101159883#demo","from":"1101231101159883#demo_9@easemob.com","to":"230909515202562","msg_id":"1215090885268604500","timestamp":1700475192937}
  41. *
  42. * muc:kick 踢出聊天室
  43. * {"callId":"1101231101159883#demo_1215088856588617164","channel_channel":"1101231101159883#demo_9@easemob.com","eventType":"chat","channel_user":"1101231101159883#demo_231181574537218@admin.conference.easemob.com","chat_type":"muc","security":"83f9462c7769df1c979fd9dea88e7400","is_downgrade":false,"content_type":"muc:kick","payload":{"muc_id":"1101231101159883#demo_231181574537218@conference.easemob.com","reason":"chatroom kick offline user","is_chatroom":true,"operation":"kick","status":{"description":"","error_code":"ok"}},"group_id":"231181574537218","writed_channel":false,"host":"msync@ebs-ali-beijing-msync71","appkey":"1101231101159883#demo","from":"1101231101159883#demo_9@easemob.com","to":"9","msg_id":"1215088856588617164","timestamp":1700474720591}
  44. *
  45. * muc:absence 有成员离开了聊天室
  46. * {"callId":"1101231101159883#demo_1215088856710252128","channel_channel":"1101231101159883#demo_231181574537218@admin.conference.easemob.com","eventType":"chat","channel_user":"admin@easemob.com","chat_type":"muc","security":"ec7d29ea415ea5930c2236089dff3bc2","is_downgrade":false,"content_type":"muc:absence","payload":{"muc_id":"1101231101159883#demo_231181574537218@conference.easemob.com","is_chatroom":true,"operation":"absence"},"group_id":"231181574537218","writed_channel":false,"host":"msync@ebs-ali-beijing-msync108","appkey":"1101231101159883#demo","from":"1101231101159883#demo_9@easemob.com","to":"231181574537218","msg_id":"1215088856710252128","timestamp":1700474720619}
  47. *
  48. * muc:leave 成员主动退出聊天室
  49. * {"callId":"1101231101159883#demo_1216580964256318924","channel_channel":"1101231101159883#demo_231346001739777@conference.easemob.com","eventType":"chat","channel_user":"1101231101159883#demo_231346001739777@admin.conference.easemob.com","chat_type":"muc","security":"059f0313db99c98cde55b42d28538f9a","is_downgrade":false,"content_type":"muc:leave","payload":{"muc_id":"1101231101159883#demo_231346001739777@conference.easemob.com","is_chatroom":true,"operation":"leave","status":{"description":"","error_code":"ok"}},"group_id":"231346001739777","writed_channel":false,"host":"msync@ebs-ali-beijing-msync71","appkey":"1101231101159883#demo","from":"1101231101159883#demo_9@easemob.com","to":"231346001739777","msg_id":"1216580964256318924","timestamp":1700822128988}
  50. *
  51. * 用户登入
  52. * {"callId":"1101231101159883#demo_927e28f2-0e88-4a58-855b-c8d26949ea4f","reason":"login","security":"6b793f812b5ed74f62d3a95d9ea48c8f","os":"android","ip":"182.37.138.94:39768","host":"msync@ebs-ali-beijing-msync60","session_id":"1215076057950983584","appkey":"1101231101159883#demo","user":"1101231101159883#demo_2@easemob.com/android_f9f51032-3369-4f02-95bb-0cbf41b26837","version":"4.1.2","timestamp":1700471740680,"status":"online"}
  53. *
  54. * 用户登出
  55. * {"callId":"1101231101159883#demo_ee82832b-3455-472d-9024-3706b1e519a7","reason":"logout","security":"6266f2a31bc3b603d8458f3d39a49d47","os":"android","ip":"182.37.138.94:39768","host":"msync@ebs-ali-beijing-msync60","session_id":"1215076057950983584","appkey":"1101231101159883#demo","user":"1101231101159883#demo_2@easemob.com/android_f9f51032-3369-4f02-95bb-0cbf41b26837","version":"4.1.2","timestamp":1700472505682,"status":"offline"}
  56. *
  57. * 用户登出(被其他设备踢掉)
  58. * {"callId":"1101231101159883#demo_b2cdc4d9-a499-4e46-8aff-4503fb83a5c5","reason":"replaced","security":"1f4bb2ebb99c2f5da20048c7ca87f352","os":"android","ip":"182.37.138.94:41044","host":"msync@ebs-ali-beijing-msync62","appkey":"1101231101159883#demo","user":"1101231101159883#demo_9@easemob.com/android_fb260fdf-3935-4499-a09d-b270fdd88a0e","version":"4.1.2","timestamp":1700473675582,"status":"offline"}
  59. */
  60. public function index(){}
  61. //登入,登出,进入房间其实都不需要处理。登入不影响房间。只登出只要不影响房间,在退出房间时间会重复回调。登入房间有接口,这里没必要重复处理。就只有退出房间有用也简单
  62. public function callback() {
  63. $this->notify_log_start();
  64. $input = file_get_contents("php://input"); // 主题信息
  65. $input = json_decode($input,true);
  66. //验证加密
  67. //解析数据格式
  68. //用户登入
  69. if(isset($input['reason']) && $input['reason'] == 'login' && isset($input['status']) && $input['status'] == 'online'){
  70. $user = $input['user'];
  71. $uid = $this->get_easemob_uid($user);//用户主键id
  72. //开始处理
  73. $loginToday = Db::name('user')->where('id',$uid)->whereTime('onlinetime', 'today')->find();
  74. if ($loginToday){
  75. \app\common\model\User::update(["is_online"=>1,"onlinetime"=>time()],["id"=>$uid]);
  76. }else{
  77. \app\common\model\User::update(["is_online"=>1,"onlinetime"=>time()],["id"=>$uid]);
  78. }
  79. exit;
  80. }
  81. //用户登出
  82. //用户登出(被其他设备踢掉)
  83. if(isset($input['reason']) && ( $input['reason'] == 'logout' || $input['status'] == 'replaced') && isset($input['status']) && $input['status'] == 'offline'){
  84. $user = $input['user'];
  85. $uid = $this->get_easemob_uid($user);//用户主键id
  86. //开始处理
  87. // 更新用户在线状态为离线
  88. \app\common\model\User::update(["is_online"=>0],["id"=>$uid]);
  89. \app\common\model\User::update(["is_live"=>0],["id"=>$uid]);
  90. $livingUserPartyId = $this->redis->hGet("livingUser", $uid);
  91. if ($livingUserPartyId) {
  92. // 扣除在线用户在房间情况
  93. $this->redis->hDel("livingUser", $uid);
  94. $this->redis->HDel("online_" . $livingUserPartyId, $uid);
  95. $this->redis->zRem("party_user_".$livingUserPartyId,$uid); //新加的
  96. //退出房间获取房间自定义属性
  97. //清理这个人的麦序
  98. //重置房间在线人数
  99. $party_info = Db::name('party')->field('id,user_id,easemob_room_id')->where('id',$livingUserPartyId)->find();
  100. if(empty($party_info)){
  101. exit;
  102. }
  103. $this->clean_room($party_info,$uid);
  104. }
  105. exit;
  106. }
  107. //群组和聊天室操作:
  108. //muc:presence 有新成员加入了聊天室
  109. //muc:kick 踢出聊天室
  110. //muc:absence 有成员离开了聊天室
  111. //muc:leave 成员主动退出聊天室
  112. if(isset($input['chat_type']) && $input['chat_type'] == 'muc' && isset($input['eventType']) && $input['eventType'] == 'chat'){
  113. $room_id = '';
  114. $is_chatroom = false;
  115. $operation = false;
  116. $error_code = false;
  117. if(isset($input['payload'])){
  118. $payload = $input['payload'];
  119. if(isset($payload['muc_id'])){
  120. $room_id = $this->get_easemob_uid($payload['muc_id']);
  121. }
  122. if(isset($payload['is_chatroom']) && ($payload['is_chatroom'] == true || $payload['is_chatroom'] == 1) ){
  123. $is_chatroom = true;
  124. }
  125. if(isset($payload['operation']) && in_array($payload['operation'],['kick','absence','leave']) ){
  126. $operation = 'out';
  127. }
  128. if(isset($payload['operation']) && $payload['operation'] == 'presence' ){
  129. $operation = 'in';
  130. $operation = false;//进入房间走接口,不在这里处理
  131. }
  132. if(isset($payload['status']['error_code']) && $payload['status']['error_code'] == 'ok'){
  133. $error_code = true;
  134. }
  135. }
  136. //用户
  137. $uid = 0;
  138. if(isset($input['from'])){
  139. $uid = $this->get_easemob_uid($input['from']);
  140. }
  141. $party_info = Db::name('party')->field('id,user_id,easemob_room_id')->where('easemob_room_id',$room_id)->find();
  142. if(empty($party_info)){
  143. exit;
  144. }
  145. $partyid = $party_info['id'];
  146. //开始处理
  147. //进入房间
  148. if($uid && $partyid && $is_chatroom && $operation == 'in' && $error_code){
  149. $userId = $uid;
  150. $this->redis->hSet("online_" . $partyid, $userId, $userId);
  151. $this->redis->zAdd("party_user_".$partyid,$userId,$userId); //新加的
  152. // 记录在线用户在房间情况
  153. $this->redis->hSet("livingUser",$userId,$partyid);
  154. // 更新房间在线状态
  155. $partyInfo = $this->redis->get("party_" . $partyid);
  156. if ($partyInfo) {
  157. $partyInfo = json_decode($partyInfo, true);
  158. if ($partyInfo["is_online"] != 1) {
  159. $partyInfo["is_online"] = 1;
  160. $this->redis->set("party_" . $partyid, json_encode($partyInfo));
  161. \app\common\model\Party::update(["is_online" => 1], ["id" => $partyid]);
  162. }
  163. }
  164. // 更新房间在线状态
  165. $liveInfo = $this->redis->get("live_" . $partyid);
  166. if ($liveInfo) {
  167. $liveInfo = json_decode($liveInfo, true);
  168. if ($liveInfo["is_online"] != 1) {
  169. $liveInfo["is_online"] = 1;
  170. $this->redis->set("live_" . $partyid, json_encode($liveInfo));
  171. \app\common\model\Party::update(["is_online" => 1], ["id" => $partyid]);
  172. $rs_user = Db::name('user')->where('id',$userId)->update(['is_live'=>1]);
  173. }
  174. }
  175. //[环信] 更新聊天室自定义属性 在线用户人数
  176. $easemob = new Easemoblib();
  177. $matedata = [
  178. 'online_user_num' => count($this->redis->hGetAll("online_".$partyid)),
  179. ];
  180. $easemob->room_setRoomCustomAttributeForced($room_id,$uid,$matedata);
  181. }
  182. //出去房间
  183. if($uid && $partyid && $is_chatroom && $operation == 'out' && $error_code){
  184. $userId = $uid;
  185. $this->redis->HDel("online_" . $partyid, $userId);
  186. $this->redis->zRem("party_user_".$partyid,$userId); //新加的
  187. // 扣除在线用户在房间情况
  188. $this->redis->hDel("livingUser",$userId);
  189. // 更新房间在线状态
  190. $partyInfo = $this->redis->get("party_" . $partyid);
  191. if ($partyInfo) {
  192. $partyInfo = json_decode($partyInfo, true);
  193. $memCount = count($this->redis->hGetAll("online_" . $partyid));
  194. if ($memCount <= 0) {
  195. $partyInfo["is_online"] = 0;
  196. $this->redis->set("party_" . $partyid, json_encode($partyInfo));
  197. \app\common\model\Party::update(["is_online" => 0], ["id" => $partyid]);
  198. }
  199. }
  200. //
  201. $liveInfo = $this->redis->get("live_" . $partyid);
  202. if ($liveInfo) {
  203. $liveInfo = json_decode($liveInfo, true);
  204. $memCount = count($this->redis->hGetAll("online_" . $partyid));
  205. if ($memCount <= 0) {
  206. $liveInfo["is_online"] = 0;
  207. $this->redis->set("live_" . $partyid, json_encode($liveInfo));
  208. \app\common\model\Party::update(["is_online" => 0], ["id" => $partyid]);
  209. $rs_user = Db::name('user')->where('id',$userId)->update(['is_live'=>0]);
  210. }
  211. }
  212. //退出房间获取房间自定义属性
  213. //清理这个人的麦序
  214. //重置房间在线人数
  215. $this->clean_room($party_info,$uid);
  216. }
  217. exit;
  218. }
  219. }
  220. //清除某个麦位
  221. //重置房间在线人数
  222. private function clean_room($party_info,$uid){
  223. $easemob_room_id = $party_info['easemob_room_id'];
  224. //获取所有麦位,假设8个
  225. $easemob = new Easemoblib();
  226. $seatlist = $easemob->room_getRoomCustomAttribute($easemob_room_id,['seat0','seat1','seat2','seat3','seat4','seat5','seat6','seat7']);
  227. $newseat = [
  228. 'charm' => 0, //红心,魅力值
  229. 'isMaster' => false, // 是否是房主
  230. 'headUrl' => '', // 头像
  231. 'userNo' => '', // 座位上用户no
  232. 'rtcUid' => '', // 座位上用户id,与rtc的userId一致
  233. 'name' => '', // 座位上用户昵称
  234. 'seatIndex' => -1, // 座位编号
  235. 'chorusSongCode' => '', // 是否合唱
  236. 'isAudioMuted' => 1, // 是否静音
  237. 'isVideoMuted' => 0, // 是否开启视频
  238. 'checked' => false, // 用于送礼物选择用户
  239. 'isUsed' => true, // 用于送礼物选择用户
  240. 'gender' => 1, //性别
  241. ];
  242. $matedata = [];
  243. if(!empty($seatlist)){
  244. foreach($seatlist as $k => $seat){
  245. $seat = json_decode($seat,true);
  246. //找到当前用户所在的麦位
  247. if(isset($seat['rtcUid']) && !empty($seat['rtcUid']) && $seat['rtcUid'] == $uid){
  248. //$newseat['seatIndex'] = substr($k,-1);
  249. //初始化这个麦位
  250. $matedata = [
  251. $k => json_encode($newseat),
  252. ];
  253. //redis,删除占用麦位
  254. $key = "party_seat_".$party_info['id'];
  255. $seat_num = substr($k,-1,1);
  256. $this->redis->HDel($key, $seat_num);
  257. }
  258. }
  259. }
  260. //下麦
  261. $key = "party_seat_".$party_info['id'];
  262. $seats = $this->redis->hGetAll($key);
  263. foreach($seats as $seat_num => $seatuserid){
  264. if($seatuserid == $uid){
  265. $this->redis->HDel($key, $seat_num);
  266. }
  267. }
  268. //重置房间在线人数
  269. $matedata['online_user_num'] = count($this->redis->hGetAll("online_".$party_info['id']));
  270. //删除他点的歌曲
  271. $singlist = $easemob->room_getRoomCustomAttribute($easemob_room_id,['waitsing_list']);
  272. if(isset($singlist['waitsing_list']) && !empty($singlist['waitsing_list'])){
  273. $singlist = json_decode($singlist['waitsing_list'],true);
  274. //轮询,找到,删除
  275. $new_singlist = [];
  276. foreach($singlist as $key => $sing){
  277. if($sing['userNo'] == $uid){
  278. unset($singlist[$key]);
  279. }else{
  280. $new_singlist[] = $sing;
  281. }
  282. }
  283. $matedata['waitsing_list'] = json_encode($new_singlist);
  284. }
  285. //修改属性
  286. if(!empty($matedata)){
  287. $easemob->room_setRoomCustomAttributeForced($easemob_room_id,$party_info['user_id'],$matedata);
  288. }
  289. return true;
  290. }
  291. /**
  292. * 获取用户所加入的聊天室
  293. */
  294. private function getJoindGroupList($user_id) {
  295. $easemob = new Easemoblib();
  296. $list = $easemob->room_listAllRoomsUserJoined($user_id);
  297. return $list;
  298. }
  299. /**
  300. * 获取群组信息
  301. */
  302. private function getGroupInfo($easemob_room_id = '230909515202562') {
  303. $easemob = new Easemoblib();
  304. $info = $easemob->room_getRoom($easemob_room_id);
  305. return $info;
  306. }
  307. /**
  308. * 更新麦位前四
  309. */
  310. private function updatePosition($user_id,$party_id) {
  311. // 获取用户头像
  312. $userInfo = \app\common\model\User::field("avatar")->where(["id"=>$user_id])->find();
  313. $userAvatar = isset($userInfo["avatar"])?$userInfo["avatar"]:"";
  314. // 更新下麦时间
  315. $update = [];
  316. $update["offsite_time"] = time();
  317. $update["status"] = 2;
  318. \app\common\model\UserOnsiteTime::update($update,["user_id"=>$user_id,"status"=>1]);
  319. //
  320. $room_type = Db::name('party')->where('id',$party_id)->value('room_type');
  321. $redisData = $this->redis->get($room_type."_".$party_id);
  322. if(!$redisData){
  323. return true;
  324. }
  325. $partyInfo = json_decode($redisData,true);
  326. // 遍历已有头像
  327. $partyuser = isset($partyInfo["party_user"])?$partyInfo["party_user"]:"";
  328. if(is_array($partyuser)) foreach($partyuser as $k => $v) if($v === $userAvatar) unset($partyInfo["party_user"][$k]);
  329. $this->redis->set($room_type."_".$party_id,json_encode($partyInfo));
  330. }
  331. /**
  332. * 取消排麦
  333. */
  334. private function cancelLineUp($user_id,$party_id) {
  335. return false;
  336. //因为没有排麦了,设计图就没这个功能,所以后面没了
  337. }
  338. /**
  339. * 强制下线
  340. */
  341. private function downSite($user_id,$groupsites) {
  342. /*此处删减参考ggyuyin,api/tenim/downsite*/
  343. // 先更新下麦时间
  344. /*$update = [];
  345. $update["offsite_time"] = time();
  346. $update["status"] = 2;
  347. \app\common\model\UserOnsiteTime::update($update,["user_id"=>$user_id,"status"=>1]);*/
  348. // 循环房间
  349. /*此处删减参考ggyuyin,api/tenim/downsite*/
  350. }
  351. //输入: 1101231101159883#demo_9@easemob.com/android_f9f51032-3369-4f02-95bb-0cbf41b26837
  352. //输出: 9
  353. //输入: 1101231101159883#demo_231181574537218@admin.conference.easemob.com
  354. //输出: 231181574537218
  355. private function get_easemob_uid($user = ''){
  356. //去掉后半段
  357. $easemob = '@';
  358. $start = strpos($user,$easemob);
  359. $uid = substr($user,0,$start);
  360. //echo $uid;
  361. //echo '<br>';
  362. //去掉前缀
  363. $uid = substr($uid,strlen($this->appKey)+1);
  364. //echo $uid;
  365. return intval($uid);
  366. }
  367. //异步日志
  368. private function notify_log_start($paytype = 'easemob'){
  369. //记录支付回调数据
  370. ignore_user_abort(); // run script in background
  371. set_time_limit(30);
  372. // 日志文件 start
  373. $log_base_dir = '../paylog/'.$paytype.'/';
  374. if (!is_dir($log_base_dir))
  375. {
  376. mkdir($log_base_dir, 0770, true);
  377. @chmod($log_base_dir, 0770);
  378. }
  379. $notify_file = $log_base_dir.'notify.txt';
  380. if(!file_exists($notify_file)) {
  381. @touch($notify_file);
  382. @chmod($notify_file, 0770);
  383. }
  384. if(filesize($notify_file)>5242880)//大于5M自动切换
  385. {
  386. rename($notify_file, $log_base_dir.'notify_'.date('Y_m_d_H_i_s').'.txt');
  387. }
  388. if(!file_exists($notify_file)) {
  389. @touch($notify_file);
  390. @chmod($notify_file, 0770);
  391. }
  392. // 日志文件 end
  393. //开始写入
  394. $xml = file_get_contents("php://input");
  395. file_put_contents($notify_file, "\r\n\r\n".date('Y-m-d H:i:s')." [notify][入口接收php://input流原始数据] \n".$xml, FILE_APPEND);
  396. ini_set('display_errors','On');
  397. return $notify_file;
  398. }
  399. }