PageRenderTime 45ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/src/com/wqdsoft/im/service/SNSMessageManager.java

https://gitlab.com/Er_Hei/PlayCar
Java | 407 lines | 239 code | 51 blank | 117 comment | 17 complexity | ce923479cebfe17e3d47dad2fe7686e1 MD5 | raw file
  1. package com.wqdsoft.im.service;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.Date;
  5. import java.util.List;
  6. import android.database.sqlite.SQLiteDatabase;
  7. import android.text.TextUtils;
  8. import android.util.Log;
  9. import com.alibaba.fastjson.JSON;
  10. import com.alibaba.fastjson.JSONObject;
  11. import com.wqdsoft.im.DB.DBHelper;
  12. import com.wqdsoft.im.DB.UserTable;
  13. import com.wqdsoft.im.Entity.Login;
  14. import com.wqdsoft.im.Entity.MessageInfo;
  15. import com.wqdsoft.im.Entity.MessageType;
  16. import com.wqdsoft.im.global.IMCommon;
  17. import com.wqdsoft.im.map.BMapApiApp;
  18. import com.wqdsoft.im.receiver.MultiMessageListener;
  19. import com.wqdsoft.im.receiver.NotifyChatMessage;
  20. import com.wqdsoft.im.receiver.NotifyMessage;
  21. import com.wqdsoft.im.receiver.NotifySystemMessage;
  22. import com.wqdsoft.im.receiver.PushChatMessage;
  23. import com.wqdsoft.im.receiver.PushMessage;
  24. import com.xmpp.push.sns.Chat;
  25. import com.xmpp.push.sns.ChatManagerListener;
  26. import com.xmpp.push.sns.Form;
  27. import com.xmpp.push.sns.MessageListener;
  28. import com.xmpp.push.sns.SmackConfiguration;
  29. import com.xmpp.push.sns.XMPPException;
  30. import com.xmpp.push.sns.muc.Affiliate;
  31. import com.xmpp.push.sns.muc.DiscussionHistory;
  32. import com.xmpp.push.sns.muc.MultiUserChat;
  33. import com.xmpp.push.sns.packet.Message;
  34. /**
  35. *
  36. * 功能:聊天监听.监听服务端信息(聊天信息,系统消息等...) <br />
  37. * 日期:2013-5-5<br />
  38. * 地点:无穷大软件<br />
  39. * 版本:ver 1.0<br />
  40. *
  41. * guoxin
  42. * @since
  43. */
  44. public class SNSMessageManager implements ChatManagerListener{
  45. private static final String SYSTEM_USER = "beautyas";
  46. private XmppManager xmppManager;
  47. private MessageListener chatListener;
  48. // private LruMemoryCache<String, Chat> chatCache = new LruMemoryCache<String, Chat>(6);
  49. private NotifyChatMessage chatMessage;
  50. private NotifySystemMessage systemMessage;
  51. private PushChatMessage pushChatMessage;
  52. public SNSMessageManager(XmppManager xmppManager) {
  53. super();
  54. this.xmppManager = xmppManager;
  55. chatListener = new ChatListenerImpl();
  56. chatMessage = new NotifyChatMessage(xmppManager);
  57. systemMessage = new NotifySystemMessage(xmppManager);
  58. pushChatMessage = new PushChatMessage(xmppManager);
  59. }
  60. @Override
  61. public void chatCreated(Chat chat, boolean createdLocally) {
  62. if(!createdLocally){
  63. chat.addMessageListener(chatListener);
  64. }
  65. // chatCache.put(chat.getParticipant().split("@")[0], chat);
  66. }
  67. public boolean joinRoom(String roomName, Date date){
  68. MultiUserChat muc = new MultiUserChat(xmppManager.getConnection(),
  69. roomName + "@conference."
  70. + xmppManager.getConnection().getServiceName());
  71. DiscussionHistory history = new DiscussionHistory();
  72. //history.setSince(date);
  73. history.setMaxChars(0);
  74. muc.addMessageListener(new MultiMessageListener(xmppManager));
  75. muc.addParticipantStatusListener(new XMPPParticipantStatusListener(xmppManager));
  76. try {
  77. //muc.join(xmppManager.getUsername());
  78. muc.join(xmppManager.getUsername(), null, history, SmackConfiguration.getPacketReplyTimeout());
  79. return true;
  80. } catch (XMPPException e) {
  81. e.printStackTrace();
  82. }
  83. return false;
  84. }
  85. public MultiUserChat createMUC(String groupName){
  86. try {
  87. // 创建一个MultiUserChat
  88. MultiUserChat muc = new MultiUserChat(xmppManager.getConnection(),
  89. groupName + "@conference."
  90. + xmppManager.getConnection().getServiceName());
  91. // 创建聊天室
  92. muc.create(groupName); // roomName房间的名字
  93. // 获得聊天室的配置表单
  94. Form form = muc.getConfigurationForm();
  95. // 根据原始表单创建一个要提交的新表单。
  96. Form submitForm = form.createAnswerForm();
  97. // 向要提交的表单添加默认答复
  98. /*
  99. * for (Iterator<FormField> fields = form.getFields(); fields
  100. * .hasNext();) { FormField field = (FormField) fields.next(); if
  101. * (!FormField.TYPE_HIDDEN.equals(field.getType()) &&
  102. * field.getVariable() != null) { // 设置默认值作为答复
  103. * submitForm.setDefaultAnswer(field.getVariable()); } } //
  104. * 设置聊天室的新拥有者 List<String> owners = new ArrayList<String>();
  105. * owners.add(xmppManager.getConnection().getUser());// 用户JID
  106. * submitForm.setAnswer("muc#roomconfig_roomowners", owners); //
  107. * 设置聊天室是持久聊天室,即将要被保存下来
  108. * submitForm.setAnswer("muc#roomconfig_persistentroom", false); //
  109. * 房间仅对成员开放 submitForm.setAnswer("muc#roomconfig_membersonly",
  110. * false); // 允许占有者邀请其他人
  111. * submitForm.setAnswer("muc#roomconfig_allowinvites", true); //
  112. * 进入是否需要密码
  113. * //submitForm.setAnswer("muc#roomconfig_passwordprotectedroom",
  114. * true); // 设置进入密码
  115. * //submitForm.setAnswer("muc#roomconfig_roomsecret", "password");
  116. * // 能够发现占有者真实 JID 的角色 //
  117. * submitForm.setAnswer("muc#roomconfig_whois", "anyone"); // 登录房间对话
  118. * submitForm.setAnswer("muc#roomconfig_enablelogging", true); //
  119. * 仅允许注册的昵称登录 submitForm.setAnswer("x-muc#roomconfig_reservednick",
  120. * true); // 允许使用者修改昵称
  121. * submitForm.setAnswer("x-muc#roomconfig_canchangenick", false); //
  122. * 允许用户注册房间 submitForm.setAnswer("x-muc#roomconfig_registration",
  123. * false); // 发送已完成的表单(有默认值)到服务器来配置聊天室
  124. * submitForm.setAnswer("muc#roomconfig_passwordprotectedroom",
  125. * true); // 发送已完成的表单(有默认值)到服务器来配置聊天室
  126. */
  127. // muc.sendConfigurationForm(form);
  128. List<String> owners = new ArrayList<String>();
  129. owners.add(xmppManager.getConnection().getUser());// 用户JID
  130. // 设置聊天室的新拥有者
  131. submitForm.setAnswer("muc#roomconfig_roomowners", owners);
  132. submitForm.setAnswer("muc#roomconfig_membersonly", false);
  133. // 设置聊天室是持久聊天室,即将要被保存下来
  134. submitForm.setAnswer("muc#roomconfig_persistentroom", true);
  135. // 登录房间对话
  136. //submitForm.setAnswer("muc#roomconfig_enablelogging", true);
  137. // 发送已完成的表单(有默认值)到服务器来配置聊天室
  138. muc.sendConfigurationForm(submitForm);
  139. return muc;
  140. } catch (XMPPException e) {
  141. e.printStackTrace();
  142. }
  143. return null;
  144. }
  145. public boolean initMUC(String groupName, MultiUserChat muc, List<Login> userList){
  146. try {
  147. muc.addMessageListener(new MultiMessageListener(xmppManager));
  148. muc.join(xmppManager.getUsername());
  149. for (int i = 0; i < userList.size(); i++) {
  150. SQLiteDatabase db = DBHelper.getInstance(xmppManager.getSnsService()).getWritableDatabase();
  151. //RoomUserTable table = new RoomUserTable(db);
  152. //table.insert(groupName, userList.get(i).uid);
  153. UserTable userTable = new UserTable(db);
  154. Login login = userTable.query(userList.get(i).uid);
  155. if(login == null){
  156. userTable.insert(userList.get(i), userList.get(i).groupId);
  157. }
  158. muc.invite(userList.get(i).uid + "@" + xmppManager.getConnection().getServiceName(), "");
  159. }
  160. return true;
  161. } catch (XMPPException e) {
  162. e.printStackTrace();
  163. }
  164. return false;
  165. }
  166. public boolean inviteUser(String groupName, MultiUserChat muc, List<Login> userList){
  167. try {
  168. for (int i = 0; i < userList.size(); i++) {
  169. SQLiteDatabase db = DBHelper.getInstance(xmppManager.getSnsService()).getWritableDatabase();
  170. //RoomUserTable table = new RoomUserTable(db);
  171. //table.insert(groupName, userList.get(i).uid);
  172. UserTable userTable = new UserTable(db);
  173. Login login = userTable.query(userList.get(i).uid);
  174. if(login == null){
  175. userTable.insert(userList.get(i), userList.get(i).groupId);
  176. }
  177. muc.invite(userList.get(i).uid + "@" + xmppManager.getConnection().getServiceName(), "");
  178. }
  179. return true;
  180. } catch (Exception e) {
  181. e.printStackTrace();
  182. }
  183. return false;
  184. }
  185. public boolean kickParticipant(MultiUserChat muc, String uid){
  186. try {
  187. muc.kickParticipant(uid, "");
  188. return true;
  189. } catch (XMPPException e) {
  190. e.printStackTrace();
  191. }
  192. return false;
  193. }
  194. public boolean destoryRoom(String roomName){
  195. try {
  196. String jid = roomName + "@conference." + xmppManager.getConnection().getServiceName();
  197. MultiUserChat muc = new MultiUserChat(xmppManager.getConnection(), jid);
  198. muc.destroy("", jid);
  199. return true;
  200. } catch (XMPPException e) {
  201. e.printStackTrace();
  202. }
  203. return false;
  204. }
  205. public boolean exitRoom(String roomName){
  206. try {
  207. String jid = roomName + "@conference." + xmppManager.getConnection().getServiceName();
  208. MultiUserChat muc = new MultiUserChat(xmppManager.getConnection(), jid);
  209. muc.leave();
  210. return true;
  211. } catch (Exception e) {
  212. e.printStackTrace();
  213. }
  214. return false;
  215. }
  216. /**
  217. * 创建一个会话.
  218. * @param chatID
  219. * @return 没有连接状态时,返回空.
  220. * 作者:fighter <br />
  221. * 创建时间:2013-5-5<br />
  222. * 修改时间:<br />
  223. */
  224. public Chat createChat(String chatID){
  225. Chat chat = null;
  226. // chatCache.get(chatID);
  227. // if(chat == null){
  228. try {
  229. chat = xmppManager
  230. .getConnection()
  231. .getChatManager()
  232. .createChat(
  233. chatID
  234. + "@"
  235. + xmppManager.getConnection()
  236. .getServiceName(), chatListener);
  237. } catch (Exception e) {
  238. e.printStackTrace();
  239. }
  240. // }
  241. // if(chat != null){
  242. // chatCache.put(chatID, chat);
  243. // }
  244. return chat;
  245. }
  246. /**
  247. * 通过服务端自己的接口发送消息
  248. */
  249. public void sendMsg(MessageInfo info){
  250. }
  251. /**
  252. * 通过 openfire 给指定的某人发送消息
  253. *
  254. * @param uid
  255. * @param info
  256. * 作者:fighter <br />
  257. * 创建时间:2013-3-16<br />
  258. * 修改时间:<br />
  259. */
  260. public boolean sendMessage(MessageInfo info, String group) {
  261. boolean flag = false;
  262. Chat chat = createChat(info.getToId());
  263. if(chat != null){
  264. try {
  265. JSONObject json = (JSONObject) JSON.toJSON(info);
  266. json.remove("id");
  267. json.remove("sendState");
  268. json.remove("readState");
  269. json.remove("sessionId");
  270. json.remove("pullTime");
  271. if(json.containsKey("isOutlander")){
  272. json.remove("isOutlander");
  273. }
  274. if(MessageType.MAP == info.typefile
  275. || MessageType.PICTURE == info.typefile/*
  276. ||MessageType.APPNEWS == info.type*/){
  277. json.put("content", JSONObject.parseObject(info.getContent()));
  278. }
  279. /*if(IMCommon.getLoginResult(BMapApiApp.getInstance())!=null){
  280. if(IMCommon.getLoginResult(BMapApiApp.getInstance()).type >=2 ){
  281. json.put("isUser", 1);
  282. }
  283. }*/
  284. chat.sendMessage(json.toJSONString());
  285. flag = true;
  286. } catch (XMPPException e) {
  287. e.printStackTrace();
  288. flag = false;
  289. } catch (IllegalStateException e) {
  290. // 没连接上服务器
  291. e.printStackTrace();
  292. flag = false;
  293. xmppManager.startReconnectionThread();
  294. }
  295. }
  296. info.setSendState(flag? 1 : 0);
  297. return flag;
  298. }
  299. /**
  300. * 发送聊天信息
  301. * @param pushMessage
  302. * @param messageInfo
  303. * 作者:fighter <br />
  304. * 创建时间:2013-5-6<br />
  305. * 修改时间:<br />
  306. */
  307. public void pushMessage(PushMessage pushMessage, MessageInfo msg, String group){
  308. pushMessage.pushMessage(msg, group);
  309. }
  310. /**
  311. * 接收到消息,通过广播发送发送.
  312. * @param notifyMessage
  313. * @param content
  314. * 作者:fighter <br />
  315. * 创建时间:2013-5-6<br />
  316. * 修改时间:<br />
  317. */
  318. public void notityMessage(NotifyMessage notifyMessage, String content){
  319. notifyMessage.notifyMessage(content);
  320. }
  321. public NotifySystemMessage getSystemMessage() {
  322. return systemMessage;
  323. }
  324. public PushChatMessage getPushChatMessage() {
  325. return pushChatMessage;
  326. }
  327. public NotifyChatMessage getNotifyChatMessage() {
  328. return chatMessage;
  329. }
  330. /**
  331. *
  332. * 功能:聊天对象的单对单对话监听<br />
  333. * 日期:2013-5-5<br />
  334. * 地点:无穷大软件<br />
  335. * 版本:ver 1.0<br />
  336. *
  337. * guoxin
  338. * @since
  339. */
  340. class ChatListenerImpl implements MessageListener{
  341. @Override
  342. public void processMessage(Chat chat, Message message) {
  343. // jid 为 chatId@domin/chat组成
  344. String chatId = chat.getParticipant().split("@")[0]; // 发来消息的用户
  345. String content = message.getBody(); // 发送来的内容.
  346. if(SYSTEM_USER.equals(chatId)){
  347. notityMessage(systemMessage, content);
  348. }else{
  349. if(!TextUtils.isEmpty(content) && content.startsWith("{")){
  350. Log.e("ChatListenerImpl", content);
  351. }
  352. notityMessage(chatMessage, content);
  353. }
  354. }
  355. }
  356. }