package com.lyms.talkonlineweb.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.IOUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.client.RestTemplate;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.zip.GZIPInputStream;
import static org.apache.commons.io.FilenameUtils.getExtension;
/**
* 环信相关API
*/
@Component
@Log4j2
public class HXService {
@Value("${hx.APPKEY}")
private String appKey;
@Value("${hx.ClientID}")
private String clientId;
@Value("${hx.ClientSecret}")
private String clientSecret;
@Value("${hx.org_name}")
private String orgName;
@Value("${hx.app_name}")
private String appName;
@Autowired
private RestTemplate restTemplate;
private ResponseEntity<String> resp;
// @Autowired
// private RestTemplate restTemplate;
// @Bean
// public EMService getEMService(){
// EMProperties properties = EMProperties.builder()
// .setAppkey(appKey)
// .setClientId(clientId)
// .setClientSecret(clientSecret)
// .build();
//
// EMService service = new EMService(properties);
// return service;
// }
public String getUrl(){
return String.format("http://a1.easemob.com/%s/%s/",orgName,appName);
}
public String getToken(){
String token="";
Map<String,Object> param=new HashMap<>();
param.put("grant_type","client_credentials");
param.put("client_id",clientId);
param.put("client_secret",clientSecret);
ResponseEntity<String> resp=restTemplate.postForEntity(getUrl()+"token",param,String.class);
System.out.println(resp);
if(resp.getStatusCodeValue()==200) {
token= JSON.parseObject(resp.getBody()).getString("access_token");
}
return token;
}
public JSONObject getUser(String username){
JSONObject user=new JSONObject();
String token=getToken();
HttpHeaders headers=new HttpHeaders();
headers.add("Authorization","Bearer "+token);
HttpEntity param=new HttpEntity(headers);
resp=restTemplate.exchange(getUrl()+"users/"+username, HttpMethod.GET,param,String.class);
if (resp.getStatusCodeValue()==200){
user= JSON.parseObject(resp.getBody());
}
return user;
}
public JSONObject addUser(String username,String passwd,String nickname){
JSONObject rs=new JSONObject();
Map<String,Object> param=new HashMap<>();
HttpHeaders headers=new HttpHeaders();
headers.add("Authorization","Bearer "+getToken());
List lParam=new ArrayList();
param.clear();
param.put("username",username);
param.put("password",passwd);
param.put("nickname",nickname);
lParam.add(param);
log.info("注册环信用户:"+param);
HttpEntity entity=new HttpEntity(param,headers);
resp=restTemplate.postForEntity(getUrl()+"users",entity,String.class);
if (resp.getStatusCodeValue()==200){
rs= JSON.parseObject(resp.getBody());
}
log.info(rs);
return rs;
}
/**
* 删除用户
* @param username 环信用户ID
* @return
*/
public JSONObject delUser(String username){
JSONObject user=new JSONObject();
String token=getToken();
HttpHeaders headers=new HttpHeaders();
headers.add("Authorization","Bearer "+token);
HttpEntity param=new HttpEntity(headers);
resp=restTemplate.exchange(getUrl()+"users/"+username, HttpMethod.DELETE,param,String.class);
if (resp.getStatusCodeValue()==200){
user= JSON.parseObject(resp.getBody());
}
return user;
}
public JSONObject sendMsg(String[] target,String msgType,String msgContent,String from){
JSONObject rs=new JSONObject();
Map<String,Object> param=new HashMap<>();
HttpHeaders headers=new HttpHeaders();
headers.add("Authorization","Bearer "+getToken());
List lParam=new ArrayList();
param.put("target",target);
Map<String,Object> msg=new HashMap<>();
msg.put("type",msgType);
msg.put("msg",msgContent);
param.put("msg",msg);
param.put("from",from);
lParam.add(param);
HttpEntity entity=new HttpEntity(param,headers);
resp=restTemplate.postForEntity(getUrl()+"messages",entity,String.class);
if (resp.getStatusCodeValue()==200){
rs= JSON.parseObject(resp.getBody());
}
log.info(rs);
return rs;
}
/**
* 群组发送消息
* @param target hxgroupid
* @param target_type 发送的目标类型:
* • users:给用户发消息;
* • chatgroups:给群发消息;
* • chatrooms:给聊天室发消息。
* @param msgContent
* @param from
* @return
*/
public JSONObject sendGroupMsg(String[] target ,String msgContent,String from){
JSONObject rs=new JSONObject();
Map<String,Object> param=new HashMap<>();
HttpHeaders headers=new HttpHeaders();
headers.add("Authorization","Bearer "+getToken());
List lParam=new ArrayList();
param.put("target_type","chatgroups");
param.put("target",target);
Map<String,Object> msg=new HashMap<>();
msg.put("type","txt");
msg.put("msg",msgContent);
param.put("msg",msg);
param.put("from",from);
lParam.add(param);
HttpEntity entity=new HttpEntity(param,headers);
resp=restTemplate.postForEntity(getUrl()+"messages",entity,String.class);
if (resp.getStatusCodeValue()==200){
rs= JSON.parseObject(resp.getBody());
}
log.info(rs);
return rs;
}
/**
* 获取聊天记录
* @param time 查询的时间格式为10位数字形式(YYYYMMDDHH)
* @return
*/
public List<String> getChatMessages(String time){
List<String> cLst=new ArrayList<>();
JSONObject msg=new JSONObject();
String token=getToken();
HttpHeaders headers=new HttpHeaders();
headers.add("Authorization","Bearer "+token);
HttpEntity param=new HttpEntity(headers);
try {
resp = restTemplate.exchange(getUrl() + "chatmessages/" + time, HttpMethod.GET, param, String.class);
if (resp.getStatusCodeValue()==200){
msg= JSON.parseObject(resp.getBody());
log.info(msg);
JSONArray data=msg.getJSONArray("data");
if(data.size()>0){
for (int i = 0; i < data.size() ; i++) {
String url=data.getJSONObject(i).getString("url");
File file=getFileFromUrl(url);
FileUtils.copyURLToFile(new URL(url),file);
file=doUncompressFile(file);
cLst=FileUtils.readLines(file,"utf-8");
}
}
}
}catch (Exception e){
log.error(e.getMessage());
e.printStackTrace();
}
return cLst;
}
private File getFileFromUrl(String url){
String preStr=url.split("\\?")[0];
String[] preArr=preStr.split("/");
File file=new File(preArr[preArr.length-1]);
if(file.exists()){
file.delete();
}
return file;
}
/**
* Uncompress the incoming file. 解压缩的文件。
* @param inFileName 未压缩文件的名称
*/
private static File doUncompressFile(File inFileName) {
try {
if (!getExtension(inFileName.getName()).equalsIgnoreCase("gz")) {
System.err.println("文件名必须有扩展名 \".gz\"");
System.exit(1);
}
System.out.println("打开压缩文件.");
GZIPInputStream in = null;
try {
in = new GZIPInputStream(new FileInputStream(inFileName));
} catch(Exception e) {
System.err.println("文件未找到. " + inFileName);
System.exit(1);
}
System.out.println("打开输出文件.");
String outFileName = getFileName(inFileName.getName());
File file=new File(outFileName);
FileOutputStream out = null;
try {
out = new FileOutputStream(file,false);
} catch (FileNotFoundException e) {
System.err.println("不能写入文件. " + outFileName);
System.exit(1);
}
System.out.println("将字节从压缩文件传输到输出文件.");
byte[] buf = new byte[1024];
int len;
while((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
System.out.println("关闭文件和流");
in.close();
out.close();
return file;
} catch (IOException e) {
e.printStackTrace();
// System.exit(1);
}
return null;
}
public static String getFileName(String f) {
String fname = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1) {
fname = f.substring(0,i);
}
return fname;
}
/**
* 创建聊天室
* @param description
* @param owner
* @param members
* @return
*/
public JSONObject addChatGroups(String description,String owner,String[] members){
JSONObject rs=new JSONObject();
Map<String,Object> param=new HashMap<>();
HttpHeaders headers=new HttpHeaders();
headers.add("Authorization","Bearer "+getToken());
List lParam=new ArrayList();
param.put("groupname", Arrays.toString(members));
param.put("desc",description);
param.put("public",true);
param.put("owner",owner);
param.put("members",Arrays.asList(members));
lParam.add(param);
HttpEntity entity=new HttpEntity(param,headers);
resp=restTemplate.postForEntity(getUrl()+"chatgroups",entity,String.class);
if (resp.getStatusCodeValue()==200){
rs= JSON.parseObject(resp.getBody());
}
log.info(rs);
return rs;
}
/**
* 批量获取用户状态
* @param usernames
* @return
*/
public JSONObject chkUserStatus(String[] usernames) {
JSONObject rs=new JSONObject();
Map<String,Object> param=new HashMap<>();
HttpHeaders headers=new HttpHeaders();
headers.add("Authorization","Bearer "+getToken());
List lParam=new ArrayList();
param.put("usernames", usernames);
lParam.add(param);
HttpEntity entity=new HttpEntity(param,headers);
resp=restTemplate.postForEntity(getUrl()+"users/batch/status",entity,String.class);
if (resp.getStatusCodeValue()==200){
rs= JSON.parseObject(resp.getBody());
}
log.info(rs);
return rs;
}
}