#include "gotyemsg.h" #include "mywidget.h" #include #include #include #include "gotye/GotyeMessage.h" #include "gotye/GotyeAPI.h" USING_NS_GOTYEAPI; #include "mywidgetitem.h" #include GotyeMsg *GotyeMsg::m_GotypMsg = NULL; GotyeMsg::GotyeMsg(QWidget *parent) : QWidget(parent) { isLogin = false; apiist-> addListener(*this); apiist-> setMessageReadIncrement(20); apiist-> setMessageRequestIncrement(20); // < 设定单次向服务器请求消息增量为20,默认10 showMsgViwe = NULL; //显示聊天的view useShowList = NULL; //显示聊天列表 showUserName = NULL; myHeadImg = QString(""); otherHeadImg = QString(""); markerMsgTime = 0; myUid = -1; isUpdataMsg = false; nowUser.name = "0"; // player = new QMediaPlayer(); // QString mpath = QCoreApplication::applicationDirPath()+"/ring/msg.mp3"; // mpath.replace("\\", "/"); // player->setMedia(QUrl::fromLocalFile(mpath)); QString mpath = QCoreApplication::applicationDirPath()+"/ring/msg.wav"; mpath.replace("\\", "/"); sound = new QSound(mpath); } void GotyeMsg::init() { apiist->init("a0044a1c-09e0-473a-8ceb-a13b445b086d", "com.gotye.api.demo");//测试环境 // apiist->init("51e493d8-879a-4c0f-8ce4-478cebdc3c8f", "com.gotye.api.demo"); //正式环境 } void GotyeMsg::login(QString uid) { loginUid = uid; apiist->login(uid.toStdString(), nullptr);///<对应回调GotyeDelegate::onLogin } void GotyeMsg::logout() { apiist->logout();///<对应回调GotyeDelegate::onLogin apiist->exit(); isLogin = false; } void GotyeMsg::apiist_exit() { apiist->exit(); } GotyeMsg *GotyeMsg::Instance() { if (!m_GotypMsg) m_GotypMsg = new GotyeMsg(); return m_GotypMsg; } void GotyeMsg::onLogin(GotyeStatusCode code, const GotyeLoginUser& user) { switch(code) { case GotyeStatusCodeOK: case GotyeStatusCodeReloginOK: { qDebug("CMQ 亲加云登录OK.....\n"); apiist->beginReceiveOfflineMessage(); isLogin = true; ShowNewMsgNum(); break; } case GotyeStatusCodeOfflineLoginOK: { qDebug("CMQ 亲加云退出登录.....\n"); isLogin = false; login(loginUid); break; } case GotyeStatusCodeLoginFailed: { qDebug("CMQ 亲加云登录失败.....\n"); isLogin = false; login(loginUid); break; } default: break; } } void GotyeMsg::setShowMsgWebviwe(QWebView *showViwe) { qDebug()<<"setShowMsgWebviwe\n"; if(showViwe) showMsgViwe = showViwe; qDebug()<<"setShowMsgWebviwe 000\n"; connect(showMsgViwe->page(), SIGNAL(scrollRequested(int,int,const QRect&)), SLOT(scrollTop(int,int,const QRect&))); } void GotyeMsg::setUpdataUserList(QListWidget *useList) { if(useList) useShowList = useList; else useShowList = NULL; } void GotyeMsg::setShowUserName(QLabel *showName) { if(showName) showUserName = showName; } void GotyeMsg::setMyHeadImg(QString img) { if(img.length() > 1) myHeadImg = img; } void GotyeMsg::setMyUid(int uid) { myUid = uid; } void GotyeMsg::setIsUpdata(bool flag) { isUpdataMsg = flag; if(!isUpdataMsg) apiist->deactiveSession (nowUser); // < 隐藏与target的会话 } void GotyeMsg::setShowMsgNum(QLabel *label) { showNewMsg = label; ShowNewMsgNum(); } void GotyeMsg::ShowNewMsgNum() { int msgNum = apiist->getTotalUnreadMessageCount(); if(msgNum > 0) { showNewMsg->setStyleSheet("background-color:rgba(0,0,0,0);color:rgb(255,255,255);border-image: url(:Images/Home/img_msg_num.png);"); showNewMsg->setAlignment(Qt::AlignCenter); if(msgNum > 99) showNewMsg->setText(QString("99+")); else showNewMsg->setText(QString("%1").arg(msgNum)); showNewMsg->show(); } else showNewMsg->hide(); // qDebug("ShowNewMsgNum msgNum%d..",msgNum); } void GotyeMsg::sendMessage(QString targetUid,QString msg,GotyeMessageType type) { GotyeChatTarget receiver(targetUid.toLatin1().data()); GotyeStatusCode status; GotyeMessage message; qDebug("targetUid = %s\n",receiver.info.data()); if(type == GotyeMessageTypeText) { message = GotyeMessage::createTextMessage(receiver, msg.toUtf8().data()); } else if(type == GotyeMessageTypeImage) { message = GotyeMessage::createImageMessage(receiver, msg.toStdString()); } else if(type == GotyeMessageTypeUserData) { qDebug("CMQ GotyeMessageTypeUserData.....\n"); } else if(type == GotyeMessageTypeAudio) { } status = apiist-> sendMessage (message); /// < 对应回调GotyeDelegate:: onSendMessage if(status == GotyeStatusCodeOK) { qDebug("CMQ 发送成功.....\n"); // qDebug() << QString::fromLocal8Bit("发送成功"); } } void GotyeMsg::sendMessage(QString msg,GotyeMessageType type) { GotyeStatusCode status; GotyeMessage message; if(type == GotyeMessageTypeText) { message = GotyeMessage::createTextMessage(nowUser, msg.toUtf8().data()); } else if(type == GotyeMessageTypeImage) { message = GotyeMessage::createImageMessage(nowUser, msg.toStdString()); } else if(type == GotyeMessageTypeUserData) { qDebug("CMQ GotyeMessageTypeUserData.....\n"); } else if(type == GotyeMessageTypeAudio) { } status = apiist-> sendMessage (message); /// < 对应回调GotyeDelegate:: onSendMessage if(status == GotyeStatusCodeOK) { qDebug("CMQ 发送成功.....\n"); // qDebug() << QString::fromLocal8Bit("发送成功"); } } void GotyeMsg::onSendMessage(GotyeStatusCode code, const GotyeMessage& message) { // static int flagMsgTime = 1; qDebug("CMQ GotyeMsg onSendMessage code = %d..markerMsgTime.text = %s...\n",code,message.text.data()); if(atoi(nowUser.name.data()) == 0) return; showMsgTime(markerMsgTime,message.date); markerMsgTime = message.date; if(message.type == GotyeMessageTypeText) { if(message.status == GotyeMessageStatusSending) SendMsgShow(QString::fromUtf8(message.text.data()),myHeadImg,QString("Sending")); else if(message.status == GotyeMessageStatusSendingFailed) SendMsgShow(QString::fromUtf8(message.text.data()),myHeadImg,QString("Failed")); else SendMsgShow(QString::fromUtf8(message.text.data()),myHeadImg,QString("")); } else if(message.type == GotyeMessageTypeImage) { if(message.status == GotyeMessageStatusSending) SendImageShow(QString::fromStdString(message.media.pathEx),myHeadImg,QString("Sending")); else if(message.status == GotyeMessageStatusSendingFailed) SendImageShow(QString::fromStdString(message.media.pathEx),myHeadImg,QString("Failed")); else SendImageShow(QString::fromStdString(message.media.pathEx),myHeadImg,QString("")); } else if(message.type == GotyeMessageTypeUserData) { qDebug("CMQ GotyeMessageTypeUserData.....\n"); } else if(message.type == GotyeMessageTypeAudio) { } msgChatAreaInit();//刷新聊天列表 } void GotyeMsg::onDownloadMedia(GotyeStatusCode code, GotyeMedia& media) { otherHeadImg = QString(imgTitle) + QString::fromStdString(media.path); otherHeadImg.replace("\\","/"); msgChatAreaInit();//刷新聊天列表 qDebug("CMQ GotyeMsg onDownloadMedia code = %d.....\n",code); } void GotyeMsg::onGetUserDetail(GotyeStatusCode code, const GotyeUser& user) { qDebug("CMQ GotyeMsg onGetUserDetail code = %d.....\n",code); if(strlen(user.icon.path.data()) > 2) apiist->downloadMedia(user.icon); else { otherHeadImg = QString(defaultHeadimg); msgChatAreaInit();//刷新聊天列表 } } void GotyeMsg::onDownloadMediaInMessage(const GotyeStatusCode code, const GotyeMessage& message) { qDebug("CMQ onDownloadMediaInMessage code = %d.....\n",code); if(atoi(nowUser.name.data()) == atoi(message.sender.name.data())) RevImageShow(QString::fromStdString(message.media.pathEx),otherHeadImg); } void GotyeMsg::onReceiveMessage(const GotyeMessage& message, bool* downloadMediaIfNeed) { GotyeUser userInfo; userInfo = apiist->getUserDetail(message.sender); if(atoi(message.sender.name.data()) >= 1000 && atoi(message.sender.name.data()) <= 1003) { qDebug("CMQ IShowMain onReceiveMessage ..message.text.data() = %s...message.name.data() = %s\n",message.text.data(),message.sender.name.data()); apiist->clearMessages(message.sender);//清除聊天 apiist->deleteSession(message.sender); return; } // qDebug()<currentMedia().canonicalUrl(); // player->play(); sound->play(); ShowNewMsgNum(); if(!isUpdataMsg) return; if(strlen(userInfo.icon.path.data()) > 1) { otherHeadImg = QString(imgTitle) + QString::fromStdString(userInfo.icon.path); otherHeadImg.replace("\\","/"); msgChatAreaInit();//刷新聊天列表 } else userInfo = apiist->getUserDetail(message.sender,true); qDebug()<<"CMQ otherHeadImg111="< messageList; GotyeMessage getMessage; GotyeUser userInfo; nowUser = getReceiver; nowMessageNum = 0; apiist-> markMessagesAsRead(nowUser,true); // < 全部标记为已读状态 apiist->activeSession (nowUser); // < 激活与target的会话 messageList = apiist->getMessageList(nowUser,false); qDebug("CMQ messageList->size() = %d...\n",messageList.size()); userInfo = apiist->getUserDetail(nowUser,true); if(strlen(userInfo.icon.path.data()) > 2) { otherHeadImg = QString(imgTitle) + QString::fromStdString(userInfo.icon.path); otherHeadImg.replace("\\","/"); } else otherHeadImg = QString(defaultHeadimg); QString html = QString( "document.body.innerHTML=''" ); showMsgViwe->page()->mainFrame()->evaluateJavaScript(html); // showUserName->setText(QString(userInfo.nickname.data())); for(int i = 0;i < messageList.size();i++) { getMessage = messageList.at(i); qDebug("CMQ getMessage.text = %s..icon = %s.\n",getMessage.sender.name.data(),getMessage.sender.icon.path.data()); showMsgTime(flagMsgTime,getMessage.date); flagMsgTime = getMessage.date; showUpMsg(getMessage); } } QString GotyeMsg::getShowTime(int secondNum) { QString returnDate; QDateTime dt = QDateTime::fromTime_t(secondNum); QString strDate = dt.toString("yyyy-MM-dd");//日期格式自定义 QDateTime current_date_time = QDateTime::currentDateTime(); QString current_date = current_date_time.toString("yyyy-MM-dd"); // qDebug("CMQ getShowTime current_date = %s...",current_date.toLatin1().data()); if(current_date == strDate) { QString strtime = dt.toString("hh:mm");//日期格式自定义 // QString current_time = current_date_time.toString("hh:mm"); returnDate = strtime; } else returnDate = strDate; return returnDate; } //刷新聊天记录 void GotyeMsg::scrollTop(int dx, int dy, const QRect& scrollViewRect) { std::deque messageList; int scrollNum = showMsgViwe->page()->mainFrame()->scrollBarValue(Qt::Vertical); if(dy < 0 || scrollNum > 60 ) return; messageList = apiist->getMessageList(nowUser,true); if(nowMessageNum != messageList.size()) { GotyeMessage getMessage; GotyeUser userInfo; int flagMsgTime = 1; int scrollMax = 0; int scrollHigh = 0; nowMessageNum = messageList.size(); qDebug("CMQ scrollTop messageList->size() = %d...\n",messageList.size()); userInfo = apiist->getUserDetail(nowUser,true); scrollHigh = showMsgViwe->page()->mainFrame()->scrollBarMaximum(Qt::Vertical); QString html = QString( "document.body.innerHTML=''" ); showMsgViwe->page()->mainFrame()->evaluateJavaScript(html); // showUserName->setText(QString(userInfo.nickname.data())); for(int i = 0;i < messageList.size();i++) { getMessage = messageList.at(i); showMsgTime(flagMsgTime,getMessage.date); flagMsgTime = getMessage.date; showUpMsg(getMessage); } scrollMax = showMsgViwe->page()->mainFrame()->scrollBarMaximum(Qt::Vertical); showMsgViwe->page()->mainFrame()->setScrollBarValue(Qt::Vertical,scrollMax - scrollHigh); } } QString GotyeMsg::getNowUserName() { return QString(nowUser.name.data()); } void GotyeMsg::delItemChat(QListWidgetItem *ChangedItem) { GotyeChatTarget userDel; qDebug("CMQ delItemChat.....%d......\n",useShowList->row(ChangedItem)); useShowList->removeItemWidget(ChangedItem); userDel = pTargetList.at(useShowList->row(ChangedItem)); apiist->deleteSession(userDel); apiist->clearMessages(userDel); // < 删除和某个聊天对象的所有消息 if(strcmp(userDel.name.data(),nowUser.name.data()) == 0) { QString html = QString( "document.body.innerHTML=''" ); showMsgViwe->page()->mainFrame()->evaluateJavaScript(html); nowUser.name = "0"; // showUserName->setText(""); } ShowNewMsgNum(); msgChatAreaInit(); } void GotyeMsg::showLastChatArea(GotyeChatTarget user) { std::deque messageList; GotyeMessage getMessage; GotyeUser userInfo; int flagMsgTime = 1; static int lastCount = -1; int count = 0; count = useShowList->currentRow(); qDebug("CMQ count = %d \n",count); apiist->deactiveSession(nowUser); // < 隐藏与target的会话 nowUser = user; markerMsgTime = 1; nowMessageNum = 0; apiist-> markMessagesAsRead(nowUser,true); // < 全部标记为已读状态 apiist->activeSession(nowUser); // < 激活与target的会话 if(atoi(nowUser.name.data()) == 0) return; messageList = apiist->getMessageList(nowUser,false); qDebug("CMQ messageList->size() = %d...\n",messageList.size()); userInfo = apiist->getUserDetail(nowUser,true); if(strlen(userInfo.icon.path.data()) > 2) { otherHeadImg = QString(imgTitle) + QString::fromStdString(userInfo.icon.path); otherHeadImg.replace("\\","/"); } else otherHeadImg = QString(defaultHeadimg); qDebug("nowUser.name = %s useShowList cound = %d",nowUser.name.data(),useShowList->count()); if(lastCount == -1 || lastCount != count || count == useShowList->count()-1 ) { QString html = QString( "document.body.innerHTML=''" ); showMsgViwe->page()->mainFrame()->evaluateJavaScript(html); // showUserName->setText(QString(userInfo.nickname.data())); msgChatAreaInit(); for(int i = 0;i < messageList.size();i++) { getMessage = messageList.at(i); showMsgTime(flagMsgTime,getMessage.date); flagMsgTime = getMessage.date; showUpMsg(getMessage); } lastCount = count; } ShowNewMsgNum(); } GotyeChatTarget GotyeMsg::setChooseUser(int count) { apiist->deactiveSession(nowUser); // < 隐藏与target的会话 nowUser = pTargetList.at(count); showLastChatArea(nowUser); useShowList->setCurrentRow(count); return nowUser; } void GotyeMsg::showUpMsg(GotyeMessage upMessage) { if(upMessage.type == GotyeMessageTypeText) { if(myUid == atoi(upMessage.sender.name.data())) SendMsgShow(QString::fromUtf8(upMessage.text.data()),myHeadImg,QString("")); else RevMsgShow(QString::fromUtf8(upMessage.text.data()),otherHeadImg); } else if(upMessage.type == GotyeMessageTypeImage) { if(myUid == atoi(upMessage.sender.name.data())) SendImageShow(QString::fromStdString(upMessage.media.pathEx),myHeadImg,QString("")); else RevImageShow(QString::fromStdString(upMessage.media.pathEx),otherHeadImg); } else if(upMessage.type == GotyeMessageTypeUserData) { qDebug("CMQ GotyeMessageTypeUserData.....\n"); } else if(upMessage.type == GotyeMessageTypeAudio) { } ShowNewMsgNum(); } void GotyeMsg::msgChatAreaInit() { GotyeMessage lastMessage; GotyeChatTarget getUser; GotyeUser userInfo; int count = 0; if(useShowList == NULL) return; useShowList->clear(); pTargetList = apiist->getSessionList(); qDebug("CMQ pTargetList.size() = %d.....\n",pTargetList.size()); if(pTargetList.size() < 1) return; for(int i = 0;i < pTargetList.size();i++) { getUser = pTargetList.at(i); // continue; lastMessage = apiist->getLastMessage(getUser); userInfo = apiist->getUserDetail(getUser); QListWidgetItem* item = new QListWidgetItem(); useShowList->addItem(item); MyWidget *userItem = new MyWidget(); // MyWidgetItem* userItem;// = new MyWidgetItem(); count = apiist-> getUnreadMessageCount(getUser); if(atoi(getUser.name.data()) != 1000) { if(lastMessage.type == GotyeMessageTypeText) { userItem->init(QString(userInfo.icon.path.data()),QString(userInfo.nickname.data()),getShowTime(lastMessage.date),QString(lastMessage.text.data()),count); } else { userItem->init(QString(userInfo.icon.path.data()),QString(userInfo.nickname.data()),getShowTime(lastMessage.date),QString("[img]"),count); } useShowList->setItemWidget(item,userItem); } else { apiist->deleteSession(userInfo); apiist->clearMessages(userInfo); // < 删除和某个聊天对象的所有消息 ShowNewMsgNum(); // continue; } int row = useShowList->count(); useShowList->item(row - 1)->setSizeHint(QSize(useShowList->width()-15,60)); if(strcmp(nowUser.name.data(),getUser.name.data()) == 0) { QListWidgetItem *item = useShowList->item(i); item->setSelected(true); useShowList->scrollToItem(item); // qDebug("CMQ setSelected = %d.....\n",i); } } } /* QString转换为Html的显示风格 */ void stringToHtml(QString &str,QColor crl) { QByteArray array; array.append(crl.red()); array.append(crl.green()); array.append(crl.blue()); QString strC(array.toHex()); str = QString("%2").arg(strC).arg(str); } void imgPathToHtml(QString &path) { path = QString("").arg(path); } void stringToHtmlFilter(QString &str) { //注意这几行代码的顺序不能乱,否则会造成多次替换 str.replace("&","&"); str.replace(">",">"); str.replace("<","<"); str.replace("\"","""); str.replace("\'","'"); str.replace(" "," "); str.replace("\n","
"); str.replace("\r","
"); } void GotyeMsg::showMsgTime(int lastTime,int nowTime) { QString html = QString( "" ); if(lastTime > 0 && nowTime > lastTime) { // qDebug("CMQ SendMsgShow..nowTime = %d..lastTime = %d...\n",nowTime,lastTime); if(nowTime - lastTime > 60) { html.append(QString( "document.getElementById(\"content\").insertAdjacentHTML(\"beforeEnd\",\"

%1

\");" ) .arg(getShowTime(nowTime))); showMsgViwe->page()->mainFrame()->evaluateJavaScript(html); } } } void GotyeMsg::SendMsgShow(QString msg ,QString head,QString status) { QString html = QString( "" ); // qDebug("CMQ IMG head = %s......\n",head.toLatin1().data()); // qDebug("CMQ SendMsgShow msg = %s...\n",msg.toLatin1().data()); stringToHtmlFilter(msg); // imgPathToHtml(head); html.append(QString( "document.getElementById(\"content\").insertAdjacentHTML(\"beforeEnd\",\"

%2

%3

\");document.body.scrollTop = document.documentElement.scrollHeight;" ) .arg( head ) .arg( msg ) .arg( status )); showMsgViwe->page()->mainFrame()->evaluateJavaScript(html); // showMsgViwe->page()->mainFrame()->setScrollBarValue(Qt::Vertical,showMsgViwe->page()->mainFrame()->scrollBarMaximum(Qt::Vertical)); // qDebug("CMQ scrollBarMaximum = %d...\n",showMsgViwe->page()->mainFrame()->scrollBarMaximum(Qt::Vertical)); // m_timer->start( 30000 ); } void GotyeMsg::SendImageShow(QString msg ,QString head,QString status) { //style='max-width:100px; padding-top:20px;margin:20px 20px 5px 0; msg.replace("\\","/"); qDebug("CMQ msg = %s...\n",msg.toLatin1().data()); QString html = QString( "" ); html.append(QString( "document.getElementById(\"content\").insertAdjacentHTML(\"beforeEnd\",\"

