Tenim.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use think\Request;
  5. use getusersig\getusersig;
  6. use tencentim\tencentim;
  7. use Redis;
  8. use think\Db;
  9. /**
  10. * 腾讯im接口
  11. */
  12. class Tenim extends Api
  13. {
  14. protected $noNeedLogin = ["callback",'test','createIMGroup','updateRoomInfo','setImManage','sendMessageToUser','outMemberFromRoom',
  15. 'autoUserLine','getRoomUser','getGroupList','getGroupInfo'];
  16. protected $noNeedRight = ['*'];
  17. public function test() {
  18. $groupinfo = $this->getGroupInfo("112");
  19. print_r($groupinfo);
  20. exit;
  21. // 获取所有派对信息
  22. $partyList = \app\common\model\Party::field("id,user_id,party_name")->where(["status"=>1])->order("id","asc")->select();
  23. foreach($partyList as $k => $v) {
  24. if($k>=140 && $k<180) {
  25. $groupinfo = $this->getGroupInfo((string)$v["id"]);
  26. print_r($groupinfo);
  27. // $groupinfo = json_encode($groupinfo);
  28. // Db::table("hx_aaaa")->insert(["party_id"=>$v["id"],"user_id"=>$v["user_id"],"party_name"=>$v["party_name"],"json"=>$groupinfo]);
  29. }
  30. }
  31. exit;
  32. // $this->success("",$partyList);
  33. }
  34. /**
  35. * 创建im群组
  36. */
  37. public function createIMGroup() {
  38. $random = rand(10000000,99999999);
  39. $usersig = $this->usersig("administrator");
  40. // 获取配置信息
  41. $config = config("tencent_im");
  42. $url = "https://console.tim.qq.com/v4/group_open_http_svc/create_group";
  43. $url .= "?sdkappid=".$config["sdkappid"];
  44. $url .= "&identifier=administrator";
  45. $url .= "&usersig=".$usersig;
  46. $url .= "&random==".$random;
  47. $url .= "&contenttype=json";
  48. $tencentObj = new tencentim($url);
  49. // 获取群im信息
  50. $imInfo = Db::table("hx_aaaa")->where(["party_id"=>112])->select();
  51. if($imInfo) foreach($imInfo as $k => $v) {
  52. // if($k>=160 && $k<200) {
  53. $grouparr = json_decode($v["json"], true);
  54. $grouparr = $grouparr["GroupInfo"][0];
  55. $AppDefinedData = $grouparr["AppDefinedData"];
  56. $data = [];
  57. $data["Owner_Account"] = (string)$v["user_id"];
  58. $data["Type"] = "AVChatRoom";
  59. $data["GroupId"] = (string)$v["party_id"];
  60. $data["Name"] = $this->substr((string)$v["party_name"],0,7);
  61. $AppDefinedDataNew = [
  62. [
  63. "Key" => "roomInfo",
  64. "Value" => "sssssss"
  65. ],
  66. [
  67. "Key" => "seat0",
  68. "Value" => '{"mute":false,"status":0,"user":""}'
  69. ],
  70. [
  71. "Key" => "seat1",
  72. "Value" => $AppDefinedData[2]["Value"]
  73. ],
  74. [
  75. "Key" => "seat2",
  76. "Value" => $AppDefinedData[3]["Value"]
  77. ],
  78. [
  79. "Key" => "seat3",
  80. "Value" => $AppDefinedData[4]["Value"]
  81. ],
  82. [
  83. "Key" => "seat4",
  84. "Value" => $AppDefinedData[5]["Value"]
  85. ],
  86. [
  87. "Key" => "seat5",
  88. "Value" => $AppDefinedData[6]["Value"]
  89. ],
  90. [
  91. "Key" => "seat6",
  92. "Value" => $AppDefinedData[7]["Value"]
  93. ],
  94. [
  95. "Key" => "seat7",
  96. "Value" => $AppDefinedData[8]["Value"]
  97. ],
  98. [
  99. "Key" => "seat8",
  100. "Value" => $AppDefinedData[9]["Value"]
  101. ]
  102. ];
  103. $data["AppDefinedData"] = json_encode($AppDefinedDataNew);
  104. $groupInfo = $tencentObj->toSend($data);
  105. if($groupInfo["ActionStatus"] != 'OK') {
  106. echo $v["party_id"];
  107. break;
  108. }
  109. // }
  110. }
  111. print_r($groupInfo);exit;
  112. }
  113. public function substr(string $string, int $start, int $length = null)
  114. {
  115. return mb_substr($string, $start, $length, 'UTF-8');
  116. }
  117. /**
  118. * 更新房间信息
  119. */
  120. public function updateRoomInfo() {
  121. $random = rand(10000000, 99999999);
  122. $usersig = $this->usersig("administrator");
  123. // 获取配置信息
  124. $config = config("tencent_im");
  125. $url = "https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info";
  126. $url .= "?sdkappid=" . $config["sdkappid"];
  127. $url .= "&identifier=administrator";
  128. $url .= "&usersig=" . $usersig;
  129. $url .= "&random=" . $random;
  130. $url .= "&contenttype=json";
  131. $tencentObj = new tencentim($url);
  132. // 获取群im信息
  133. $imInfo = Db::table("hx_aaaa")->select();
  134. if($imInfo) foreach($imInfo as $k => $v) {
  135. if($k>=120 && $k<180) {
  136. $grouparr = json_decode($v["json"], true);
  137. $groupsites = $grouparr["GroupInfo"];
  138. // 循环房间
  139. if ($groupsites) foreach ($groupsites as $k => $v) {
  140. // 循环座位
  141. $data = [];
  142. foreach ($v["AppDefinedData"] as $m => $n) {
  143. // 解析字段信息
  144. $siteInfo = json_decode($n["Value"], true);
  145. $data["AppDefinedData"][] = [
  146. "Key" => $n["Key"],
  147. "Value" => $n["Value"],
  148. ];
  149. }
  150. if (!empty($data)) {
  151. $data["GroupId"] = $v["GroupId"];
  152. $res = $tencentObj->toSend($data);
  153. } else {
  154. echo "error!";
  155. break;
  156. }
  157. }
  158. }
  159. }
  160. print_r($res);
  161. exit;
  162. }
  163. /**
  164. * 获取群组信息
  165. */
  166. public function getGroupInfo($party_id='0') {
  167. $party_id = !empty($party_id) ? $party_id : $this->request->param('part_id',0);
  168. $random = rand(10000000,99999999);
  169. $usersig = $this->usersig("administrator");
  170. // 获取配置信息
  171. $config = config("tencent_im");
  172. $url = "https://console.tim.qq.com/v4/group_open_http_svc/get_group_info";
  173. $url .= "?sdkappid=".$config["sdkappid"];
  174. $url .= "&identifier=administrator";
  175. $url .= "&usersig=".$usersig;
  176. $url .= "&random==".$random;
  177. $url .= "&contenttype=json";
  178. $tencentObj = new tencentim($url);
  179. $data = [];
  180. $data["GroupIdList"] = [$party_id];
  181. $data["ResponseFilter"] = [
  182. "GroupBaseInfoFilter" => ["GroupId","Type","Name","FaceUrl","Owner_Account","MemberNum"],
  183. "MemberInfoFilter" => ["Account","Role"],
  184. "AppDefinedDataFilter_Group" => ["roomInfo"],
  185. ];
  186. $groupInfo = $tencentObj->toSend($data);
  187. $this->success('获取成功',$groupInfo['GroupInfo']);
  188. }
  189. /**
  190. * 获取所有群组
  191. */
  192. public function getGroupList() {
  193. $random = rand(10000000,99999999);
  194. $usersig = $this->usersig("administrator");
  195. // 获取配置信息
  196. $config = config("tencent_im");
  197. $url = "https://console.tim.qq.com/v4/group_open_http_svc/get_appid_group_list";
  198. $url .= "?sdkappid=".$config["sdkappid"];
  199. $url .= "&identifier=administrator";
  200. $url .= "&usersig=".$usersig;
  201. $url .= "&random==".$random;
  202. $url .= "&contenttype=json";
  203. $tencentObj = new tencentim($url);
  204. $data = [];
  205. $data["Limit"] = 100;//本次获取的群组 ID 数量的上限,不得超过 10000。如果不填,默认为最大值 10000
  206. $data["GroupType"] = 'AVChatRoom';//群组形态包括 Public(公开群),Private(即 Work,好友工作群),ChatRoom(即 Meeting,会议群),AVChatRoom(音视频聊天室),BChatRoom(在线成员广播大群)和社群(Community)
  207. $groupList = $tencentObj->toSend($data);
  208. $result = [];
  209. if (isset($groupList['ActionStatus']) && $groupList['ActionStatus'] == 'OK') {
  210. $result = isset($groupList['GroupIdList']) ? $groupList['GroupIdList'] : [];
  211. }
  212. $this->success('获取成功',$result);
  213. }
  214. /**
  215. * 获取用户所加入的群组
  216. */
  217. public function getJoindGroupList($user_id) {
  218. $random = rand(10000000,99999999);
  219. $usersig = $this->usersig("administrator");
  220. // 获取配置信息
  221. $config = config("tencent_im");
  222. $url = "https://console.tim.qq.com/v4/group_open_http_svc/get_joined_group_list";
  223. $url .= "?sdkappid=".$config["sdkappid"];
  224. $url .= "&identifier=administrator";
  225. $url .= "&usersig=".$usersig;
  226. $url .= "&random=".$random;
  227. $url .= "&contenttype=json";
  228. $tencentObj = new tencentim($url);
  229. $data = [];
  230. $data["Member_Account"] = $user_id;
  231. $data["WithHugeGroups"] = 1;
  232. $data["GroupType"] = 'AVChatRoom';
  233. $data["ResponseFilter"] = ["GroupBaseInfoFilter" => ['GroupId'] ];
  234. $groupInfo = $tencentObj->toSend($data);
  235. // \app\common\model\Test::update(["content"=>json_encode($groupInfo)],["id"=>1]);
  236. return $groupInfo;
  237. }
  238. //"https:\/\/console.tim.qq.com\/v4\/group_open_http_svc\/get_joined_group_list?sdkappid=1400458032&identifier=administrator&usersig=eJyrVgrxCdYrSy1SslIy0jNQ0gHzM1NS80oy0zLBwqamUNHilOzEgoLMFCUrQxMDAxNTCwNjI4hMakVBZlEqUNzU1NTIwMAAIlqSmQsSMzO0MDY0NDOwhJqSmQ40NNwowsvMzzXKw8wsLNIwRr9S28giPKjMPSkpKLPcLcfFPd3TO7swz9fXOdLTVqkWADrXLzo_&random=73931990&contenttype=json"
  239. // /**
  240. // * 删除群成员
  241. // */
  242. // public function delMemberFromGroup($user_id,$party_id) {
  243. // $random = rand(10000000,99999999);
  244. // $usersig = $this->usersig($user_id);
  245. // // 获取配置信息
  246. // $config = config("tencent_im");
  247. // $url = "https://console.tim.qq.com/v4/group_open_http_svc/delete_group_member";
  248. // $url .= "?sdkappid=".$config["sdkappid"];
  249. // $url .= "&identifier=administrator";
  250. // $url .= "&usersig=".$usersig;
  251. // $url .= "&random=".$random;
  252. // $url .= "&contenttype=json";
  253. // $tencentObj = new tencentim($url);
  254. // $data = [];
  255. // $data["GroupId"] = $party_id;
  256. // $data["Silence"] = 1;
  257. // $data["MemberToDel_Account"] = [$user_id];
  258. // $res = $tencentObj->toSend($data);
  259. // \app\common\model\Test::update(["content"=>json_encode($res)],["id"=>1]);
  260. // return $res;
  261. // }
  262. /**
  263. * 设置管理员
  264. */
  265. public function setImManage($manage_user_id,$party_id) {
  266. // $manage_user_id = "2";
  267. // $party_id = "6";
  268. $random = rand(10000000,99999999);
  269. $usersig = $this->usersig("administrator");
  270. // 获取配置信息
  271. $config = config("tencent_im");
  272. $url = "https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info";
  273. $url .= "?sdkappid=".$config["sdkappid"];
  274. $url .= "&identifier=administrator";
  275. $url .= "&usersig=".$usersig;
  276. $url .= "&random=".$random;
  277. $url .= "&contenttype=json";
  278. $tencentObj = new tencentim($url);
  279. // 获取群组信息
  280. $groupInfo = $this->getGroupInfo($party_id);
  281. if($groupInfo["GroupInfo"][0]["ErrorCode"] > 0) return false;
  282. $roomInfoData = $groupInfo["GroupInfo"][0]["AppDefinedData"];
  283. $roomInfo = [];
  284. if($roomInfoData) foreach($roomInfoData as $k => $v) {
  285. if($v["Key"] == "roomInfo") $roomInfo = $v["Value"];
  286. }
  287. $roomInfo = json_decode($roomInfo,true);
  288. // 更新的信息
  289. if(isset($roomInfo["managers"])) {
  290. if(!$roomInfo["managers"]) $roomInfo["managers"] = [];
  291. array_push($roomInfo["managers"],$manage_user_id);
  292. $roomInfo["managers"] = array_unique($roomInfo["managers"]);
  293. }
  294. $data = [];
  295. $data["GroupId"] = $party_id;
  296. $data["AppDefinedData"][0] = [
  297. "Key" => "roomInfo",
  298. "Value" => json_encode($roomInfo),
  299. // "Value" => json_encode(json_decode('{"bg":"","cover":"","isScreen":0,"managers":["14","29"],"needRequest":0,"onMode":2,"ownerId":"55","ownerName":"过户手续","pwd":"","roomName":"告白气球~满眼是✨✨","seatSize":9,"silencers":[]}',true)),
  300. ];
  301. if(isset($roomInfo["ownerId"]) && isset($roomInfo["roomName"])) {
  302. $tencentObj->toSend($data);
  303. }
  304. }
  305. /**
  306. * 强制下线
  307. */
  308. public function downSite($user_id,$groupsites) {
  309. $random = rand(10000000,99999999);
  310. $usersig = $this->usersig("administrator");
  311. // 获取配置信息
  312. $config = config("tencent_im");
  313. $url = "https://console.tim.qq.com/v4/group_open_http_svc/modify_group_base_info";
  314. $url .= "?sdkappid=".$config["sdkappid"];
  315. $url .= "&identifier=administrator";
  316. $url .= "&usersig=".$usersig;
  317. $url .= "&random=".$random;
  318. $url .= "&contenttype=json";
  319. $tencentObj = new tencentim($url);
  320. // 先更新下麦时间
  321. $update = [];
  322. $update["offsite_time"] = time();
  323. $update["status"] = 2;
  324. \app\common\model\UserOnsiteTime::update($update,["user_id"=>$user_id,"status"=>1]);
  325. // 循环房间
  326. if($groupsites) foreach($groupsites as $k => $v) {
  327. // 循环座位
  328. $data = [];
  329. foreach($v["AppDefinedData"] as $m => $n) {
  330. // 解析字段信息
  331. $siteInfo = json_decode($n["Value"],true);
  332. if($m != 0 && isset($siteInfo["status"]) && $siteInfo["status"] == 1 && isset($siteInfo["status"]) && $siteInfo["user"] == $user_id) {
  333. $data["AppDefinedData"][] = [
  334. "Key" => $n["Key"],
  335. "Value" => '{"mute":false,"status":0,"user":""}',
  336. ];
  337. }
  338. }
  339. if(!empty($data)) {
  340. $data["GroupId"] = $v["GroupId"];
  341. return $tencentObj->toSend($data);
  342. }
  343. }
  344. }
  345. /**
  346. * 踢出房间内所有用户
  347. */
  348. public function outMemberFromRoom($party_id) {
  349. if($party_id <= 0) return false;
  350. $message = [];
  351. $message["type"] = "91";
  352. $message["content"] = "房间已被管理员关闭!详情请联系客服!";
  353. $msgData = [];
  354. $msgData["version"] = "1.0";
  355. $msgData["action"] = 301;
  356. $msgData["command"] = "";
  357. $msgData["message"] = json_encode($message);
  358. $random = rand(10000000,99999999);
  359. $usersig = $this->usersig("administrator");
  360. // 获取配置信息
  361. $config = config("tencent_im");
  362. $url = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg";
  363. $url .= "?sdkappid=".$config["sdkappid"];
  364. $url .= "&identifier=administrator";
  365. $url .= "&usersig=".$usersig;
  366. $url .= "&random=".$random;
  367. $url .= "&contenttype=json";
  368. $tencentObj = new tencentim($url);
  369. $data = [];
  370. $data["GroupId"] = $party_id;
  371. $data["Random"] = rand(1000000,9999999);
  372. $data["MsgBody"][] = [
  373. "MsgType" => "TIMCustomElem",
  374. "MsgContent" => [
  375. "Data"=> json_encode($msgData)
  376. ],
  377. ];
  378. $tencentObj->toSend($data);
  379. }
  380. /**
  381. * 获取usersig签名
  382. */
  383. public function getUsersig() {
  384. $user_id = $this->auth->id;
  385. $this->success("获取成功!",$this->usersig($user_id));
  386. }
  387. /**
  388. * 获取usersig签名-具体操作
  389. */
  390. private function usersig($user_id) {
  391. // 获取配置信息
  392. $config = config("tencent_im");
  393. $usersigObj = new getusersig($config["sdkappid"],$config["key"]);
  394. $usersig = $usersigObj->genUserSig($user_id);
  395. return $usersig;
  396. }
  397. /**
  398. * 强制下麦
  399. */
  400. public function updateSiteInfo() {
  401. $user_id = $this->request->request("user_id");// 用户ID
  402. if(!$user_id) $this->error("参数缺失!");
  403. // 更新用户在线状态为离线
  404. \app\common\model\User::update(["is_online"=>0],["id"=>$user_id]);
  405. \app\common\model\User::update(["is_live"=>0],["id"=>$user_id]);
  406. \app\common\model\Party::update(["is_online"=>0],["user_id"=>$user_id]);
  407. // 获取用户所在群信息
  408. $groupids = $this->getJoindGroupList($user_id);
  409. if($groupids["ErrorCode"] == 0) {
  410. $grouplist = $groupids["GroupIdList"];
  411. $groupsites = [];
  412. if($grouplist) foreach($grouplist as $k => $v) {
  413. // 获取群组消息
  414. $groupInfo = $this->getGroupInfo($v["GroupId"]);
  415. if($groupInfo["ErrorCode"] == 0) $groupsites[] = $groupInfo["GroupInfo"][0];
  416. // 踢出用户在线组
  417. $redis = new Redis();
  418. $redisconfig = config("redis");
  419. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  420. if ($redisconfig['redis_pwd']) {
  421. $redis->auth($redisconfig['redis_pwd']);
  422. }
  423. if($redisconfig['redis_selectdb'] > 0){
  424. $redis->select($redisconfig['redis_selectdb']);
  425. }
  426. $redis->HDel("online_".$v["GroupId"],$user_id);
  427. }
  428. // 强制下麦
  429. $this->downSite($user_id,$groupsites);
  430. }
  431. $this->success("状态更新成功!");
  432. }
  433. /**
  434. * 更新麦位前四
  435. */
  436. public function updatePosition($user_id,$party_id) {
  437. // 获取用户头像
  438. $userInfo = \app\common\model\User::field("avatar")->where(["id"=>$user_id])->find();
  439. $userAvatar = isset($userInfo["avatar"])?$userInfo["avatar"]:"";
  440. $redis = new Redis();
  441. $redisconfig = config("redis");
  442. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  443. if ($redisconfig['redis_pwd']) {
  444. $redis->auth($redisconfig['redis_pwd']);
  445. }
  446. if($redisconfig['redis_selectdb'] > 0){
  447. $redis->select($redisconfig['redis_selectdb']);
  448. }
  449. $redisData = $redis->get("party_".$party_id);
  450. if(!$redisData) {
  451. return true;
  452. }
  453. $partyInfo = json_decode($redisData,true);
  454. // 遍历已有头像
  455. $partyuser = isset($partyInfo["party_user"])?$partyInfo["party_user"]:"";
  456. if(is_array($partyuser)) foreach($partyuser as $k => $v) if($v === $userAvatar) unset($partyInfo["party_user"][$k]);
  457. $redis->set("party_".$party_id,json_encode($partyInfo));
  458. }
  459. /**
  460. * 取消排麦
  461. */
  462. public function cancelLineUp($user_id,$party_id) {
  463. if (!$party_id || !$user_id) {
  464. return false;
  465. }
  466. $redis = new Redis();
  467. $redisconfig = config("redis");
  468. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  469. if ($redisconfig['redis_pwd']) {
  470. $redis->auth($redisconfig['redis_pwd']);
  471. }
  472. if($redisconfig['redis_selectdb'] > 0){
  473. $redis->select($redisconfig['redis_selectdb']);
  474. }
  475. $data=unserialize($redis->hGet("party_lineup",$party_id));
  476. // 更改红点排麦数量
  477. $num = 0;
  478. $send = false;
  479. if($data) foreach($data as $k => $v) {
  480. if($v["user_id"] == $user_id) {
  481. $send = true;
  482. unset($data[$k]);
  483. break;
  484. }
  485. }
  486. $redis->hSet("party_lineup",$party_id,serialize($data));
  487. if($send) {
  488. is_array($data) && $num = count($data);
  489. $random = rand(10000000,99999999);
  490. $usersig = $this->usersig("administrator");
  491. // 获取配置信息
  492. $config = config("tencent_im");
  493. $url = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg";
  494. $url .= "?sdkappid=".$config["sdkappid"];
  495. $url .= "&identifier=administrator";
  496. $url .= "&usersig=".$usersig;
  497. $url .= "&random=".$random;
  498. $url .= "&contenttype=json";
  499. $tencentObj = new tencentim($url);
  500. $data = [];
  501. $data["GroupId"] = $party_id;
  502. $data["Random"] = rand(1000000,9999999);
  503. $message = [
  504. "message" => json_encode(["type"=>23,"content"=>$num]),
  505. "version" => "1.0",
  506. "action" => 301,
  507. "command" => ""
  508. ];
  509. $data["MsgBody"][] = [
  510. "MsgType" => "TIMCustomElem",
  511. "MsgContent" => [
  512. "Data"=> json_encode($message)
  513. ],
  514. ];
  515. $tencentObj->toSend($data);
  516. }
  517. }
  518. /**
  519. * 回调
  520. */
  521. public function callback() {
  522. $input = file_get_contents("php://input"); // 主题信息
  523. $input = json_decode($input,true);
  524. $CallbackCommand = $input["CallbackCommand"];
  525. switch ($CallbackCommand) {
  526. case 'State.StateChange': // 用户在线状态变更
  527. $info = $input["Info"];
  528. if($info["Action"] == "Login") { // 用户登录
  529. $loginToday = Db::name('user')->where('id',$info["To_Account"])->whereTime('onlinetime', 'today')->find();
  530. if ($loginToday){
  531. \app\common\model\User::update(["is_online"=>1,"onlinetime"=>time()],["id"=>$info["To_Account"]]);
  532. }else{
  533. \app\common\model\User::update(["is_online"=>1,"onlinetime"=>time()],["id"=>$info["To_Account"]]);
  534. }
  535. $res = [];
  536. $res["ActionStatus"] = "OK";
  537. $res["ErrorCode"] = 0;
  538. $res["ErrorInfo"] = "";
  539. echo json_encode($res);exit;
  540. } elseif($info["Action"] == "Logout" || $info["Action"] == "Disconnect") { // 用户退出 不需要管什么原因
  541. // 更新用户在线状态为离线
  542. \app\common\model\User::update(["is_online"=>0],["id"=>$info["To_Account"]]);
  543. \app\common\model\User::update(["is_live"=>0],["id"=>$info["To_Account"]]);
  544. // 获取用户在派对直播间情况信息
  545. $redis = new Redis();
  546. $redisconfig = config("redis");
  547. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  548. if ($redisconfig['redis_pwd']) {
  549. $redis->auth($redisconfig['redis_pwd']);
  550. }
  551. if($redisconfig['redis_selectdb'] > 0){
  552. $redis->select($redisconfig['redis_selectdb']);
  553. }
  554. $livingUserPartyId = $redis->hGet("livingUser", $info["To_Account"]);
  555. if ($livingUserPartyId) {
  556. // 扣除在线用户在房间情况
  557. $redis->hDel("livingUser", $info["To_Account"]);
  558. $redis->HDel("online_" . $livingUserPartyId, $info["To_Account"]);
  559. }
  560. // 获取用户所在群信息
  561. $groupids = $this->getJoindGroupList($info["To_Account"]);
  562. // \app\common\model\Test::update(["content"=>json_encode($groupids)],["id"=>1]);
  563. if($groupids["ErrorCode"] == 0) {
  564. $grouplist = $groupids["GroupIdList"];
  565. $groupsites = [];
  566. if($grouplist) foreach($grouplist as $k => $v) {
  567. // 获取群组消息
  568. $groupInfo = $this->getGroupInfo($v["GroupId"]);
  569. if($groupInfo["ErrorCode"] == 0) $groupsites[] = $groupInfo["GroupInfo"][0];
  570. // 踢出用户在线组
  571. $redis = new Redis();
  572. $redisconfig = config("redis");
  573. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  574. if ($redisconfig['redis_pwd']) {
  575. $redis->auth($redisconfig['redis_pwd']);
  576. }
  577. if($redisconfig['redis_selectdb'] > 0){
  578. $redis->select($redisconfig['redis_selectdb']);
  579. }
  580. $redis->HDel("online_".$v["GroupId"],$info["To_Account"]);
  581. // 更新麦位前四
  582. $this->updatePosition($info["To_Account"],$v["GroupId"]);
  583. // 取消排麦
  584. $this->cancelLineup($info["To_Account"],$v["GroupId"]);
  585. // 房间状态变更
  586. $partyInfo = $redis->get("party_".$v["GroupId"]);
  587. if($partyInfo) {
  588. $partyInfo = json_decode($partyInfo,true);
  589. $memCount = count($redis->hGetAll("online_".$v["GroupId"]));
  590. if($memCount <= 0) {
  591. $partyInfo["is_online"] = 0;
  592. $redis->set("party_".$v["GroupId"],json_encode($partyInfo));
  593. \app\common\model\Party::update(["is_online"=>0],["id"=>$v["GroupId"]]);
  594. }
  595. }
  596. $liveInfo = $redis->get("live_".$v["GroupId"]);
  597. if($liveInfo) {
  598. $liveInfo = json_decode($liveInfo,true);
  599. $memCount = count($redis->hGetAll("online_".$v["GroupId"]));
  600. if($memCount <= 0) {
  601. $liveInfo["is_online"] = 0;
  602. $redis->set("live_".$v["GroupId"],json_encode($liveInfo));
  603. \app\common\model\Party::update(["is_online"=>0],["id"=>$v["GroupId"]]);
  604. }
  605. }
  606. }
  607. // 强制下麦
  608. print_r($this->downSite($info["To_Account"],$groupsites));
  609. }
  610. }
  611. break;
  612. case 'Group.CallbackAfterNewMemberJoin': // 新成员入群
  613. $redis = new Redis();
  614. $redisconfig = config("redis");
  615. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  616. if ($redisconfig['redis_pwd']) {
  617. $redis->auth($redisconfig['redis_pwd']);
  618. }
  619. if($redisconfig['redis_selectdb'] > 0){
  620. $redis->select($redisconfig['redis_selectdb']);
  621. }
  622. $members = $input["NewMemberList"];
  623. if($members) foreach($members as $k => $v) {
  624. $redis->hSet("online_".$input["GroupId"],$v["Member_Account"],$v["Member_Account"]);
  625. // 更新房间在线状态
  626. $party_id = $input["GroupId"];
  627. $partyInfo = $redis->get("party_".$party_id);
  628. if($partyInfo) {
  629. $partyInfo = json_decode($partyInfo,true);
  630. if($partyInfo["is_online"] != 1) {
  631. $partyInfo["is_online"] = 1;
  632. $redis->set("party_".$party_id,json_encode($partyInfo));
  633. \app\common\model\Party::update(["is_online"=>1],["id"=>$party_id]);
  634. }
  635. }
  636. }
  637. $res = [];
  638. $res["ActionStatus"] = "OK";
  639. $res["ErrorCode"] = 0;
  640. $res["ErrorInfo"] = "";
  641. echo json_encode($res);
  642. break;
  643. case 'Group.CallbackAfterMemberExit': // 成员离开
  644. $redis = new Redis();
  645. $redisconfig = config("redis");
  646. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  647. if ($redisconfig['redis_pwd']) {
  648. $redis->auth($redisconfig['redis_pwd']);
  649. }
  650. if($redisconfig['redis_selectdb'] > 0){
  651. $redis->select($redisconfig['redis_selectdb']);
  652. }
  653. $members = $input["ExitMemberList"];
  654. if($members) foreach($members as $k => $v) {
  655. $redis->HDel("online_".$input["GroupId"],$v["Member_Account"]);
  656. }
  657. // 更新房间在线状态
  658. $party_id = $input["GroupId"];
  659. $partyInfo = $redis->get("party_".$party_id);
  660. if($partyInfo) {
  661. $partyInfo = json_decode($partyInfo,true);
  662. $memCount = count($redis->hGetAll("online_".$party_id));
  663. if($memCount <= 0) {
  664. $partyInfo["is_online"] = 0;
  665. $redis->set("party_".$party_id,json_encode($partyInfo));
  666. \app\common\model\Party::update(["is_online"=>0],["id"=>$party_id]);
  667. }
  668. }
  669. $liveInfo = $redis->get("live_".$party_id);
  670. if($liveInfo) {
  671. $liveInfo = json_decode($liveInfo,true);
  672. $memCount = count($redis->hGetAll("online_".$party_id));
  673. if($memCount <= 0) {
  674. $liveInfo["is_online"] = 0;
  675. $redis->set("live_".$party_id,json_encode($liveInfo));
  676. \app\common\model\Party::update(["is_online"=>0],["id"=>$party_id]);
  677. }
  678. }
  679. $res = [];
  680. $res["ActionStatus"] = "OK";
  681. $res["ErrorCode"] = 0;
  682. $res["ErrorInfo"] = "";
  683. echo json_encode($res);
  684. break;
  685. /* case 'Group.CallbackBeforeSendMsg': // 群内发送消息之前
  686. $config = config("wxMiniProgram");
  687. $access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$config["appid"]."&secret=".$config["secret"];
  688. $access_token_arr = $this->getJson($access_token_url);
  689. $access_token = isset($access_token_arr["access_token"])?$access_token_arr["access_token"]:"";
  690. if(!$access_token) {
  691. $res = [];
  692. $res["ActionStatus"] = "OK";
  693. $res["ErrorInfo"] = "";
  694. $res["ErrorCode"] = 0;
  695. echo json_encode($res);
  696. break;
  697. }
  698. // \app\common\model\Test::update(["content"=>json_encode($access_token)],["id"=>1]);
  699. $infoMessage = $input["MsgBody"];
  700. $badMessage = false;
  701. if($infoMessage) foreach($infoMessage as $k => $v) {
  702. if(isset($v["MsgContent"]["Text"])) {
  703. $message = json_decode($v["MsgContent"]["Text"],true);
  704. $content = isset($message["content"])?$message["content"]:"";
  705. $message_check_url ='https://api.weixin.qq.com/wxa/msg_sec_check?access_token='.$access_token;
  706. $tencentObj = new tencentim($message_check_url);
  707. $content_json = '{"content": "'.$content.'"}';
  708. $body = $tencentObj->messageCheck($content_json);
  709. if($body["errcode"] == 87014) {
  710. // \app\common\model\Test::update(["content"=>$body["errcode"]],["id"=>1]);
  711. // $res = [];
  712. // $res["ActionStatus"] = "OK";
  713. // $res["ErrorInfo"] = "检测到敏感词汇!";
  714. // $res["ErrorCode"] = 1;
  715. // echo json_encode($res);exit;
  716. $message["content"] = "*******";
  717. $infoMessage[$k]["MsgContent"]["Text"] = json_encode($message);
  718. $badMessage = true;
  719. }
  720. }
  721. }
  722. if($badMessage) {
  723. $res = [];
  724. $res["ActionStatus"] = "OK";
  725. $res["ErrorInfo"] = "检测到敏感词汇!";
  726. $res["ErrorCode"] = 10102;
  727. $res["MsgBody"] = $infoMessage;
  728. } else {
  729. $res = [];
  730. $res["ActionStatus"] = "OK";
  731. $res["ErrorInfo"] = "";
  732. $res["ErrorCode"] = 0;
  733. }
  734. // \app\common\model\Test::update(["content"=>json_encode($res)],["id"=>1]);
  735. echo json_encode($res);exit;
  736. break;*/
  737. default:
  738. break;
  739. }
  740. exit;
  741. }
  742. private function getJson($url){
  743. $ch = curl_init();
  744. curl_setopt($ch, CURLOPT_URL, $url);
  745. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  746. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  747. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  748. $output = curl_exec($ch);
  749. curl_close($ch);
  750. return json_decode($output, true);
  751. }
  752. /**
  753. * 发送消息给某人
  754. */
  755. public function sendMessageToUser($from_user,$to_user,$message) {
  756. // $from_user = 54;
  757. // $to_user = 6;
  758. // $message = "sdsd";
  759. $random = rand(10000000,99999999);
  760. $usersig = $this->usersig("administrator");
  761. // 获取配置信息
  762. $config = config("tencent_im");
  763. $url = "https://console.tim.qq.com/v4/openim/sendmsg";
  764. $url .= "?sdkappid=".$config["sdkappid"];
  765. $url .= "&identifier=administrator";
  766. $url .= "&usersig=".$usersig;
  767. $url .= "&random=".$random;
  768. $url .= "&contenttype=json";
  769. $tencentObj = new tencentim($url);
  770. $data = [];
  771. $data["SyncOtherMachine"] = 1;
  772. $data["From_Account"] = (string)$from_user;
  773. $data["To_Account"] = (string)$to_user;
  774. $data["MsgRandom"] = rand(1000000,9999999);
  775. $data["MsgTimeStamp"] = time();
  776. $data["MsgBody"][] = [
  777. "MsgType" => "TIMTextElem",
  778. "MsgContent" => [
  779. "Text"=> $message
  780. ],
  781. ];
  782. $tencentObj->toSend($data);
  783. }
  784. /**
  785. * 发送消息给某人-接口调用
  786. */
  787. public function sendToUser() {
  788. $from_user = $this->request->request("from_user");// 发送者
  789. $to_user = $this->request->request("to_user");// 接收者
  790. $message = $this->request->request("message");// 接收者
  791. if(!$from_user || !$to_user || !$message) $this->error("参数缺失!");
  792. $this->sendMessageToUser($from_user,$to_user,$message);
  793. }
  794. //请求的基础参数
  795. private function baseTencentObj($url)
  796. {
  797. $random = rand(10000000,99999999);
  798. $usersig = $this->usersig("administrator");
  799. // 获取配置信息
  800. $config = config("tencent_im");
  801. $url = "$url";
  802. $url .= "?sdkappid=".$config["sdkappid"];
  803. $url .= "&identifier=administrator";
  804. $url .= "&usersig=".$usersig;
  805. $url .= "&random=".$random;
  806. $url .= "&contenttype=json";
  807. return new tencentim($url);
  808. }
  809. /** 设置管理员(im端的改变)
  810. * @param $user_id
  811. * @param $party_id
  812. * @param int $status 1:yes 0:no
  813. * @return array|false|mixed
  814. */
  815. public function setUpIMAdmin($user_id, $party_id, int $status=0) {
  816. $url = "https://console.tim.qq.com/v4/group_open_http_svc/modify_group_member_info";
  817. $tencentObj = $this->baseTencentObj($url);
  818. $groupInfo = $this->getGroupInfo($party_id);
  819. if($groupInfo["GroupInfo"][0]["ErrorCode"] > 0) return false;
  820. // 更新的信息
  821. $data = [];
  822. $data["GroupId"] = $party_id;
  823. if ($status==1){
  824. $data['Role'] = 'Admin';
  825. }else{
  826. $data['Role'] = 'Member';
  827. }
  828. $data['Member_Account'] = $user_id;
  829. return $tencentObj->toSend($data);
  830. }
  831. //获取群成员详细资料(目前没用到)
  832. private function getGroupMemberDetails($party_id)
  833. {
  834. $url = "https://console.tim.qq.com/v4/group_open_http_svc/get_group_member_info";
  835. $tencentObj = $this->baseTencentObj($url);
  836. // 获取群组信息
  837. $groupInfo = $this->getGroupInfo($party_id);
  838. if($groupInfo["GroupInfo"][0]["ErrorCode"] > 0) return false;
  839. // 更新的信息
  840. $data = [];
  841. $data["GroupId"] = $party_id;
  842. return $tencentObj->toSend($data);
  843. }
  844. //IM管理员维护,同步本地管理员
  845. public function imAdminMaintenance()
  846. {
  847. $partyIds = \app\admin\model\party\Party::column('id');
  848. foreach ($partyIds as $party_id){
  849. $groupInfo = $this->getGroupInfo($party_id);
  850. if($groupInfo["GroupInfo"][0]["ErrorCode"] > 0) continue;
  851. $roomInfoData = $groupInfo["GroupInfo"][0]["AppDefinedData"];
  852. $roomInfo = [];
  853. if($roomInfoData) foreach($roomInfoData as $k => $v) {
  854. if($v["Key"] == "roomInfo") $roomInfo = $v["Value"];
  855. }
  856. $roomInfo = json_decode($roomInfo,true);
  857. // 更新管理员
  858. if(isset($roomInfo["managers"]) && !empty($roomInfo['managers'])) {
  859. foreach ($roomInfo['managers'] as $v){
  860. $this->setUpIMAdmin($v,$party_id,1);
  861. }
  862. }
  863. }
  864. $this->success("成功!");
  865. }
  866. /**
  867. * 获取用户在线更新
  868. */
  869. public function autoUserLine() {
  870. $random = rand(10000000,99999999);
  871. $usersig = $this->usersig("administrator");
  872. // 获取配置信息
  873. $config = config("tencent_im");
  874. $url = "https://console.tim.qq.com/v4/openim/query_online_status";
  875. $url .= "?sdkappid=".$config["sdkappid"];
  876. $url .= "&identifier=administrator";
  877. $url .= "&usersig=".$usersig;
  878. $url .= "&random=".$random;
  879. $url .= "&contenttype=json";
  880. $tencentObj = new tencentim($url);
  881. // 获取用户
  882. $where = [];
  883. $userData = model('User')->field('id')->where($where)->order('id asc')->select();
  884. $userArr = array_column($userData,'id');
  885. $data = [];
  886. $data["To_Account"] = $userArr;
  887. $result = [];
  888. if(!empty($data)) {
  889. $result = $tencentObj->toSend($data);
  890. if (isset($result['ActionStatus']) && $result['ActionStatus'] == 'OK') {
  891. if (isset($result['ErrorList'])) {//没有人员
  892. unset($result['ErrorList']);
  893. /*foreach ($result['ErrorList'] as $errKey => $errVal) {
  894. $userError[] = $errVal['To_Account'];
  895. }*/
  896. }
  897. if (isset($result['QueryResult'])) {
  898. $userOnline = $userOffline=[];
  899. foreach ($result['QueryResult'] as $key => $value) {
  900. if (in_array($value['Status'],['Online','PushOnline'])) {//在线(前台在线和后台在线)
  901. $userOnline[] = intval($value['To_Account']);
  902. } else {//离线
  903. $userOffline[] = intval($value['To_Account']);
  904. }
  905. }
  906. if (!empty($userOnline)) {//处理在线
  907. $onlineWhere['id'] = ['in',$userOnline];
  908. $onlineWhere['is_online'] = 0;
  909. model('User')->where($onlineWhere)->update(['is_online'=>1]);
  910. }
  911. if (!empty($userOffline)) {//处理离线
  912. $offlineWhere['id'] = ['in',$userOffline];
  913. $offlineWhere['is_online'] = 1;
  914. model('User')->where($offlineWhere)->update(['is_online'=>0]);
  915. }
  916. }
  917. }
  918. }
  919. $this->success('操作成功');
  920. }
  921. /**
  922. * 获取房间用户
  923. */
  924. public function getRoomUser() {
  925. $partyIds = $this->request->param('party_ids','');
  926. if (!empty($partyIds)) {
  927. $partyIds = explode(',',$partyIds);
  928. }
  929. $random = rand(10000000,99999999);
  930. $usersig = $this->usersig("administrator");
  931. // 获取配置信息
  932. $config = config("tencent_im");
  933. $url = "https://console.tim.qq.com/v4/group_open_avchatroom_http_svc/get_members";
  934. $url .= "?sdkappid=".$config["sdkappid"];
  935. $url .= "&identifier=administrator";
  936. $url .= "&usersig=".$usersig;
  937. $url .= "&random=".$random;
  938. $url .= "&contenttype=json";
  939. $tencentObj = new tencentim($url);
  940. //获取用户 ["57","62","63","105","106","107","108","109","116","119"]
  941. $partyArr = $partyIds;
  942. $memberList = [];
  943. if(!empty($partyArr)) {
  944. foreach ($partyArr as $key => $value) {
  945. $data["GroupId"] = $value;
  946. $result = $tencentObj->toSend($data);
  947. if (isset($result['ActionStatus']) && $result['ActionStatus'] == 'OK') {
  948. if (isset($result['MemberList']) && !empty($result['MemberList'])) {
  949. foreach ($result['MemberList'] as $ukey => $uval) {
  950. $memberList[$value]['member_list'][] = [
  951. 'avatar' => $uval['Avatar'],
  952. 'user_id'=> $uval['Member_Account'],
  953. 'nickname' => $uval['NickName'],
  954. ];
  955. }
  956. $memberList[$value]['online_num'] = count($memberList[$value]['member_list']);
  957. }
  958. }
  959. }
  960. }
  961. $result = $memberList;
  962. $this->success('操作成功',$result);
  963. }
  964. }