diff --git a/.gitignore b/.gitignore index 5f9e6bb054ddefa475dfbdfa13f31d3f03ac4c3c..455118128af154fb9cf7d1e453650dc93e141ef7 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,10 @@ target_wrapper.* # QtCreator CMake CMakeLists.txt.user* -.idea -__pycache__ -bitXiaoSha/data/ +.idea +__pycache__ +bitXiaoSha/data/ +Client/debug/ +Server/debug/ +*.json +.vscode/ diff --git a/Client/Client.pro b/Client/Client.pro index d91d79529b82a06f2af8febabc9b53b0e765eb8d..e60b656970c80a0483f34c93a2ee368ed1a10640 100644 --- a/Client/Client.pro +++ b/Client/Client.pro @@ -21,13 +21,14 @@ SOURCES += \ Session/onlinesession.cpp \ clientdatacenter.cpp \ clientmain.cpp \ + codeeditor.cpp \ databaseoperation.cpp \ - highlighter.cpp \ kuang.cpp \ main.cpp \ mainwindow.cpp \ message.cpp \ messagemodel.cpp \ + myhighlighter.cpp \ userlogin.cpp \ usermodel.cpp \ userregister.cpp \ @@ -39,9 +40,11 @@ HEADERS += \ Session/onlinesession.h \ clientdatacenter.h \ clientmain.h \ + codeeditor.h \ databaseoperation.h \ + myhighlighter.h \ + typedef.h \ userregister.cpp \ - highlighter.h \ kuang.h \ ltest.h \ mainwindow.h \ @@ -66,6 +69,4 @@ else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target RESOURCES += \ - rsc.qrc \ - rsc.qrc \ system.qrc diff --git a/Client/Session/onlinesession.cpp b/Client/Session/onlinesession.cpp index 3ee1e234d024e8be121ff7da4ed194ae8c377ad8..4c7246fa0b2a321b9e4f744fc6e16bae1c05f5db 100644 --- a/Client/Session/onlinesession.cpp +++ b/Client/Session/onlinesession.cpp @@ -10,7 +10,6 @@ void OnlineSession::loadDataFromJson(const QJsonObject &json) { id = json["SessionID"].toInt(); loadUsersFromJson(json); - qDebug() << "debug" ; Profile = json["Profile"].toObject(); if ((getSessionType() == SessionType::GROUP && json["SessionType"] == "GROUP") || (getSessionType() == SessionType::FRIEND && json["SessionType"] == "FRIEND") ) @@ -24,7 +23,6 @@ void OnlineSession::loadDataFromJson(const QJsonObject &json) } else { qDebug() << "load error" ; - throw "load error"; } latest = Profile["LatestMessageID"].toInt(); } @@ -39,7 +37,6 @@ void OnlineSession::loadUsersFromJson(const QJsonObject& json) { QJsonArray userlist = json["Members"].toArray(); - if (userlist.size() < 2) { qDebug() << "Value Error"; throw "userlist 至少需要两个 user 元素"; } for (int i = 0; i < userlist.size(); i++) { QString usrname = userlist.at(i).toObject()["Username"].toString(); members.append(usrname); @@ -52,14 +49,14 @@ QJsonObject OnlineSession::generateJsonFromData() const { ret["MsgType"] = "SessionData"; ret["SessionID"] = id; ret["SessionType"] = getSessionType() == SessionType::GROUP ? "GROUP" : "FRIEND"; - ret["Profile"] = Profile; QJsonArray userlist; for (int i = 0; i < members.size(); i++) { QJsonObject tmp; - tmp["username"] = members.at(i); + tmp["Username"] = members.at(i); userlist.append(tmp); } ret["Members"] = userlist; - ret["LatestMessageID"] = latest; + Profile["LatestMessageID"] = latest; + ret["Profile"] = Profile; return ret; } diff --git a/Client/clientdatacenter.cpp b/Client/clientdatacenter.cpp index 62f8f1a6b4bf3cff1b2316d99054055c575b33cb..ee3147ef332775670d9800fccd5256191cc54f75 100644 --- a/Client/clientdatacenter.cpp +++ b/Client/clientdatacenter.cpp @@ -18,7 +18,7 @@ void ClientDataCenter::GetSessionMessage(){ int SessionID = Kuang::KuangChosenNow->SessionID; if(hasSession(SessionID)){ OnlineSession &temp = getSession(Kuang::KuangChosenNow->SessionID); - for(int i = 0;i < temp.getLatestMessageID();i++){ + for(int i = 1;i <= temp.getLatestMessageID();i++){ if(hasMessage(SessionID,i)){ QJsonObject tem = getMessage(SessionID,i).generateJsonOutput(); emit addsessionmessage(tem); @@ -48,10 +48,14 @@ void ClientDataCenter::registerMessage(OnlineMessage *msg) { } void ClientDataCenter::RegisterSession(QJsonObject data){ + if(!hasSession(data["SessionID"].toInt())){ + OnlineSession *temp = new OnlineSession(data); registerSession(temp); + qDebug() << data["SessionType"].toString() << "\n"; if(data["SessionType"].toString()=="FRIEND"){ + emit FriendSessionDataReceived(data); } if(data["SessionType"].toString()=="GROUP"){ @@ -64,7 +68,7 @@ void ClientDataCenter::RegisterMessage(QJsonObject data){ if(!hasMessage(data["SessionID"].toInt(),data["MessageID"].toInt())){ OnlineMessage *temp = new OnlineMessage(data); registerMessage(temp); - getSession(data["SessionID"].toInt()).getLatestMessageID()++; + getSession(data["SessionID"].toInt()).getLatestMessageID() = data["MessageID"].toInt(); } } diff --git a/Client/clientmain.cpp b/Client/clientmain.cpp index 46fd4d8383bc58cd81b9fbdb6a4b9ebbb20ee4a7..11e62cfc3f8d46ff42adf5454d5df5fb5405d272 100644 --- a/Client/clientmain.cpp +++ b/Client/clientmain.cpp @@ -1,7 +1,9 @@ #include "clientmain.h" #include +#include #include + ClientMain::ClientMain(QString IPAddress, int portOpen, QObject *parent) : QObject(parent), ipAdd(IPAddress), port(portOpen) { @@ -76,15 +78,14 @@ void ClientMain::connectToServer() { socket->connectToHost (QHostAddress(ipAdd), port); } -void ClientMain::receiveMessage() -{ - QByteArray arr = socket->readAll (); - QJsonDocument doc = QJsonDocument::fromJson(arr); - QJsonObject data = doc.object(); +void ClientMain::processMethod(QJsonObject data) { if(data["MsgType"].toString()=="UserData"){ emit UserDataReceived(data); } if(data["MsgType"].toString()=="LogInConfirm"){ + static bool init = false; + if (init) return; + init = true; emit LogInConfirmReceived(data); } if(data["MsgType"].toString()=="RegistConfirm"){ @@ -96,7 +97,24 @@ void ClientMain::receiveMessage() if(data["MsgType"].toString()=="SessionData"){ emit AddSessionToDatabase(data); } +} +void ClientMain::receiveMessage() +{ + QByteArray arr = socket->readAll (); + QJsonDocument doc = QJsonDocument::fromJson(arr); + QJsonObject data = doc.object(); + qDebug() << "Received from server: " << data; + if(!data.contains("MsgType")) return; + if (data["MsgType"].toString() == "JsonArray") { + auto array = data["MsgList"].toArray(); + for (int i = 0; i < array.size(); i++) { + processMethod(array[i].toObject()); + } + } + else { + processMethod(data); + } } void ClientMain::operator()() { diff --git a/Client/clientmain.h b/Client/clientmain.h index 58388ced2a56cd987cb41c5c35450fa99b9e96fc..e686d04f610a713bfb113378b01ee81387bbae29 100644 --- a/Client/clientmain.h +++ b/Client/clientmain.h @@ -26,10 +26,13 @@ public: //接收并打印的槽函数 void receiveMessage(); + void processMethod(QJsonObject data); bool isConnected() { return is_connected; } void createmainwindow(QJsonObject data); void MessageFromMainwindow(const QString & sendername, const QString &text); + void receiveJsonObject(QJsonObject); + signals: void serverConnected(); void serverDisconnected(); diff --git a/Client/codeeditor.cpp b/Client/codeeditor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..30f668a46c5495c56c466394b1f0247b899028b7 --- /dev/null +++ b/Client/codeeditor.cpp @@ -0,0 +1,110 @@ +#include "codeeditor.h" +#include + +CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent) +{ + lineNumberArea = new LineNumberArea(this); + + connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int))); + connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int))); + connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine())); + + updateLineNumberAreaWidth(0); + setMode(BROWSE); +} +int CodeEditor::lineNumberAreaWidth() +{ + int digits = 1; + int max = qMax(1, blockCount()); + while (max >= 10) { + max /= 10; + ++digits; + } + + int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits; + + return space; +} + +void CodeEditor::updateLineNumberAreaWidth(int /* newBlockCount */) +{ + setViewportMargins(lineNumberAreaWidth(), 0, 0, 0); +} + +void CodeEditor::updateLineNumberArea(const QRect &rect, int dy) +{ + if (dy) + lineNumberArea->scroll(0, dy); + else + lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height()); + + if (rect.contains(viewport()->rect())) + updateLineNumberAreaWidth(0); +} + +void CodeEditor::resizeEvent(QResizeEvent *e) +{ + QPlainTextEdit::resizeEvent(e); + + QRect cr = contentsRect(); + lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height())); +} +void CodeEditor::highlightCurrentLine() +{ + QList extraSelections; + + if (!isReadOnly()) { + QTextEdit::ExtraSelection selection; + + QColor lineColor = QColor(Qt::yellow).lighter(160); + + selection.format.setBackground(lineColor); + selection.format.setProperty(QTextFormat::FullWidthSelection, true); + //selection.cursor = textCursor(); + //selection.cursor.clearSelection(); + extraSelections.append(selection); + } + + setExtraSelections(extraSelections); +} + +void CodeEditor::lineNumberAreaPaintEvent(QPaintEvent *event) +{ + QPainter painter(lineNumberArea); + painter.fillRect(event->rect(), Qt::lightGray); + + + QTextBlock block = firstVisibleBlock(); + int blockNumber = block.blockNumber(); + int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); + int bottom = top + (int) blockBoundingRect(block).height(); + + while (block.isValid() && top <= event->rect().bottom()) { + if (block.isVisible() && bottom >= event->rect().top()) { + QString number = QString::number(blockNumber + 1); + painter.setPen(Qt::black); + painter.drawText(-2, top, lineNumberArea->width(), fontMetrics().height(), + Qt::AlignRight, number); + } + + block = block.next(); + top = bottom; + bottom = top + (int) blockBoundingRect(block).height(); + ++blockNumber; + } +} +void CodeEditor::setMode(editorMode mode) +{ + if(mode == BROWSE) + { + this->setReadOnly(true); + this->setStyleSheet("background:#f2f2f3;"); + highlightCurrentLine(); + } + else if(mode == EDIT) + { + this->setReadOnly(false); + this->setStyleSheet("background:#ffffff;"); + highlightCurrentLine(); + } +} diff --git a/Client/codeeditor.h b/Client/codeeditor.h new file mode 100644 index 0000000000000000000000000000000000000000..c6cf84e1e65392f882d1a98af0a760842afeeef9 --- /dev/null +++ b/Client/codeeditor.h @@ -0,0 +1,57 @@ +#ifndef CODEEDITOR_H +#define CODEEDITOR_H +#include +#include + +#include +#include +#include +#include +#include +#include +class LineNumberArea; + +class CodeEditor : public QPlainTextEdit +{ + Q_OBJECT + +public: + CodeEditor(QWidget *parent = 0); + void setMode(editorMode mode); + void lineNumberAreaPaintEvent(QPaintEvent *event); + int lineNumberAreaWidth(); + +protected: + void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE; + +private slots: + void updateLineNumberAreaWidth(int newBlockCount); + void highlightCurrentLine(); + void updateLineNumberArea(const QRect &, int); + +private: + QWidget *lineNumberArea; +}; + + +class LineNumberArea : public QWidget +{ +public: + LineNumberArea(CodeEditor *editor) : QWidget(editor) { + codeEditor = editor; + } + + QSize sizeHint() const Q_DECL_OVERRIDE { + return QSize(codeEditor->lineNumberAreaWidth(), 0); + } + +protected: + void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE { + codeEditor->lineNumberAreaPaintEvent(event); + } + +private: + CodeEditor *codeEditor; +}; + +#endif // CODEEDITOR_H diff --git a/Client/databaseoperation.cpp b/Client/databaseoperation.cpp index 8cc1ba375cfb5007daaddbec5eac17a996cd91aa..0bf7392ee3e455e4ce8f72fcbe617f2543295570 100644 --- a/Client/databaseoperation.cpp +++ b/Client/databaseoperation.cpp @@ -103,7 +103,6 @@ QList DatabaseOperation::findAllSessions() { int sessionId = query.value(0).toInt(); QJsonObject json = query.value(1).toJsonObject(); QString sessionName = json.contains("SessionName") ? json["SessionName"].toString() : "None"; - QList members = queryMembersBySession(sessionId); OnlineSession * session = new OnlineSession(sessionId, sessionName, json, members); @@ -314,7 +313,7 @@ OnlineUserModel & ClientDataCenter::getUser(QString username) { } OnlineMessage & ClientDataCenter::getMessage(int SessionId, int MessageId) { - if (_getMessage(SessionId, MessageId)) throw "Not exist"; + if (_getMessage(SessionId, MessageId) == nullptr) throw "Not exist"; return *messages[{SessionId, MessageId}]; } @@ -336,8 +335,8 @@ OnlineSession* ClientDataCenter::_getSession(int SessionId) { } OnlineMessage* ClientDataCenter::_getMessage(int SessionId, int MessageId) { - if (messages.contains({SessionId, MessageId})) - return messages[{SessionId, MessageId}]; + if (messages.contains(QPair({SessionId, MessageId}))) + return messages[QPair({SessionId, MessageId})]; return nullptr; } diff --git a/Client/kuang.cpp b/Client/kuang.cpp index 2fa6da3d7b30d0184e49ee280cefbdc6cde31f84..e054fea15c04a59b4e87da064e2e926536505322 100644 --- a/Client/kuang.cpp +++ b/Client/kuang.cpp @@ -2,6 +2,9 @@ #include "ui_kuang.h" #include #include +#include +#include "clientdatacenter.h" + Kuang::Kuang(QWidget *parent) : QWidget(parent), @@ -23,6 +26,8 @@ Kuang::Kuang(const QString &username,QJsonObject data,QWidget *parent): else { ui->name->setText(temp[0].toObject()["Username"].toString()); } + ui->profile->setPixmap(QPixmap(":/img/system/img/LittleRed.svg")); + } // GROUP @@ -35,10 +40,11 @@ Kuang::Kuang(QJsonObject data,QWidget *parent): } Kuang* Kuang::KuangChosenNow = nullptr; void Kuang::mousePressEvent(QMouseEvent *ev){ + qDebug() << "Mouse Pressed" << ClientDataCenter::Singleton().getSession(SessionID).getLatestMessageID(); if(ev->button()==Qt::LeftButton){ if(!KuangChosenNow || KuangChosenNow != this){ - emit KuangChosenChanged(); KuangChosenNow = this; + emit KuangChosenChanged(); } } } diff --git a/Client/kuang.ui b/Client/kuang.ui index 113ff0c5d708ecb554c98dbf63464f40af349e23..1ccd57fc669c23e73b8e46e3fe48f8c6304e033a 100644 --- a/Client/kuang.ui +++ b/Client/kuang.ui @@ -6,45 +6,115 @@ 0 0 - 200 - 75 + 253 + 70 + + + 253 + 70 + + + + + 253 + 70 + + + + ArrowCursor + + + Qt::ClickFocus + Form + + false + + + QWidget::hover +{ + background-color::rgb(200,198,198); +} + - 10 - 15 + 20 + 10 50 50 + + QLabel +{ + background-color:transparent; +} + - QFrame::Box + QFrame::NoFrame profile + + true + - 70 - 20 - 121 - 41 + 80 + 10 + 161 + 21 + + + Microsoft YaHei + 14 + + + + QLabel +{ + background-color:transparent; +} + - QFrame::Box + QFrame::NoFrame name + + + + 0 + 0 + 253 + 70 + + + + QLabel::hover +{ + background-color:rgb(198,198,198); +} + + + + + + label + profile + name diff --git a/Client/main.cpp b/Client/main.cpp index fde944759c4098da325ced3e8e0e50571e66e0a7..1a1c577fa16bb3700f4bd50a0f14c29be96db41d 100644 --- a/Client/main.cpp +++ b/Client/main.cpp @@ -11,6 +11,7 @@ #include #include + const QString filename = QDir::currentPath() + "/settings.json"; QJsonObject readSettings() { @@ -25,12 +26,19 @@ QJsonObject readSettings() { return QJsonObject(); } +#define DEBUG + int main(int argc, char *argv[]) { QApplication a(argc, argv); +#ifndef DEBUG auto settings = readSettings(); QString ip = settings.contains("Server IP") ? settings["Server IP"].toString() : "127.0.0.1"; int port = settings.contains("Port") ? settings["Port"].toInt() : 8888; +#else + QString ip = "10.194.52.201"; + int port = 8888; +#endif qDebug() << "IP = " << ip << ", port = " << port; ClientMain & client = ClientMain::Singleton(ip, port); diff --git a/Client/mainwindow.cpp b/Client/mainwindow.cpp index c9106a1324be4b2e2660c9ac5abd6597d0817119..e32c1ddf822c3f103c31b2fdb30270b8d41d11c2 100644 --- a/Client/mainwindow.cpp +++ b/Client/mainwindow.cpp @@ -6,6 +6,8 @@ #include #include #include +#include +#include MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), @@ -13,34 +15,25 @@ MainWindow::MainWindow(QWidget *parent) : { ui->setupUi(this); ui->tabWidget->setAttribute(Qt::WA_StyledBackground); - qApp->installEventFilter(this); //为所有控件添加事件过滤器 - - QToolButton *btn = new QToolButton; - btn->setIcon(QPixmap(":/img/system/img/LittlePink.svg")); - btn->setFixedSize(190, 100); - btn->setIconSize(QSize(50, 50)); - btn->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - btn->setText("小粉"); - btn->setAutoRaise(true); - ui->lyFrd->addWidget(btn); - - QToolButton *btn2 = new QToolButton; - btn2->setIcon(QPixmap(":/img/system/img/LittleRed.svg")); - btn2->setIconSize(QSize(190, 100)); - btn2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - btn2->setText("小红"); - btn2->setAutoRaise(true); - ui->lyFrd->addWidget(btn2); - - QToolButton *btn3 = new QToolButton; - btn3->setIcon(QPixmap(":/img/system/img/LittleBlack.svg")); - btn3->setIconSize(QSize(190, 100)); - btn3->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - btn3->setText("小黑"); - btn3->setAutoRaise(true); - ui->lyFrd->addWidget(btn3); - - ui->lyFrd->addStretch(); + + QJsonObject data = {{ "MsgType", "SessionData" }, {"SessionID", 1}, {"SessionType", "FRIEND"} }; + QJsonArray members; + members.append(QJsonObject{{"Username", "小蓝"}}); + members.append(QJsonObject{{"Username", "xxx"}}); + data["Members"]=members; + Kuang *k = new Kuang("小蓝", data, this); + friendlayout = new QVBoxLayout(ui->frd); + friendlayout->setContentsMargins(0,0,0,0); + friendlayout->addWidget(k); + + QToolButton* btnSearch = new QToolButton; + btnSearch->setCursor(Qt::PointingHandCursor);//如果不设置鼠标样式,鼠标移动到按钮上依旧显示为编辑框的鼠标样式 + btnSearch->setIcon(QPixmap(":/img/system/img/search.png")); + btnSearch->setIconSize(QSize(20,20)); + btnSearch->setStyleSheet("QToolButton{border:none;}"); + QWidgetAction* action = new QWidgetAction(ui->search); + action->setDefaultWidget(btnSearch); + ui->search->addAction(action, QLineEdit::TrailingPosition); } MainWindow::~MainWindow() @@ -55,6 +48,8 @@ void MainWindow::dealMessage(Message *messageW, QListWidgetItem *item, QString t item->setSizeHint(size); //设置item基本规格 同widget messageW->setTextContent(text, time, size, type); //设置message基本内容 ui->listWidget->setItemWidget(item, messageW); //将message的内容 在给定的 item中显示 + + ui->listWidget->setCurrentRow(ui->listWidget->count()-1); } void MainWindow::dealMessageTime(QString curMsgTime) @@ -87,32 +82,12 @@ void MainWindow::on_btnSend_clicked() { QString msg = ui->textEdit->toPlainText(); //返回文字 ui->textEdit->setText(""); //清空 - QString time = QString::number(QDateTime::currentDateTime().toTime_t()); //获取当前时间并转为时间戳 - - dealMessageTime(time); //用于处理时间 - Message *messageW = new Message(ui->listWidget->parentWidget()); - QListWidgetItem *item = new QListWidgetItem(ui->listWidget); - dealMessage(messageW, item, msg, time, Message::userMe); emit SendMessageToServer(username, msg); - - //test 用例 - if(ui->listWidget->count()%2) { - bool isSending = true; - if(isSending) { - dealMessageTime(time); - - Message* messageW = new Message(ui->listWidget->parentWidget()); - QListWidgetItem* item = new QListWidgetItem(ui->listWidget); - dealMessage(messageW, item, msg, time, Message::userMe); - } - } else { - if(msg != "") { - dealMessageTime(time); - - Message* messageW = new Message(ui->listWidget->parentWidget()); - QListWidgetItem* item = new QListWidgetItem(ui->listWidget); - dealMessage(messageW, item, msg, time, Message::userOther); - } + QList owners, repos, commits; + int git_mentions = captureGitRepo(msg, owners, repos, commits); + for (int i = 0; i < git_mentions; i++) { + msg = generateGitMessage(owners[i], repos[i], commits[i]); + emit SendMessageToServer(username, msg); } ui->listWidget->setCurrentRow(ui->listWidget->count()-1); @@ -129,7 +104,7 @@ void MainWindow::resizeEvent(QResizeEvent *event) } } //bool MainWindow::eventFilter(QObject *watched, QEvent *event) { - +//用于光标焦点改变 // if(event->type() == QEvent::MouseButtonPress && watched != ui->nickNameShow) // { // ui->nickNameShow->clearFocus(); @@ -147,22 +122,43 @@ MainWindow::MainWindow(QJsonObject data,QWidget *parent): ui->tabWidget->setAttribute(Qt::WA_StyledBackground); friendlayout = new QVBoxLayout(ui->frd); grouplayout = new QVBoxLayout(ui->group); + setup(data); + friendlayout->addStretch(); + grouplayout->addStretch(); +} + +void MainWindow::setup(QJsonObject data) { ui->userNameShow->setText(data["Username"].toString()); username = data["Username"].toString(); ui->nickNameShow->setText(data["Nickname"].toString()); + //搜索框按钮 + QToolButton* btnSearch = new QToolButton; + btnSearch->setCursor(Qt::PointingHandCursor);//如果不设置鼠标样式,鼠标移动到按钮上依旧显示为编辑框的鼠标样式 + btnSearch->setIcon(QPixmap(":/img/system/img/search.png")); + btnSearch->setIconSize(QSize(20,20)); + btnSearch->setStyleSheet("QToolButton{border:none;}"); + QWidgetAction* action = new QWidgetAction(ui->search); + action->setDefaultWidget(btnSearch); + ui->search->addAction(action, QLineEdit::TrailingPosition); } void MainWindow::FriendSessionAdd(QJsonObject data){ + QLayoutItem * lastItem = friendlayout->itemAt(friendlayout->count() - 1); // 头像弹簧 + friendlayout->removeItem(lastItem); Kuang *k = new Kuang(username,data,this); friendlayout->addWidget(k); connect(k,&Kuang::KuangChosenChanged,this,&MainWindow::clearlistview); + friendlayout->addStretch(); } void MainWindow::GroupSessionAdd(QJsonObject data){ + QLayoutItem * lastItem = grouplayout->itemAt(grouplayout->count() - 1); // 头像弹簧 + grouplayout->removeItem(lastItem); Kuang *k = new Kuang(data,this); grouplayout->addWidget(k); connect(k,&Kuang::KuangChosenChanged,this,&MainWindow::clearlistview); + grouplayout->addStretch(); } void MainWindow::clearlistview(){ diff --git a/Client/mainwindow.h b/Client/mainwindow.h index 1df99c6e46b1e8d30939c6b5d8118b975e5404eb..34780b143ad8af87d4299e93a4c2198b2a4035f2 100644 --- a/Client/mainwindow.h +++ b/Client/mainwindow.h @@ -24,14 +24,16 @@ public: explicit MainWindow(QWidget *parent = nullptr); MainWindow(QJsonObject data,QWidget *parent = nullptr); ~MainWindow(); + void setup(QJsonObject data); void FriendSessionAdd(QJsonObject data); void GroupSessionAdd(QJsonObject data); QVBoxLayout *friendlayout; QVBoxLayout *grouplayout; QString username; - //处理信息 void dealMessage(Message *messageW, QListWidgetItem *item, QString text, QString time, Message::UserType type); + //处理搜索框好友显示 + void dealNewFriend(QString text); //处理时间 void dealMessageTime(QString curMsgTime); void AddMessagetoListview(QJsonObject data); @@ -42,6 +44,7 @@ signals: bool eventFilter(QObject *watched, QEvent *event); private slots: void on_btnSend_clicked(); + protected: //重生事件 调整聊天框大小 void resizeEvent(QResizeEvent *event); diff --git a/Client/mainwindow.ui b/Client/mainwindow.ui index d1d49c3949952f32864f65dfd64fd05aa046a7bf..b7b339b35ccb2d31e4a79c9514f11ef7a5344602 100644 --- a/Client/mainwindow.ui +++ b/Client/mainwindow.ui @@ -1,1014 +1,1104 @@ - - - MainWindow - - - - 0 - 0 - 899 - 642 - - - - BICQ - - - - :/img/system/img/bicq.png:/img/system/img/bicq.png - - - 1.000000000000000 - - - QMainWindow -{ - border-radius: 8px; -} - - - - 100 - 100 - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - true - - - QTabWidget{ - background-color:rgb(46,46,46); -} -QTabBar::tab -{ - background-color:rgb(46,46,46); - width:70px; - height:70px; -} - -QTabBar::tab:hover -{ - background-color:rgb(20,33,61); -} - - - - QTabWidget::West - - - QTabWidget::Rounded - - - 3 - - - - 30 - 30 - - - - Qt::ElideNone - - - false - - - false - - - false - - - false - - - - - :/img/system/img/personalOff.png - :/img/system/img/personalOn.png - - - - - - - 个人信息 - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - 700 - 600 - - - - - - 300 - 240 - 231 - 40 - - - - - Microsoft YaHei - 10 - false - - - - QLabel{ - border:1px solid rgb(55,63,85); - border-radius: 8px; - padding-left: 15px; - background-color:rgb(245,245,245); -} - - - QFrame::NoFrame - - - Little_Blue - - - - - - 300 - 300 - 311 - 40 - - - - - Microsoft YaHei - 15 - 75 - true - - - - color: rgb(55, 63, 85); - - - QFrame::NoFrame - - - nick name: - - - - - - 300 - 180 - 241 - 40 - - - - - Microsoft YaHei - 15 - 75 - false - true - - - - color: rgb(55, 63, 85); - - - QFrame::NoFrame - - - user name: - - - Qt::AutoText - - - false - - - false - - - - - - 110 - 240 - 120 - 120 - - - - - - - :/img/system/img/LittleBlue.svg - - - true - - - Qt::AlignCenter - - - - - true - - - - 300 - 350 - 231 - 40 - - - - - Microsoft YaHei - 10 - - - - Qt::ClickFocus - - - 输入昵称 - - - - - - - - - QLineEdit -{ - border:1px solid rgb(55,63,85); - border-radius: 8px; - padding-left: 15px; - background-color:rgb(245,245,245); -} -QLineEdit::hover -{ - border:2px solid rgb(142,202,230); - border-radius: 8px; - padding-left: 15px; - background-color:rgb(245,245,245); -} -QLineEdit::focus -{ - border:2px solid rgb(18,150,219); - border-radius: 8px; - padding-left: 15px; - background-color:rgb(245,245,245); -} - - - 昵称 - - - false - - - - - - - - - - :/system/system/img/message.png - :/img/system/img/messageOff.png - :/img/system/img/messageOn.png:/system/system/img/message.png - - - - - - 聊天 - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 570 - 0 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - 253 - 0 - - - - - 253 - 16777215 - - - - - Microsoft YaHei - 10 - - - - QToolBox { - background:rgb(240,240,240); -} - -QToolBox::tab { - background:rgb(245,245,245); - color:rgb(0,0,0); - border:1px solid black; - border-radius:5px; -} -QToolBox::tab::hover{ - background:rgb(255,255,255); - color:rgb(18,150,219); - border:1px solid black; - border-radius:5px; -} - - - 1 - - - 1 - - - - - 0 - 0 - 100 - 30 - - - - - Microsoft YaHei - 20 - - - - > top session - - - - - - 0 - 0 - 253 - 540 - - - - > friend - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - 0 - 0 - 100 - 30 - - - - > group - - - - - - - - - 0 - 0 - - - - - 370 - 350 - - - - QListWidget -{ -background-color: rgb(245, 245, 245); -color:rgb(51,51,51); -border: 1px solid rgb(245, 245, 245); -outline:0px;} -QListWidget::Item{background-color: rgb(245, 245, 245);} -QListWidget::Item:hover{background-color: rgb(245, 245, 245); } -QListWidget::item:selected{ - background-color: rgb(245, 245, 245); - color:black; - border: 1px solid rgb(245, 245, 245); -} -QListWidget::item:selected:!active{border: 1px solid rgb(245, 245, 245); background-color: rgb(245, 245, 245); color:rgb(51,51,51); } - - - QFrame::NoFrame - - - Qt::ScrollBarAsNeeded - - - Qt::ScrollBarAlwaysOff - - - - - - - - 370 - 30 - - - - - 16777215 - 30 - - - - QFrame::NoFrame - - - QFrame::Plain - - - - - 40 - 0 - 40 - 30 - - - - background-color: rgb(255, 255, 255); - - - - - - - :/img/system/img/git.png:/img/system/img/git.png - - - - 30 - 30 - - - - false - - - true - - - - - - 0 - 0 - 40 - 30 - - - - background-color: rgb(255, 255, 255); - - - - - - - :/img/system/img/face.png:/img/system/img/face.png - - - - 25 - 25 - - - - true - - - false - - - false - - - false - - - true - - - - - - - - - 370 - 150 - - - - - 16777215 - 150 - - - - - Microsoft YaHei - 20 - - - - Qt::ClickFocus - - - QFrame::NoFrame - - - QFrame::Plain - - - - - - - - 0 - 40 - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - 0 - 30 - - - - send - - - Backspace - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 40 - 20 - - - - - - - - - - - - - - - - :/system/system/img/searchOff.png - :/img/system/img/searchOff.png - :/img/system/img/searchOn.png:/system/system/img/searchOff.png - - - - - - 添加好友/群聊 - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - :/img/system/img/search.png:/img/system/img/search.png - - - - 50 - 50 - - - - false - - - true - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - 500 - 40 - - - - - Microsoft YaHei - 10 - - - - Qt::ClickFocus - - - QLineEdit -{ - border:1px solid rgb(55,63,85); - border-radius: 8px; - padding-left: 10px; - background-color:rgb(217,217,217); -} -QLineEdit::hover -{ - border:2px solid rgb(142,202,230); - border-radius: 8px; - padding-left: 10px; - background-color:rgb(217,217,217); -} -QLineEdit::focus -{ - border:2px solid rgb(18,150,219); - border-radius: 8px; - padding-left: 10px; - background-color:rgb(217,217,217); -} - - - - - - 用户名或昵称或群聊ID - - - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 20 - 20 - - - - - - - - - - :/system/system/img/addOff.png - :/img/system/img/addOff.png - :/img/system/img/addOn.png:/system/system/img/addOff.png - - - - - - 创建群聊 - - - - - - :/img/system/img/gitOff.png - :/img/system/img/gitOn.png - - - - - - - Git - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - - - - - - - - Widget - QWidget -
widget.h
- 1 -
-
- - - - -
+ + + MainWindow + + + + 0 + 0 + 899 + 642 + + + + BICQ + + + + :/img/system/img/bicqGreen.png:/img/system/img/bicqGreen.png + + + 1.000000000000000 + + + + + + + 100 + 100 + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + ArrowCursor + + + false + + + QTabWidget{ + background-color:rgb(1,73,124); +} +QTabBar::tab +{ + background-color:rgb(1,73,124); + width:70px; + height:70px; +} + +QTabBar::tab:hover +{ + background-color:rgb(20,33,61); +} + + + + QTabWidget::West + + + QTabWidget::Rounded + + + 0 + + + + 30 + 30 + + + + Qt::ElideNone + + + false + + + false + + + false + + + false + + + + ArrowCursor + + + + :/img/system/img/personalOff.png + :/img/system/img/test.png + + + + + + + 个人信息 + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + 700 + 600 + + + + + + 300 + 240 + 231 + 40 + + + + + Microsoft YaHei + 10 + false + + + + QLabel{ + border:1px solid rgb(55,63,85); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + QFrame::NoFrame + + + Little_Blue + + + + + + 300 + 300 + 311 + 40 + + + + + Microsoft YaHei + 15 + 75 + true + + + + color: rgb(55, 63, 85); + + + QFrame::NoFrame + + + Nickname: + + + + + + 300 + 180 + 241 + 40 + + + + + Microsoft YaHei + 15 + 75 + false + true + + + + color: rgb(55, 63, 85); + + + QFrame::NoFrame + + + Username: + + + Qt::AutoText + + + false + + + false + + + + + + 110 + 240 + 120 + 120 + + + + + + + :/img/system/img/LittleBlue.svg + + + true + + + Qt::AlignCenter + + + + + true + + + + 300 + 350 + 231 + 40 + + + + + Microsoft YaHei + 10 + + + + Qt::ClickFocus + + + 输入昵称 + + + + + + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + 昵称 + + + false + + + + + + + + + ArrowCursor + + + + :/system/system/img/message.png + :/img/system/img/messageOff.png + :/img/system/img/messageOnFinal.png:/system/system/img/message.png + + + + + + 聊天 + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 570 + 0 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 253 + 0 + + + + + 253 + 16777215 + + + + + Microsoft YaHei + 10 + + + + QToolBox { + background:rgb(240,240,240); +} + +QToolBox::tab { + background:rgb(235,235,235); + color:rgb(0,0,0); +} +QToolBox::tab::hover{ + background:rgb(255,255,255); + color:rgb(18,150,219); +} + + + 2 + + + 0 + + + + + 0 + 0 + 253 + 540 + + + + + Microsoft YaHei + 20 + + + + > top session + + + + + + 0 + 0 + 253 + 543 + + + + > friend + + + + + + 0 + 0 + 253 + 543 + + + + > group + + + + + + + + + 0 + 40 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 93 + 30 + + + + + 93 + 30 + + + + + Microsoft YaHei + 10 + + + + PointingHandCursor + + + color: rgb(96,96,96); + + + send + + + Backspace + + + + + + + Qt::Horizontal + + + QSizePolicy::Fixed + + + + 40 + 20 + + + + + + + + + + + + 370 + 150 + + + + + 16777215 + 150 + + + + + Microsoft YaHei + 20 + + + + Qt::ClickFocus + + + QFrame::NoFrame + + + QFrame::Plain + + + + + + + + 0 + 0 + + + + + 370 + 350 + + + + QListWidget +{ +background-color: rgb(245, 245, 245); +color:rgb(51,51,51); +border: 1px solid rgb(245, 245, 245); +outline:0px;} +QListWidget::Item{background-color: rgb(245, 245, 245);} +QListWidget::Item:hover{background-color: rgb(245, 245, 245); } +QListWidget::item:selected{ + background-color: rgb(245, 245, 245); + color:black; + border: 1px solid rgb(245, 245, 245); +} +QListWidget::item:selected:!active{border: 1px solid rgb(245, 245, 245); background-color: rgb(245, 245, 245); color:rgb(51,51,51); } + + + QFrame::NoFrame + + + Qt::ScrollBarAsNeeded + + + Qt::ScrollBarAlwaysOff + + + + + + + + 370 + 30 + + + + + 16777215 + 30 + + + + QFrame::NoFrame + + + QFrame::Plain + + + + + 40 + 0 + 40 + 30 + + + + PointingHandCursor + + + background-color: rgb(255, 255, 255); + + + + + + + :/img/system/img/git.png:/img/system/img/git.png + + + + 30 + 30 + + + + false + + + true + + + + + + 0 + 0 + 40 + 30 + + + + PointingHandCursor + + + background-color: rgb(255, 255, 255); + + + + + + + :/img/system/img/face.png:/img/system/img/face.png + + + + 25 + 25 + + + + false + + + false + + + false + + + false + + + true + + + + + + + + + + + + + :/system/system/img/searchOff.png + :/img/system/img/searchOff.png + :/img/system/img/searchOnFinal.png:/system/system/img/searchOff.png + + + + + + 添加好友/群聊 + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 700 + 300 + + + + + + 100 + 57 + 501 + 171 + + + + +QToolBox +{ + background:rgb(240,240,240); +} + +QToolBox::tab +{ + background:rgb(245,245,245); + color:rgb(0,0,0); + border:1px solid black; + border-radius:9px; +} + + + 0 + + + + + 0 + 0 + 501 + 142 + + + + background-color: transparent; + + + + + + + + + + 100 + 40 + 500 + 40 + + + + + 500 + 40 + + + + + Microsoft YaHei + 10 + + + + Qt::ClickFocus + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 8px; + padding-left: 10px; + background-color:rgb(217,217,217); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 10px; + background-color:rgb(217,217,217); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 10px; + background-color:rgb(217,217,217); +} + + + + + + 用户名或昵称 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + :/system/system/img/addOff.png + :/img/system/img/addOff.png + :/img/system/img/addOnFinal.png:/system/system/img/addOff.png + + + + + + 创建群聊 + + + + + 10 + 80 + 301 + 611 + + + + 0 + + + + + 0 + 0 + 301 + 582 + + + + Page 2 + + + + + + + 380 + 100 + 381 + 591 + + + + 0 + + + + + 0 + 0 + 381 + 562 + + + + Page 2 + + + + + + + 510 + 10 + 93 + 28 + + + + PushButton + + + + + + 150 + 0 + 113 + 21 + + + + + + + + + + + :/img/system/img/gitOff.png + :/img/system/img/gitOnFinal.png + + + + + + + Git + + + + 0 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + + + + + + + + + Widget + QWidget +
widget.h
+ 1 +
+
+ + + + +
diff --git a/Client/message.cpp b/Client/message.cpp index 060b2f9ef4f4f88fd0522bb081c902f07d66d162..c60adfc7d562674e6dcb4fd2de74a22ee737320b 100644 --- a/Client/message.cpp +++ b/Client/message.cpp @@ -166,13 +166,7 @@ void Message::paintEvent(QPaintEvent *event) painter.drawText(m_textLeftRect, m_msg,option);//写文本 } else if(m_userType == UserType::userMe) { // 自己 //头像 - - painter.drawPixmap(m_iconRightRect, m_meRightIcon); - qDebug() << "this->width()" << this->width(); - qDebug() << "x" << m_iconRightRect.x(); - qDebug() << "this->width()" << this->width(); - //框 QColor col_Kuang(75,164,242); painter.setBrush(QBrush(col_Kuang)); diff --git a/Client/messagemodel.cpp b/Client/messagemodel.cpp index cfbc0aeeca72b472d19039502e80b9c331f13e9f..d9b62b3a4bc6ef2f3cc6204783fb34728ac6c24c 100644 --- a/Client/messagemodel.cpp +++ b/Client/messagemodel.cpp @@ -32,7 +32,7 @@ OnlineMessage::OnlineMessage(QJsonObject json, MessageModel * parent) : { messageID = json["MessageID"].toInt(); sessionID = json["SessionID"].toInt(); - senderUsername = json["SenderUsername"].toString(); + senderUsername = json["SenderName"].toString(); QJsonObject body = json["Body"].toObject(); text = body["Text"].toString(); diff --git a/Client/myhighlighter.cpp b/Client/myhighlighter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a997a954a2dee07ad7957fc355f7aa894aadd60 --- /dev/null +++ b/Client/myhighlighter.cpp @@ -0,0 +1,91 @@ +#include "myhighlighter.h" + +MyHighLighter::MyHighLighter(QTextDocument *parent) + : QSyntaxHighlighter(parent) +{ + HighlightingRule rule; + + keywordFormat.setForeground(Qt::darkBlue); + keywordFormat.setFontWeight(QFont::Bold); + QStringList keywordPatterns; + keywordPatterns << "\\bchar\\b" << "\\bclass\\b" << "\\bconst\\b" + << "\\bdouble\\b" << "\\benum\\b" << "\\bexplicit\\b" + << "\\bfriend\\b" << "\\binline\\b" << "\\bint\\b" + << "\\blong\\b" << "\\bnamespace\\b" << "\\boperator\\b" + << "\\bprivate\\b" << "\\bprotected\\b" << "\\bpublic\\b" + << "\\bshort\\b" << "\\bsignals\\b" << "\\bsigned\\b" + << "\\bslots\\b" << "\\bstatic\\b" << "\\bstruct\\b" + << "\\btemplate\\b" << "\\btypedef\\b" << "\\btypename\\b" + << "\\bunion\\b" << "\\bunsigned\\b" << "\\bvirtual\\b" + << "\\bvoid\\b" << "\\bvolatile\\b" <<"\\bdef\\b" + << "\\binclude\\b" << "\\breturn\\b" <<"\\bbreak\\b" + << "\\bcontinue\\b" << "\\bif\\b" <<"\\belse\\b" + << "\\belif\\b" << "\\band\\b" <<"\\bTrue\\b" + << "\\bself\\b" << "\\bnn\\b" <<"\\bimport\\b" + << "\\bin\\b" << "\\bfor\\b" <<"\\bis\\b"; + foreach (const QString &pattern, keywordPatterns) { + rule.pattern = QRegExp(pattern); + rule.format = keywordFormat; + highlightingRules.append(rule); + } + classFormat.setFontWeight(QFont::Bold); + classFormat.setForeground(Qt::darkMagenta); + rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b"); + rule.format = classFormat; + highlightingRules.append(rule); + + singleLineCommentFormat.setForeground(Qt::red); + rule.pattern = QRegExp("//[^\n]*"); + rule.format = singleLineCommentFormat; + highlightingRules.append(rule); + + multiLineCommentFormat.setForeground(Qt::red); + + quotationFormat.setForeground(Qt::darkGreen); + rule.pattern = QRegExp("\".*\""); + rule.format = quotationFormat; + highlightingRules.append(rule); + + functionFormat.setFontItalic(true); + functionFormat.setForeground(Qt::blue); + rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()"); + rule.format = functionFormat; + highlightingRules.append(rule); + + commentStartExpression = QRegExp("/\\*"); + commentEndExpression = QRegExp("\\*/"); +} + +void MyHighLighter::highlightBlock(const QString &text) +{ + foreach (const HighlightingRule &rule, highlightingRules) { + QRegExp expression(rule.pattern); + int index = expression.indexIn(text); + while (index >= 0) { + int length = expression.matchedLength(); + setFormat(index, length, rule.format); + index = expression.indexIn(text, index + length); + } + } + + setCurrentBlockState(0); + + int startIndex = 0; + if (previousBlockState() != 1) + startIndex = commentStartExpression.indexIn(text); + + + while (startIndex >= 0) { + int endIndex = commentEndExpression.indexIn(text, startIndex); + int commentLength; + if (endIndex == -1) { + setCurrentBlockState(1); + commentLength = text.length() - startIndex; + } else { + commentLength = endIndex - startIndex + + commentEndExpression.matchedLength(); + } + setFormat(startIndex, commentLength, multiLineCommentFormat); + startIndex = commentStartExpression.indexIn(text, startIndex + commentLength); + } +} diff --git a/Client/myhighlighter.h b/Client/myhighlighter.h new file mode 100644 index 0000000000000000000000000000000000000000..edd2c7acff24ab2f830b9302588bb1a715834025 --- /dev/null +++ b/Client/myhighlighter.h @@ -0,0 +1,36 @@ +#ifndef MYHIGHLIGHTER_H +#define MYHIGHLIGHTER_H +#include +#include +#include +class MyHighLighter : public QSyntaxHighlighter +{ + Q_OBJECT + +public: + MyHighLighter(QTextDocument *parent = 0); + +protected: + void highlightBlock(const QString &text) Q_DECL_OVERRIDE; + +private: + struct HighlightingRule + { + QRegExp pattern; + QTextCharFormat format; + }; + QVector highlightingRules; + + QRegExp commentStartExpression; + QRegExp commentEndExpression; + + QTextCharFormat keywordFormat; + QTextCharFormat classFormat; + QTextCharFormat singleLineKey; + QTextCharFormat singleLineValue; + QTextCharFormat singleLineCommentFormat; + QTextCharFormat multiLineCommentFormat; + QTextCharFormat quotationFormat; + QTextCharFormat functionFormat; +}; +#endif // MYHIGHLIGHTER_H diff --git a/Client/system.qrc b/Client/system.qrc index b861af6d26168169658b0e2c62183dd77fcab72b..97afe8bee04ecdfbe01bd853a694a28c78a44b06 100644 --- a/Client/system.qrc +++ b/Client/system.qrc @@ -21,5 +21,15 @@ system/img/LittleBlack.svg system/img/LittlePink.svg system/img/LittleRed.svg + system/img/bicqWhite.png + system/img/gitWhite.png + system/img/test.png + system/img/bicqBlue.png + system/img/bicqGreen.png + system/img/dot.png + system/img/addOnFinal.png + system/img/gitOnFinal.png + system/img/messageOnFinal.png + system/img/searchOnFinal.png diff --git a/Client/system/img/addOnFinal.png b/Client/system/img/addOnFinal.png new file mode 100644 index 0000000000000000000000000000000000000000..cc83baf29100e997df66e5120b5b52891d3d3f6d Binary files /dev/null and b/Client/system/img/addOnFinal.png differ diff --git a/Client/system/img/bicqBlue.png b/Client/system/img/bicqBlue.png new file mode 100644 index 0000000000000000000000000000000000000000..9ce6ec252f5827ebb95597ff3eaeda6f75dbbad4 Binary files /dev/null and b/Client/system/img/bicqBlue.png differ diff --git a/Client/system/img/bicqGreen.png b/Client/system/img/bicqGreen.png new file mode 100644 index 0000000000000000000000000000000000000000..b397cf3973590bbbf4db818ab89ac263718e64f4 Binary files /dev/null and b/Client/system/img/bicqGreen.png differ diff --git a/Client/system/img/bicqWhite.png b/Client/system/img/bicqWhite.png new file mode 100644 index 0000000000000000000000000000000000000000..e789c8fab18531e15d1586f8abccfe855c5d71c9 Binary files /dev/null and b/Client/system/img/bicqWhite.png differ diff --git a/Client/system/img/dot.png b/Client/system/img/dot.png new file mode 100644 index 0000000000000000000000000000000000000000..b68fe73d89f5c3f6b59139dde5f56e047c195fe5 Binary files /dev/null and b/Client/system/img/dot.png differ diff --git a/Client/system/img/gitOnFinal.png b/Client/system/img/gitOnFinal.png new file mode 100644 index 0000000000000000000000000000000000000000..19befd4892b87be487f278b5384884d2000086cc Binary files /dev/null and b/Client/system/img/gitOnFinal.png differ diff --git a/Client/system/img/gitWhite.png b/Client/system/img/gitWhite.png new file mode 100644 index 0000000000000000000000000000000000000000..e0851f766146608826f56de946a62fe43c053c25 Binary files /dev/null and b/Client/system/img/gitWhite.png differ diff --git a/Client/system/img/messageOnFinal.png b/Client/system/img/messageOnFinal.png new file mode 100644 index 0000000000000000000000000000000000000000..6915ce31f1f304421d841dda5dc5dedeb02c1a41 Binary files /dev/null and b/Client/system/img/messageOnFinal.png differ diff --git a/Client/system/img/searchOnFinal.png b/Client/system/img/searchOnFinal.png new file mode 100644 index 0000000000000000000000000000000000000000..c0318459e7a69404a89f2ed137e0ebb78c8d73ed Binary files /dev/null and b/Client/system/img/searchOnFinal.png differ diff --git a/Client/system/img/test.png b/Client/system/img/test.png new file mode 100644 index 0000000000000000000000000000000000000000..560ecc55412835dd6a3142ed498017745391552f Binary files /dev/null and b/Client/system/img/test.png differ diff --git a/Client/typedef.h b/Client/typedef.h new file mode 100644 index 0000000000000000000000000000000000000000..499a81de8b6ce134d796e5ac8edf652ecfe7b9b6 --- /dev/null +++ b/Client/typedef.h @@ -0,0 +1,10 @@ +#ifndef TYPEDEF_H +#define TYPEDEF_H + +typedef enum{ + BROWSE, + EDIT, +}editorMode; + + +#endif // TYPEDEF_H diff --git a/Client/userlogin.cpp b/Client/userlogin.cpp index ceb6ff0839336960c2933ee5837de1942de3e243..719280a6eda1827ebb1e47cf5b7a36b9efc3d595 100644 --- a/Client/userlogin.cpp +++ b/Client/userlogin.cpp @@ -21,15 +21,23 @@ UserLogin::UserLogin(QWidget *parent) //点击注册跳转到注册页面 connect(ui->btnRegister,&QPushButton::clicked,[=](){ this->hide(); - emit registerButtonClicked(); }); - +//#define UIDEBUG +#ifndef UIDEBUG //点击登录发送登录信息 connect(ui->btnLogIn,&QPushButton::clicked,[=](){ QJsonObject login = { {"MsgType","LogIn"},{"Username",ui->lineEditUserName->text()},{"Password",ui->lineEditPassword->text()}}; emit sendlogindata(login); }); +#else + //调试入口 + connect(ui->btnLogIn, &QPushButton::clicked,[=](){ + MainWindow *main = new MainWindow(); + main->show(); + }); +#endif + // main = new MainWindow(this); } void UserLogin::loginconfirm(QJsonObject data){ diff --git a/Client/userlogin.h b/Client/userlogin.h index fd5a40e495470199b0bceb78143b7503f42a5fba..8b1312730314cf2905bcf3b3dc2cf44d0f68bb2f 100644 --- a/Client/userlogin.h +++ b/Client/userlogin.h @@ -24,6 +24,8 @@ signals: void registerButtonClicked(); void sendlogindata(QJsonObject data); void createMainWindow(QJsonObject data); +private slots: + private: Ui::UserLogin *ui; }; diff --git a/Client/userlogin.ui b/Client/userlogin.ui index 7131e2e7f85e765bf0f682e5d4193e801b028675..4da7a6ec3ecc9cf8cfe8084a5c0cd32fa4a5b23b 100644 --- a/Client/userlogin.ui +++ b/Client/userlogin.ui @@ -6,250 +6,340 @@ 0 0 - 400 - 300 + 430 + 700 - 400 - 300 + 430 + 700 - 400 - 300 + 430 + 700 UserLogin - - - - - - - - - - - QLineEdit::Password - - - - - - - 用户名 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - 密码 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Vertical - - - QSizePolicy::Fixed - - - - 20 - 10 - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - 登录 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - 注册 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - + + + :/img/system/img/bicqGreen.png:/img/system/img/bicqGreen.png + + + + + + background-color: rgb(255, 255, 255); + + + + + 165 + 50 + 100 + 100 + + + + + 100 + 100 + + + + + 100 + 100 + + + + + + + + + + :/img/system/img/bicq.png + + + true + + + + + + 25 + 610 + 381 + 50 + + + + + Microsoft YaHei + 10 + false + false + + + + PointingHandCursor + + + QPushButton{ + color: rgb(0,0,0); + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(255,255,255); +} +QPushButton::hover{ + color: rgb(0,0,0); + border:3px solid rgb(1,73,124); + border-radius: 10px; +} + + + + Don't have an acount? Register for FREE. + + + false + + + false + + + false + + + + + + 15 + 240 + 400 + 331 + + + + QWidget{ + + border-radius: 20px; + background-color:rgb(246,248,250); +} + + + + + 20 + 30 + 141 + 31 + + + + + Microsoft YaHei + 13 + + + + Username + + + + + + 20 + 70 + 360 + 50 + + + + + 0 + 50 + + + + + Microsoft YaHei + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 10px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + + + + 20 + 140 + 111 + 37 + + + + + Microsoft YaHei + 13 + + + + Password + + + + + + 20 + 180 + 360 + 50 + + + + + 0 + 50 + + + + + Microsoft YaHei + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + QLineEdit::Password + + + + + + 20 + 250 + 360 + 53 + + + + + 0 + 53 + + + + + Microsoft YaHei + 16 + + + + PointingHandCursor + + + QPushButton{ + + color: rgb(255, 255, 255); + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(1,73,124); +} +QPushButton::hover{ + + color: rgb(255, 255, 255); + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(18,150,219); +} + + + Sign In + + + + 20 + 20 + + + + + + + + 110 + 170 + 201 + 51 + + + + + Microsoft YaHei + 16 + + + + QLabel +{ + color: rgb(18,150,219); +} + + + Sign In to BICQ + + - + + + diff --git a/Client/usermodel.h b/Client/usermodel.h index ccb7ab9ce1a89949e47833aae52e30afa3012b77..91b28302a7faadfd2e9b6fdc5d952b5d58a2047d 100644 --- a/Client/usermodel.h +++ b/Client/usermodel.h @@ -31,7 +31,7 @@ public: OfflineUserModel(QString Username, QObject *parent = nullptr); Type getType() const { return Type::Offline; } void setNickname(QString nname) { nickname = nname; } - void setSigniture(QString sig) { profile["Signiture"] = sig; } + void setSigniture(QString sig) { profile["signiture"] = sig; } QJsonObject generateUserModelJson() const; @@ -49,7 +49,7 @@ public: OnlineUserModel(QString usrname, QString nick, QJsonObject json, QObject * parent = nullptr); Type getType() const { return Type::Online; } const QString& getNickname() const { return nickname; } - const QString getSigniture() const { return profile["Signiture"].toString(); } + const QString getSigniture() const { return profile["signiture"].toString(); } QJsonObject generateUserModelJson() const; signals: diff --git a/Client/userregister.ui b/Client/userregister.ui index 4e1ef100d14c5702c2cafe0599f2a6ac1ad1b392..dbaabbfd7bbecade2b035ce55ca8f35d320c2ac0 100644 --- a/Client/userregister.ui +++ b/Client/userregister.ui @@ -6,95 +6,493 @@ 0 0 - 400 - 300 + 430 + 700 - 400 - 300 + 430 + 700 - 400 - 300 + 430 + 700 - Form + UserRegister + + + + :/img/system/img/bicqGreen.png:/img/system/img/bicqGreen.png + + + - 90 - 70 - 226 - 128 + 15 + 210 + 400 + 391 - - - - - 用户名 - - - - - - - - - - 昵称 - - - - - - - QLineEdit::Password - - - - - - - 密码 - - - - - - - - - - 确认密码 - - - - - - - + + QWidget{ + + border-radius: 20px; + background-color:rgb(246,248,250); +} + + + + + 20 + 5 + 121 + 31 + + + + + Microsoft YaHei + 13 + + + + Username + + + + + + 20 + 40 + 360 + 50 + + + + + Microsoft YaHei + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 10px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + + + + 20 + 90 + 161 + 31 + + + + + Microsoft YaHei + 13 + + + + Nickname + + + + + + 20 + 130 + 360 + 50 + + + + + Microsoft YaHei + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 10px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + QLineEdit::Normal + + + + + + 20 + 200 + 131 + 31 + + + + + Microsoft YaHei + 13 + + + + Password + + + + + + 20 + 240 + 360 + 50 + + + + + Microsoft YaHei + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 10px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + QLineEdit::Password + + + + + + 20 + 310 + 360 + 50 + + + + + Microsoft YaHei + + + + QLineEdit +{ + border:1px solid rgb(55,63,85); + border-radius: 10px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::hover +{ + border:2px solid rgb(142,202,230); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} +QLineEdit::focus +{ + border:2px solid rgb(18,150,219); + border-radius: 8px; + padding-left: 15px; + background-color:rgb(245,245,245); +} + + + QLineEdit::Password + + + Confirm Password + + - 170 - 220 - 84 - 24 + 25 + 630 + 381 + 50 + + + + + Microsoft YaHei + 16 + + + + PointingHandCursor + + + QPushButton{ + + color: rgb(255, 255, 255); + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(1,73,124); +} +QPushButton::hover{ + + color: rgb(255, 255, 255); + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(18,150,219); +} + + + Sign Up + + + + + + 50 + 60 + 100 + 100 - 注册 + + + + :/img/system/img/LittleBlue.svg + + + true + + + + + + 160 + 50 + 231 + 51 + + + + + Microsoft YaHei + 16 + + + + QLabel +{ + color: rgb(18,150,219); +} + + + Sign Up to + + + + + + 163 + 103 + 20 + 20 + + + + + 20 + 20 + + + + + 10 + 10 + + + + QLabel +{ + background-color:transparent; +} + + + + + + :/img/system/img/dot.png + + + true + + + + + + 174 + 96 + 20 + 20 + + + + + 20 + 20 + + + + + 10 + 10 + + + + QLabel +{ + background-color:transparent; +} + + + + + + :/img/system/img/dot.png + + + true + + + + + + 150 + 106 + 20 + 20 + + + + + 20 + 20 + + + + + 10 + 10 + + + + QLabel +{ + background-color:transparent; +} + + + + + + :/img/system/img/dot.png + + + true + + + + + + 303 + 46 + 101 + 51 + + + + + Microsoft YaHei + 20 + 75 + true + + + + QLabel +{ + color: rgb(18,150,219); +} + + + BICQ - + + + diff --git a/Client/widget.cpp b/Client/widget.cpp index 75a737c1e8c53ec30b2f6373738e55a55a665428..e14925656c045d6c899610ff606319e6a04f8158 100644 --- a/Client/widget.cpp +++ b/Client/widget.cpp @@ -1,19 +1,25 @@ #include "widget.h" #include "ui_widget.h" -#include "highlighter.h" #include #include #include #include #include #include +#include +#include "myhighlighter.h" +#include "codeeditor.h" +#include "typedef.h" +#include Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); - + configEditor = new CodeEditor(); + configEditor->setMode(BROWSE); + ui->gridLayout_3->addWidget(configEditor); connect (ui->listWidget, &QListWidget::itemDoubleClicked, this, &Widget::showContents); } @@ -26,7 +32,9 @@ Widget::~Widget() void Widget::on_pushButton_clicked() { - QByteArray file = get(ui->lineEdit->text ()); + QString giturl = "https://gitee.com/api/v5/repos/" + ui->lineEdit->text() + "/" + + ui->lineEdit_2->text() + "/git/trees/master"; + QByteArray file = get(giturl); QJsonDocument newjson = QJsonDocument::fromJson(file); QJsonObject jsonObject = newjson.object (); @@ -58,14 +66,20 @@ void Widget::showContents(QListWidgetItem * nowItem) { QJsonValue iconArray = array.at(i); QJsonObject icon = iconArray.toObject(); + if(icon["path"].toString ()==nowItem->text ()) { QByteArray content = get(icon["url"].toString ()); QJsonDocument newjson = QJsonDocument::fromJson(content); QJsonObject jsonObject = newjson.object (); - ui->textEdit->setText ( QByteArray::fromBase64(jsonObject["content"].toString ().toUtf8 ())); - Highlighter * h = new Highlighter(ui->textEdit->document ()); + configEditor->setPlainText(QByteArray::fromBase64(jsonObject["content"].toString ().toUtf8 ()).data ()); + //ui->gridLayout->addWidget(configEditor); + QString text = "def hhh()"; + MyHighLighter *highlighter = new MyHighLighter(configEditor->document()); + + //Highlighter * h = new Highlighter(ui->textEdit->document ()); + } } @@ -75,3 +89,62 @@ void Widget::showContents(QListWidgetItem * nowItem) // git commit try at: https://gitee.com/api/v5/repos/jasonliu233/gitstudy/commits/master // git tree at: https://gitee.com/api/v5/repos/jasonliu233/zhishigongcheng/git/trees/master +int captureGitRepo(QString raw, QList &authors, QList &repos, QList &commits) { + QRegExp reg("@\\[((?:[^ ,\\,])+),[ ]*((?:[^ ,\\,])+)(?:,[ ]*((?:[^ ,\\,])*))?\\]"); + int pos = 0, initial = authors.size(); + while ((pos = reg.indexIn(raw, pos)) != -1) { + authors.append(reg.cap(1)); + repos.append(reg.cap(2)); + commits.append(reg.cap(3) == "" ? "master" : reg.cap(3)); + pos += reg.matchedLength(); + } + return authors.size() - initial; +} + +QByteArray get(const QString &str_url){ + const QUrl url = QUrl::fromUserInput(str_url); + QNetworkRequest qnr(url); + QNetworkAccessManager qnam; + QNetworkReply *reply = qnam.get(qnr); + QEventLoop eventloop; + QObject::connect(reply, &QNetworkReply::finished, &eventloop, &QEventLoop::quit); + eventloop.exec(QEventLoop::ExcludeUserInputEvents); + QByteArray reply_data = reply->readAll(); + reply->deleteLater(); + reply = nullptr; + return reply_data; +} + +QString generateGitMessage(QString owner, QString repo, QString sha) { + QString url = "https://gitee.com/api/v5/repos/"+owner+"/"+repo+"/"+"commits"+"/"+sha; + + QByteArray file = get(url); + + QJsonDocument newjson = QJsonDocument::fromJson(file); + QJsonObject jsonObject = newjson.object (); + + QString output; + QString msg = jsonObject["commit"].toObject ()["message"].toString (); + QString author = jsonObject["commit"].toObject ()["author"].toObject ()["name"].toString (); + QString commitInformation = "提交信息 git@gitee:" + owner + "/" + repo + "\n" + msg+"by "+author + "\n"; + + output.append (commitInformation); + QJsonArray fileList = jsonObject["files"].toArray (); + for(int i=0;i #include #include +#include + QT_BEGIN_NAMESPACE namespace Ui { class Widget; } @@ -42,5 +44,10 @@ private slots: private: Ui::Widget *ui; QJsonValue arrayValue; + CodeEditor *configEditor; }; + + +int captureGitRepo(QString raw, QList &authors, QList &repos, QList &commits); +QString generateGitMessage(QString owner, QString repo, QString sha); #endif // WIDGET_H diff --git a/Client/widget.ui b/Client/widget.ui index 0ea2faa3d57551204036f9e444f1a25b2c3140a9..9613d09c320990752c733a91e57dc5f7e076359b 100644 --- a/Client/widget.ui +++ b/Client/widget.ui @@ -107,17 +107,28 @@ QLineEdit::focus 80 + + PointingHandCursor + - background-color: rgb(46,46,46); + QPushButton{ + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(22,138,173); +} +QPushButton::hover{ + + border:1px solid rgb(55,63,85); + border-radius: 10px; + background-color:rgb(18,150,219); +} - - :/img/system/img/gitBtnOff.png - :/img/system/img/gitBtnOn.png - + + :/img/system/img/gitWhite.png:/img/system/img/gitWhite.png @@ -214,22 +225,6 @@ border-style: solid; - - - - - Microsoft Yi Baiti - 12 - - - - background-color: rgb(245, 245, 245); - - - QFrame::NoFrame - - - @@ -279,8 +274,17 @@ border-style: solid; + + + + 0 + + + - + + + diff --git a/README.md b/README.md index 0d2acb40a07fa75cbe5ccae2c26ed5953387b688..73f5ad59d68677681561bc041ab0e57b570fe811 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,19 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework 1. 类名、文件名使用大驼峰命名法,函数名使用小驼峰命名法 2. 仓库在 master 和 Develop 分支上设置了保护,一般工作在feature分支上,如果是可以独立开发的模块,强烈建议单独拉一条新分支出来。每个 working state 会合并到 Develop 分支,release 版本合并到 master 分支 +```json +{ + "MsgType": "JsonArray", + "MsgList": [ + { ... }, + { ... }, + { ... }, + ] +} + +``` + + ### 注册信息 ``` json @@ -48,7 +61,6 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework } } ``` - ``` json { "MsgType": "LogInConfirm", @@ -56,6 +68,38 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework } } ``` +### 搜索消息 + + ``` json + { + "MsgType": "Search", + "SearchInfo": "..." + } + ``` + + ``` json + { + "MsgType": "SearchInfo", + "SearchInfo": [ + { "UserName": "...", "NickName": "..." }, + { "UserName": "...", "NickName": "..." }, + ... + { "UserName": "...", "NickName": "..." } + ] + } + ``` +### 新建群组消息 + ``` json + { + "MsgType": "NewGroup", + "SessionName":"..." + "Members": [ + { "username": "..." }, + { "username": "..." }, + { "username": "..." }, + ], + } + ``` ### 登录后服务端行为 首先发送 LogInConfirm @@ -67,12 +111,8 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework ``` json { "MsgType": "MessageSyncCode", - "Sessions": [ - { "SessionID": 1, "Latest Message ID": 123 }, - { "SessionID": ..., "Latest Message ID": ... }, - ... - { "SessionID": ..., "Latest Message ID": ... } - ] + "SessionID": 1, + "Latest Message ID": 123 } ``` @@ -86,7 +126,7 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework "Username": "...", "Nickname": "...", "Profile" : { - "Signiture" : "...", + "signiture" : "...", "..." : "...", } } @@ -100,13 +140,11 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework "MsgType": "SessionData", "SessionID": 111, "SessionType": "FRIEND", - "Latest Message ID":123 "Members": [ { "Username": "..." }, { "Username": "..." }, ], "Profile": [ - "CreatedTime": "yyyy-mm-dd", "LatestMessageID": ..., ] } @@ -126,7 +164,6 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework ], "Profile": { "SessionName": "...", - "CreatedTime": "yyyy-mm-dd", "LatestMessageID": ..., } } @@ -153,8 +190,6 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework "Body": { "Text": "...", "Profile": { - "hasMentionInfo": false, - "ReadMark": true / false, "...": "...", } } @@ -163,23 +198,6 @@ BIT ICQ, a Realtime Communicating Solution using C++ Qt framework - 注:客户端向服务器发送时没有 "MessageID" -消息版本列表 -``` json -{ - "MsgType": "MessageVersion", - "Data": [ - { - "SessionID": ..., - "LatestMessageID": ... - }, - { - "SessionID": ..., - "LatestMessageID": ... - }, - ... - ] -} -``` #### 软件架构 软件架构说明 diff --git a/Server/Session/onlinesession.cpp b/Server/Session/onlinesession.cpp index 10aa549b250e439e43296a03b0bf2a0e7dd33be3..4b6595ba588e0029fac21f4ae8cc676f294ec899 100644 --- a/Server/Session/onlinesession.cpp +++ b/Server/Session/onlinesession.cpp @@ -1,8 +1,7 @@ #include "onlinesession.h" #include -OnlineSession::OnlineSession(QJsonObject &json, AbstractSession * parent) : - QObject(parent) +OnlineSession::OnlineSession(QJsonObject &json) { loadDataFromJson(json); } @@ -11,7 +10,6 @@ void OnlineSession::loadDataFromJson(const QJsonObject &json) { id = json["SessionID"].toInt(); loadUsersFromJson(json); - qDebug() << "debug" ; Profile = json["Profile"].toObject(); if ((getSessionType() == SessionType::GROUP && json["SessionType"] == "GROUP") || (getSessionType() == SessionType::FRIEND && json["SessionType"] == "FRIEND") ) @@ -25,8 +23,8 @@ void OnlineSession::loadDataFromJson(const QJsonObject &json) } else { qDebug() << "load error" ; - throw "load error"; } + latest = Profile["LatestMessageID"].toInt(); } const QString& OnlineSession::getSessionName() const { @@ -52,11 +50,13 @@ QJsonObject OnlineSession::generateJsonFromData() const { ret["MsgType"] = "SessionData"; ret["SessionID"] = id; ret["SessionType"] = getSessionType() == SessionType::GROUP ? "GROUP" : "FRIEND"; + Profile["LatestMessageID"] = latest; ret["Profile"] = Profile; + QJsonArray userlist; for (int i = 0; i < members.size(); i++) { QJsonObject tmp; - tmp["username"] = members.at(i); + tmp["Username"] = members.at(i); userlist.append(tmp); } ret["Members"] = userlist; diff --git a/Server/Session/onlinesession.h b/Server/Session/onlinesession.h index 5a37a8c4c7436ae6611ee20b742c9389561ab567..877e081eb93353cd1c2e2cf6d08876bcf19e1750 100644 --- a/Server/Session/onlinesession.h +++ b/Server/Session/onlinesession.h @@ -9,18 +9,20 @@ class OnlineSession: public AbstractSession Q_OBJECT public: - OnlineSession(QJsonObject &json, AbstractSession * parent = nullptr); + OnlineSession(QJsonObject &json); OnlineSession(int sessionID, QString sessionName, QJsonObject profile, UserContainer Users) { id = sessionID, SessionName = sessionName, Profile = profile, members = Users; + latest = profile["LatestMessageID"].toInt(); } int getSessionID() const { return id; } const QString& getSessionName() const; + int & getLatestMessageID() { return latest; } const QJsonObject& getProfile() const { return Profile; } QJsonObject generateJsonFromData() const; private: - int id; + int id, latest; QString SessionName; QJsonObject Profile; diff --git a/Server/databaseoperation.cpp b/Server/databaseoperation.cpp index 6e48e953aef8e6e357206544301353393df938b0..abc493de6896a9bd6165f2c41c92f838b2b14a89 100644 --- a/Server/databaseoperation.cpp +++ b/Server/databaseoperation.cpp @@ -1,396 +1,414 @@ -#include -#include -#include -#include -#include - -#include "databaseoperation.h" - -QString json2str(QJsonObject json) { - return QString(QJsonDocument(json).toJson()); -} - -QJsonObject str2json(QString str) { - QJsonDocument jsonDoc = QJsonDocument::fromJson(str.toUtf8().data()); - if (jsonDoc.isNull()) { - qDebug() << "read json obj from str failed: str = " << str.toLocal8Bit().data(); - } - return jsonDoc.object(); -} - -DatabaseOperation::DatabaseOperation(QObject *parent) : QObject(parent) -{ - status = Status::Stop; -} - -void DatabaseOperation::startDatabaseConnection(QString dbfilename) { - if (status != Status::Stop) { - qDebug() << "db server already running..."; - throw "Already running error"; - } - QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); - db.setDatabaseName(dbfilename); //如果本目录下没有该文件,则会在本目录下生成,否则连接该文件 - if (!db.open()) { - qDebug() << db.lastError().text(); - throw "Database Error"; - } - status = Status::Running; - createTables(); - findAllUsers(); - findAllSessions(); - findAllMessages(); - emit signal_DB_ready(); -} - -void DatabaseOperation::executeSqlStatement(QString str) { - QSqlQuery query (str); - if (!query.isActive()) { - qDebug() << query.lastError(); - } -} - -void DatabaseOperation::createTables() { - executeSqlStatement("CREATE TABLE User(Username TEXT PRIMARY KEY, Nickname TEXT NOT NULL, Password TEXT NOT NULL, Profile TEXT)"); - executeSqlStatement("CREATE TABLE Session(SessionID INT PRIMARY KEY, SessionType TEXT NOT NULL, Profile TEXT)"); - executeSqlStatement("CREATE TABLE Message(SessionID INT NOT NULL, MessageID INT NOT NULL, SenderUsername TEXT NOT NULL, MessageText TEXT NOT NULL, Profile TEXT, PRIMARY KEY(SessionID, MessageID), FOREIGN KEY(SessionID) REFERENCES Session(SessionID), FOREIGN KEY(SenderUserName) REFERENCES User(Username))"); - executeSqlStatement("CREATE TABLE IsMember(SessionID INT NOT NULL, Username TEXT NOT NULL, PRIMARY KEY (Username, SessionID), FOREIGN KEY (Username) REFERENCES User(username), FOREIGN KEY (SessionID) REFERENCES Session(SessionID))"); -} - -bool DatabaseOperation::isDBExist(QString dbfilename) const { - QFileInfo file(dbfilename); - return file.exists(); -} - -void DatabaseOperation::closeDB() { - if (status != Status::Running) throw "already closed"; - database.close(); - - status = Status::Stop; - emit signal_DBstop(); -} - -QList DatabaseOperation::findAllUsers() { - QList ret; - QSqlQuery sqlQuery; - sqlQuery.exec("SELECT Username, Nickname, Password, Profile FROM User"); - if(!sqlQuery.exec()) { - qDebug() << "Error: Fail to query table. " << sqlQuery.lastError(); - throw "DB read error"; - } - else { - auto & dcenter = ServerDataCenter::Singleton(); - while(sqlQuery.next()) { - QString username = sqlQuery.value(0).toString(); - QString nickname = sqlQuery.value(1).toString(); - QString profile = sqlQuery.value(3).toString(); - auto newuser = new OnlineUserModel(username, nickname, str2json(profile)); - dcenter.registerUser(newuser); - ret.append(newuser); - } - } - return ret; -} - -QList DatabaseOperation::findAllSessions() { - QList ret; - QSqlQuery query; - if (!query.exec("SELECT SessionID, Profile FROM Session")) { - qDebug() << "findAllSessions: " << query.lastError(); - throw "DB read error"; - } - auto & dcenter = ServerDataCenter::Singleton(); - while (query.next()) { - int sessionId = query.value(0).toInt(); - QJsonObject json = query.value(1).toJsonObject(); - QString sessionName = json.contains("SessionName") ? json["SessionName"].toString() : "None"; - - QList members = queryMembersBySession(sessionId); - - OnlineSession * session = new OnlineSession(sessionId, sessionName, json, members); - ret.append(session); - dcenter.registerSession(session); - } - return ret; -} - -QList DatabaseOperation::findAllMessages() { - QList ret; - QSqlQuery query; - if (!query.exec("SELECT SessionID, MessageID, senderUsername, MessageText, Profile FROM messages")) { - while (query.next()) { - int sessionID = query.value(0).toInt(); - int msgId = query.value(1).toInt(); - QString sender = query.value(2).toString(); - QString text = query.value(3).toString(); - QJsonObject profile = query.value(4).toJsonObject(); - - auto * msg = new OnlineMessage(msgId, sessionID, sender, text, profile); - ret.append(msg); - ServerDataCenter::Singleton().registerMessage(msg); - } - } - return ret; -} - - -//往User表中插入数据 -bool DatabaseOperation::insertUser(const char* username, const char* nickname, const char* password, const char* profile){ - QSqlQuery query; -// QString insert_sql = "insert into User(Username, Nickname, Password, Profile) values (?, ?, ?, ?)"; - QString insert_sql = QString("INSERT INTO User(Username, Nickname, Password, Profile) VALUES ('%1', '%2', '%3', '%4')") - .arg(username).arg(nickname).arg(password).arg(profile); - qDebug() << insert_sql; -// query.prepare(insert_sql); -// query.addBindValue(username); -// query.addBindValue(nickname); -// query.addBindValue(password); -// query.addBindValue(profile); - if (! query.exec(insert_sql) ) { - qDebug() << query.lastError(); - return false; - } - ServerDataCenter::Singleton().registerUser(new OnlineUserModel( - QString(username), QString(nickname), str2json(QString(profile)) )); - return true; -} - -bool DatabaseOperation::insertUser(const OnlineUserModel &user, const QString &password) { - return insertUser(user.getUsername().toUtf8().data(), - user.getNickname().toUtf8().data(), - password.toUtf8().data(), - json2str(user.getProfile()).toUtf8().data()); -} - - - -int DatabaseOperation::getTableCount(const char * tableName) const { - QSqlQuery query; - QString sql = QString("SELECT COUNT(*) FROM %1").arg(tableName); - query.addBindValue(tableName); - if (!query.exec(sql)) { - qDebug() << query.lastError(); - return -1; - } - if (!query.next()) return -1; - return query.value(0).toInt(); -} - -//往 Session 表中插入数据 -int DatabaseOperation::insertSessionBasicInfo(const char* SessionType, const char* profile) { - QSqlQuery query; - QString insert_sql = "insert into Session(SessionID, SessionType, Profile) values(?, ?, ?)"; - query.prepare(insert_sql); - int sessionId = getTableCount("Session") + 1; - query.addBindValue(sessionId); - query.addBindValue(SessionType); - query.addBindValue(profile); - if (!query.exec()) { - qDebug() << query.lastError(); - return -1; - } - return sessionId; -} - -bool DatabaseOperation::insertMember(int sessionID, const char * user){ - QSqlQuery query; - QString insert_sql = "insert into IsMember values(?, ?)"; - query.prepare(insert_sql); - query.addBindValue(sessionID); - query.addBindValue(user); - if(!query.exec()){ - qDebug()<<"query error: "< DatabaseOperation::queryMembersBySession(int sessionID){ - QList member_List; - QSqlQuery query; - QString query_sql = "SELECT SessionID, Username FROM IsMember WHERE sessionID = (?)"; - query.prepare(query_sql); - query.addBindValue(sessionID); - if (! query.exec()) { - qDebug() << "error occurred in queryMembersBySession, " << query.lastError(); - return member_List; - } - while(query.next()){ - member_List.append(query.value(1).toString()); - } - return member_List; -} - -//查询用户所拥有的session -QList DatabaseOperation::querySessionsByMember(const char * username){ - QList member_List; - QSqlQuery query; - QString query_sql = "SELECT SessionId, Username FROM IsMember WHERE username = (?)"; - query.prepare(query_sql); - query.addBindValue(username); - query.exec(); - while(query.next()){ - member_List.append(query.value(0).toInt()); - } - return member_List; -} - -bool DatabaseOperation::attemptLogIn(QString username, QString password) const { - //用户名检测 - QSqlQuery query(database); - query.prepare("select username, password from User where username=?"); - query.addBindValue(username); - bool ok = query.exec(); - if(!ok){ - qDebug() << "Fail query register username" << query.lastError(); - return false; - } - if(query.next()){ - //密码检测 - if (query.value(1).toString() == password) - return true; - qDebug() << "password incorrect"; - return false; - } - qDebug() << "Username not found"; - return false; -} - -int DatabaseOperation::insertNewMessage(int SessionId, const char *senderUsername, const char *MessageText, const char *profile) { - QSqlQuery query; - QString sql = "select count (*) from Message WHERE SessionId = ?"; - query.prepare(sql); - query.addBindValue(SessionId); - if (!query.exec() || !query.next()) { - qDebug() << "Error Occurred when querying Message Number" << query.lastError(); - return -1; - } - int msgId = query.value(0).toInt() + 1; - qDebug() << "Current MsgId for sessionId = " << msgId; - - sql = "insert into Message(SessionID, MessageID, SenderUsername, MessageText, Profile) VALUES (?, ?, ?, ?, ?)"; - query.prepare(sql); - query.addBindValue(SessionId); - query.addBindValue(msgId); - query.addBindValue(senderUsername); - query.addBindValue(MessageText); - query.addBindValue(profile); - if (!query.exec()) { - qDebug() << "insertNewMessage : " << query.lastError(); - return -1; - } - return msgId; -} - -QList DatabaseOperation::getMessageListBySessionID(int SessionId) const { - QList ret; - QSqlQuery query; - QString sql = "SELECT MessageID, SenderUsername, MessageText, Profile FROM Message WHERE SessionID = ?"; - query.prepare(sql); - query.addBindValue(SessionId); - if (!query.exec()) { - qDebug() << "getMessageListBySessionID: " << query.lastError(); - throw query.lastError(); - } - while(query.next()) { - int msgId = query.value(0).toInt(); - QString senderUsername = query.value(1).toString(); - QString messageText = query.value(2).toString(); - QJsonObject profile = query.value(3).toJsonObject(); - auto * msg = new OnlineMessage(msgId, SessionId, senderUsername, messageText, profile); - ret.append(msgId); - ServerDataCenter::Singleton().registerMessage(msg); - } - return ret; -} - -OnlineUserModel & ServerDataCenter::getUser(QString username) { - if (_getUser(username) == nullptr) throw "Not exist"; - return *users[username]; -} - -OnlineMessage & ServerDataCenter::getMessage(int SessionId, int MessageId) { - if (_getMessage(SessionId, MessageId)) throw "Not exist"; - return *messages[{SessionId, MessageId}]; -} - -OnlineSession & ServerDataCenter::getSession(int SessionId) { - if (_getSession(SessionId) == nullptr) throw "Not exist"; - return *sessions[SessionId]; -} - -OnlineUserModel* ServerDataCenter::_getUser(QString username) { - if (users.contains(username)) - return users[username]; - return nullptr; -} - -OnlineSession* ServerDataCenter::_getSession(int SessionId) { - if (sessions.contains(SessionId)) - return sessions[SessionId]; - return nullptr; -} - -OnlineMessage* ServerDataCenter::_getMessage(int SessionId, int MessageId) { - if (messages.contains({SessionId, MessageId})) - return messages[{SessionId, MessageId}]; - return nullptr; -} - -OnlineUserModel * DatabaseOperation::findUser(QString username) { - QSqlQuery query; - QString sql = "SELECT Username, Nickname, Profile FROM User WHERE Username = " + username; - if (!query.exec(sql) || !query.first()) { - qDebug() << "DBOps::findUser: " << query.lastError(); - return nullptr; - } - OnlineUserModel * ret = new OnlineUserModel(query.value(0).toString(), - query.value(1).toString(), - query.value(2).toJsonObject()); - ServerDataCenter::Singleton().registerUser(ret); - return ret; -} - -OnlineSession * DatabaseOperation::findSession(int sessionID) { - QSqlQuery query; - QString sql = "SELECT Profile FROM Session WHERE SessionID = " + QString::number(sessionID); - if (!query.exec(sql) || !query.first()) { - qDebug() << "DBOps::findSession: " << query.lastError(); - return nullptr; - } - - auto json = query.value(0).toJsonObject(); - QString SessionName = json.contains("SessionName") ? - json["SessionName"].toString() : "None"; - - OnlineSession * ret = new OnlineSession(sessionID, SessionName, json, - queryMembersBySession(sessionID)); - ServerDataCenter::Singleton().registerSession(ret); - return ret; -} - -OnlineMessage * DatabaseOperation::findMessage(int sessionId, int MessageId) { - QSqlQuery query; - QString sql = "SELECT SenderUsername, MessageText, Profile FROM Message WHERE SessionID = " + - QString::number(sessionId) + " and MessageID = " + QString::number(MessageId); - if (!query.exec(sql) || !query.first()) { - qDebug() << "DBOps::findMessage: " << query.lastError(); - return nullptr; - } - - QString sender = query.value(0).toString(); - QString text = query.value(1).toString(); - QJsonObject json = query.value(2).toJsonObject(); - OnlineMessage * ret = new OnlineMessage(MessageId, sessionId, sender, text, json); - ServerDataCenter::Singleton().registerMessage(ret); - return ret; -} - -ServerDataCenter::ServerDataCenter(QObject *parent) : QObject(parent) -{ - connect(&DatabaseOperation::Singleton(), &DatabaseOperation::signal_DBstop, this, &ServerDataCenter::clean); -} +#include +#include +#include +#include +#include + +#include "databaseoperation.h" + +QString json2str(QJsonObject json) { + return QString(QJsonDocument(json).toJson()); +} + +QJsonObject str2json(QString str) { + QJsonDocument jsonDoc = QJsonDocument::fromJson(str.toUtf8().data()); + if (jsonDoc.isNull()) { + qDebug() << "read json obj from str failed: str = " << str.toLocal8Bit().data(); + } + return jsonDoc.object(); +} + +DatabaseOperation::DatabaseOperation(QObject *parent) : QObject(parent) +{ + status = Status::Stop; +} + +void DatabaseOperation::startDatabaseConnection(QString dbfilename) { + if (status != Status::Stop) { + qDebug() << "db server already running..."; + throw "Already running error"; + } + QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); + db.setDatabaseName(dbfilename); //如果本目录下没有该文件,则会在本目录下生成,否则连接该文件 + if (!db.open()) { + qDebug() << db.lastError().text(); + throw "Database Error"; + } + status = Status::Running; + createTables(); + findAllUsers(); + findAllSessions(); + findAllMessages(); + emit signal_DB_ready(); +} + +void DatabaseOperation::executeSqlStatement(QString str) { + QSqlQuery query (str); + if (!query.isActive()) { + qDebug() << query.lastError(); + } +} + +void DatabaseOperation::createTables() { + executeSqlStatement("CREATE TABLE User(Username TEXT PRIMARY KEY, Nickname TEXT NOT NULL, Password TEXT NOT NULL, Profile TEXT)"); + executeSqlStatement("CREATE TABLE Session(SessionID INT PRIMARY KEY, SessionType TEXT NOT NULL, Profile TEXT)"); + executeSqlStatement("CREATE TABLE Message(SessionID INT NOT NULL, MessageID INT NOT NULL, SenderUsername TEXT NOT NULL, MessageText TEXT NOT NULL, Profile TEXT, PRIMARY KEY(SessionID, MessageID), FOREIGN KEY(SessionID) REFERENCES Session(SessionID), FOREIGN KEY(SenderUserName) REFERENCES User(Username))"); + executeSqlStatement("CREATE TABLE IsMember(SessionID INT NOT NULL, Username TEXT NOT NULL, PRIMARY KEY (Username, SessionID), FOREIGN KEY (Username) REFERENCES User(username), FOREIGN KEY (SessionID) REFERENCES Session(SessionID))"); +} + +bool DatabaseOperation::isDBExist(QString dbfilename) const { + QFileInfo file(dbfilename); + return file.exists(); +} + +void DatabaseOperation::closeDB() { + if (status != Status::Running) throw "already closed"; + database.close(); + + status = Status::Stop; + emit signal_DBstop(); +} + +QList DatabaseOperation::findAllUsers() { + QList ret; + QSqlQuery sqlQuery; + sqlQuery.exec("SELECT Username, Nickname, Password, Profile FROM User"); + if(!sqlQuery.exec()) { + qDebug() << "Error: Fail to query table. " << sqlQuery.lastError(); + throw "DB read error"; + } + else { + auto & dcenter = ServerDataCenter::Singleton(); + while(sqlQuery.next()) { + QString username = sqlQuery.value(0).toString(); + QString nickname = sqlQuery.value(1).toString(); + QString profile = sqlQuery.value(3).toString(); + auto newuser = new OnlineUserModel(username, nickname, str2json(profile)); + dcenter.registerUser(newuser); + ret.append(newuser); + } + } + return ret; +} + +QList DatabaseOperation::findAllSessions() { + QList ret; + QSqlQuery query; + if (!query.exec("SELECT SessionID, Profile FROM Session")) { + qDebug() << "findAllSessions: " << query.lastError(); + throw "DB read error"; + } + auto & dcenter = ServerDataCenter::Singleton(); + while (query.next()) { + int sessionId = query.value(0).toInt(); + QJsonObject json = query.value(1).toJsonObject(); + QString sessionName = json.contains("SessionName") ? json["SessionName"].toString() : "None"; + + QList members = queryMembersBySession(sessionId); + + OnlineSession * session = new OnlineSession(sessionId, sessionName, json, members); + ret.append(session); + dcenter.registerSession(session); + } + return ret; +} + +QList DatabaseOperation::findAllMessages() { + QList ret; + QSqlQuery query; + if (query.exec("SELECT SessionID, MessageID, senderUsername, MessageText, Profile FROM Message")) { + while (query.next()) { + int sessionID = query.value(0).toInt(); + int msgId = query.value(1).toInt(); + QString sender = query.value(2).toString(); + QString text = query.value(3).toString(); + QJsonObject profile = query.value(4).toJsonObject(); + + auto * msg = new OnlineMessage(msgId, sessionID, sender, text, profile); + ret.append(msg); + ServerDataCenter::Singleton().registerMessage(msg); + } + } + return ret; +} + + +//往User表中插入数据 +bool DatabaseOperation::insertUser(const char* username, const char* nickname, const char* password, const char* profile){ + QSqlQuery query; +// QString insert_sql = "insert into User(Username, Nickname, Password, Profile) values (?, ?, ?, ?)"; + QString insert_sql = QString("INSERT INTO User(Username, Nickname, Password, Profile) VALUES ('%1', '%2', '%3', '%4')") + .arg(username).arg(nickname).arg(password).arg(profile); + qDebug() << insert_sql; +// query.prepare(insert_sql); +// query.addBindValue(username); +// query.addBindValue(nickname); +// query.addBindValue(password); +// query.addBindValue(profile); + if (! query.exec(insert_sql) ) { + qDebug() << query.lastError(); + return false; + } + ServerDataCenter::Singleton().registerUser(new OnlineUserModel( + QString(username), QString(nickname), str2json(QString(profile)) )); + return true; +} + +bool DatabaseOperation::insertUser(const OnlineUserModel &user, const QString &password) { + return insertUser(user.getUsername().toUtf8().data(), + user.getNickname().toUtf8().data(), + password.toUtf8().data(), + json2str(user.getProfile()).toUtf8().data()); +} + + + +int DatabaseOperation::getTableCount(const char * tableName) const { + QSqlQuery query; + QString sql = QString("SELECT COUNT(*) FROM %1").arg(tableName); + query.addBindValue(tableName); + if (!query.exec(sql)) { + qDebug() << query.lastError(); + return -1; + } + if (!query.next()) return -1; + return query.value(0).toInt(); +} + +//往 Session 表中插入数据 +int DatabaseOperation::insertSessionBasicInfo(const char* SessionType, const char* profile) { + QSqlQuery query; + QString insert_sql = "insert into Session(SessionID, SessionType, Profile) values(?, ?, ?)"; + query.prepare(insert_sql); + int sessionId = getTableCount("Session") + 1; + query.addBindValue(sessionId); + query.addBindValue(SessionType); + query.addBindValue(profile); + if (!query.exec()) { + qDebug() << query.lastError(); + return -1; + } + return sessionId; +} + +bool DatabaseOperation::insertMember(int sessionID, const char * user){ + QSqlQuery query; + QString insert_sql = "insert into IsMember values(?, ?)"; + query.prepare(insert_sql); + query.addBindValue(sessionID); + query.addBindValue(user); + if(!query.exec()){ + qDebug()<<"query error: "< DatabaseOperation::queryMembersBySession(int sessionID){ + QList member_List; + QSqlQuery query; + QString query_sql = "SELECT SessionID, Username FROM IsMember WHERE sessionID = (?)"; + query.prepare(query_sql); + query.addBindValue(sessionID); + if (! query.exec()) { + qDebug() << "error occurred in queryMembersBySession, " << query.lastError(); + return member_List; + } + while(query.next()){ + member_List.append(query.value(1).toString()); + } + return member_List; +} + +//查询用户所拥有的session +QList DatabaseOperation::querySessionsByMember(const char * username){ + QList member_List; + QSqlQuery query; + QString query_sql = "SELECT SessionId, Username FROM IsMember WHERE username = (?)"; + query.prepare(query_sql); + query.addBindValue(username); + query.exec(); + while(query.next()){ + member_List.append(query.value(0).toInt()); + } + return member_List; +} + +//查询会话的所有历史消息 +QList DatabaseOperation::queryMessageBySession(int sessionID) { + QList ret; + QSqlQuery query; + QString sql = "SELECT MessageID FROM Message WHERE SessionID = (?)"; + query.prepare(sql); query.addBindValue(sessionID); + if (!query.exec()) { + qDebug() << "queryMessageBySession: " << query.lastError(); + return ret; + } + while (query.next()) { + ret.append(query.value(0).toInt()); + } + return ret; +} + + +bool DatabaseOperation::attemptLogIn(QString username, QString password) const { + //用户名检测 + QSqlQuery query(database); + query.prepare("select username, password from User where username=?"); + query.addBindValue(username); + bool ok = query.exec(); + if(!ok){ + qDebug() << "Fail query register username" << query.lastError(); + return false; + } + if(query.next()){ + //密码检测 + if (query.value(1).toString() == password) + return true; + qDebug() << "password incorrect"; + return false; + } + qDebug() << "Username not found"; + return false; +} + +int DatabaseOperation::insertNewMessage(int SessionId, const char *senderUsername, const char *MessageText, const char *profile) { + QSqlQuery query; + QString sql = "select count (*) from Message WHERE SessionId = ?"; + query.prepare(sql); + query.addBindValue(SessionId); + if (!query.exec() || !query.next()) { + qDebug() << "Error Occurred when querying Message Number" << query.lastError(); + return -1; + } + int msgId = query.value(0).toInt() + 1; + qDebug() << "Current MsgId for sessionId = " << msgId; + + sql = "insert into Message(SessionID, MessageID, SenderUsername, MessageText, Profile) VALUES (?, ?, ?, ?, ?)"; + query.prepare(sql); + query.addBindValue(SessionId); + query.addBindValue(msgId); + query.addBindValue(senderUsername); + query.addBindValue(MessageText); + query.addBindValue(profile); + if (!query.exec()) { + qDebug() << "insertNewMessage : " << query.lastError(); + return -1; + } + return msgId; +} + +QList DatabaseOperation::getMessageListBySessionID(int SessionId) const { + QList ret; + QSqlQuery query; + QString sql = "SELECT MessageID, SenderUsername, MessageText, Profile FROM Message WHERE SessionID = ?"; + query.prepare(sql); + query.addBindValue(SessionId); + if (!query.exec()) { + qDebug() << "getMessageListBySessionID: " << query.lastError(); + throw query.lastError(); + } + while(query.next()) { + int msgId = query.value(0).toInt(); + QString senderUsername = query.value(1).toString(); + QString messageText = query.value(2).toString(); + QJsonObject profile = query.value(3).toJsonObject(); + auto * msg = new OnlineMessage(msgId, SessionId, senderUsername, messageText, profile); + ret.append(msgId); + ServerDataCenter::Singleton().registerMessage(msg); + } + return ret; +} + +OnlineUserModel & ServerDataCenter::getUser(QString username) { + if (_getUser(username) == nullptr) throw "Not exist"; + return *users[username]; +} + +OnlineMessage & ServerDataCenter::getMessage(int SessionId, int MessageId) { + if (_getMessage(SessionId, MessageId) == nullptr) throw "Not exist"; + return *messages[{SessionId, MessageId}]; +} + +OnlineSession & ServerDataCenter::getSession(int SessionId) { + if (_getSession(SessionId) == nullptr) throw "Not exist"; + return *sessions[SessionId]; +} + +OnlineUserModel* ServerDataCenter::_getUser(QString username) { + if (users.contains(username)) + return users[username]; + return nullptr; +} + +OnlineSession* ServerDataCenter::_getSession(int SessionId) { + if (sessions.contains(SessionId)) + return sessions[SessionId]; + return nullptr; +} + +OnlineMessage* ServerDataCenter::_getMessage(int SessionId, int MessageId) { + OnlineMessage * ret = nullptr; + if (messages.contains(QPair({SessionId, MessageId}))) + ret = messages[QPair({SessionId, MessageId})]; + return ret; +} + +OnlineUserModel * DatabaseOperation::findUser(QString username) { + QSqlQuery query; + QString sql = "SELECT Username, Nickname, Profile FROM User WHERE Username = " + username; + if (!query.exec(sql) || !query.first()) { + qDebug() << "DBOps::findUser: " << query.lastError(); + return nullptr; + } + OnlineUserModel * ret = new OnlineUserModel(query.value(0).toString(), + query.value(1).toString(), + query.value(2).toJsonObject()); + ServerDataCenter::Singleton().registerUser(ret); + return ret; +} + +OnlineSession * DatabaseOperation::findSession(int sessionID) { + QSqlQuery query; + QString sql = "SELECT Profile FROM Session WHERE SessionID = " + QString::number(sessionID); + if (!query.exec(sql) || !query.first()) { + qDebug() << "DBOps::findSession: " << query.lastError(); + return nullptr; + } + + auto json = query.value(0).toJsonObject(); + QString SessionName = json.contains("SessionName") ? + json["SessionName"].toString() : "None"; + + OnlineSession * ret = new OnlineSession(sessionID, SessionName, json, + queryMembersBySession(sessionID)); + ServerDataCenter::Singleton().registerSession(ret); + return ret; +} + +OnlineMessage * DatabaseOperation::findMessage(int sessionId, int MessageId) { + QSqlQuery query; + QString sql = "SELECT SenderUsername, MessageText, Profile FROM Message WHERE SessionID = " + + QString::number(sessionId) + " and MessageID = " + QString::number(MessageId); + if (!query.exec(sql) || !query.first()) { + qDebug() << "DBOps::findMessage: " << query.lastError(); + return nullptr; + } + + QString sender = query.value(0).toString(); + QString text = query.value(1).toString(); + QJsonObject json = query.value(2).toJsonObject(); + OnlineMessage * ret = new OnlineMessage(MessageId, sessionId, sender, text, json); + ServerDataCenter::Singleton().registerMessage(ret); + return ret; +} + +ServerDataCenter::ServerDataCenter(QObject *parent) : QObject(parent) +{ + connect(&DatabaseOperation::Singleton(), &DatabaseOperation::signal_DBstop, this, &ServerDataCenter::clean); +} diff --git a/Server/databaseoperation.h b/Server/databaseoperation.h index 9b90e3e7ed79780bca3e995b3a505dc29b7015cd..36d03f95e32ff53a0e5e27db432043c33ac20f49 100644 --- a/Server/databaseoperation.h +++ b/Server/databaseoperation.h @@ -42,6 +42,7 @@ public: QList queryMembersBySession(int sessionID); QList querySessionsByMember(const char * username); + QList queryMessageBySession(int sessionID); QList getMessageListBySessionID(int SessionId) const; OnlineMessage * findMessage(int sessionId, int MessageId); diff --git a/Server/handlesignal.h b/Server/handlesignal.h index 111256e98177cf04ec4aa995b84c0f4a5b51b476..6e1db5aa480ab139327486baa54ad6c37836b2a4 100644 --- a/Server/handlesignal.h +++ b/Server/handlesignal.h @@ -13,6 +13,7 @@ public: signals: void sendSignal(int); + }; #endif // HANDLESIGNAL_H diff --git a/Server/messagemodel.cpp b/Server/messagemodel.cpp index 8e4695ce4b5fae191ceb1f4c0bf3d1ec1d4765f9..9472682771279ff255412481e46e040896d58645 100644 --- a/Server/messagemodel.cpp +++ b/Server/messagemodel.cpp @@ -32,7 +32,7 @@ OnlineMessage::OnlineMessage(QJsonObject json, MessageModel * parent) : { messageID = json["MessageID"].toInt(); sessionID = json["SessionID"].toInt(); - senderUsername = json["SenderUsername"].toString(); + senderUsername = json["SenderName"].toString(); QJsonObject body = json["Body"].toObject(); text = body["Text"].toString(); @@ -48,3 +48,12 @@ OnlineMessage::OnlineMessage(int MessageID, int SessionID, QString sender, QStri profile = Profile; this->setParent(parent); } + +QJsonObject OnlineMessage::generateJsonOutput() const { + QJsonObject ret = {{ "MsgType", "SessionMessage" }}; + ret["SessionID"] = sessionID; + ret["MessageID"] = messageID; + ret["SenderName"] = senderUsername; + ret["Body"] = QJsonObject({{"Text", text}, {"Profile", QJsonObject()}}); + return ret; +} diff --git a/Server/messagemodel.h b/Server/messagemodel.h index 9b68c6276d3263c83067731efce6f9289e66a955..d7559ab63f08948b1606ff9502b890a5b59234a1 100644 --- a/Server/messagemodel.h +++ b/Server/messagemodel.h @@ -24,7 +24,6 @@ public: enum class Type { Offline, Online }; virtual Type getType() const { return Type::Offline; } - QJsonObject generateJsonOutput() const; signals: @@ -44,6 +43,7 @@ public: explicit OnlineMessage(QJsonObject json, MessageModel * parent = nullptr); explicit OnlineMessage(int MessageID, int SessionID, QString sender, QString text, QJsonObject Profile, MessageModel * parent = nullptr); int getMessageID() const override { return messageID; } + QJsonObject generateJsonOutput() const; private: int messageID; }; diff --git a/Server/operations.cpp b/Server/operations.cpp index 1b878eceb3a4f376742532ecd74b0e74a3fac7bb..533e1a61d34b6c17d19c418eac480934ab631121 100644 --- a/Server/operations.cpp +++ b/Server/operations.cpp @@ -7,16 +7,10 @@ Operations::Operations(QObject *parent) : QObject(parent) } - - - - ServerDataCenter& dcenter = ServerDataCenter::Singleton(); using resp = QList; using Json = QJsonObject; - - resp Operations::loginResponse(QJsonObject json) { DatabaseOperation & db = DatabaseOperation::Singleton(); QString username = json["Username"].toString(); @@ -28,6 +22,7 @@ resp Operations::loginResponse(QJsonObject json) { } response["IsLegal"] = true; response["Username"] = username; + auto & user = dcenter.getUser(username); response["Nickname"] = user.getNickname(); response["Profile"] = user.getProfile(); @@ -35,15 +30,21 @@ resp Operations::loginResponse(QJsonObject json) { auto sessionlist = db.querySessionsByMember(username.toUtf8().data()); for (int i = 0; i < sessionlist.size(); i++) { - auto userlist = db.queryMembersBySession(sessionlist.at(i)); + int ssid = sessionlist.at(i); + auto userlist = db.queryMembersBySession(ssid); for (int j = 0; j < userlist.size(); j++) { auto cur = userlist.at(j); if (cur == username) continue; auto & curuser = dcenter.getUser(cur); ret.append(curuser.generateUserModelJson()); + + } + ret.append(dcenter.getSession(ssid).generateJsonFromData()); + auto msglist = db.queryMessageBySession(sessionlist.at(i)); + for (int j = 0; j < msglist.size(); j++) { + ret.append(dcenter.getMessage(ssid, msglist[j]).generateJsonOutput()); } - ret.append(dcenter.getSession(sessionlist.at(i)).generateJsonFromData()); } return ret; } @@ -60,8 +61,25 @@ resp Operations::registerResponse(QJsonObject json) { char * nickname = json["Nickname"].toString().toUtf8().data(); char * password = json["Password"].toString().toUtf8().data(); - if (!db.insertUser(username, nickname, password, "{ \"Signiture\": \"None\"}")) + if (!db.insertUser(username, nickname, password, "{ \"signiture\": \"None\"}")) return {head}; head["IsLegal"] = true; return {head}; } + +resp Operations::newMessageResponse(QJsonObject json) { + DatabaseOperation & db = DatabaseOperation::Singleton(); + int sessionID = json["SessionID"].toInt(); + QString senderUsername = json["SenderName"].toString(); + auto json1 = json["Body"].toObject(); + QString text = json1["Text"].toString(); + bool mention = json1["Profile"].toObject()["hasMentionInfo"].toBool(); + if (mention) { + throw "Not Implemented"; + } + int msgID = db.insertNewMessage(sessionID, senderUsername.toUtf8().data(), text.toUtf8().data(), json2str(json["Profile"].toObject()).toUtf8().data()); + json["MessageID"] = msgID; + emit newMessage(sessionID, json); + + return resp(); +} diff --git a/Server/operations.h b/Server/operations.h index fc1e3723f1e345d281131f9275eb8ba6d4c4f6d7..86c206d15b5b2f7d25fffc3e8f7901d1385642ec 100644 --- a/Server/operations.h +++ b/Server/operations.h @@ -21,6 +21,8 @@ public: QList request(QJsonObject json); signals: + void newMessage(int sessionId, QJsonObject msg); + public: explicit Operations(QObject *parent = nullptr); diff --git a/Server/serverdatacenter.cpp b/Server/serverdatacenter.cpp index 20076d6374fb164e63a52abd7556a96592a8e36c..358360b71bfc131908eb38d7538e5f839ec5b16a 100644 --- a/Server/serverdatacenter.cpp +++ b/Server/serverdatacenter.cpp @@ -28,7 +28,6 @@ void ServerDataCenter::registerMessage(OnlineMessage *msg) { messages[{msg->getSessionID(), msg->getMessageID()}] = msg; msg->setParent(this); registeredObjects.append(msg); - qDebug() << "### ServerDataCenter Down"; } diff --git a/Server/sever.cpp b/Server/sever.cpp index 943d40a6feb626c35acc6cb2cba4c44f9ac769f9..942eccd811adb24ce522325736ea0baf4cb4ff8e 100644 --- a/Server/sever.cpp +++ b/Server/sever.cpp @@ -6,6 +6,7 @@ #include #include"databaseoperation.h" + Sever::Sever(QObject *parent) : QTcpServer (parent) { @@ -30,9 +31,13 @@ void Sever::incomingConnection(qintptr handle) newHandle->aaa(handle); }); + connect(socket,&QTcpSocket::disconnected,[=](){ + emit offLine (handle); + }); + emit sendChannel (handle); - emit linkMsg (socket->peerAddress ().toString ()+"上线了", 2); //2表示在登录框中显示 + emit linkMsg (socket->peerAddress ().toString ()+"连接成功!"); //2表示在登录框中显示 } @@ -67,17 +72,50 @@ void Sever::receiveMessage(int handle) auto returnList = QList(); auto &op = Operations::Singleton (); + + QString messageSender = ""; //标记消息来源用户名称 if(method == "login") { - returnList = op.loginResponse (recejson); + //首次收到登陆信息 + messageSender = recejson["Username"].toString(); + QMap >::iterator it1 = userToHandle.begin(); + int flag=0; + while(it1!=userToHandle.end ()) + { + if(it1.key ()==messageSender)//并非首次登陆 + { + it1.value ().append (handle); + emit linkMsg (messageSender+" "+QString::number (it1.value ().size ())+" "+"登陆了!"); + qDebug()<< it1.value ().size (); + flag=1; + break; + } + it1++; + } + if(flag==0)//首次登陆 + { + QList ll; + ll.append (handle); + userToHandle.insert (messageSender,ll); + emit linkMsg (messageSender+" 1 "+"登陆了!"); + } + returnList = op.loginResponse (recejson); + emit sendMsg (returnList, messageSender); } else if (method == "regist") { returnList = op.registerResponse(recejson); + emit sendMsg (returnList, messageSender); } else if (method == "info") { - qDebug() << recejson["Message"].toString(); - emit linkMsg(recejson["Message"].toString(), 1); + + emit linkMsg(recejson["Message"].toString()); + + } + else if(method == "sessionmessage"){ + op.newMessageResponse (recejson); + //同时触发信号,到widget } - qDebug() << returnList; - emit sendMsg (returnList, handle); //1表示在文本框中显示 + + + } diff --git a/Server/sever.h b/Server/sever.h index 2c6d4689b9f77840f47c96eb1378ec2ab7432b18..48baf1a8e32ce0b246823b76094d69553c01cec8 100644 --- a/Server/sever.h +++ b/Server/sever.h @@ -12,8 +12,12 @@ class Sever : public QTcpServer public: explicit Sever(QObject *parent = nullptr); + //handle索引的socket QMap clientMap; + //username索引的handle,实现了一对多 + QMap> userToHandle; + private: QTcpSocket *sock; void incomingConnection(qintptr handle); @@ -22,11 +26,14 @@ private: public slots: void setIP(QString); + signals: - void linkMsg(QString, int); - void sendMsg(QList, int);//将tcp_server收到的信息作为信号发送给mianwindow + void linkMsg(QString); + void sendMsg(QList, QString);//将tcp_server收到的信息作为信号发送给 MainWindow void ready_Read(qintptr); void sendChannel(int); + void offLine(int); + }; #endif // SEVER_H diff --git a/Server/testcases.cpp b/Server/testcases.cpp index ff2a6a38902ed3e759d100e2edf86edfb42742c4..6553652e25f9fa3ccee340f9153ca0b2845169c5 100644 --- a/Server/testcases.cpp +++ b/Server/testcases.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include "databaseoperation.h" #include "serverdatacenter.h" @@ -88,7 +89,7 @@ ENDSUITE(SessionTest) TESTSUITE(UserTest) CASE(OfflineUserGenerateJsonObject) { - OfflineUserModel user("userA", &obj); + OfflineUserModel user("userA"); user.setNickname("nicknameA"); user.setSigniture("None"); auto json = user.generateUserModelJson(); @@ -96,17 +97,17 @@ CASE(OfflineUserGenerateJsonObject) { assertEqual(json["Nickname"].toString(), "nicknameA"); auto profile = json["Profile"].toObject(); - assertEqual(profile["Signiture"].toString(), "None"); + assertEqual(profile["signiture"].toString(), "None"); } CASE(NewOnlineUser_ReadJson_LoadProfile) { - OfflineUserModel user("userA", &obj); + OfflineUserModel user("userA"); user.setNickname("nicknameA"); user.setSigniture("None"); auto json = user.generateUserModelJson(); - OnlineUserModel newuser(json, &obj); + OnlineUserModel newuser(json); assertEqual(newuser.getType(), UserModel::Type::Online); assertEqual(newuser.getUsername(), "userA"); @@ -130,17 +131,17 @@ CASE(CanGetSingleton) { } CASE(getOnlineUserFromUsername) { - OfflineUserModel user("userA", &obj); + OfflineUserModel user("userA"); user.setNickname("nicknameA"); user.setSigniture("None"); auto json = user.generateUserModelJson(); - OnlineUserModel newuser(json, &obj); + OnlineUserModel newuser(json); - OfflineUserModel userB("userB", &obj); + OfflineUserModel userB("userB"); userB.setNickname("nicknameA"); userB.setSigniture("None"); json = userB.generateUserModelJson(); - OnlineUserModel newuserB(json, &obj); + OnlineUserModel newuserB(json); auto& dcenter = ServerDataCenter::Singleton(); dcenter.registerUser(& newuser); @@ -164,17 +165,17 @@ TESTSUITE(MessageTest) CASE(NewMessage_GeneratedBy_UserAndSessionObject) { - OfflineUserModel userA("userA", &obj); + OfflineUserModel userA("userA"); userA.setNickname("nicknameA"); userA.setSigniture("None"); auto json = userA.generateUserModelJson(); - OnlineUserModel userA_online(json, &obj); + OnlineUserModel userA_online(json); - OfflineUserModel userB("userB", &obj); + OfflineUserModel userB("userB"); userB.setNickname("nicknameA"); userB.setSigniture("None"); json = userB.generateUserModelJson(); - OnlineUserModel userB_online(json, &obj); + OnlineUserModel userB_online(json); ServerDataCenter & dcenter = ServerDataCenter::Singleton(); dcenter.registerUser(&userA_online); @@ -197,7 +198,7 @@ CASE(NewMessage_GeneratedBy_UserAndSessionObject) testlog("Constructed mock users and session."); - MessageModel msg(userA_online, session, "a->b text", QJsonObject(), &obj); + MessageModel msg(userA_online, session, "a->b text", QJsonObject()); testlog("Generated offline message"); assertEqual(msg.getType(), MessageModel::Type::Offline); @@ -230,11 +231,11 @@ CASE(CanCreateNewDB) { } void insertUser() { - db.insertUser("xiaoming","XiaoMing", "xiaoming123", "{\"Signiture\":\"nop\"}"); - db.insertUser("xxx", "XXX", "xXxXx", "{ \"Signiture\": \"yyy\"}"); - db.insertUser("wuzirui", "wuzirui", "1234", "{ \"Signiture\": \"cai\"}"); - db.insertUser("usera", "UserA", "AAAA", "{ \"Signiture\": \"B -1\"}"); - db.insertUser("userB", "bibibi", "bbbb", "{ \"Signiture\": \"A+1\"}"); + db.insertUser("xiaoming","XiaoMing", "xiaoming123", "{\"signiture\":\"nop\"}"); + db.insertUser("xxx", "XXX", "xXxXx", "{ \"signiture\": \"yyy\"}"); + db.insertUser("wuzirui", "wuzirui", "1234", "{ \"signiture\": \"cai\"}"); + db.insertUser("usera", "UserA", "AAAA", "{ \"signiture\": \"B -1\"}"); + db.insertUser("userB", "bibibi", "bbbb", "{ \"signiture\": \"A+1\"}"); } void checkInsertedUser() { @@ -410,8 +411,6 @@ CASE(MessageForwardTest) { json["Body"] = body; // auto response = op.newMessageResponse(json); - - } void execute() { @@ -423,3 +422,34 @@ void execute() { } ENDSUITE(Functional) + +int captureGitRepo(QString raw, QList &authors, QList &repos, QList &commits) { + QRegExp reg("@\\[((?:[^ ,\\,])+),[ ]*((?:[^ ,\\,])+)(?:,[ ]*((?:[^ ,\\,])*))?\\]"); + int pos = 0, initial = authors.size(); + while ((pos = reg.indexIn(raw, pos)) != -1) { + authors.append(reg.cap(1)); + repos.append(reg.cap(2)); + commits.append(reg.cap(3) == "" ? "master" : reg.cap(3)); + pos += reg.matchedLength(); + } + return authors.size() - initial; +} + +TESTSUITE(reg) + +CASE(REG_Repo) { + QList authors, repos, commits; + int ret = captureGitRepo("a message with a gitee @[jasonliu233,zhishigongcheng, master] repo", authors, repos, commits); + assertEqual(ret, 1, ret); + testlog("Pattern recognized: author = %s, repo = %s, commit = %s", authors[0].toUtf8().data(), + repos[0].toUtf8().data(), commits[0].toUtf8().data()); + assertEqual(authors[0], "jasonliu233"); + assertEqual(repos[0], "zhishigongcheng"); + assertEqual(commits[0], "master"); +} + + +void execute() override { + EXE(REG_Repo) +} +ENDSUITE(reg) diff --git a/Server/usermodel.cpp b/Server/usermodel.cpp index bf3f1543dd1aed49e2a84877e8eadf21a0f14fe7..0286b012ab29699b69067342745270b77d8923a7 100644 --- a/Server/usermodel.cpp +++ b/Server/usermodel.cpp @@ -1,17 +1,17 @@ #include "usermodel.h" -UserModel::UserModel(QObject *parent) : QObject(parent) +UserModel::UserModel() { - + profile["signiture"] = "Nop"; } -OfflineUserModel::OfflineUserModel(QString Username, QObject *parent) :QObject (parent) +OfflineUserModel::OfflineUserModel(QString Username) { username = Username; } -OnlineUserModel::OnlineUserModel(QJsonObject &json, QObject *parent) : QObject (parent) +OnlineUserModel::OnlineUserModel(QJsonObject &json) { loadBasicInfoFromJson(json); } @@ -23,8 +23,7 @@ void OnlineUserModel::loadBasicInfoFromJson(QJsonObject &json) { } -OnlineUserModel::OnlineUserModel(QString usrname, QString nick, QJsonObject json, QObject * parent) : - UserModel(parent) +OnlineUserModel::OnlineUserModel(QString usrname, QString nick, QJsonObject json) { username = usrname; nickname = nick; @@ -43,6 +42,7 @@ QJsonObject OnlineUserModel::generateUserModelJson() const { QJsonObject OfflineUserModel::generateUserModelJson() const { QJsonObject json; + json["MsgType"] = "UserData"; json["Username"] = username; json["Nickname"] = nickname; json["Profile"] = profile; diff --git a/Server/usermodel.h b/Server/usermodel.h index ccb7ab9ce1a89949e47833aae52e30afa3012b77..1295d5dc6c55a956de6b215c68ec6a82f2adc874 100644 --- a/Server/usermodel.h +++ b/Server/usermodel.h @@ -10,7 +10,7 @@ class UserModel : virtual public QObject { Q_OBJECT public: - UserModel(QObject *parent = nullptr); + UserModel(); enum class Type { Offline, Online, None}; virtual Type getType() const { return Type::None; } const QString& getUsername() const { return username; } @@ -24,14 +24,14 @@ protected: QJsonObject profile; }; -class OfflineUserModel : virtual public UserModel, virtual public QObject +class OfflineUserModel : public UserModel { Q_OBJECT public: - OfflineUserModel(QString Username, QObject *parent = nullptr); + OfflineUserModel(QString Username); Type getType() const { return Type::Offline; } void setNickname(QString nname) { nickname = nname; } - void setSigniture(QString sig) { profile["Signiture"] = sig; } + void setSigniture(QString sig) { profile["signiture"] = sig; } QJsonObject generateUserModelJson() const; @@ -41,15 +41,15 @@ signals: }; -class OnlineUserModel : virtual public UserModel, virtual public QObject +class OnlineUserModel : public UserModel { Q_OBJECT public: - OnlineUserModel(QJsonObject &json, QObject *parent = nullptr); - OnlineUserModel(QString usrname, QString nick, QJsonObject json, QObject * parent = nullptr); + OnlineUserModel(QJsonObject &json); + OnlineUserModel(QString usrname, QString nick, QJsonObject json); Type getType() const { return Type::Online; } const QString& getNickname() const { return nickname; } - const QString getSigniture() const { return profile["Signiture"].toString(); } + const QString getSigniture() const { return profile["signiture"].toString(); } QJsonObject generateUserModelJson() const; signals: diff --git a/Server/widget.cpp b/Server/widget.cpp index c8dafd47394642c21c4adde15b459f1eead29aea..a329a292f17c84a8a35f036b52448c7ef356a12b 100644 --- a/Server/widget.cpp +++ b/Server/widget.cpp @@ -14,6 +14,8 @@ Widget::Widget(QWidget *parent) //widget接受来自server的信息,并进行打印 connect(&sever, &Sever::linkMsg,this, &Widget::printLink); connect(&sever, &Sever::sendMsg,this, &Widget::printMsg); + connect(&sever, &Sever::offLine,this,&Widget::setOffline); + //socket首次连接之后设置handle connect(&sever, &Sever::sendChannel,this,&Widget::setChannel); @@ -21,6 +23,9 @@ Widget::Widget(QWidget *parent) connect(this,&Widget::pushIP,&sever, &Sever::setIP); connect(&(DatabaseOperation::Singleton()), &DatabaseOperation::signal_DB_ready, this, &Widget::load_Users); + + connect(&(Operations::Singleton ()),&Operations::newMessage,this, &Widget::getMessageTargetandContent); + } Widget::~Widget() @@ -30,31 +35,33 @@ Widget::~Widget() } -void Widget::printLink(QString str, int type) +void Widget::printLink(QString str) { - if(type==1) - { - ui->listWidget->addItem (str); - ui->listWidget->setCurrentRow (ui->listWidget->count ()-1); - } - else - { - ui->listWidget_2->addItem (str); - ui->listWidget_2->setCurrentRow (ui->listWidget_2->count ()-1); - } - + ui->listWidget_2->addItem (str); + ui->listWidget_2->setCurrentRow (ui->listWidget_2->count ()-1); } -void Widget::printMsg(QList list, int handle) +void Widget::printMsg(QList list, QString messageSender) { + //回发客户端功能,实现同用户多设备回发 qDebug() << "in printMsg!"; - for(int i=0;iwrite(send2.data ()); } + } void Widget::on_btnSend_clicked() @@ -94,6 +101,26 @@ void Widget::on_btnSetServer_clicked() } +void Widget::setOffline(int handle) +{ + //下线功能,非常重要!!! + int index = ui->comboBox->findText(QString::number (handle)); + if(index != -1 ) + ui->comboBox->setItemText (index, "disconnected."); + QString str = sever.clientMap[handle]->peerAddress ().toString ()+"断开连接!"; + ui->listWidget_2->addItem (str); + ui->listWidget_2->setCurrentRow (ui->listWidget_2->count ()-1); + + sever.clientMap.remove (handle); + //没有删除usertohandle的表格 + for(QMap >::iterator it1 = sever.userToHandle.begin();it1!=sever.userToHandle.end ();it1++) + { + it1.value ().removeAll (handle); + + } + qDebug() << sever.userToHandle; + +} void Widget::load_Users() { auto& db = DatabaseOperation::Singleton(); auto list = db.findAllUsers(); @@ -101,3 +128,45 @@ void Widget::load_Users() { this->ui->userWidgets->addItem(list[i]->getNickname() + " @" + list[i]->getUsername()); } } + +void Widget::getMessageTargetandContent(int sessionID, QJsonObject msg) +{ + + auto& db = DatabaseOperation::Singleton(); + QList sessionList = db.queryMembersBySession (sessionID); + + + qDebug() <>::iterator it1 = sever.userToHandle.begin();it1!=sever.userToHandle.end ();it1++) + { + qDebug() <write (send2.data ()); + + } + break; + } + } + } + + +} diff --git a/Server/widget.h b/Server/widget.h index 9e5dc9895c6a214d65e39b144defab6108581a49..7d368bc38cf18fedf3a35a98e4950073616620e0 100644 --- a/Server/widget.h +++ b/Server/widget.h @@ -19,8 +19,8 @@ public: private slots: // void on_pushButton_3_clicked() {} - void printLink(QString, int); //收到由server发来窗口的信号,并且打印到文本框 - void printMsg(QList,int); + void printLink(QString); //收到由server发来窗口的信号,并且打印到文本框 + void printMsg(QList, QString); void on_btnSend_clicked(); @@ -30,8 +30,10 @@ private slots: void on_btnSetServer_clicked(); + void setOffline(int); void load_Users(); + void getMessageTargetandContent(int, QJsonObject); signals: