Tenim.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  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. // 更新下麦时间
  441. $update = [];
  442. $update["offsite_time"] = time();
  443. $update["status"] = 2;
  444. \app\common\model\UserOnsiteTime::update($update,["user_id"=>$user_id,"status"=>1]);
  445. //
  446. $redis = new Redis();
  447. $redisconfig = config("redis");
  448. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  449. if ($redisconfig['redis_pwd']) {
  450. $redis->auth($redisconfig['redis_pwd']);
  451. }
  452. if($redisconfig['redis_selectdb'] > 0){
  453. $redis->select($redisconfig['redis_selectdb']);
  454. }
  455. $room_type = 'party';
  456. $redisData = $redis->get("party_".$party_id);
  457. if(!$redisData) {
  458. $room_type = 'live';
  459. $redisData = $redis->get("live_".$party_id);
  460. }
  461. if(!$redisData){
  462. return true;
  463. }
  464. $partyInfo = json_decode($redisData,true);
  465. // 遍历已有头像
  466. $partyuser = isset($partyInfo["party_user"])?$partyInfo["party_user"]:"";
  467. if(is_array($partyuser)) foreach($partyuser as $k => $v) if($v === $userAvatar) unset($partyInfo["party_user"][$k]);
  468. $redis->set($room_type."_".$party_id,json_encode($partyInfo));
  469. }
  470. /**
  471. * 取消排麦
  472. */
  473. public function cancelLineUp($user_id,$party_id) {
  474. if (!$party_id || !$user_id) {
  475. return false;
  476. }
  477. $redis = new Redis();
  478. $redisconfig = config("redis");
  479. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  480. if ($redisconfig['redis_pwd']) {
  481. $redis->auth($redisconfig['redis_pwd']);
  482. }
  483. if($redisconfig['redis_selectdb'] > 0){
  484. $redis->select($redisconfig['redis_selectdb']);
  485. }
  486. $data=unserialize($redis->hGet("party_lineup",$party_id));
  487. // 更改红点排麦数量
  488. $num = 0;
  489. $send = false;
  490. if($data) foreach($data as $k => $v) {
  491. if($v["user_id"] == $user_id) {
  492. $send = true;
  493. unset($data[$k]);
  494. break;
  495. }
  496. }
  497. $redis->hSet("party_lineup",$party_id,serialize($data));
  498. if($send) {
  499. is_array($data) && $num = count($data);
  500. $random = rand(10000000,99999999);
  501. $usersig = $this->usersig("administrator");
  502. // 获取配置信息
  503. $config = config("tencent_im");
  504. $url = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg";
  505. $url .= "?sdkappid=".$config["sdkappid"];
  506. $url .= "&identifier=administrator";
  507. $url .= "&usersig=".$usersig;
  508. $url .= "&random=".$random;
  509. $url .= "&contenttype=json";
  510. $tencentObj = new tencentim($url);
  511. $data = [];
  512. $data["GroupId"] = $party_id;
  513. $data["Random"] = rand(1000000,9999999);
  514. $message = [
  515. "message" => json_encode(["type"=>23,"content"=>$num]),
  516. "version" => "1.0",
  517. "action" => 301,
  518. "command" => ""
  519. ];
  520. $data["MsgBody"][] = [
  521. "MsgType" => "TIMCustomElem",
  522. "MsgContent" => [
  523. "Data"=> json_encode($message)
  524. ],
  525. ];
  526. $tencentObj->toSend($data);
  527. }
  528. }
  529. /**
  530. * 回调
  531. */
  532. public function callback() {
  533. $input = file_get_contents("php://input"); // 主题信息
  534. $input = json_decode($input,true);
  535. $CallbackCommand = $input["CallbackCommand"];
  536. switch ($CallbackCommand) {
  537. case 'State.StateChange': // 用户在线状态变更
  538. $info = $input["Info"];
  539. if($info["Action"] == "Login") { // 用户登录
  540. $loginToday = Db::name('user')->where('id',$info["To_Account"])->whereTime('onlinetime', 'today')->find();
  541. if ($loginToday){
  542. \app\common\model\User::update(["is_online"=>1,"onlinetime"=>time()],["id"=>$info["To_Account"]]);
  543. }else{
  544. \app\common\model\User::update(["is_online"=>1,"onlinetime"=>time()],["id"=>$info["To_Account"]]);
  545. }
  546. $res = [];
  547. $res["ActionStatus"] = "OK";
  548. $res["ErrorCode"] = 0;
  549. $res["ErrorInfo"] = "";
  550. echo json_encode($res);exit;
  551. } elseif($info["Action"] == "Logout" || $info["Action"] == "Disconnect") { // 用户退出 不需要管什么原因
  552. // 更新用户在线状态为离线
  553. \app\common\model\User::update(["is_online"=>0],["id"=>$info["To_Account"]]);
  554. \app\common\model\User::update(["is_live"=>0],["id"=>$info["To_Account"]]);
  555. // 获取用户在派对直播间情况信息
  556. $redis = new Redis();
  557. $redisconfig = config("redis");
  558. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  559. if ($redisconfig['redis_pwd']) {
  560. $redis->auth($redisconfig['redis_pwd']);
  561. }
  562. if($redisconfig['redis_selectdb'] > 0){
  563. $redis->select($redisconfig['redis_selectdb']);
  564. }
  565. $livingUserPartyId = $redis->hGet("livingUser", $info["To_Account"]);
  566. if ($livingUserPartyId) {
  567. // 扣除在线用户在房间情况
  568. $redis->hDel("livingUser", $info["To_Account"]);
  569. $redis->HDel("online_" . $livingUserPartyId, $info["To_Account"]);
  570. $redis->zRem("party_user_".$livingUserPartyId,$info["To_Account"]); //新加的
  571. }
  572. // 获取用户所在群信息
  573. $groupids = $this->getJoindGroupList($info["To_Account"]);
  574. // \app\common\model\Test::update(["content"=>json_encode($groupids)],["id"=>1]);
  575. if($groupids["ErrorCode"] == 0) {
  576. $grouplist = $groupids["GroupIdList"];
  577. $groupsites = [];
  578. if($grouplist) foreach($grouplist as $k => $v) {
  579. // 获取群组消息
  580. $groupInfo = $this->getGroupInfo($v["GroupId"]);
  581. if($groupInfo["ErrorCode"] == 0) $groupsites[] = $groupInfo["GroupInfo"][0];
  582. // 踢出用户在线组
  583. $redis = new Redis();
  584. $redisconfig = config("redis");
  585. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  586. if ($redisconfig['redis_pwd']) {
  587. $redis->auth($redisconfig['redis_pwd']);
  588. }
  589. if($redisconfig['redis_selectdb'] > 0){
  590. $redis->select($redisconfig['redis_selectdb']);
  591. }
  592. $redis->HDel("online_".$v["GroupId"],$info["To_Account"]);
  593. $redis->zRem("party_user_".$v["GroupId"],$info["To_Account"]); //新加的
  594. // 更新麦位前四
  595. $this->updatePosition($info["To_Account"],$v["GroupId"]);
  596. // 取消排麦
  597. $this->cancelLineup($info["To_Account"],$v["GroupId"]);
  598. // 房间状态变更
  599. $partyInfo = $redis->get("party_".$v["GroupId"]);
  600. if($partyInfo) {
  601. $partyInfo = json_decode($partyInfo,true);
  602. $memCount = count($redis->hGetAll("online_".$v["GroupId"]));
  603. if($memCount <= 0) {
  604. $partyInfo["is_online"] = 0;
  605. $redis->set("party_".$v["GroupId"],json_encode($partyInfo));
  606. \app\common\model\Party::update(["is_online"=>0],["id"=>$v["GroupId"]]);
  607. }
  608. }
  609. $liveInfo = $redis->get("live_".$v["GroupId"]);
  610. if($liveInfo) {
  611. $liveInfo = json_decode($liveInfo,true);
  612. $memCount = count($redis->hGetAll("online_".$v["GroupId"]));
  613. if($memCount <= 0) {
  614. $liveInfo["is_online"] = 0;
  615. $redis->set("live_".$v["GroupId"],json_encode($liveInfo));
  616. \app\common\model\Party::update(["is_online"=>0],["id"=>$v["GroupId"]]);
  617. }
  618. }
  619. }
  620. // 强制下麦
  621. print_r($this->downSite($info["To_Account"],$groupsites));
  622. }
  623. }
  624. break;
  625. /*case 'Group.CallbackAfterNewMemberJoin': // 新成员入群
  626. $redis = new Redis();
  627. $redisconfig = config("redis");
  628. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  629. if ($redisconfig['redis_pwd']) {
  630. $redis->auth($redisconfig['redis_pwd']);
  631. }
  632. if($redisconfig['redis_selectdb'] > 0){
  633. $redis->select($redisconfig['redis_selectdb']);
  634. }
  635. $members = $input["NewMemberList"];
  636. if($members) foreach($members as $k => $v) {
  637. $redis->hSet("online_".$input["GroupId"],$v["Member_Account"],$v["Member_Account"]);
  638. // 更新房间在线状态
  639. $party_id = $input["GroupId"];
  640. $partyInfo = $redis->get("party_".$party_id);
  641. if($partyInfo) {
  642. $partyInfo = json_decode($partyInfo,true);
  643. if($partyInfo["is_online"] != 1) {
  644. $partyInfo["is_online"] = 1;
  645. $redis->set("party_".$party_id,json_encode($partyInfo));
  646. \app\common\model\Party::update(["is_online"=>1],["id"=>$party_id]);
  647. }
  648. }
  649. }
  650. $res = [];
  651. $res["ActionStatus"] = "OK";
  652. $res["ErrorCode"] = 0;
  653. $res["ErrorInfo"] = "";
  654. echo json_encode($res);
  655. break;*/
  656. /*case 'Group.CallbackAfterMemberExit': // 成员离开
  657. $redis = new Redis();
  658. $redisconfig = config("redis");
  659. $redis->connect($redisconfig["host"], $redisconfig["port"]);
  660. if ($redisconfig['redis_pwd']) {
  661. $redis->auth($redisconfig['redis_pwd']);
  662. }
  663. if($redisconfig['redis_selectdb'] > 0){
  664. $redis->select($redisconfig['redis_selectdb']);
  665. }
  666. $members = $input["ExitMemberList"];
  667. if($members) foreach($members as $k => $v) {
  668. $redis->HDel("online_".$input["GroupId"],$v["Member_Account"]);
  669. }
  670. // 更新房间在线状态
  671. $party_id = $input["GroupId"];
  672. $partyInfo = $redis->get("party_".$party_id);
  673. if($partyInfo) {
  674. $partyInfo = json_decode($partyInfo,true);
  675. $memCount = count($redis->hGetAll("online_".$party_id));
  676. if($memCount <= 0) {
  677. $partyInfo["is_online"] = 0;
  678. $redis->set("party_".$party_id,json_encode($partyInfo));
  679. \app\common\model\Party::update(["is_online"=>0],["id"=>$party_id]);
  680. }
  681. }
  682. $liveInfo = $redis->get("live_".$party_id);
  683. if($liveInfo) {
  684. $liveInfo = json_decode($liveInfo,true);
  685. $memCount = count($redis->hGetAll("online_".$party_id));
  686. if($memCount <= 0) {
  687. $liveInfo["is_online"] = 0;
  688. $redis->set("live_".$party_id,json_encode($liveInfo));
  689. \app\common\model\Party::update(["is_online"=>0],["id"=>$party_id]);
  690. }
  691. }
  692. $res = [];
  693. $res["ActionStatus"] = "OK";
  694. $res["ErrorCode"] = 0;
  695. $res["ErrorInfo"] = "";
  696. echo json_encode($res);
  697. break;*/
  698. /* case 'Group.CallbackBeforeSendMsg': // 群内发送消息之前
  699. $config = config("wxMiniProgram");
  700. $access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$config["appid"]."&secret=".$config["secret"];
  701. $access_token_arr = $this->getJson($access_token_url);
  702. $access_token = isset($access_token_arr["access_token"])?$access_token_arr["access_token"]:"";
  703. if(!$access_token) {
  704. $res = [];
  705. $res["ActionStatus"] = "OK";
  706. $res["ErrorInfo"] = "";
  707. $res["ErrorCode"] = 0;
  708. echo json_encode($res);
  709. break;
  710. }
  711. // \app\common\model\Test::update(["content"=>json_encode($access_token)],["id"=>1]);
  712. $infoMessage = $input["MsgBody"];
  713. $badMessage = false;
  714. if($infoMessage) foreach($infoMessage as $k => $v) {
  715. if(isset($v["MsgContent"]["Text"])) {
  716. $message = json_decode($v["MsgContent"]["Text"],true);
  717. $content = isset($message["content"])?$message["content"]:"";
  718. $message_check_url ='https://api.weixin.qq.com/wxa/msg_sec_check?access_token='.$access_token;
  719. $tencentObj = new tencentim($message_check_url);
  720. $content_json = '{"content": "'.$content.'"}';
  721. $body = $tencentObj->messageCheck($content_json);
  722. if($body["errcode"] == 87014) {
  723. // \app\common\model\Test::update(["content"=>$body["errcode"]],["id"=>1]);
  724. // $res = [];
  725. // $res["ActionStatus"] = "OK";
  726. // $res["ErrorInfo"] = "检测到敏感词汇!";
  727. // $res["ErrorCode"] = 1;
  728. // echo json_encode($res);exit;
  729. $message["content"] = "*******";
  730. $infoMessage[$k]["MsgContent"]["Text"] = json_encode($message);
  731. $badMessage = true;
  732. }
  733. }
  734. }
  735. if($badMessage) {
  736. $res = [];
  737. $res["ActionStatus"] = "OK";
  738. $res["ErrorInfo"] = "检测到敏感词汇!";
  739. $res["ErrorCode"] = 10102;
  740. $res["MsgBody"] = $infoMessage;
  741. } else {
  742. $res = [];
  743. $res["ActionStatus"] = "OK";
  744. $res["ErrorInfo"] = "";
  745. $res["ErrorCode"] = 0;
  746. }
  747. // \app\common\model\Test::update(["content"=>json_encode($res)],["id"=>1]);
  748. echo json_encode($res);exit;
  749. break;*/
  750. default:
  751. break;
  752. }
  753. exit;
  754. }
  755. private function getJson($url){
  756. $ch = curl_init();
  757. curl_setopt($ch, CURLOPT_URL, $url);
  758. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  759. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  760. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  761. $output = curl_exec($ch);
  762. curl_close($ch);
  763. return json_decode($output, true);
  764. }
  765. /**
  766. * 发送消息给某人
  767. */
  768. public function sendMessageToUser($from_user,$to_user,$message) {
  769. // $from_user = 54;
  770. // $to_user = 6;
  771. // $message = "sdsd";
  772. $random = rand(10000000,99999999);
  773. $usersig = $this->usersig("administrator");
  774. // 获取配置信息
  775. $config = config("tencent_im");
  776. $url = "https://console.tim.qq.com/v4/openim/sendmsg";
  777. $url .= "?sdkappid=".$config["sdkappid"];
  778. $url .= "&identifier=administrator";
  779. $url .= "&usersig=".$usersig;
  780. $url .= "&random=".$random;
  781. $url .= "&contenttype=json";
  782. $tencentObj = new tencentim($url);
  783. $data = [];
  784. $data["SyncOtherMachine"] = 1;
  785. $data["From_Account"] = (string)$from_user;
  786. $data["To_Account"] = (string)$to_user;
  787. $data["MsgRandom"] = rand(1000000,9999999);
  788. $data["MsgTimeStamp"] = time();
  789. $data["MsgBody"][] = [
  790. "MsgType" => "TIMTextElem",
  791. "MsgContent" => [
  792. "Text"=> $message
  793. ],
  794. ];
  795. $tencentObj->toSend($data);
  796. }
  797. /**
  798. * 发送消息给某人-接口调用
  799. */
  800. public function sendToUser() {
  801. $from_user = $this->request->request("from_user");// 发送者
  802. $to_user = $this->request->request("to_user");// 接收者
  803. $message = $this->request->request("message");// 接收者
  804. if(!$from_user || !$to_user || !$message) $this->error("参数缺失!");
  805. $this->sendMessageToUser($from_user,$to_user,$message);
  806. }
  807. //请求的基础参数
  808. private function baseTencentObj($url)
  809. {
  810. $random = rand(10000000,99999999);
  811. $usersig = $this->usersig("administrator");
  812. // 获取配置信息
  813. $config = config("tencent_im");
  814. $url = "$url";
  815. $url .= "?sdkappid=".$config["sdkappid"];
  816. $url .= "&identifier=administrator";
  817. $url .= "&usersig=".$usersig;
  818. $url .= "&random=".$random;
  819. $url .= "&contenttype=json";
  820. return new tencentim($url);
  821. }
  822. /** 设置管理员(im端的改变)
  823. * @param $user_id
  824. * @param $party_id
  825. * @param int $status 1:yes 0:no
  826. * @return array|false|mixed
  827. */
  828. public function setUpIMAdmin($user_id, $party_id, int $status=0) {
  829. $url = "https://console.tim.qq.com/v4/group_open_http_svc/modify_group_member_info";
  830. $tencentObj = $this->baseTencentObj($url);
  831. $groupInfo = $this->getGroupInfo($party_id);
  832. if($groupInfo["GroupInfo"][0]["ErrorCode"] > 0) return false;
  833. // 更新的信息
  834. $data = [];
  835. $data["GroupId"] = $party_id;
  836. if ($status==1){
  837. $data['Role'] = 'Admin';
  838. }else{
  839. $data['Role'] = 'Member';
  840. }
  841. $data['Member_Account'] = $user_id;
  842. return $tencentObj->toSend($data);
  843. }
  844. //获取群成员详细资料(目前没用到)
  845. private function getGroupMemberDetails($party_id)
  846. {
  847. $url = "https://console.tim.qq.com/v4/group_open_http_svc/get_group_member_info";
  848. $tencentObj = $this->baseTencentObj($url);
  849. // 获取群组信息
  850. $groupInfo = $this->getGroupInfo($party_id);
  851. if($groupInfo["GroupInfo"][0]["ErrorCode"] > 0) return false;
  852. // 更新的信息
  853. $data = [];
  854. $data["GroupId"] = $party_id;
  855. return $tencentObj->toSend($data);
  856. }
  857. //IM管理员维护,同步本地管理员
  858. public function imAdminMaintenance()
  859. {
  860. $partyIds = \app\admin\model\party\Party::column('id');
  861. foreach ($partyIds as $party_id){
  862. $groupInfo = $this->getGroupInfo($party_id);
  863. if($groupInfo["GroupInfo"][0]["ErrorCode"] > 0) continue;
  864. $roomInfoData = $groupInfo["GroupInfo"][0]["AppDefinedData"];
  865. $roomInfo = [];
  866. if($roomInfoData) foreach($roomInfoData as $k => $v) {
  867. if($v["Key"] == "roomInfo") $roomInfo = $v["Value"];
  868. }
  869. $roomInfo = json_decode($roomInfo,true);
  870. // 更新管理员
  871. if(isset($roomInfo["managers"]) && !empty($roomInfo['managers'])) {
  872. foreach ($roomInfo['managers'] as $v){
  873. $this->setUpIMAdmin($v,$party_id,1);
  874. }
  875. }
  876. }
  877. $this->success("成功!");
  878. }
  879. /**
  880. * 获取用户在线更新
  881. */
  882. public function autoUserLine() {
  883. $random = rand(10000000,99999999);
  884. $usersig = $this->usersig("administrator");
  885. // 获取配置信息
  886. $config = config("tencent_im");
  887. $url = "https://console.tim.qq.com/v4/openim/query_online_status";
  888. $url .= "?sdkappid=".$config["sdkappid"];
  889. $url .= "&identifier=administrator";
  890. $url .= "&usersig=".$usersig;
  891. $url .= "&random=".$random;
  892. $url .= "&contenttype=json";
  893. $tencentObj = new tencentim($url);
  894. // 获取用户
  895. $where = [];
  896. $userData = model('User')->field('id')->where($where)->order('id asc')->select();
  897. $userArr = array_column($userData,'id');
  898. $data = [];
  899. $data["To_Account"] = $userArr;
  900. $result = [];
  901. if(!empty($data)) {
  902. $result = $tencentObj->toSend($data);
  903. if (isset($result['ActionStatus']) && $result['ActionStatus'] == 'OK') {
  904. if (isset($result['ErrorList'])) {//没有人员
  905. unset($result['ErrorList']);
  906. /*foreach ($result['ErrorList'] as $errKey => $errVal) {
  907. $userError[] = $errVal['To_Account'];
  908. }*/
  909. }
  910. if (isset($result['QueryResult'])) {
  911. $userOnline = $userOffline=[];
  912. foreach ($result['QueryResult'] as $key => $value) {
  913. if (in_array($value['Status'],['Online','PushOnline'])) {//在线(前台在线和后台在线)
  914. $userOnline[] = intval($value['To_Account']);
  915. } else {//离线
  916. $userOffline[] = intval($value['To_Account']);
  917. }
  918. }
  919. if (!empty($userOnline)) {//处理在线
  920. $onlineWhere['id'] = ['in',$userOnline];
  921. $onlineWhere['is_online'] = 0;
  922. model('User')->where($onlineWhere)->update(['is_online'=>1]);
  923. }
  924. if (!empty($userOffline)) {//处理离线
  925. $offlineWhere['id'] = ['in',$userOffline];
  926. $offlineWhere['is_online'] = 1;
  927. model('User')->where($offlineWhere)->update(['is_online'=>0]);
  928. }
  929. }
  930. }
  931. }
  932. $this->success('操作成功');
  933. }
  934. /**
  935. * 获取房间用户
  936. */
  937. public function getRoomUser() {
  938. $partyIds = $this->request->param('party_ids','');
  939. if (!empty($partyIds)) {
  940. $partyIds = explode(',',$partyIds);
  941. }
  942. $random = rand(10000000,99999999);
  943. $usersig = $this->usersig("administrator");
  944. // 获取配置信息
  945. $config = config("tencent_im");
  946. $url = "https://console.tim.qq.com/v4/group_open_avchatroom_http_svc/get_members";
  947. $url .= "?sdkappid=".$config["sdkappid"];
  948. $url .= "&identifier=administrator";
  949. $url .= "&usersig=".$usersig;
  950. $url .= "&random=".$random;
  951. $url .= "&contenttype=json";
  952. $tencentObj = new tencentim($url);
  953. //获取用户 ["57","62","63","105","106","107","108","109","116","119"]
  954. $partyArr = $partyIds;
  955. $memberList = [];
  956. if(!empty($partyArr)) {
  957. foreach ($partyArr as $key => $value) {
  958. $data["GroupId"] = $value;
  959. $result = $tencentObj->toSend($data);
  960. if (isset($result['ActionStatus']) && $result['ActionStatus'] == 'OK') {
  961. if (isset($result['MemberList']) && !empty($result['MemberList'])) {
  962. foreach ($result['MemberList'] as $ukey => $uval) {
  963. $memberList[$value]['member_list'][] = [
  964. 'avatar' => $uval['Avatar'],
  965. 'user_id'=> $uval['Member_Account'],
  966. 'nickname' => $uval['NickName'],
  967. ];
  968. }
  969. $memberList[$value]['online_num'] = count($memberList[$value]['member_list']);
  970. }
  971. }
  972. }
  973. }
  974. $result = $memberList;
  975. $this->success('操作成功',$result);
  976. }
  977. }