Пример #1
0
	bool CFSModule::Create_Directory( const std::string& Dir ) {
		// Enforce leading /
		if( Dir.empty() || (Dir.substr(0,1) != "/") || (Dir.substr(Dir.length() - 1) == "/") ) {
			return NULL;
		}
		
		string Node;
		string BaseDir;

		// Split path into Node and Basedir
		Split_Full_Path( Dir, BaseDir, Node );
		
		CFSNode* pNode = Get_Node( BaseDir );
		
		if( pNode->Get_Node_Type() != NODE_DIR ) {
			return NULL;
		}
		
		CDirectory* pBaseDir = (CDirectory*)pNode;
		
		// Create the directory
		if( pBaseDir->Create_Directory( Node ) ) {
			return true;
		} else {
			return false;
		}
	}
Пример #2
0
	bool CFSModule::Create_File( const std::string& Name ) {
		// Enforce leading /
		if( Name.empty() || (Name.substr(0,1) != "/") || (Name.substr(Name.length() - 1) == "/") ) {
			return NULL;
		}
		
		string Node;
		string BaseDir;

		// Split path into Node and Basedir
		Split_Full_Path( Name, BaseDir, Node );
		
		CDirectory* pDir = (CDirectory*)Get_Node( BaseDir );
		
		if( !pDir ) {
			return NULL;
		}
		
		if( pDir->Get_Node_Type() != NODE_DIR ) {
			return NULL;
		}
		
		if( pDir->Create_File( Node ) ) {
			return true;
		} else {
			return false;
		}
	}
