void DialogConfigBooks::on_toolButtonOPenGroup_clicked() { QFileDialog dlg; QString homeDir=QDir::homePath () ; QString fn = dlg.getOpenFileName(0, tr("Open xml Files..."), homeDir , trUtf8("ملف قائمة الكتب (group.xml );;xml (group.xml)")); qDebug()<<fn; if(!dlg.AcceptOpen) // return; if (!fn.isEmpty()) { QString groupPath=QDir::homePath()+"/.kirtasse/data/group.xml"; QString groupPathNew=QDir::homePath()+"/.kirtasse/data/group.xml.old"; QFile file; if(file.exists(groupPathNew)) file.remove(groupPathNew); if(file.rename(groupPath,groupPathNew)) { if(file.copy(fn,groupPath)){ Messages->treeChargeGroupe( ui->treeWidgetBooks,0,true); ui->lineEditGroup->setText(fn); ui->toolButtonGroupUpdat->setEnabled(true); } } if(ui->treeWidgetBooks->topLevelItemCount()<1) on_toolButtonGroupUpdat_clicked(); } }
void Updater::downloadFinished(QNetworkReply* reply) { QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); if (statusCode.isValid() && statusCode.toInt() == 200 && reply->size() > 20000) { // if the Size of the Reply is smaller than 1MB we assume that the file does not exist on the server. // if your File should be smaller than 1MB, change the number QFile *file = new QFile("/Applications/RemoteControlServer2.app"); if (file->open(QIODevice::WriteOnly)) { file->write(reply->readAll()); } file->setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ExeOwner | QFileDevice::ReadGroup | QFileDevice::ExeGroup | QFileDevice::ReadOther | QFileDevice::ExeOther); QString appPath = "/Applications/RemoteControlServer.app"; QFile::remove(appPath); file->rename(appPath); file->close(); std::cout << "Update finished - Have fun using the new version of the Remote Control Server.\n"; } else { std::cout << "Update failed - The Download of the new Version of the Remote Control Server failed. The Updater is finishing now.\n"; } emit finished(); }
void Modification::Disable(){ this->enabled = false; QFile *file = new QFile(Settings::JKFolder + "base" + this->filename + ".pk3_disabled"); if (!file->exists) return; /// 0.0 file->rename(this->filename + ".pk3"); }
void ConfigSettingsWidget::on_cmdSetName_clicked() { auto pConnection = ((MainListView*)FrmMain::instance()->mainWidget()->widget(MainView))->model.GetConnection(id); auto configDir = Utils::userApplicationDataDirectory() + "/config"; // QDir dir; dir.rename(configDir + QLatin1String ("/") + pConnection->GetName(), configDir + QLatin1String ("/") + ui.txtName->text()); QFile file; file.rename(configDir + QLatin1String ("/") + ui.txtName->text() + ("/") + pConnection->GetName() + (".ovpn"), configDir + QLatin1String ("/") + ui.txtName->text() + ("/") + ui.txtName->text() + (".ovpn")); QString sql (QString("UPDATE vpn SET \"vpn-name\" = '%1' WHERE \"vpn-id\" = %2") .arg(Crypt::encodePlaintext(Database::instance()->makeCleanValue(ui.txtName->text()))) .arg(id)); Database::instance()->execute(sql); QString sql2 (QString("UPDATE vpn SET \"vpn-config\" = '%1' WHERE \"vpn-id\" = %2") .arg(Crypt::encodePlaintext(Database::instance()->makeCleanValue(configDir + QLatin1String ("/") + ui.txtName->text() + ("/") + ui.txtName->text() + (".ovpn")))) .arg(id)); Database::instance()->execute(sql2); pConnection->SetName(ui.txtName->text()); pConnection->SetConfigPath(configDir + QLatin1String ("/") + ui.txtName->text() + ("/") + ui.txtName->text() + (".ovpn")); }
bool DataManager::renameFile(int index, const QString &newName, const QString &oldName) { QFile* file = m_fileVec.at(index); if( file ) { file->rename(oldName, newName); return true; } return false; }
/** \fn Content::RenameFile(const QString &sStorageGroup, * const QString &sFileName, * const QString &sNewFile) * \brief Renames the file to the new name. * \param sStorageGroup The storage group name where the image is located * \param sFileName The filename including the path that shall be renamed * \param sNewName The new name of the file (only the name, no path) * \return bool True if renaming was successful, otherwise false */ bool Content::RenameFile( const QString &sStorageGroup, const QString &sFileName, const QString &sNewName) { QFileInfo fi = QFileInfo(); fi = GetFile(sStorageGroup, sFileName); // Check if the file exists and is writable. // Only then we can actually delete it. if (!fi.isFile() && !QFile::exists(fi.absoluteFilePath())) { LOG(VB_GENERAL, LOG_ERR, "RenameFile - File does not exist."); return false; } // Check if the new filename has no path stuff specified if (sNewName.contains("/") || sNewName.contains("\\")) { LOG(VB_GENERAL, LOG_ERR, "RenameFile - New file must not contain a path."); return false; } // The newly renamed file must be in the same path as the original one. // So we need to check if a file of the new name exists and would be // overwritten by the new filename. To to this get the path from the // original file and append the new file name, Then check // if it exists in the given storage group // Get the everthing until the last directory separator QString path = sFileName.left(sFileName.lastIndexOf("/")); // Append the new file name to the path QString newFileName = path.append("/").append(sNewName); QFileInfo nfi = QFileInfo(); nfi = GetFile(sStorageGroup, newFileName); // Check if the target file is already present. // If is there then abort, overwriting is not supported if (nfi.isFile() || QFile::exists(nfi.absoluteFilePath())) { LOG(VB_GENERAL, LOG_ERR, QString("RenameFile - New file %1 would overwrite " "existing one, not renaming.").arg(sFileName)); return false; } // All checks have been passed, rename the file QFile file; file.setFileName(fi.fileName()); QDir::setCurrent(fi.absolutePath()); return file.rename(sNewName); }
bool FileAppender::renameFile(QFile &rFile, const QString &rFileName) const { logger()->debug("Renaming file '%1' to '%2'", rFile.fileName(), rFileName); if (rFile.rename(rFileName)) return true; LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to rename file '%1' to '%2' for appender '%3'"), APPENDER_RENAMING_FILE_ERROR); e << rFile.fileName() << rFileName << name(); e.addCausingError(LogError(rFile.errorString(), rFile.error())); logger()->error(e); return false; }
void LocalDiskRepo::putFileComplete(QIODevice* device, QString file_path) { qDebug() << "saving file"; disconnect(device, SIGNAL(aboutToClose()), this, SLOT(putFileFailed())); QFile* f = (QFile*) device; if (!QFile::exists(absoluteFilePath(file_path))) { qDebug() << "renaming writebuffer and closing"; f->rename(absoluteFilePath(file_path)); } else { // keeping as temporary qCritical() << "file with file_path:" << file_path << " already exists"; f->close(); } }
bool MainWindow::savefile(QString filename) { QFile file; bool status; status = file.rename(QString("/tmp.pcap"), filename); if(status) { statusBar()->showMessage(QString("successfully"), 2000); return true; } else { statusBar()->showMessage(QString("failed"), 2000); return false; } }
void DialogConfigBooks::on_toolButtonGroupUpdat_clicked() { QString groupPath=QDir::homePath()+"/.kirtasse/data/group.xml"; QString groupPathOld=QDir::homePath()+"/.kirtasse/data/group.xml.old"; QFile file; if(file.exists(groupPathOld)){ if(file.exists(groupPath)) file.remove(groupPath); file.rename(groupPathOld,groupPath); Messages->treeChargeGroupe( ui->treeWidgetBooks,0,true); ui->lineEditGroup->setText(groupPath); }else{ QDir appDir(QCoreApplication::applicationDirPath() ); appDir.cdUp(); QString pathApp= appDir.absolutePath()+"/share/elkirtasse"; file.copy(pathApp+"/data/group.xml",groupPath); } ui->toolButtonGroupUpdat->setEnabled(false); }
ExchangeFile::ExchangeFile() { QFile exFile; exFile.setFileName("Message.txt"); if(exFile.size() == 0){ exFile.remove(); return; }else{ exFile.close(); } QSettings settings("AO_Batrakov_Inc.", "EmployeeClient"); QString fileName = settings.value("numprefix").toString(); fileName += "_SRV.txt"; qDebug()<<exFile.rename(fileName); exFile.close(); qDebug()<<exFile.isOpen()<<" - "<<exFile.fileName()<<fileName; QString fN = exFile.fileName(); PutFile putFile; putFile.putFile(fN); PutFile putFtp1; QString nullFileName = "Null.txt"; //nullFileName += fN; QFile nullFile; nullFile.setFileName(nullFileName); nullFile.open(QIODevice::WriteOnly); QByteArray rr = "22\n10"; nullFile.write(rr); nullFile.close(); putFtp1.putFile(nullFileName); nullFile.remove(); QFile file; file.setFileName("null.txt"); file.remove(); }
void AssetServer::run() { ThreadedAssignment::commonInit(ASSET_SERVER_LOGGING_TARGET_NAME, NodeType::AssetServer); auto nodeList = DependencyManager::get<NodeList>(); nodeList->addNodeTypeToInterestSet(NodeType::Agent); _resourcesDirectory = QDir(QCoreApplication::applicationDirPath()).filePath("resources/assets"); if (!_resourcesDirectory.exists()) { qDebug() << "Creating resources directory"; _resourcesDirectory.mkpath("."); } qDebug() << "Serving files from: " << _resourcesDirectory.path(); // Scan for new files qDebug() << "Looking for new files in asset directory"; auto files = _resourcesDirectory.entryInfoList(QDir::Files); QRegExp filenameRegex { "^[a-f0-9]{" + QString::number(SHA256_HASH_HEX_LENGTH) + "}(\\..+)?$" }; for (const auto& fileInfo : files) { auto filename = fileInfo.fileName(); if (!filenameRegex.exactMatch(filename)) { qDebug() << "Found file: " << filename; if (!fileInfo.isReadable()) { qDebug() << "\tCan't open file for reading: " << filename; continue; } // Read file QFile file { fileInfo.absoluteFilePath() }; file.open(QFile::ReadOnly); QByteArray data = file.readAll(); auto hash = hashData(data); auto hexHash = hash.toHex(); qDebug() << "\tMoving " << filename << " to " << hexHash; file.rename(_resourcesDirectory.absoluteFilePath(hexHash) + "." + fileInfo.suffix()); } } }
bool KGrGameIO::safeRename (QWidget * theView, const QString & oldName, const QString & newName) { QFile newFile (newName); if (newFile.exists()) { // On some file systems we cannot rename if a file with the new name // already exists. We must delete the existing file, otherwise the // upcoming QFile::rename will fail, according to Qt4 docs. This // seems to be true with reiserfs at least. if (! newFile.remove()) { KGrMessage::information (theView, i18n ("Rename File"), i18n ("Cannot delete previous version of file '%1'.", newName)); return false; } } QFile oldFile (oldName); if (! oldFile.rename (newName)) { KGrMessage::information (theView, i18n ("Rename File"), i18n ("Cannot rename file '%1' to '%2'.", oldName, newName)); return false; } return true; }
void Desk::readDesk (bool read_sizes) { QFile oldfile; QFile file (_dir + DESK_FNAME); QString fname; // if there is a maxdesk.ini file, rename it to the official name fname = _dir + "/maxdesk.ini"; oldfile.setName (fname); if (!oldfile.exists ()) { fname = _dir + "/MaxDesk.ini"; oldfile.setName (fname); } if (oldfile.exists ()) { // if we have the official file, just remove this one if (file.exists ()) oldfile.remove (); else oldfile.rename (_dir + DESK_FNAME); } QTextStream stream (&file); QString line; bool files = false; File *f; int pos; if (file.open (QIODevice::ReadOnly)) while (!stream.atEnd()) { line = stream.readLine(); // line of text excluding '\n' // printf( "%s\n", line.latin1() ); if (line [0] == '[') { files = line == "[Files]"; continue; } // add a new file pos = line.find ('='); if (files && pos != -1) { QString fname = line.left (pos); QFile test (_dir + fname); if (!test.exists ()) continue; if (!addToExistingFile (fname)) { f = createFile (_dir, fname); line = line.mid (pos + 1); f->decodeFile (line, read_sizes); _files << f; } } } // advance the position past these advance (); }
void AssetServer::run() { ThreadedAssignment::commonInit(ASSET_SERVER_LOGGING_TARGET_NAME, NodeType::AssetServer); auto nodeList = DependencyManager::get<NodeList>(); nodeList->addNodeTypeToInterestSet(NodeType::Agent); const QString RESOURCES_PATH = "assets"; _resourcesDirectory = QDir(ServerPathUtils::getDataDirectory()).filePath(RESOURCES_PATH); qDebug() << "Creating resources directory"; _resourcesDirectory.mkpath("."); bool noExistingAssets = !_resourcesDirectory.exists() \ || _resourcesDirectory.entryList(QDir::Files).size() == 0; if (noExistingAssets) { qDebug() << "Asset resources directory not found, searching for existing asset resources"; QString oldDataDirectory = QCoreApplication::applicationDirPath(); auto oldResourcesDirectory = QDir(oldDataDirectory).filePath("resources/" + RESOURCES_PATH); if (QDir(oldResourcesDirectory).exists()) { qDebug() << "Existing assets found in " << oldResourcesDirectory << ", copying to " << _resourcesDirectory; QDir resourcesParentDirectory = _resourcesDirectory.filePath(".."); if (!resourcesParentDirectory.exists()) { qDebug() << "Creating data directory " << resourcesParentDirectory.absolutePath(); resourcesParentDirectory.mkpath("."); } auto files = QDir(oldResourcesDirectory).entryList(QDir::Files); for (auto& file : files) { auto from = oldResourcesDirectory + QDir::separator() + file; auto to = _resourcesDirectory.absoluteFilePath(file); qDebug() << "\tCopying from " << from << " to " << to; QFile::copy(from, to); } } } qDebug() << "Serving files from: " << _resourcesDirectory.path(); // Scan for new files qDebug() << "Looking for new files in asset directory"; auto files = _resourcesDirectory.entryInfoList(QDir::Files); QRegExp filenameRegex { "^[a-f0-9]{" + QString::number(SHA256_HASH_HEX_LENGTH) + "}(\\..+)?$" }; for (const auto& fileInfo : files) { auto filename = fileInfo.fileName(); if (!filenameRegex.exactMatch(filename)) { qDebug() << "Found file: " << filename; if (!fileInfo.isReadable()) { qDebug() << "\tCan't open file for reading: " << filename; continue; } // Read file QFile file { fileInfo.absoluteFilePath() }; file.open(QFile::ReadOnly); QByteArray data = file.readAll(); auto hash = hashData(data); auto hexHash = hash.toHex(); qDebug() << "\tMoving " << filename << " to " << hexHash; file.rename(_resourcesDirectory.absoluteFilePath(hexHash) + "." + fileInfo.suffix()); } } }
int main(int argc, char *argv[]) { #ifdef _WIN32 freopen("stdout.txt", "w", stderr); # ifdef QT5 qInstallMessageHandler(myMessageOutput); # else qInstallMsgHandler(myMessageOutput); # endif #endif #if defined(Q_OS_MACX) // On Mac, switch working directory to resources folder CFURLRef pluginRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef macPath = CFURLCopyFileSystemPath(pluginRef, kCFURLPOSIXPathStyle); QString path( CFStringGetCStringPtr(macPath, CFStringGetSystemEncoding()) ); path += "/Contents/Resources"; QDir::setCurrent( path ); CFRelease(pluginRef); CFRelease(macPath); #elif defined(PO_DATA_REPO) QDir::setCurrent(PO_DATA_REPO); #endif bool quit = false; bool updated = false; for (int i = 0; i < argc; i++) { /* Update parameter: move file from one place to another. Called by commandline on windows when you need admin rights to update the auto updater for example */ if (strcmp(argv[i], "-update") == 0) { quit = true; if (i + 2 >= argc) { break; } QString dest = argv[++i]; QString src = argv[++i]; /* Todo: check if those 3 lines are necessary ? */ QFile s (dest); s.remove(); s.close(); QFile f (src); if (!f.rename(dest)) { //QMessageBox::critical(NULL, tr("Error during PO update"), tr("Couldn't update file %1.").arg(rel)); qCritical() << QString("Couldn't update file %1.").arg(dest); } } else if (strcmp(argv[i], "--updated") == 0) { updated = true; } } if (quit) { return 0; } srand(time(NULL)); try { //HotKeyClass HotKeyEvent; QApplication a(argc, argv); a.setQuitOnLastWindowClosed(true); //a.installEventFilter(&HotKeyEvent); /* Names to use later for QSettings */ QCoreApplication::setApplicationName("Pokemon-Online"); QCoreApplication::setOrganizationName("Dreambelievers"); QCoreApplication::setApplicationVersion(VERSION); QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuBar); QSettings settings; #if defined(Q_OS_MACX) // Check if there are updates using Sparkle CocoaInitializer initializer; //SparkleAutoUpdater* updater = new SparkleAutoUpdater; //updater->checkForUpdates(); #else // Auto updator and Icon are not applicable on Mac OSX // Mac OSX has it's own updater using Sparkle // Additionally, setting Icon here seems to break native OSX way. // /* icon ;) */ a.setWindowIcon(QIcon("db/icon.png")); //QSharedMemory memory("Pokemon Online at " + QDir().absolutePath()); if (settings.value("Updates/Ready").toBool()) { /* Check Updates/ReadyFor, match it with current updateId, then if true then set Updates/Ready to false and spawn the auto updater with the correct target directory and quit */ //Vals: Updates/Ready, Updates/ReadyFor, Updates/ReadyTarget (directory with updates) QSettings in("version.ini", QSettings::IniFormat); int readyFor = settings.value("Updates/ReadyFor").toInt(); if (readyFor == std::max(UPDATE_ID, in.value("updateId").toInt())) { /* Ensures that the PO process is the only one running */ if (settings.value("Updates/RunningTime").toInt() + 3*60 < ::time(NULL)) { //if (memory.create(20, QSharedMemory::ReadOnly)) { QString target = settings.value("Updates/ReadyTarget").toString(); if (testWritable()) { QProcess p; p.startDetached("./pomaintenance", QStringList() << "-src" << target << "-caller" << argv[0]); goto success; } else { #ifdef Q_OS_WIN qDebug() << "running as admin"; ::ShellExecute(0, // owner window L"runas", L"pomaintenance.exe", //update exe (LPCWSTR)(QString("-src '%1' -caller '%2'").arg(target, argv[0]).utf16()), // params 0, // directory SW_SHOWNORMAL); goto success; #else goto failure; #endif } success: settings.setValue("Updates/Ready", false); //In case any problem happens, we won't try to update again anyway //memory.detach(); return 0; #ifndef Q_OS_WIN failure:; /* The current dir is not writable, and no way to run an auto updater with the correct permission */ //memory.detach(); #endif } } } /* Share memory, so that we can make sure to know the number of other apps from the same folder running atm */ //if (!memory.create(20, QSharedMemory::ReadOnly)) { //memory.attach(QSharedMemory::ReadOnly); //} #endif if (settings.value("language").isNull()) { settings.setValue("language", QLocale::system().name().section('_', 0, 0)); } QString locale = settings.value("language").toString(); qtTranslator.load(QString("qt_") + locale, QLibraryInfo::location(QLibraryInfo::TranslationsPath)); a.installTranslator(&qtTranslator); translator.load(QString("trans/translation_%1").arg(locale)); a.installTranslator(&translator); MainEngine w(updated); return a.exec(); } /*catch (const std::exception &e) { qDebug() << "Caught runtime " << e.what(); } catch (const QString &s) { qDebug() << "Caught string " << s; } */catch (const char* s) { qDebug() << "Caught const char* " << s; } /*catch (...) { qDebug() << "Caught Exception."; }*/ return 0; }
void SecurityManager::loadMembers() { if (isSql()) { loadSqlMembers(); return; } const char *path = "serverdb/members.txt"; const char *backup = "serverdb/members.backup.txt"; { QDir d; d.mkdir("serverdb"); } if (!QFile::exists(path) && QFile::exists(backup)) { QFile::rename(backup, path); } memberFile.setFileName(path); if (!memberFile.open(QFile::ReadWrite)) { throw QObject::tr("Error: cannot open the file that contains the members (%1)").arg(path); } int pos = memberFile.pos(); while (!memberFile.atEnd()) { QByteArray arr = memberFile.readLine(); QString s = QString::fromUtf8(arr.constData(), std::max(0,arr.length()-1)); //-1 to remove the \n QStringList ls = s.split('%'); if (ls.size() >= 6 && isValid(ls[0])) { Member m (ls[0], ls[1].trimmed(), ls[2][0].toLatin1() - '0', ls[2][1] == '1', ls[3].trimmed().toLatin1(), ls[4].trimmed().toLatin1(), ls[5].trimmed()); if (ls.size() >= 7) { m.ban_expire_time = ls[6].toInt(); } m.filepos = pos; members[ls[0]] = m; /* Update pos for next iteration */ pos = memberFile.pos(); if (m.isBanned()) { bannedIPs.insert(m.ip, m.ban_expire_time); bannedMembers.insert(m.name.toLower(), std::pair<QString, int>(m.ip, m.ban_expire_time)); } if (m.authority() > 0) { authed.insert(m.name); } playersByIp.insert(m.ip, m.name); } lastPlace = memberFile.pos(); } //We also clean up the file by rewritting it with only the valid contents QFile temp (backup); if (!temp.open(QFile::WriteOnly | QFile::Truncate)) throw QObject::tr("Impossible to change %1").arg(backup); pos = temp.pos(); for(auto it = members.begin(); it != members.end(); ++it) { Member &m = it->second; m.write(&temp); m.filepos = pos; pos = temp.pos(); } lastPlace = temp.pos(); temp.flush(); memberFile.remove(); if (!temp.rename(path)) { throw QObject::tr("Error: cannot rename the file that contains the members (%1 -> %2)").arg(backup).arg(path); } temp.rename(path); if (!memberFile.open(QFile::ReadWrite)) { throw QObject::tr("Error: cannot reopen the file that contains the members (%1)").arg(path); } }
/*========================================================================= cutFromClipboard =========================================================================*/ bool KFileBrowser::cutFromClipboard (const FileClipboard *fc) { const QStringList &names = fc->getNames(); QMessageBox msgBox; msgBox.setText(tr("Confirm move")); if (names.count() == 1) msgBox.setInformativeText (tr("Do you want to move this item?")); else { char ss[20]; sprintf (ss, "%d", names.count()); msgBox.setInformativeText ((QString)tr("Do you want to move these") + " " + ss + " " + tr ("items") + "?"); } msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); int r = msgBox.exec(); if (r != QMessageBox::Ok) return false; bool ret = FALSE; const QString &root = fc->getRoot(); int l = names.count(); int itemsDone = 0; QProgressDialog progress (tr("Moving files..."), tr("Stop"), 0, l, this); progress.setWindowModality (Qt::WindowModal); progress.setMinimumDuration (0); progress.show(); bool stop = false; QString errorMessage = ""; for (int i = 0; i < l && !progress.wasCanceled() &&!stop; i++) { QString sourceName = root + "/" + names[i]; QString targetName; if (fc->getPasteByNameOnly()) { QFileInfo info (path + "/" + names[i]); QString shortName = info.fileName(); targetName = path + "/" + shortName; } else targetName = path + "/" + names[i]; errorMessage = ""; if (sourceName == targetName) { errorMessage = tr ("Source and destination files are the same"); } else { QFileInfo info (sourceName); if (info.isDir()) { QDir dir; if (dir.rename (sourceName, targetName)) itemsDone++; else errorMessage = tr("Can't move directory"); } else { QFile file; if (file.rename (sourceName, targetName)) itemsDone++; else errorMessage = tr("Can't move file"); } } if (errorMessage != "") { if (i < l - 1) { QMessageBox msgBox; msgBox.setText(tr("Error copying file")); msgBox.setInformativeText (errorMessage + ". " + tr("Do you want to coninue with the next item?")); msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox.setDefaultButton(QMessageBox::Cancel); int ret = msgBox.exec(); if (ret != QMessageBox::Ok) stop = true; } else error (errorMessage); } progress.setValue (i); } if (progress.wasCanceled()) message ("canceled"); progress.setValue (l); ret = true; if (stop) ret = false; if (progress.wasCanceled()) ret = false; if (errorMessage != "") ret = false; emit dirContentsChanged(); QString sm = tr("Moved"); char ss[20]; sprintf (ss, "%d", itemsDone); sm += ss; sm += " " + (itemsDone == 1 ? tr("items") : tr("items")); emit statusUpdate (sm); return ret; }
void ImportConfig::on_cmdImport_clicked() { if (!m_ui->txtExistingOvpn->text().isEmpty()) { // Import existing file QString configName (m_ui->txtExistingOvpn->text().replace(".ovpn", "")); configName = configName.right(configName.size() - configName.lastIndexOf("/") - 1); // Anderer name als Dateiname if (m_ui->rbSaveAsName->isChecked()) { if (!m_ui->txtNewName->text().isEmpty()) { configName = m_ui->txtNewName->text(); } } QString pathToConfig (m_ui->txtExistingOvpn->text()); // Copy config to local app data and rename it, if an other name is specified // Only in service mode! if(!Settings::getInstance()->getIsPortableClient()) { // If file is available copy it // First create folder QString newConfigFolderPath (QString("%1/config/%2") .arg(AppFunc::getAppSavePath()) .arg(configName)); QDir newConfigFolderPathDirectory (newConfigFolderPath); if (newConfigFolderPathDirectory.exists(newConfigFolderPath)){ // A config with this name is already existing Message::error(QObject::tr("A configuration with this name is already existing!")); // return; } // Create path newConfigFolderPathDirectory.mkpath(newConfigFolderPath); // Now copy Files QString newConfigPath (QString("%1/%2.ovpn") .arg(newConfigFolderPath) .arg(configName)); QFile::copy(pathToConfig, newConfigPath); // QString sourceDirectory (pathToConfig.left(pathToConfig.lastIndexOf("/"))); // // Override old path pathToConfig = newConfigPath; // Ca auto copyConfigFile = [&](const QString &key) { auto keyValue = (ConfigValues::instance()->valueFromConfigKey(pathToConfig, key)); if(!keyValue.isEmpty()) { QString sourcePath (QString("%1/%2") .arg(sourceDirectory) .arg(keyValue)); QString destName (keyValue); if (ConfigValues::instance()->isGivenPathAbsolute(keyValue)) { // Yes, override path sourcePath = keyValue; // Get the file name from path destName = ConfigValues::instance()->fileNameOfAbsolutePath(keyValue); // Change value in config ConfigValues::instance()->changeKeyValueInConfig(pathToConfig, key, QString("\"%1\"") .arg(destName)); } // Copy QFile::copy(sourcePath, QString("%1/%2") .arg(newConfigFolderPath) .arg(destName)); } }; for(const auto &key : keys) { copyConfigFile(key); } } Preferences::instance()->addNewConfigToDatabase(configName, pathToConfig); Preferences::instance()->refreshConfigList(); Preferences::instance()->setConnectionStatus(); Preferences::instance()->setIcon(); // Fertig Message::information(QObject::tr("Import successfully ended!"), QObject::tr("Import Configuration")); Preferences::instance()->refreshDialog(); this->close(); } else { // Import crypt file if (m_ui->txtPassword->text().isEmpty()) { Message::error(QObject::tr("No password specified!"), QObject::tr("Import Configuration")); return; } if (!m_ui->txtImportPath->text().isEmpty()) { if (m_ui->rbSaveAsName->isChecked() && m_ui->txtNewName->text().isEmpty()) { Message::error(QObject::tr("No import name specified!"), QObject::tr("Import Configuration")); return; } // Portale oder install QString dirPath; QString configName; if (!m_ui->rbSaveAsName->isChecked()) { configName = m_ui->txtImportPath->text().right(m_ui->txtImportPath->text().size() - m_ui->txtImportPath->text().lastIndexOf("/") -1); configName = configName.left(configName.size()-6); } else { configName = m_ui->txtNewName->text().trimmed(); } dirPath = AppFunc::getAppSavePath() + QString ("/config/") + configName; // Verzeichnis da? QDir dirobj (dirPath); if (!dirobj.exists(dirPath)){ //Verzeichnis existiert nicht // Pfad erstellen if (!dirobj.mkpath(dirPath)) { // Pfad konnte nicht erstellt werden Message::error(QObject::tr("Unable to create directory!"), QObject::tr("Import Configuration")); return; } } else { // Verzeichnis existiert Message::error(QObject::tr("A diretory with this name already exists!"), QObject::tr("Import Configuration")); return; } // Datei ins neue Verzeichnis kopieren //QFile importFileCrypt (m_ui->txtImportPath->text()); QString packFile = dirPath + QString("/") + configName + QString(".zip"); // Erstmal entschlüsseln if(QFile::exists(packFile)) { QFile::remove(packFile); } // Die Daten einlesen { QFile crypted (m_ui->txtImportPath->text()); if (crypted.open(QIODevice::ReadOnly)) { // Nun das Ziel öfffnen QFile targetFile (packFile); if (targetFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { // Alles offen, kann losgehen QByteArray data = crypted.readAll(); Crypt crypt; crypt.setSecretKey(m_ui->txtPassword->text()); targetFile.write(crypt.cryptToPlainTextExt(data)); targetFile.waitForBytesWritten(3000); targetFile.flush(); targetFile.waitForBytesWritten(3000); // Alles Ok targetFile.close(); crypted.close(); } } else { Message::error(QObject::tr("Can't open crypted file")); return; } } // Nun die Datei entpacken if (!Zip::extract(packFile, dirPath)) { Message::error(QObject::tr("Can't open zip file")); return; } // Nun ist alles entpackt, das Ziparchiv nun löschen QFile configZip (packFile); if (!configZip.remove()) { Message::error(configZip.errorString(), QObject::tr("Import Configuration")); } QString saveName; QString savePath; QString ovpnFilePath = m_ui->txtImportPath->text().right(m_ui->txtImportPath->text().size() - m_ui->txtImportPath->text().lastIndexOf("/") -1); saveName = ovpnFilePath.left(ovpnFilePath.size()-6); savePath = dirPath + QString("/") + ovpnFilePath.left(ovpnFilePath.size()-6) + QString(".ovpn"); if (m_ui->rbSaveAsName->isChecked()) { // ovpn umbennen QFile ovpnFile (savePath); if (ovpnFile.exists()) { // umbenennen ovpnFile.rename(dirPath + QString("/") + configName + QString(".ovpn")); saveName = configName; } } savePath = dirPath + QString("/") + saveName + QString(".ovpn"); QFile ovpnFile (dirPath + QString("/") + configName + QString(".ovpn")); if (!ovpnFile.exists()) { Message::error(QObject::tr("Import failed! Removing empty directory."), QObject::tr("Import Configuration")); dirobj.rmdir(dirPath); } else { Preferences::instance()->addNewConfigToDatabase(saveName, savePath.replace("\\", "/")); Preferences::instance()->refreshConfigList(); Preferences::instance()->setConnectionStatus(); Message::information(QObject::tr("Import successfully ended!"), QObject::tr("Import Configuration")); Preferences::instance()->refreshDialog(); Preferences::instance()->setIcon(); this->close(); } } else { Message::error(QObject::tr("No import file selected!"), QObject::tr("Import Configuration")); } } }