<?php
/**
 * 极光云通信
 * @Copyright (C) 2019 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Common\Vendor;
class JimIM {
	//应用ID
	public $appKey;
	public $masterSecret;
    private $base_url = 'https://api.im.jpush.cn/v1/';
    public $version=1;
	
	public function __construct($appKey='',$masterSecret=''){
        // $this->appKey =!empty($sdkappid)?$sdkappid: 'b589734caa5deb171986a5f3';
        // $this->masterSecret =!empty($identifier)?$identifier: 'dfde779642f70403455ee627';
        $this->appKey =!empty($sdkappid)?$sdkappid: getconfig('LIVE_JIGUANG_KEY');
        $this->masterSecret =!empty($identifier)?$identifier: getconfig('LIVE_JIGUANG_MASTER');
    }
    
    public function signature(){
        $param=array(
            'appkey'=>$this->appKey,
            'timestamp'=>NOW_TIME.'000',
            'random_str'=>randStr(32),
        );
        $param['signature']=strtoupper(md5(http_build_query($param).'&key='.$this->masterSecret));
        return $param; 
    }
    //注册    
    public function register($username, $password,$nickname){
        $body = [[
            'username' => $username,
            'password' => $password,
            'nickname'=>$nickname
        ]];
        $response= $this->batchRegister($body);
        if(empty($response[0]['error'])){
            $return =array('status'=>1);
        }else{
            $return =array('status'=>0,'info'=>$response[0]['error']['message'].'('.$response[0]['error']['code'].')');
        }return $return;
    }
    //批量注册    
    public function batchRegister(array $body) {
        $uri = $this->base_url.'users/';
        return $this->request($uri, $body,'POST');
    }
    //获取用户信息    
    public function show($username) {
        $uri = $this->base_url.'users/' . $username;
        return $this->request($uri);
    }
    /**
     * 更新用户信息
     * nickname 	（选填）用户昵称 	不支持的字符：英文字符： \n \r\n
        avatar 	（选填）头像 	需要填上从文件上传接口获得的 media_id
        birthday 	（选填）生日 	example: 1990-01-24 yyyy-MM-dd
        signature 	（选填）签名 	支持的字符：全部，包括 Emoji
        gender 	（选填） 性别 	0 - 未知， 1 - 男 ，2 - 女
        region 	（选填）地区 	支持的字符：全部，包括 Emoji
        address 	（选填）地址 	支持的字符：全部，包括 Emoji
     */
    public function update($username, array $body) {
        $uri = $this->base_url.'users/' . $username;
        return $this->request($uri, $body,'POST');
    }
    //查询用户在线状态
    public function stat($username) {
        $uri = $this->base_url.'users/' . $username . '/userstat';
        return $this->request($uri);
    }
    //修改密码
    public function updatePassword($username, $password) {
        $uri = $this->base_url.'users/' . $username . '/password';
        return $this->request($uri, [ 'new_password' => $password ],'POST');
    }
    
    //删除用户
    public function delete($username) {
        $uri = $this->base_url.'users/' . $username;
        $response = $this->request($uri,'','DELETE');
        return $response;
    }
    
    /**
     * 禁用用户
     *
     * @param string $username
     * @param bool $enabled
     * @return mixed
     */
    public function forbidden($username, $enabled) {
        if ($enabled) {
            $bool = 'true';
        } else {
            $bool = 'false';
        }
        $uri = $this->base_url.'users/' . $username . '/forbidden?disable=' . $bool;
        $response = $this->request($uri,'','PUT');
        return $response;
    }
    
    //管理员注册
    public function registerAdmin(array $admin) {
        $uri = $this->base_url.'admins/';
        $body = $admin;
        $response = $this->request($uri, $body,'POST');
        return $response;
    }
    //获取应用管理员列表
    public function listAllAdmin($count, $start = 0) {
        $uri = $this->base_url.'admins/';
        $query = [
            'start' => $start,
            'count' => $count
        ];
        $response = $this->request($uri, $query);
        return $response;
    }
    
    //发送文本消息
    /*   
    $from: 发送者信息数组
type 	是 	发送消息者身份 当前只限 admin 用户，必须先注册 admin 用户
id 	是 	发送者的用户名
    $target: 接受者信息数组
type 	是 	发送目标类型， 'single' - 个人，'group' - 群组, 'chatroom' - 聊天室
id 	是 	目标 id， 'single' 填 username 'group' 填 Group Id
    $msg: 消息体数组
text 	是 	消息内容
extras 	否 	接受一个自定义键值对数组
    */
    
    public function sendText(array $from, array $target, array $msg, array $notification = [], array $options = []) {
        $opts = array_merge([
            'msg_type' => 'text',
            'msg_body' => [
                'text' => $msg['text']
            ]
        ], $this->buildMessage($from, $target, $notification, $options));

        if (isset($msg['extras']) && is_array($msg['extras'])) {
            $opts['msg_body']['extras'] = $msg['extras'];
        }
        return $this->send($opts);
    }
    //发送图片消息
    public function sendImage(array $from, array $target, array $msg, array $notification = [], array $options = []) {
        $opts = array_merge([
            'msg_type' => 'image',
            'msg_body' => [
                'media_id'    => $msg['media_id'],
                'media_crc32' => $msg['media_crc32'],
                'width'       => $msg['width'],
                'height'      => $msg['height'],
                'format'      => $msg['format'],
                'fsize'       => $msg['fsize']
            ]
        ], $this->buildMessage($from, $target, $notification, $options));

        if (isset($msg['hash'])) {
            $opts['msg_body']['hash'] = $msg['hash'];
        }

        return $this->send($opts);
    }
    //发送语音消息
    public function sendVoice(array $from, array $target, array $msg, array $notification = [], array $options = []) {
        $opts = array_merge([
            'msg_type' => 'voice',
            'msg_body' => [
                'media_id'    => $msg['media_id'],
                'media_crc32' => $msg['media_crc32'],
                'duration'    => $msg['duration'],
                'hash'        => $msg['hash'],
                'fsize'       => $msg['fsize']
            ]
        ], $this->buildMessage($from, $target, $notification, $options));

        if (isset($msg['hash'])) {
            $opts['msg_body']['hash'] = $msg['hash'];
        }

        return $this->send($opts);
    }
    //发送自定义消息
    public function sendCustom(array $from, array $target, array $msg, array $notification = [], array $options = []) {
        $opts = array_merge([
            'msg_type' => 'custom',
            'msg_body' => $msg
        ], $this->buildMessage($from, $target, $notification, $options));

        return $this->send($opts);
    }
    //创建消息包体
    private function buildMessage(array $from, array $target, array $notification = [], array $options = []) {
        $opts = [
            'version'     => $this->version,
            'target_type' => $target['type'],
            'from_type'   => $from['type'],
            'target_id'   => $target['id'],
            'from_id'     => $from['id']
        ];
        if (isset($from['name'])) {
            $opts['from_name'] = $from['name'];
        }
        if (isset($target['name'])) {
            $opts['target_name'] = $target['name'];
        }
        if (isset($options['offline'])) {
            $opts['no_offline'] = !$options['offline'];
        }

        if (isset($options['target_appkey'])) {
            $opts['target_appkey'] = $options['target_appkey'];
        }

        if (isset($notification['notifiable'])){
            $opts['no_notification'] = !$notification['notifiable'];
        }
        if (isset($notification['title'])){
            $opts['notification']['title'] = $notification['title'];
        }
        if (isset($notification['alert'])){
            $opts['notification']['alert'] = $notification['alert'];
        }
        return $opts;
    }
    //发送消息
    public function send(array $options) {
        $uri =  $this->base_url.'messages/';
        $body = $options;
        $response = $this->request($uri, $body,'POST');
        return $response;
    }
    //消息撤回
    public function retract($msgid, $username) {
        $uri = $this->base_url.'messages/' . '/' . $username . '/' . $msgid . '/retract';
        $response = $this->request($uri,'','POST');
        return $response;
    }
    
    
    
    
    
        
    //获取用户聊天室列表
    public function chatrooms($username) {
        $uri = $this->base_url.'users/' . $username . '/chatroom';
        $response = $this->request($uri);
        return $response;
    }
    
    
    //获取当前应用的聊天室列表    
    public function listAllRoom($count, $start = 0) {
        $uri = $this->base_url.'chatroom/';
        $query = [
            'start' => $start,
            'count' => $count
        ];
        $response = $this->request($uri, $query);
        return $response;
    }
    //创建聊天室
    public function createRoom($name, $owner, array $members = [], $description = null ) {
        $uri = $this->base_url.'chatroom/';
        $body = [
            'name'              => $name,
            'owner_username'    => $owner
        ];
        if (!empty($members)) {
            $body['members_username'] = $members;
        }
        if (!is_null($description)) {
            $body['description'] = $description;
        }
        $response = $this->request($uri, $body,'POST');
        return $response;
    }
    //获取聊天室详情
    public function showRoom($roomId) {
        return $this->showBatch([$roomId]);
    }
    //获取多个聊天室详情
    public function showBatchRoom(array $roomIds) {
        $uri = $this->base_url.'chatroom/' . 'batch';
        $body = $roomIds;
        $response = $this->request($uri, $body,'POST');
        return $response;
    }
    //更新聊天室信息
    public function updateRoom($roomId, array $options) {
        $uri = $this->base_url.'chatroom/'. $roomId;
        $body = $options;
        $response = $this->request($uri, $body,'PUT');
        return $response;
    }
    //删除聊天室
    public function deleteRoom($roomId) {
        $uri = $this->base_url.'chatroom/' . $roomId;
        $response = $this->request($uri,'','DELETE');
        return $response;
    }
    //修改用户禁言状态
    public function forbiddenUserRoom($roomId, $user, $enabled) {
        $status = (bool)$enabled ? 1 : 0;
        $uri = $this->base_url.'chatroom/' . $roomId . '/forbidden/' . $user . '?status=' . $status;
        $response = $this->request($uri,'','PUT');
        return $response;
    }
    //获取聊天室成员列表
    public function membersRoom($roomId, $count, $start = 0) {
        $uri = $this->base_url.'chatroom/'. $roomId. '/members';
        $query = [
            'start' => $start,
            'count' => $count
        ];
        $response = $this->request($uri, $query);
        return $response;
    }
    //添加聊天室成员
    public function addMembersRoom($roomId, array $members) {
        $uri = $this->base_url.'chatroom/'. $roomId . '/members';
        $body = $members;
        $response = $this->request($uri, $body,'PUT');
        if(empty($response['error'])){
            $return =array('status'=>1);
        }else{
            $return =array('status'=>0,'info'=>$response['error']['message'].'('.$response['error']['code'].')');
        }
        return $return;
    }
    //移除聊天室成员
    public function removeMembersRoom($roomId, array $members) {
        $uri = $this->base_url.'chatroom/' . $roomId . '/members';
        $body = $members;
        $response = $this->request($uri, $body,'DELETE');
        return $response;
    }
    
    //获取敏感词列表
    public function listAllWord($count=10, $start = 1) {
        $uri = $this->base_url.'sensitiveword';
        $query = [
            'start' => $start,
            'count' => $count
        ];
        $response = $this->request($uri, $query,'GET');
        return $response;
    }
    //添加敏感词
    public function addWord(array $words) {
        $uri = $this->base_url.'sensitiveword';
        $body = $words;
        $response = $this->request($uri, $body,'POST');
        return $response;
    }
    //删除敏感词
    public function deleteWord($word) {
        $uri = $this->base_url.'sensitiveword';
        $body = ['word' => $word];
        $response = $this->request($uri, $body,'DELETE');
        return $response;
    }
    //修改敏感词
    public function updateWord($old, $new) {
        $uri = $this->base_url.'sensitiveword';
        $body = [
            'old_word' => $old,
            'new_word' => $new
        ];
        $response = $this->request($uri, $body,'PUT');
        return $response;
    }
    //获取敏感词功能状态
    public function getStatusWord() {
        $uri = $this->base_url.'sensitiveword' . '/status';

        $response = $this->request($uri);
        return $response;
    }
    //更新敏感词功能状态
    public function updateStatusWord($opened) {
        $uri = $this->base_url.'sensitiveword' . '/status?status=' . (int)$opened;

        $response = $this->request($uri,'','PUT');
        return $response;
    }
    //请求
    private function request($uri, array $body = [],$method='GET',  array $headers = []) {
        $default_headers = [
            'Content-Type: application/json',
            'Connection: Keep-Alive'
        ];
        $method = strtoupper($method);        
        if (!empty($body) && $method=='GET') {
            $uri = $uri . '?' . http_build_query($body);
        }        
        $ch = curl_init();
        $options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => true,
            CURLOPT_HTTPHEADER => (empty($headers) ? $default_headers : $headers),
            CURLOPT_USERAGENT => 'JMessage-Api-PHP-Client',
            CURLOPT_CONNECTTIMEOUT => 20,
            CURLOPT_TIMEOUT => 120,

            CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
            CURLOPT_USERPWD => $this->appKey . ':' . $this->masterSecret,

            CURLOPT_URL => $uri,
            CURLOPT_CUSTOMREQUEST => ('UPLOAD' == $method) ? 'POST' : $method
        );
        $options[CURLOPT_SSL_VERIFYPEER] = false;
        $options[CURLOPT_SSL_VERIFYHOST] = 0;

        if (!empty($body)) {
            if ('UPLOAD' == $method) {
                /*if (class_exists('\CURLFile')) {
                    $options[CURLOPT_SAFE_UPLOAD] = true;
                    $options[CURLOPT_POSTFIELDS] = ['filename' => new \CURLFile($body['path'])];
                } else {
                    if (defined('CURLOPT_SAFE_UPLOAD')) {
                        $options[CURLOPT_SAFE_UPLOAD] = false;
                    }
                    $options[CURLOPT_POSTFIELDS] = ['filename' => '@' . $body['path']];
                }*/
            } else {
                $options[CURLOPT_POSTFIELDS] = json_encode($body);
            }
        }

        curl_setopt_array($ch, $options);
        $output = curl_exec($ch);

        if($output === false) {
            return "Error Code:" . curl_errno($ch) . ", Error Message:".curl_error($ch);
        } else {
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
            $header_text = substr($output, 0, $header_size);
            $body = substr($output, $header_size);
            $headers = array();
            foreach (explode("\r\n", $header_text) as $i => $line) {
                if (!empty($line)) {
                    if ($i === 0) {
                        $headers[0] = $line;
                    } else if (strpos($line, ": ")) {
                        list ($key, $value) = explode(': ', $line);
                        $headers[$key] = $value;
                    }
                }
            }
            //$response['headers'] = $headers;
            $response['body'] = json_decode($body, true);
            $response['http_code'] = $httpCode;
        }
        curl_close($ch);
        return $response['body']?$response['body']:$response;
    }
}
?>