通过apicloud开发app,集成融云的sdk开发IM聊天系统
1初始化融云,显示聊天列表 var rong var header_h = 50 var footer_h = 45 var toUserId; var token; apiready = function() { token = $api.getStorage("local_user").token; rong = api.require('rongCloud2'); rong.init(function(ret, err) { if (ret.status == 'error') { // viewErr(err.code) } }); rong.setConnectionStatusListener(function(ret, err) { viewErr(ret.result.code) if (ret.result.code == 6) { reloginIm(); } sendEvent('imConStatus', { code : ret.result.code }) }); rong.setOnReceiveMessageListener(function(ret, err) { api.sendEvent({ name : 'getNewMes', extra : { data : ret.result.message } }) }) rong.connect({ token : token }, function(ret, err) { if (ret.status == 'success') { api.toast({ msg : "连接成功" }); getLast(); } else { // api.toast({ // msg : JSON.stringify(err) // }); } }); getEvent('sendMsg', function(data) { sendMsg(data.msg) }) getEvent('sendImgMsg', function(data) { sendImgMsg(data.path) }) getEvent('sendVoiceMsg', function(data) { sendVoiceMsg(data.path, data.duration) }) getEvent('hisList', function(data) { hisList(); }) getEvent('loginOrOut', function(data) { reLoginIm(); }) } function hisList(msgid) { rong.getLatestMessages({ conversationType : 'PRIVATE', targetId : toUserId, count : 10 }, function(ret, err) { sendEvent('viewHisList', { result : ret.result }) }) } function sendMsg(msg) { rong.sendTextMessage({ conversationType : 'PRIVATE', targetId : toUserId, text : msg, extra : '' }, function(ret, err) { sendCallBack(ret, err) }); } function sendImgMsg(imgPath) { rong.sendImageMessage({ conversationType : 'PRIVATE', targetId : toUserId, imagePath : imgPath, extra : '' }, function(ret, err) { sendCallBack(ret, err) }); } function sendVoiceMsg(voicePath, duration) { rong.sendVoiceMessage({ conversationType : 'PRIVATE', targetId : toUserId, voicePath : voicePath, duration : duration, extra : '' }, function(ret, err) { sendCallBack(ret, err) }); } function sendCallBack(ret, err) { if (ret.status == 'prepare') { sendEvent("viewMsg", { result : ret.result.message, status : ret.status }) } else { sendEvent("viewMsg", { status : ret.status, messageId : ret.result.message.messageId, err : err }) } } //点击用户进入页面开始聊天 function imOpen(imId) { toUserId = imId; var num = $(".pppp4").text(); ajax('doctorManage/scImg', { id : imId }, function(rets, err) { $api.setStorage("local_us", rets.result.user); }) api.openWin({ name : 'imMain', url : 'widget://html/qm/imMain.html', pageParam : { toUserId : imId, dateSize : dateSize, num : num, sbName : sbName, InternetType : InternetType } }); } function getLast() { rong.getConversationList(function(ret, err) { //将获得的数据插入到容器中 if (ret.result != undefined) { } } }) }
2UI页面主要控制聊天窗口样式 var header_h = 59 var footer_h = 35 var uicInit = 0; var UIChatBox; apiready = function() { $("#page_title").append($api.getStorage("local_us").realname); var $header = $api.dom('header'); $api.fixStatusBar($header); header_h = $api.offset($header).h; UIChatBox = api.require('UIChatBox'); uic() UIChatBox.addEventListener({ target : 'inputBar', name : 'move' }, function(ret, err) { ucbChange(ret) }); UIChatBox.addEventListener({ target : 'inputBar', name : 'change' }, function(ret, err) { if (uicInit == 0) { uicInit = 1 } else { ucbChange(ret) } }); UIChatBox.addEventListener({ target : 'recordBtn', name : 'press' }, function(ret, err) { openTip('recordStart') api.startPlay({ path : 'widget://image/im/sound/play_voice.mp3' }, function() { api.startRecord(); }); }); UIChatBox.addEventListener({ target : 'recordBtn', name : 'press_cancel' }, function(ret, err) { api.closeFrame({ name : 'recordStart' }); setTimeout(function() { api.stopRecord(function(ret, err) { if (ret.duration == 0) { openTip('recordError') setTimeout(function() { api.closeFrame({ name : 'recordError' }); }, 500) } else { sendEvent('sendVoiceMsg', { path : ret.path, duration : ret.duration }) } api.startPlay({ path : 'widget://image/im/sound/stop_voice.mp3' }); }); }, 300) }); UIChatBox.addEventListener({ target : 'recordBtn', name : 'move_out' }, function(ret, err) { api.closeFrame({ name : 'recordStart' }); openTip('recordChange') }); UIChatBox.addEventListener({ target : 'recordBtn', name : 'move_out_cancel' }, function(ret, err) { api.closeFrame({ name : 'recordChange' }); api.stopRecord(function(ret, err) { }); }); UIChatBox.addEventListener({ target : 'recordBtn', name : 'move_in' }, function(ret, err) { api.closeFrame({ name : 'recordChange' }); openTip('recordStart') }); randomSwitchBtn(document.getElementById("asd"), 'cloud', 0) }; function openTip(name) { api.openFrame({ name : name, url : 'widget://html/qm/' + name + '.html', rect : { y : (api.winHeight - 200 - 35) / 2, x : (api.winWidth - 200 ) / 2, w : 200, h : 200 }, hScrollBarEnabled : false, vScrollBarEnabled : false }); } function ucbChange(ret) { var _h = ret.inputBarHeight + ret.panelHeight; var h = api.winHeight - header_h - _h; if (ret.panelHeight != 0) { // h = h - 35 } api.setFrameAttr({ name : "imIndex", rect : { x : 0, y : header_h, w : 'auto', h : h }, bounces : true }); setBottom(); } function setBottom() { api.execScript({ frameName : 'imIndex', script : 'down();' }); } function uic() { UIChatBox.open({ placeholder : '', maxRows : 4, emotionPath : 'widget://image/im/uic/emotion', texts : { recordBtn : { normalTitle : '按住 说话', activeTitle : '松开 结束' } }, styles : { inputBar : { borderColor : '#d9d9d9', bgColor : '#f2f2f2' }, inputBox : { borderColor : '#B3B3B3', bgColor : '#FFFFFF' }, emotionBtn : { normalImg : 'widget://image/im/uic/face1.png' }, extrasBtn : { normalImg : 'widget://image/im/uic/add1.png' }, keyboardBtn : { normalImg : 'widget://image/im/uic/key1.png' }, speechBtn : { normalImg : 'widget://image/im/uic/voice.png' }, recordBtn : { normalBg : '#c4c4c4', activeBg : '#999999', color : '#000', size : 14 }, indicator : { target : 'both', color : '#c4c4c4', activeColor : '#9e9e9e' } }, extras : { titleSize : 10, titleColor : '#a3a3a3', btns : [{ title : '图片', normalImg : 'widget://image/im/uic/album1.png', activeImg : 'widget://image/im/uic/album2.png' }, { title : '拍照', normalImg : 'widget://image/im/uic/cam1.png', activeImg : 'widget://image/im/uic/cam2.png' }] } }, function(ret) { //点击附加功能面板 if (ret.eventType == 'clickExtras') { if (ret.index == 0) { api.getPicture({ sourceType : 'library', allowEdit : true, quality : 50, targetWidth : 1000, targetHeight : 1000 }, function(ret, err) { if (ret && ret.data) { sendEvent('sendImgMsg', { path : ret.data }) } else { // alert('你没有选择图片') api.toast({ msg : '你没有选择图片', location : 'middle' }) } }) } if (ret.index == 1) { api.getPicture({ sourceType : 'camera', allowEdit : true, quality : 50, targetWidth : 1000, targetHeight : 1000 }, function(ret, err) { if (ret && ret.data) { sendEvent('sendImgMsg', { path : ret.data }) } else { // alert('你没有选择图片') api.toast({ msg : '你没有选择图片', location : 'middle' }) } }) } } //点击发送按钮 if (ret.eventType == 'send') { sendEvent('sendMsg', { msg : ret.msg }) } }); } // 随意切换按钮 function randomSwitchBtn(obj, name, index) { api.openFrame({ name : "imIndex", url : "widget://html/qm/imIndex.html", pageParam : { toUserId : api.pageParam.toUserId }, rect : { x : 0, y : header_h, w : 'auto', h : api.winHeight - header_h - footer_h } }); }
3实时聊天数据显示页面JS var toUserId var emotionData; apiready = function() { //存储表情 getImgsPaths("widget://image/im/uic/emotion/emotion", function(emotion) { emotionData = emotion; }) toUserId = (api.pageParam.toUserId) getEvent('viewMsg', function(ret) { if (ret.status == 'prepare') { disMsg(ret.result) } else if (ret.status == 'success') { $("#imSendStatus_" + ret.messageId).empty() } else if (ret.status == 'error') { $("#imSendStatus_" + ret.messageId).empty().append("<img src='../../image/im/im_send_error.gif'>") //alert(JSON.stringify(ret.err)) } }) getEvent('getNewMes', function(ret) { if (ret.data.targetId == toUserId) { disMsg(ret.data) } }) getEvent('viewHisList', function(ret) { disHisMsg(ret.result); }) getEvent('imConStatus', function(ret) { viewErr(ret.code) sendEvent('loginOrOut', {}) }) sendEvent('hisList', {}) } function down() { setTimeout(function() { document.getElementsByTagName('body')[0].scrollTop = document.getElementsByTagName('body')[0].scrollHeight; }, 200) } function disHisMsg(items) { try { for ( inx = 0; inx < items.length; inx++) { $("#messageList").prepend(msgView(items[inx], 1)) down(); } } catch(e) { sendEvent('hisList', {}) } } function disMsg(item) { $("#messageList").append(msgView(item)) down(); } /** * { content: { text: 'Hello world!', extra: '' }, // 消息内容 conversationType: 'PRIVATE', // 参见 会话类型 枚举 messageDirection: 'SEND', // 消息方向:SEND 或者 RECEIVE targetId: '55', // 这里对应消息发送者的 userId objectName: 'RC:TxtMsg', // 消息类型,参见 http://docs.rongcloud.cn/android_message.html#_内置内容类消息 sentStatus: 'SENDING', // 发送状态:SENDING, SENT 或 FAILED senderUserId: '55', // 发送者 userId messageId: 608, // 本地消息 Id sentTime: 1418971531533, // 发送消息的时间戳,从 1970 年 1 月 1 日 0 点 0 分 0 秒开始到现在的毫秒数 receivedTime: 0 // 收到消息的时间戳,从 1970 年 1 月 1 日 0 点 0 分 0 秒开始到现在的毫秒数 } */ function msgView(item, timeGenre) { var htm = ''; if (item.sentStatus != 'FAILED') { var className = '' var userLogo = '../../image/im/face1.png' var msg = ''; var imSendStatus = '' var imVcImg = '' switch(item.messageDirection) { case 'SEND': className = 'sender' imVcImg = 'to' userLogo = sys_base_url+ $api.getStorage("local_user").Idimg; break; case 'RECEIVE': className = 'receiver' imVcImg = 'from' userLogo = sys_base_url+$api.getStorage("local_us").Idimg; break; } switch(item.sentStatus) { case 'SENDING': imSendStatus = "<img src='../../image/im/im_send.jpg'>" break; case 'SENT': break; case 'FAILED': imSendStatus = "<img src='../../image/im/im_send_error.jpg'>" break; } switch(item.objectName) { case 'RC:TxtMsg': msg = item.content.text; msg = transText(msg); msg = " <span>" + msg + "</span>" break; case 'RC:ImgMsg': if (item.content.localPath) { msg = "<img src='" + item.content.localPath + "' width='100px'>" } else { msg = "<img src='" + item.content.imageUrl + "' width='100px'>" } msg = " <span>" + msg + "</span>" break; case 'RC:VcMsg': if (item.content.voicePath) { msg = " <span onclick=\"voicePlay('" + item.content.voicePath + "',this)\"><img height=\"16px\" id='imVice" + item.messageId + "' src=\"../../image/im/" + imVcImg + "_voice.png\" oldsrc=\"" + imVcImg + "\"><span>" + item.content.duration + "\"</span></span>" } else { // alert(JSON.stringify(item)) } break; } var imTimeArgs = commDateView(item.sentTime) if (timeGenre) { $("#time" + imTimeArgs[0]).remove() } if ($("#time" + imTimeArgs[0]).length == 0) { htm += "<div class=\"imtime\" id=\"time" + imTimeArgs[0] + "\">" + imTimeArgs[1] + "</div>" } htm += "<div class=\"" + className + "\">"; htm += "<div class=\"avatar\">"; htm += " <img src=\"" + userLogo + "\">"; htm += "</div>" htm += "<div class=\"cont\">"; htm += " <div class=\"triangle\"></div>"; htm += msg; htm += " <div id=\"imSendStatus_" + item.messageId + "\" class=\"status\">"; htm += imSendStatus; htm += " </div>"; htm += "</div>"; htm += "</div>"; } return htm } var play_id = [] function voicePlay(voicePath, item) { var imgGenre = $(item).children("img").attr('oldsrc') var imgId = $(item).children("img").attr('id') if (play_id.length == 0) { play_id[0] = imgGenre; play_id[1] = imgId; $(item).children("img").attr('src', '../../image/im/' + imgGenre + '_voice.gif') api.startPlay({ path : voicePath }, function() { $(item).children("img").attr('src', '../../image/im/' + imgGenre + '_voice.png') play_id = []; }); } else { api.stopPlay(); $("#" + play_id[1]).attr('src', '../../image/im/' + play_id[0] + '_voice.png') if (play_id[1] != imgId) { play_id = []; voicePlay(voicePath, item) } else { play_id = []; } } } function transText(text, imgWidth, imgHeight) { var imgWidth = imgWidth || 16; var imgHeight = imgHeight || 16; var regx = /\[(.*?)\]/gm; var textTransed = text.replace(regx, function(match) { var imgSrc = emotionData[match]; if (!imgSrc) { //说明不对应任何表情,直接返回 return match; } var img = "<img src=" + imgSrc + " width=" + imgWidth + " height=" + imgHeight + ">"; return img; }); return textTransed; } function getImgsPaths(sourcePathOfChatBox, callback) { var jsonPath = sourcePathOfChatBox + ".json"; api.readFile({ path : jsonPath }, function(ret, err) { if (ret.status) { var emotionArray = JSON.parse(ret.data); var emotion = {}; for (var idx in emotionArray) { var emotionItem = emotionArray[idx]; var emotionText = emotionItem["text"]; var emotionUrl = "../../image/im/uic/emotion/" + emotionItem["name"] + ".png"; emotion[emotionText] = emotionUrl; } /* 把 emotion对象 回调出去. */ if ("function" === typeof (callback)) { callback(emotion); } } }); }