Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Unsolved Use QNetworkAccessManager to send post request between 5000-10000, from one QThread.

    General and Desktop
    1
    1
    352
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Taz742
      Taz742 last edited by

      Hi! I have a folder where i have a many databases. It is possible over time, add or remove this database from the folder. So I made QTimer.

      In my QThread constructor i read the information to whom to send a message from database.
      Now we have a list of people who send the message and in my QThread::run() i start send sms.

      Read a databases and start a threads:

          this->timer = new QTimer(this);
          this->timer->setInterval(15000);
          connect(this->timer, &QTimer::timeout, this, [=]() {
              qDebug() << "time outed";
              QString path = "C:\\Program Files\\Daxi\\SMSServer\\cgi\\SMSSenderAllBASE";
              //QString path = qApp->applicationDirPath() + "\\SMSSenderAllBASE";
              QDir recoredDir(path);
              QStringList allFiles = recoredDir.entryList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden  | QDir::AllDirs | QDir::Files, QDir::DirsFirst);//(QDir::Filter::Files,QDir::SortFlag::NoSort)
              for (int i = 0; i < allFiles.size(); i++) {
                  QString fullPath = path + "\\" + allFiles[i];
                  QString connectionName = allFiles[i];
                  connectionName = connectionName.remove(connectionName.size() - 4, 4);
                  {
                      QSqlDatabase db = QSqlDatabase::addDatabase("QIBASE", connectionName);
                      db.setDatabaseName(fullPath);
                      db.setHostName("localhost");
                      db.setPort(3050);
                      db.setUserName("SYSDBA");
                      db.setPassword("masterkey");
                  }
      
                  MyPhone *thread = new MyPhone(connectionName, this);
                  connect(thread, &MyPhone::finished, thread, &MyPhone::deleteLater);
                  thread->start();
              }
          });
          this->timer->start();
      

      My QThread Class:

      #ifndef MYPHONESENDSMS_H
      #define MYPHONESENDSMS_H
      
      #include "QObject"
      #include "QRunnable"
      #include "QDebug"
      #include "QThread"
      #include "QNetworkAccessManager"
      #include "QNetworkRequest"
      #include "QNetworkReply"
      #include "QEventLoop"
      #include "QJsonDocument"
      #include "QJsonValue"
      #include "QJsonObject"
      #include "QSqlDatabase"
      #include "QSqlQuery"
      #include "QSqlError"
      #include "QSqlDriver"
      #include "clsautosend.h"
      #include "QMessageBox"
      #include "testslotclass.h"
      #include "QSqlDatabase"
      #include "QSqlQuery"
      #include "QSqlError"
      
      class clsAutoSend;
      
      class MyPhone : public QThread
      {
          Q_OBJECT
      public:
          MyPhone(QString connectionName, QObject *parent = NULL) {
              this->db = QSqlDatabase::database(connectionName);
              this->setParent(parent);
      
              if (this->db.open()) {
                  qDebug() << "db open";
                  QString strQuery = "SELECT TEMPLATE_CONTACT_PROFILE.UID As TCPUID, TEMPLATE_CONTACT_PROFILE.ContactUID As CUID, TEMPLATE_CONTACT_PROFILE.TemplateUID As TUID, TEMPLATE_CONTACT_PROFILE.SendTime As SENDTIME, TEMPLATE_CONTACT_PROFILE.DAXIID As DAXIID, TEMPLATEHELPER.SendDay As SENDDAY, TEMPLATEHELPER.BaseDate As BASEDATE, TEMPLATES.Mesage As MESSAGE, TEMPLATES.TCHECKED As TMPLPAUSE, TEMPLATES.TEMPLATETYPE AS TYPE, CONTACTS.MOBILE AS MOBILE, TREE.PAUSE AS TREEPAUSE,CLIENTSINFO.M_USERNAME AS USERNAME, CLIENTSINFO.M_PASSWORD AS PASSWORD FROM TEMPLATE_CONTACT_PROFILE INNER JOIN Contacts ON TEMPLATE_CONTACT_PROFILE.ContactUID = Contacts.UID INNER JOIN Templates ON TEMPLATE_CONTACT_PROFILE.TemplateUID = Templates.UID INNER JOIN TemplateHelper On TEMPLATE_CONTACT_PROFILE.THUID = TemplateHelper.UID INNER JOIN Tree ON Templates.TreeUID = Tree.UID INNER JOIN CLIENTSINFO ON TEMPLATE_CONTACT_PROFILE.DAXIID = CLIENTSINFO.DAXIID WHERE SENDTIME <= :oHIGHTIME AND SENDTIME >= :oLOWTIME AND TREE.PAUSE = 1 AND TEMPLATES.TCHECKED = 1";
                  QDateTime currDate = QDateTime::currentDateTime();
                  QDateTime minuss = currDate;
                  minuss.setTime(QTime(currDate.time().hour(), currDate.time().minute() - 1, currDate.time().second()));
                  QSqlQuery query(this->db);
                  query.prepare(strQuery);
                  query.bindValue(":oHIGHTIME", currDate);
                  query.bindValue(":oLOWTIME", minuss);
                  query.setForwardOnly(true);
                  if (query.exec()) {
                      clsAutoSend now;
                      while (query.next()) {
                          now = clsAutoSend(query.value("TCPUID").toInt(),
                                             query.value("SENDTIME").toDateTime(),
                                             query.value("BASEDATE").toDateTime(),
                                             query.value("MESSAGE").toString(),
                                             query.value("MOBILE").toString(),
                                             query.value("TUID").toInt(),
                                             query.value("CUID").toInt(),
                                             query.value("TYPE").toInt(),
                                             query.value("SENDDAY").toInt(),
                                             query.value("USERNAME").toString(),
                                             query.value("PASSWORD").toString(),
                                             query.value("DAXIID").toInt()
                                             );
                          this->vctr.push_back(now);
                      }
                      query.clear();
                  } else {
                      qDebug() << "helper error: " << query.lastError() << db.databaseName() << query.lastQuery();
                  }
      
                  this->db.close();
              }
          }
      
          ~MyPhone() {
          }
      
      signals:
          void m_finished(bool status, QDateTime sendTime, clsAutoSend);
      
      public slots:
          void run() {
              qDebug() << "thread running: " << this->vctr.size();
              for (int i = 0; i < this->vctr.size(); i++) {
                  const clsAutoSend &clsAuto = this->vctr[i];
                  QNetworkRequest req;
                  req.setUrl(QUrl("https://url"));
                  req.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-www-form-urlencoded"));
      
                  QString MOBILE = clsAuto.Mobile;
      
                  if (MOBILE.size() > 9) {
                      MOBILE = MOBILE.remove(0, MOBILE.size() - 9);
                  }
      
                  QString API_USER = clsAuto.USERNAME;
                  QString API_KEY =  clsAuto.PASSWORD;
                  QString service = "sms";
                  QString action = "send";
                  QString reciever = "995" + MOBILE;
                  QString text = clsAuto.Message;
                  QString hash = QString(QCryptographicHash::hash(QString(service + action + reciever + text + API_USER + API_KEY).toUtf8(),
                                                                  QCryptographicHash::Sha1).toHex()).replace("=", "").toLower();
                  QByteArray  postData;
                  postData.append("service=" + service + "&");
                  postData.append("action=" + action + "&");
                  postData.append("receiver=" + reciever + "&");
                  postData.append("text=" + text + "&");
                  postData.append("API_USER=" + API_USER + "&");
                  postData.append("hash=" + hash);
      
                  QNetworkAccessManager manager;
                  QNetworkReply *reply = manager.post(req, postData);
                  QEventLoop loop;
                  QObject::connect(reply, &QNetworkReply::finished, this, [=](){
                      QDateTime sendTime = QDateTime::currentDateTime();
                      Q_UNUSED(sendTime);
                      int errorCode = 666;
                      QString errorStr = "";
                      if (reply->error()) {
                          errorStr = reply->errorString();
                      } else {
                          QJsonValue value = QJsonDocument::fromJson(reply->readAll()).object().value("code");
                          if (value.toString() == "-5")
                              errorStr = "ანგარიშზე არაა საკმარისი თანხა.", errorCode = -5;
                          else if (value.toString() == "401")
                              errorStr = "სახელი (API_USER) ან/და პაროლი (API_KEY) არასწრია.", errorCode = 401;
                          else if (value.toString() == "403")
                              errorStr = "აკრძალულია!", errorCode = 403;
                          else if (value.toString() == "-4")
                              errorStr = "ტექსტი ცარიელია.", errorCode = -4;
                          else if (value.toString() == "-3")
                              errorStr = "ნომერი არასწორია.", errorCode = -3;
                          else if (value.toString() == "1")
                              errorStr = "წარმატებით გაიგზავნა.", errorCode = 1;
                      }
      
                      this->history.push_back(qMakePair(errorCode == 1 ? 1 : 0, qMakePair(sendTime, clsAuto)));
      
                      ++this->counter;
      
                      if (this->counter == this->vctr.size()) {
                          qDebug() << "thread finished! all sms are sended :)";
                          //now start to insert history to db.
                          if (db.open()) {
                              db.driver()->beginTransaction();
      
                              bool ok = true;
                              for (int i = 0; i < this->history.size(); i++) {
                                  //add history
                              }
      
                              ok ? db.driver()->comitTransaction() : db.driver()->rollbackTransaction();
      
                              db.close();
                          }
                      }
                  });
                  QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
                  QObject::connect(reply, &QNetworkReply::finished, reply, &QNetworkReply::deleteLater);
                  loop.exec();
              }
          }
      
      private:
          QSqlDatabase db;
          QVector<clsAutoSend> vctr;
          QVector<QPair<bool, QPair<QDateTime, clsAutoSend> > > history;
          int counter = 0;
      };
      
      #endif // MYPHONESENDSMS_H
      
      

      To read the information from the database, send messages and write the history of the database and delete records that have already been sent, at a very long time!
      How can I send all message to QNetworkAccessManager without QEventLoop?

      Do not have any idea? How do I do this correctly?

      Do what you want.

      1 Reply Last reply Reply Quote 0
      • First post
        Last post