| 1 | |
| 2 | |
| 3 | #include "Main/globals.hxx" |
| 4 | #include "config.h" |
| 5 | #include "simgear/misc/sg_path.hxx" |
| 6 | |
| 7 | #include "DownloadTerrasyncSharedData.hxx" |
| 8 | |
| 9 | // Qt |
| 10 | #include <QNetworkAccessManager> |
| 11 | |
| 12 | #include <GUI/QtDNSClient.hxx> |
| 13 | #include <Main/options.hxx> |
| 14 | |
| 15 | |
| 16 | #include <simgear/io/untar.hxx> |
| 17 | #include <simgear/misc/sg_dir.hxx> |
| 18 | |
| 19 | |
| 20 | using namespace std::chrono_literals; |
| 21 | |
| 22 | namespace { |
| 23 | |
| 24 | int calculateProgressPercentage(quint64 current, quint64 total) { |
| 25 | |
| 26 | constexpr int max_percent = 100; |
| 27 | |
| 28 | if (total == 0) { |
| 29 | return 0; |
| 30 | } |
| 31 | |
| 32 | // Compute percentage and clamp to avoid overflow or narrowing |
| 33 | const quint64 percent = std::min((current * max_percent) / total, static_cast<quint64>(max_percent)); |
| 34 | |
| 35 | return static_cast<int>(percent); |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | |
| 40 | DownloadTerrasyncSharedData::DownloadTerrasyncSharedData(QObject* pr, QNetworkAccessManager* nam) : |
| 41 | QThread(pr), |
| 42 | m_networkManager(nam), |
| 43 | m_dns(new QtDNSClient(this, "ws2")) |
| 44 | { |
| 45 | const SGPath terrasyncRoot = flightgear::Options::sharedInstance()->actualTerrasyncDir(); |
| 46 | if (!terrasyncRoot.exists()) { |
| 47 | simgear::Dir d(terrasyncRoot); |
| 48 | d.create(0755); |
| 49 | } |
| 50 | |
| 51 | m_items.emplace_back("../SharedModels.txz", terrasyncRoot / "Models", tr("shared scenery models")); |
| 52 | m_items.emplace_back("Airports_archive.tgz", terrasyncRoot / "Airports", tr("airports data")); |
| 53 | |
| 54 | m_updateTimer.setInterval(20); |
| 55 | |
| 56 | connect(m_dns, &QtDNSClient::finished, [this]() { |
| 57 | auto baseServer = m_dns->result(); |
| 58 | |
| 59 | m_serverUri = baseServer; |
| 60 | qInfo() << Q_FUNC_INFO << "will download shared data from" << baseServer; |
| 61 | startNextDownload(); |
| 62 | |
| 63 | }); |
| 64 | |
| 65 | connect(m_dns, &QtDNSClient::failed, [this](QString msg) { |
| 66 | // use us1mirror |
| 67 | qWarning() << "DNS query failed:" << msg; |
| 68 | m_serverUri = QStringLiteral("https://us1mirror.flightgear.org/terrasync/ws2/"); |
| 69 | startNextDownload(); |
| 70 | }); |
| 71 | |
| 72 | m_dns->makeDNSRequest(); |
| 73 | } |
| 74 | |
| 75 | DownloadTerrasyncSharedData::~DownloadTerrasyncSharedData() |
| 76 | { |
| 77 | if (!m_done) { |
| 78 | if (m_download) { |
| 79 | m_download->abort(); |
| 80 | } |
| 81 | m_error = true; |
| 82 | } |
| 83 | |
| 84 | if (m_download) { |
| 85 | m_download->deleteLater(); |
| 86 | m_download = nullptr; |
| 87 | } |
| 88 | |
| 89 | wait(); |
| 90 | } |
| 91 | |
| 92 | void DownloadTerrasyncSharedData::startNextDownload() |
| 93 | { |
| 94 | std::unique_lock g(m_mutex); |
| 95 | if (m_items.empty()) { |
| 96 | m_done = true; // exit the thread loop |
| 97 | return; |
| 98 | } |
| 99 | |
| 100 | const auto& item = m_items.front(); |
| 101 | // if the directory exists, skip it : we will use normal TerraSync incremental updating |
| 102 | if (item.terrasyncPath.exists()) { |
| 103 | m_items.pop_front(); |
| 104 | QTimer::singleShot(0, this, &DownloadTerrasyncSharedData::startNextDownload); |
| 105 | return; |
| 106 | } |
| 107 | |
| 108 | // reset the archive |
| 109 | m_archive.reset(new simgear::ArchiveExtractor(item.terrasyncPath)); |
| 110 | m_archive->setRemoveTopmostDirectory(true); |
| 111 | m_archive->setCreateDirHashEntries(true); |
| 112 | |
| 113 | // +1 to include the leading / |
| 114 | m_pathPrefixLength = item.terrasyncPath.utf8Str().length() + 1; |
| 115 | |
| 116 | QString url = m_serverUri + item.relativeURIPath; |
| 117 | QNetworkRequest req{url}; |
| 118 | req.setMaximumRedirectsAllowed(5); |
| 119 | req.setRawHeader("user-agent", "flightgear-installer"); |
| 120 | m_download = m_networkManager->get(req); |
| 121 | m_download->setReadBufferSize(64 * 1024 * 1024); |
| 122 | |
| 123 | m_buffer.clear(); |
| 124 | |
| 125 | connect(m_download, &QNetworkReply::downloadProgress, this, &DownloadTerrasyncSharedData::onDownloadProgress); |
| 126 | connect(m_download, &QNetworkReply::readyRead, this, &DownloadTerrasyncSharedData::processBytes); |
| 127 | connect(m_download, &QNetworkReply::finished, this, &DownloadTerrasyncSharedData::onReplyFinished); |
| 128 | #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) |
| 129 | connect(m_download, &QNetworkReply::errorOccurred, this, &DownloadTerrasyncSharedData::onNetworkError); |
| 130 | #endif |
| 131 | |
| 132 | m_totalSize = 0; |
| 133 | m_haveFirstMByte = false; |
| 134 | |
| 135 | emit beginArchive(item.archiveName); |
| 136 | m_items.pop_front(); |
| 137 | } |
| 138 | |
| 139 | void DownloadTerrasyncSharedData::onNetworkError(QNetworkReply::NetworkError code) |
| 140 | { |
| 141 | if (code == QNetworkReply::OperationCanceledError) { |
| 142 | // abort() is handled differently, |
| 143 | // eg when a resume fails |
| 144 | return; |
| 145 | } |
| 146 | |
| 147 | SG_LOG(SG_IO, SG_WARN, "shared data download failed (" << m_download->errorString().toStdString() << "): for " |
| 148 | << m_download->url().toString().toStdString()); |
| 149 | |
| 150 | m_error = true; |
| 151 | emit failed(m_download->errorString()); |
| 152 | } |
| 153 | |
| 154 | void DownloadTerrasyncSharedData::onDownloadProgress(quint64 got, quint64 total) |
| 155 | { |
| 156 | emit downloadProgress(got, total); |
| 157 | m_totalSize = total; |
| 158 | } |
| 159 | |
| 160 | void DownloadTerrasyncSharedData::processBytes() |
| 161 | { |
| 162 | QByteArray bytes = m_download->readAll(); |
| 163 | { |
| 164 | std::unique_lock g(m_mutex); |
| 165 | m_buffer.append(bytes); |
| 166 | m_bufferWait.notify_one(); |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | void DownloadTerrasyncSharedData::onReplyFinished() |
| 171 | { |
| 172 | // we can't use m_download here because in the case of re-trying, |
| 173 | // we already replaced m_download with our new request. |
| 174 | QNetworkReply* r = qobject_cast<QNetworkReply*>(sender()); |
| 175 | r->deleteLater(); |
| 176 | |
| 177 | #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) |
| 178 | if (r->error() != QNetworkReply::NoError) { |
| 179 | onNetworkError(r->error()); |
| 180 | } |
| 181 | #endif |
| 182 | } |
| 183 | |
| 184 | void DownloadTerrasyncSharedData::updateProgress() |
| 185 | { |
| 186 | if (!m_archive) { |
| 187 | return; // happens upon completion |
| 188 | } |
| 189 | |
| 190 | std::unique_lock g(m_mutex); |
| 191 | const int percent = calculateProgressPercentage(m_extractedBytes, m_totalSize); |
| 192 | auto fullPathStr = m_archive->mostRecentExtractedPath().utf8Str(); |
| 193 | fullPathStr.erase(0, m_pathPrefixLength); |
| 194 | emit installProgress(QString::fromStdString(fullPathStr), percent); |
| 195 | } |
| 196 | |
| 197 | void DownloadTerrasyncSharedData::run() |
| 198 | { |
| 199 | while (!m_error & !m_done) { |
| 200 | QByteArray localBytes; |
| 201 | { |
| 202 | std::unique_lock g(m_mutex); |
| 203 | if (m_buffer.isEmpty()) { |
| 204 | m_bufferWait.wait_for(g, 100ms); |
| 205 | } |
| 206 | |
| 207 | // don't start passing bytes to the archive extractor, until we have 1MB |
| 208 | // this is necessary to avoid passing redirect/404 page bytes in, and breaking |
| 209 | // the extractor. |
| 210 | if (!m_haveFirstMByte && (m_buffer.size() < 0x100000)) { |
| 211 | continue; |
| 212 | } else { |
| 213 | m_haveFirstMByte = true; |
| 214 | } |
| 215 | |
| 216 | // take at most 1MB |
| 217 | localBytes = m_buffer.left(0x100000); |
| 218 | m_buffer.remove(0, localBytes.length()); |
| 219 | } |
| 220 | |
| 221 | if (!localBytes.isEmpty()) { |
| 222 | m_archive->extractBytes((const uint8_t*)localBytes.constData(), localBytes.size()); |
| 223 | m_extractedBytes += localBytes.size(); |
| 224 | } |
| 225 | |
| 226 | updateProgress(); |
| 227 | if (m_archive) { |
| 228 | if (m_archive->hasError()) { |
| 229 | m_error = true; |
| 230 | qWarning() << "Archive error"; |
| 231 | } else if (m_archive->isAtEndOfArchive()) { |
| 232 | m_archive.reset(); |
| 233 | // start the next download, or set m_done=true if nothing left to do |
| 234 | QTimer::singleShot(0, this, &DownloadTerrasyncSharedData::startNextDownload); |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | if (m_error) { |
| 240 | // ensure the archive is cleaned up, including any files, |
| 241 | // since we will likely attempt to remove it. |
| 242 | m_archive.reset(); |
| 243 | } |
| 244 | } |