Пример #3
0
bool CDirectory::dir2fdd(char *sourceDirectory, char *fddImageName)
{
    Debug::out(LOG_INFO, "CDirectory::dir2fdd() -- will try to create %s from %s", fddImageName, sourceDirectory);
    
   	CDirectory *pDir = new CDirectory();
	pDir->DirectoryScan(sourceDirectory);

    if(!pDir) {
        Debug::out(LOG_ERROR, "CreateTreeFromDirectory failed...");
        return false;
    }
    
    CFloppy floppy;
    floppy.Create(NB_HEAD,NB_SECTOR_PER_TRACK,NB_CYLINDER);

    bool bOk = floppy.Fill( pDir, (char *) "CONF_FDD" );

    if (bOk) {
        Debug::out(LOG_INFO, "CDirectory::dir2fdd() -- Writing file %s", fddImageName);
        floppy.WriteImage(fddImageName);
    }

    delete pDir;
	return bOk;
}
Пример #4
0
bool CLanguage::Load ( const CString& szLangName )
{
    CString szPath ( "../lang/%s/", szLangName.c_str () );

    CDirectory dir ( szPath );
    if ( !dir.IsOk ( ) )
        return false;

    for ( CDirectory::CIterator iter = dir.Begin ();
          iter != dir.End ();
          ++iter )
    {
        CString szCur = iter.GetName ();
        size_t iExt = szCur.rfind ( '.' );
        if ( iExt != CString::npos )
        {
            if ( szCur.substr ( iExt ) == ".txt" )
            {
                LoadFile ( szLangName, szCur.substr ( 0, iExt ) );
            }
        }
    }

    m_bIsOk = true;
    return true;
}
Пример #5
0
void CSingleIndexBarrelReader::open(const tchar* name)
{
    m_name = name;

    CDirectory* pDirectory = m_pIndex->getDirectory();
    tstring s = m_name + _T(".fdi");
    CIndexInput* pIndexInput = pDirectory->openInput(s.c_str());
    m_pFieldsInfo->read(pIndexInput);
    pIndexInput->close();
    delete pIndexInput;

    m_pStoredFieldsReader->open(pDirectory,name,m_pFieldsInfo);
    m_pNormsReader->open(name,m_pFieldsInfo);

    if(pDirectory->fileExists(m_name + _T(".del")))
    {
        CIndexInput* pDelInput = pDirectory->openInput(m_name + _T(".del"));
        m_pDeletedDocs = new CBitVector(pDelInput);
        delete pDelInput;
    }
    else m_pDeletedDocs = new CBitVector();

    if(m_pTermReader)
    {
        delete m_pTermReader;
        m_pTermReader = NULL;
    }
    if(m_pFieldsInfo->numIndexFields() > 1)
    {
        m_pTermReader = new CMultiFieldTermReader(pDirectory,name,m_pFieldsInfo,m_pDeletedDocs,getFactoryFinder());
        m_pTermReader->setFilter(m_pDeletedDocs);
    }
    else if(m_pFieldsInfo->numIndexFields() == 1)
    {
        m_pFieldsInfo->startIterator();
        CFieldInfo* pFieldInfo;
        while (m_pFieldsInfo->hasNext())
        {
            pFieldInfo = m_pFieldsInfo->next();
            if(pFieldInfo->isIndexed())
            {
                m_pTermReader = getFactoryFinder()->getFactory(pFieldInfo->getID())->createTermReader();
                m_pTermReader->setFilter(m_pDeletedDocs);
                m_pTermReader->open(pDirectory,name,pFieldInfo,m_pDeletedDocs);
                break;
            }
        }
    }
    else
    {
        FIRTEX_THROW2(INDEX_COLLAPSE_ERROR,_T("the field number is 0."));
    }
}
Пример #6
0
IDirectory *LibrarySystem::OpenDirectory(const char *path)
{
	CDirectory *dir = new CDirectory(path);

	if (!dir->IsValid())
	{
		delete dir;
		return NULL;
	}

	return dir;
}
Пример #7
0
// native open_dir(dir[], firstfile[], length, &FileType:type = FileType_Unknown, bool:use_valve_fs=false, const valve_path_id[] = "GAME");
static cell AMX_NATIVE_CALL amx_open_dir(AMX *amx, cell *params)
{
	int length;
	const char* path = get_amxstring(amx, params[1], 0, length);

	if (!*path)
	{
		return 0;
	}

	size_t numParams = *params / sizeof(cell);

	if (numParams >= 4 && params[5] > 0)
	{
		const char* wildcardedPath = g_LibSys.PathFormat("%s%s*", path, (path[length - 1] != '/' && path[length - 1] != '\\') ? "/" : "");
		const char* pathID = get_amxstring_null(amx, params[6], 1, length);

		static FileFindHandle_t handle;
		const char* pFirst = g_FileSystem->FindFirst(wildcardedPath, &handle, pathID);

		if (!pFirst)
		{
			return 0;
		}

		set_amxstring_utf8(amx, params[2], pFirst, strlen(pFirst), params[3] + 1);
		cell* fileType = get_amxaddr(amx, params[4]);

		*fileType = g_FileSystem->FindIsDirectory(handle) ? FileType_Directory : FileType_File;

		return reinterpret_cast<cell>(new DirectoryHandle(reinterpret_cast<void*>(&handle), true));
	}

	CDirectory* dir = g_LibSys.OpenDirectory(build_pathname("%s", path));

	if (!dir)
	{
		return 0;
	}

	if (numParams >= 4)
	{
		cell* fileType = get_amxaddr(amx, params[4]);
		*fileType = dir->IsEntryDirectory() ? FileType_Directory : FileType_File;
	}

	const char* entry = dir->GetEntryName();
	set_amxstring_utf8(amx, params[2], entry, strlen(entry), params[3] + 1);

	return reinterpret_cast<cell>(new DirectoryHandle(reinterpret_cast<void*>(dir), false));
}
Пример #8
0
bool vip_Start::Process()
{
    GFRLOG_TRACE("VIP starts to process");
    CDirectory dir;
    list<string> filelist = dir.get_file_list(m_str_src);

    list<string>::iterator it;
    for (it = filelist.begin(); it != filelist.end(); ++it)
    {
        cout<< "Processing [" << *it << "]" <<endl;
        this->load_file(*it);
    }

    return true;
}
Пример #9
0
CDirectory* CDirectoryQueue::Pop()
{
    bool force_wait = false;
    CDirectory* tmp;
    CDirectory* tmpPrev;

    EnterCriticalSection(&_cs);
    tmpPrev = NULL;
    tmp = _head;
    while (tmp != NULL) {
        if (tmp->TryLock()) {
            if (tmp == _head)
                _head = _head->_next;
            if (tmpPrev != NULL)
                tmpPrev->_next = tmp->_next; // unlink it
            if (tmp == _tail)
                _tail = tmpPrev;
            --_length;
            break;
        }
        Warning("Skipping locked directory %s (will return to it)",
            tmp->GetDirectoryName());
        tmpPrev = tmp;
        tmp = tmp->_next;
    }
    if (tmp == NULL && _head != NULL) {
        // There's at least one directory, but they're all in use by another
        // copy of rl. Just grab the first one and wait on it.
        tmp = _head;
        _head = _head->_next;
        if (tmp == _tail)
            _tail = NULL;
        --_length;
        // wait until it's no longer in use..... However, don't wait inside the
        // critical section.
        force_wait = true;
    }
    ReleaseSemaphore(_hMaxWorkQueueSem, 1, NULL);
    LeaveCriticalSection(&_cs);
    if (tmp != NULL)    // might be empty diff queue before masters are run
        tmp->_next = NULL;
    if (force_wait)
        tmp->WaitLock();
    return tmp;
}
Пример #10
0
void CDirectory::DirectoryScan(const char *pDir)
{
	char tmpName[_MAX_PATH];
	strcpy(tmpName,pDir);
	strcat(tmpName,"\\*.*");
	
	DIR *dir = opendir((char *) pDir);						        // try to open the dir
	
    if(dir == NULL) {                                 			    // not found?
        return;
    }
    
	while(1) {                                                  	// while there are more files, store them
		struct dirent *de = readdir(dir);							// read the next directory entry
	
		if(de == NULL) {											// no more entries?
			break;
		}
	
		if(de->d_type != DT_DIR && de->d_type != DT_REG) {			// not 	a file, not a directory?
			continue;
		}

		sprintf(tmpName,"%s/%s", pDir, de->d_name);

        if(de->d_type == DT_DIR) {                                  // for dir
            if(de->d_name[0] == '.') {                              // skip . and ..
                continue;
            }
            
            CDirectory *pNewDir = new CDirectory();
			this->AddEntry(de, pNewDir, tmpName);
            
			pNewDir->DirectoryScan(tmpName);
        } else {
            this->AddEntry(de, NULL, tmpName);
        }
    }

    closedir(dir);	
}
Пример #11
0
bool CFileOperations::FillFileItemList(const CVariant &parameterObject, CFileItemList &list)
{
  if (parameterObject.isMember("directory"))
  {
    CStdString media =  parameterObject["media"].asString();
    media = media.ToLower();

    CStdString strPath = parameterObject["directory"].asString();
    if (!strPath.empty())
    {
      CFileItemList items;
      CStdString extensions = "";
      CStdStringArray regexps;

      if (media.Equals("video"))
      {
        regexps = g_advancedSettings.m_videoExcludeFromListingRegExps;
        extensions = g_settings.m_videoExtensions;
      }
      else if (media.Equals("music"))
      {
        regexps = g_advancedSettings.m_audioExcludeFromListingRegExps;
        extensions = g_settings.m_musicExtensions;
      }
      else if (media.Equals("pictures"))
      {
        regexps = g_advancedSettings.m_pictureExcludeFromListingRegExps;
        extensions = g_settings.m_pictureExtensions;
      }

      CDirectory directory;
      if (directory.GetDirectory(strPath, items, extensions))
      {
        items.Sort(SORT_METHOD_FILE, SortOrderAscending);
        CFileItemList filteredDirectories;
        for (unsigned int i = 0; i < (unsigned int)items.Size(); i++)
        {
          if (CUtil::ExcludeFileOrFolder(items[i]->GetPath(), regexps))
            continue;

          if (items[i]->m_bIsFolder)
            filteredDirectories.Add(items[i]);
          else if ((media == "video" && items[i]->HasVideoInfoTag()) ||
                   (media == "music" && items[i]->HasMusicInfoTag()))
            list.Add(items[i]);
          else
          {
            CFileItem fileItem;
            if (FillFileItem(items[i], fileItem, media))
              list.Add(CFileItemPtr(new CFileItem(fileItem)));
            else if (media == "files")
              list.Add(items[i]);
          }
        }

        if (parameterObject.isMember("recursive") && parameterObject["recursive"].isBoolean())
        {
          for (int i = 0; i < filteredDirectories.Size(); i++)
          {
            CVariant val = parameterObject;
            val["directory"] = filteredDirectories[i]->GetPath();
            FillFileItemList(val, list);
          }
        }

        return true;
      }
    }
  }

  return false;
}
Пример #12
0
// native next_file(dirh, buffer[], length, &FileType:type = FileType_Unknown);
static cell AMX_NATIVE_CALL amx_get_dir(AMX *amx, cell *params)
{
	DirectoryHandle* p = reinterpret_cast<DirectoryHandle*>(params[1]);

	if (!p)
	{
		return 0;
	}

	size_t numParams = *params / sizeof(cell);

	if (p->valvefs)
	{
		FileFindHandle_t* handle = reinterpret_cast<FileFindHandle_t*>(p->handle);

		if (!handle)
		{
			return 0;
		}

		const char* entry = g_FileSystem->FindNext(*handle);

		if (!entry)
		{
			return 0;
		}

		if (numParams >= 4)
		{
			cell* fileType = get_amxaddr(amx, params[4]);
			*fileType = g_FileSystem->FindIsDirectory(*handle) ? FileType_Directory : FileType_File;
		}

		set_amxstring_utf8(amx, params[2], entry, strlen(entry), params[3] + 1);
	}
	else
	{
		CDirectory* handle = reinterpret_cast<CDirectory*>(p->handle);

		if (!handle)
		{
			return 0;
		}

		handle->NextEntry();

		if (!handle->MoreFiles())
		{
			return 0;
		}

		if (numParams >= 4)
		{
			cell* fileType = get_amxaddr(amx, params[4]);
			*fileType = handle->IsEntryDirectory() ? FileType_Directory : FileType_File;
		}

		const char* entry = handle->GetEntryName();

		set_amxstring_utf8(amx, params[2], entry, strlen(entry), params[3] + 1);
	}

	return 1;
}
Пример #13
0
void CGUIWindowPrograms::PopulateTrainersList()
{
  CDirectory directory;
  CFileItemList trainers;
  CFileItemList archives;
  CFileItemList inArchives;
  // first, remove any dead items
  std::vector<CStdString> vecTrainerPath;
  m_database.GetAllTrainers(vecTrainerPath);
  CGUIDialogProgress* m_dlgProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
  m_dlgProgress->SetLine(0,12023);
  m_dlgProgress->SetLine(1,"");
  m_dlgProgress->SetLine(2,"");
  m_dlgProgress->StartModal();
  m_dlgProgress->SetHeading(12012);
  m_dlgProgress->ShowProgressBar(true);
  m_dlgProgress->Progress();

  bool bBreak=false;
  bool bDatabaseState = m_database.IsOpen();
  if (!bDatabaseState)
    m_database.Open();
  m_database.BeginTransaction();
  for (unsigned int i=0;i<vecTrainerPath.size();++i)
  {
    m_dlgProgress->SetPercentage((int)((float)i/(float)vecTrainerPath.size()*100.f));
    CStdString strLine;
    strLine.Format("%s %i / %i",g_localizeStrings.Get(12013).c_str(), i+1,vecTrainerPath.size());
    m_dlgProgress->SetLine(1,strLine);
    m_dlgProgress->Progress();
    if (!CFile::Exists(vecTrainerPath[i]) || vecTrainerPath[i].find(g_guiSettings.GetString("myprograms.trainerpath",false)) == -1)
      m_database.RemoveTrainer(vecTrainerPath[i]);
    if (m_dlgProgress->IsCanceled())
    {
      bBreak = true;
      m_database.RollbackTransaction();
      break;
    }
  }
  if (!bBreak)
  {
    CLog::Log(LOGDEBUG,"trainerpath %s",g_guiSettings.GetString("myprograms.trainerpath",false).c_str());
    directory.GetDirectory(g_guiSettings.GetString("myprograms.trainerpath").c_str(),trainers,".xbtf|.etm");
    if (g_guiSettings.GetString("myprograms.trainerpath",false).IsEmpty())
    {
      m_database.RollbackTransaction();
      m_dlgProgress->Close();

      return;
    }

    directory.GetDirectory(g_guiSettings.GetString("myprograms.trainerpath").c_str(),archives,".rar|.zip",false); // TODO: ZIP SUPPORT
    for( int i=0;i<archives.Size();++i)
    {
      if (stricmp(URIUtils::GetExtension(archives[i]->GetPath()),".rar") == 0)
      {
        g_RarManager.GetFilesInRar(inArchives,archives[i]->GetPath(),false);
        CHDDirectory dir;
        dir.SetMask(".xbtf|.etm");
        for (int j=0;j<inArchives.Size();++j)
          if (dir.IsAllowed(inArchives[j]->GetPath()))
          {
            CFileItemPtr item(new CFileItem(*inArchives[j]));
            CStdString strPathInArchive = item->GetPath();
            CStdString path;
            URIUtils::CreateArchivePath(path, "rar", archives[i]->GetPath(), strPathInArchive,"");
            item->SetPath(path);
            trainers.Add(item);
          }
      }
      if (stricmp(URIUtils::GetExtension(archives[i]->GetPath()),".zip")==0)
      {
        // add trainers in zip
        CStdString strZipPath;
        URIUtils::CreateArchivePath(strZipPath,"zip",archives[i]->GetPath(),"");
        CFileItemList zipTrainers;
        directory.GetDirectory(strZipPath,zipTrainers,".etm|.xbtf");
        for (int j=0;j<zipTrainers.Size();++j)
        {
          CFileItemPtr item(new CFileItem(*zipTrainers[j]));
          trainers.Add(item);
        }
      }
    }
    if (!m_dlgProgress)
      m_dlgProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
    m_dlgProgress->SetPercentage(0);
    m_dlgProgress->ShowProgressBar(true);

    CLog::Log(LOGDEBUG,"# trainers %i",trainers.Size());
    m_dlgProgress->SetLine(1,"");
    int j=0;
    while (j < trainers.Size())
    {
      if (trainers[j]->m_bIsFolder)
        trainers.Remove(j);
      else
        j++;
    }
    for (int i=0;i<trainers.Size();++i)
    {
      CLog::Log(LOGDEBUG,"found trainer %s",trainers[i]->GetPath().c_str());
      m_dlgProgress->SetPercentage((int)((float)(i)/trainers.Size()*100.f));
      CStdString strLine;
      strLine.Format("%s %i / %i",g_localizeStrings.Get(12013).c_str(), i+1,trainers.Size());
      m_dlgProgress->SetLine(0,strLine);
      m_dlgProgress->SetLine(2,"");
      m_dlgProgress->Progress();
      if (m_database.HasTrainer(trainers[i]->GetPath())) // skip existing trainers
        continue;

      CTrainer trainer;
      if (trainer.Load(trainers[i]->GetPath()))
      {
        m_dlgProgress->SetLine(1,trainer.GetName());
        m_dlgProgress->SetLine(2,"");
        m_dlgProgress->Progress();
        unsigned int iTitle1, iTitle2, iTitle3;
        trainer.GetTitleIds(iTitle1,iTitle2,iTitle3);
        if (iTitle1)
          m_database.AddTrainer(iTitle1,trainers[i]->GetPath());
        if (iTitle2)
          m_database.AddTrainer(iTitle2,trainers[i]->GetPath());
        if (iTitle3)
          m_database.AddTrainer(iTitle3,trainers[i]->GetPath());
      }
      if (m_dlgProgress->IsCanceled())
      {
        m_database.RollbackTransaction();
        break;
      }
    }
  }
  m_database.CommitTransaction();
  m_dlgProgress->Close();

  if (!bDatabaseState)
    m_database.Close();
  else
    Update(m_vecItems->GetPath());
}
Пример #14
0
JSON_STATUS CFileOperations::GetDirectory(const CStdString &method, ITransportLayer *transport, IClient *client, const Value &parameterObject, Value &result)
{
  CStdString media = parameterObject["media"].asString();
  media = media.ToLower();

  CDirectory directory;
  CFileItemList items;
  CStdString strPath = parameterObject["directory"].asString();

  CStdStringArray regexps;
  CStdString extensions = "";
  if (media.Equals("video"))
  {
    regexps = g_advancedSettings.m_videoExcludeFromListingRegExps;
    extensions = g_stSettings.m_videoExtensions;
  }
  else if (media.Equals("music"))
  {
    regexps = g_advancedSettings.m_audioExcludeFromListingRegExps;
    extensions = g_stSettings.m_musicExtensions;
  }
  else if (media.Equals("pictures"))
  {
    regexps = g_advancedSettings.m_pictureExcludeFromListingRegExps;
    extensions = g_stSettings.m_pictureExtensions;
  }

  if (directory.GetDirectory(strPath, items, extensions))
  {
    CFileItemList filteredDirectories, filteredFiles;
    for (unsigned int i = 0; i < (unsigned int)items.Size(); i++)
    {
      if (CUtil::ExcludeFileOrFolder(items[i]->m_strPath, regexps))
        continue;

      if (items[i]->IsSmb())
      {
        CURI url(items[i]->m_strPath);
        items[i]->m_strPath = url.GetWithoutUserDetails();
      }

      if (items[i]->m_bIsFolder)
        filteredDirectories.Add(items[i]);
      else
        filteredFiles.Add(items[i]);
    }

    // Check if the "fields" list exists
    // and make sure it contains the "file"
    // field
    Value param = parameterObject;
    if (!param.isMember("fields"))
      param["fields"] = Value(arrayValue);

    bool hasFileField = false;
    for (unsigned int i = 0; i < param["fields"].size(); i++)
    {
      if (param["fields"][i].asString().compare("file") == 0)
      {
        hasFileField = true;
        break;
      }
    }

    if (!hasFileField)
      param["fields"].append("file");

    HandleFileItemList(NULL, true, "files", filteredDirectories, param, result);
    for (unsigned int index = 0; index < result["files"].size(); index++)
    {
      result["files"][index]["filetype"] = "directory";
    }
    int count = result["limits"]["total"].asInt();

    HandleFileItemList(NULL, true, "files", filteredFiles, param, result);
    for (unsigned int index = count; index < result["files"].size(); index++)
    {
      result["files"][index]["filetype"] = "file";
    }
    count += result["limits"]["total"].asInt();

    result["limits"]["end"] = count;
    result["limits"]["total"] = count;

    result["success"] = true;

    return OK;
  }

  return InvalidParams;
}
Пример #15
0
bool CFileOperations::FillFileItemList(const Value &parameterObject, CFileItemList &list)
{
  if (parameterObject.isObject() && parameterObject.isMember("directory"))
  {
    CStdString media = "files";
    if (parameterObject.isMember("media"))
    {
      if (parameterObject["media"].isString())
        media = parameterObject["media"].asString();
      else
        return false;
    }

    media = media.ToLower();

    if (media.Equals("video") || media.Equals("music") || media.Equals("pictures") || media.Equals("files") || media.Equals("programs"))
    {
      CDirectory directory;
      CFileItemList items;
      CStdString strPath = parameterObject["directory"].asString();

      CStdStringArray regexps;
      CStdString extensions = "";
      if (media.Equals("video"))
      {
        regexps = g_advancedSettings.m_videoExcludeFromListingRegExps;
        extensions = g_stSettings.m_videoExtensions;
      }
      else if (media.Equals("music"))
      {
        regexps = g_advancedSettings.m_audioExcludeFromListingRegExps;
        extensions = g_stSettings.m_musicExtensions;
      }
      else if (media.Equals("pictures"))
      {
        regexps = g_advancedSettings.m_pictureExcludeFromListingRegExps;
        extensions = g_stSettings.m_pictureExtensions;
      }

      if (directory.GetDirectory(strPath, items, extensions))
      {
        CFileItemList filteredDirectories;
        for (unsigned int i = 0; i < (unsigned int)items.Size(); i++)
        {
          if (CUtil::ExcludeFileOrFolder(items[i]->m_strPath, regexps))
            continue;

          if (items[i]->m_bIsFolder)
            filteredDirectories.Add(items[i]);
          else
            list.Add(items[i]);
        }

        if (parameterObject.isMember("recursive") && parameterObject["recursive"].isBool())
        {
          for (int i = 0; i < filteredDirectories.Size(); i++)
          {
            Value val = parameterObject;
            val["directory"] = filteredDirectories[i]->m_strPath;
            FillFileItemList(val, list);
          }
        }

        return true;
      }
    }
  }

  return false;
}
Пример #16
0
bool CGameConfig::Reparse(char *error, size_t maxlength)
{
	m_Offsets.clear();
	m_OffsetsByClass.clear();
	m_Keys.clear();
	m_Addresses.clear();

	char path[PLATFORM_MAX_PATH];
	const char *dataDir = get_localinfo("amxx_datadir", "addons/amxmodx/data");

	build_pathname_r(path, sizeof(path), "%s/gamedata/%s/master.games.txt", dataDir, m_File);

	if (!g_LibSys.PathExists(path))
	{
		// Single config file without master
		g_LibSys.PathFormat(path, sizeof(path), "%s.txt", m_File);

		if (!EnterFile(path, error, maxlength))
		{
			return false;
		}

		// Allow customizations of default gamedata files
		build_pathname_r(path, sizeof(path), "%s/gamedata/custom/%s.txt", dataDir, m_File);

		if (g_LibSys.PathExists(path))
		{
			g_LibSys.PathFormat(path, sizeof(path), "custom/%s.txt", m_File);

			auto success = EnterFile(path, error, maxlength);

			if (success)
			{
				AMXXLOG_Log("[AMXX] Parsed custom gamedata override file: %s", path);
			}

			return success;
		}
		return true;
	}

	SMCError err;
	SMCStates state = { 0, 0 };

	ke::Vector<ke::AString> fileList;
	MasterReader.m_FileList = &fileList;

	err = textparsers->ParseSMCFile(path, &MasterReader, &state, error, maxlength);

	if (err != SMCError_Okay)
	{
		const char *msg = textparsers->GetSMCErrorString(err);

		AMXXLOG_Error("Error parsing master gameconf file \"%s\":", path);
		AMXXLOG_Error("Error %d on line %d, col %d: %s", err, state.line, state.col, msg ? msg : "Unknown error");

		return false;
	}

	for (size_t i = 0; i < fileList.length(); ++i)
	{
		g_LibSys.PathFormat(path, sizeof(path), "%s/%s", m_File, fileList[i].chars());

		if (!EnterFile(path, error, maxlength))
		{
			return false;
		}
	}

	build_pathname_r(path, sizeof(path), "%s/gamedata/%s/custom", dataDir, m_File);
	CDirectory *customDir = g_LibSys.OpenDirectory(path);

	if (!customDir)
	{
		return true;
	}

	while (customDir->MoreFiles())
	{
		if (!customDir->IsEntryFile())
		{
			customDir->NextEntry();
			continue;
		}

		const char *currentFile = customDir->GetEntryName();

		size_t length = strlen(currentFile);

		if (length > 4 && strcmp(&currentFile[length - 4], ".txt") != 0)
		{
			customDir->NextEntry();
			continue;
		}

		g_LibSys.PathFormat(path, sizeof(path), "%s/custom/%s", m_File, currentFile);

		if (!EnterFile(path, error, maxlength))
		{
			g_LibSys.CloseDirectory(customDir);
			return false;
		}

		AMXXLOG_Log("[AMXX] Parsed custom gamedata override file: %s", path);

		customDir->NextEntry();
	}

	g_LibSys.CloseDirectory(customDir);

	return true;
}
Пример #17
0
int CStorageServer::initilize()
{
	//todo: storage initilize
	typedef CThread* CThreadPtr;
	CDirectory dir;
	int nthread_curr, ret;
	addr_list proxy_addr_list;
	CThreadBeatHeart *pbeat_heart_func;
	CThreadSyncData *psync_thread_func;
	
	g_ntimeout = m_storage_server_conf.ntimeout;
	g_nstorage_bind_port = m_storage_server_conf.nbind_port;
	g_nstorage_zone_id = m_storage_server_conf.nzone_id;
	g_nstorage_weight = m_storage_server_conf.nweight;
	memcpy(g_device_root, m_storage_server_conf.device_path, KL_COMMON_PATH_LEN);

	CInetAddr bind_addr(m_storage_server_conf.bind_host, \
		m_storage_server_conf.nbind_port);
	if(bind_addr.getipaddress(g_storage_bind_ip, KL_COMMON_IP_ADDR_LEN) != 0)
	{
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"get storage node bind ip failed, err: %s", \
			__LINE__, strerror(errno));
		return errno;
	}
	
	try
	{
		g_pcontainer_rwlock = new CRWLock();
	}
	catch(std::bad_alloc)
	{
		g_pcontainer_rwlock = NULL;
	}
	catch(int errcode)
	{
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"call CRWLock constructor failed, err: %s", \
			__LINE__, strerror(errcode));
		return errcode;
	}
	if(g_pcontainer_rwlock == NULL)
	{
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"no more memory to create vnode container rwlock", \
			__LINE__);
		return ENOMEM;
	}

	try
	{
		g_pstorage_vnode_container = new CStorageVnodeContainer();
	}
	catch(std::bad_alloc)
	{
		g_pstorage_vnode_container = NULL;
	}
	catch(int errcode)
	{
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"call CStorageVnodeContainer constructor failed, err: %s", \
			__LINE__, strerror(errcode));
		return errcode;
	}
	if(g_pstorage_vnode_container == NULL)
	{
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"no more memory to create storage vnode container", \
			__LINE__);
		return ENOMEM;
	}

	//create sync message queue
	try
	{
		m_psync_msg_queue = new CMsgQueue();
	}
	catch(std::bad_alloc)
	{
		m_psync_msg_queue = NULL;
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"no more memory to create sync msg queue", \
			__LINE__);
		return ENOMEM;
	}
	catch(int errcode)
	{
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"call CMsgQueue constructor failed, err: %s", \
			__LINE__, strerror(errcode));
		return errcode;
	}
	//create sync push thread
	proxy_addr_list = m_storage_server_conf.proxy_addr_list;
	if(proxy_addr_list.empty())
	{
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"no proxy server address to join and report", \
			__LINE__);
		return -1;
	}
	try
	{
		psync_thread_func = new CThreadSyncData(m_psync_msg_queue, proxy_addr_list[0]);
	}
	catch(std::bad_alloc)
	{
		psync_thread_func = NULL;
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"no more memory to create sync thread function", \
			__LINE__);
		return ENOMEM;
	}
	try
	{
		m_psync_thread = new CThread(psync_thread_func, \
			m_storage_server_conf.nthread_stack_size);
	}
	catch(std::bad_alloc)
	{
		m_psync_thread = NULL;
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"no more memory to create storage sync thread", \
			__LINE__);
		return ENOMEM;
	}
	catch(int errcode)
	{
		m_psync_thread = NULL;
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"call CThread constructor failed, err: %s", \
			__LINE__, strerror(errcode));
		return errcode;
	}

	//create beat-hearting thread to report
	try
	{
		m_ppreport_threads = new CThreadPtr[proxy_addr_list.size()];
	}
	catch(std::bad_alloc)
	{
		m_ppreport_threads = NULL;
	}
	if(m_ppreport_threads == NULL)
	{
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"no more memory to create report thread array", \
			__LINE__);
		return ENOMEM;
	}
	//create a report thread to each proxynode
	for(nthread_curr = 0; nthread_curr < proxy_addr_list.size(); nthread_curr++)
	{
		try
		{
			pbeat_heart_func = new CThreadBeatHeart(proxy_addr_list[nthread_curr], \
				m_psync_msg_queue, nthread_curr);
		}
		catch(std::bad_alloc)
		{
			pbeat_heart_func = NULL;
		}
		catch(int errcode)
		{
			KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
				"call CThreadBeatHeart constructor failed, err: %s", \
				__LINE__, strerror(errcode));
			return errcode;
		}
		if(pbeat_heart_func == NULL)
		{
			KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
				"no more memory to create beat-hearting function", \
				__LINE__);
			return ENOMEM;
		}

		try
		{
			m_ppreport_threads[nthread_curr] = new CThread(pbeat_heart_func, \
				m_storage_server_conf.nthread_stack_size);
		}
		catch(std::bad_alloc)
		{
			m_ppreport_threads[nthread_curr] = NULL;
		}
		catch(int errcode)
		{
			KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
				"call CThread constructor failed, err: %s", \
				__LINE__, strerror(errcode));
			return errcode;
		}
		if(m_ppreport_threads[nthread_curr] == NULL)
		{
			KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
				"no more memory to create beat-hearting thread", \
				__LINE__);
			return ENOMEM;
		}
	}
	//make device root dir
	if(dir.dir_exist(g_device_root))
	{
		dir.remove_dir(g_device_root);
	}
	if((ret = dir.make_dir(g_device_root)) != 0)
	{
		KL_SYS_ERRORLOG("file: "__FILE__", line: %d, " \
			"make device root dir failed, dir_path: %s, err: %s", \
			__LINE__, g_device_root, strerror(ret));
		return ret;
	}
	//do base server initilize
	return CBaseServer::initilize();
}
Пример #18
0
JSON_STATUS CFileOperations::GetDirectory(const CStdString &method, ITransportLayer *transport, IClient *client, const CVariant &parameterObject, CVariant &result)
{
  CStdString media = parameterObject["media"].asString();
  media = media.ToLower();

  CDirectory directory;
  CFileItemList items;
  CStdString strPath = parameterObject["directory"].asString();

  CStdStringArray regexps;
  CStdString extensions = "";
  if (media.Equals("video"))
  {
    regexps = g_advancedSettings.m_videoExcludeFromListingRegExps;
    extensions = g_settings.m_videoExtensions;
  }
  else if (media.Equals("music"))
  {
    regexps = g_advancedSettings.m_audioExcludeFromListingRegExps;
    extensions = g_settings.m_musicExtensions;
  }
  else if (media.Equals("pictures"))
  {
    regexps = g_advancedSettings.m_pictureExcludeFromListingRegExps;
    extensions = g_settings.m_pictureExtensions;
  }

  if (directory.GetDirectory(strPath, items, extensions))
  {
    CFileItemList filteredDirectories, filteredFiles;
    for (unsigned int i = 0; i < (unsigned int)items.Size(); i++)
    {
      if (CUtil::ExcludeFileOrFolder(items[i]->GetPath(), regexps))
        continue;

      if (items[i]->IsSmb())
      {
        CURL url(items[i]->GetPath());
        items[i]->SetPath(url.GetWithoutUserDetails());
      }

      if (items[i]->m_bIsFolder)
        filteredDirectories.Add(items[i]);
      else if ((media == "video" && items[i]->HasVideoInfoTag()) ||
               (media == "music" && items[i]->HasMusicInfoTag()))
        filteredFiles.Add(items[i]);
      else
      {
        CFileItem fileItem;
        if (FillFileItem(items[i]->GetPath(), fileItem, media))
          filteredFiles.Add(CFileItemPtr(new CFileItem(fileItem)));
      }
    }

    // Check if the "fields" list exists
    // and make sure it contains the "file"
    // field
    CVariant param = parameterObject;
    if (!param.isMember("fields"))
      param["fields"] = CVariant(CVariant::VariantTypeArray);

    bool hasFileField = false;
    for (CVariant::const_iterator_array itr = param["fields"].begin_array(); itr != param["fields"].end_array(); itr++)
    {
      if (*itr == CVariant("file"))
      {
        hasFileField = true;
        break;
      }
    }

    if (!hasFileField)
      param["fields"].append("file");

    HandleFileItemList(NULL, true, "files", filteredDirectories, param, result);
    for (unsigned int index = 0; index < result["files"].size(); index++)
    {
      result["files"][index]["filetype"] = "directory";
    }
    int count = (int)result["limits"]["total"].asInteger();

    HandleFileItemList("id", true, "files", filteredFiles, param, result);
    for (unsigned int index = count; index < result["files"].size(); index++)
    {
      result["files"][index]["filetype"] = "file";
    }
    count += (int)result["limits"]["total"].asInteger();

    result["limits"]["end"] = count;
    result["limits"]["total"] = count;

    return OK;
  }

  return InvalidParams;
}