环信聊天记录的完整代码

按照文档自己封装的,水平有限仅供参考

class Easemob
{
    protected $client_id;//app的id
    protected $client_secret;//app的秘钥
    protected $org_name; //企业id
    protected $app_name; //应用名称
    protected $app_key;//路径
    protected $url;//应用标识
    public function __construct(){
        $this->client_id = '';            				
        $this->client_secret = '';  					
        $this->org_name = '';                      		
        $this->app_name = '';                     		
        $this->url ='https://a1.easemob.com/';  		
        $this->app_key = '';                    			
    }

    public function getToken()
    {
        $file = '../storage/accesstoken';
        //如果本地文件保存了token 则读取本地文件
        if( file_exists($file) ){
            $content = file_get_contents($file);
            $content = json_decode($content);
            if( time()-filemtime($file) < $content->expires_in ){
                return $content->access_token;
            }
        }
        //请求token的地址
        $path=$this->url.$this->org_name.'/'.$this->app_name.'/token';
        //curl请求参数data
        $options=array(
            "grant_type"=>"client_credentials",
            "client_id"=>$this->client_id,
            "client_secret"=>$this->client_secret
        );
        $body=json_encode($options);
        $header = array(
            'Content-Type:application/json',
            'Content-Length:'.strlen($body)
        );
        //curl请求
        $content = $this->_request($path,$body,$header);
        //由于token不能频繁请求,所以放在本地
        file_put_contents($file,$content);
        $content = json_decode($content);
        return $content->access_token;
    }
    
    //根据时间返回下载地址
    public function getChat($time){
        //请求url
        $path=$this->url.$this->org_name.'/'.$this->app_name.'/chatmessages/'.$time;
        $header=array("Content-Type”:”application/json","Authorization:Bearer ".$this->getToken());
        $result=$this->_request($path,'',$header);
        return json_decode($result,true);
    }
    
    //下载内容,此类直接调用此方法
    public function downContent($time){
        $path = '../storage/chatrescore/';//设置根路径
        $sub_dir = substr($time,0,8);//截取时间的天如20180822作为文件夹
        //如果本地存贮了聊天文件,由于访问限制,每个文件都是一小时的聊天记录
        $find_file = realpath($path).'/'.$sub_dir.'/'.$time;
        if(file_exists($find_file)){
            $txt = file_get_contents($find_file);
            if(empty(trim($txt))) return '该时段暂无数据3';
            //这段代码是直接返回 然后入数据表
             $aa = explode("\n",trim($txt));
            foreach($aa as $key => $val){
                $info[$key] = json_decode($val,true);
            }
            return $info;
        }
        
        $result = $this->getChat($time); //调用下载方法,返回的是文件下载URL
        if(isset($result['error'])) return '该时段暂无数据1';
        if(!isset($result['data'][0]['url'])) return '该时段暂无数据2';
        //请求httpcopy方法,返回下载好的压缩文件
        $downData = $this->httpcopy($result['data'][0]['url'],$path);
        if($downData == 'fail') return '下载失败';
        //解压缩后返回文件路径
        $ungz = $this->unzipGz($downData);
        //return $ungz;//www/wwwroot/PHP/storage/chatrescore/20180820/2018082014
        if($ungz == 'fail') return '解压失败';
        if(!file_exists($ungz)) return '文件不存在';
        $txt = file_get_contents($ungz);
        if(empty(trim($txt))) return '该时段暂无数据3';
        $aa = explode("\n",trim($txt));
        foreach($aa as $key => $val){
            $info[$key] = json_decode($val,true);
        }
       return $info;
    }
    
     //下载远程文件
    public function httpcopy($url,$path, $files="", $timeout=60) {
        $file_a = empty($files) ? pathinfo($url,PATHINFO_BASENAME) : $files;
        //分割
        $file = explode('?',$file_a)[0];
        $sub_dir = substr($file,0,8);
        $dir = realpath($path).'/'.$sub_dir;

        if(!is_dir($dir)){
            @mkdir($dir,0755,true);
        }
        $url = str_replace(" ","%20",$url);
        $temp = file_get_contents($url);
        if(@file_put_contents($dir.'/'.$file, $temp)) {
            return $dir.'/'.$file;
        } else {
            return 'fail';
        }
    }
    
     //解压gz压缩包
    public function unzipGz($gz_file){
        $buffer_size = 1000000; //限定大小
        $out_file_name = str_replace('.gz', '', $gz_file);
        $file = gzopen($gz_file, 'rb');
        $out_file = fopen($out_file_name, 'wb');
        $str='';
        if(!gzeof($file)) {
            fwrite($out_file, gzread($file, $buffer_size));
            fclose($out_file);
            gzclose($file);
            return $out_file_name;
        } else {
            return 'fail';
        }
    }
	//下载图片视频地址
    public function downImgAudio($url,$secret,$time,$msg_id,$type,$is_thumb=true)
    {
        $path = './uploads/chats';
        $dir = realpath($path).'/'.substr($time,0,8);
        if(!is_dir($dir)){
            @mkdir($dir,0755,true);
        }
        $imgAudioFile = $dir.'/'.$msg_id.'.'.$type;
        //如果存在则返回文件路径
        if(file_exists($imgAudioFile)){
            return '/uploads/chats/'.substr($time,0,8).'/'.$msg_id.'.'.$type;
        }
        $header = [
            'share-secret'=>$secret,
            "Authorization:Bearer ".$this->getToken(),
            'Accept'=>'application/octet-stream',
            'thumbnail'=> 'true',
        ];
        $result=$this->_request($url,'',$header);
        file_put_contents($imgAudioFile,$result);
        return '/uploads/chats/'.substr($time,0,8).'/'.$msg_id.'.'.$type;
    }

    public function _request($url, $postData, $header)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        // 将curl_exec()获取的数据以字符串返回,而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //设置为false,只会获得响应的正文(true的话会连响应头一并获取到)
        curl_setopt($ch,CURLOPT_HEADER,0);
        //设置发起连接前的等待时间,如果设置为0,则无限等待,防止死循环。
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
        if(!empty($postData)){
            //设置请求方式为post
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        }
        //curl注意事项,如果发送的请求是https,必须要禁止服务器端校检SSL证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        //设置发送的数据是json数据
        /*if($isJson){
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type:application/json',
                'Content-Length:'.strlen($postData)
            ));
        }*/
        //设置请求头
        if(count($header)>0){
            curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        }
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}

猜你喜欢

转载自blog.csdn.net/yt_php/article/details/83542274