%3

\");document.body.scrollTop = document.documentElement.scrollHeight;" ) .arg(head) .arg(msg) .arg(status)); showMsgViwe->page()->mainFrame()->evaluateJavaScript(html); // m_timer->start( 30000 ); } void GotyeMsg::RevImageShow(QString msg,QString head) { msg.replace("\\","/"); qDebug("CMQ RevMsgShow msg = %s...\n",msg.toLatin1().data()); QString html = QString("document.getElementById(\"content\").insertAdjacentHTML(\"beforeEnd\",\"

\");document.body.scrollTop = document.documentElement.scrollHeight;") .arg(head) .arg(msg); showMsgViwe->page()->mainFrame()->evaluateJavaScript(html); // showMsgViwe->page()->mainFrame()->setScrollBarValue(Qt::Vertical,showMsgViwe->page()->mainFrame()->scrollBarMaximum(Qt::Vertical)); } void GotyeMsg::RevMsgShow(QString msg,QString head) { if(msg.indexOf("Call has no answer") > -1) stringToHtml(msg,Qt::red); else stringToHtmlFilter(msg); // qDebug("CMQ IMG head = %s......\n",head.toLatin1().data()); // qDebug("CMQ RevMsgShow msg = %s...\n",msg.toLatin1().data()); QString html = QString("document.getElementById(\"content\").insertAdjacentHTML(\"beforeEnd\",\"

%2

\");document.body.scrollTop = document.documentElement.scrollHeight;") .arg(head) .arg(msg); showMsgViwe->page()->mainFrame()->evaluateJavaScript(html); // showMsgViwe->page()->mainFrame()->setScrollBarValue(Qt::Vertical,showMsgViwe->page()->mainFrame()->scrollBarMaximum(Qt::Vertical)); }