環信即時通訊——整合客戶端

hkzj0571發表於2017-11-13

最近公司在開發一款APP,需要使用環信即時通訊來做及時聊天和直播,找了好多官方的REST API發現並沒有把直播整合服務寫完,於是自己完善了一下,與大家分享O(∩_∩)O
話不多說上程式碼

namespace yournamespace

class Easemob{
    private $client_id;
    private $client_secret;
    private $org_name;
    private $app_name;
    private $url;
//------------------------------------------------------使用者體系    
        /**
     * 初始化引數
     *
     * @param array $options   
     * @param $options['client_id']     
     * @param $options['client_secret'] 
     * @param $options['org_name']      
     * @param $options['app_name']          
     */
    public function __construct($options) {
        $this->client_id = 'XXXXXXXXXXXXXX';
        $this->client_secret =  'XXXXXXXXXXXXXX';
        $this->org_name = 'XXXXXXXXXXXXXX';
        $this->app_name =  'XXXXXXXXXXXXXX';
        if (! empty ( $this->org_name ) && ! empty ( $this->app_name )) {
            $this->url = 'https://a1.easemob.com/' . $this->org_name . '/' . $this->app_name . '/';
        }
    }   
    /**
    *獲取token 
    */
    function getToken()
    {
        $options=array(
        "grant_type"=>"client_credentials",
        "client_id"=>$this->client_id,
        "client_secret"=>$this->client_secret
        );
        //json_encode()函式,可將PHP陣列或物件轉成json字串,使用json_decode()函式,可以將json字串轉換為PHP陣列或物件
        $body=json_encode($options);
        //使用 $GLOBALS 替代 global
        $url=$this->url.'token';
        //$url=$base_url.'token';
        $tokenResult = $this->postCurl($url,$body,$header=array());
        //var_dump($tokenResult['expires_in']);
        //return $tokenResult;
        return "Authorization:Bearer ".$tokenResult['access_token'];

    }
    /**
      授權註冊
    */
    function createUser($username,$password){
        $url=$this->url.'users';
        $options=array(
            "username"=>$username,
            "password"=>$password
        );
        $body=json_encode($options);
        $header=array($this->getToken());
        $result=$this->postCurl($url,$body,$header);
        return $result;
    }
    /*
        批次註冊使用者
    */
    function createUsers($options){
        $url=$this->url.'users';

        $body=json_encode($options);
        $header=array($this->getToken());
        $result=$this->postCurl($url,$body,$header);
        return $result;
    }
    /*
        重置使用者密碼
    */
    function resetPassword($username,$newpassword){
        $url=$this->url.'users/'.$username.'/password';
        $options=array(
            "newpassword"=>$newpassword
        );
        $body=json_encode($options);
        $header=array($this->getToken());
        $result=$this->postCurl($url,$body,$header,"PUT");
        return $result;
    }

