diff --git a/CustomModels/channelmodel.cpp b/CustomModels/channelmodel.cpp index 7e80bbb71b3b5378ac5b8466f7f51f08cfb91b5c..102f5a47a2b9a58cd5698218298f2e36a8decf41 100644 --- a/CustomModels/channelmodel.cpp +++ b/CustomModels/channelmodel.cpp @@ -59,8 +59,8 @@ QVariant ChannelModel::data( const QModelIndex &index, int role ) const return ""; } - if ( message->getMessageType() == "file" || message->getMessageType() == "image" || message->getMessageType() == "audio" ) { - return tr( "file upload" ); + if ( message->getMessageType() == QStringLiteral( "file" ) || message->getMessageType() == QStringLiteral( "image" ) || message->getMessageType() == QStringLiteral( "audio" ) ) { + return tr( QByteArrayLiteral( "file upload" ) ); } return message->getMessageString(); @@ -97,6 +97,7 @@ bool ChannelModel::addChannel( const QSharedPointer<RocketChatChannel> &channel connect( channel.data(), &RocketChatChannel::messageAdded, this, &ChannelModel::onNewerMessage, Qt::UniqueConnection ); connect( channel.data(), &RocketChatChannel::unreadMessagesChanged, this, &ChannelModel::onUnreadMessageChanged, Qt::UniqueConnection ); connect( channel.data(), &RocketChatChannel::dataChanged, this, &ChannelModel::onDataChanged, Qt::UniqueConnection ); + connect( channel.data(), &RocketChatChannel::channelDeleted, this, &ChannelModel::onDeleted, Qt::UniqueConnection ); duplicateCheck.insert( channel->getRoomId() ); int pos = channelList.findPosition( channel ); emit beginInsertRows( QModelIndex(), pos, pos ); @@ -112,14 +113,15 @@ bool ChannelModel::addChannel( const QSharedPointer<RocketChatChannel> &channel QHash<int, QByteArray> ChannelModel::roleNames() const { QHash<int, QByteArray> roles; - roles[name] = "name"; - roles[roomId] = "roomId"; - roles[unreadMessages] = "unreadMessages"; - roles[channelType] = "type"; - roles[lastMessageText] = "lastMessageText"; - roles[readonly] = "readonly"; - roles[archived] = "archived"; - roles[blocked] = "blocked"; + roles[name] = QByteArrayLiteral( "name" ); + roles[roomId] = QByteArrayLiteral( "roomId" ); + roles[unreadMessages] = QByteArrayLiteral( "unreadMessages" ); + roles[channelType] = QByteArrayLiteral( "type" ); + roles[lastMessageText] = QByteArrayLiteral( "lastMessageText" ); + roles[readonly] = QByteArrayLiteral( "readonly" ); + roles[archived] = QByteArrayLiteral( "archived" ); + roles[blocked] = QByteArrayLiteral( "blocked" ); + roles[deleted] = QByteArrayLiteral( "deleted" ); return roles; } @@ -194,6 +196,25 @@ void ChannelModel::onDataChanged( const QString &id, const QString &property ) } } +void ChannelModel::onDeleted( const QString &pId, bool deleted ) +{ + int idx = -1; + + for ( int i = 0; i < channelList.length(); i++ ) { + if ( channelList.at( i )->getRoomId() == pId ) { + idx = i; + break; + } + } + + if ( idx != -1 ) { + beginRemoveRows( QModelIndex(), idx, idx ); + channelList.remove( idx ); + endRemoveRows(); + } + +} + void ChannelModel::addChannelSlot( const QSharedPointer<RocketChatChannel> &channel ) { addChannel( channel ); diff --git a/CustomModels/channelmodel.h b/CustomModels/channelmodel.h index ba4a270f27632a515fbd72f1983e711804eac825..03dd2a7da62c9031b92ca50e6a064de9e8ead48a 100644 --- a/CustomModels/channelmodel.h +++ b/CustomModels/channelmodel.h @@ -46,7 +46,8 @@ class ChannelModel : public QAbstractListModel channelType, readonly, archived, - blocked + blocked, + deleted }; public: ChannelModel(); @@ -65,6 +66,7 @@ class ChannelModel : public QAbstractListModel void onNewerMessage( const QString &id, qint64 timestamp ); void onUnreadMessageChanged( const QString &id, int number ); void onDataChanged( const QString &id, const QString &property ); + void onDeleted( const QString &pId, bool deleted ); QTimer timer; signals: void countChanged( void ); diff --git a/CustomModels/loginmethodsmodel.cpp b/CustomModels/loginmethodsmodel.cpp index c5c4ecddff8a87f2f1fa554e0d66ced521a81442..9c935b8f8ced21336ec1f3081c87f15628dab81c 100644 --- a/CustomModels/loginmethodsmodel.cpp +++ b/CustomModels/loginmethodsmodel.cpp @@ -24,7 +24,7 @@ LoginMethodsModel::LoginMethodsModel( QObject *parent ): QAbstractListModel( parent ) { QMap<QString, QVariant> entry; - entry.insert( "service", "user+password" ); + entry.insert( QStringLiteral( "service" ), QStringLiteral( "user+password" ) ); elements.append( entry ); } @@ -48,19 +48,19 @@ QVariant LoginMethodsModel::data( const QModelIndex &index, int role ) const if ( elements.size() >= index.row() ) { switch ( role ) { case 1: - return elements[index.row()]["service"]; + return elements[index.row()][QStringLiteral( "service" )]; break; case 2: - return elements[index.row()]["idpUrl"]; + return elements[index.row()][QStringLiteral( "idpUrl" )]; break; case 3: - return elements[index.row()]["buttonText"]; + return elements[index.row()][QStringLiteral( "buttonText" )]; break; case 4: - return elements[index.row()]["redirectUrl"]; + return elements[index.row()][QStringLiteral( "redirectUrl" )]; break; default: @@ -77,7 +77,7 @@ void LoginMethodsModel::reset() beginResetModel(); elements.clear(); QMap<QString, QVariant> entry; - entry.insert( "service", "user+password" ); + entry.insert( QStringLiteral( "service" ), QStringLiteral( "user+password" ) ); elements.append( entry ); endResetModel(); } @@ -85,10 +85,10 @@ void LoginMethodsModel::reset() QHash<int, QByteArray> LoginMethodsModel::roleNames() const { QHash<int, QByteArray> roles; - roles[1] = "service"; - roles[2] = "idpUrl"; - roles[3] = "buttonText"; - roles[4] = "redirectUrl"; + roles[1] = QByteArrayLiteral( "service" ); + roles[2] = QByteArrayLiteral( "idpUrl" ); + roles[3] = QByteArrayLiteral( "buttonText" ); + roles[4] = QByteArrayLiteral( "redirectUrl" ); return roles; } diff --git a/CustomModels/messagemodel.cpp b/CustomModels/messagemodel.cpp index 75724fbddbf5569a7f3398419de1930e360a9f3b..a97a0b27fa15f571028372609ad91f6da9601994 100644 --- a/CustomModels/messagemodel.cpp +++ b/CustomModels/messagemodel.cpp @@ -159,18 +159,18 @@ bool MessagesModel::addChannel( const QSharedPointer<RocketChatChannel> &channel QHash<int, QByteArray> MessagesModel::roleNames() const { QHash<int, QByteArray> roles; - roles[text] = "msg"; - roles[author] = "author"; - roles[linkurl] = "linkurl"; - roles[type] = "type"; - roles[date] = "date"; - roles[time] = "time"; - roles[ownMessage] = "ownMessage"; - roles[height] = "height"; - roles[width ] = "width"; - roles[formattedDate ] = "formattedDate"; - roles[formattedTime] = "formattedTime"; - roles[messageType] = "messageType"; + roles[text] = QByteArrayLiteral( "msg" ); + roles[author] = QByteArrayLiteral( "author" ); + roles[linkurl] = QByteArrayLiteral( "linkurl" ); + roles[type] = QByteArrayLiteral( "type" ); + roles[date] = QByteArrayLiteral( "date" ); + roles[time] = QByteArrayLiteral( "time" ); + roles[ownMessage] = QByteArrayLiteral( "ownMessage" ); + roles[height] = QByteArrayLiteral( "height" ); + roles[width ] = QByteArrayLiteral( "width" ); + roles[formattedDate ] = QByteArrayLiteral( "formattedDate" ); + roles[formattedTime] = QByteArrayLiteral( "formattedTime" ); + roles[messageType] = QByteArrayLiteral( "messageType" ); return roles; } diff --git a/CustomModels/usermodel.cpp b/CustomModels/usermodel.cpp index 4fd46b0c6a6a1298d53a3156fd4944e293470a5e..dcfe896faa30121a5ac4c88cc4ca1d20ed3d6a10 100644 --- a/CustomModels/usermodel.cpp +++ b/CustomModels/usermodel.cpp @@ -97,7 +97,7 @@ void UserModel::onCurrentChannelChanged( const QString &newText ) QHash<int, QByteArray> UserModel::roleNames() const { QHash<int, QByteArray> roles; - roles[UserName] = "username"; - roles[UserId] = "userId"; + roles[UserName] = QByteArrayLiteral( "username" ); + roles[UserId] = QByteArrayLiteral( "userId" ); return roles; } diff --git a/api/meteorddp.cpp b/api/meteorddp.cpp index 26c6d91665716c5b3da11e9543d9196c1ca11979..1266e43c706431843c5e9a20b93a36260221669a 100755 --- a/api/meteorddp.cpp +++ b/api/meteorddp.cpp @@ -39,7 +39,7 @@ MeteorDDP::MeteorDDP( QObject *parent, const QString &pUri ): QObject( parent ) void MeteorDDP::init( const QString &pUri ) { mWsClient = new Websocket( this ); - QUrl wsUri = QUrl( "wss://" + pUri + "/websocket" ); + QUrl wsUri = QUrl( QStringLiteral( "wss://" ) + pUri + QStringLiteral( "/websocket" ) ); qDebug() << wsUri; qDebug( "meteor init" ); mWebsocketUri = pUri; @@ -60,9 +60,9 @@ void MeteorDDP::connectWithServer() support.append( "1" ); - msgObj["msg"] = "connect"; - msgObj["version"] = "1"; - msgObj["support"] = support; + msgObj[QStringLiteral( "msg" )] = QStringLiteral( "connect" ); + msgObj[QStringLiteral( "version" )] = "1"; + msgObj[QStringLiteral( "support" )] = support; sendJson( msgObj ); } @@ -83,22 +83,22 @@ void MeteorDDP::onTextMessageReceived( const QString &pMsg ) QJsonDocument jsonResponse = QJsonDocument::fromJson( pMsg.toUtf8(), mError ); QJsonObject objectResponse = jsonResponse.object(); - if ( Q_LIKELY( mError->error == QJsonParseError::NoError && objectResponse.contains( "msg" ) ) ) { + if ( Q_LIKELY( mError->error == QJsonParseError::NoError && objectResponse.contains( QStringLiteral( "msg" ) ) ) ) { QDateTime now = QDateTime::currentDateTime(); mLastPing = now.toTime_t(); - QString messagePart = objectResponse["msg"].toString(); + QString messagePart = objectResponse[QStringLiteral( "msg" )].toString(); - if ( messagePart == "ping" || messagePart == "pong" ) { + if ( messagePart == QStringLiteral( "ping" ) || messagePart == QStringLiteral( "pong" ) ) { emit messageReceived( objectResponse ); } - if ( messagePart == "ping" ) { + if ( messagePart == QStringLiteral( "ping" ) ) { qDebug() << QString::number( mLastPing ); pong(); - } else if ( messagePart == "ready" ) { - if ( Q_LIKELY( objectResponse.contains( "subs" ) ) ) { - QJsonArray subsArray = objectResponse["subs"].toArray(); + } else if ( messagePart == QStringLiteral( "ready" ) ) { + if ( Q_LIKELY( objectResponse.contains( QStringLiteral( "subs" ) ) ) ) { + QJsonArray subsArray = objectResponse[QStringLiteral( "subs" )].toArray(); if ( Q_LIKELY( subsArray.size() ) ) { QString id = subsArray[0].toString(); @@ -114,20 +114,20 @@ void MeteorDDP::onTextMessageReceived( const QString &pMsg ) } //emit ddpLoginConfigured(); - } else if ( messagePart == "connected" ) { + } else if ( messagePart == QStringLiteral( "connected" ) ) { qDebug() << "connection confirmed"; emit ddpConnected(); - } else if ( messagePart == "added" || messagePart == "changed" || messagePart == "removed" ) { - if ( objectResponse.contains( "fields" ) ) { - QJsonObject fields = objectResponse["fields"].toObject(); + } else if ( messagePart == QStringLiteral( "added" ) || messagePart == QStringLiteral( "changed" ) || messagePart == QStringLiteral( "removed" ) ) { + if ( objectResponse.contains( QStringLiteral( "fields" ) ) ) { + QJsonObject fields = objectResponse[QStringLiteral( "fields" )].toObject(); - if ( Q_LIKELY( fields.contains( "args" ) ) ) { - QJsonArray args = fields["args"].toArray(); + if ( Q_LIKELY( fields.contains( QStringLiteral( "args" ) ) ) ) { + QJsonArray args = fields[QStringLiteral( "args" )].toArray(); for ( auto currentArg : args ) { QJsonObject argObj = currentArg.toObject(); - if ( Q_LIKELY( argObj.contains( "_id" ) ) ) { + if ( Q_LIKELY( argObj.contains( QStringLiteral( "_id" ) ) ) ) { //qDebug()<<"message received"; emit messageReceived( objectResponse ); } @@ -138,9 +138,9 @@ void MeteorDDP::onTextMessageReceived( const QString &pMsg ) } } - if ( objectResponse.contains( "id" ) ) { + if ( objectResponse.contains( QStringLiteral( "id" ) ) ) { - QString id = objectResponse["id"].toString(); + QString id = objectResponse[QStringLiteral( "id" )].toString(); if ( Q_LIKELY( !mReceivedEvents.contains( id ) ) ) { mReceivedEvents.insert( id ); @@ -148,7 +148,7 @@ void MeteorDDP::onTextMessageReceived( const QString &pMsg ) if ( Q_LIKELY( mResponseBinding.contains( id ) ) ) { std::function<void ( QJsonObject, MeteorDDP * )> succesFunction = mResponseBinding[id]->getSuccess(); DdpCallback errorFunction = mResponseBinding[id]->getError(); - bool error = objectResponse.contains( "error" ); + bool error = objectResponse.contains( QStringLiteral( "error" ) ); if ( Q_UNLIKELY( error && errorFunction ) ) { errorFunction( objectResponse, this ); @@ -183,8 +183,8 @@ void MeteorDDP::onConnected() void MeteorDDP::pong() { QJsonObject msgObj; - msgObj["msg"] = "pong"; - msgObj["id"] = getFrameCount(); + msgObj[QStringLiteral( "msg" )] = QStringLiteral( "pong" ); + msgObj[QStringLiteral( "id" )] = getFrameCount(); sendJson( msgObj ); } @@ -196,8 +196,8 @@ void MeteorDDP::sendRequest( const QSharedPointer<DDPRequest> &pDdpRequest ) QString frame = getFrameCount(); QJsonObject rawRequest = pDdpRequest->getRawRequest(); - if ( !rawRequest.contains( "id" ) ) { - rawRequest["id"] = frame; + if ( !rawRequest.contains( QStringLiteral( "id" ) ) ) { + rawRequest[QStringLiteral( "id" )] = frame; } pDdpRequest->setFrame( frame ); @@ -216,7 +216,7 @@ void MeteorDDP::resume() if ( mWsClient ) { #if defined(Q_OS_ANDROID) || defined(Q_OS_LINUX) qDebug() << "websocket valid: " << mWsClient->isValid(); - QUrl wsUri = QUrl( "wss://" + mWebsocketUri + "/websocket" ); + QUrl wsUri = QUrl( QStringLiteral( "wss://" ) + mWebsocketUri + QStringLiteral( "/websocket" ) ); if ( mWsClient->isDisconnected() ) { mWsClient->open( wsUri ); diff --git a/api/restapi.cpp b/api/restapi.cpp index 2d6115a2a35a1fbc77717f87a89b5c234a8f7e6c..3fc791c58ad01db1a35133b0e7f32e56897ba857 100755 --- a/api/restapi.cpp +++ b/api/restapi.cpp @@ -29,8 +29,8 @@ RestApi::RestApi( QObject *parent, const QString &pBaseUrl, const QString &pApiU void RestApi::init() { - mApiLogin = "/login"; - mApiLogoff = "/logout"; + mApiLogin = QStringLiteral( "/login" ); + mApiLogoff = QStringLiteral( "/logout" ); mCookieJar = new QNetworkCookieJar; mNam.setCookieJar( mCookieJar ); mNetworkReplies.reserve( 100 ); @@ -57,12 +57,12 @@ void RestApi::login( const QString &pUsername, const QString &pPassword ) this->mPass = pPassword; QNetworkRequest request; - request.setHeader( QNetworkRequest::ContentTypeHeader, QString( "application/x-www-form-urlencoded" ) ); + request.setHeader( QNetworkRequest::ContentTypeHeader, QString( QStringLiteral( "application/x-www-form-urlencoded" ) ) ); request.setUrl( url ); qDebug() << "send rest api login to " + mApiUri + mApiLogin; mNetworkReplies[mNam.post( request, data )] = methods::LOGIN; } else { - mLoginErrorString = "no username or password provided"; + mLoginErrorString = QStringLiteral( "no username or password provided" ); emit( loginError() ); } } @@ -75,8 +75,8 @@ void RestApi::logout() QUrl url = QString( mApiUri + mApiLogoff ); QNetworkRequest request; request.setUrl( url ); - request.setRawHeader( QByteArray( "X-Auth-Token" ), QByteArray( mToken.toLocal8Bit() ) ); - request.setRawHeader( QByteArray( "X-User-Id" ), QByteArray( mUserId.toLocal8Bit() ) ); + request.setRawHeader( QByteArray( QByteArrayLiteral( "X-Auth-Token" ) ), QByteArray( mToken.toLocal8Bit() ) ); + request.setRawHeader( QByteArray( QByteArrayLiteral( "X-User-Id" ) ), QByteArray( mUserId.toLocal8Bit() ) ); // mNetworkReplies[mNam.get( request )] = methods::LOGOFF; @@ -91,19 +91,19 @@ void RestApi::processLoginRequest( QNetworkReply *pReply ) QJsonDocument replyJson = QJsonDocument::fromJson( replyString.toUtf8(), mError ); QJsonObject replyObject = replyJson.object(); - if ( replyObject["status"].toString() == "success" && replyObject.contains( "data" ) ) { - QJsonObject data = replyObject["data"].toObject(); + if ( replyObject[QStringLiteral( "status" )].toString() == QStringLiteral( "success" ) && replyObject.contains( QStringLiteral( "data" ) ) ) { + QJsonObject data = replyObject[QStringLiteral( "data" )].toObject(); - if ( data.contains( "authToken" ) && data.contains( "userId" ) ) { - this->mToken = data["authToken"].toString(); - this->mUserId = data["userId"].toString(); + if ( data.contains( QStringLiteral( "authToken" ) ) && data.contains( QStringLiteral( "userId" ) ) ) { + this->mToken = data[QStringLiteral( "authToken" )].toString(); + this->mUserId = data[QStringLiteral( "userId" )].toString(); qDebug() << "REST token: " << this->mToken; qDebug() << "REST user: " << this->mUserId; emit( loggedIn() ); initCookie(); } } else { - mLoginErrorString = "wrong username or password"; + mLoginErrorString = QStringLiteral( "wrong username or password" ); qDebug() << "log in error" << replyString << pReply->errorString(); emit( loginError() ); } @@ -149,7 +149,7 @@ void RestApi::processNetworkRequest( QNetworkReply *pReply ) auto success = request->getSuccess(); auto error = request->getError(); - if ( ( replyObject["status"].toString() == "success" || ( status >= 200 && status < 300 ) ) && success ) { + if ( ( replyObject[QStringLiteral( "status" )].toString() == QStringLiteral( "success" ) || ( status >= 200 && status < 300 ) ) && success ) { success( pReply, replyObject, this ); } else if ( error ) { error( pReply, replyObject, this ); @@ -200,8 +200,8 @@ QNetworkReply *RestApi::post( const QString &pUrl, const QByteArray &pData, cons QNetworkRequest request; request.setUrl( pUrl ); request.setHeader( QNetworkRequest::ContentTypeHeader, pMimeType ); - request.setRawHeader( QByteArray( "X-Auth-Token" ), QByteArray( mToken.toLocal8Bit() ) ); - request.setRawHeader( QByteArray( "X-User-Id" ), QByteArray( mUserId.toLocal8Bit() ) ); + request.setRawHeader( QByteArray( QByteArrayLiteral( "X-Auth-Token" ) ), QByteArray( mToken.toLocal8Bit() ) ); + request.setRawHeader( QByteArray( QByteArrayLiteral( "X-User-Id" ) ), QByteArray( mUserId.toLocal8Bit() ) ); request.setAttribute( QNetworkRequest::HttpPipeliningAllowedAttribute, true ); request.setAttribute( QNetworkRequest::HTTP2AllowedAttribute, true ); request.setAttribute( QNetworkRequest::SpdyAllowedAttribute, true ); @@ -213,8 +213,8 @@ QNetworkReply *RestApi::get( const QString &pUrl, const QString &pMimeType ) { QNetworkRequest request; request.setUrl( pUrl ); - request.setRawHeader( QByteArray( "X-Auth-Token" ), QByteArray( mToken.toLocal8Bit() ) ); - request.setRawHeader( QByteArray( "X-User-Id" ), QByteArray( mUserId.toLocal8Bit() ) ); + request.setRawHeader( QByteArray( QByteArrayLiteral( "X-Auth-Token" ) ), QByteArray( mToken.toLocal8Bit() ) ); + request.setRawHeader( QByteArray( QByteArrayLiteral( "X-User-Id" ) ), QByteArray( mUserId.toLocal8Bit() ) ); request.setHeader( QNetworkRequest::ContentTypeHeader, QString( pMimeType ) ); request.setAttribute( QNetworkRequest::HttpPipeliningAllowedAttribute, true ); request.setAttribute( QNetworkRequest::HTTP2AllowedAttribute, true ); @@ -256,8 +256,8 @@ void RestApi::processDownload( QNetworkReply *pReply ) QString url = pReply->url().toString(); QString filename = pReply->url().fileName(); QString directory = QStandardPaths::writableLocation( QStandardPaths::TempLocation ); - QString filePath = directory + "/" + filename; - filePath.replace( filePath.length() - 4, 4, "." + suffix ); + QString filePath = directory + '/' + filename; + filePath.replace( filePath.length() - 4, 4, '.' + suffix ); QFile file( filePath ); if ( file.open( QIODevice::ReadWrite ) ) { @@ -295,13 +295,13 @@ void RestApi::initCookie() QString host = mBaseUrl.split( "//" )[1]; QNetworkCookie rc_uid; rc_uid.setDomain( host ); - rc_uid.setName( "rc_uid" ); + rc_uid.setName( QByteArrayLiteral( "rc_uid" ) ); rc_uid.setValue( mUserId.toUtf8() ); QNetworkCookie rc_token; rc_token.setDomain( host ); - rc_token.setName( "rc_token" ); + rc_token.setName( QByteArrayLiteral( "rc_token" ) ); rc_token.setValue( mToken.toUtf8() ); mCookieJar->insertCookie( rc_token ); diff --git a/ddpRequests/ddploginrequest.cpp b/ddpRequests/ddploginrequest.cpp index 306b3708fdad122491057b9722d0ceb2f0ca86c8..b4164a2c6a8f2e053511d3d5f7deff4d0d4557d0 100755 --- a/ddpRequests/ddploginrequest.cpp +++ b/ddpRequests/ddploginrequest.cpp @@ -31,9 +31,9 @@ DDPLoginRequest::DDPLoginRequest( const QString &pToken ) { //["{\"msg\":\"method\",\"method\":\"login\",\"params\":[{\"resume\":\"mkdhgeChLGBAzGleEilxx7CgqIVkjthWdLmWsrCKsmH\"}],\"id\":\"1\"}"] - QJsonObject tokenParameter = {{"resume", pToken}}; + QJsonObject tokenParameter = {{QStringLiteral( "resume" ), pToken}}; QJsonArray params = {tokenParameter}; - buildRequest( "login", params ); + buildRequest( QStringLiteral( "login" ), params ); } DDPLoginRequest::DDPLoginRequest( const QString &pToken, const std::function<void ( QJsonObject, MeteorDDP * )> &success ): DDPLoginRequest( pToken ) @@ -50,23 +50,23 @@ DDPLoginRequest::DDPLoginRequest( const QString &pUsername, const QString &pPswH QJsonObject loginData; QJsonObject passwordObj; - QRegularExpression emailRegex( "^[0-9a-zA-Z]+([0-9a-zA-Z]*[-._+])*[0-9a-zA-Z]+@[0-9a-zA-Z]+([-.][0-9a-zA-Z]+)*([0-9a-zA-Z]*[.])[a-zA-Z]{2,6}$" ); + QRegularExpression emailRegex( QStringLiteral( "^[0-9a-zA-Z]+([0-9a-zA-Z]*[-._+])*[0-9a-zA-Z]+@[0-9a-zA-Z]+([-.][0-9a-zA-Z]+)*([0-9a-zA-Z]*[.])[a-zA-Z]{2,6}$" ) ); QRegularExpressionMatch emailMatch = emailRegex.match( pUsername ); if ( emailMatch.hasMatch() ) { - user["email"] = pUsername; + user[QStringLiteral( "email" )] = pUsername; } else { - user["username"] = pUsername; + user[QStringLiteral( "username" )] = pUsername; } //QByteArray hashArray = QCryptographicHash::hash( password.toUtf8(), QCryptographicHash::Sha256 ); QString hash = pPswHash; - passwordObj["digest"] = hash; - passwordObj["algorithm"] = "sha-256"; - loginData["user"] = user; - loginData["password"] = passwordObj; + passwordObj[QStringLiteral( "digest" )] = hash; + passwordObj[QStringLiteral( "algorithm" )] = QStringLiteral( "sha-256" ); + loginData[QStringLiteral( "user" )] = user; + loginData[QStringLiteral( "password" )] = passwordObj; params.append( loginData ); - buildRequest( "login", params ); + buildRequest( QStringLiteral( "login" ), params ); } DDPLoginRequest::DDPLoginRequest( const QString &pUsername, const QString &pPswHash, const std::function<void ( QJsonObject, MeteorDDP * )> &success ): DDPLoginRequest( pUsername, pPswHash ) diff --git a/ddpRequests/ddpopenidloginrequest.cpp b/ddpRequests/ddpopenidloginrequest.cpp index ea23b1bc5718f9294a590eae275b059ab1fa2d63..fb3b197ea429e1238fae91b15c5ed270ce540f41 100644 --- a/ddpRequests/ddpopenidloginrequest.cpp +++ b/ddpRequests/ddpopenidloginrequest.cpp @@ -26,10 +26,10 @@ DDPOpenIDLoginRequest::DDPOpenIDLoginRequest( const QString &pToken, const QStri { QJsonObject tokenParameter; QJsonObject oauth; - oauth["credentialToken"] = pToken; - oauth["credentialSecret"] = pSecret; - tokenParameter["oauth"] = oauth; + oauth[QStringLiteral( "credentialToken" )] = pToken; + oauth[QStringLiteral( "credentialSecret" )] = pSecret; + tokenParameter[QStringLiteral( "oauth" )] = oauth; QJsonArray params; params.append( tokenParameter ); - buildRequest( "login", params ); + buildRequest( QStringLiteral( "login" ), params ); } diff --git a/ddpRequests/ddpsamlloginrequest.cpp b/ddpRequests/ddpsamlloginrequest.cpp index c5bc7487e5c66c82c09424f0be6891e2d892d342..7ab8714f0ef43dabf00586f0bdfc907f39bb0c3c 100644 --- a/ddpRequests/ddpsamlloginrequest.cpp +++ b/ddpRequests/ddpsamlloginrequest.cpp @@ -26,8 +26,8 @@ ddpSamlLoginRequest::ddpSamlLoginRequest( const QString &pSamlToken ) { qDebug() << "saml token: " << pSamlToken; QJsonObject tokenParameter; - tokenParameter["saml"] = true; - tokenParameter["credentialToken"] = pSamlToken; + tokenParameter[QStringLiteral( "saml" )] = true; + tokenParameter[QStringLiteral( "credentialToken" )] = pSamlToken; QJsonArray params = {tokenParameter}; - buildRequest( "login", params ); + buildRequest( QStringLiteral( "login" ), params ); } diff --git a/ddpRequests/ddpsubscriptionrequest.cpp b/ddpRequests/ddpsubscriptionrequest.cpp index da6a374a59d9124c47d34868cfde1c692b01f58f..c2d70f73688c054b6060893ba630e3ef74fd0d4c 100755 --- a/ddpRequests/ddpsubscriptionrequest.cpp +++ b/ddpRequests/ddpsubscriptionrequest.cpp @@ -43,8 +43,8 @@ void DDPSubscriptionRequest::buildRequest( const QString &pCollection, const QJs QJsonArray params = pParams; QJsonArray args; QJsonObject obj; - obj["useCollection"] = false; - obj["args"] = args; + obj[QStringLiteral( "useCollection" )] = false; + obj[QStringLiteral( "args" )] = args; int major = std::get<0>( RocketChatServerConfig::serverVersion ); int minor = std::get<1>( RocketChatServerConfig::serverVersion ); int patch = std::get<2>( RocketChatServerConfig::serverVersion ); @@ -56,8 +56,8 @@ void DDPSubscriptionRequest::buildRequest( const QString &pCollection, const QJs } QJsonObject request; - request["name"] = pCollection; - request["msg"] = "sub"; - request["params"] = params; + request[QStringLiteral( "name" )] = pCollection; + request[QStringLiteral( "msg" )] = QStringLiteral( "sub" ); + request[QStringLiteral( "params" )] = params; mRawRequest = request; } diff --git a/ddpRequests/ddpufscreaterequest.cpp b/ddpRequests/ddpufscreaterequest.cpp index f4e6565761d3232e690f9969020babf746d9d7ac..3965e1ed3ca41eac545d702d57ac2ab5531d4bd2 100755 --- a/ddpRequests/ddpufscreaterequest.cpp +++ b/ddpRequests/ddpufscreaterequest.cpp @@ -32,11 +32,11 @@ DDPUfsCreateRequest::DDPUfsCreateRequest( const QString &pChannelId, const QStri { QJsonArray params; QJsonObject paramObj; - paramObj["name"] = pFilename; - paramObj["size"] = pSize; - paramObj["type"] = pMime; - paramObj["rid"] = pChannelId; - paramObj["store"] = "rocketchat_uploads"; + paramObj[QStringLiteral( "name" )] = pFilename; + paramObj[QStringLiteral( "size" )] = pSize; + paramObj[QStringLiteral( "type" )] = pMime; + paramObj[QStringLiteral( "rid" )] = pChannelId; + paramObj[QStringLiteral( "store" )] = QStringLiteral( "rocketchat_uploads" ); params.append( paramObj ); - buildRequest( "ufsCreate", params ); + buildRequest( QStringLiteral( "ufsCreate" ), params ); } diff --git a/ddpRequests/ddpunsubscriptionrequest.cpp b/ddpRequests/ddpunsubscriptionrequest.cpp index ebeeaf098849306c04837f9ba186ef8760bbf14e..72f61d371c06735abcf7d60c1772df6a0f06bec8 100755 --- a/ddpRequests/ddpunsubscriptionrequest.cpp +++ b/ddpRequests/ddpunsubscriptionrequest.cpp @@ -31,7 +31,7 @@ DDPUnsubscriptionRequest::DDPUnsubscriptionRequest( const QString &pId ) void DDPUnsubscriptionRequest::buildRequest( const QString &pId ) { QJsonObject request; - request["msg"] = "unsub"; - request["id"] = pId; + request[QStringLiteral( "msg" )] = QStringLiteral( "unsub" ); + request[QStringLiteral( "id" )] = pId; mRawRequest = request; } diff --git a/ddpRequests/methodrequest.cpp b/ddpRequests/methodrequest.cpp index 254c541410213eb03f4fda5cacb0f5f73e62cf77..452ef06003ebd84372b7b86b1002ae886926a5d5 100755 --- a/ddpRequests/methodrequest.cpp +++ b/ddpRequests/methodrequest.cpp @@ -40,8 +40,8 @@ DDPMethodRequest::DDPMethodRequest() void DDPMethodRequest::buildRequest( const QString &method, const QJsonArray ¶ms ) { QJsonObject request; - request["msg"] = "method"; - request["method"] = method; - request["params"] = params; + request[QStringLiteral( "msg" )] = QStringLiteral( "method" ); + request[QStringLiteral( "method" )] = method; + request[QStringLiteral( "params" )] = params; mRawRequest = request; } diff --git a/ddpRequests/pingrequest.cpp b/ddpRequests/pingrequest.cpp index 1888a9b1eefde06bd66e6df40b89744bf1967a07..148b8517b3567b49fc1ce59e464b1569202fa9db 100755 --- a/ddpRequests/pingrequest.cpp +++ b/ddpRequests/pingrequest.cpp @@ -24,7 +24,7 @@ PingRequest::PingRequest() { QJsonObject request; - request["msg"] = "ping"; + request[QStringLiteral( "msg" )] = QStringLiteral( "ping" ); std::function<void ( QJsonObject, MeteorDDP * )> succesFunction = [this]( QJsonObject pRequest, MeteorDDP * pDdp ) { Q_UNUSED( pRequest ); Q_UNUSED( pDdp ); diff --git a/ddpRequests/rocketchatadduserstochannel.cpp b/ddpRequests/rocketchatadduserstochannel.cpp index 88ba90a8ff47c27e7cf2d9214c40e4d2d4af57f7..8c7b5cdabd7940db01803fc8064a02f0606daf70 100755 --- a/ddpRequests/rocketchatadduserstochannel.cpp +++ b/ddpRequests/rocketchatadduserstochannel.cpp @@ -28,10 +28,10 @@ RocketChatAddUsersToChannel::RocketChatAddUsersToChannel( const QString &pChanne QJsonArray params; QJsonObject paramObj; - paramObj["rid"] = pChannel; - paramObj["username"] = users.first(); + paramObj[QStringLiteral( "rid" )] = pChannel; + paramObj[QStringLiteral( "username" )] = users.first(); params.append( paramObj ); - buildRequest( "addUserToRoom", params ); + buildRequest( QStringLiteral( "addUserToRoom" ), params ); } RocketChatAddUsersToChannel::RocketChatAddUsersToChannel( const QString &pChannel, const QString &pUsername ): RocketChatAddUsersToChannel( pChannel, QStringList( pUsername ) ) diff --git a/ddpRequests/rocketchatblockuserrequest.cpp b/ddpRequests/rocketchatblockuserrequest.cpp index 9c0684cd4b42fe06482a4c2773a3bd0ea7fa07a0..3b736d0039e89a1c81057ab69b866fe6e74ec235 100644 --- a/ddpRequests/rocketchatblockuserrequest.cpp +++ b/ddpRequests/rocketchatblockuserrequest.cpp @@ -4,8 +4,8 @@ RocketChatBlockUserRequest::RocketChatBlockUserRequest( const QString &pChannelI { QJsonArray params; QJsonObject userData; - userData["rid"] = pChannelId; - userData["blocked"] = pUserId; + userData[QStringLiteral( "rid" )] = pChannelId; + userData[QStringLiteral( "blocked" )] = pUserId; params.append( userData ); - buildRequest( "blockUser", params ); + buildRequest( QStringLiteral( "blockUser" ), params ); } diff --git a/ddpRequests/rocketchatchangeuserpresancedefaultstatus.cpp b/ddpRequests/rocketchatchangeuserpresancedefaultstatus.cpp index 0f937cbf212d1cf899f44b9adfef8144ded09d90..3757a5770beb426333fd2165b9b4cea8027c1310 100644 --- a/ddpRequests/rocketchatchangeuserpresancedefaultstatus.cpp +++ b/ddpRequests/rocketchatchangeuserpresancedefaultstatus.cpp @@ -28,14 +28,14 @@ RocketChatChangeUserPresanceDefaultStatus::RocketChatChangeUserPresanceDefaultSt QString statusText; if ( pStatus == status::AWAY ) { - statusText = "away"; + statusText = QStringLiteral( "away" ); } else if ( pStatus == status::ONLINE ) { - statusText = "online"; + statusText = QStringLiteral( "online" ); } else if ( pStatus == status::OFFLINE ) { - statusText = "offline"; + statusText = QStringLiteral( "offline" ); } params.append( statusText ); - buildRequest( "UserPresence:setDefaultStatus", params ); + buildRequest( QStringLiteral( "UserPresence:setDefaultStatus" ), params ); } diff --git a/ddpRequests/rocketchatcreateaccount.cpp b/ddpRequests/rocketchatcreateaccount.cpp index 1147bffa2db82c3a5fcdf7c05cf6887796b6dfbc..fc2eaccfb553aa930d66a5ccd3d565b531e49ec3 100644 --- a/ddpRequests/rocketchatcreateaccount.cpp +++ b/ddpRequests/rocketchatcreateaccount.cpp @@ -25,8 +25,8 @@ RocketChatCreateAccount::RocketChatCreateAccount( const QString &username, const { QJsonArray params; QJsonObject userData; - userData["email"] = email; - userData["name"] = username; - userData["pass"] = password; - buildRequest( "registerUser", params ); + userData[QStringLiteral( "email" )] = email; + userData[QStringLiteral( "name" )] = username; + userData[QStringLiteral( "pass" )] = password; + buildRequest( QStringLiteral( "registerUser" ), params ); } diff --git a/ddpRequests/rocketchatcreatechannelrequest.cpp b/ddpRequests/rocketchatcreatechannelrequest.cpp index f265f2162ddf7747e238e8558774057fb5bd3c4e..36059d6f92893f33071899171a3c84290387e755 100755 --- a/ddpRequests/rocketchatcreatechannelrequest.cpp +++ b/ddpRequests/rocketchatcreatechannelrequest.cpp @@ -25,7 +25,7 @@ RocketChatCreateChannelRequest::RocketChatCreateChannelRequest( const QString &p { QJsonArray users = QJsonArray::fromStringList( pUserName ); QJsonArray params = {pChannelName, users, pReadonly}; - buildRequest( "createChannel", params ); + buildRequest( QStringLiteral( "createChannel" ), params ); setSuccess( pSuccess ); } diff --git a/ddpRequests/rocketchatcreateprivategrouprequest.cpp b/ddpRequests/rocketchatcreateprivategrouprequest.cpp index 06192b3c1d21a8656f39cc9dce1fee5a3298a8ce..039fd78a27664449e0e995ff57ecb3a94b53ed2f 100755 --- a/ddpRequests/rocketchatcreateprivategrouprequest.cpp +++ b/ddpRequests/rocketchatcreateprivategrouprequest.cpp @@ -25,7 +25,7 @@ RocketChatCreatePrivateGroupRequest::RocketChatCreatePrivateGroupRequest( const { QJsonArray users = QJsonArray::fromStringList( pUserName ); QJsonArray params = {pChannelName, users, pReadonly}; - buildRequest( "createPrivateGroup", params ); + buildRequest( QStringLiteral( "createPrivateGroup" ), params ); setSuccess( pSuccess ); } diff --git a/ddpRequests/rocketchatgetroomsrequest.cpp b/ddpRequests/rocketchatgetroomsrequest.cpp index 6fad490ac6381abc589e59033d31b2e41062b784..5b84e5bc18f5ca1f58daa558da2476b071bbd2b5 100755 --- a/ddpRequests/rocketchatgetroomsrequest.cpp +++ b/ddpRequests/rocketchatgetroomsrequest.cpp @@ -21,7 +21,7 @@ #include "rocketchatgetroomsrequest.h" -RocketChatGetRoomsRequest::RocketChatGetRoomsRequest( const std::function<void ( QJsonObject, MeteorDDP * )> &success ): DDPMethodRequest( "rooms/get", {}, success ) +RocketChatGetRoomsRequest::RocketChatGetRoomsRequest( const std::function<void ( QJsonObject, MeteorDDP * )> &success ): DDPMethodRequest( QStringLiteral( "rooms/get" ), {}, success ) { } diff --git a/ddpRequests/rocketchatleaveroomrequest.cpp b/ddpRequests/rocketchatleaveroomrequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4dc7ccf610d8e1c8156d57fcc25bc0fa9479fbd5 --- /dev/null +++ b/ddpRequests/rocketchatleaveroomrequest.cpp @@ -0,0 +1,8 @@ +#include "rocketchatleaveroomrequest.h" + +RocketChatLeaveRoomRequest::RocketChatLeaveRoomRequest( const QString &pChanneId ) +{ + QJsonArray params; + params.append( pChanneId ); + buildRequest( QStringLiteral( "leaveRoom" ), params ); +} diff --git a/ddpRequests/rocketchatleaveroomrequest.h b/ddpRequests/rocketchatleaveroomrequest.h new file mode 100644 index 0000000000000000000000000000000000000000..26b632e96b623795b9a56069fc24f4bcb94adb11 --- /dev/null +++ b/ddpRequests/rocketchatleaveroomrequest.h @@ -0,0 +1,12 @@ +#ifndef ROCKETCHATLEAVEROOM_H +#define ROCKETCHATLEAVEROOM_H + +#include "ddpmethodrequest.h" + +class RocketChatLeaveRoomRequest: public DDPMethodRequest +{ + public: + RocketChatLeaveRoomRequest( const QString &pChanneId ); +}; + +#endif // ROCKETCHATLEAVEROOM_H diff --git a/ddpRequests/rocketchatmarkchannelasreadrequest.cpp b/ddpRequests/rocketchatmarkchannelasreadrequest.cpp index c2236ea99e5b026a0f4846b3e993a7710f0cc974..14d079be229773dbdfb61a69e9774a2e60435895 100755 --- a/ddpRequests/rocketchatmarkchannelasreadrequest.cpp +++ b/ddpRequests/rocketchatmarkchannelasreadrequest.cpp @@ -23,5 +23,5 @@ RocketChatMarkChannelAsReadRequest::RocketChatMarkChannelAsReadRequest( const QString &pChannelId ) { - buildRequest( "readMessages", {pChannelId} ); + buildRequest( QStringLiteral( "readMessages" ), {pChannelId} ); } diff --git a/ddpRequests/rocketchatmessagesearchrequest.cpp b/ddpRequests/rocketchatmessagesearchrequest.cpp index 54d5db9c405197d131fe70e77471450437d3c9ca..4ddf82fbcc3547ee3dc27f7eacfc91814fe0dd5b 100755 --- a/ddpRequests/rocketchatmessagesearchrequest.cpp +++ b/ddpRequests/rocketchatmessagesearchrequest.cpp @@ -24,7 +24,7 @@ RocketChatMessageSearchRequest::RocketChatMessageSearchRequest( const QString &pChannelId, const QString &pTerm ) { QJsonArray params = {pTerm, pChannelId}; - buildRequest( "messageSearch", params ); + buildRequest( QStringLiteral( "messageSearch" ), params ); } RocketChatMessageSearchRequest::RocketChatMessageSearchRequest( const QString &pChannelId, const QString &pTerm, const std::function<void ( QJsonObject, MeteorDDP * )> &pSuccess ): RocketChatMessageSearchRequest( pChannelId, pTerm ) diff --git a/ddpRequests/rocketchatnotifynoticesrequest.cpp b/ddpRequests/rocketchatnotifynoticesrequest.cpp index 028e883d8ff17828cf016eac01a27133082b1846..3add9360a55430c77de5ad428b01bf6e4fd5326c 100755 --- a/ddpRequests/rocketchatnotifynoticesrequest.cpp +++ b/ddpRequests/rocketchatnotifynoticesrequest.cpp @@ -21,7 +21,7 @@ #include "rocketchatnotifynoticesrequest.h" -RocketChatNotifyNoticesRequest::RocketChatNotifyNoticesRequest( const QString &pUserId ): RocketChatSubscribeUserNotify( pUserId + "/notification" ) +RocketChatNotifyNoticesRequest::RocketChatNotifyNoticesRequest( const QString &pUserId ): RocketChatSubscribeUserNotify( pUserId + QStringLiteral( "/notification" ) ) { } diff --git a/ddpRequests/rocketchatspotlightrequest.cpp b/ddpRequests/rocketchatspotlightrequest.cpp index 7892e5e33128d4e16bfc34d0cf553824d2695aa6..432474385928a11c6d9bdb8d97927db92e7e7f07 100644 --- a/ddpRequests/rocketchatspotlightrequest.cpp +++ b/ddpRequests/rocketchatspotlightrequest.cpp @@ -31,5 +31,5 @@ RocketChatSpotLightRequest::RocketChatSpotLightRequest( const QString &term ) QJsonArray params; params.append( term ); - buildRequest( "addUserToRoom", params ); + buildRequest( QStringLiteral( "addUserToRoom" ), params ); } diff --git a/ddpRequests/rocketchatsubscribeactiveusers.cpp b/ddpRequests/rocketchatsubscribeactiveusers.cpp index de3caf37090de45209be58c86288549f92d564a1..056e098fe863f7bbff6a08b92febc9b7ba4eb696 100644 --- a/ddpRequests/rocketchatsubscribeactiveusers.cpp +++ b/ddpRequests/rocketchatsubscribeactiveusers.cpp @@ -21,7 +21,7 @@ #include "rocketchatsubscribeactiveusers.h" -RocketChatSubscribeActiveUsers::RocketChatSubscribeActiveUsers(): DDPSubscriptionRequest( "activeUsers", {} ) +RocketChatSubscribeActiveUsers::RocketChatSubscribeActiveUsers(): DDPSubscriptionRequest( QStringLiteral( "activeUsers" ), {} ) { } diff --git a/ddpRequests/rocketchatsubscribechannelrequest.cpp b/ddpRequests/rocketchatsubscribechannelrequest.cpp index 39cb15e95a5d5b0e017470a28b7857ebcd722cf2..f0b16fb67146a5080ccb68cc8fa63ae96f021bc2 100755 --- a/ddpRequests/rocketchatsubscribechannelrequest.cpp +++ b/ddpRequests/rocketchatsubscribechannelrequest.cpp @@ -21,7 +21,7 @@ #include "rocketchatsubscribechannelrequest.h" -RocketChatSubscribeChannelRequest::RocketChatSubscribeChannelRequest( const QString &pRoomId ): DDPSubscriptionRequest( "stream-room-messages", +RocketChatSubscribeChannelRequest::RocketChatSubscribeChannelRequest( const QString &pRoomId ): DDPSubscriptionRequest( QStringLiteral( "stream-room-messages" ), { pRoomId } ) diff --git a/ddpRequests/rocketchatsubscribeloginmethods.cpp b/ddpRequests/rocketchatsubscribeloginmethods.cpp index a501a1f003078dddcbff35b2bb95d7b0cbddbc28..bf7ec7a1a5082858a350b79aa71429f44df9f461 100644 --- a/ddpRequests/rocketchatsubscribeloginmethods.cpp +++ b/ddpRequests/rocketchatsubscribeloginmethods.cpp @@ -21,7 +21,7 @@ #include "rocketchatsubscribeloginmethods.h" -RocketChatSubscribeLoginMethods::RocketChatSubscribeLoginMethods(): DDPSubscriptionRequest( "meteor.loginServiceConfiguration", {} ) +RocketChatSubscribeLoginMethods::RocketChatSubscribeLoginMethods(): DDPSubscriptionRequest( QStringLiteral( "meteor.loginServiceConfiguration" ), {} ) { } diff --git a/ddpRequests/rocketchatsubscriberoomrequest.cpp b/ddpRequests/rocketchatsubscriberoomrequest.cpp index 2a262ffca8c4252ba0d95dd9011098d38a275906..ee79ed650ff71534f245394e92db667047663df5 100755 --- a/ddpRequests/rocketchatsubscriberoomrequest.cpp +++ b/ddpRequests/rocketchatsubscriberoomrequest.cpp @@ -21,7 +21,7 @@ #include "rocketchatsubscriberoomrequest.h" -RocketChatSubscribeRoomRequest::RocketChatSubscribeRoomRequest( const QString &roomName ): DDPSubscriptionRequest( "room", +RocketChatSubscribeRoomRequest::RocketChatSubscribeRoomRequest( const QString &roomName ): DDPSubscriptionRequest( QStringLiteral( "room" ), { roomName } ) diff --git a/ddpRequests/rocketchatsubscribeusernotify.cpp b/ddpRequests/rocketchatsubscribeusernotify.cpp index c82b7fda6faa7c0e9da94cf8e5b38916f67710c8..9c3148b6b879ad0344049002afbd55c3e3eebe4c 100755 --- a/ddpRequests/rocketchatsubscribeusernotify.cpp +++ b/ddpRequests/rocketchatsubscribeusernotify.cpp @@ -24,5 +24,5 @@ RocketChatSubscribeUserNotify::RocketChatSubscribeUserNotify( const QString &pUsername ): DDPSubscriptionRequest() { QJsonArray params = {pUsername, false}; - buildRequest( "stream-notify-user", params ); + buildRequest( QStringLiteral( "stream-notify-user" ), params ); } diff --git a/ddpRequests/rocketchatsubscriptionchangedrequest.cpp b/ddpRequests/rocketchatsubscriptionchangedrequest.cpp index 3fef082e5aff22920fff03f99ce343f7dea67ae6..247ef81e14775c7a3a4b28506c8fea74fa9ba063 100755 --- a/ddpRequests/rocketchatsubscriptionchangedrequest.cpp +++ b/ddpRequests/rocketchatsubscriptionchangedrequest.cpp @@ -21,7 +21,7 @@ #include "rocketchatsubscriptionchangedrequest.h" -RocketChatSubScriptionChangedRequest::RocketChatSubScriptionChangedRequest( const QString &pUserid ): RocketChatSubscribeUserNotify( pUserid + "/subscriptions-changed" ) +RocketChatSubScriptionChangedRequest::RocketChatSubScriptionChangedRequest( const QString &pUserid ): RocketChatSubscribeUserNotify( pUserid + QStringLiteral( "/subscriptions-changed" ) ) { } diff --git a/ddpRequests/rocketchatunblockuserrequest.cpp b/ddpRequests/rocketchatunblockuserrequest.cpp index eb8ec2b320b4fc8d47b968a81eb13e6b969c51f0..7cf75bfa56c5eb5fd63b47d9de900e7286c1feaa 100644 --- a/ddpRequests/rocketchatunblockuserrequest.cpp +++ b/ddpRequests/rocketchatunblockuserrequest.cpp @@ -4,8 +4,8 @@ RocketChatUnblockUserRequest::RocketChatUnblockUserRequest( const QString &pChan { QJsonArray params; QJsonObject userData; - userData["rid"] = pChannelId; - userData["blocked"] = pUserId; + userData[QStringLiteral( "rid" )] = pChannelId; + userData[QStringLiteral( "blocked" )] = pUserId; params.append( userData ); - buildRequest( "unblockUser", params ); + buildRequest( QStringLiteral( "unblockUser" ), params ); } diff --git a/ddpRequests/rocketchatupdatejitsitimeout.cpp b/ddpRequests/rocketchatupdatejitsitimeout.cpp index 4906dabce8c195887b10a5aa48db33a57d5343bc..01f58fb29cd6c6ade1ac28c9798d83de9e3670b1 100644 --- a/ddpRequests/rocketchatupdatejitsitimeout.cpp +++ b/ddpRequests/rocketchatupdatejitsitimeout.cpp @@ -26,7 +26,7 @@ RocketChatUpdateJitsiTimeout::RocketChatUpdateJitsiTimeout( const QString &pRid { QJsonArray params; params.append( pRid ); - buildRequest( "jitsi:updateTimeout", params ); + buildRequest( QStringLiteral( "jitsi:updateTimeout" ), params ); } diff --git a/ddpRequests/rocketchatupdatepushtokenrequest.cpp b/ddpRequests/rocketchatupdatepushtokenrequest.cpp index 7738b88661fae5db2f2cd680c9ab93c37366da2f..10c9c8feb5981451c9bbac0ce5b355c4c3f84dcd 100755 --- a/ddpRequests/rocketchatupdatepushtokenrequest.cpp +++ b/ddpRequests/rocketchatupdatepushtokenrequest.cpp @@ -32,7 +32,7 @@ RocketChatUpdatePushTokenRequest::RocketChatUpdatePushTokenRequest( const QStrin Q_UNUSED( pToken ); #endif #ifdef Q_OS_ANDROID - tokenObject["gcm"] = pToken; + tokenObject[QStringLiteral( "gcm" )] = pToken; #endif #ifdef Q_OS_IOS tokenObject["apn"] = pToken; @@ -42,12 +42,12 @@ RocketChatUpdatePushTokenRequest::RocketChatUpdatePushTokenRequest( const QStrin #endif if ( tokenObject.size() ) { - options["userId"] = pUserId; - options["token"] = tokenObject; + options[QStringLiteral( "userId" )] = pUserId; + options[QStringLiteral( "token" )] = tokenObject; //TODO: handle appName - options["appName"] = "qt mobile client"; + options[QStringLiteral( "appName" )] = QStringLiteral( "qt mobile client" ); params.append( options ); - buildRequest( "raix:push-update", params ); + buildRequest( QStringLiteral( "raix:push-update" ), params ); } } diff --git a/engine.pro b/engine.pro index bdbee04702809ee7c79f531b6609d18cd066515a..cd2a9a34233c9eb08e604b3a05b3cb7de3b03c84 100644 --- a/engine.pro +++ b/engine.pro @@ -87,7 +87,9 @@ SOURCES += api/meteorddp.cpp \ repos/entities/loginmethod.cpp \ restRequests/getserverinforequest.cpp \ ddpRequests/rocketchatblockuserrequest.cpp \ - ddpRequests/rocketchatunblockuserrequest.cpp + ddpRequests/rocketchatunblockuserrequest.cpp \ + restRequests/getserverinforequest.cpp \ + ddpRequests/rocketchatleaveroomrequest.cpp HEADERS += \ api/meteorddp.h \ @@ -175,7 +177,9 @@ HEADERS += \ repos/entities/loginmethod.h \ restRequests/getserverinforequest.h \ ddpRequests/rocketchatblockuserrequest.h \ - ddpRequests/rocketchatunblockuserrequest.h + ddpRequests/rocketchatunblockuserrequest.h \ + restRequests/getserverinforequest.h \ + ddpRequests/rocketchatleaveroomrequest.h linux{ @@ -266,3 +270,4 @@ CONFIG(release, debug|release) { RESOURCES += \ sql.qrc + diff --git a/persistancelayer.cpp b/persistancelayer.cpp index 51688d6b6da07a4f6e6b0c7328792f0bd194a976..78cf4afd6f6932af40354dfbdcacc199b8843f06 100755 --- a/persistancelayer.cpp +++ b/persistancelayer.cpp @@ -51,7 +51,7 @@ PersistanceLayer *PersistanceLayer::instance() void PersistanceLayer::initShema() { QSqlQuery pragmaquery; - pragmaquery.prepare( "PRAGMA synchronous = OFF" ); + pragmaquery.prepare( QStringLiteral( "PRAGMA synchronous = OFF" ) ); if ( !pragmaquery.exec() ) { qDebug() << pragmaquery.lastError(); @@ -61,13 +61,13 @@ void PersistanceLayer::initShema() // if(!pragmaquery.exec()){ // qDebug() << pragmaquery.lastError(); // } - pragmaquery.prepare( "PRAGMA JOURNAL_MODE=MEMORY" ); + pragmaquery.prepare( QStringLiteral( "PRAGMA JOURNAL_MODE=MEMORY" ) ); if ( !pragmaquery.exec() ) { qDebug() << pragmaquery.lastError(); } - pragmaquery.prepare( "PRAGMA TEMP_STORE=MEMORY" ); + pragmaquery.prepare( QStringLiteral( "PRAGMA TEMP_STORE=MEMORY" ) ); if ( !pragmaquery.exec() ) { qDebug() << pragmaquery.lastError(); @@ -76,77 +76,77 @@ void PersistanceLayer::initShema() transaction(); QSqlQuery query; - query.prepare( "CREATE TABLE IF NOT EXISTS user_data " - "(id integer primary key," - "username varchar(40)," - "password varchar(40)," - "token varchar(100)," - "token_expire integer," - "user_id varchar(12)," - "server varchar(100))" ); + query.prepare( QStringLiteral( "CREATE TABLE IF NOT EXISTS user_data " + "(id integer primary key," + "username varchar(40)," + "password varchar(40)," + "token varchar(100)," + "token_expire integer," + "user_id varchar(12)," + "server varchar(100))" ) ); if ( !query.exec() ) { qWarning() << query.lastError(); } - query.prepare( "CREATE TABLE IF NOT EXISTS rooms " - "(id varchar(12) primary key, " - "name varchar(100)," - "type varchar(10)," - "read_only bool," - "muted text," - "archived bool," - "joined bool, " - "blocked bool DEFAULT 0)" ); + query.prepare( QStringLiteral( "CREATE TABLE IF NOT EXISTS rooms " + "(id varchar(12) primary key, " + "name varchar(100)," + "type varchar(10)," + "read_only bool," + "muted text," + "archived bool," + "joined bool, " + "blocked bool DEFAULT 0)" ) ); if ( !query.exec() ) { qWarning() << query.lastError(); } - query.prepare( "CREATE TABLE IF NOT EXISTS messages " - "(id varchar(12) primary key," - "rid varchar(12)," - "author varchar(30)," - "ts integer," - "read BOOLEAN DEFAULT FALSE," - "json text)" ); + query.prepare( QStringLiteral( "CREATE TABLE IF NOT EXISTS messages " + "(id varchar(12) primary key," + "rid varchar(12)," + "author varchar(30)," + "ts integer," + "read BOOLEAN DEFAULT FALSE," + "json text)" ) ); if ( !query.exec() ) { qWarning() << query.lastError(); } - query.prepare( "CREATE INDEX msgRidIndex " - "ON messages (rid)" ); + query.prepare( QStringLiteral( "CREATE INDEX msgRidIndex " + "ON messages (rid)" ) ); if ( !query.exec() ) { qWarning() << query.lastError(); } - query.prepare( "CREATE TABLE IF NOT EXISTS file_cache " - "(url varchar(200) primary key," - "path varchar(200)," - "ts integer)" ); + query.prepare( QStringLiteral( "CREATE TABLE IF NOT EXISTS file_cache " + "(url varchar(200) primary key," + "path varchar(200)," + "ts integer)" ) ); if ( !query.exec() ) { qWarning() << query.lastError(); } - query.prepare( "CREATE TABLE IF NOT EXISTS current_room" - "(id integer primary key," - "rid varchar(12)," - "name varchar(30))" ); + query.prepare( QStringLiteral( "CREATE TABLE IF NOT EXISTS current_room" + "(id integer primary key," + "rid varchar(12)," + "name varchar(30))" ) ); if ( !query.exec() ) { qWarning() << query.lastError(); } - query.prepare( "CREATE TABLE IF NOT EXISTS custom_emojis" - "(id varchar(30) primary key," - "file varchar(200)," - "html varchar(200)," - "unicode varchar(20)," - "category varchar(100)," - "sort_order integer DEFAULT 1)" ); + query.prepare( QStringLiteral( "CREATE TABLE IF NOT EXISTS custom_emojis" + "(id varchar(30) primary key," + "file varchar(200)," + "html varchar(200)," + "unicode varchar(20)," + "category varchar(100)," + "sort_order integer DEFAULT 1)" ) ); if ( !query.exec() ) { qWarning() << query.lastError(); @@ -154,7 +154,7 @@ void PersistanceLayer::initShema() commit(); - query.prepare( "SELECT db_ver FROM app_info WHERE id=0" ); + query.prepare( QStringLiteral( "SELECT db_ver FROM app_info WHERE id=0" ) ); int dbVer = -1; if ( !query.exec() ) { @@ -162,7 +162,7 @@ void PersistanceLayer::initShema() } else { dbVer = 0; QSqlRecord rec = query.record(); - int dbVerIndex = rec.indexOf( "db_ver" ); + int dbVerIndex = rec.indexOf( QStringLiteral( "db_ver" ) ); while ( query.next() ) { dbVer = query.value( dbVerIndex ).toInt(); @@ -173,10 +173,10 @@ void PersistanceLayer::initShema() upgradeSchema(); } else if ( dbVer == -1 ) { transaction(); - query.prepare( "CREATE TABLE IF NOT EXISTS app_info" - "(id varchar(30) primary key," - "db_ver integer," - "app_ver integer)" ); + query.prepare( QStringLiteral( "CREATE TABLE IF NOT EXISTS app_info" + "(id varchar(30) primary key," + "db_ver integer," + "app_ver integer)" ) ); if ( !query.exec() ) { qWarning() << query.lastError(); @@ -184,18 +184,18 @@ void PersistanceLayer::initShema() commit(); QString dbVersion = QString::number( DBVERSION ); - query.prepare( "INSERT INTO app_info (db_ver) VALUES(" + dbVersion + ")" ); + query.prepare( QStringLiteral( "INSERT INTO app_info (db_ver) VALUES(" ) + dbVersion + ")" ); if ( !query.exec() ) { qWarning() << query.lastError(); } } - query.prepare( "CREATE TABLE IF NOT EXISTS app_settings" - "(id integer primary key," - "serverid integer," - "property varchar(100) UNIQUE," - "value varchar(100))" ); + query.prepare( QStringLiteral( "CREATE TABLE IF NOT EXISTS app_settings" + "(id integer primary key," + "serverid integer," + "property varchar(100) UNIQUE," + "value varchar(100))" ) ); if ( !query.exec() ) { qWarning() << query.lastError(); @@ -203,7 +203,7 @@ void PersistanceLayer::initShema() - query.prepare( "SELECT id FROM custom_emojis" ); + query.prepare( QStringLiteral( "SELECT id FROM custom_emojis" ) ); if ( !query.exec() ) { qWarning() << "failed SELECT custom_emojis"; @@ -217,7 +217,7 @@ void PersistanceLayer::initShema() } if ( size <= 0 ) { - QFile dump( ":/sql/emojis.sql" ); + QFile dump( QStringLiteral( ":/sql/emojis.sql" ) ); if ( !dump.open( QIODevice::ReadOnly | QIODevice::Text ) ) { qWarning() << "error loading dump"; @@ -250,7 +250,7 @@ void PersistanceLayer::initShema() void PersistanceLayer::upgradeSchema() { QSqlQuery query; - query.prepare( "SELECT db_ver FROM app_info" ); + query.prepare( QStringLiteral( "SELECT db_ver FROM app_info" ) ); int dbVersion = 0; if ( !query.exec() ) { @@ -269,8 +269,8 @@ void PersistanceLayer::upgradeSchema() if ( dbVersion < 1 ) { currentTarget = 1; - sqlFile.setFileName( ":/sql/migrations/1.sql" ); - query.prepare( "DELETE FROM custom_emojis" ); + sqlFile.setFileName( QStringLiteral( ":/sql/migrations/1.sql" ) ); + query.prepare( QStringLiteral( "DELETE FROM custom_emojis" ) ); if ( query.exec() ) { qWarning() << "truncation of, custom_emojis failed"; @@ -278,7 +278,7 @@ void PersistanceLayer::upgradeSchema() } } else if ( dbVersion < 2 ) { currentTarget = 2; - sqlFile.setFileName( ":/sql/migrations/2.sql" ); + sqlFile.setFileName( QStringLiteral( ":/sql/migrations/2.sql" ) ); } if ( !sqlFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) { @@ -314,7 +314,7 @@ void PersistanceLayer::wipeDb() { mDb.close(); QString directory = QStandardPaths::writableLocation( QStandardPaths::AppLocalDataLocation ); - QString filePath = directory + "/data.sqlite"; + QString filePath = directory + QStringLiteral( "/data.sqlite" ); QFile file( filePath ); if ( !file.remove() ) { @@ -367,10 +367,10 @@ void PersistanceLayer::setUserName( QString pUsername ) { transaction(); QSqlQuery setName; - setName.prepare( "UPDATE user_data " - "SET username=:username WHERE id=:id" ); - setName.bindValue( ":id", 0 ); - setName.bindValue( ":username", pUsername ); + setName.prepare( QStringLiteral( "UPDATE user_data " + "SET username=:username WHERE id=:id" ) ); + setName.bindValue( QStringLiteral( ":id" ), 0 ); + setName.bindValue( QStringLiteral( ":username" ), pUsername ); if ( !setName.exec() ) { qWarning() << setName.lastError(); @@ -383,10 +383,10 @@ void PersistanceLayer::setPassword( QString pPassword ) { transaction(); QSqlQuery setPass; - setPass.prepare( "UPDATE user_data " - "SET password=:password WHERE id=:id" ); - setPass.bindValue( ":password", pPassword ); - setPass.bindValue( ":id", 0 ); + setPass.prepare( QStringLiteral( "UPDATE user_data " + "SET password=:password WHERE id=:id" ) ); + setPass.bindValue( QStringLiteral( ":password" ), pPassword ); + setPass.bindValue( QStringLiteral( ":id" ), 0 ); if ( !setPass.exec() ) { qWarning() << setPass.lastError(); @@ -400,11 +400,11 @@ void PersistanceLayer::setToken( QString pToken, uint pExpire ) transaction(); QSqlQuery setToken; - setToken.prepare( "UPDATE user_data " - "SET token=:token, token_expire=:token_expire WHERE id=:id" ); - setToken.bindValue( ":token", pToken ); - setToken.bindValue( ":id", 0 ); - setToken.bindValue( ":token_expire", pExpire ); + setToken.prepare( QStringLiteral( "UPDATE user_data " + "SET token=:token, token_expire=:token_expire WHERE id=:id" ) ); + setToken.bindValue( QStringLiteral( ":token" ), pToken ); + setToken.bindValue( QStringLiteral( ":id" ), 0 ); + setToken.bindValue( QStringLiteral( ":token_expire" ), pExpire ); if ( !setToken.exec() ) { qWarning() << setToken.lastError(); @@ -418,8 +418,8 @@ void PersistanceLayer::setUserData( QString pUser, QString pPass ) transaction(); QSqlQuery setUser; - setUser.prepare( "REPLACE INTO user_data " - "(id,password,username) VALUES(:id,:password,:username)" ); + setUser.prepare( QStringLiteral( "REPLACE INTO user_data " + "(id,password,username) VALUES(:id,:password,:username)" ) ); setUser.bindValue( ":password", pPass ); setUser.bindValue( ":id", 0 ); setUser.bindValue( ":username", pUser ); @@ -435,7 +435,7 @@ QString PersistanceLayer::addFileToTemp( QString pUrl, QString pPath ) { QFile file( pPath ); QString urlPrefix = ""; - QStringList urlSegments = pUrl.split( "/" ); + QStringList urlSegments = pUrl.split( '/' ); QString folder; if ( urlSegments.length() ) { @@ -446,7 +446,7 @@ QString PersistanceLayer::addFileToTemp( QString pUrl, QString pPath ) QString newFilePath = QStandardPaths::writableLocation( QStandardPaths::TempLocation ); - newFilePath += "/" + folder; + newFilePath += '/' + folder; createFolder( newFilePath ); if ( !newFilePath.length() ) { @@ -460,7 +460,7 @@ QString PersistanceLayer::addFileToTemp( QString pUrl, QString pPath ) } } - newFilePath += "/" + pPath.split( "/" ).last(); + newFilePath += '/' + pPath.split( '/' ).last(); qDebug() << "old path: " << pPath; qDebug() << "new path: " << newFilePath; @@ -558,7 +558,7 @@ QString PersistanceLayer::addFileToMusics( QString pUrl, QString pPath ) } } - newFilePath += +"/" + realname; + newFilePath += +'/' + realname; QFile destFile( newFilePath ); if ( destFile.exists() ) { @@ -595,7 +595,7 @@ QString PersistanceLayer::addFileToVideos( QString pUrl, QString pPath ) if ( !newFilePath.length() ) { newFilePath = pPath; } else { - QString realname = file.fileName().split( "/" ).last(); + QString realname = file.fileName().split( '/' ).last(); QDir dbPath( newFilePath ); if ( !dbPath.exists() ) { @@ -604,7 +604,7 @@ QString PersistanceLayer::addFileToVideos( QString pUrl, QString pPath ) } } - newFilePath += +"/" + realname; + newFilePath += +'/' + realname; QFile destFile( newFilePath ); @@ -651,7 +651,7 @@ QString PersistanceLayer::addFileToImages( QString pUrl, QString pPath ) } } - newFilePath += +"/" + realname; + newFilePath += +'/' + realname; QFile destFile( newFilePath ); if ( destFile.exists() ) { @@ -693,9 +693,9 @@ void PersistanceLayer::setUserId( QString pUserId ) { transaction(); QSqlQuery setUserId; - setUserId.prepare( "UPDATE user_data SET user_id=:userId WHERE id=:id" ); - setUserId.bindValue( ":id", 0 ); - setUserId.bindValue( ":userId", pUserId ); + setUserId.prepare( QStringLiteral( "UPDATE user_data SET user_id=:userId WHERE id=:id" ) ); + setUserId.bindValue( QStringLiteral( ":id" ), 0 ); + setUserId.bindValue( QStringLiteral( ":userId" ), pUserId ); if ( !setUserId.exec() ) { qWarning() << setUserId.lastError(); @@ -708,11 +708,11 @@ void PersistanceLayer::setCurrentChannel( QString pChannelId, QString pChannelNa { transaction(); QSqlQuery setChannel; - setChannel.prepare( "REPLACE INTO current_room" - "(id,rid,name) VALUES(:id,:rid,:name)" ); - setChannel.bindValue( ":id", 0 ); - setChannel.bindValue( ":rid", pChannelId ); - setChannel.bindValue( ":name", pChannelName ); + setChannel.prepare( QStringLiteral( "REPLACE INTO current_room" + "(id,rid,name) VALUES(:id,:rid,:name)" ) ); + setChannel.bindValue( QStringLiteral( ":id" ), 0 ); + setChannel.bindValue( QStringLiteral( ":rid" ), pChannelId ); + setChannel.bindValue( QStringLiteral( ":name" ), pChannelName ); if ( !setChannel.exec() ) { qWarning() << setChannel.lastError(); @@ -725,10 +725,10 @@ void PersistanceLayer::setSetting( QString pProperty, QString pValue ) { transaction(); QSqlQuery setChannel; - setChannel.prepare( "REPLACE INTO app_settings" - "(property,value) VALUES(:property,:value)" ); - setChannel.bindValue( ":property", pProperty ); - setChannel.bindValue( ":value", pValue ); + setChannel.prepare( QStringLiteral( "REPLACE INTO app_settings" + "(property,value) VALUES(:property,:value)" ) ); + setChannel.bindValue( QStringLiteral( ":property" ), pProperty ); + setChannel.bindValue( QStringLiteral( ":value" ), pValue ); if ( !setChannel.exec() ) { qWarning() << setChannel.lastError(); @@ -742,16 +742,16 @@ void PersistanceLayer::addChannel( QString pId, QString pName, QString pType, bo { transaction(); QSqlQuery setChannel; - setChannel.prepare( "REPLACE INTO rooms " - "(id,name,type,joined,read_only,muted,archived,blocked) VALUES(:id,:name,:type,:joined,:read_only,:muted,:archived,:blocked)" ); - setChannel.bindValue( ":id", pId ); - setChannel.bindValue( ":name", pName ); - setChannel.bindValue( ":joined", pJoined ); - setChannel.bindValue( ":type", pType ); - setChannel.bindValue( ":read_only", pReadOnly ); - setChannel.bindValue( ":muted", pMuted ); - setChannel.bindValue( ":archived", pArchived ); - setChannel.bindValue( ":blocked", pBlocked ); + setChannel.prepare( QStringLiteral( "REPLACE INTO rooms " + "(id,name,type,joined,read_only,muted,archived,blocked) VALUES(:id,:name,:type,:joined,:read_only,:muted,:archived,:blocked)" ) ); + setChannel.bindValue( QStringLiteral( ":id" ), pId ); + setChannel.bindValue( QStringLiteral( ":name" ), pName ); + setChannel.bindValue( QStringLiteral( ":joined" ), pJoined ); + setChannel.bindValue( QStringLiteral( ":type" ), pType ); + setChannel.bindValue( QStringLiteral( ":read_only" ), pReadOnly ); + setChannel.bindValue( QStringLiteral( ":muted" ), pMuted ); + setChannel.bindValue( QStringLiteral( ":archived" ), pArchived ); + setChannel.bindValue( QStringLiteral( ":blocked" ), pBlocked ); if ( !setChannel.exec() ) { qWarning() << setChannel.lastError(); @@ -769,17 +769,35 @@ void PersistanceLayer::addChannel( QString pId, QString pName, QString pType, bo addChannel( pId, pName, pType, pJoined, readOnly, muted, archived, blocked ); } +void PersistanceLayer::deleteChannel( QString pId ) +{ + QSqlQuery deleteQuery; + deleteQuery.prepare( QStringLiteral( "DELETE FROM rooms WHERE id=:id" ) ); + deleteQuery.bindValue( QStringLiteral( ":id" ), pId ); + + if ( !deleteQuery.exec() ) { + qWarning() << deleteQuery.lastError(); + } else { + deleteQuery.prepare( QStringLiteral( "DELETE FROM messages WHERE rid=:id" ) ); + deleteQuery.bindValue( QStringLiteral( ":id" ), pId ); + + if ( !deleteQuery.exec() ) { + qWarning() << deleteQuery.lastError(); + } + } +} + void PersistanceLayer::addMessage( QString pId, QString pRid, QString pAuthor, qint64 pTs, QString pJson ) { transaction(); QSqlQuery addMessage( mDb ); - addMessage.prepare( "REPLACE INTO messages " - "(id,rid,author,ts,json,read) VALUES (:id,:rid,:author,:ts,:json,0)" ); - addMessage.bindValue( ":id", pId ); - addMessage.bindValue( ":rid", pRid ); - addMessage.bindValue( ":author", pAuthor ); - addMessage.bindValue( ":ts", pTs ); - addMessage.bindValue( ":json", pJson ); + addMessage.prepare( QStringLiteral( "REPLACE INTO messages " + "(id,rid,author,ts,json,read) VALUES (:id,:rid,:author,:ts,:json,0)" ) ); + addMessage.bindValue( QStringLiteral( ":id" ), pId ); + addMessage.bindValue( QStringLiteral( ":rid" ), pRid ); + addMessage.bindValue( QStringLiteral( ":author" ), pAuthor ); + addMessage.bindValue( QStringLiteral( ":ts" ), pTs ); + addMessage.bindValue( QStringLiteral( ":json" ), pJson ); if ( !addMessage.exec() ) { qWarning() << "id: " << pId << " rid: " << pRid << " author: " << pAuthor << " ts: " << pTs << " json: " << pJson; @@ -799,11 +817,11 @@ void PersistanceLayer::addFileCacheEntry( QString pUrl, QString pPath ) QDateTime dateTime = QDateTime::currentDateTime(); QSqlQuery addCacheEntry; - addCacheEntry.prepare( "REPLACE INTO file_cache (url,path,ts)" - " VALUES (:url,:path,:ts)" ); - addCacheEntry.bindValue( ":url", pUrl ); - addCacheEntry.bindValue( ":path", pPath ); - addCacheEntry.bindValue( ":ts", dateTime.toTime_t() ); + addCacheEntry.prepare( QStringLiteral( "REPLACE INTO file_cache (url,path,ts)" + " VALUES (:url,:path,:ts)" ) ); + addCacheEntry.bindValue( QStringLiteral( ":url" ), pUrl ); + addCacheEntry.bindValue( QStringLiteral( ":path" ), pPath ); + addCacheEntry.bindValue( QStringLiteral( ":ts" ), dateTime.toTime_t() ); if ( !addCacheEntry.exec() ) { qWarning() << addCacheEntry.lastError(); @@ -825,14 +843,14 @@ void PersistanceLayer::addCustomEmoji( QString pTag, QString pPath, QString pHtm { transaction(); QSqlQuery addCustomEmojiQuery; - addCustomEmojiQuery.prepare( "REPLACE INTO custom_emojis (id,file,html,unicode,category,sort_order)" - " VALUES (:id,:file,:html,:unicode,:category,:sort_order)" ); - addCustomEmojiQuery.bindValue( ":id", pTag ); - addCustomEmojiQuery.bindValue( ":file", pPath ); - addCustomEmojiQuery.bindValue( ":html", pHtml ); - addCustomEmojiQuery.bindValue( ":unicode", pUnicode ); - addCustomEmojiQuery.bindValue( ":category", pCategory ); - addCustomEmojiQuery.bindValue( ":sort_order", pOrder ); + addCustomEmojiQuery.prepare( QStringLiteral( "REPLACE INTO custom_emojis (id,file,html,unicode,category,sort_order)" + " VALUES (:id,:file,:html,:unicode,:category,:sort_order)" ) ); + addCustomEmojiQuery.bindValue( QStringLiteral( ":id" ), pTag ); + addCustomEmojiQuery.bindValue( QStringLiteral( ":file" ), pPath ); + addCustomEmojiQuery.bindValue( QStringLiteral( ":html" ), pHtml ); + addCustomEmojiQuery.bindValue( QStringLiteral( ":unicode" ), pUnicode ); + addCustomEmojiQuery.bindValue( QStringLiteral( ":category" ), pCategory ); + addCustomEmojiQuery.bindValue( QStringLiteral( ":sort_order" ), pOrder ); if ( !addCustomEmojiQuery.exec() ) { qWarning() << addCustomEmojiQuery.lastError(); @@ -845,8 +863,8 @@ void PersistanceLayer::addCustomEmoji( QString pTag, QString pPath, QString pHtm QHash<QString, QString> PersistanceLayer::getMessageByid( QString pId ) { QSqlQuery message; - message.prepare( "SELECT * FROM messages WHERE id=:id" ); - message.bindValue( ":id", pId ); + message.prepare( QStringLiteral( "SELECT * FROM messages WHERE id=:id" ) ); + message.bindValue( QStringLiteral( ":id" ), pId ); QHash<QString, QString> row; if ( !message.exec() ) { @@ -854,20 +872,20 @@ QHash<QString, QString> PersistanceLayer::getMessageByid( QString pId ) } else { QSqlRecord rec = message.record(); - int idCol = rec.indexOf( "id" ); - int ridCol = rec.indexOf( "rid" ); - int authorCol = rec.indexOf( "author" ); - int tsCol = rec.indexOf( "ts" ); - int messageCol = rec.indexOf( "message" ); - int typeCol = rec.indexOf( "type" ); + int idCol = rec.indexOf( QStringLiteral( "id" ) ); + int ridCol = rec.indexOf( QStringLiteral( "rid" ) ); + int authorCol = rec.indexOf( QStringLiteral( "author" ) ); + int tsCol = rec.indexOf( QStringLiteral( "ts" ) ); + int messageCol = rec.indexOf( QStringLiteral( "message" ) ); + int typeCol = rec.indexOf( QStringLiteral( "type" ) ); while ( message.next() ) { - row["id"] = message.value( idCol ).toString(); - row["rid"] = message.value( ridCol ).toString(); - row["author"] = message.value( authorCol ).toString(); - row["message"] = message.value( messageCol ).toString(); - row["ts"] = message.value( tsCol ).toString(); - row["type"] = message.value( typeCol ).toString(); + row[QStringLiteral( "id" )] = message.value( idCol ).toString(); + row[QStringLiteral( "rid" )] = message.value( ridCol ).toString(); + row[QStringLiteral( "author" )] = message.value( authorCol ).toString(); + row[QStringLiteral( "message" )] = message.value( messageCol ).toString(); + row[QStringLiteral( "ts" )] = message.value( tsCol ).toString(); + row[QStringLiteral( "type" )] = message.value( typeCol ).toString(); } } @@ -878,7 +896,7 @@ QHash<QString, QString> PersistanceLayer::getMessageByid( QString pId ) QString PersistanceLayer::getUserName() { QSqlQuery getName; - getName.prepare( "SELECT username FROM user_data WHERE id=0" ); + getName.prepare( QStringLiteral( "SELECT username FROM user_data WHERE id=0" ) ); QString name = ""; @@ -887,7 +905,7 @@ QString PersistanceLayer::getUserName() } else { QSqlRecord rec = getName.record(); - int nameCol = rec.indexOf( "username" ); + int nameCol = rec.indexOf( QStringLiteral( "username" ) ); while ( getName.next() ) { name = getName.value( nameCol ).toString(); @@ -900,7 +918,7 @@ QString PersistanceLayer::getUserName() std::tuple<QString, QString> PersistanceLayer::getCurrentChannel() { QSqlQuery getChannel; - getChannel.prepare( "SELECT * FROM current_room WHERE id=0" ); + getChannel.prepare( QStringLiteral( "SELECT * FROM current_room WHERE id=0" ) ); QString id; QString name; @@ -908,8 +926,8 @@ std::tuple<QString, QString> PersistanceLayer::getCurrentChannel() qWarning() << getChannel.lastError(); } else { while ( getChannel.next() ) { - id = getChannel.value( "rid" ).toString(); - name = getChannel.value( "name" ).toString(); + id = getChannel.value( QStringLiteral( "rid" ) ).toString(); + name = getChannel.value( QStringLiteral( "name" ) ).toString(); } } @@ -919,7 +937,7 @@ std::tuple<QString, QString> PersistanceLayer::getCurrentChannel() QString PersistanceLayer::getPassword() { QSqlQuery getPass; - getPass.prepare( "SELECT password FROM user_data WHERE id=0" ); + getPass.prepare( QStringLiteral( "SELECT password FROM user_data WHERE id=0" ) ); QString pass = ""; if ( !getPass.exec() ) { @@ -927,7 +945,7 @@ QString PersistanceLayer::getPassword() } else { QSqlRecord rec = getPass.record(); - int nameCol = rec.indexOf( "password" ); + int nameCol = rec.indexOf( QStringLiteral( "password" ) ); while ( getPass.next() ) { pass = getPass.value( nameCol ).toString(); @@ -940,7 +958,7 @@ QString PersistanceLayer::getPassword() QPair<QString, uint> PersistanceLayer::getToken() { QSqlQuery getToken; - getToken.prepare( "SELECT token, token_expire FROM user_data WHERE id=0" ); + getToken.prepare( QStringLiteral( "SELECT token, token_expire FROM user_data WHERE id=0" ) ); // getToken.bindValue( ":id", 0 ); QPair<QString, uint> token; @@ -948,8 +966,8 @@ QPair<QString, uint> PersistanceLayer::getToken() qWarning() << getToken.lastError(); } else { QSqlRecord rec = getToken.record(); - int tokenCol = rec.indexOf( "token" ); - int expireCol = rec.indexOf( "token_expire" ); + int tokenCol = rec.indexOf( QStringLiteral( "token" ) ); + int expireCol = rec.indexOf( QStringLiteral( "token_expire" ) ); while ( getToken.next() ) { token.first = getToken.value( tokenCol ).toString(); @@ -971,7 +989,7 @@ QString PersistanceLayer::getUserId() qWarning() << "userid error" << getUserId.lastError(); } else { QSqlRecord rec = getUserId.record(); - int userIdCol = rec.indexOf( "user_id" ); + int userIdCol = rec.indexOf( QStringLiteral( "user_id" ) ); while ( getUserId.next() ) { userId = getUserId.value( userIdCol ).toString(); @@ -984,21 +1002,21 @@ QString PersistanceLayer::getUserId() QList<QJsonObject> PersistanceLayer::getMessagesByRid( QString pRid ) { QSqlQuery messages; - messages.prepare( "SELECT * FROM messages WHERE rid=:rid ORDER BY ts DESC LIMIT 20" ); - messages.bindValue( ":rid", pRid ); + messages.prepare( QStringLiteral( "SELECT * FROM messages WHERE rid=:rid ORDER BY ts DESC LIMIT 20" ) ); + messages.bindValue( QStringLiteral( ":rid" ), pRid ); QList<QJsonObject> rows; rows.reserve( 50 ); if ( !messages.exec() ) { - qWarning() << "request room with rid: " << pRid; + qWarning() << QStringLiteral( "request room with rid: " ) << pRid; qWarning() << messages.lastError(); } else { QSqlRecord rec = messages.record(); - int idCol = rec.indexOf( "id" ); - int jsonCol = rec.indexOf( "json" ); - int readCol = rec.indexOf( "read" ); + int idCol = rec.indexOf( QStringLiteral( "id" ) ); + int jsonCol = rec.indexOf( QStringLiteral( "json" ) ); + int readCol = rec.indexOf( QStringLiteral( "read" ) ); while ( messages.next() ) { @@ -1008,7 +1026,7 @@ QList<QJsonObject> PersistanceLayer::getMessagesByRid( QString pRid ) bool read = messages.value( readCol ).toBool(); QJsonDocument doc = QJsonDocument::fromJson( json.toUtf8() ); QJsonObject object = doc.object(); - object["read"] = read; + object[QStringLiteral( "read" )] = read; //entry[id] = object; // rows[id] = object; rows.append( object ); @@ -1022,10 +1040,10 @@ QList<QJsonObject> PersistanceLayer::getMessagesByRid( QString pRid ) QList<QJsonObject> PersistanceLayer::getMessagesByRid( QString pRid, qint64 pFrom, qint64 pTo ) { QSqlQuery messages; - messages.prepare( "SELECT * FROM messages WHERE rid=:rid AND ts<=:from AND ts>=:to ORDER BY ts DESC LIMIT 50" ); - messages.bindValue( ":rid", pRid ); - messages.bindValue( ":from", ( qint64 )( pFrom / 1000 ) ); - messages.bindValue( ":to", ( qint64 )( pTo / 1000 ) ); + messages.prepare( QStringLiteral( "SELECT * FROM messages WHERE rid=:rid AND ts<=:from AND ts>=:to ORDER BY ts DESC LIMIT 50" ) ); + messages.bindValue( QStringLiteral( ":rid" ), pRid ); + messages.bindValue( QStringLiteral( ":from" ), ( qint64 )( pFrom / 1000 ) ); + messages.bindValue( QStringLiteral( ":to" ), ( qint64 )( pTo / 1000 ) ); QList<QJsonObject> rows; rows.reserve( 50 ); @@ -1036,9 +1054,9 @@ QList<QJsonObject> PersistanceLayer::getMessagesByRid( QString pRid, qint64 pFro } else { QSqlRecord rec = messages.record(); - int idCol = rec.indexOf( "id" ); - int jsonCol = rec.indexOf( "json" ); - int readCol = rec.indexOf( "read" ); + int idCol = rec.indexOf( QStringLiteral( "id" ) ); + int jsonCol = rec.indexOf( QStringLiteral( "json" ) ); + int readCol = rec.indexOf( QStringLiteral( "read" ) ); while ( messages.next() ) { @@ -1048,7 +1066,7 @@ QList<QJsonObject> PersistanceLayer::getMessagesByRid( QString pRid, qint64 pFro bool read = messages.value( readCol ).toBool(); QJsonDocument doc = QJsonDocument::fromJson( json.toUtf8() ); QJsonObject object = doc.object(); - object["read"] = read; + object[QStringLiteral( "read" )] = read; //entry["id"] = id; // entry["json"] = object; // rows.append(entry); @@ -1062,10 +1080,10 @@ QList<QJsonObject> PersistanceLayer::getMessagesByRid( QString pRid, qint64 pFro QList<QJsonObject > PersistanceLayer::getMessagesByRid( QString pRid, qint64 pFrom, int pLimit ) { QSqlQuery messages; - messages.prepare( "SELECT * FROM messages WHERE rid=:rid AND ts<=:from ORDER BY ts DESC LIMIT :limit" ); - messages.bindValue( ":rid", pRid ); - messages.bindValue( ":from", ( qint64 )( pFrom ) ); - messages.bindValue( ":limit", pLimit ); + messages.prepare( QStringLiteral( "SELECT * FROM messages WHERE rid=:rid AND ts<=:from ORDER BY ts DESC LIMIT :limit" ) ); + messages.bindValue( QStringLiteral( ":rid" ), pRid ); + messages.bindValue( QStringLiteral( ":from" ), ( qint64 )( pFrom ) ); + messages.bindValue( QStringLiteral( ":limit" ), pLimit ); QList<QJsonObject > rows; rows.reserve( 50 ); @@ -1076,9 +1094,9 @@ QList<QJsonObject > PersistanceLayer::getMessagesByRid( QString pRid, qint64 pFr } else { QSqlRecord rec = messages.record(); - int idCol = rec.indexOf( "id" ); - int jsonCol = rec.indexOf( "json" ); - int readCol = rec.indexOf( "read" ); + int idCol = rec.indexOf( QStringLiteral( "id" ) ); + int jsonCol = rec.indexOf( QStringLiteral( "json" ) ); + int readCol = rec.indexOf( QStringLiteral( "read" ) ); while ( messages.next() ) { @@ -1092,7 +1110,7 @@ QList<QJsonObject > PersistanceLayer::getMessagesByRid( QString pRid, qint64 pFr if ( !object.size() ) { qWarning() << "invalid message Json: " << json; } else { - object["read"] = read; + object[QStringLiteral( "read" )] = read; // QJsonValue idJson = id; // entry["json"] = object; @@ -1108,7 +1126,7 @@ QList<QJsonObject > PersistanceLayer::getMessagesByRid( QString pRid, qint64 pFr QList<QVariantHash> PersistanceLayer::getChannels( void ) { QSqlQuery rooms; - rooms.prepare( "SELECT * FROM rooms LEFT JOIN (SELECT DISTINCT rid FROM messages ORDER BY ts DESC) AS sub ON rooms.id = sub.rid " ); + rooms.prepare( QStringLiteral( "SELECT * FROM rooms LEFT JOIN (SELECT DISTINCT rid FROM messages ORDER BY ts DESC) AS sub ON rooms.id = sub.rid " ) ); QList<QVariantHash> roomsList; roomsList.reserve( 100 ); @@ -1116,27 +1134,27 @@ QList<QVariantHash> PersistanceLayer::getChannels( void ) qWarning() << rooms.lastError(); } else { QSqlRecord rec = rooms.record(); - int idCol = rec.indexOf( "id" ); - int nameCol = rec.indexOf( "name" ); - int joinedCol = rec.indexOf( "joined" ); - int typeCol = rec.indexOf( "type" ); - int readOnlyCol = rec.indexOf( "read_only" ); - int mutedCol = rec.indexOf( "muted" ); - int archivedCol = rec.indexOf( "archived" ); - int blocked = rec.indexOf( "blocked" ); + int idCol = rec.indexOf( QStringLiteral( "id" ) ); + int nameCol = rec.indexOf( QStringLiteral( "name" ) ); + int joinedCol = rec.indexOf( QStringLiteral( "joined" ) ); + int typeCol = rec.indexOf( QStringLiteral( "type" ) ); + int readOnlyCol = rec.indexOf( QStringLiteral( "read_only" ) ); + int mutedCol = rec.indexOf( QStringLiteral( "muted" ) ); + int archivedCol = rec.indexOf( QStringLiteral( "archived" ) ); + int blocked = rec.indexOf( QStringLiteral( "blocked" ) ); while ( rooms.next() ) { QVariantHash roomsHash; QString muted = rooms.value( mutedCol ).toString(); - roomsHash["id"] = rooms.value( idCol ).toString(); - roomsHash["name"] = rooms.value( nameCol ).toString(); - roomsHash["joined"] = rooms.value( joinedCol ).toBool(); - roomsHash["type"] = rooms.value( typeCol ).toString(); - roomsHash["readOnly"] = rooms.value( readOnlyCol ).toBool(); - roomsHash["muted"] = muted; - roomsHash["list"] = muted.split( "," ); - roomsHash["archived"] = rooms.value( archivedCol ).toBool(); - roomsHash["blocked"] = rooms.value( blocked ).toBool(); + roomsHash[QStringLiteral( "id" )] = rooms.value( idCol ).toString(); + roomsHash[QStringLiteral( "name" )] = rooms.value( nameCol ).toString(); + roomsHash[QStringLiteral( "joined" )] = rooms.value( joinedCol ).toBool(); + roomsHash[QStringLiteral( "type" )] = rooms.value( typeCol ).toString(); + roomsHash[QStringLiteral( "readOnly" )] = rooms.value( readOnlyCol ).toBool(); + roomsHash[QStringLiteral( "muted" )] = muted; + roomsHash[QStringLiteral( "list" )] = muted.split( ',' ); + roomsHash[QStringLiteral( "archived" )] = rooms.value( archivedCol ).toBool(); + roomsHash[QStringLiteral( "blocked" )] = rooms.value( blocked ).toBool(); roomsList.append( roomsHash ); } } @@ -1147,7 +1165,7 @@ QList<QVariantHash> PersistanceLayer::getChannels( void ) QList< QHash<QString, QString > > PersistanceLayer::getCustomEmojis() { QSqlQuery emojiQuery; - emojiQuery.prepare( "SELECT id,file,html,category,unicode,sort_order FROM custom_emojis" ); + emojiQuery.prepare( QStringLiteral( "SELECT id,file,html,category,unicode,sort_order FROM custom_emojis" ) ); QList<QHash<QString, QString> > returnList; returnList.reserve( 3000 ); @@ -1157,21 +1175,21 @@ QList< QHash<QString, QString > > PersistanceLayer::getCustomEmojis() QSqlRecord rec = emojiQuery.record(); - int idCol = rec.indexOf( "id" ); - int fileCol = rec.indexOf( "file" ); - int htmlCol = rec.indexOf( "html" ); - int catCol = rec.indexOf( "category" ); - int unicodeCol = rec.indexOf( "unicode" ); - int orderCol = rec.indexOf( "sort_order" ); + int idCol = rec.indexOf( QStringLiteral( "id" ) ); + int fileCol = rec.indexOf( QStringLiteral( "file" ) ); + int htmlCol = rec.indexOf( QStringLiteral( "html" ) ); + int catCol = rec.indexOf( QStringLiteral( "category" ) ); + int unicodeCol = rec.indexOf( QStringLiteral( "unicode" ) ); + int orderCol = rec.indexOf( QStringLiteral( "sort_order" ) ); while ( emojiQuery.next() ) { QHash<QString, QString> entry; - entry["id"] = emojiQuery.value( idCol ).toString(); - entry["file"] = emojiQuery.value( fileCol ).toString(); - entry["html"] = emojiQuery.value( htmlCol ).toString(); - entry["category"] = emojiQuery.value( catCol ).toString(); - entry["unicode"] = emojiQuery.value( unicodeCol ).toString(); - entry["sort_order"] = emojiQuery.value( orderCol ).toString(); + entry[QStringLiteral( "id" )] = emojiQuery.value( idCol ).toString(); + entry[QStringLiteral( "file" )] = emojiQuery.value( fileCol ).toString(); + entry[QStringLiteral( "html" )] = emojiQuery.value( htmlCol ).toString(); + entry[QStringLiteral( "category" )] = emojiQuery.value( catCol ).toString(); + entry[QStringLiteral( "unicode" )] = emojiQuery.value( unicodeCol ).toString(); + entry[QStringLiteral( "sort_order" )] = emojiQuery.value( orderCol ).toString(); returnList.append( entry ); } @@ -1183,8 +1201,8 @@ QList< QHash<QString, QString > > PersistanceLayer::getCustomEmojis() QString PersistanceLayer::getFileCacheEntry( QString pUrl ) { QSqlQuery cacheEntry; - cacheEntry.prepare( "SELECT path FROM file_cache WHERE url=:url" ); - cacheEntry.bindValue( ":url", pUrl ); + cacheEntry.prepare( QStringLiteral( "SELECT path FROM file_cache WHERE url=:url" ) ); + cacheEntry.bindValue( QStringLiteral( ":url" ), pUrl ); QString returnString = ""; if ( !cacheEntry.exec() ) { @@ -1192,7 +1210,7 @@ QString PersistanceLayer::getFileCacheEntry( QString pUrl ) } else { QSqlRecord rec = cacheEntry.record(); - int pathCol = rec.indexOf( "path" ); + int pathCol = rec.indexOf( QStringLiteral( "path" ) ); while ( cacheEntry.next() ) { returnString = cacheEntry.value( pathCol ).toString(); @@ -1214,8 +1232,8 @@ QString PersistanceLayer::getFileCacheEntry( QString pUrl ) QString PersistanceLayer::getSetting( QString pProperty ) { QSqlQuery settingsEntry; - settingsEntry.prepare( "SELECT property,value FROM app_settings WHERE property=:property" ); - settingsEntry.bindValue( ":property", pProperty ); + settingsEntry.prepare( QStringLiteral( "SELECT property,value FROM app_settings WHERE property=:property" ) ); + settingsEntry.bindValue( QStringLiteral( ":property" ), pProperty ); QString returnString = ""; if ( !settingsEntry.exec() ) { @@ -1223,7 +1241,7 @@ QString PersistanceLayer::getSetting( QString pProperty ) } else { QSqlRecord rec = settingsEntry.record(); - int valueClol = rec.indexOf( "value" ); + int valueClol = rec.indexOf( QStringLiteral( "value" ) ); while ( settingsEntry.next() ) { returnString = settingsEntry.value( valueClol ).toString(); @@ -1255,8 +1273,8 @@ void PersistanceLayer::removeFileCacheEntry( QString pUrl, QString pPath ) } QSqlQuery cacheEntry; - cacheEntry.prepare( "DELETE FROM file_cache WHERE url=:url" ); - cacheEntry.bindValue( ":url", pUrl ); + cacheEntry.prepare( QStringLiteral( "DELETE FROM file_cache WHERE url=:url" ) ); + cacheEntry.bindValue( QStringLiteral( ":url" ), pUrl ); if ( !cacheEntry.exec() ) { qWarning() << cacheEntry.lastError(); @@ -1269,7 +1287,7 @@ void PersistanceLayer::removeFileCacheEntry( QString pUrl, QString pPath ) QString PersistanceLayer::getNewVideoPath( void ) { QString path; - path = QStandardPaths::writableLocation( QStandardPaths::MoviesLocation ) + "/recordings"; + path = QStandardPaths::writableLocation( QStandardPaths::MoviesLocation ) + QStringLiteral( "/recordings" ); if ( path != "" ) { QDir dir( path ); @@ -1282,15 +1300,15 @@ QString PersistanceLayer::getNewVideoPath( void ) QDateTime dateTime = QDateTime::currentDateTime(); uint timeStamp = dateTime.toTime_t(); - QFile file( path + "/" + timeStamp + ".mp4" ); + QFile file( path + '/' + timeStamp + QStringLiteral( ".mp4" ) ); if ( !file.exists() ) { //file.open( QIODevice::ReadWrite ); //file.close(); } - qDebug() << path + "/" + QString::number( timeStamp ) + ".mp4"; - return path + "/" + QString::number( timeStamp ) + ".mp4"; + qDebug() << path + '/' + QString::number( timeStamp ) + ".mp4"; + return path + '/' + QString::number( timeStamp ) + QStringLiteral( ".mp4" ); } else { return ""; } @@ -1299,7 +1317,7 @@ QString PersistanceLayer::getNewVideoPath( void ) QString PersistanceLayer::getNewImagePath( void ) { QString path; - path = QStandardPaths::writableLocation( QStandardPaths::PicturesLocation ) + "/recordings"; + path = QStandardPaths::writableLocation( QStandardPaths::PicturesLocation ) + QStringLiteral( "/recordings" ); if ( path != "" ) { QDir dir( path ); @@ -1312,15 +1330,15 @@ QString PersistanceLayer::getNewImagePath( void ) QDateTime dateTime = QDateTime::currentDateTime(); uint timeStamp = dateTime.toTime_t(); - QFile file( path + "/" + timeStamp + ".jpg" ); + QFile file( path + '/' + timeStamp + QStringLiteral( ".jpg" ) ); if ( !file.exists() ) { //file.open( QIODevice::ReadWrite ); //file.close(); } - qDebug() << path + "/" + QString::number( timeStamp ) + ".jpg"; - return path + "/" + QString::number( timeStamp ) + ".jpg"; + qDebug() << path + '/' + QString::number( timeStamp ) + QStringLiteral( ".jpg" ); + return path + '/' + QString::number( timeStamp ) + QStringLiteral( ".jpg" ); } else { return ""; } @@ -1336,7 +1354,7 @@ PersistanceLayer::~PersistanceLayer() void PersistanceLayer::init() { QString directory = QStandardPaths::writableLocation( QStandardPaths::AppLocalDataLocation ); - QString filePath = directory + "/data.sqlite"; + QString filePath = directory + QStringLiteral( "/data.sqlite" ); qDebug() << "SQLITE: " << filePath; mDb.setDatabaseName( filePath ); diff --git a/persistancelayer.h b/persistancelayer.h index 2d9cca8f757fcc7ec7372ad637110a2af09dff4e..ef7dfc6ae1ffe55f307427e00260114ffaec8825 100755 --- a/persistancelayer.h +++ b/persistancelayer.h @@ -41,6 +41,7 @@ class PersistanceLayer : public QObject void setToken( QString, uint ); void addChannel( QString pId, QString pName, QString pType, bool pJoined, bool pReadOnly, QString pMuted, bool pArchived, bool pBlocked ); void addChannel( QString pId, QString pName, QString pType, bool pJoined ); + void deleteChannel( QString pId ); void addMessage( QString pId, QString pRid, QString pAuthor, qint64 pTs, QString pJson ); void addFileCacheEntry( QString pUrl, QString pPath ); void addCustomEmoji( QString pTag, QString pPath, QString pHtml, QString pCategory ); diff --git a/repos/channelrepository.cpp b/repos/channelrepository.cpp index 8dbc2aeff4a57a35e014cffada33cdebe4863eaa..87ff5df7159783ac15be143088c3b42b65cd7638 100755 --- a/repos/channelrepository.cpp +++ b/repos/channelrepository.cpp @@ -34,11 +34,11 @@ bool ChannelRepository::add( QString id, QSharedPointer<RocketChatChannel> msg ) QString type = msg->getType(); if ( type == "c" ) { - QMetaObject::invokeMethod( &mChannelsModel, "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) ); + QMetaObject::invokeMethod( &mChannelsModel, "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) ); } else if ( type == "d" ) { QMetaObject::invokeMethod( &mDirectModel, "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) ); } else if ( type == "p" ) { - QMetaObject::invokeMethod( &mGroupsModel, "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) ); + QMetaObject::invokeMethod( &mGroupsModel, "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) ); } mNameIndex[msg->getName()] = msg; diff --git a/repos/entities/emoji.cpp b/repos/entities/emoji.cpp index 92498daf91c895d63775e6da8ce1ff6ec0e89b49..5fd1be479e7bda5fafd380c075f59706922a4f42 100644 --- a/repos/entities/emoji.cpp +++ b/repos/entities/emoji.cpp @@ -24,10 +24,10 @@ Emoji::Emoji( QString name, QString extension, QString category ): mCategory( category ) { - this->mIdentifier = ":" + name + ":"; + this->mIdentifier = ':' + name + ':'; mName = name; mExtension = extension; - this->mType = "emoji"; + this->mType = QStringLiteral( "emoji" ); } Emoji::Emoji( QString name, QString category, QString filePath, QString html ): mCategory( category ) @@ -65,10 +65,10 @@ QString Emoji::getIdentifier() const QVariantMap Emoji::toQVariantMap() { QVariantMap entry; - entry["category"] = mCategory; - entry["text"] = mIdentifier; - entry["file"] = mFilePath; - entry["order"] = mOrder; + entry[QStringLiteral( "category" )] = mCategory; + entry[QStringLiteral( "text" )] = mIdentifier; + entry[QStringLiteral( "file" )] = mFilePath; + entry[QStringLiteral( "order" )] = mOrder; return entry; } diff --git a/repos/entities/loginmethod.cpp b/repos/entities/loginmethod.cpp index c66ada999d1b041e805b3a5819a15d52454a83d2..8b603dca9fcd63ec2a6112e63fa113deafe4b4d0 100644 --- a/repos/entities/loginmethod.cpp +++ b/repos/entities/loginmethod.cpp @@ -120,10 +120,10 @@ void LoginMethod::setCredentialToken( const QString &pCredentialToken ) QString LoginMethod::getState() const { QJsonObject stateObj; - stateObj["loginStyle"] = "popup"; - stateObj["credentialToken"] = mCredentialToken; - stateObj["isCordova"] = false; - stateObj["redirectUrl"] = getRedirectUrl(); + stateObj[QStringLiteral( "loginStyle" )] = QStringLiteral( "popup" ); + stateObj[QStringLiteral( "credentialToken" )] = mCredentialToken; + stateObj[QStringLiteral( "isCordova" )] = false; + stateObj[QStringLiteral( "redirectUrl" )] = getRedirectUrl(); QJsonDocument doc( stateObj ); QByteArray json = doc.toJson(); return json.toBase64(); @@ -143,13 +143,13 @@ QString LoginMethod::getIdpUrl() const { QString redirectUrl; redirectUrl += getAuthorizeUrl(); - redirectUrl += "?client_id="; + redirectUrl += QStringLiteral( "?client_id=" ); redirectUrl += mClientId; - redirectUrl += "&redirect_uri="; + redirectUrl += QStringLiteral( "&redirect_uri=" ); redirectUrl += getRedirectUrl(); - redirectUrl += "&response_type=code&state="; + redirectUrl += QStringLiteral( "&response_type=code&state=" ); redirectUrl += getState(); - redirectUrl += "&scope=openid"; + redirectUrl += QStringLiteral( "&scope=openid" ); qDebug() << redirectUrl; return redirectUrl; } @@ -157,11 +157,11 @@ QString LoginMethod::getIdpUrl() const QMap<QString, QVariant> LoginMethod::toMap() const { QMap<QString, QVariant> map; - map.insert( "idpUrl", getIdpUrl() ); - map.insert( "redirectUrl", getRedirectUrl() ); - map.insert( "service", getService() ); - map.insert( "buttonText", getButtonLabelText() ); - qDebug() << map["idpUrl"]; + map.insert( QStringLiteral( "idpUrl" ), getIdpUrl() ); + map.insert( QStringLiteral( "redirectUrl" ), getRedirectUrl() ); + map.insert( QStringLiteral( "service" ), getService() ); + map.insert( QStringLiteral( "buttonText" ), getButtonLabelText() ); + qDebug() << map[QStringLiteral( "idpUrl" )]; return map; } diff --git a/repos/entities/rocketchatchannel.cpp b/repos/entities/rocketchatchannel.cpp index 780912fed1eab89a0cac78023b9bf86f3748cf78..289310fb1f0ff61be5e4bdce07dfef498df4dbdc 100755 --- a/repos/entities/rocketchatchannel.cpp +++ b/repos/entities/rocketchatchannel.cpp @@ -216,13 +216,13 @@ void RocketChatChannel::setArchived( bool value ) QJsonObject RocketChatChannel::toJsonObject() { QJsonObject currentChannelObject; - currentChannelObject["name"] = getName(); - currentChannelObject["joined"] = getJoined(); - currentChannelObject["ro"] = getReadOnly(); - currentChannelObject["muted"] = QJsonArray::fromStringList( getMuted() ); - currentChannelObject["archived"] = getArchived(); - currentChannelObject["type"] = getType(); - currentChannelObject["roomId"] = getRoomId(); + currentChannelObject[QStringLiteral( "name" )] = getName(); + currentChannelObject[QStringLiteral( "joined" )] = getJoined(); + currentChannelObject[QStringLiteral( "ro" )] = getReadOnly(); + currentChannelObject[QStringLiteral( "muted" )] = QJsonArray::fromStringList( getMuted() ); + currentChannelObject[QStringLiteral( "archived" )] = getArchived(); + currentChannelObject[QStringLiteral( "type" )] = getType(); + currentChannelObject[QStringLiteral( "roomId" )] = getRoomId(); return currentChannelObject; } @@ -245,6 +245,16 @@ int RocketChatChannel::operator >( RocketChatChannel &channel ) return timestamp1 > timestamp2; } +bool RocketChatChannel::getDeleted() const +{ + return mDeleted; +} + +void RocketChatChannel::setDeleted( bool deleted ) +{ + mDeleted = deleted; + emit channelDeleted( this->getRoomId(), deleted ); +} bool RocketChatChannel::getBlocked() const { return mBlocked; diff --git a/repos/entities/rocketchatchannel.h b/repos/entities/rocketchatchannel.h index d7589a94b03cd7438eef3d64372b61b19b5c38c4..51df694c8d4a5ccaaca7e3e3a27d8caf2ad78fc0 100755 --- a/repos/entities/rocketchatchannel.h +++ b/repos/entities/rocketchatchannel.h @@ -103,11 +103,15 @@ class RocketChatChannel : public QObject void setParentRepo( ChannelRepository *pParentRepo ); int operator >( RocketChatChannel &channel ); + bool getBlocked() const; void setBlocked( bool blocked ); - protected: + bool getDeleted() const; + void setDeleted( bool deleted ); + protected: + bool mDeleted; bool mReadOnly = false; bool mArchived = false; bool mBlocked = false; @@ -124,7 +128,9 @@ class RocketChatChannel : public QObject void messageListReceived( QString pChannelId, QList<ChatMessage> pMessages ); void messageAdded( QString id, qint64 timestamp ); void unreadMessagesChanged( QString id, int number ); + void channelDeleted( const QString &pId, bool deleted ); void dataChanged( QString id, QString property ); + }; #endif // ROCKETCHATCHANNEL_H diff --git a/repos/entities/rocketchatmessage.cpp b/repos/entities/rocketchatmessage.cpp index fd3dab9442b7977742038348971a9a20e4e4f6fc..20938c90038ec1a870580d07cab1d59a8cb1bfd9 100755 --- a/repos/entities/rocketchatmessage.cpp +++ b/repos/entities/rocketchatmessage.cpp @@ -29,8 +29,8 @@ RocketChatMessage::RocketChatMessage( QJsonObject data, unsigned long timestamp, RocketChatMessage::RocketChatMessage( QJsonObject data ) : data( data ) { timestamp = Utils::getMessageTimestamp( data ); - roomId = data["rid"].toString(); - id = data["_id"].toString(); + roomId = data[QStringLiteral( "rid" )].toString(); + id = data[QStringLiteral( "_id" )].toString(); messageString.reserve( 300 ); @@ -113,14 +113,14 @@ QString RocketChatMessage::getMessageString() const void RocketChatMessage::setMessageString( const QString &value ) { - data["msg"] = value; + data[QStringLiteral( "msg" )] = value; messageString = value; } QString RocketChatMessage::getMessageType() { if ( messageType.length() == 0 ) { - this->messageType = "textMessage"; + this->messageType = QStringLiteral( "textMessage" ); if ( !attachments.empty() ) { QSharedPointer<RocketChatAttachment> first = attachments.first(); diff --git a/repos/loginmethodsrepository.cpp b/repos/loginmethodsrepository.cpp index 5db4893ffe2f0d0d37a6bf9326cf45643a810177..70aa579deb12e52622538756b71ef6b394500089 100644 --- a/repos/loginmethodsrepository.cpp +++ b/repos/loginmethodsrepository.cpp @@ -29,22 +29,22 @@ LoginMethodsRepository::LoginMethodsRepository( QObject *parent ) : QObject( par void LoginMethodsRepository::addLoginMethod( QJsonObject pObject, QString pBaseUrl ) { - if ( pObject.contains( "service" ) && pObject.contains( "serverURL" ) && pObject.contains( "clientId" ) && - pObject.contains( "tokenPath" ) && pObject.contains( "identityPath" ) && - pObject.contains( "authorizePath" ) && pObject.contains( "scope" ) ) { + if ( pObject.contains( QStringLiteral( "service" ) ) && pObject.contains( QStringLiteral( "serverURL" ) ) && pObject.contains( QStringLiteral( "clientId" ) ) && + pObject.contains( QStringLiteral( "tokenPath" ) ) && pObject.contains( QStringLiteral( "identityPath" ) ) && + pObject.contains( QStringLiteral( "authorizePath" ) ) && pObject.contains( QStringLiteral( "scope" ) ) ) { LoginMethod loginMethod; - loginMethod.setServerUrl( pObject["serverURL"].toString() ); + loginMethod.setServerUrl( pObject[QStringLiteral( "serverURL" )].toString() ); - loginMethod.setClientId( pObject["clientId"].toString() ); - loginMethod.setService( pObject["service"].toString() ); - loginMethod.setTokenPath( pObject["tokenPath"].toString() ); - loginMethod.setIdentityPath( pObject["identityPath"].toString() ); - loginMethod.setAuthorizePath( pObject["authorizePath"].toString() ); - loginMethod.setRedirectPath( pBaseUrl + "/_oauth/" + loginMethod.getService() ); - loginMethod.setButtonLabelText( pObject["buttonLabelText"].toString() ); + loginMethod.setClientId( pObject[QStringLiteral( "clientId" )].toString() ); + loginMethod.setService( pObject[QStringLiteral( "service" )].toString() ); + loginMethod.setTokenPath( pObject[QStringLiteral( "tokenPath" )].toString() ); + loginMethod.setIdentityPath( pObject[QStringLiteral( "identityPath" )].toString() ); + loginMethod.setAuthorizePath( pObject[QStringLiteral( "authorizePath" )].toString() ); + loginMethod.setRedirectPath( pBaseUrl + QStringLiteral( "/_oauth/" ) + loginMethod.getService() ); + loginMethod.setButtonLabelText( pObject[QStringLiteral( "buttonLabelText" )].toString() ); - if ( pObject["scope"] == "openid" ) { + if ( pObject[QStringLiteral( "scope" )] == QStringLiteral( "openid" ) ) { loginMethod.setType( LoginMethod::Type::OPENID ); loginMethod.setCredentialToken( Utils::getRandomString() ); diff --git a/restRequests/restpaths.cpp b/restRequests/restpaths.cpp index f4d707a097ad9f6092610a45f88c62fef7ba9aff..667ba8ff73db3fd3c7058edb958b57b859bbe740 100755 --- a/restRequests/restpaths.cpp +++ b/restRequests/restpaths.cpp @@ -21,14 +21,14 @@ #include "restpaths.h" -const QString RestPaths::apiLogin = "/login"; -const QString RestPaths::apiLogoff = "/logout"; -const QString RestPaths::apiMe = "/me"; -const QString RestPaths::apiGetRooms = "/channels.list"; -const QString RestPaths::apiJoinRoom = "/channels.open"; -const QString RestPaths::apiLeaveRoom = "/channels.leave"; -const QString RestPaths::apiRoomMessages = "/channels.history"; -const QString RestPaths::apiSendMessage = "/chat.postMessage"; -const QString RestPaths::apiJoinedRooms = "/channels.list.joined"; -const QString RestPaths::apiJoinedGroups = "/groups.list"; -const QString RestPaths::apiServerInfo = "/info"; +const QString RestPaths::apiLogin {QStringLiteral( "/login" )}; +const QString RestPaths::apiLogoff { QStringLiteral( "/logout" )}; +const QString RestPaths::apiMe { QStringLiteral( "/me" )}; +const QString RestPaths::apiGetRooms {QStringLiteral( "/channels.list" )}; +const QString RestPaths::apiJoinRoom {QStringLiteral( "/channels.open" )}; +const QString RestPaths::apiLeaveRoom { QStringLiteral( "/channels.leave" )}; +const QString RestPaths::apiRoomMessages {QStringLiteral( "/channels.history" )}; +const QString RestPaths::apiSendMessage { QStringLiteral( "/chat.postMessage" )}; +const QString RestPaths::apiJoinedRooms {QStringLiteral( "/channels.list.joined" )}; +const QString RestPaths::apiJoinedGroups { QStringLiteral( "/groups.list" )}; +const QString RestPaths::apiServerInfo { QStringLiteral( "/info" )}; diff --git a/rocketchat.cpp b/rocketchat.cpp index 89712ffdada4da94b8c35e87e6a346d671299da2..765f1946d2fd784ccdf2c17a24867f0aa7b79628 100755 --- a/rocketchat.cpp +++ b/rocketchat.cpp @@ -94,7 +94,7 @@ void RocketChat::joinChannel( const QString &pServerId, const QString &pChannelI if ( mServerStatus ) { - QMetaObject::invokeMethod( mServerMap.first(), "joinChannel", Q_ARG( QString, pChannelId ) ); + QMetaObject::invokeMethod( mServerMap.first(), "joinChannel", Q_ARG( QString, pChannelId ) ); } } @@ -109,7 +109,7 @@ void RocketChat::login( const QString &pServerId, const QString &pUsername, cons qDebug() << "login thread id: " << QThread::currentThreadId(); if ( mServerStatus ) { - QMetaObject::invokeMethod( mServerMap.first(), "login", Q_ARG( QString, pUsername ), Q_ARG( QString, pPassword ) ); + QMetaObject::invokeMethod( mServerMap.first(), "login", Q_ARG( QString, pUsername ), Q_ARG( QString, pPassword ) ); } } @@ -117,7 +117,7 @@ void RocketChat::loginWithSamlToken( const QString &pToken ) { if ( !pToken.isEmpty() ) { if ( mServerStatus ) { - QMetaObject::invokeMethod( mServerMap.first(), "loginWtihSamlToken", Q_ARG( QString, pToken ) ); + QMetaObject::invokeMethod( mServerMap.first(), "loginWtihSamlToken", Q_ARG( QString, pToken ) ); } } } @@ -125,14 +125,14 @@ void RocketChat::loginWithSamlToken( const QString &pToken ) void RocketChat::loginWithMethod( const QString &method, const QString &payload ) { if ( mServerStatus ) { - QMetaObject::invokeMethod( mServerMap.first(), "loginWithMethod", Q_ARG( QString, method ), Q_ARG( QString, payload ) ); + QMetaObject::invokeMethod( mServerMap.first(), "loginWithMethod", Q_ARG( QString, method ), Q_ARG( QString, payload ) ); } } void RocketChat::loadRecentHistory( const QString &pChannelId ) { if ( mServerStatus ) { - QMetaObject::invokeMethod( mServerMap.first(), "loadRecentHistory", Q_ARG( QString, pChannelId ) ); + QMetaObject::invokeMethod( mServerMap.first(), "loadRecentHistory", Q_ARG( QString, pChannelId ) ); } } @@ -190,7 +190,7 @@ bool RocketChat::customEmojisReady() void RocketChat::checkLoggedIn() { if ( mServerStatus ) { - QMetaObject::invokeMethod( mServerMap.first(), "requestIsLoggedIn" ); + QMetaObject::invokeMethod( mServerMap.first(), "requestIsLoggedIn" ); } } @@ -224,6 +224,11 @@ void RocketChat::unBlockUser( const QString &pChannelId ) QMetaObject::invokeMethod( mServerMap.first(), "unBlockUser", Q_ARG( QString, pChannelId ) ); } +void RocketChat::leaveChannel( const QString &pChannelId ) +{ + QMetaObject::invokeMethod( mServerMap.first(), "leaveChannel", Q_ARG( QString, pChannelId ) ); +} + bool RocketChat::newServerByDomain( const QString &domain ) { newServerMutex.lock(); @@ -240,7 +245,7 @@ bool RocketChat::newServerByDomain( const QString &domain ) qDebug() << "test0"; qDebug() << "domain: " << domain; QString baseUrl = domain; - QString apiUri = "https://" + domain + "/api/v1"; + QString apiUri = QStringLiteral( "https://" ) + domain + QStringLiteral( "/api/v1" ); qDebug() << "test1"; this->channelModel.clear(); this->groupsModel.clear(); @@ -257,7 +262,7 @@ bool RocketChat::newServerByDomain( const QString &domain ) } else { QString baseUrl = domain; - QString apiUri = "https://" + domain + "/api/v1"; + QString apiUri = QStringLiteral( "https://" ) + domain + QStringLiteral( "/api/v1" ); this->channelModel.clear(); this->groupsModel.clear(); this->directmodel.clear(); @@ -297,7 +302,7 @@ void RocketChat::openPrivateChannelWith( const QString &pServerId, const QString void RocketChat::getFileRessource( const QString &pUrl ) { if ( mServerStatus ) { - QMetaObject::invokeMethod( mServerMap.first(), "getFileRessource", Q_ARG( QString, pUrl ), Q_ARG( QString, "temp" ) ); + QMetaObject::invokeMethod( mServerMap.first(), "getFileRessource", Q_ARG( QString, pUrl ), Q_ARG( QString, QStringLiteral( "temp" ) ) ); } } @@ -343,7 +348,7 @@ void RocketChat::addUsersToChannel( const QString &pServerId, const QString &pCh Q_UNUSED( pServerId ); if ( mServerStatus ) { - QStringList unserList = pUsernames.split( "," ); + QStringList unserList = pUsernames.split( ',' ); QMetaObject::invokeMethod( mServerMap.first(), "addUsersToChannel", Q_ARG( QString, pChannelName ), Q_ARG( QStringList, unserList ) ); } } @@ -355,7 +360,7 @@ void RocketChat::sendMessage( const QString &pServerId, const QString &pChannelI if ( mServerStatus ) { RocketChatServerData *server = mServerMap.first(); - QMetaObject::invokeMethod( server, "sendMessage", Q_ARG( QString, pChannelId ), Q_ARG( QString, pMessage ) ); + QMetaObject::invokeMethod( server, "sendMessage", Q_ARG( QString, pChannelId ), Q_ARG( QString, pMessage ) ); } } @@ -422,7 +427,7 @@ void RocketChat::getAllChannels() void RocketChat::uploadSharedFileToChannel( const QString &pChannelId ) { if ( mServerStatus ) { - QMetaObject::invokeMethod( mServerMap.first(), "uploadFile", Q_ARG( QString, pChannelId ), Q_ARG( QString, mFileToShare ) ); + QMetaObject::invokeMethod( mServerMap.first(), "uploadFile", Q_ARG( QString, pChannelId ), Q_ARG( QString, mFileToShare ) ); } } @@ -432,7 +437,7 @@ void RocketChat::joinJitsiCall( const QString &pServer, const QString &pChannelI Q_UNUSED( pMessageId ); if ( mServerStatus ) { - QMetaObject::invokeMethod( mServerMap.first(), "joinJitsiCall", Q_ARG( QString, pChannelIdm ) ); + QMetaObject::invokeMethod( mServerMap.first(), "joinJitsiCall", Q_ARG( QString, pChannelIdm ) ); } } @@ -526,20 +531,20 @@ void RocketChat::markChannelAsRead( const QString &pChannelId ) QString RocketChat::getCurrentChannel() { std::tuple<QString, QString> tuple = mStorage->getCurrentChannel(); - QJsonObject data = {{"id", std::get<0>( tuple )}, {"name", std::get<1>( tuple )}}; + QJsonObject data = {{QStringLiteral( "id" ), std::get<0>( tuple )}, {QStringLiteral( "name" ), std::get<1>( tuple )}}; QJsonDocument doc( data ); return doc.toJson(); } void RocketChat::resetCurrentChannel() { - mStorage->setCurrentChannel( "none", "none" ); + mStorage->setCurrentChannel( QStringLiteral( "none" ), QStringLiteral( "none" ) ); } void RocketChat::getUserSuggestions( const QString &pTerm, const QString &pExceptions ) { if ( mServerStatus ) { - QMetaObject::invokeMethod( mServerMap.first(), "getUserSuggestions", Q_ARG( QString, pTerm ), Q_ARG( QString, pExceptions ) ); + QMetaObject::invokeMethod( mServerMap.first(), "getUserSuggestions", Q_ARG( QString, pTerm ), Q_ARG( QString, pExceptions ) ); } } @@ -566,7 +571,7 @@ void RocketChat::logout( const QString &pServerId ) Q_UNUSED( pServerId ); if ( mServerStatus ) { - QMetaObject::invokeMethod( mServerMap.first(), "logout" ); + QMetaObject::invokeMethod( mServerMap.first(), "logout" ); } } @@ -688,11 +693,11 @@ void RocketChat::onChannelSwitchRequest( const QString &server, const QString &r { //TODO: fix emit channelSwitchRequest( server, rid, name, type, readonly ); - mChannelSwitchRequest["server"] = server; - mChannelSwitchRequest["rid"] = rid; - mChannelSwitchRequest["name"] = name; - mChannelSwitchRequest["type"] = type; - mChannelSwitchRequest["ro"] = readonly; + mChannelSwitchRequest[QStringLiteral( "server" )] = server; + mChannelSwitchRequest[QStringLiteral( "rid" )] = rid; + mChannelSwitchRequest[QStringLiteral( "name" )] = name; + mChannelSwitchRequest[QStringLiteral( "type" )] = type; + mChannelSwitchRequest[QStringLiteral( "ro" )] = readonly; } void RocketChat::serverReadySlot() @@ -770,9 +775,9 @@ void RocketChat::openFileNameReady( const QString &pFile ) qDebug() << "file to be uploaded " << pFile; if ( pFile == "null" ) { - emit error( "invalid file information" ); + emit error( QStringLiteral( "invalid file information" ) ); } else if ( !pFile.isEmpty() && mServerStatus ) { - QMetaObject::invokeMethod( mServerMap.first(), "uploadFile", Q_ARG( QString, mCurrentChannel ), Q_ARG( QString, pFile ) ); + QMetaObject::invokeMethod( mServerMap.first(), "uploadFile", Q_ARG( QString, mCurrentChannel ), Q_ARG( QString, pFile ) ); } } @@ -856,7 +861,7 @@ void RocketChat::onOnlineStateChanged( bool pOnline ) if ( pOnline ) { for ( const auto &server : mServerMap ) { - QMetaObject::invokeMethod( server, "resume" ); + QMetaObject::invokeMethod( server, "resume" ); } } else { for ( const auto &server : mServerMap ) { @@ -897,7 +902,7 @@ void RocketChat::onApplicationStateChanged( const Qt::ApplicationState &pState ) if ( mNetworkConfiguration.isOnline() ) { for ( auto server : mServerMap ) { QMetaObject::invokeMethod( server, "setUserPresenceStatus", Q_ARG( int, 2 ) ); - QMetaObject::invokeMethod( server, "disconnectFromServer" ); + QMetaObject::invokeMethod( server, "disconnectFromServer" ); } } diff --git a/rocketchat.h b/rocketchat.h index c4c056b34bf9623ff01936aa82f3652157c17a87..dc329004e821aeaefe2d1e197e4c68fcc5ae9409 100755 --- a/rocketchat.h +++ b/rocketchat.h @@ -125,6 +125,8 @@ class RocketChat : public QObject Q_INVOKABLE void unBlockUser( const QString &pChannelId ); + Q_INVOKABLE void leaveChannel( const QString &pChannelId ); + void registerServer( RocketChatServerData *pServer ); diff --git a/rocketchatserver.cpp b/rocketchatserver.cpp index dbff073e0a34c4b9a87a43b4bdcf4ccdcdd32800..30c1487cfe1a13925f6f47c0a8fe66084a2eec20 100755 --- a/rocketchatserver.cpp +++ b/rocketchatserver.cpp @@ -57,7 +57,7 @@ RocketChatServerData::RocketChatServerData( const QString &pId, QString pBaseUr }; mFileService = new FileService( this ); mEmojiService = new EmojiService( this, mFileService, mStorage ); - setRestApi( new RestApi( this, "https://" + mBaseUrl, mApiUri ) ); + setRestApi( new RestApi( this, QStringLiteral( "https://" ) + mBaseUrl, mApiUri ) ); } RocketChatServerData::~RocketChatServerData() @@ -93,18 +93,19 @@ void RocketChatServerData::init() //mMessageService = new MessageService( mStorage, this, mEmojisMap ); mMessageService = new MessageService( mStorage, this, mEmojiRepo ); - channelService = new RocketChatChannelService( this, mMessageService ); - channelService->setChannels( mChannels ); + mChannelService = new RocketChatChannelService( this, mMessageService ); + mChannelService->setDdp( mDdpApi ); + mChannelService->setChannels( mChannels ); - connect( channelService, &RocketChatChannelService::channelsLoaded, this, &RocketChatServerData::onChannelsLoaded, Qt::UniqueConnection ); - connect( channelService, &RocketChatChannelService::usersLoaded, this, &RocketChatServerData::onUsersLoaded, Qt::UniqueConnection ); - connect( channelService, &RocketChatChannelService::directChannelReady, this, &RocketChatServerData::switchChannelByRid, Qt::UniqueConnection ); + connect( mChannelService, &RocketChatChannelService::channelsLoaded, this, &RocketChatServerData::onChannelsLoaded, Qt::UniqueConnection ); + connect( mChannelService, &RocketChatChannelService::usersLoaded, this, &RocketChatServerData::onUsersLoaded, Qt::UniqueConnection ); + connect( mChannelService, &RocketChatChannelService::directChannelReady, this, &RocketChatServerData::switchChannelByRid, Qt::UniqueConnection ); connect( &channelsModel, &ChannelModel::unreadMessagesChanged, this, &RocketChatServerData::onUnreadCountChanged, Qt::UniqueConnection ); connect( &directModel, &ChannelModel::unreadMessagesChanged, this, &RocketChatServerData::onUnreadCountChanged, Qt::UniqueConnection ); connect( &groupsModel, &ChannelModel::unreadMessagesChanged, this, &RocketChatServerData::onUnreadCountChanged, Qt::UniqueConnection ); - QString lastServer = mStorage->getSetting( "currentServer" ); + QString lastServer = mStorage->getSetting( QStringLiteral( "currentServer" ) ); if ( lastServer == mBaseUrl ) { QPair<QString, uint> tokenDb = mStorage->getToken(); @@ -121,7 +122,7 @@ void RocketChatServerData::init() } emit readyToCheckForPendingNotification(); - channelService->loadJoinedChannelsFromDb(); + mChannelService->loadJoinedChannelsFromDb(); } @@ -192,7 +193,7 @@ void RocketChatServerData::switchChannel( const QString &pServer, const QString if ( mChannels != nullptr && !mChannels->contains( pRid ) ) { if ( pType == "d" || pType == "c" || pType == "p" ) { qDebug() << "create new channel object to:" << pRid; - channelService->createChannelObject( pRid, pName, pType ); + mChannelService->createChannelObject( pRid, pName, pType ); if ( mChannels->contains( pRid ) && !mChannels->get( pRid ).isNull() ) { switchPossible = true; @@ -220,7 +221,7 @@ void RocketChatServerData::switchChannelByRid( const QString &pName ) if ( mLoggedIn ) { if ( mChannels->getChannelByName( pName ) ) { auto channel = mChannels->getChannelByName( pName ); - switchChannel( "default", channel->getRoomId(), pName, channel->getType() ); + switchChannel( QStringLiteral( "default" ), channel->getRoomId(), pName, channel->getType() ); mPendingSwitchRoomRequest.clear(); } else { searchForRoomIdByName( pName ); @@ -258,13 +259,13 @@ void RocketChatServerData::requestGetChannelDetails( const QString &pChannelId ) QVariantMap details; - details["archived"] = archived; - details["ro"] = readonly; - details["muted"] = mutedList; - details["selfMuted"] = selfMuted; - details["type"] = type; - details["name"] = channel->getName(); - details["blocked"] = channel->getBlocked(); + details[QStringLiteral( "archived" )] = archived; + details[QStringLiteral( "ro" )] = readonly; + details[QStringLiteral( "muted" )] = mutedList; + details[QStringLiteral( "selfMuted" )] = selfMuted; + details[QStringLiteral( "type" )] = type; + details[QStringLiteral( "name" )] = channel->getName(); + details[QStringLiteral( "blocked" )] = channel->getBlocked(); emit channelDetailsReady( details, pChannelId ); } @@ -274,7 +275,7 @@ void RocketChatServerData::requestGetChannelDetails( const QString &pChannelId ) void RocketChatServerData::requestIsLoggedIn() { if ( mLoggedIn ) { - emit loggedIn( "default" ); + emit loggedIn( QStringLiteral( "default" ) ); } } @@ -315,36 +316,36 @@ void RocketChatServerData::searchForRoomIdByName( const QString &pName ) QSharedPointer<RocketChatSpotLightRequest> request( new RocketChatSpotLightRequest( pName ) ); std::function<void ( QJsonObject, MeteorDDP * )> success = [ = ]( QJsonObject pResponse, MeteorDDP * ) { - if ( pResponse.contains( "result" ) ) { - QJsonObject result = pResponse["result"].toObject(); + if ( pResponse.contains( QStringLiteral( "result" ) ) ) { + QJsonObject result = pResponse[QStringLiteral( "result" )].toObject(); - if ( result.contains( "users" ) ) { - QJsonArray users = result["users"].toArray(); + if ( result.contains( QStringLiteral( "users" ) ) ) { + QJsonArray users = result[QStringLiteral( "users" )].toArray(); for ( const auto &user : users ) { QJsonObject userObj = user.toObject(); - if ( userObj.contains( "username" ) && userObj.contains( "_id" ) ) { - QString username = userObj["username"].toString(); + if ( userObj.contains( QStringLiteral( "username" ) ) && userObj.contains( QStringLiteral( "_id" ) ) ) { + QString username = userObj[QStringLiteral( "username" )].toString(); if ( !username.compare( pName, Qt::CaseInsensitive ) ) { - QString id = userObj["_id"].toString(); - switchChannel( "default", id, pName, "d" ); + QString id = userObj[QStringLiteral( "_id" )].toString(); + switchChannel( QStringLiteral( "default" ), id, pName, "d" ); } } } - } else if ( result.contains( "rooms" ) ) { - QJsonArray rooms = result["rooms"].toArray(); + } else if ( result.contains( QStringLiteral( "rooms" ) ) ) { + QJsonArray rooms = result[QStringLiteral( "rooms" )].toArray(); for ( const auto &room : rooms ) { QJsonObject roomObj = room.toObject(); - if ( roomObj.contains( "name" ) && roomObj.contains( "_id" ) ) { - QString roomname = roomObj["name"].toString(); + if ( roomObj.contains( QStringLiteral( "name" ) ) && roomObj.contains( QStringLiteral( "_id" ) ) ) { + QString roomname = roomObj[QStringLiteral( "name" )].toString(); if ( !roomname.compare( pName, Qt::CaseInsensitive ) ) { - QString id = roomObj["_id"].toString(); - switchChannel( "default", id, pName, "c" ); + QString id = roomObj[QStringLiteral( "_id" )].toString(); + switchChannel( QStringLiteral( "default" ), id, pName, "c" ); } } } @@ -448,7 +449,7 @@ void RocketChatServerData::onUnreadCountChanged() } } - emit unreadCountChanged( "default", number ); + emit unreadCountChanged( QStringLiteral( "default" ), number ); } qint16 RocketChatServerData::getCustomEmojisHash() const @@ -485,7 +486,7 @@ void RocketChatServerData::offlineLogin() if ( !userId.isEmpty() && !userName.isEmpty() ) { this->mUserId = userId; - emit loggedIn( "default" ); + emit loggedIn( QStringLiteral( "default" ) ); } } @@ -535,16 +536,16 @@ void RocketChatServerData::loginWithHash( const QString &pUsername, const QStrin std::function<void ( QJsonObject, MeteorDDP * )> success = [ = ]( QJsonObject pResponse, MeteorDDP * ) { qDebug() << "authenticated"; - if ( pResponse.contains( "result" ) ) { - QJsonObject result = pResponse["result"].toObject(); + if ( pResponse.contains( QStringLiteral( "result" ) ) ) { + QJsonObject result = pResponse[QStringLiteral( "result" )].toObject(); - if ( result.contains( "token" ) && result.contains( "id" ) ) { + if ( result.contains( QStringLiteral( "token" ) ) && result.contains( QStringLiteral( "id" ) ) ) { mConnectionState = ConnectionState::ONLINE; - mResumeToken = result["token"].toString(); - QJsonObject expireObject = result["tokenExpires"].toObject(); - double expireDouble = expireObject["$date"].toDouble(); + mResumeToken = result[QStringLiteral( "token" )].toString(); + QJsonObject expireObject = result[( "tokenExpires" )].toObject(); + double expireDouble = expireObject[QStringLiteral( "$date" )].toDouble(); mTokenExpire = static_cast<uint>( expireDouble / 1000 ); - QString userId = result["id"].toString(); + QString userId = result[QStringLiteral( "id" )].toString(); mStorage->transaction(); mStorage->setUserData( pUsername, pPswHash ); mStorage->setToken( mResumeToken, mTokenExpire ); @@ -552,7 +553,7 @@ void RocketChatServerData::loginWithHash( const QString &pUsername, const QStrin mRestApi->setToken( mResumeToken ); mRestApi->setUserId( userId ); mStorage->commit(); - this->mUserId = result["id"].toString(); + this->mUserId = result[QStringLiteral( "id" )].toString(); mDdpApi->setToken( mResumeToken ); mDdpApi->unsetResponseBinding( request->getFrame() ); this->onDDPAuthenticated(); @@ -582,8 +583,8 @@ void RocketChatServerData::loginWithToken( const QString &pUsername, const QStri RestRequestCallback meCallBackSuccess = [ = ]( QNetworkReply *, QJsonObject data, RestApi * ) { - if ( data.contains( "username" ) ) { - mUsername = data["username"].toString(); + if ( data.contains( QStringLiteral( "username" ) ) ) { + mUsername = data[QStringLiteral( "username" )].toString(); mStorage->setUserName( mUsername ); onResume(); this->onDDPAuthenticated(); @@ -596,21 +597,21 @@ void RocketChatServerData::loginWithToken( const QString &pUsername, const QStri qDebug() << "authenticated"; mConnectionState = ConnectionState::ONLINE; - if ( pResponse.contains( "result" ) ) { - QJsonObject result = pResponse["result"].toObject(); + if ( pResponse.contains( QStringLiteral( "result" ) ) ) { + QJsonObject result = pResponse[QStringLiteral( "result" )].toObject(); - if ( result.contains( "token" ) && result.contains( "id" ) ) { - this->mResumeToken = result["token"].toString(); - QJsonObject expireObject = result["tokenExpires"].toObject(); - double expireDouble = expireObject["$date"].toDouble(); + if ( result.contains( QStringLiteral( "token" ) ) && result.contains( QStringLiteral( "id" ) ) ) { + this->mResumeToken = result[QStringLiteral( "token" )].toString(); + QJsonObject expireObject = result[QStringLiteral( "tokenExpires" )].toObject(); + double expireDouble = expireObject[QStringLiteral( "$date" )].toDouble(); mTokenExpire = static_cast<uint>( expireDouble / 1000 ); - QString userId = result["id"].toString(); + QString userId = result[QStringLiteral( "id" )].toString(); mStorage->setToken( mResumeToken, mTokenExpire ); mStorage->setUserId( userId ); mRestApi->setToken( mResumeToken ); mRestApi->setUserId( userId ); - this->mUserId = result["id"].toString(); + this->mUserId = result[QStringLiteral( "id" )].toString(); mDdpApi->setToken( mResumeToken ); mDdpApi->unsetResponseBinding( request->getFrame() ); @@ -659,8 +660,8 @@ void RocketChatServerData::loginWtihSamlToken( const QString &pToken ) RestRequestCallback meCallBackSuccess = [ = ]( QNetworkReply *, QJsonObject data, RestApi * ) { - if ( data.contains( "username" ) ) { - mUsername = data["username"].toString(); + if ( data.contains( QStringLiteral( "username" ) ) ) { + mUsername = data[QStringLiteral( "username" )].toString(); mStorage->setUserName( mUsername ); onResume(); this->onDDPAuthenticated(); @@ -673,21 +674,21 @@ void RocketChatServerData::loginWtihSamlToken( const QString &pToken ) qDebug() << "authenticated"; mConnectionState = ConnectionState::ONLINE; - if ( pResponse.contains( "result" ) ) { - QJsonObject result = pResponse["result"].toObject(); + if ( pResponse.contains( QStringLiteral( "result" ) ) ) { + QJsonObject result = pResponse[QStringLiteral( "result" )].toObject(); - if ( result.contains( "token" ) && result.contains( "id" ) ) { - this->mResumeToken = result["token"].toString(); - QJsonObject expireObject = result["tokenExpires"].toObject(); - double expireDouble = expireObject["$date"].toDouble(); + if ( result.contains( QStringLiteral( "token" ) ) && result.contains( QStringLiteral( "id" ) ) ) { + this->mResumeToken = result[QStringLiteral( "token" )].toString(); + QJsonObject expireObject = result[QStringLiteral( "tokenExpires" )].toObject(); + double expireDouble = expireObject[QStringLiteral( "$date" )].toDouble(); mTokenExpire = static_cast<uint>( expireDouble / 1000 ); - QString userId = result["id"].toString(); + QString userId = result[QStringLiteral( "id" )].toString(); mStorage->setToken( mResumeToken, mTokenExpire ); mStorage->setUserId( userId ); mRestApi->setToken( mResumeToken ); mRestApi->setUserId( userId ); - this->mUserId = result["id"].toString(); + this->mUserId = result[QStringLiteral( "id" )].toString(); mDdpApi->setToken( mResumeToken ); mDdpApi->unsetResponseBinding( request->getFrame() ); @@ -723,8 +724,8 @@ void RocketChatServerData::loginWithOpenIDToken( const QString &pToken, const QS RestRequestCallback meCallBackSuccess = [ = ]( QNetworkReply *, QJsonObject data, RestApi * ) { - if ( data.contains( "username" ) ) { - mUsername = data["username"].toString(); + if ( data.contains( QStringLiteral( "username" ) ) ) { + mUsername = data[QStringLiteral( "username" )].toString(); mStorage->transaction(); mStorage->setUserData( mUsername, "" ); mStorage->setToken( mResumeToken, mTokenExpire ); @@ -741,21 +742,21 @@ void RocketChatServerData::loginWithOpenIDToken( const QString &pToken, const QS qDebug() << "authenticated"; mConnectionState = ConnectionState::ONLINE; - if ( pResponse.contains( "result" ) ) { - QJsonObject result = pResponse["result"].toObject(); + if ( pResponse.contains( QStringLiteral( "result" ) ) ) { + QJsonObject result = pResponse[QStringLiteral( "result" )].toObject(); - if ( result.contains( "token" ) && result.contains( "id" ) ) { + if ( result.contains( QStringLiteral( "token" ) ) && result.contains( QStringLiteral( "id" ) ) ) { mConnectionState = ConnectionState::ONLINE; - mResumeToken = result["token"].toString(); - QJsonObject expireObject = result["tokenExpires"].toObject(); - double expireDouble = expireObject["$date"].toDouble(); + mResumeToken = result[QStringLiteral( "token" )].toString(); + QJsonObject expireObject = result[QStringLiteral( "tokenExpires" )].toObject(); + double expireDouble = expireObject[QStringLiteral( "$date" )].toDouble(); mTokenExpire = static_cast<uint>( expireDouble / 1000 ); - QString userId = result["id"].toString(); + QString userId = result[QStringLiteral( "id" )].toString(); mRestApi->setToken( mResumeToken ); mRestApi->setUserId( userId ); - mUserId = result["id"].toString(); + mUserId = result[QStringLiteral( "id" )].toString(); mDdpApi->setToken( mResumeToken ); mDdpApi->unsetResponseBinding( request->getFrame() ); @@ -797,9 +798,9 @@ void RocketChatServerData::loginWithMethod( const QString &method, const QString QJsonDocument doc = QJsonDocument::fromJson( payload.toUtf8() ); QJsonObject obj = doc.object(); - if ( obj.contains( "credentialToken" ) && obj.contains( "credentialSecret" ) ) { - token = obj["credentialToken"].toString(); - secret = obj["credentialSecret"].toString(); + if ( obj.contains( QStringLiteral( "credentialToken" ) ) && obj.contains( QStringLiteral( "credentialSecret" ) ) ) { + token = obj[QStringLiteral( "credentialToken" )].toString(); + secret = obj[QStringLiteral( "credentialSecret" )].toString(); loginWithOpenIDToken( token, secret ); } } @@ -836,7 +837,7 @@ void RocketChatServerData::onDDPAuthenticated() //TODO: dirty fix! getCustomEmojis(); setUserPresenceStatus( 1 ); - mStorage->setSetting( "currentServer", mBaseUrl ); + mStorage->setSetting( QStringLiteral( "currentServer" ), mBaseUrl ); getServerInfo(); if ( !mCurrentChannel.isEmpty() ) { @@ -847,22 +848,22 @@ void RocketChatServerData::onDDPAuthenticated() void RocketChatServerData::handleChannelMessage( const QJsonObject &pMessage ) { - if ( Q_LIKELY( pMessage.contains( "fields" ) ) ) { - QJsonObject fields = pMessage["fields"].toObject(); + if ( Q_LIKELY( pMessage.contains( QStringLiteral( "fields" ) ) ) ) { + QJsonObject fields = pMessage[QStringLiteral( "fields" )].toObject(); - if ( Q_LIKELY( fields.contains( "args" ) ) ) { - QJsonArray args = fields["args"].toArray(); + if ( Q_LIKELY( fields.contains( QStringLiteral( "args" ) ) ) ) { + QJsonArray args = fields[QStringLiteral( "args" )].toArray(); QString firstArg = args[0].toString(); - if ( firstArg == "insert" || firstArg == "inserted" ) { + if ( firstArg == QStringLiteral( "insert" ) || firstArg == QStringLiteral( "inserted" ) ) { QJsonObject newChannel = args[1].toObject(); - if ( newChannel.contains( "name" ) && newChannel.contains( "rid" ) && newChannel.contains( "t" ) ) { - QString name = newChannel["name"].toString(); - QString rid = newChannel["rid"].toString(); + if ( newChannel.contains( QStringLiteral( "name" ) ) && newChannel.contains( QStringLiteral( "rid" ) ) && newChannel.contains( "t" ) ) { + QString name = newChannel[QStringLiteral( "name" )].toString(); + QString rid = newChannel[QStringLiteral( "rid" )].toString(); - if ( !mChannels->contains( "id" ) ) { - QSharedPointer<RocketChatChannel> channel = channelService->createChannelObject( rid, name, newChannel["t"].toString() ); + if ( !mChannels->contains( QStringLiteral( "id" ) ) ) { + QSharedPointer<RocketChatChannel> channel = mChannelService->createChannelObject( rid, name, newChannel["t"].toString() ); if ( !channel.isNull() ) { channel->setJoined( true ); @@ -874,15 +875,15 @@ void RocketChatServerData::handleChannelMessage( const QJsonObject &pMessage ) } } } - } else if ( firstArg == "updated" ) { + } else if ( firstArg == QStringLiteral( "updated" ) ) { QJsonObject data = args[1].toObject(); - int unread = data["unread"].toInt(); - QString rid = data["rid"].toString(); + int unread = data[QStringLiteral( "unread" )].toInt(); + QString rid = data[QStringLiteral( "rid" )].toString(); bool blocked = false; - QString name = data["name"].toString(); + QString name = data[QStringLiteral( "name" )].toString(); - if ( data.contains( "blocker" ) ) { - blocked = data["blocker"].toBool(); + if ( data.contains( QStringLiteral( "blocker" ) ) ) { + blocked = data[QStringLiteral( "blocker" )].toBool(); } if ( mChannels->contains( rid ) && !mChannels->get( rid ).isNull() ) { @@ -906,14 +907,14 @@ uint RocketChatServerData::diffToLastDDPPing() void RocketChatServerData::getFileRessource( const QString &pUrl ) { - getFileRessource( pUrl, "temp" ); + getFileRessource( pUrl, QStringLiteral( "temp" ) ); } void RocketChatServerData::getFileRessource( const QString &pUrl, const QString &pType ) { bool showInline = false; - if ( pType == "temp" ) { + if ( pType == QStringLiteral( "temp" ) ) { showInline = true; } @@ -943,8 +944,8 @@ void RocketChatServerData::requestAllChannels() for ( const auto &channel : mChannels->getElements() ) { if ( !channel.isNull() ) { QVariantMap obj; - obj["name"] = channel->getName(); - obj["id"] = channel->getRoomId(); + obj[QStringLiteral( "name" )] = channel->getName(); + obj[QStringLiteral( "id" )] = channel->getRoomId(); channelsMap.append( obj ); } } @@ -1039,28 +1040,28 @@ void RocketChatServerData::onDDPMessageReceived( const QJsonObject &pMessage ) { sendUnsentMessages(); - if ( Q_LIKELY( pMessage.contains( "collection" ) ) ) { + if ( Q_LIKELY( pMessage.contains( QStringLiteral( "collection" ) ) ) ) { - if ( pMessage["collection"] == "stream-notify-user" ) { + if ( pMessage[QStringLiteral( "collection" )] == QStringLiteral( "stream-notify-user" ) ) { handleChannelMessage( pMessage ); - } else if ( pMessage["collection"] == "users" ) { - QString userId = pMessage["id"].toString(); + } else if ( pMessage[QStringLiteral( "collection" )] == QStringLiteral( "users" ) ) { + QString userId = pMessage[QStringLiteral( "id" )].toString(); if ( mUsers.contains( userId ) ) { - QString msg = pMessage["msg"].toString(); + QString msg = pMessage[QStringLiteral( "msg" )].toString(); - if ( msg == "added" ) { + if ( msg == QStringLiteral( "added" ) ) { mUsers.get( userId )->setStatus( RocketChatUser::status::ONLINE ); - } else if ( msg == "changed" ) { + } else if ( msg == QStringLiteral( "changed" ) ) { QJsonObject fields = pMessage["fields"].toObject(); - if ( fields.contains( "status" ) ) { - QString msgStatus = fields["status"].toString(); + if ( fields.contains( QStringLiteral( "status" ) ) ) { + QString msgStatus = fields[QStringLiteral( "status" )].toString(); RocketChatUser::status userStatus; - if ( msgStatus == "online" ) { + if ( msgStatus == QStringLiteral( "online" ) ) { userStatus = RocketChatUser::status::ONLINE; - } else if ( msgStatus == "away" ) { + } else if ( msgStatus == QStringLiteral( "away" ) ) { userStatus = RocketChatUser::status::AWAY; } else { userStatus = RocketChatUser::status::OFFLINE; @@ -1069,36 +1070,36 @@ void RocketChatServerData::onDDPMessageReceived( const QJsonObject &pMessage ) mUsers.get( userId )->setStatus( userStatus ); } - } else if ( msg == "removed" ) { + } else if ( msg == QStringLiteral( "removed" ) ) { mUsers.get( userId )->setStatus( RocketChatUser::status::OFFLINE ); } } else { } - } else if ( pMessage["collection"] == "autocompleteRecords" ) { - if ( Q_LIKELY( pMessage.contains( "fields" ) && pMessage.contains( "msg" ) && pMessage.contains( "id" ) ) ) { - QJsonObject fields = pMessage["fields"].toObject(); - - if ( pMessage["msg"] == "added" ) { - mAutocompleteRecords[pMessage["id"].toString()] = fields; - } else if ( pMessage["msg"] == "removed" ) { - mAutocompleteRecords.remove( pMessage["id"].toString() ); + } else if ( pMessage[QStringLiteral( "collection" )] == QStringLiteral( "autocompleteRecords" ) ) { + if ( Q_LIKELY( pMessage.contains( QStringLiteral( "fields" ) ) && pMessage.contains( QStringLiteral( "msg" ) ) && pMessage.contains( QStringLiteral( "id" ) ) ) ) { + QJsonObject fields = pMessage[QStringLiteral( "fields" )].toObject(); + + if ( pMessage[QStringLiteral( "msg" )] == QStringLiteral( "added" ) ) { + mAutocompleteRecords[pMessage[QStringLiteral( "id" )].toString()] = fields; + } else if ( pMessage[QStringLiteral( "msg" )] == QStringLiteral( "removed" ) ) { + mAutocompleteRecords.remove( pMessage[QStringLiteral( "id" )].toString() ); } } - } else if ( pMessage["collection"] == "meteor_accounts_loginServiceConfiguration" ) { - if ( Q_LIKELY( pMessage.contains( "fields" ) && pMessage.contains( "msg" ) && pMessage.contains( "id" ) ) ) { - QString msg = pMessage["msg"].toString(); + } else if ( pMessage[QStringLiteral( "collection" )] == QStringLiteral( "meteor_accounts_loginServiceConfiguration" ) ) { + if ( Q_LIKELY( pMessage.contains( QStringLiteral( "fields" ) ) && pMessage.contains( QStringLiteral( "msg" ) ) && pMessage.contains( QStringLiteral( "id" ) ) ) ) { + QString msg = pMessage[QStringLiteral( "msg" )].toString(); - if ( msg == "added" ) { - QJsonObject data = pMessage["fields"].toObject(); + if ( msg == QStringLiteral( "added" ) ) { + QJsonObject data = pMessage[QStringLiteral( "fields" )].toObject(); - if ( data.contains( "scope" ) ) { - QString scope = data["scope"].toString(); + if ( data.contains( QStringLiteral( "scope" ) ) ) { + QString scope = data[QStringLiteral( "scope" )].toString(); - if ( scope == "openid" ) { + if ( scope == QStringLiteral( "openid" ) ) { // QMap<QString, QVariant> entry = data.toVariantMap(); - QString service = data["service"].toString(); - mLoginMethodRepo.addLoginMethod( data, "https://" + mBaseUrl ); + QString service = data[QStringLiteral( "service" )].toString(); + mLoginMethodRepo.addLoginMethod( data, QStringLiteral( "https://" ) + mBaseUrl ); if ( mLoginMethodRepo.contains( service ) ) { LoginMethod loginMethod = mLoginMethodRepo.get( service ); @@ -1118,7 +1119,7 @@ void RocketChatServerData::onDDPMessageReceived( const QJsonObject &pMessage ) bool RocketChatServerData::isStreamRoomMessage( const QJsonObject &pMessage ) const { - if ( Q_LIKELY( pMessage.contains( "collection" ) && pMessage["collection"] == "stream-room-messages" ) ) { + if ( Q_LIKELY( pMessage.contains( QStringLiteral( "collection" ) ) && pMessage[QStringLiteral( "collection" )] == QStringLiteral( "stream-room-messages" ) ) ) { return true; } @@ -1127,7 +1128,7 @@ bool RocketChatServerData::isStreamRoomMessage( const QJsonObject &pMessage ) co bool RocketChatServerData::isUserJoinMessage( const QJsonObject &pMessage ) const { - if ( pMessage.contains( "fields" ) && pMessage["fields"].toObject().contains( "t" ) && pMessage["fields"].toObject()["t"] == "uj" ) { + if ( pMessage.contains( QStringLiteral( "fields" ) ) && pMessage[QStringLiteral( "fields" )].toObject().contains( "t" ) && pMessage[QStringLiteral( "fields" )].toObject()["t"] == QStringLiteral( "uj" ) ) { return true; } @@ -1136,17 +1137,17 @@ bool RocketChatServerData::isUserJoinMessage( const QJsonObject &pMessage ) cons void RocketChatServerData::handleStreamRoomMessage( const QJsonObject &pMessage ) { - if ( Q_LIKELY( pMessage.contains( "fields" ) ) ) { - QJsonObject fields = pMessage["fields"].toObject(); + if ( Q_LIKELY( pMessage.contains( QStringLiteral( "fields" ) ) ) ) { + QJsonObject fields = pMessage[QStringLiteral( "fields" )].toObject(); - if ( Q_LIKELY( fields.contains( "args" ) ) ) { - QJsonArray args = fields["args"].toArray(); + if ( Q_LIKELY( fields.contains( QStringLiteral( "args" ) ) ) ) { + QJsonArray args = fields[QStringLiteral( "args" )].toArray(); for ( const auto ¤tArg : args ) { QJsonObject currentArgObj = currentArg.toObject(); - if ( Q_LIKELY( currentArgObj.contains( "rid" ) && currentArgObj.contains( "_id" ) ) ) { - QString roomId = currentArgObj["rid"].toString(); + if ( Q_LIKELY( currentArgObj.contains( QStringLiteral( "rid" ) ) && currentArgObj.contains( QStringLiteral( "_id" ) ) ) ) { + QString roomId = currentArgObj[QStringLiteral( "rid" )].toString(); auto message = mMessageService->parseMessage( currentArgObj, true ); if ( Q_LIKELY( mChannels->contains( roomId ) ) ) { @@ -1161,16 +1162,16 @@ void RocketChatServerData::handleStreamRoomMessage( const QJsonObject &pMessage void RocketChatServerData::handleUserJoinMessage( const QJsonObject &pMessage ) { - if ( Q_LIKELY( pMessage.contains( "fields" ) ) ) { - QJsonObject fields = pMessage["fields"].toObject(); + if ( Q_LIKELY( pMessage.contains( QStringLiteral( "fields" ) ) ) ) { + QJsonObject fields = pMessage[QStringLiteral( "fields" )].toObject(); if ( Q_LIKELY( fields.contains( "rid" ) && fields.contains( "u" ) ) ) { - QString roomId = fields["rid"].toString(); + QString roomId = fields[QStringLiteral( "rid" )].toString(); QJsonObject userData = fields["u"].toObject(); - if ( Q_LIKELY( userData.contains( "_id" ) && userData.contains( "username" ) ) ) { - QString userId = userData["_id"].toString(); - QString username = userData["username"].toString(); + if ( Q_LIKELY( userData.contains( QStringLiteral( "_id" ) ) && userData.contains( QStringLiteral( "username" ) ) ) ) { + QString userId = userData[QStringLiteral( "_id" )].toString(); + QString username = userData[QStringLiteral( "username" )].toString(); if ( Q_LIKELY( mChannels->contains( roomId ) ) ) { QSharedPointer<RocketChatChannel> channel = mChannels->get( roomId ); @@ -1206,7 +1207,7 @@ void RocketChatServerData::onResume() if ( mChannels->contains( channelId ) ) { auto channel = mChannels->get( channelId ); - channelService->subscribeChannel( channel ); + mChannelService->subscribeChannel( channel ); //loadMissedMessages(); qDebug() << "connection resumed"; @@ -1221,17 +1222,17 @@ void RocketChatServerData::onResume() QJsonObject RocketChatServerData::formatMessageTime( const QJsonObject &pJsonObject ) { - if ( Q_LIKELY( pJsonObject.contains( "ts" ) ) ) { - QJsonObject ts = pJsonObject["ts"].toObject(); + if ( Q_LIKELY( pJsonObject.contains( QStringLiteral( "ts" ) ) ) ) { + QJsonObject ts = pJsonObject[QStringLiteral( "ts" )].toObject(); - if ( Q_LIKELY( ts.contains( "$date" ) ) ) { - double timeStamp = ts["$date"].toDouble(); + if ( Q_LIKELY( ts.contains( QStringLiteral( "$date" ) ) ) ) { + double timeStamp = ts[QStringLiteral( "$date" )].toDouble(); QDateTime dateTime = QDateTime::fromMSecsSinceEpoch( timeStamp ); - QString formattedTime = dateTime.toString( "hh:mm" ); - QString formattedDate = dateTime.toString( "dd.MM.yyyy" ); - pJsonObject["formattedDate"] = formattedDate; - pJsonObject["formattedTime"] = formattedTime; - pJsonObject["msg"] = parseMessageReceived( pJsonObject["msg"].toString() ); + QString formattedTime = dateTime.toString( QStringLiteral( "hh:mm" ) ); + QString formattedDate = dateTime.toString( QStringLiteral( "dd.MM.yyyy" ) ); + pJsonObject[QStringLiteral( "formattedDate" )] = formattedDate; + pJsonObject[QStringLiteral( "formattedTime" )] = formattedTime; + pJsonObject[QStringLiteral( "msg" )] = parseMessageReceived( pJsonObject[QStringLiteral( "msg" )].toString() ); return pJsonObject; } } @@ -1245,11 +1246,11 @@ void RocketChatServerData::joinJitsiCall( const QString &pRoomId ) if ( Q_LIKELY( mChannels->contains( pRoomId ) ) ) { QString hash = QCryptographicHash::hash( ( RocketChatServerConfig::uniqueId + pRoomId ).toUtf8(), QCryptographicHash::Md5 ).toHex(); #if defined(Q_OS_IOS) || defined(Q_OS_ANDROID) - QString scheme = "org.jitsi.meet://"; + QString scheme = QStringLiteral( "org.jitsi.meet://" ); #else QString scheme = "https://"; #endif - QString url = scheme + RocketChatServerConfig::jitsiMeetUrl + "/" + RocketChatServerConfig::jitsiMeetPrefix + hash; + QString url = scheme + RocketChatServerConfig::jitsiMeetUrl + '/' + RocketChatServerConfig::jitsiMeetPrefix + hash; qDebug() << url; emit openUrl( url ); } @@ -1306,25 +1307,25 @@ void RocketChatServerData::setUsername( const QString &pUsername ) void RocketChatServerData::getServerSettings() { QJsonArray params = {}; - QSharedPointer<DDPMethodRequest> request( new DDPMethodRequest( "public-settings/get", params ) ); + QSharedPointer<DDPMethodRequest> request( new DDPMethodRequest( QStringLiteral( "public-settings/get" ), params ) ); DdpCallback sucess = [ = ]( QJsonObject data, MeteorDDP * ddpApi ) { Q_UNUSED( ddpApi ); - QJsonArray configs = data["result"].toArray(); + QJsonArray configs = data[QStringLiteral( "result" )].toArray(); for ( const auto ¤tConfig : configs ) { QJsonObject currentConfObject = currentConfig.toObject(); - QString id = currentConfObject["_id"].toString(); - QString value = currentConfObject["value"].toString(); + QString id = currentConfObject[QStringLiteral( "_id" )].toString(); + QString value = currentConfObject[QStringLiteral( "value" )].toString(); - if ( id == "uniqueID" ) { + if ( id == QStringLiteral( "uniqueID" ) ) { RocketChatServerConfig::uniqueId = value; } - if ( id == "Jitsi_Domain" ) { + if ( id == QStringLiteral( "Jitsi_Domain" ) ) { RocketChatServerConfig::jitsiMeetUrl = value; } - if ( id == "Jitsi_URL_Room_Prefix" ) { + if ( id == QStringLiteral( "Jitsi_URL_Room_Prefix" ) ) { RocketChatServerConfig::jitsiMeetPrefix = value; } } @@ -1351,7 +1352,7 @@ void RocketChatServerData::onFileDownloaded( const QString &pUrl, const QString void RocketChatServerData::onLoggedIn() { mLoggedIn = true; - channelService->loadJoinedChannelsFromServer(); + mChannelService->loadJoinedChannelsFromServer(); emit loggedIn( mServerId ); if ( !mPendingSwitchRoomRequest.isEmpty() ) { @@ -1372,7 +1373,7 @@ void RocketChatServerData::joinChannel( const QString &pChannelId ) // if(mCurrentChannel != pChannelId){ mCurrentChannel = pChannelId; auto channel = mChannels->get( pChannelId ); - channelService->subscribeChannel( channel ); + mChannelService->subscribeChannel( channel ); setUnreadMessages( pChannelId, 0 ); markChannelAsRead( pChannelId ); setCurrentChannel( pChannelId ); @@ -1405,7 +1406,7 @@ void RocketChatServerData::setServerId( const QString &pValue ) void RocketChatServerData::setServerAddress( const QString &pServerAddress ) { mBaseUrl = pServerAddress; - mApiUri = "https://" + pServerAddress + "/api/v1"; + mApiUri = QStringLiteral( "https://" ) + pServerAddress + QStringLiteral( "/api/v1" ); } bool RocketChatServerData::isConnected() const @@ -1478,7 +1479,7 @@ void RocketChatServerData::getCustomEmojis() mEmojiRepo->add( emoji->getIdentifier(), emoji ); variantList.append( emoji->toQVariantMap() ); - if ( emoji->getCategory() == "custom" ) { + if ( emoji->getCategory() == QStringLiteral( "custom" ) ) { // mCustomEmojisHash = Utils::hash(mCustomEmojis); } } @@ -1516,7 +1517,7 @@ void RocketChatServerData::openPrivateChannelWith( const QString &pUsername ) if ( mChannels->getChannelByName( pUsername ) ) { switchChannelByRid( pUsername ); } else { - channelService->openPrivateChannelWith( pUsername ); + mChannelService->openPrivateChannelWith( pUsername ); } } @@ -1541,9 +1542,9 @@ void RocketChatServerData::uploadFile( const QString &pChannelId, const QString }; connect( uploader, &FileUploader::ufsCreated, this, [ = ]( const QString & fileId ) { QJsonObject data; - data["fileId"] = fileId; - data["filePath"] = Utils::getPathPrefix() + pFilePath; - data["filename"] = uri.fileName(); + data[QStringLiteral( "fileId" )] = fileId; + data[QStringLiteral( "filePath" )] = Utils::getPathPrefix() + pFilePath; + data[QStringLiteral( "filename" )] = uri.fileName(); mFileUploads[fileId] = uploader; QJsonDocument doc( data ); emit fileuploadStarted( doc.toJson() ); @@ -1551,8 +1552,8 @@ void RocketChatServerData::uploadFile( const QString &pChannelId, const QString connect( uploader, &FileUploader::progressChanged, this, [ = ]( double progress ) { qDebug() << "progress changed"; QJsonObject data; - data["fileId"] = uploader->getFileId(); - data["progress"] = progress; + data[QStringLiteral( "fileId" )] = uploader->getFileId(); + data[QStringLiteral( "progress" )] = progress; QJsonDocument doc( data ); emit fileUploadProgressChanged( doc.toJson() ); } ); @@ -1584,7 +1585,7 @@ void RocketChatServerData::getUserSuggestions( const QString &pTerm, const QStri QJsonObject firstParam; QJsonDocument jsonExceptions = QJsonDocument::fromJson( pExeptions.toUtf8() ); - QStringList users = pExeptions.split( "," ); + QStringList users = pExeptions.split( ',' ); QJsonArray exceptionEntries; for ( const auto &entry : users ) { @@ -1592,16 +1593,16 @@ void RocketChatServerData::getUserSuggestions( const QString &pTerm, const QStri } //exceptionEntries.append( mUsername ); - firstParam["exceptions"] = exceptionEntries; - firstParam["term"] = pTerm; + firstParam[QStringLiteral( "exceptions" )] = exceptionEntries; + firstParam[QStringLiteral( "term" )] = pTerm; params.append( firstParam ); - QSharedPointer<DDPSubscriptionRequest> subSuggestions( new DDPSubscriptionRequest( "userAutocomplete", params ) ); + QSharedPointer<DDPSubscriptionRequest> subSuggestions( new DDPSubscriptionRequest( QStringLiteral( "userAutocomplete" ), params ) ); std::function<void ( QJsonObject, MeteorDDP * )> success = [ = ]( QJsonObject pResponse, MeteorDDP * pDdp ) { if ( pDdp ) { - if ( pResponse.contains( "msg" ) ) { - if ( pResponse["msg"] == "ready" ) { + if ( pResponse.contains( QStringLiteral( "msg" ) ) ) { + if ( pResponse[QStringLiteral( "msg" )] == QStringLiteral( "ready" ) ) { emit suggestionsReady( mAutocompleteRecords ); mAutocompleteRecords.clear(); QSharedPointer<DDPUnsubscriptionRequest> unSubSuggestions( new DDPUnsubscriptionRequest( subSuggestions->getFrame() ) ); @@ -1645,12 +1646,12 @@ void RocketChatServerData::getServerInfo() Q_UNUSED( pReply ); qDebug() << data; - if ( data.contains( "info" ) ) { - QJsonObject info = data["info"].toObject(); + if ( data.contains( QStringLiteral( "info" ) ) ) { + QJsonObject info = data[QStringLiteral( "info" )].toObject(); - if ( info.contains( "version" ) ) { - QString version = info["version"].toString(); - QStringList verParts = version.split( "." ); + if ( info.contains( QStringLiteral( "version" ) ) ) { + QString version = info[QStringLiteral( "version" )].toString(); + QStringList verParts = version.split( '.' ); std::get<0>( RocketChatServerConfig::serverVersion ) = verParts[0].toInt(); std::get<1>( RocketChatServerConfig::serverVersion ) = verParts[1].toInt(); std::get<2>( RocketChatServerConfig::serverVersion ) = verParts[2].toInt(); @@ -1661,6 +1662,11 @@ void RocketChatServerData::getServerInfo() mRestApi->sendRequest( serverInfoRequest ); } +void RocketChatServerData::leaveChannel( const QString &pId ) +{ + mChannelService->leaveChannel( pId ); +} + QList<QSharedPointer<RocketChatUser> > RocketChatServerData::getUserOfChannel( const QString &pChannelId ) { QList<QSharedPointer<RocketChatUser>> users; diff --git a/rocketchatserver.h b/rocketchatserver.h index c2bec5c4983c5591887d5471688ba67a217707c9..9f8d72d577cdc542b545472fe115737c6c09d991 100755 --- a/rocketchatserver.h +++ b/rocketchatserver.h @@ -130,7 +130,7 @@ class RocketChatServerData : public QObject void createChannel( const QString &pChannelName, const QStringList &pUsers, bool pReadonly ); void createPrivateGroup( const QString &pChannelName, const QStringList &pUsers, bool pReadonly ); void addUsersToChannel( const QString &pChannelName, const QStringList &pUsers ); - void sendMessage( const QString &pChannelId, const QString &pMessage ); + void sendMessage( const QString &pMessage, const QString &pChannelId ); void uploadFile( const QString &pChannelId, const QString &pFile ); void cancelUpload( const QString &pFileId ); @@ -200,6 +200,8 @@ class RocketChatServerData : public QObject void unBlockUser( const QString &pChannelId ); + void leaveChannel( const QString &pId ); + public: QString getServerId() const; @@ -209,7 +211,7 @@ class RocketChatServerData : public QObject QList<QSharedPointer<RocketChatUser>> getUserOfChannel( const QString &pChannelId ); RestApi *getRestApi() const; ChannelRepository *getChannels() const; - RocketChatChannelService *channelService; + RocketChatChannelService *mChannelService; void handleChannelMessage( const QJsonObject &pMessage ); uint diffToLastDDPPing(); QVariantList getEmojisByCategory() const; diff --git a/services/emojiservice.cpp b/services/emojiservice.cpp index 33e2682719f21268b8d059c6c6cda70d2605e5ac..280b5ee254f982e86ae77fc7c667987633b7501f 100755 --- a/services/emojiservice.cpp +++ b/services/emojiservice.cpp @@ -45,12 +45,12 @@ void EmojiService::loadCustomEmojis( std::function<void ( QList<QSharedPointer<E QJsonArray params; std::function<void ( QJsonObject, MeteorDDP * )> success = [ = ]( QJsonObject pResponse, MeteorDDP * pDdp ) { Q_UNUSED( pDdp ); - QJsonArray result = pResponse["result"].toArray(); + QJsonArray result = pResponse[QStringLiteral( "result" )].toArray(); EmojiData *data = new EmojiData( result ); data->success = pSuccess; handleCustomEmojisReceived( data ); }; - QSharedPointer<DDPMethodRequest> request( new DDPMethodRequest( "listEmojiCustom", params, success ) ); + QSharedPointer<DDPMethodRequest> request( new DDPMethodRequest( QStringLiteral( "listEmojiCustom" ), params, success ) ); server->sendDdprequest( request ); } /** @@ -75,7 +75,7 @@ QList<QSharedPointer<Emoji>> EmojiService::loadEmojisFromDb() void EmojiService::persistEmoji( QSharedPointer<Emoji> pEmoji ) { - storage->addCustomEmoji( pEmoji->getIdentifier(), pEmoji->getFilePath(), pEmoji->getHtml(), "custom", "dontcare" ); + storage->addCustomEmoji( pEmoji->getIdentifier(), pEmoji->getFilePath(), pEmoji->getHtml(), QStringLiteral( "custom" ), QStringLiteral( "dontcare" ) ); } void EmojiService::handleCustomEmojisReceived( EmojiData *data ) @@ -90,7 +90,7 @@ void EmojiService::handleCustomEmojisReceived( EmojiData *data ) if ( !parsedEmoji.isNull() ) { mParsedCustomEmojisTemp.append( parsedEmoji ); qDebug() << "emoji parsed: " << parsedEmoji->getIdentifier(); - QString url = "/emoji-custom/" + parsedEmoji->getName() + "." + parsedEmoji->getExtension(); + QString url = QStringLiteral( "/emoji-custom/" ) + parsedEmoji->getName() + '.' + parsedEmoji->getExtension(); std::function<void ( QSharedPointer<TempFile>, bool )> then = [ = ]( QSharedPointer<TempFile> file, bool ) { if ( Q_UNLIKELY( file.isNull() ) ) { qWarning() << "file is null" << parsedEmoji->getIdentifier(); @@ -98,16 +98,16 @@ void EmojiService::handleCustomEmojisReceived( EmojiData *data ) } QString path = Utils::getPathPrefix() + file->getFilePath(); - parsedEmoji->setCategory( "custom" ); + parsedEmoji->setCategory( QStringLiteral( "custom" ) ); parsedEmoji->setFilePath( path ); - parsedEmoji->setHtml( "<img height='20' width='20' src='" + path + "' />" ); + parsedEmoji->setHtml( QStringLiteral( "<img height='20' width='20' src='" ) + path + QStringLiteral( "' />" ) ); data->emojisProcessed++; if ( data->emojisProcessed == data->emojiCounter ) { data->success( mParsedCustomEmojisTemp ); } }; - QSharedPointer<FileRequest> fileRequest( new FileRequest( url, "emoji", then, true ) ); + QSharedPointer<FileRequest> fileRequest( new FileRequest( url, QStringLiteral( "emoji" ), then, true ) ); mFileService->getFileRessource( fileRequest ); } } @@ -129,13 +129,13 @@ void EmojiService::handleCustomEmojisReceived( EmojiData *data ) */ QSharedPointer<Emoji> EmojiService::parseEmoji( QHash<QString, QString> pEmojiData ) { - QString name = pEmojiData["id"]; - QString extension = pEmojiData["extension"]; - QString html = pEmojiData["html"]; - QString catgeory = pEmojiData["category"]; - QString filePath = pEmojiData["file"]; - QString unicode = pEmojiData["unicode"]; - int order = pEmojiData["sort_order"].toInt(); + QString name = pEmojiData[QStringLiteral( "id" )]; + QString extension = pEmojiData[QStringLiteral( "extension" )]; + QString html = pEmojiData[QStringLiteral( "html" )]; + QString catgeory = pEmojiData[QStringLiteral( "category" )]; + QString filePath = pEmojiData[QStringLiteral( "file" )]; + QString unicode = pEmojiData[QStringLiteral( "unicode" )]; + int order = pEmojiData[QStringLiteral( "sort_order" )].toInt(); QSharedPointer<Emoji> emoji( new Emoji( name, catgeory, filePath, html, unicode, order ) ); return emoji; @@ -143,9 +143,9 @@ QSharedPointer<Emoji> EmojiService::parseEmoji( QHash<QString, QString> pEmojiDa QSharedPointer<Emoji> EmojiService::parseEmoji( QJsonObject pEmojiData ) { - QString name = pEmojiData["name"].toString(); - QString extension = pEmojiData["extension"].toString(); - QString category = pEmojiData["category"].toString(); + QString name = pEmojiData[QStringLiteral( "name" )].toString(); + QString extension = pEmojiData[QStringLiteral( "extension" )].toString(); + QString category = pEmojiData[QStringLiteral( "category" )].toString(); QSharedPointer<Emoji> emoji( new Emoji( name, extension, category ) ); return emoji; diff --git a/services/fileservice.cpp b/services/fileservice.cpp index 4d3817dae9715fad1f84ca9d7480caec575ee353..06f9defe974e54ece2cc626f8bb49c6fea0c6ed7 100755 --- a/services/fileservice.cpp +++ b/services/fileservice.cpp @@ -131,7 +131,7 @@ void FileService::getFileFromServer( QSharedPointer< FileRequest > pRequest ) QString location = determineLocation( pReply->url(), mimetype ); QUrl locationUrl( location ); QString dirPath = locationUrl.adjusted( QUrl::RemoveFilename ).toString(); - QStringList parts = location.split( "/" ); + QStringList parts = location.split( '/' ); QDir dir( dirPath ); @@ -139,7 +139,7 @@ void FileService::getFileFromServer( QSharedPointer< FileRequest > pRequest ) QString tempPath = parts.first(); for ( int i = 1; i < parts.length() - 1; i++ ) { - tempPath.append( "/" + parts[i] ); + tempPath.append( '/' + parts[i] ); QDir temp( tempPath ); if ( !temp.exists() ) { @@ -227,11 +227,11 @@ QString FileService::determineLocation( QUrl pUrl, QMimeType pType ) { QString mimeTypeName = pType.name(); QString urlString = pUrl.toString(); - bool image = mimeTypeName.contains( "image" ); - bool video = mimeTypeName.contains( "video" ); - bool audio = mimeTypeName.contains( "audio" ); + bool image = mimeTypeName.contains( QStringLiteral( "image" ) ); + bool video = mimeTypeName.contains( QStringLiteral( "video" ) ); + bool audio = mimeTypeName.contains( QStringLiteral( "audio" ) ); int hits = image + video + audio; - QString urlPath = "/rocketChat" + pUrl.path(); + QString urlPath = QStringLiteral( "/rocketChat" ) + pUrl.path(); QString filePath; if ( hits > 1 ) { diff --git a/services/messageservice.cpp b/services/messageservice.cpp index 624b9bf5f8ea3759ff386422625dbc18ec035875..5d09bb9e952ead6b971c91e2b90810077a9db61a 100644 --- a/services/messageservice.cpp +++ b/services/messageservice.cpp @@ -71,9 +71,9 @@ void MessageService::sendMessage( QSharedPointer<RocketChatMessage> pMessage ) { if ( !pMessage.isNull() ) { QJsonObject params; - params["rid"] = pMessage->getRoomId(); - params["msg"] = pMessage->getMessageString(); - QSharedPointer<DDPRequest> sendMessageRequest( new DDPMethodRequest( "sendMessage", {params} ) ); + params[QStringLiteral( "rid" )] = pMessage->getRoomId(); + params[QStringLiteral( "msg" )] = pMessage->getMessageString(); + QSharedPointer<DDPRequest> sendMessageRequest( new DDPMethodRequest( QStringLiteral( "sendMessage" ), {params} ) ); mServer->sendDdprequest( sendMessageRequest, true ); } } @@ -107,19 +107,19 @@ QSharedPointer<RocketChatMessage> MessageService::parseMessage( const QJsonObjec QString userId = mServer->getUserId(); qint16 emojiHash = mServer->getCustomEmojisHash(); - if ( Q_LIKELY( pMessageData.contains( "msg" ) ) ) { + if ( Q_LIKELY( pMessageData.contains( QStringLiteral( "msg" ) ) ) ) { //parse message String - QString msgString = pMessageData["msg"].toString(); + QString msgString = pMessageData[QStringLiteral( "msg" )].toString(); qint16 emojiHashMsg = 0; - if ( pMessageData.contains( "emojiHash" ) ) { - emojiHashMsg = pMessageData["emojiHash"].toInt(); + if ( pMessageData.contains( QStringLiteral( "emojiHash" ) ) ) { + emojiHashMsg = pMessageData[QStringLiteral( "emojiHash" )].toInt(); } if ( !emojiHashMsg || !emojiHash || emojiHash != emojiHashMsg ) { msgString = Utils::emojiFy( msgString, mEmojiRepo ); emojiHashMsg = emojiHash; - pMessageData["emojiHash"] = emojiHashMsg; + pMessageData[QStringLiteral( "emojiHash" )] = emojiHashMsg; } msgString = Utils::removeUtf8Emojis( msgString ); @@ -128,7 +128,7 @@ QSharedPointer<RocketChatMessage> MessageService::parseMessage( const QJsonObjec msgString = Utils::removeUtf8Emojis( msgString ); msgString = Utils::linkiFy( msgString ); - msgString = msgString.replace( "\n", "<br>" ); + msgString = msgString.replace( QStringLiteral( "\n" ), QStringLiteral( "<br>" ) ); } if ( mEmojiRepo != nullptr ) { @@ -145,17 +145,17 @@ QSharedPointer<RocketChatMessage> MessageService::parseMessage( const QJsonObjec QJsonObject userObject = pMessageData["u"].toObject(); - if ( Q_LIKELY( userObject.contains( "username" ) ) ) { - author = userObject["username"].toString(); + if ( Q_LIKELY( userObject.contains( QStringLiteral( "username" ) ) ) ) { + author = userObject[QStringLiteral( "username" )].toString(); } // if alias given, us it instead of the username, required for bridges - if ( Q_LIKELY( pMessageData.contains( "alias" ) ) ) { - author = pMessageData["alias"].toString(); + if ( Q_LIKELY( pMessageData.contains( QStringLiteral( "alias" ) ) ) ) { + author = pMessageData[QStringLiteral( "alias" )].toString(); } if ( Q_LIKELY( userObject.contains( "_id" ) ) ) { - authorId = userObject["_id"].toString(); + authorId = userObject[QStringLiteral( "_id" )].toString(); } bool ownMessage = false; @@ -164,18 +164,18 @@ QSharedPointer<RocketChatMessage> MessageService::parseMessage( const QJsonObjec ownMessage = true; } - QJsonObject timestampObject = pMessageData["ts"].toObject(); + QJsonObject timestampObject = pMessageData[QStringLiteral( "ts" )].toObject(); qint64 timestamp = 0; - if ( Q_LIKELY( timestampObject.contains( "$date" ) ) ) { - timestamp = timestampObject["$date"].toDouble(); + if ( Q_LIKELY( timestampObject.contains( QStringLiteral( "$date" ) ) ) ) { + timestamp = timestampObject[QStringLiteral( "$date" )].toDouble(); } QDateTime date = QDateTime::fromMSecsSinceEpoch( timestamp ); - QString formattedDate = date.toString( "dd.MM.yyyy" ); - QString formattedTime = date.toString( "hh:mm" ); + QString formattedDate = date.toString( QStringLiteral( "dd.MM.yyyy" ) ); + QString formattedTime = date.toString( QStringLiteral( "hh:mm" ) ); auto attachments = processAttachments( pMessageData ); message = ChatMessage( new RocketChatMessage( pMessageData ) ); message->setAttachments( attachments ); @@ -221,9 +221,9 @@ void MessageService::loadHistoryFromServer( QSharedPointer<LoadHistoryRequestCon if ( !currentChannelRequest.isNull() ) { QString roomId = currentChannelRequest->getChannelIds().first(); QJsonObject startObj ; - startObj["$date"] = currentChannelRequest->getStart(); + startObj[QStringLiteral( "$date" )] = currentChannelRequest->getStart(); QJsonObject endObj ; - endObj["$date"] = currentChannelRequest->getEnd(); + endObj[QStringLiteral( "$date" )] = currentChannelRequest->getEnd(); QJsonArray params; int limit = currentChannelRequest->getLimit(); @@ -239,15 +239,15 @@ void MessageService::loadHistoryFromServer( QSharedPointer<LoadHistoryRequestCon params = {roomId, endObj, limit, startObj}; } - QSharedPointer<DDPMethodRequest> request( new DDPMethodRequest( "loadHistory", params ) ); + QSharedPointer<DDPMethodRequest> request( new DDPMethodRequest( QStringLiteral( "loadHistory" ), params ) ); std::function<void ( QJsonObject, MeteorDDP * )> ddpSuccess = [ = ]( QJsonObject pResponse, MeteorDDP * pDdp ) { Q_UNUSED( pDdp ); - if ( Q_LIKELY( pResponse.contains( "result" ) ) ) { - QJsonObject result = pResponse["result"].toObject(); + if ( Q_LIKELY( pResponse.contains( QStringLiteral( "result" ) ) ) ) { + QJsonObject result = pResponse[QStringLiteral( "result" )].toObject(); - if ( Q_LIKELY( result.contains( "messages" ) ) ) { - QJsonArray messages = result["messages"].toArray(); + if ( Q_LIKELY( result.contains( QStringLiteral( "messages" ) ) ) ) { + QJsonArray messages = result[QStringLiteral( "messages" )].toArray(); for ( auto currentMessage : messages ) { RocketChatMessage message( currentMessage.toObject() ); @@ -406,11 +406,11 @@ QList<QSharedPointer<RocketChatAttachment>> MessageService::processAttachments( QList<QSharedPointer<RocketChatAttachment> > attachmentsList; - if ( Q_LIKELY( pMessageObj.contains( "file" ) ) ) { - QJsonObject fileObj = pMessageObj["file"].toObject(); + if ( Q_LIKELY( pMessageObj.contains( QStringLiteral( "file" ) ) ) ) { + QJsonObject fileObj = pMessageObj[QStringLiteral( "file" )].toObject(); - if ( Q_LIKELY( fileObj.contains( "_id" ) ) ) { - QJsonArray attachments = pMessageObj["attachments"].toArray(); + if ( Q_LIKELY( fileObj.contains( QStringLiteral( "_id" ) ) ) ) { + QJsonArray attachments = pMessageObj[QStringLiteral( "attachments" )].toArray(); if ( Q_LIKELY( attachments.size() ) ) { QString type; @@ -420,31 +420,31 @@ QList<QSharedPointer<RocketChatAttachment>> MessageService::processAttachments( int height = 100; QJsonObject attachment = attachments[0].toObject(); - if ( Q_LIKELY( attachment.contains( "image_url" ) ) ) { - type = "image"; - url = attachment["image_url"].toString(); + if ( Q_LIKELY( attachment.contains( QStringLiteral( "image_url" ) ) ) ) { + type = QStringLiteral( "image" ); + url = attachment[QStringLiteral( "image_url" )].toString(); - if ( attachment.contains( "image_dimensions" ) ) { - QJsonObject imageDimensions = attachment["image_dimensions"].toObject(); + if ( attachment.contains( QStringLiteral( "image_dimensions" ) ) ) { + QJsonObject imageDimensions = attachment[QStringLiteral( "image_dimensions" )].toObject(); - if ( imageDimensions.contains( "height" ) && imageDimensions.contains( "width" ) ) { - height = imageDimensions["height"].toDouble(); - width = imageDimensions["width"].toDouble(); + if ( imageDimensions.contains( QStringLiteral( "height" ) ) && imageDimensions.contains( QStringLiteral( "width" ) ) ) { + height = imageDimensions[QStringLiteral( "height" )].toDouble(); + width = imageDimensions[QStringLiteral( "width" )].toDouble(); } } - } else if ( attachment.contains( "video_url" ) ) { - type = "video"; - url = attachment["video_url"].toString(); - } else if ( attachment.contains( "audio_url" ) ) { - type = "audio"; - url = attachment["audio_url"].toString(); - } else if ( attachment.contains( "title_link" ) ) { - type = "file"; - url = attachment["title_link"].toString(); + } else if ( attachment.contains( QStringLiteral( "video_url" ) ) ) { + type = QStringLiteral( "video" ); + url = attachment[QStringLiteral( "video_url" )].toString(); + } else if ( attachment.contains( QStringLiteral( "audio_url" ) ) ) { + type = QStringLiteral( "audio" ); + url = attachment[QStringLiteral( "audio_url" )].toString(); + } else if ( attachment.contains( QStringLiteral( "title_link" ) ) ) { + type = QStringLiteral( "file" ); + url = attachment[QStringLiteral( "title_link" )].toString(); } - if ( Q_LIKELY( attachment.contains( "title" ) ) ) { - title = attachment["title"].toString(); + if ( Q_LIKELY( attachment.contains( QStringLiteral( "title" ) ) ) ) { + title = attachment[QStringLiteral( "title" )].toString(); } QSharedPointer<RocketChatAttachment> attachmentObject( new RocketChatAttachment( url, type, title ) ); diff --git a/services/rocketchatchannelservice.cpp b/services/rocketchatchannelservice.cpp index f5f7c9528c0465a51a8ac5d8d29a50716e496aa5..532577773edda5030fed6227d67ce8d3c90bfc98 100755 --- a/services/rocketchatchannelservice.cpp +++ b/services/rocketchatchannelservice.cpp @@ -281,6 +281,16 @@ RocketChatChannelService::~RocketChatChannelService() } +MeteorDDP *RocketChatChannelService::getDdp() const +{ + return mDdp; +} + +void RocketChatChannelService::setDdp( MeteorDDP *ddp ) +{ + mDdp = ddp; +} + ChannelRepository *RocketChatChannelService::getChannels() const { return mChannels; @@ -290,17 +300,37 @@ void RocketChatChannelService::setChannels( ChannelRepository *pChannels ) { mChannels = pChannels; } + +void RocketChatChannelService::leaveChannel( const QString &pId ) +{ + //TODO: handle response, as soon as RC is fixed to do so + if ( mChannels->contains( pId ) ) { + QSharedPointer<RocketChatLeaveRoomRequest> request( new RocketChatLeaveRoomRequest( pId ) ); + auto ddp = getDdp(); + ddp->sendRequest( request ); + deleteChannel( pId ); + mStorage->deleteChannel( pId ); + } +} + +void RocketChatChannelService::deleteChannel( const QString &pId ) +{ + if ( mChannels->contains( pId ) ) { + mChannels->get( pId )->setDeleted( true ); + } +} + void RocketChatChannelService::openPrivateChannelWith( QString pUsername ) { QJsonArray params = {pUsername}; - QSharedPointer<DDPMethodRequest> request( new DDPMethodRequest( "createDirectMessage", params ) ); + QSharedPointer<DDPMethodRequest> request( new DDPMethodRequest( QStringLiteral( "createDirectMessage" ), params ) ); std::function<void ( QJsonObject, MeteorDDP * )> success = [ = ]( QJsonObject pResponse, MeteorDDP * pDdp ) { - if ( Q_LIKELY( pResponse.contains( "result" ) ) ) { - QJsonObject result = pResponse["result"].toObject(); + if ( Q_LIKELY( pResponse.contains( QStringLiteral( "result" ) ) ) ) { + QJsonObject result = pResponse[QStringLiteral( "result" )].toObject(); - if ( Q_LIKELY( result.contains( "rid" ) ) ) { - QString rid = result["rid"].toString(); - QSharedPointer<DDPSubscriptionRequest> subRoom( new DDPSubscriptionRequest( "room", {"d" + pUsername} ) ); + if ( Q_LIKELY( result.contains( QStringLiteral( "rid" ) ) ) ) { + QString rid = result[QStringLiteral( "rid" )].toString(); + QSharedPointer<DDPSubscriptionRequest> subRoom( new DDPSubscriptionRequest( QStringLiteral( "room" ), {"d" + pUsername} ) ); QSharedPointer<RocketChatSubscribeChannelRequest> subMessages( new RocketChatSubscribeChannelRequest( rid ) ); QSharedPointer<RocketChatChannel> channel = createChannelObject( rid, pUsername, "d" ); diff --git a/services/rocketchatchannelservice.h b/services/rocketchatchannelservice.h index c09dd2f7f7136d084c1519fe984ff8093a8746f6..3595aa30703236deb8eddfabf88f21242be054c1 100755 --- a/services/rocketchatchannelservice.h +++ b/services/rocketchatchannelservice.h @@ -35,6 +35,7 @@ #include "restRequests/restrequest.h" #include "rocketchatserver.h" #include "ddpRequests/rocketchatgetroomsrequest.h" +#include "ddpRequests/rocketchatleaveroomrequest.h" #include "services/messageservice.h" #include "repos/channelrepository.h" @@ -55,8 +56,8 @@ class RocketChatChannelService : public QObject RestApi *getRestApi() const; void setRestApi( RestApi *pValue ); - MeteorDDP *getDdpApi() const; - void setDdpApi( MeteorDDP *pValue ); + MeteorDDP *getDdp() const; + void setDdp( MeteorDDP *ddp ); QSharedPointer<RocketChatChannel> createChannelObject( QString pRoomId, QString pName, QString pType ); void openPrivateChannelWith( QString pUsername ); @@ -72,13 +73,20 @@ class RocketChatChannelService : public QObject ChannelRepository *getChannels() const; void setChannels( ChannelRepository *pChannels ); + void leaveChannel( const QString &pId ); + + void deleteChannel( const QString &pId ); + ~RocketChatChannelService(); + + protected: PersistanceLayer *mStorage = nullptr; RocketChatServerData *mServer = nullptr; ChannelRepository *mChannels = nullptr; + MeteorDDP *mDdp; QVector<QSharedPointer<RocketChatChannel>> processChannelData( QJsonArray pChannelArray, bool pJoined ); @@ -87,7 +95,6 @@ class RocketChatChannelService : public QObject void channelsLoaded( channelVector pChannelList, bool pJoined ); void usersLoaded( QString roomId, userVector pUserList ); void directChannelReady( QString roomId ); - }; #endif // ROCKETCHATCHANNELFACTORY_H diff --git a/utils.cpp b/utils.cpp index bbaae7b5b19bdff903b400670be2ebf893ac6721..95ee297f9a1dff8296152a873a4c7b4d17b2586c 100755 --- a/utils.cpp +++ b/utils.cpp @@ -38,7 +38,7 @@ */ QString Utils::removeUtf8Emojis( const QString &pText ) { - static const QRegularExpression nonAlphaNumeric( "[\\p{L}\\p{M}\\p{N}\\p{Z}\\p{Sm}\\p{Sc}\\p{Sk}\\p{P}\\p{Cc}\\p{Cf}*]", QRegularExpression::UseUnicodePropertiesOption ); + static const QRegularExpression nonAlphaNumeric{ QStringLiteral( "[\\p{L}\\p{M}\\p{N}\\p{Z}\\p{Sm}\\p{Sc}\\p{Sk}\\p{P}\\p{Cc}\\p{Cf}*]" ), QRegularExpression::UseUnicodePropertiesOption }; QRegularExpressionMatchIterator iter = nonAlphaNumeric.globalMatch( pText ); QString retString; @@ -56,22 +56,22 @@ QString Utils::removeUtf8Emojis( const QString &pText ) QString Utils::linkiFy( const QString &pText ) { - static const QString scheme( "[a-z\\d.-]+://" ); - static const QString ipv4( "(?:(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])" ); - static const QString hostname( "(?:(?:[^\\s!@#$%^&*()_=+[\\]{}\\\\|;:'\",.<>/?]+)\\.)+" ); - static const QString tld( "(?:ac|ad|aero|ae|af|ag|ai|al|am|an|ao|aq|arpa|ar|asia|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|biz|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|cat|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|coop|com|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|info|int|in|io|iq|ir|is|it|je|jm|jobs|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mobi|mo|mp|mq|mr|ms|mt|museum|mu|mv|mw|mx|my|mz|name|na|nc|net|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|travel|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|xn--0zwm56d|xn--11b5bs3a9aj6g|xn--80akhbyknj4f|xn--9t4b11yi5a|xn--deba0ad|xn--g6w251d|xn--hgbk6aj7f53bba|xn--hlcj6aya9esc7a|xn--jxalpdlp|xn--kgbechtv|xn--zckzah|ye|yt|yu|za|zm|zw)" ); - static const QString host_or_ip( "(?:" + hostname + tld + "|" + ipv4 + ")" ); - static const QString path( "(?:[;/][^#?<>\\s]*)?" ); - static const QString query_frag( "(?:\\?[^#<>\\s]*)?(?:#[^<>\\s]*)?" ); - static const QString uri1( "\\b" + scheme + "[^<>\\s]+" ); - static const QString uri2( "\\b" + host_or_ip + path + query_frag + "(?!\\w)" ); - static const QString skip = "(?!file)"; - static const QString mailto( "mailto" ); - static const QString email( "(?:" + mailto + ")?[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@" + host_or_ip + query_frag + "(?!\\w)" ); - static const QRegularExpression uri_re( skip + "(?:" + uri1 + "|" + uri2 + "|" + email + ")", QRegularExpression::CaseInsensitiveOption ); - static const QRegularExpression scheme_re( "^" + scheme, QRegularExpression::CaseInsensitiveOption ); - static const QRegularExpression punctRegexp( "(?:[!?.,:;'\"]|(?:&|&)(?:lt|gt|quot|apos|raquo|laquo|rsaquo|lsaquo);)$" ); - static const QRegularExpression illegalEnding( "([:/])w+$" ); + static const QString scheme{ QStringLiteral( "[a-z\\d.-]+://" ) }; + static const QString ipv4{ QStringLiteral( "(?:(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])" ) }; + static const QString hostname{ QStringLiteral( "(?:(?:[^\\s!@#$%^&*()_=+[\\]{}\\\\|;:'\",.<>/?]+)\\.)+" ) }; + static const QString tld{ QStringLiteral( "(?:ac|ad|aero|ae|af|ag|ai|al|am|an|ao|aq|arpa|ar|asia|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|biz|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|cat|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|coop|com|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|info|int|in|io|iq|ir|is|it|je|jm|jobs|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mobi|mo|mp|mq|mr|ms|mt|museum|mu|mv|mw|mx|my|mz|name|na|nc|net|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|travel|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|xn--0zwm56d|xn--11b5bs3a9aj6g|xn--80akhbyknj4f|xn--9t4b11yi5a|xn--deba0ad|xn--g6w251d|xn--hgbk6aj7f53bba|xn--hlcj6aya9esc7a|xn--jxalpdlp|xn--kgbechtv|xn--zckzah|ye|yt|yu|za|zm|zw)" ) }; + static const QString host_or_ip{ QStringLiteral( "(?:" ) + hostname + tld + '|' + ipv4 + ')' }; + static const QString path{ QStringLiteral( "(?:[;/][^#?<>\\s]*)?" ) }; + static const QString query_frag{ QStringLiteral( "(?:\\?[^#<>\\s]*)?(?:#[^<>\\s]*)?" ) }; + static const QString uri1{ QStringLiteral( "\\b" ) + scheme + QStringLiteral( "[^<>\\s]+" ) }; + static const QString uri2{ QStringLiteral( "\\b" ) + host_or_ip + path + query_frag + QStringLiteral( "(?!\\w)" ) }; + static const QString skip {QStringLiteral( "(?!file)" ) }; + static const QString mailto{ QStringLiteral( "mailto" ) }; + static const QString email{ QStringLiteral( "(?:" ) + mailto + QStringLiteral( ")?[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@" ) + host_or_ip + query_frag + QStringLiteral( "(?!\\w)" ) }; + static const QRegularExpression uri_re{ skip + QStringLiteral( "(?:" ) + uri1 + '|' + uri2 + '|' + email + ')', QRegularExpression::CaseInsensitiveOption }; + static const QRegularExpression scheme_re{ '^' + scheme, QRegularExpression::CaseInsensitiveOption}; + static const QRegularExpression punctRegexp{ QStringLiteral( "(?:[!?.,:;'\"]|(?:&|&)(?:lt|gt|quot|apos|raquo|laquo|rsaquo|lsaquo);)$" ) }; + static const QRegularExpression illegalEnding{ QStringLiteral( "([:/])w+$" ) }; static QHash<QString, QString> quotes; quotes["'"] = "`"; quotes[">"] = "<"; @@ -113,8 +113,8 @@ QString Utils::linkiFy( const QString &pText ) QString quote_begin = quotes[quote_end]; if ( quote_begin.length() ) { - QRegularExpression begin( "\\" + quote_begin + "(?!$)" ); - QRegularExpression end( "\\" + quote_end ); + QRegularExpression begin( QStringLiteral( "\\" ) + quote_begin + QStringLiteral( "(?!$)" ) ); + QRegularExpression end( QStringLiteral( "\\" ) + quote_end ); QRegularExpressionMatch matches_begin = begin.match( link ); QRegularExpressionMatch matches_end = end.match( link ); @@ -133,12 +133,12 @@ QString Utils::linkiFy( const QString &pText ) } else { href = mailto + href; } - } else if ( !href.indexOf( "irc." ) ) { - href = "irc://" + href; - } else if ( !href.indexOf( "ftp." ) ) { - href = "ftp://" + href; + } else if ( !href.indexOf( QStringLiteral( "irc." ) ) ) { + href = QStringLiteral( "irc://" ) + href; + } else if ( !href.indexOf( QStringLiteral( "ftp." ) ) ) { + href = QStringLiteral( "ftp://" ) + href; } else { - href = "http://" + href; + href = QStringLiteral( "http://" ) + href; } } @@ -149,7 +149,7 @@ QString Utils::linkiFy( const QString &pText ) idx_prev = idx_last; - parts.append( "<a href='" + href + "'>" + link + "</a>" ); + parts.append( QStringLiteral( "<a href='" ) + href + QStringLiteral( "'>" ) + link + QStringLiteral( "</a>" ) ); } parts.append( pText.right( pText.length() - idx_last ) ); @@ -170,11 +170,11 @@ double Utils::getMessageTimestamp( const QJsonObject &pMessage ) { double seconds = 0; - if ( Q_LIKELY( pMessage.contains( "ts" ) ) ) { - QJsonObject ts = pMessage["ts"].toObject(); + if ( Q_LIKELY( pMessage.contains( QStringLiteral( "ts" ) ) ) ) { + QJsonObject ts = pMessage[QStringLiteral( "ts" )].toObject(); - if ( Q_LIKELY( ts.contains( "$date" ) ) ) { - seconds = ts["$date"].toDouble(); + if ( Q_LIKELY( ts.contains( QStringLiteral( "$date" ) ) ) ) { + seconds = ts[QStringLiteral( "$date" )].toDouble(); } } @@ -182,9 +182,9 @@ double Utils::getMessageTimestamp( const QJsonObject &pMessage ) } bool Utils::messageHasTimestamp( const QJsonObject &pMessage ) { - if ( Q_LIKELY( pMessage.contains( "ts" ) ) ) { - QJsonObject ts = pMessage["ts"].toObject(); - return ts.contains( "$date" ); + if ( Q_LIKELY( pMessage.contains( QStringLiteral( "ts" ) ) ) ) { + QJsonObject ts = pMessage[QStringLiteral( "ts" )].toObject(); + return ts.contains( QStringLiteral( "$date" ) ); } return false; @@ -193,16 +193,16 @@ bool Utils::messageHasTimestamp( const QJsonObject &pMessage ) QString Utils::getPathPrefix() { #if defined(Q_OS_WINDOWS)||defined(Q_OS_WINRT) - return "file:///"; + return QStringLiteral( "file:///" ); #else - return "file://"; + return QStringLiteral( "file://" ); #endif } QString Utils::escapeUnicodeEmoji( const QString &pString ) { qDebug() << pString; - static const QRegularExpression reg( "(\\b[A-Fa-f0-9]{2,6}\\b)" ); + static const QRegularExpression reg{ QStringLiteral( "(\\b[A-Fa-f0-9]{2,6}\\b)" ) }; QRegularExpressionMatchIterator iter = reg.globalMatch( pString ); QString retString; @@ -272,7 +272,7 @@ bool Utils::compareMessageTimestamps( const QJsonObject &pMessage1, const QJsonO QString Utils::emojiFy( const QString &pMessage, EmojiRepo *pEmojiRepo ) { QString returnText = pMessage; - static const QRegularExpression reg( ":[a-zA-Z-_0-9ßöüäÖÜÄ]+:" ); + static const QRegularExpression reg{ QStringLiteral( ":[a-zA-Z-_0-9ßöüäÖÜÄ]+:" ) }; if ( pEmojiRepo != nullptr ) { QRegularExpressionMatchIterator iter = reg.globalMatch( pMessage ); @@ -347,7 +347,7 @@ qint16 Utils::hash( const QStringList &pStrings ) QString Utils::getRandomString( int pLength ) { - static const QString BASE64_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"; + static const QString BASE64_CHARS{ QStringLiteral( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_" )}; QString randString;