Ejemplo n.º 1
0
/* Clears the web cache, because Qt 5.2 WebView chokes on caches from
 * older Qt versions.
 */
void clearWebCache()
{
    const QStringList cachePaths = QStandardPaths::standardLocations(
                QStandardPaths::CacheLocation);

    if (cachePaths.size())
    {
        // some very old versions of SailfishOS may not find this cache,
        // but that's OK since they don't have the web cache bug anyway
        const QString tidingsWebCache =
                QDir(cachePaths.at(0)).filePath(".QtWebKit");
        QDir cacheDir(tidingsWebCache);
        if (cacheDir.exists())
        {
            if (cacheDir.removeRecursively())
            {
                qDebug() << "Cleared web cache:" << tidingsWebCache;
            }
            else
            {
                qDebug() << "Failed to clear web cache:" << tidingsWebCache;
            }
        }
        else
        {
            qDebug() << "Web cache does not exist:" << tidingsWebCache;
        }
    }
    else
    {
        qDebug() << "No web cache available.";
    }
}
Ejemplo n.º 2
0
void SFtpFileEngine::readDir(const QString &dir)
{
    QString cacheDir(getCachePath(dir, true));

    _fileInfoCache->removeDirInfo(cacheDir);

    // add an empty entry to distinguish a empty directory from
    // a non-existent directory
    _fileInfoCache->addFileInfo(cacheDir, QUrlInfo());

    LIBSSH2_SFTP_HANDLE* dir_handle;

    dir_handle = libssh2_sftp_opendir(_sftp_session,
                                      _textCodec->fromUnicode(dir).data());
    if (dir_handle)
    {
        QByteArray entry(512, 0);
        QByteArray longEntry(512, 0);
        LIBSSH2_SFTP_ATTRIBUTES attr;

        while (libssh2_sftp_readdir_ex(dir_handle, entry.data(),
                                       entry.capacity(), longEntry.data(),
                                       longEntry.capacity(), &attr) > 0)
        {
            QString entryUni(_textCodec->toUnicode(entry.data()));

            QUrlInfo urlInfo;
            attr2urlinfo(&urlInfo, entryUni, &attr);

            _fileInfoCache->addFileInfo(cacheDir, urlInfo);
        }

        libssh2_sftp_closedir(dir_handle);
    }
}
Ejemplo n.º 3
0
void setupXDGVars()
{
	gcString homeDir(getenv("HOME")); // Used for falling back.
	gcString configDir(getenv("XDG_CONFIG_HOME"));
	gcString cacheDir(getenv("XDG_CACHE_HOME"));

	if (homeDir.empty())
	{
		// Below we just use 'falling back' and don't note we're setting it,
		// but as $HOME is referenced later on it might confuse anybody reading the
		// logs.
		// Also use 'passwd' instead of 'password' as that may freak out some users.
		printf("$HOME not set, temporarily setting it to the user's passwd entry.");

		struct passwd* pass = getpwuid(getuid());
		homeDir = pass->pw_dir;
	}

	if (configDir.empty())
	{
		printf("$XDG_CONFIG_HOME not set, falling back to $HOME/.config.");
		configDir = homeDir + "/.config";
	}

	if (cacheDir.empty())
	{
		printf("$XDG_CACHE_HOME not set, falling back to $HOME/.cache.");
		cacheDir = homeDir + "/.cache";
	}

	setenv("HOME", homeDir.c_str(), 1);
	setenv("XDG_CONFIG_HOME", configDir.c_str(), 1);
	setenv("XDG_CACHE_HOME", cacheDir.c_str(), 1);
}
Ejemplo n.º 4
0
// Loads a revision from the cache
Revision *Cache::get(const std::string &id)
{
	if (!m_loaded) {
		load();
	}

	std::string dir = cacheDir();
	std::pair<uint32_t, uint32_t> offset = m_index[id];
	std::string path = str::printf("%s/cache.%u", dir.c_str(), offset.first);
	if (m_cin == NULL || offset.first != m_ciindex) {
		delete m_cin;
		m_cin = new BIStream(path);
		m_ciindex = offset.first;
		if (!m_cin->ok()) {
			throw PEX(str::printf("Unable to read from cache file: %s", path.c_str()));
		}
	}
	if (!m_cin->seek(offset.second)) {
		throw PEX(str::printf("Unable to read from cache file: %s", path.c_str()));
	}

	Revision *rev = new Revision(id);
	std::vector<char> data;
	*m_cin >> data;
	data = utils::uncompress(data);
	if (data.empty()) {
		throw PEX(str::printf("Unable to read from cache file: %s", path.c_str()));
	}
	MIStream rin(data);
	if (!rev->load03(rin)) {
		throw PEX(str::printf("Unable to read from cache file: %s", path.c_str()));
	}
	return rev;
}
Ejemplo n.º 5
0
void lmcMainWindow::stop(void) {
	//	These settings are saved only if the window was opened at least once by the user
	if(windowLoaded) {
		pSettings->setValue(IDS_WINDOWMAIN, saveGeometry());
		pSettings->setValue(IDS_MINIMIZEMSG, showMinimizeMsg, IDS_MINIMIZEMSG_VAL);
	}

	pSettings->beginWriteArray(IDS_GROUPEXPHDR);
	for(int index = 0; index < ui.tvUserList->topLevelItemCount(); index++) {
		pSettings->setArrayIndex(index);
		pSettings->setValue(IDS_GROUP, ui.tvUserList->topLevelItem(index)->isExpanded());
	}
	pSettings->endArray();

	pTrayIcon->hide();

	//	delete all temp files from cache
	QDir cacheDir(StdLocation::cacheDir());
	if(!cacheDir.exists())
		return;
    QDir::Filters filters = QDir::Files | QDir::Readable;
    QDir::SortFlags sort = QDir::Name;
    //  save all cached conversations to history, then delete the files
    QString filter = "msg_*.tmp";
    lmcMessageLog* pMessageLog = new lmcMessageLog();
    QStringList fileNames = cacheDir.entryList(QStringList() << filter, filters, sort);
    foreach (QString fileName, fileNames) {
        QString filePath = cacheDir.absoluteFilePath(fileName);
        pMessageLog->restoreMessageLog(filePath, false);
        QString szMessageLog = pMessageLog->prepareMessageLogForSave();
        History::save(pMessageLog->peerName, QDateTime::currentDateTime(), &szMessageLog);
        QFile::remove(filePath);
    }
Ejemplo n.º 6
0
void LogFile::init()
{
    assert(dir_.empty());
    dir_ = cacheDir() + "log/";
    if (!boost::filesystem::is_directory(dir_.c_str()))
    {
        boost::filesystem::create_directories(dir_.c_str());
    }
}
Ejemplo n.º 7
0
// Loads the index file
void Cache::load()
{
	std::string path = cacheDir();
	PDEBUG << "Using cache dir: " << path << endl;

	m_index.clear();
	m_loaded = true;

	bool created;
	checkDir(path, &created);
	lock();
	if (created) {
		return;
	}

	// For git repositories, the hardest part is calling uuid()
	sys::datetime::Watch watch;

	GZIStream *in = new GZIStream(path+"/index");
	if (!in->ok()) {
		Logger::info() << "Cache: Empty cache for '" << uuid() << '\'' << endl;
		return;
	}

	uint32_t version;
	*in >> version;
	switch (checkVersion(version)) {
		case OutOfDate:
			delete in;
			throw PEX(str::printf("Cache is out of date - please run the check_cache report", version));
		case UnknownVersion:
			delete in;
			throw PEX(str::printf("Unknown cache version number %u - please run the check_cache report", version));
		default:
			break;
	}

	Logger::status() << "Loading cache index... " << ::flush;

	std::string buffer;
	std::pair<uint32_t, uint32_t> pos;
	uint32_t crc;
	while (!(*in >> buffer).eof()) {
		if (buffer.empty()) {
			break;
		}
		*in >> pos.first >> pos.second;
		*in >> crc;
		m_index[buffer] = pos;
	}

	Logger::status() << "done" << endl;
	delete in;
	Logger::info() << "Cache: Loaded " << m_index.size() << " revisions in " << watch.elapsedMSecs() << " ms" << endl;
}
Ejemplo n.º 8
0
void StreamCache::PurgeCache( void )
{
	std::string cacheDir( WSW_UI_STREAMCACHE_DIR );

	std::vector<std::string> cachedFiles;
	getFileList( cachedFiles, cacheDir, "*", true );

	for( std::vector<std::string>::const_iterator it = cachedFiles.begin(); it != cachedFiles.end(); ++it ) {
		trap::FS_RemoveFile( (cacheDir + "/" + *it).c_str() );
	}
}
Ejemplo n.º 9
0
// Checks cache consistency
void LdbCache::check(bool force)
{
	try {
		if (!m_db) opendb();
	} catch (const std::exception &ex) {
		PDEBUG << "Exception while opening database: " << ex.what() << endl;
		Logger::info() << "LdbCache: Database can't be opened, trying to repair it" << endl;
	}

	if (force || !m_db) {
		std::string path = cacheDir() + "/ldb";
		leveldb::Status status = leveldb::RepairDB(path, leveldb::Options());
		if (!status.ok()) {
			Logger::err() << "Error repairing database: " << status.ToString() << endl;
		} else {
			Logger::info() << "LdbCache: Database repaired" << endl;
		}
		closedb();
		opendb();
	}

	// Simply try to read all revisions
	Logger::info() << "LdbCache: Checking revisions..." << endl;
	std::vector<std::string> corrupted;
	size_t n = 0;
	leveldb::Iterator* it = m_db->NewIterator(leveldb::ReadOptions());
	for (it->SeekToFirst(); it->Valid(); it->Next()) {
		Revision rev(it->key().ToString());
		std::string value = it->value().ToString();
		MIStream rin(value.c_str(), value.length());
		if (!rev.load(rin)) {
			PDEBUG << "Revision " << it->key().ToString() << " corrupted!" << endl;
			corrupted.push_back(it->key().ToString());
		}
		++n;
	}
	if (!it->status().ok()) {
		Logger::err() << "Error iterating over cached revisions: " << it->status().ToString() << endl;
		Logger::err() << "Please re-run with --force to repair the database (might cause data loss)" << endl;
		return;
	}
	Logger::info() << "LdbCache: Checked " << n << " revisions, found " << corrupted.size() << " to be corrupted" << endl;

	for (size_t i = 0; i < corrupted.size(); i++) {
		Logger::err() << "LdbCache: Revision " << corrupted[i] << " is corrupted, removing from index file" << endl;
		leveldb::Status status = m_db->Delete(leveldb::WriteOptions(), corrupted[i]);
		if (!status.ok()) {
			Logger::err() << "Error: Can't remove from revision " << corrupted[i] << " from database: " << status.ToString() << endl;
			return;
		}
	}
}
Ejemplo n.º 10
0
CachedImageProvider::CachedImageProvider() :
    QDeclarativeImageProvider(QDeclarativeImageProvider::Image)
{
    qDebug("entered");
    cache = new QHash<QString, QImage>();
    QDir cacheDir(CACHE_FOLDER);
    if (!cacheDir.exists()) {
        cacheDir.mkpath(".");
    }
    QList<QFileInfo> files = cacheDir.entryInfoList(QDir::Files);
    foreach(QFileInfo fi, files){
        cache->insert(fi.fileName(), QImage(fi.absoluteFilePath()));
    }
Ejemplo n.º 11
0
void BtrfsBalancer::checkLastBalanced()
{
    QDir cacheDir(CACHE_DIR);
    if (cacheDir.cd(BALANCER_DIR)) {
        QFileInfo timeStampFile(cacheDir.absoluteFilePath(TIMESTAMP_FILE));
        if (timeStampFile.exists()) {
            emit lastBalanced(timeStampFile.lastModified().toMSecsSinceEpoch());
        } else {
            emit lastBalanced(0);
        }
    } else {
        emit lastBalanced(0);
    }
}
Ejemplo n.º 12
0
void FSettingsDialog::on_btn_Artwork_ClearCache_clicked() {
    QDir cacheDir(FGame::getCacheDir());

#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
    cacheDir.setNameFilters(QStringList()<<"*.*");
    QStringList steamFiles = cacheDir.entryList();
    for(int i=0;i<steamFiles.length();++i) {
        cacheDir.remove(steamFiles[i]);
    }
#else
   cacheDir.removeRecursively();
#endif

}
Ejemplo n.º 13
0
// Update the cache informations
void SettingsDialog::updateCacheInformations()
{
	QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

	QDir cacheDir(targetPath->text());
	QPair<int, qint64> cacheInfos= cacheNumberAndSize(cacheDir, true);

	QString numberOfFiles= QString::number(cacheInfos.first);
	numberOfCacheFiles->setText(numberOfFiles);

	QString cacheSize= sizeFromQint64ToString(cacheInfos.second);
	sizeOfCache->setText(cacheSize);

	QApplication::restoreOverrideCursor();
}
Ejemplo n.º 14
0
STATIC enum cacheRet maybeCache( const char *fullpath, CENTRYPTR *pc )
/********************************************************************/
{
    char            path[_MAX_PATH];
    char            name[NAME_MAX + 1];
    DHEADPTR        dcur;
    CENTRYPTR       centry;
    enum cacheRet   ret;
    PGROUP          pg;
    char const      *ext;

    assert( fullpath != NULL );

    _splitpath2( fullpath, pg.buffer, &pg.drive, &pg.dir, &pg.fname, &pg.ext );
    _makepath( path, pg.drive, pg.dir, NULL, NULL );
    ext = pg.ext;
    if( ext[0] == '.' && ext[1] == 0 ) {
        ext = NULL;
    }
    _makepath( name, NULL, NULL, pg.fname, ext );

    FixName( path );
    FixName( name );

    dcur = findDir( path );
    if( dcur == NULL ) {        /* must cache new directory */
        ret = cacheDir( &dcur, path );
        if( ret != CACHE_OK ) {
            return( ret );
        }
        dcur->dh_next = cacheHead;
        cacheHead = dcur;
    }

    /* now dcur points to Cached directory */
    assert( dcur != NULL );

    centry = findFile( dcur, name );
    if( centry == NULL ) {
        return( CACHE_FILE_NOT_FOUND );
    }

    if( pc != NULL ) {
        *pc = centry;
    }

    return( CACHE_OK );
}
Ejemplo n.º 15
0
BarcodeDecoder::BarcodeDecoder(QObject *parent)
    : QObject(parent)
    // ZXing
    , decoder(new QZXing())
{
    // prepare cache directory
    QString cacheFolderLocation = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation) + "/codereader";
    cacheCaptureLocation = cacheFolderLocation + "/screenshot.jpg";
    qDebug() << "screenshot location: " << cacheCaptureLocation;

    QDir cacheDir(cacheFolderLocation);

    if (!cacheDir.exists()) {
        cacheDir.mkpath(".");
    }
}
Ejemplo n.º 16
0
// Clears all cache files
void Cache::clear()
{
	flush();

	std::string path = cacheDir();
	if (!sys::fs::dirExists(path)) {
		return;
	}

	PDEBUG << "Clearing cache in dir: " << path << endl;
	std::vector<std::string> files = sys::fs::ls(path);
	for (size_t i = 0; i < files.size(); i++) {
		std::string fullpath = path + "/" + files[i];
		PDEBUG << "Unlinking " << fullpath << endl;
		sys::fs::unlink(fullpath);
	}
}
Ejemplo n.º 17
0
void lmcChatRoomWindow::setUserAvatar(QString* lpszUserId, QString* lpszFilePath) {
	QTreeWidgetItem* pUserItem = getUserItem(lpszUserId);
	if(!pUserItem)
		return;

	QDir cacheDir(StdLocation::cacheDir());
	QString fileName = "avt_" + *lpszUserId + ".png";
	QString filePath = cacheDir.absoluteFilePath(fileName);

	QPixmap avatar(filePath);
	avatar = avatar.scaled(QSize(32, 32), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
	pUserItem->setData(0, AvatarRole, QIcon(avatar));

	if(lpszFilePath)
		filePath = *lpszFilePath;
	pMessageLog->updateAvatar(lpszUserId, &filePath);
}
Ejemplo n.º 18
0
void CopyPhotosDialog::receivedPhotos_get(VKRequest *req)
{
    if((req->reqType!=VKRequest::Photos_get) ||
            (reqPhotosGet != req->reqId)){
        return;
    }
    reqPhotosGet = -1;
    plog(tr("Get source album photos description"));

    photos.clear();

    QDomDocument doc("Photos");
    doc.setContent(req->result);
    QDomElement docElem = doc.documentElement();
    QDomNodeList users = docElem.elementsByTagName ( "photo" );
    for(int i=0; i < users.count(); i++){
        QDomElement userElem = users.at(i).toElement();

        VKAlbumPhoto photo;

        photo.pid = userElem.elementsByTagName("pid").at(0).toElement().text();
        photo.aid = userElem.elementsByTagName("aid").at(0).toElement().text();
        photo.owner_id = userElem.elementsByTagName("owner_id").at(0).toElement().text();
        photo.src = userElem.elementsByTagName("src").at(0).toElement().text();
        photo.src_big = userElem.elementsByTagName("src_big").at(0).toElement().text();
        photo.src_small = userElem.elementsByTagName("src_small").at(0).toElement().text();
        photo.text = userElem.elementsByTagName("text").at(0).toElement().text();
        photo.src_xbig = userElem.elementsByTagName("src_xbig").at(0).toElement().text();
        photo.src_xxbig = userElem.elementsByTagName("src_xxbig").at(0).toElement().text();
        photo.cacheFileName = albumDir + photo.src_big.right(photo.src_big.length() - (photo.src_big.lastIndexOf("/")));
        qDebug() << photo.cacheFileName;

        photos.append( photo );
    }
    currentPhoto = 0;

    plog(tr("Finded %1 photos").arg(photos.count()));
    plog(tr("Caching all photos to local filesystem"));

    QDir cacheDir(albumDir);
    if (!cacheDir.exists(cacheDir.path())){
        cacheDir.mkpath(cacheDir.path());
    }
    downloadNextPhoto();
}
Ejemplo n.º 19
0
void NetTree::cleanCacheDir()
{
    QString cache = QString("%1/thumbcache")
                       .arg(GetConfDir());
    QDir cacheDir(cache);
    QStringList thumbs = cacheDir.entryList(QDir::Files);

    for (QStringList::const_iterator i = thumbs.end() - 1;
            i != thumbs.begin() - 1; --i)
    {
        QString filename = QString("%1/%2").arg(cache).arg(*i);
        LOG(VB_GENERAL, LOG_DEBUG, QString("Deleting file %1").arg(filename));
        QFileInfo fi(filename);
        QDateTime lastmod = fi.lastModified();
        if (lastmod.addDays(7) < QDateTime::currentDateTime())
            QFile::remove(filename);
    }
}
Ejemplo n.º 20
0
void CollectionConfiguration::copyConfiguration(const QHelpEngineCore &source,
                                                QHelpEngineCore &target)
{
    setCreationTime(target, creationTime(source));
    setWindowTitle(target, windowTitle(source));
    target.setCurrentFilter(source.currentFilter());
    setCacheDir(target, cacheDir(source), cacheDirIsRelativeToCollection(source));
    setFilterFunctionalityEnabled(target, filterFunctionalityEnabled(source));
    setFilterToolbarVisible(target, filterToolbarVisible(source));
    setAddressBarEnabled(target, addressBarEnabled(source));
    setAddressBarVisible(target, addressBarVisible(source));
    setDocumentationManagerEnabled(target, documentationManagerEnabled(source));
    setApplicationIcon(target, applicationIcon(source));
    setAboutMenuTexts(target, aboutMenuTexts(source));
    setAboutIcon(target, aboutIcon(source));
    setAboutTexts(target, aboutTexts(source));
    setAboutImages(target, aboutImages(source));
    setDefaultHomePage(target, defaultHomePage(source));
}
Ejemplo n.º 21
0
// Unlocks the cache directory
void Cache::unlock()
{
	if (m_lock < 0) {
		PDEBUG << "Not locked yet (" << m_lock << ")" << endl;
		return;
	}

	std::string path = cacheDir();
	PTRACE << "Unlocking file " << path + "/lock" << endl;
	struct flock flck;
	memset(&flck, 0x00, sizeof(struct flock));
	flck.l_type = F_UNLCK;
	if (fcntl(m_lock, F_SETLK, &flck) == -1) {
		throw PEX(str::printf("Unable to unlock cache, please delete %s/lock manually if required", path.c_str()));
	}
	if (::close(m_lock) == -1) {
		throw PEX_ERRNO();
	}
}
Ejemplo n.º 22
0
void ProtocolHandler::LoadPasswords()
{
	//find settings dir
	BPath passwordPath;
	find_directory(B_USER_SETTINGS_DIRECTORY, &passwordPath);
	//append Bme path and Cache path
	passwordPath.Append(K_BME_SETTINGS_PATH);
	passwordPath.Append(K_CACHE_PATH);
	//loop through Bme Cache path and find all login names with saved passwords
	BDirectory cacheDir(passwordPath.Path());
		
	int32 entryNum = cacheDir.CountEntries();
	//compose list of loginNames with passwords
	for (int32 i = 0; i < entryNum;i++)
	{
		BEntry entry;
		cacheDir.GetNextEntry(&entry);
		//only open if it is a file!!!
		if (entry.IsFile())
		{
			BFile settingsFile(&entry, B_READ_ONLY);
			//data is stored as BMessages
			BMessage message;
			message.Unflatten(&settingsFile);
			//see if password is stored in message
			BString password;
			BMessage userMessage;
			if (message.FindMessage("user",&userMessage) == B_OK)
			{				
				if (userMessage.FindString("User::password",&password) == B_OK)
				{					
					BString loginName;
					if (userMessage.FindString("Contact::passport" ,&loginName) == B_OK)
					{						
						Login login = {loginName,password};
						m_passwords.push_back(login);
					}
				}
			}
		}
	}
}
Ejemplo n.º 23
0
bool
CloudDBChartClient::writeChartCache(ChartAPIv1 * chart) {

    // make sure the subdir exists
    QDir cacheDir(g_cacheDir);
    if (cacheDir.exists()) {
        cacheDir.mkdir("charts");
    } else {
        return false;
    }
    QFile file(g_cacheDir+"/charts/"+QString::number(chart->Header.Id)+".dat");
    if (file.exists()) {
       // overwrite data
       file.resize(0);
    }

    if (!file.open(QIODevice::WriteOnly)) return false;
    QDataStream out(&file);
    out.setVersion(QDataStream::Qt_4_6);
    // track a version to be able change data structure
    out << chart_magic_string;
    out << chart_cache_version;
    out << chart->Header.LastChanged; // start
    out << chart->Header.CreatorId;
    out << chart->Header.Curated;
    out << chart->Header.Deleted;
    out << chart->Header.Description;
    out << chart->Header.GcVersion;
    out << chart->Header.Id;
    out << chart->Header.Language;
    out << chart->Header.Name;
    out << chart->ChartSport;
    out << chart->ChartType;
    out << chart->ChartView;
    out << chart->ChartDef;
    out << chart->CreatorEmail;
    out << chart->CreatorNick;
    out << chart->Image;

    file.close();
    return true;
}
Ejemplo n.º 24
0
CloudDBChartClient::CloudDBChartClient()
{
    g_nam = new QNetworkAccessManager(this);
    QDir cacheDir(QStandardPaths::standardLocations(QStandardPaths::AppLocalDataLocation).at(0));
    cacheDir.cdUp();
    g_cacheDir = QString(cacheDir.absolutePath()+"/GoldenCheetahCloudDB");

    // general handling for sslErrors
    connect(g_nam, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this,
            SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));

    // common definitions used

    g_chart_url_base = g_chart_url_header = g_chartcuration_url_base = CloudDBCommon::cloudDBBaseURL;

    g_chart_url_base.append("gchart/");
    g_chart_url_header.append("gchartheader");
    g_chartcuration_url_base.append("gchartcuration/");

}
Ejemplo n.º 25
0
void MetadataResultsDialog::cleanCacheDir()
{
    QString cache = QString("%1/cache/metadata-thumbcache")
                       .arg(GetConfDir());
    QDir cacheDir(cache);
    QStringList thumbs = cacheDir.entryList(QDir::Files);

    for (QStringList::const_iterator i = thumbs.end() - 1;
            i != thumbs.begin() - 1; --i)
    {
        QString filename = QString("%1/%2").arg(cache).arg(*i);
        QFileInfo fi(filename);
        QDateTime lastmod = fi.lastModified();
        if (lastmod.addDays(2) < MythDate::current())
        {
            LOG(VB_GENERAL, LOG_DEBUG, QString("Deleting old cache file %1")
                  .arg(filename));
            QFile::remove(filename);
        }
    }
}
Ejemplo n.º 26
0
// Locks the cache directory for this process
void Cache::lock()
{
	if (m_lock >= 0) {
		PDEBUG << "Already locked (" << m_lock << ")" << endl;
		return;
	}

	std::string path = cacheDir();
	std::string lock = path + "/lock";
	m_lock = ::open(lock.c_str(), O_WRONLY | O_CREAT, S_IWUSR);
	if (m_lock == -1) {
		throw PEX(str::printf("Unable to lock cache %s: %s", path.c_str(), PepperException::strerror(errno).c_str()));
	}

	PTRACE << "Locking file " << lock << endl;
	struct flock flck;
	memset(&flck, 0x00, sizeof(struct flock));
	flck.l_type = F_WRLCK;
	if (fcntl(m_lock, F_SETLK, &flck) == -1) {
		throw PEX(str::printf("Unable to lock cache %s, it may be used by another instance", path.c_str()));
	}
}
Ejemplo n.º 27
0
STATIC enum cacheRet maybeCache( const char *fullpath, CENTRYPTR *pc )
/********************************************************************/
{
    char            path[_MAX_PATH];
    char            name[NAME_MAX + 1];
    DHEADPTR        dcur;
    CENTRYPTR       centry;
    enum cacheRet   ret;

    assert( fullpath != NULL );

    splitFullPath( fullpath, path, name );
    FixName( path );
    FixName( name );

    dcur = findDir( path );
    if( dcur == NULL ) {        /* must cache new directory */
        ret = cacheDir( &dcur, path );
        if( ret != CACHE_OK ) {
            return( ret );
        }
        dcur->dh_next = cacheHead;
        cacheHead = dcur;
    }

    /* now dcur points to Cached directory */
    assert( dcur != NULL );

    centry = findFile( dcur, name );
    if( centry == NULL ) {
        return( CACHE_FILE_NOT_FOUND );
    }

    if( pc != NULL ) {
        *pc = centry;
    }

    return( CACHE_OK );
}
Ejemplo n.º 28
0
void KVNetworkReply::writeToDisk(const QByteArray &body) {
	int page = 0;
	if(body.size() <= 1024)
	{
		QUrlQuery query(body);
		page = query.queryItemValue("api_page_no").toInt();
	}

	QString cacheDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/userdata");
	QString path(cacheDir + url().path());
	if(page > 0)
		path += "__" + QString::number(page);
	path += ".json";

	QFileInfo fileInfo(path);
	fileInfo.absoluteDir().mkpath(".");

	QFile file(fileInfo.absoluteFilePath());
	if(file.open(QIODevice::WriteOnly))
		file.write(body);
	else
		qWarning() << "Couldn't write reply data to" << fileInfo.absoluteFilePath() << "(" << file.error() << ")";
}
Ejemplo n.º 29
0
// Opens the database connection
void LdbCache::opendb()
{
	if (m_db) return;

	std::string path = cacheDir() + "/ldb";
	PDEBUG << "Using cache dir: " << path << endl;
	if (!sys::fs::dirExists(path)) {
		sys::fs::mkpath(path);
	}
	leveldb::Options options;
	options.create_if_missing = false;
	leveldb::Status s = leveldb::DB::Open(options, path, &m_db);
	if (!s.ok()) {
		// New cache: Import revisions from old cache
		options.create_if_missing = true;
		leveldb::Status s = leveldb::DB::Open(options, path, &m_db);
		if (!s.ok()) {
			throw PEX(str::printf("Unable to open database %s: %s", path.c_str(), s.ToString().c_str()));
		}

		Cache c(m_backend, m_opts);
		import(&c);
	}
}
Ejemplo n.º 30
0
void KCDocumentRecorder::clear()
{
    clearCache();

    QDir cacheDir(unclosedUntitledFileDir);
    QFileInfoList cacheFileList=cacheDir.entryInfoList();
    int cacheFileListCount=cacheFileList.count();
    if(cacheFileListCount>2)
    {
        for(int i=0; i<cacheFileListCount; i++)
        {
            if(cacheFileList.at(i).isFile())
            {
                cacheDir.remove(cacheFileList.at(i).fileName());
            }
        }
    }

    QSettings settings(unclosedSettingFile,
                       QSettings::IniFormat);
    settings.beginGroup("UnclosedFile");
    settings.remove("");
    settings.endGroup();
}