Esempio n. 1
0
int ArchiveExtractor::getFileInfoList(const QString &path,
                                      std::vector<ArchiveFileInfo> &list) const
{
    QFile archiveFile(path);

    // Try to open as ZIP
    QuaZip zip(&archiveFile);
    if (zip.open(QuaZip::mdUnzip))
    {
        zip.setFileNameCodec("UTF-8");
        QList<QuaZipFileInfo> zipList = zip.getFileInfoList();
        while(!zipList.empty())
        {
            const QuaZipFileInfo fi = zipList.takeLast();
            list.emplace_back(fi.name, fi.dateTime, fi.uncompressedSize);
        }
        zip.close();
        if (zip.getZipError() != UNZ_OK)
        {
            qWarning("testRead(): zip.close(): %d", zip.getZipError());
            return 1;
        }
        return 0;
    }

    // Try to open as RAR
    if (ArchiveRar::loadlib())
    {
        if (ArchiveRar::getFileInfoList(path, list) == 0)
        {
            return 0;
        }
    }
    return 1;
}
Esempio n. 2
0
void DurationUpdaterZip::run(ThreadWeaver::JobPointer, ThreadWeaver::Thread *)
{
    OkArchive archiveFile(m_fileName);
    int duration = archiveFile.getSongDuration();
    if (duration == -1)
    {
        qWarning() << "Unable to get duration for file: " << m_fileName;
        return;
    }
    QSqlQuery query;
    query.exec("UPDATE dbsongs SET duration = " + QString::number(duration) + " WHERE path == \"" + m_fileName + "\"");
}
Esempio n. 3
0
bool LineConfigDataManager::Persistent()
{
	//std::ofstream ofs(PERSISTENT_FILE);
    //assert(ofs.good());

    //boost::archive::xml_oarchive oa(ofs);
	//boost::archive::text_oarchive oa(ofs);

	acutPrintf(L"开始保存管线类型\n");

	CFile archiveFile(PERSISTENT_FILE,CFile::modeCreate|CFile::modeWrite);

	typedef vector<LineCategoryItemData*>::const_iterator DataIterator;

	//遍历所有的类型定义
	for( DataIterator iter = mLineConfigData->begin(); 
			iter != mLineConfigData->end(); 
			iter++)
	{
		LineCategoryItemData* data = *iter;

		if( data )
		{
			//得到消息的宽字符序列化
			wstring wData = data->toString();

			//转为窄字符
			string dataStr = WstringToString(wData);

			//acutPrintf(L"管线类型数据 [%s] [%d]\n",wData.c_str(),(UINT)dataStr.length());

			//使用 virtual void Write( const void* lpBuf, UINT nCount ); 将窄字符写入文件
			archiveFile.Write(dataStr.c_str(),dataStr.size());

			//oa << BOOST_SERIALIZATION_NVP(*data);
			//oa << *data;
		}
	}

	acutPrintf(L"管线类型保存完成\n");
	archiveFile.Close();

	return true;
}
Esempio n. 4
0
void SelfUpdater::DownloadFinished()
{
    if(currentDownload)
    {
        FileManager::Instance()->ClearTempDirectory();

        const QString & archiveFilePath = FileManager::Instance()->GetTempDownloadFilepath();
        const QString & tempDir = FileManager::Instance()->GetTempDirectory();
        const QString & appDir = FileManager::Instance()->GetLauncherDirectory();
        const QString & selfUpdateDir = FileManager::Instance()->GetSelfUpdateTempDirectory();

        QFile archiveFile(archiveFilePath);
        archiveFile.open(QFile::WriteOnly);
        archiveFile.write(currentDownload->readAll());
        archiveFile.close();

        currentDownload->deleteLater();
        currentDownload = 0;

        unpacker->UnZipFile(archiveFilePath, selfUpdateDir);

        FileManager::Instance()->MoveFilesOnlyToDirectory(appDir, tempDir);
        FileManager::Instance()->MoveFilesOnlyToDirectory(selfUpdateDir, appDir);
        FileManager::Instance()->DeleteDirectory(selfUpdateDir);

        ErrorMessanger::Instance()->ShowNotificationDlg("Launcher was updated. Please, relaunch application.");

        qApp->exit();
    }
    else if(lastErrorCode != QNetworkReply::OperationCanceledError)
    {
        setResult(QDialog::Rejected);
        ErrorMessanger::Instance()->ShowErrorMessage(ErrorMessanger::ERROR_NETWORK, lastErrorCode, lastErrorDesrc);
        close();
    }
}
Esempio n. 5
0
void PackageManager::archivePath(const char * pFilePath)
{
#ifdef WIN32
	if (!pFilePath || pFilePath[0] == 0) {
		return;
	}

    WIN32_FIND_DATAA FindFileData;
    HANDLE hFind = INVALID_HANDLE_VALUE;
    char DirSpec[MAX_PATH + 1];// 指定路径
    DWORD dwError;

    strncpy (DirSpec, pFilePath, strlen(pFilePath) + 1);
	if (pFilePath[strlen(pFilePath) - 1] == '/') {
		strncat(DirSpec, "*", 2);
	} else {
		strncat(DirSpec, "/*", 3);
	}

    hFind = FindFirstFileA(DirSpec, &FindFileData);

    if (hFind == INVALID_HANDLE_VALUE) {
        printf ("Invalid file handle. Error is %u ", GetLastError());
        return ;
    }

    if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
		archiveFile(FindFileData.cFileName, pFilePath);
	} else if((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        && strcmp(FindFileData.cFileName, ".") != 0
        && strcmp(FindFileData.cFileName, "..") != 0
		&& strcmp(FindFileData.cFileName, ".svn") != 0) {   //找到目录
        char Dir[MAX_PATH + 1];
        strcpy(Dir, pFilePath);
		if (pFilePath[strlen(pFilePath) - 1] != '/') {
			 strncat(Dir, "/", 2);
		}

        strcat(Dir, FindFileData.cFileName);
        archivePath(Dir);
    }

    while (FindNextFileA(hFind, &FindFileData) != 0)
    {
        if (!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {   //找到文件
			archiveFile(FindFileData.cFileName, pFilePath);
        } else if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
            && strcmp(FindFileData.cFileName, ".") != 0
            && strcmp(FindFileData.cFileName, "..") != 0
			&& strcmp(FindFileData.cFileName, ".svn") != 0) { //找到目录
            char Dir[MAX_PATH + 1];
            strcpy(Dir, pFilePath);
			if (pFilePath[strlen(pFilePath) - 1] != '/') {
				 strncat(Dir, "/", 2);
			}
            strcat(Dir, FindFileData.cFileName);
            archivePath(Dir);
		}
    }

    dwError = GetLastError();
    FindClose(hFind);

    if (dwError != ERROR_NO_MORE_FILES) {
        printf ("FindNextFile error. Error is %u ", dwError);
        return;
    }
#endif
}
Esempio n. 6
0
int Awstats::update(const HttpVHost * pVHost )
{
    // rotate current access log file to access.log.awstats
    const char * pLogPath;
    int ret;
    pLogPath = pVHost->getAccessLogPath();
    if ( !pLogPath )
    {
        LOG_ERR(( "Virtual host [%s] must use its own access log, "
                  "in order to use awstats", pVHost->getName() ));
        return -1;
    }

    if ( prepareAwstatsEnv( pVHost ) )
        return -1;
    
    ret = renameLogFile( pLogPath, "", ".awstats" );
    LOG4CXX_NS::LogRotate::postRotate( pVHost->getAccessLog()->getAppender(),
                        HttpGlobals::s_uid, HttpGlobals::s_gid);
    if ( ret == -1 )
    {
        return -1;
    }
    
    int pid = fork();
    if ( pid )
    {
        //parent process or error
        return (pid == -1)? pid : 0;
    }

    // child process
    // fork again
    pid = fork();
    if ( pid < 0)
        LOG_ERR(( "fork() failed" ));
    else if ( pid == 0 )
    {
        if ( HttpGlobals::s_psChroot )
        {
            chroot( HttpGlobals::s_psChroot->c_str() );
        }
        if ( pVHost->getRootContext().getSetUidMode() == UID_DOCROOT )
        {
            setuid( pVHost->getUid() );
        }
        else
            setuid( HttpGlobals::s_uid );
        executeUpdate( pVHost->getName() );
        exit( 0 );
    }
    else
        waitpid( pid, NULL, 0 );

    // rotate again and compress if required
    if ( archiveFile( pLogPath, ".awstats",
            pVHost->getAccessLog()->getCompress(),
            HttpGlobals::s_uid, HttpGlobals::s_gid ) == -1 )
    {
        char achBuf[1024];
        safe_snprintf( achBuf, 1024, "%s%s", pLogPath, ".awstats" );
        unlink( achBuf );
        LOG_ERR(( "Unable to rename [%s], remove it.", achBuf ));
    }
    exit( 0 );
}
Esempio n. 7
0
void Archive::save(Basket *basket, bool withSubBaskets, const QString &destination)
{
	QDir dir;
	KProgressDialog dialog(0, i18n("Save as Basket Archive"), i18n("Saving as basket archive. Please wait..."), /*Not modal, for password dialogs!*/false);
	dialog.showCancelButton(false);
	dialog.setAutoClose(true);
	dialog.show();
	QProgressBar *progress = dialog.progressBar();
    
    progress->setRange(0,/*Preparation:*/1 + /*Finishing:*/1 + /*Basket:*/1 + /*SubBaskets:*/(withSubBaskets ? Global::bnpView->basketCount(Global::bnpView->listViewItemForBasket(basket)) : 0));
	progress->setValue(0);

	// Create the temporary folder:
	QString tempFolder = Global::savesFolder() + "temp-archive/";
	dir.mkdir(tempFolder);

	// Create the temporary archive file:
	QString tempDestination = tempFolder + "temp-archive.tar.gz";
	KTar tar(tempDestination, "application/x-gzip");
	tar.open(QIODevice::WriteOnly);
	tar.writeDir("baskets", "", "");

    progress->setValue(progress->value()+1);        // Preparation finished
    
	kDebug() << "Preparation finished out of " << progress->maximum();

	// Copy the baskets data into the archive:
	QStringList backgrounds;
	Archive::saveBasketToArchive(basket, withSubBaskets, &tar, backgrounds, tempFolder, progress);

	// Create a Small baskets.xml Document:
	QDomDocument document("basketTree");
	QDomElement root = document.createElement("basketTree");
	document.appendChild(root);
	Global::bnpView->saveSubHierarchy(Global::bnpView->listViewItemForBasket(basket), document, root, withSubBaskets);
	Basket::safelySaveToFile(tempFolder + "baskets.xml", "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + document.toString());
	tar.addLocalFile(tempFolder + "baskets.xml", "baskets/baskets.xml");
	dir.remove(tempFolder + "baskets.xml");

	// Save a Small tags.xml Document:
	QList<Tag*> tags;
	listUsedTags(basket, withSubBaskets, tags);
	Tag::saveTagsTo(tags, tempFolder + "tags.xml");
	tar.addLocalFile(tempFolder + "tags.xml", "tags.xml");
	dir.remove(tempFolder + "tags.xml");

	// Save Tag Emblems (in case they are loaded on a computer that do not have those icons):
	QString tempIconFile = tempFolder + "icon.png";
	for (Tag::List::iterator it = tags.begin(); it != tags.end(); ++it) {
		State::List states = (*it)->states();
		for (State::List::iterator it2 = states.begin(); it2 != states.end(); ++it2) {
			State *state = (*it2);
			QPixmap icon = KIconLoader::global()->loadIcon(
                state->emblem(), KIconLoader::Small, 16, KIconLoader::DefaultState,
                QStringList(), 0L, true
                );
			if (!icon.isNull()) {
				icon.save(tempIconFile, "PNG");
				QString iconFileName = state->emblem().replace('/', '_');
				tar.addLocalFile(tempIconFile, "tag-emblems/" + iconFileName);
			}
		}
	}
	dir.remove(tempIconFile);

	// Finish Tar.Gz Exportation:
	tar.close();

	// Computing the File Preview:
	Basket *previewBasket = basket; // FIXME: Use the first non-empty basket!
	QPixmap previewPixmap(previewBasket->visibleWidth(), previewBasket->visibleHeight());
	QPainter painter(&previewPixmap);
	// Save old state, and make the look clean ("smile, you are filmed!"):
	NoteSelection *selection = previewBasket->selectedNotes();
	previewBasket->unselectAll();
	Note *focusedNote = previewBasket->focusedNote();
	previewBasket->setFocusedNote(0);
	previewBasket->doHoverEffects(0, Note::None);
	// Take the screenshot:
	previewBasket->drawContents(&painter, 0, 0, previewPixmap.width(), previewPixmap.height());
	// Go back to the old look:
	previewBasket->selectSelection(selection);
	previewBasket->setFocusedNote(focusedNote);
	previewBasket->doHoverEffects();
	// End and save our splandid painting:
	painter.end();
	QImage previewImage = previewPixmap.toImage();
	const int PREVIEW_SIZE = 256;
	previewImage = previewImage.scaled(PREVIEW_SIZE, PREVIEW_SIZE, Qt::KeepAspectRatio);
	previewImage.save(tempFolder + "preview.png", "PNG");

	// Finaly Save to the Real Destination file:
	QFile file(destination);
	if (file.open(QIODevice::WriteOnly)) {
		ulong previewSize = QFile(tempFolder + "preview.png").size();
		ulong archiveSize = QFile(tempDestination).size();
		QTextStream stream(&file);
		stream.setCodec("ISO-8859-1");
		stream << "BasKetNP:archive\n"
		       << "version:0.6.1\n"
//		       << "read-compatible:0.6.1\n"
//		       << "write-compatible:0.6.1\n"
		       << "preview*:" << previewSize << "\n";

		stream.flush();
		// Copy the Preview File:
		const unsigned long BUFFER_SIZE = 1024;
		char *buffer = new char[BUFFER_SIZE];
		long sizeRead;
		QFile previewFile(tempFolder + "preview.png");
		if (previewFile.open(QIODevice::ReadOnly)) {
			while ((sizeRead = previewFile.read(buffer, BUFFER_SIZE)) > 0)
				file.write(buffer, sizeRead);
		}
		stream << "archive*:" << archiveSize << "\n";
		stream.flush();

		// Copy the Archive File:
		QFile archiveFile(tempDestination);
		if (archiveFile.open(QIODevice::ReadOnly)) {
			while ((sizeRead = archiveFile.read(buffer, BUFFER_SIZE)) > 0)
				file.write(buffer, sizeRead);
		}
		// Clean Up:
		delete buffer;
		buffer = 0;
		file.close();
	}

    progress->setValue(progress->value()+1); // Finishing finished
	kDebug() << "Finishing finished";

	// Clean Up Everything:
	dir.remove(tempFolder + "preview.png");
	dir.remove(tempDestination);
	dir.rmdir(tempFolder);
}
Esempio n. 8
0
void Archive::open(const QString &path)
{
	// Create the temporar folder:
	QString tempFolder = Global::savesFolder() + "temp-archive/";
	QDir dir;
	dir.mkdir(tempFolder);
	const qint64 BUFFER_SIZE = 1024;

	QFile file(path);
	if (file.open(QIODevice::ReadOnly)) {
		QTextStream stream(&file);
		stream.setCodec("ISO-8859-1");
		QString line = stream.readLine();
		if (line != "BasKetNP:archive") {
			KMessageBox::error(0, i18n("This file is not a basket archive."), i18n("Basket Archive Error"));
			file.close();
			Tools::deleteRecursively(tempFolder);
			return;
		}
		QString version;
		QStringList readCompatibleVersions;
		QStringList writeCompatibleVersions;
		while (!stream.atEnd()) {
			// Get Key/Value Pair From the Line to Read:
			line = stream.readLine();
			int index = line.indexOf(':');
			QString key;
			QString value;
			if (index >= 0) {
				key = line.left(index);
				value = line.right(line.length() - index - 1);
			} else {
				key = line;
				value = "";
			}
			if (key == "version") {
				version = value;
			} else if (key == "read-compatible") {
				readCompatibleVersions = value.split(";");
			} else if (key == "write-compatible") {
				writeCompatibleVersions = value.split(";");
			} else if (key == "preview*") {
				bool ok;
				qint64 size = value.toULong(&ok);
				if (!ok) {
					KMessageBox::error(0, i18n("This file is corrupted. It can not be opened."), i18n("Basket Archive Error"));
					file.close();
					Tools::deleteRecursively(tempFolder);
					return;
				}
				// Get the preview file:
//FIXME: We do not need the preview for now
//				QFile previewFile(tempFolder + "preview.png");
//				if (previewFile.open(QIODevice::WriteOnly)) {
					stream.seek(stream.pos()+size);
			} else if (key == "archive*") {
				if (version != "0.6.1" && readCompatibleVersions.contains("0.6.1") && !writeCompatibleVersions.contains("0.6.1")) {
					KMessageBox::information(
						0,
						i18n("This file was created with a recent version of %1. "
						     "It can be opened but not every information will be available to you. "
						     "For instance, some notes may be missing because they are of a type only available in new versions. "
						     "When saving the file back, consider to save it to another file, to preserve the original one.",
							KGlobal::mainComponent().aboutData()->programName()),
						i18n("Basket Archive Error")
					);
				}
				if (version != "0.6.1" && !readCompatibleVersions.contains("0.6.1") && !writeCompatibleVersions.contains("0.6.1")) {
					KMessageBox::error(
						0,
						i18n("This file was created with a recent version of %1. Please upgrade to a newer version to be able to open that file.",
                            KGlobal::mainComponent().aboutData()->programName()),
						i18n("Basket Archive Error")
					);
					file.close();
					Tools::deleteRecursively(tempFolder);
					return;
				}

				bool ok;
				qint64 size = value.toULong(&ok);
				if (!ok) {
					KMessageBox::error(0, i18n("This file is corrupted. It can not be opened."), i18n("Basket Archive Error"));
					file.close();
					Tools::deleteRecursively(tempFolder);
					return;
				}

				Global::mainWindow()->raise();

				// Get the archive file:
				QString tempArchive = tempFolder + "temp-archive.tar.gz";
				QFile archiveFile(tempArchive);
				file.seek(stream.pos());
				if (archiveFile.open(QIODevice::WriteOnly)) {
					char *buffer = new char[BUFFER_SIZE];
					qint64 sizeRead;
					while ((sizeRead = file.read(buffer, qMin(BUFFER_SIZE, size))) > 0) {
						archiveFile.write(buffer, sizeRead);
						size -= sizeRead;
					}
					archiveFile.close();
					delete buffer;

					// Extract the Archive:
					QString extractionFolder = tempFolder + "extraction/";
					QDir dir;
					dir.mkdir(extractionFolder);
					KTar tar(tempArchive, "application/x-gzip");
					tar.open(QIODevice::ReadOnly);
					tar.directory()->copyTo(extractionFolder);
					tar.close();

					// Import the Tags:
					importTagEmblems(extractionFolder); // Import and rename tag emblems BEFORE loading them!
					QMap<QString, QString> mergedStates = Tag::loadTags(extractionFolder + "tags.xml");
					QMap<QString, QString>::Iterator it;
					if (mergedStates.count() > 0) {
						Tag::saveTags();
					}

					// Import the Background Images:
					importArchivedBackgroundImages(extractionFolder);

					// Import the Baskets:
					renameBasketFolders(extractionFolder, mergedStates);
					stream.seek(file.pos());

				}
			} else if (key.endsWith("*")) {
				// We do not know what it is, but we should read the embedded-file in order to discard it:
				bool ok;
				qint64 size = value.toULong(&ok);
				if (!ok) {
					KMessageBox::error(0, i18n("This file is corrupted. It can not be opened."), i18n("Basket Archive Error"));
					file.close();
					Tools::deleteRecursively(tempFolder);
					return;
				}
				// Get the archive file:
				char *buffer = new char[BUFFER_SIZE];
				qint64 sizeRead;
				while ((sizeRead = file.read(buffer, qMin(BUFFER_SIZE, size))) > 0) {
					size -= sizeRead;
				}
				delete buffer;
			} else {
				// We do not know what it is, and we do not care.
			}
			// Analyse the Value, if Understood:
		}
		file.close();
	}
	Tools::deleteRecursively(tempFolder);
}