flightawarequery.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "flightawarequery.h"
  2. #include "flightawarejsonparser.h"
  3. #include <QNetworkReply>
  4. FlightAwareQuery::FlightAwareQuery(QObject *parent)
  5. : QObject{parent}
  6. {
  7. m_networkManager = new QNetworkAccessManager(this);
  8. }
  9. QList<FlightAwareFlightData> FlightAwareQuery::getFlightData(const QString &flightId, const QDate &date)
  10. {
  11. LOG << "Preparing query data";
  12. // prepare the query data
  13. const QDateTime startDateTime = QDateTime(date, QTime(0, 0));
  14. const QDateTime endDateTime = QDateTime(date, QTime(23, 59));
  15. const QString queryUrl = QUERY_BASE_URL + flightId + QString("?start=%1&end=%2").arg(startDateTime.toString(Qt::ISODate), endDateTime.toString(Qt::ISODate));
  16. // construct the network request
  17. const QByteArray apiKey = Settings::getFlightAwareApiKey();
  18. if (apiKey.isEmpty()) {
  19. LOG << "API key not found.";
  20. return {};
  21. }
  22. LOG << "Sending network request: " << queryUrl << "with API key: " << apiKey;
  23. QNetworkRequest request;
  24. request.setRawHeader("x-apikey", apiKey);
  25. request.setRawHeader("Accept", "application/json; charset=UTF-8");
  26. request.setUrl(queryUrl);
  27. // invoke the network manager to execute the request
  28. m_networkReply = m_networkManager->get(request);
  29. // QObject::connect(m_networkReply, &QNetworkReply::finished,
  30. // this, &FlightAwareQuery::replyFinished);
  31. // Wait for finishing the network request or a timeout
  32. LOG << "Setting timer and staring event loop";
  33. QTimer timer;
  34. timer.setSingleShot(true);
  35. QObject::connect(&timer, &QTimer::timeout, this, &FlightAwareQuery::timeOut);
  36. timer.start(5000); //5s
  37. QEventLoop loop;
  38. QObject::connect(m_networkReply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
  39. loop.exec();
  40. LOG << "Reading reply...";
  41. // check the reply
  42. if(m_networkReply->error() != QNetworkReply::NoError) {
  43. LOG << m_networkReply->error();
  44. LOG << m_networkReply->errorString();
  45. return {};
  46. }
  47. LOG << "Parsing reply...";
  48. // parse the reply and return the result
  49. return FlightAwareJsonParser::readFlights(m_networkReply->readAll());
  50. }
  51. // void FlightAwareQuery::replyFinished()
  52. // {
  53. // if(m_networkReply->error() != QNetworkReply::NoError) {
  54. // qDebug() << m_networkReply->error();
  55. // qDebug() << m_networkReply->errorString();
  56. // return;
  57. // }
  58. // // parse the reply
  59. // m_flightList.clear();
  60. // m_flightList = FlightAwareJsonParser::readFlights(m_networkReply->readAll());
  61. // emit readyToRead();
  62. // }
  63. void FlightAwareQuery::timeOut()
  64. {
  65. m_networkReply->abort(); // triggers replyFinished() with an error code
  66. }