    /*
        獲取單個使用者
    */
    function getUser($username){
        $url=$this->url.'users/'.$username;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,"GET");
        return $result;
    }
    /*
        獲取批次使用者----不分頁
    */
    function getUsers($limit=0){
        if(!empty($limit)){
            $url=$this->url.'users?limit='.$limit;
        }else{
            $url=$this->url.'users';
        }
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,"GET");
        return $result;
    }
    /*
        獲取批次使用者---分頁
    */
    function getUsersForPage($limit=0,$cursor=''){
        $url=$this->url.'users?limit='.$limit.'&cursor='.$cursor;

        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,"GET");
        if(!empty($result["cursor"])){
            $cursor=$result["cursor"];
            $this->writeCursor("userfile.txt",$cursor);
        }
        //var_dump($GLOBALS['cursor'].'00000000000000');
        return $result;
    }

    //建立資料夾
    function mkdirs($dir, $mode = 0777)
     {
         if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
         if (!mkdirs(dirname($dir), $mode)) return FALSE;
         return @mkdir($dir, $mode);
     } 
     //寫入cursor
    function writeCursor($filename,$content){
        //判斷資料夾是否存在,不存在的話建立
        if(!file_exists("resource/txtfile")){
            mkdirs("resource/txtfile");
        }
        $myfile=@fopen("resource/txtfile/".$filename,"w+") or die("Unable to open file!");
        @fwrite($myfile,$content);
        fclose($myfile);    
    }
     //讀取cursor
    function readCursor($filename){
        //判斷資料夾是否存在,不存在的話建立
        if(!file_exists("resource/txtfile")){
            mkdirs("resource/txtfile");
        }
        $file="resource/txtfile/".$filename;
        $fp=fopen($file,"a+");//這裡這設定成a+
        if($fp){
            while(!feof($fp)){
                //第二個引數為讀取的長度
                $data=fread($fp,1000);  
            }   
            fclose($fp);
        }    
        return $data;   
    }
    /*
        刪除單個使用者
    */
    function deleteUser($username){
        $url=$this->url.'users/'.$username;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'DELETE');
        return $result;
    }
    /*
        刪除批次使用者
        limit:建議在100-500之間,、
        注:具體刪除哪些並沒有指定, 可以在返回值中檢視。
    */
    function deleteUsers($limit){
        $url=$this->url.'users?limit='.$limit;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'DELETE');
        return $result;

    }
    /*
        修改使用者暱稱
    */
    function editNickname($username,$nickname){
        $url=$this->url.'users/'.$username;
        $options=array(
            "nickname"=>$nickname
        );
        $body=json_encode($options);
        $header=array($this->getToken());
        $result=$this->postCurl($url,$body,$header,'PUT');
        return $result;
    }
    /*
        新增好友-
    */
    function addFriend($username,$friend_name){
        $url=$this->url.'users/'.$username.'/contacts/users/'.$friend_name;
        $header=array($this->getToken(),'Content-Type:application/json');
        $result=$this->postCurl($url,'',$header,'POST');
        return $result; 

    }

    /*
        刪除好友
    */
    function deleteFriend($username,$friend_name){
        $url=$this->url.'users/'.$username.'/contacts/users/'.$friend_name;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'DELETE');
        return $result; 

    }
    /*
        檢視好友
    */
    function showFriends($username){
        $url=$this->url.'users/'.$username.'/contacts/users';
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        return $result; 
    }
    /*
        檢視使用者黑名單
    */
    function getBlacklist($username){
        $url=$this->url.'users/'.$username.'/blocks/users';
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        return $result;

    }
    /*
        往黑名單中加人
    */
    function addUserForBlacklist($username,$usernames){
        $url=$this->url.'users/'.$username.'/blocks/users';
        $body=json_encode($usernames);
        $header=array($this->getToken());
        $result=$this->postCurl($url,$body,$header,'POST');
        return $result; 

    }
    /*
        從黑名單中減人
    */
    function deleteUserFromBlacklist($username,$blocked_name){
        $url=$this->url.'users/'.$username.'/blocks/users/'.$blocked_name;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'DELETE');
        return $result; 

    }
     /*
        檢視使用者是否線上
     */
    function isOnline($username){
        $url=$this->url.'users/'.$username.'/status';
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        return $result; 

    }
    /*
        檢視使用者離線訊息數
    */
    function getOfflineMessages($username){
        $url=$this->url.'users/'.$username.'/offline_msg_count';
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        return $result; 

    }
    /*
        檢視某條訊息的離線狀態
        ----deliverd 表示此使用者的該條離線訊息已經收到
    */
    function getOfflineMessageStatus($username,$msg_id){
        $url=$this->url.'users/'.$username.'/offline_msg_status/'.$msg_id;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        return $result; 

    }
    /*
        禁用使用者賬號
    */ 
    function deactiveUser($username){
        $url=$this->url.'users/'.$username.'/deactivate';
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header);
        return $result;
    }
    /*
        解禁使用者賬號
    */ 
    function activeUser($username){
        $url=$this->url.'users/'.$username.'/activate';
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header);
        return $result;
    } 

    /*
        強制使用者下線
    */ 
    function disconnectUser($username){
        $url=$this->url.'users/'.$username.'/disconnect';
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        return $result;
    }
    //--------------------------------------------------------上傳下載
    /*
        上傳圖片或檔案
    */
    function uploadFile($filePath){
        $url=$this->url.'chatfiles';
        $file=file_get_contents($filePath);
        $body['file']=$file;
        $header=array('enctype:multipart/form-data',$this->getToken(),"restrict-access:true");
        $result=$this->postCurl($url,$body,$header,'XXX');
        return $result;

    }
    /*
        下載檔案或圖片
    */
    function downloadFile($uuid,$shareSecret){
        $url=$this->url.'chatfiles/'.$uuid;
        $header = array("share-secret:".$shareSecret,"Accept:application/octet-stream",$this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        $filename = md5(time().mt_rand(10, 99)).".png"; //新圖片名稱
        if(!file_exists("resource/down")){
            //mkdir("../image/down");
            mkdirs("resource/down/");
        }

        $file = @fopen("resource/down/".$filename,"w+");//開啟檔案準備寫入
        @fwrite($file,$result);//寫入
        fclose($file);//關閉
        return $filename;

    }
    /*
        下載圖片縮圖
    */
    function downloadThumbnail($uuid,$shareSecret){
        $url=$this->url.'chatfiles/'.$uuid;
        $header = array("share-secret:".$shareSecret,"Accept:application/octet-stream",$this->getToken(),"thumbnail:true");
        $result=$this->postCurl($url,'',$header,'GET');
        $filename = md5(time().mt_rand(10, 99))."th.png"; //新圖片名稱
        if(!file_exists("resource/down")){
            //mkdir("../image/down");
            mkdirs("resource/down/");
        }

        $file = @fopen("resource/down/".$filename,"w+");//開啟檔案準備寫入
        @fwrite($file,$result);//寫入
        fclose($file);//關閉
        return $filename;
    }
    //-------------------------------------------------------------直播間操作
    /*
        設定直播流地址
    */
    function set_tream_url($pc_pull,$mobile_push,$mobile_pull,$pc_push){
        $url=$this->url.'liverooms/stream_url';
        $options=array(
             "pc_pull"=>$pc_pull,
             "pc_push"=>$pc_push,
             "mobile_push"=>$mobile_push,
             "mobile_pull"=>$mobile_pull,
         );
        $b=json_encode($options);
        $header=array($this->getToken());
        $result=$this->postCurl($url,$b,$header);
        return $result;
    }

    /*
        獲取某端直播流地址
    */
     function getpull($types){
         $url=$this->url.'liverooms/stream_url?type='.$types;
         $header=array($this->getToken());
         $result=$this->postCurl($url,'',$header,"GET");
         return $result;
     }

    /*
        給使用者賦予主播身份
    */
    function addsuperadmin($admin){
         $url=$this->url.'chatrooms/super_admin';
         $options=array(
             "superadmin"=>$admin
         );
         $body=json_encode($options);
         $header=array($this->getToken());
         $result=$this->postCurl($url,$body,$header);
         return $result;
     }

     /*
        建立直播聊天室
    */
    function addliveroom($liveroom_name,$desc,$superadmin){
         $url=$this->url.'chatdemoui/liverooms';
         $options=array(
             "title"=>$liveroom_name,
             "desc"=>$desc,
             "anchor"=>$superadmin,
         );
         $body=json_encode($options);
         $header=array($this->getToken());
         $result=$this->postCurl($url,$body,$header);
         return $result;
     }

    //--------------------------------------------------------傳送訊息
    /*
        傳送文字訊息
    */
    function sendText($from="admin",$target_type,$target,$content,$ext){
        $url=$this->url.'messages';
        $body['target_type']=$target_type;
        $body['target']=$target;
        $options['type']="txt";
        $options['msg']=$content;
        $body['msg']=$options;
        $body['from']=$from;
        $body['ext']=$ext;
        $b=json_encode($body);
        $header=array($this->getToken());
        $result=$this->postCurl($url,$b,$header);
        return $result;
    }
    /*
        傳送透傳訊息
    */
    function sendCmd($from="admin",$target_type,$target,$action,$ext){
        $url=$this->url.'messages';
        $body['target_type']=$target_type;
        $body['target']=$target;
        $options['type']="cmd";
        $options['action']=$action;
        $body['msg']=$options;
        $body['from']=$from;
        $body['ext']=$ext;
        $b=json_encode($body);
        $header=array($this->getToken());   
        //$b=json_encode($body,true);
        $result=$this->postCurl($url,$b,$header);
        return $result;
    }
    /*
        發圖片訊息
    */ 
    function sendImage($filePath,$from="admin",$target_type,$target,$filename,$ext){
        $result=$this->uploadFile($filePath);
        $uri=$result['uri'];
        $uuid=$result['entities'][0]['uuid'];
        $shareSecret=$result['entities'][0]['share-secret'];
        $url=$this->url.'messages';
        $body['target_type']=$target_type;
        $body['target']=$target;
        $options['type']="img";
        $options['url']=$uri.'/'.$uuid;
        $options['filename']=$filename;
        $options['secret']=$shareSecret;
        $options['size']=array(
            "width"=>480,
            "height"=>720
        );
        $body['msg']=$options;
        $body['from']=$from;
        $body['ext']=$ext;
        $b=json_encode($body);
        $header=array($this->getToken());   
        //$b=json_encode($body,true);
        $result=$this->postCurl($url,$b,$header);
        return $result;
    }
    /*
        發語音訊息
    */
    function sendAudio($filePath,$from="admin",$target_type,$target,$filename,$length,$ext){
        $result=$this->uploadFile($filePath);
        $uri=$result['uri'];
        $uuid=$result['entities'][0]['uuid'];
        $shareSecret=$result['entities'][0]['share-secret'];
        $url=$this->url.'messages';
        $body['target_type']=$target_type;
        $body['target']=$target;
        $options['type']="audio";
        $options['url']=$uri.'/'.$uuid;
        $options['filename']=$filename;
        $options['length']=$length;
        $options['secret']=$shareSecret;
        $body['msg']=$options;
        $body['from']=$from;
        $body['ext']=$ext;
        $b=json_encode($body);
        $header=array($this->getToken());   
        //$b=json_encode($body,true);
        $result=$this->postCurl($url,$b,$header);
        return $result;}
    /*
        發影片訊息
    */
    function sendVedio($filePath,$from="admin",$target_type,$target,$filename,$length,$thumb,$thumb_secret,$ext){
    $result=$this->uploadFile($filePath);
        $uri=$result['uri'];
        $uuid=$result['entities'][0]['uuid'];
        $shareSecret=$result['entities'][0]['share-secret'];
        $url=$this->url.'messages';
        $body['target_type']=$target_type;
        $body['target']=$target;
        $options['type']="video";
        $options['url']=$uri.'/'.$uuid;
        $options['filename']=$filename;
        $options['thumb']=$thumb;
        $options['length']=$length;
        $options['secret']=$shareSecret;
        $options['thumb_secret']=$thumb_secret;
        $body['msg']=$options;
        $body['from']=$from;
        $body['ext']=$ext;
        $b=json_encode($body);
        $header=array($this->getToken());   
        //$b=json_encode($body,true);
        $result=$this->postCurl($url,$b,$header);
        return $result;
    }
    /*
    發檔案訊息
    */
    function sendFile($filePath,$from="admin",$target_type,$target,$filename,$length,$ext){
        $result=$this->uploadFile($filePath);
        $uri=$result['uri'];
        $uuid=$result['entities'][0]['uuid'];
        $shareSecret=$result['entities'][0]['share-secret'];
        $url=$GLOBALS['base_url'].'messages';
        $body['target_type']=$target_type;
        $body['target']=$target;
        $options['type']="file";
        $options['url']=$uri.'/'.$uuid;
        $options['filename']=$filename;
        $options['length']=$length;
        $options['secret']=$shareSecret;
        $body['msg']=$options;
        $body['from']=$from;
        $body['ext']=$ext;
        $b=json_encode($body);
        $header=array(getToken());  
        //$b=json_encode($body,true);
        $result=postCurl($url,$b,$header);
        return $result;
    }
    //-------------------------------------------------------------群組操作

    /*
        獲取app中的所有群組----不分頁
    */
    function getGroups($limit=0){
        if(!empty($limit)){
            $url=$this->url.'chatgroups?limit='.$limit;
        }else{
            $url=$this->url.'chatgroups';
        }

        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,"GET");
        return $result;
    }
    /*
        獲取app中的所有群組---分頁
    */
    function getGroupsForPage($limit=0,$cursor=''){
        $url=$this->url.'chatgroups?limit='.$limit.'&cursor='.$cursor;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,"GET");

        if(!empty($result["cursor"])){
            $cursor=$result["cursor"];
            $this->writeCursor("groupfile.txt",$cursor);
        }
        //var_dump($GLOBALS['cursor'].'00000000000000');
        return $result;
    }
    /*
        獲取一個或多個群組的詳情
    */
    function getGroupDetail($group_ids){
        $g_ids=implode(',',$group_ids);
        $url=$this->url.'chatgroups/'.$g_ids;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        return $result;
    }
    /*
        建立一個群組
    */
    function createGroup($options){
        $url=$this->url.'chatgroups';
        $header=array($this->getToken());
        $body=json_encode($options);
        $result=$this->postCurl($url,$body,$header);
        return $result;
    }
    /*
        修改群組資訊
    */
    function modifyGroupInfo($group_id,$options){
        $url=$this->url.'chatgroups/'.$group_id;
        $body=json_encode($options);
        $header=array($this->getToken());
        $result=$this->postCurl($url,$body,$header,'PUT');
        return $result; 
    }
    /*
        刪除群組
    */
    function deleteGroup($group_id){
        $url=$this->url.'chatgroups/'.$group_id;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'DELETE');
        return $result;
    }
    /*
        獲取群組中的成員
    */
    function getGroupUsers($group_id){
        $url=$this->url.'chatgroups/'.$group_id.'/users';   
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        return $result;
    }
    /*
        群組單個加人
    */
    function addGroupMember($group_id,$username){
        $url=$this->url.'chatgroups/'.$group_id.'/users/'.$username;
        $header=array($this->getToken(),'Content-Type:application/json');
        $result=$this->postCurl($url,'',$header);
        return $result;
    }
    /*
        群組批次加人
    */
    function addGroupMembers($group_id,$usernames){
        $url=$this->url.'chatgroups/'.$group_id.'/users';
        $body=json_encode($usernames);
        $header=array($this->getToken(),'Content-Type:application/json');
        $result=$this->postCurl($url,$body,$header);
        return $result;
    }
    /*
        群組單個減人
    */
    function deleteGroupMember($group_id,$username){
        $url=$this->url.'chatgroups/'.$group_id.'/users/'.$username;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'DELETE');
        return $result;
    }
    /*
        群組批次減人
    */
    function deleteGroupMembers($group_id,$usernames){
        $url=$this->url.'chatgroups/'.$group_id.'/users/'.$usernames;
        //$body=json_encode($usernames);
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'DELETE');
        return $result;
    }
    /*
        獲取一個使用者參與的所有群組
    */
    function getGroupsForUser($username){
        $url=$this->url.'users/'.$username.'/joined_chatgroups';
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        return $result;
    }
    /*
        群組轉讓
    */
    function changeGroupOwner($group_id,$options){
        $url=$this->url.'chatgroups/'.$group_id;
        $body=json_encode($options);
        $header=array($this->getToken());
        $result=$this->postCurl($url,$body,$header,'PUT');
        return $result;
    }
    /*
        查詢一個群組黑名單使用者名稱列表
    */
    function getGroupBlackList($group_id){
        $url=$this->url.'chatgroups/'.$group_id.'/blocks/users';
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        return $result;
    }
    /*
        群組黑名單單個加人
    */
    function addGroupBlackMember($group_id,$username){
        $url=$this->url.'chatgroups/'.$group_id.'/blocks/users/'.$username;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header);
        return $result;
    }
    /*
        群組黑名單批次加人
    */
    function addGroupBlackMembers($group_id,$usernames){
        $url=$this->url.'chatgroups/'.$group_id.'/blocks/users';
        $body=json_encode($usernames);
        $header=array($this->getToken());
        $result=$this->postCurl($url,$body,$header);
        return $result;
    }
    /*
        群組黑名單單個減人
    */
    function deleteGroupBlackMember($group_id,$username){
        $url=$this->url.'chatgroups/'.$group_id.'/blocks/users/'.$username;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'DELETE');
        return $result;
    }
    /*
        群組黑名單批次減人
    */
    function deleteGroupBlackMembers($group_id,$usernames){
        $url=$this->url.'chatgroups/'.$group_id.'/blocks/users';
        $body=json_encode($usernames);
        $header=array($this->getToken());
        $result=$this->postCurl($url,$body,$header,'DELETE');
        return $result;
    }
    //-------------------------------------------------------------聊天室操作
    /*
        建立聊天室
    */
    function createChatRoom($options){
        $url=$this->url.'chatrooms';
        $header=array($this->getToken());
        $body=json_encode($options);
        $result=$this->postCurl($url,$body,$header);
        return $result;
    }
    /*
        修改聊天室資訊
    */
    function modifyChatRoom($chatroom_id,$options){
        $url=$this->url.'chatrooms/'.$chatroom_id;
        $body=json_encode($options);
        $result=$this->postCurl($url,$body,$header,'PUT');
        return $result; 
    }
    /*
        刪除聊天室
    */
    function deleteChatRoom($chatroom_id){
        $url=$this->url.'chatrooms/'.$chatroom_id;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'DELETE');
        return $result;
    }
    /*
        獲取app中所有的聊天室
    */
    function getChatRooms(){
        $url=$this->url.'chatrooms';
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,"GET");
        return $result;
    }

    /*
        獲取一個聊天室的詳情
    */
    function getChatRoomDetail($chatroom_id){
        $url=$this->url.'chatrooms/'.$chatroom_id;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        return $result;
    }
    /*
        獲取一個使用者加入的所有聊天室
    */
    function getChatRoomJoined($username){
        $url=$this->url.'users/'.$username.'/joined_chatrooms';
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'GET');
        return $result;
    }
    /*
        聊天室單個成員新增
    */
    function addChatRoomMember($chatroom_id,$username){
        $url=$this->url.'chatrooms/'.$chatroom_id.'/users/'.$username;
        //$header=array($this->getToken());
        $header=array($this->getToken(),'Content-Type:application/json');
        $result=$this->postCurl($url,'',$header);
        return $result;
    }
    /*
        聊天室批次成員新增
    */
    function addChatRoomMembers($chatroom_id,$usernames){
        $url=$this->url.'chatrooms/'.$chatroom_id.'/users';
        $body=json_encode($usernames);
        $header=array($this->getToken());
        $result=$this->postCurl($url,$body,$header);
        return $result;
    }
    /*
        聊天室單個成員刪除
    */
    function deleteChatRoomMember($chatroom_id,$username){
        $url=$this->url.'chatrooms/'.$chatroom_id.'/users/'.$username;
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'DELETE');
        return $result;
    }
    /*
        聊天室批次成員刪除
    */
    function deleteChatRoomMembers($chatroom_id,$usernames){
        $url=$this->url.'chatrooms/'.$chatroom_id.'/users/'.$usernames;
        //$body=json_encode($usernames);
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,'DELETE');
        return $result;
    }
    //-------------------------------------------------------------聊天記錄

    /*
        匯出聊天記錄----不分頁
    */
    function getChatRecord($ql){
        if(!empty($ql)){
            $url=$this->url.'chatmessages?ql='.$ql;
        }else{
            $url=$this->url.'chatmessages';
        }
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,"GET");
        return $result;
    }
    /*
        匯出聊天記錄---分頁
    */
    function getChatRecordForPage($ql,$limit=0,$cursor){
        if(!empty($ql)){
            $url=$this->url.'chatmessages?ql='.$ql.'&limit='.$limit.'&cursor='.$cursor;
        }
        $header=array($this->getToken());
        $result=$this->postCurl($url,'',$header,"GET");
        $cursor=$result["cursor"];
        $this->writeCursor("chatfile.txt",$cursor);
        //var_dump($GLOBALS['cursor'].'00000000000000');
        return $result;
    }

    /**
     *$this->postCurl方法
     */
    function postCurl($url,$body,$header,$type="POST"){
        //1.建立一個curl資源
        $ch = curl_init();
        //2.設定URL和相應的選項
        curl_setopt($ch,CURLOPT_URL,$url);//設定url
        //1)設定請求頭
        //array_push($header, 'Accept:application/json');
        //array_push($header,'Content-Type:application/json');
        //array_push($header, 'http:multipart/form-data');
        //設定為false,只會獲得響應的正文(true的話會連響應頭一併獲取到)
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt ( $ch, CURLOPT_TIMEOUT,5); // 設定超時限制防止死迴圈
        //設定發起連線前的等待時間,如果設定為0,則無限等待。
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
        //將curl_exec()獲取的資訊以檔案流的形式返回,而不是直接輸出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //2)裝置請求體
        if (count($body)>0) {
            //$b=json_encode($body,true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);//全部資料使用HTTP協議中的"POST"操作來傳送。
        }
        //設定請求頭
        if(count($header)>0){
            curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        }
        //上傳檔案相關設定
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 對認證證照來源的檢查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);// 從證照中檢查SSL加密算

        //3)設定提交方式
        switch($type){
            case "GET":
                curl_setopt($ch,CURLOPT_HTTPGET,true);
                break;
            case "POST":
                curl_setopt($ch,CURLOPT_POST,true);
                break;
            case "PUT"://使用一個自定義的請求資訊來代替"GET"或"HEAD"作為HTTP請                                                      求。這對於執行"DELETE" 或者其他更隱蔽的HTT
                curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"PUT");
                break;
            case "DELETE":
                curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"DELETE");
                break;
        }

        //4)在HTTP請求中包含一個"User-Agent: "頭的字串。-----必設

        curl_setopt($ch, CURLOPT_USERAGENT, 'SSTS Browser/1.0');
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip');

        curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)' ); // 模擬使用者使用的瀏覽器
        //5)

        //3.抓取URL並把它傳遞給瀏覽器
        $res=curl_exec($ch);

        $result=json_decode($res,true);
        //4.關閉curl資源,並且釋放系統資源
        curl_close($ch);
        if(empty($result))
            return $res;
        else
            return $result;

    }
}

將這個class儲存到專案路徑中,在controlleruse引入
For example :


public function registerImuser($username,$password,$nickname){
        $e = new Easemob();
        $result_u = $e->createUser($username,$password);
        $result_n = $e->editNickname($username,$nickname);
        return $result_n;
    }

使用:

$this->registerImuser($post_name,$post_password,$post_nickname);

注意建立直播的流程 給使用者新增主播身份,設定直播流,建立直播間(建立直播間的同時環信會自動為我們建立直播間對應的聊天室)
Thinks!

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章