void TcDownloadList::StartFileDownload(const QString &url, int count) { m_DownloadCount = count; m_FinishedNum = 0; m_Url = QUrl(url); m_FileSize = GetFileSize(m_Url); //先获得文件的名字 QFileInfo fileInfo(m_Url.path()); QString fileName = fileInfo.fileName(); if (fileName.isEmpty()) fileName = "index.html"; m_File->setFileName(fileName); //打开文件 m_File->open(QIODevice::WriteOnly); TcDownload *tempDownload; //将文件分成PointCount段,用异步的方式下载 //qDebug() << "Start download file from " << strUrl; for(int i=0; i<m_DownloadCount; i++) { //先算出每段的开头和结尾(HTTP协议所需要的信息) int start = m_FileSize * i / m_DownloadCount; int end = m_FileSize * (i+1) / m_DownloadCount; if( i != 0 ) start--; //分段下载该文件 tempDownload = new TcDownload(i + 1, this); connect(tempDownload, SIGNAL(DownloadFinished()), this, SLOT(SubPartFinished())); connect(tempDownload, SIGNAL(DownloadFinished()), tempDownload, SLOT(deleteLater())); tempDownload->StartDownload(m_Url, m_File, start, end); } }
void MagnatuneDownloadDialog::DownloadFinished() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); reply->deleteLater(); // Close any open file download_file_.reset(); QUrl redirect = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (redirect.isValid()) { // Open the output file QString output_filename = GetOutputFilename(); download_file_.reset(new QFile(output_filename)); if (!download_file_->open(QIODevice::WriteOnly)) { ShowError(tr("Couldn't open output file %1").arg(output_filename)); return; } // Round and round we go redirect.setUserName(service_->username()); redirect.setPassword(service_->password()); current_reply_ = network_->get(QNetworkRequest(redirect)); connect(current_reply_, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(Error(QNetworkReply::NetworkError))); connect(current_reply_, SIGNAL(finished()), SLOT(DownloadFinished())); connect(current_reply_, SIGNAL(downloadProgress(qint64,qint64)), SLOT(DownloadProgress(qint64,qint64))); connect(current_reply_, SIGNAL(readyRead()), SLOT(DownloadReadyRead())); return; } next_row_ ++; DownloadNext(); }
void SelfUpdater::OnStartUpdating() { currentDownload = networkManager->get(QNetworkRequest(QUrl(archiveUrl))); connect(currentDownload, SIGNAL(finished()), this, SLOT(DownloadFinished())); connect(currentDownload, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(NetworkError(QNetworkReply::NetworkError))); }
//下载结束 void TcDownload::FinishedSlot() { m_File->flush(); m_Reply->deleteLater(); m_Reply = 0; m_File = 0; qDebug() << "Part " << m_Index << " download finished"; emit DownloadFinished(); }
void MagnatuneDownloadDialog::MetadataFinished() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); reply->deleteLater(); // The reply isn't valid XML so we can't use QtXML to parse it :( QString data = QString::fromUtf8(reply->readAll()); // Check for errors if (data.contains("<ERROR>")) { ShowError(tr("There was a problem fetching the metadata from Magnatune")); return; } // Work out what format we want QString type; switch (ui_->format->currentIndex()) { case MagnatuneService::Format_Ogg: type = "URL_OGGZIP"; break; case MagnatuneService::Format_Flac: type = "URL_FLACZIP"; break; case MagnatuneService::Format_Wav: type = "URL_WAVZIP"; break; case MagnatuneService::Format_MP3_VBR: type = "URL_VBRZIP"; break; case MagnatuneService::Format_MP3_128: type = "URL_128KMP3ZIP"; break; } // Parse the XML (lol) to find the URL QRegExp re(QString("<%1>([^<]+)</%2>").arg(type, type)); if (re.indexIn(data) == -1) { ShowError(tr("This album is not available in the requested format")); return; } // Munge the URL a bit QString url_text = Utilities::DecodeHtmlEntities(re.cap(1)); QUrl url = QUrl(url_text); url.setUserName(service_->username()); url.setPassword(service_->password()); qLog(Debug) << "Downloading" << url; // Start the actual download current_reply_ = network_->get(QNetworkRequest(url)); connect(current_reply_, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(Error(QNetworkReply::NetworkError))); connect(current_reply_, SIGNAL(finished()), SLOT(DownloadFinished())); connect(current_reply_, SIGNAL(downloadProgress(qint64,qint64)), SLOT(DownloadProgress(qint64,qint64))); connect(current_reply_, SIGNAL(readyRead()), SLOT(DownloadReadyRead())); // Close any open file download_file_.reset(); // Open the output file QString output_filename = GetOutputFilename(); download_file_.reset(new QFile(output_filename)); if (!download_file_->open(QIODevice::WriteOnly)) { ShowError(tr("Couldn't open output file %1").arg(output_filename)); } }
void SelfUpdater::UpdatedConfigDownloaded(const AppsConfig& config) { m_UpdateLauncerConfig = config.m_Launcher; QString nNewVersion = Settings::GetVersion(config.m_Launcher.m_Version); QString nCurVersion = Settings::GetVersion(Settings::GetInstance()->GetLauncherVersion()); if (nCurVersion != nNewVersion) { //download new version m_pReply = m_pNetworkManager->get(QNetworkRequest(config.m_Launcher.m_Url)); connect(m_pReply, SIGNAL(finished()), this, SLOT(DownloadFinished())); } }
void MagnatuneService::Download() { QModelIndex index = library_sort_model_->mapToSource(model()->current_index()); SongList songs = library_model_->GetChildSongs(index); MagnatuneDownloadDialog* dialog = new MagnatuneDownloadDialog(this, 0); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->Show(songs); connect(dialog, SIGNAL(Finished(QStringList)), SIGNAL(DownloadFinished(QStringList))); }
void MagnatuneDownloadDialog::MetadataFinished() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); reply->deleteLater(); // The reply isn't valid XML so we can't use QtXML to parse it :( QString data = QString::fromUtf8(reply->readAll()); // Check for errors if (data.contains("<ERROR>")) { ShowError(tr("There was a problem fetching the metadata from Magnatune")); return; } // Work out what format we want QString type; switch (ui_->format->currentIndex()) { case MagnatuneService::Format_Ogg: type = "URL_OGGZIP"; break; case MagnatuneService::Format_Flac: type = "URL_FLACZIP"; break; case MagnatuneService::Format_Wav: type = "URL_WAVZIP"; break; case MagnatuneService::Format_MP3_VBR: type = "URL_VBRZIP"; break; case MagnatuneService::Format_MP3_128: type = "URL_128KMP3ZIP"; break; } // Parse the XML (lol) to find the URL QRegExp re(QString("<%1>([^<]+)</%2>").arg(type, type)); if (re.indexIn(data) == -1) { ShowError(tr("This album is not available in the requested format")); return; } // Munge the URL a bit QString url_text = re.cap(1); url_text.replace("&", "&"); QUrl url = QUrl(url_text); url.setUserName(service_->username()); url.setPassword(service_->password()); // Start the actual download current_reply_ = network_->get(QNetworkRequest(url)); connect(current_reply_, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(Error(QNetworkReply::NetworkError))); connect(current_reply_, SIGNAL(finished()), SLOT(DownloadFinished())); // No DownloadProgress connection because the first one is a redirect }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); this->setWindowTitle(tr("Launcher %1").arg(QString(LAUNCER_VER))); m_pInstaller = new Installer(this); connect(m_pInstaller, SIGNAL(SoftWareAvailable(AvailableSoftWare)), this, SLOT(AvailableSoftWareUpdated(AvailableSoftWare))); connect(m_pInstaller, SIGNAL(StartDownload()), this, SLOT(OnDownloadStarted())); connect(m_pInstaller, SIGNAL(DownloadFinished()), this, SLOT(OnDownloadFinished())); connect(m_pInstaller, SIGNAL(DownloadProgress(int)), this, SLOT(OnDownloadProgress(int))); m_pUpdateTimer = new QTimer(this); connect(m_pUpdateTimer, SIGNAL(timeout()), this, SLOT(on_btnRefresh_clicked())); m_pUpdateTimer->start(Settings::GetInstance()->GetUpdateTimerInterval()); ui->stableTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch); ui->developmentTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch); ui->dependenciesTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch); connect(ui->stableTable, SIGNAL(itemSelectionChanged()), this, SLOT(UpdateBtn())); connect(ui->dependenciesTable, SIGNAL(itemSelectionChanged()), this, SLOT(UpdateBtn())); connect(ui->developmentTable, SIGNAL(itemSelectionChanged()), this, SLOT(UpdateBtn())); connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(UpdateBtn())); connect(ui->stableTable, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_btnRun_clicked())); connect(ui->developmentTable, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_btnRun_clicked())); connect(Logger::GetInstance(), SIGNAL(LogAdded(QString)), this, SLOT(OnLogAdded(QString))); ui->downloadProgress->setVisible(false); ui->downloadProgress->setRange(0, 100); m_bBusy = false; UpdateBtn(); m_pInstaller->Init(); }
void game_compatibility::RequestCompatibility(bool online) { // Creates new map from database auto ReadJSON = [=](const QJsonObject& json_data, bool after_download) { int return_code = json_data["return_code"].toInt(); if (return_code < 0) { if (after_download) { std::string error_message; switch (return_code) { case -1: error_message = "Server Error - Internal Error"; break; case -2: error_message = "Server Error - Maintenance Mode"; break; default: error_message = "Server Error - Unknown Error"; break; } LOG_ERROR(GENERAL, "Compatibility error: { %s: return code %d }", error_message, return_code); Q_EMIT DownloadError(qstr(error_message) + " " + QString::number(return_code)); } else { LOG_ERROR(GENERAL, "Compatibility error: { Database Error - Invalid: return code %d }", return_code); } return false; } if (!json_data["results"].isObject()) { LOG_ERROR(GENERAL, "Compatibility error: { Database Error - No Results found }"); return false; } m_compat_database.clear(); QJsonObject json_results = json_data["results"].toObject(); // Retrieve status data for every valid entry for (const auto& key : json_results.keys()) { if (!json_results[key].isObject()) { LOG_ERROR(GENERAL, "Compatibility error: { Database Error - Unusable object %s }", sstr(key)); continue; } QJsonObject json_result = json_results[key].toObject(); // Retrieve compatibility information from json compat_status status = Status_Data.at(json_result.value("status").toString("NoResult")); // Add date if possible status.date = json_result.value("date").toString(); // Add status to map m_compat_database.emplace(std::pair<std::string, compat_status>(sstr(key), status)); } return true; }; if (!online) { // Retrieve database from file QFile file(m_filepath); if (!file.exists()) { LOG_NOTICE(GENERAL, "Compatibility notice: { Database file not found: %s }", sstr(m_filepath)); return; } if (!file.open(QIODevice::ReadOnly)) { LOG_ERROR(GENERAL, "Compatibility error: { Database Error - Could not read database from file: %s }", sstr(m_filepath)); return; } QByteArray data = file.readAll(); file.close(); LOG_NOTICE(GENERAL, "Compatibility notice: { Finished reading database from file: %s }", sstr(m_filepath)); // Create new map from database ReadJSON(QJsonDocument::fromJson(data).object(), online); return; } if (QSslSocket::supportsSsl() == false) { LOG_ERROR(GENERAL, "Can not retrieve the online database! Please make sure your system supports SSL."); QMessageBox::warning(nullptr, tr("Warning!"), tr("Can not retrieve the online database! Please make sure your system supports SSL.")); return; } LOG_NOTICE(GENERAL, "SSL supported! Beginning compatibility database download from: %s", sstr(m_url)); // Send request and wait for response m_network_access_manager.reset(new QNetworkAccessManager()); QNetworkReply* network_reply = m_network_access_manager->get(m_network_request); // Show Progress m_progress_dialog.reset(new QProgressDialog(tr(".Please wait."), tr("Abort"), 0, 100)); m_progress_dialog->setWindowTitle(tr("Downloading Database")); m_progress_dialog->setFixedWidth(QLabel("This is the very length of the progressbar due to hidpi reasons.").sizeHint().width()); m_progress_dialog->setValue(0); m_progress_dialog->show(); // Animate progress dialog a bit more m_progress_timer.reset(new QTimer(this)); connect(m_progress_timer.get(), &QTimer::timeout, [&]() { switch (++m_timer_count % 3) { case 0: m_timer_count = 0; m_progress_dialog->setLabelText(tr(".Please wait.")); break; case 1: m_progress_dialog->setLabelText(tr("..Please wait..")); break; default: m_progress_dialog->setLabelText(tr("...Please wait...")); break; } }); m_progress_timer->start(500); // Handle abort connect(m_progress_dialog.get(), &QProgressDialog::rejected, network_reply, &QNetworkReply::abort); // Handle progress connect(network_reply, &QNetworkReply::downloadProgress, [&](qint64 bytesReceived, qint64 bytesTotal) { m_progress_dialog->setMaximum(bytesTotal); m_progress_dialog->setValue(bytesReceived); }); // Handle response according to its contents connect(network_reply, &QNetworkReply::finished, [=]() { // Clean up Progress Dialog if (m_progress_dialog) { m_progress_dialog->close(); } if (m_progress_timer) { m_progress_timer->stop(); } // Handle Errors if (network_reply->error() != QNetworkReply::NoError) { // We failed to retrieve a new database, therefore refresh gamelist to old state QString error = network_reply->errorString(); Q_EMIT DownloadError(error); LOG_ERROR(GENERAL, "Compatibility error: { Network Error - %s }", sstr(error)); return; } LOG_NOTICE(GENERAL, "Compatibility notice: { Database download finished }"); // Read data from network reply QByteArray data = network_reply->readAll(); network_reply->deleteLater(); // Create new map from database and write database to file if database was valid if (ReadJSON(QJsonDocument::fromJson(data).object(), online)) { // We have a new database in map, therefore refresh gamelist to new state Q_EMIT DownloadFinished(); // Write database to file QFile file(m_filepath); if (file.exists()) { LOG_NOTICE(GENERAL, "Compatibility notice: { Database file found: %s }", sstr(m_filepath)); } if (!file.open(QIODevice::WriteOnly)) { LOG_ERROR(GENERAL, "Compatibility error: { Database Error - Could not write database to file: %s }", sstr(m_filepath)); return; } file.write(data); file.close(); LOG_SUCCESS(GENERAL, "Compatibility success: { Write database to file: %s }", sstr(m_filepath)); } }); // We want to retrieve a new database, therefore refresh gamelist and indicate that Q_EMIT DownloadStarted(); }
void Installer::OnAppDownloaded() { emit DownloadFinished(); if (!m_pReply) return; eAppType type = (eAppType)m_pReply->property(INSTALL_TYPE).toInt(); QString appName = m_pReply->property(INSTALL_NAME).toString(); QString appVersion = m_pReply->property(INSTALL_VERISON).toString(); const AppsConfig::AppMap* pUpdateMap = m_AppsConfig.GetAppMap(type); if (!pUpdateMap) return; AppsConfig::AppMap::const_iterator appIter = pUpdateMap->find(appName); if (appIter == pUpdateMap->end()) return; AppsConfig::AppVersion::const_iterator iter = appIter.value().find(appVersion); if (iter == appIter.value().end()) return; const AppConfig& updateConfig = iter.value(); QByteArray data = m_pReply->readAll(); if (!data.size()) { Logger::GetInstance()->AddLog(tr("Error download app")); return; } //save archive QString tempFilePath = DirectoryManager::GetInstance()->GetDownloadDir() + APP_DOWNLOAD; QFile tempFile(tempFilePath); if (!tempFile.open(QFile::WriteOnly | QFile::Truncate)) { Logger::GetInstance()->AddLog(tr("Error save archive")); return; } tempFile.write(data); tempFile.close(); //unpack archive QString tempDir = DirectoryManager::GetInstance()->GetDownloadDir() + APP_TEMP_DIR; if (!DirectoryManager::DeleteDir(tempDir)) { Logger::GetInstance()->AddLog(tr("Error delete old directory")); return; } if (!QDir().mkdir(tempDir)) { Logger::GetInstance()->AddLog(tr("Error create temp directory")); return; } //if file is a zip-archive - unpack, otherwise - just move to the tempDir //check is performed by server's file extension QFileInfo serverFileInfo(updateConfig.m_Url.toString()); QString serverFileName = serverFileInfo.fileName(); if (DirectoryManager::IsFilePacked(serverFileName)) { if (!zipHelper::unZipFile(tempFilePath, tempDir)) { Logger::GetInstance()->AddLog(tr("Error unpack archive")); return; } } else { if (!DirectoryManager::MoveFileToDir(tempFilePath, tempDir, serverFileName)) { Logger::GetInstance()->AddLog(tr("Error move file to the temp directory")); return; } } //copy to destination QString installPath = GetInstallPath(type); //no install just copy file to new folder QStringList installedFiles = DirectoryManager::GetDirectoryStructure(tempDir); bool bInstalled = false; #ifdef Q_OS_WIN if (updateConfig.m_InstallCmd.isEmpty()) { #endif bInstalled = DirectoryManager::CopyAllFromDir(tempDir, installPath); if (!bInstalled) { Logger::GetInstance()->AddLog(tr("Error copy apps to destination")); } #ifdef Q_OS_WIN }else { QString InstallerPath; do { //copy installer //create path for save installer QString InstallersPath = installPath + APP_INSTALLER_DIR; if (!QDir().exists(InstallersPath) && !QDir().mkdir(InstallersPath)) { Logger::GetInstance()->AddLog(tr("Error create installers path")); break; } //create app installer path InstallerPath = InstallersPath + "/" + appName; DirectoryManager::DeleteDir(InstallerPath); if (!QDir().mkdir(InstallerPath)) { Logger::GetInstance()->AddLog(tr("Error create installer path")); break; } //copy installer if (!DirectoryManager::CopyAllFromDir(tempDir, InstallerPath)) { Logger::GetInstance()->AddLog(tr("Error copy installer")); break; } QString installer = InstallerPath + "/" + updateConfig.m_InstallCmd; QFile aFile(installer); if (!aFile.exists()) { Logger::GetInstance()->AddLog(tr("Error running installer - file not found")); break; } QString params = updateConfig.m_InstallParams; int nExitCode = RunAndWaitForFinish(installer, params); if (updateConfig.m_nSuccessInstallCode == nExitCode) bInstalled = true; } while(false); if (!bInstalled) { //hack after cancel install directory can't be delete at once //so we rename it and then delete QString temp = InstallerPath + QString::number(QDateTime().currentMSecsSinceEpoch()); DirectoryManager::DeleteDir(QDir().rename(InstallerPath, temp) ? temp : InstallerPath); } } #endif if (bInstalled) { AppConfig config; //const AppConfig installedConfig = installedApp.value(name); config.m_Name = appName; if (!updateConfig.m_RunPath.isEmpty()) config.m_RunPath = updateConfig.m_RunPath; config.m_InstalledFiles = installedFiles; config.m_Version = updateConfig.m_Version; config.m_InstallCmd = updateConfig.m_InstallCmd; config.m_UninstallCmd = updateConfig.m_UninstallCmd; config.m_InstallParams = updateConfig.m_InstallParams; config.m_UninstallParams = updateConfig.m_UninstallParams; AppsConfig setting = Settings::GetInstance()->GetCurrentConfig(); AppsConfig::AppMap* pSettingMap = setting.GetAppMap(type); if (pSettingMap) { pSettingMap->remove(config.m_Name); //pSettingMap->insert(appName, config); (*pSettingMap)[config.m_Name][config.m_Version] = config; } Settings::GetInstance()->UpdateConfig(setting); } //delete temp files DirectoryManager::DeleteDir(tempDir); QFile().remove(tempFilePath); UpdateAvailableSoftware(); if (bInstalled) { Logger::GetInstance()->AddLog(tr("%1 installed.").arg(appName)); CheckForUpdate(); } }