Example #1
0
bool CZipManager::GetZipList(const CURL& url, std::vector<SZipEntry>& items)
{
  struct __stat64 m_StatData = {};

  std::string strFile = url.GetHostName();

  if (CFile::Stat(strFile,&m_StatData))
  {
    CLog::Log(LOGDEBUG,"CZipManager::GetZipList: failed to stat file %s", url.GetRedacted().c_str());
    return false;
  }

  std::map<std::string, std::vector<SZipEntry> >::iterator it = mZipMap.find(strFile);
  if (it != mZipMap.end()) // already listed, just return it if not changed, else release and reread
  {
    std::map<std::string,int64_t>::iterator it2=mZipDate.find(strFile);

    if (m_StatData.st_mtime == it2->second)
    {
      items = it->second;
      return true;
    }
    mZipMap.erase(it);
    mZipDate.erase(it2);
  }

  CFile mFile;
  if (!mFile.Open(strFile))
  {
    CLog::Log(LOGDEBUG,"ZipManager: unable to open file %s!",strFile.c_str());
    return false;
  }

  unsigned int hdr;
  if (mFile.Read(&hdr, 4)!=4 || (Endian_SwapLE32(hdr) != ZIP_LOCAL_HEADER &&
                                 Endian_SwapLE32(hdr) != ZIP_DATA_RECORD_HEADER &&
                                 Endian_SwapLE32(hdr) != ZIP_SPLIT_ARCHIVE_HEADER))
  {
    CLog::Log(LOGDEBUG,"ZipManager: not a zip file!");
    mFile.Close();
    return false;
  }

  if (Endian_SwapLE32(hdr) == ZIP_SPLIT_ARCHIVE_HEADER)
    CLog::LogF(LOGWARNING, "ZIP split archive header found. Trying to process as a single archive..");

  // push date for update detection
  mZipDate.insert(make_pair(strFile,m_StatData.st_mtime));


  // Look for end of central directory record
  // Zipfile comment may be up to 65535 bytes
  // End of central directory record is 22 bytes (ECDREC_SIZE)
  // -> need to check the last 65557 bytes
  int64_t fileSize = mFile.GetLength();
  // Don't need to look in the last 18 bytes (ECDREC_SIZE-4)
  // But as we need to do overlapping between blocks (3 bytes),
  // we start the search at ECDREC_SIZE-1 from the end of file
  if (fileSize < ECDREC_SIZE - 1)
  {
    CLog::Log(LOGERROR, "ZipManager: Invalid zip file length: %" PRId64"", fileSize);
    return false;
  }
  int searchSize = (int) std::min(static_cast<int64_t>(65557), fileSize-ECDREC_SIZE+1);
  int blockSize = (int) std::min(1024, searchSize);
  int nbBlock = searchSize / blockSize;
  int extraBlockSize = searchSize % blockSize;
  // Signature is on 4 bytes
  // It could be between 2 blocks, so we need to read 3 extra bytes
  auto_buffer buffer(blockSize + 3);
  bool found = false;

  // Loop through blocks starting at the end of the file (minus ECDREC_SIZE-1)
  for (int nb=1; !found && (nb <= nbBlock); nb++)
  {
    mFile.Seek(fileSize-ECDREC_SIZE+1-(blockSize*nb),SEEK_SET);
    if (mFile.Read(buffer.get(), blockSize + 3) != blockSize + 3)
      return false;
    for (int i=blockSize-1; !found && (i >= 0); i--)
    {
      if ( Endian_SwapLE32(*((unsigned int*)(buffer.get()+i))) == ZIP_END_CENTRAL_HEADER )
      {
        // Set current position to start of end of central directory
        mFile.Seek(fileSize-ECDREC_SIZE+1-(blockSize*nb)+i,SEEK_SET);
        found = true;
      }
    }
  }

  // If not found, look in the last block left...
  if ( !found && (extraBlockSize > 0) )
  {
    mFile.Seek(fileSize-ECDREC_SIZE+1-searchSize,SEEK_SET);
    if (mFile.Read(buffer.get(), extraBlockSize + 3) != extraBlockSize + 3)
      return false;
    for (int i=extraBlockSize-1; !found && (i >= 0); i--)
    {
      if ( Endian_SwapLE32(*((unsigned int*)(buffer.get()+i))) == ZIP_END_CENTRAL_HEADER )
      {
        // Set current position to start of end of central directory
        mFile.Seek(fileSize-ECDREC_SIZE+1-searchSize+i,SEEK_SET);
        found = true;
      }
    }
  }

  buffer.clear();

  if ( !found )
  {
    CLog::Log(LOGDEBUG,"ZipManager: broken file %s!",strFile.c_str());
    mFile.Close();
    return false;
  }

  unsigned int cdirOffset, cdirSize;
  // Get size of the central directory
  mFile.Seek(12,SEEK_CUR);
  if (mFile.Read(&cdirSize, 4) != 4)
    return false;
  cdirSize = Endian_SwapLE32(cdirSize);
  // Get Offset of start of central directory with respect to the starting disk number
  if (mFile.Read(&cdirOffset, 4) != 4)
    return false;
  cdirOffset = Endian_SwapLE32(cdirOffset);

  // Go to the start of central directory
  mFile.Seek(cdirOffset,SEEK_SET);

  char temp[CHDR_SIZE];
  while (mFile.GetPosition() < cdirOffset + cdirSize)
  {
    SZipEntry ze;
    if (mFile.Read(temp, CHDR_SIZE) != CHDR_SIZE)
      return false;
    readCHeader(temp, ze);
    if (ze.header != ZIP_CENTRAL_HEADER)
    {
      CLog::Log(LOGDEBUG,"ZipManager: broken file %s!",strFile.c_str());
      mFile.Close();
      return false;
    }

    // Get the filename just after the central file header
    auto_buffer bufName(ze.flength);
    if (mFile.Read(bufName.get(), ze.flength) != ze.flength)
      return false;
    std::string strName(bufName.get(), bufName.size());
    bufName.clear();
    g_charsetConverter.unknownToUTF8(strName);
    ZeroMemory(ze.name, 255);
    strncpy(ze.name, strName.c_str(), strName.size()>254 ? 254 : strName.size());

    // Jump after central file header extra field and file comment
    mFile.Seek(ze.eclength + ze.clength,SEEK_CUR);

    items.push_back(ze);
  }

  /* go through list and figure out file header lengths */
  for(std::vector<SZipEntry>::iterator it = items.begin(); it != items.end(); ++it)
  {
    SZipEntry& ze = *it;
    // Go to the local file header to get the extra field length
    // !! local header extra field length != central file header extra field length !!
    mFile.Seek(ze.lhdrOffset+28,SEEK_SET);
    if (mFile.Read(&(ze.elength), 2) != 2)
      return false;
    ze.elength = Endian_SwapLE16(ze.elength);

    // Compressed data offset = local header offset + size of local header + filename length + local file header extra field length
    ze.offset = ze.lhdrOffset + LHDR_SIZE + ze.flength + ze.elength;

  }

  mZipMap.insert(make_pair(strFile,items));
  mFile.Close();
  return true;
}
Example #2
0
int OpenDataChannel(char *retrfile, int timeout, int ptype, char *pserver, int pport, char *puid, char *ppwd, char *szReturn, CFtpParam& ftpParam)
{
	CString	strCmd = _T("");
	CString	retMsg = _T("");
	char	buffer[1024] = {0};
	SOCKET dataChannel;

	if(ftpParam.passive_mode)
	{
		dataChannel = socket(AF_INET, SOCK_STREAM, 0);
		if(dataChannel == SOCKET_ERROR)
		{
			sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                "FTP_CREATE_COMMUNICATE_ERROR"));//<%IDS_FTP_18%>
			return 1;
		}

		if(*pserver && ptype == 1)
		{
			if(socks5_protocol(dataChannel, ftpParam.remote_host, ftpParam.remote_port, 
						pserver, pport, puid, ppwd, timeout))
			{
				sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                    "FTP_CREATE_COMMUNICATE_ERROR"));//<%IDS_FTP_19%>
				return 1;
			}
		}
		else
		{
			struct sockaddr_in rsa;
			rsa.sin_addr.s_addr = inet_addr(ftpParam.remote_host);
			rsa.sin_family = AF_INET;
			rsa.sin_port = htons(ftpParam.remote_port);
			if(connect_timeo(dataChannel, (struct sockaddr *)&rsa, sizeof(rsa), timeout))
			{
				sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                    "FTP_CREATE_COMMUNICATE_ERROR"));//<%IDS_FTP_20%>
				return 1;
			}
		}
	}
	else
	{
		struct sockaddr_in rsa;
		int rsalen = sizeof(rsa);
		dataChannel = accept(ftpParam.dataSocket, (struct sockaddr *)&rsa, &rsalen);
		if(dataChannel == INVALID_SOCKET)
		{
			sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_FTP",
                "FTP_CREATE_COMMUNICATE_ERROR"));//<%IDS_FTP_21%>
			return 1;
		}
	}
#ifdef SAVEASFILE
	CFile datafile;
	if(!datafile.Open("C:\\download\\download", CFile::modeWrite|CFile::modeCreate)) 
	{
		return 1;
	}
#endif
	DWORD	recvBegin = GetTickCount();
	while(1) 
	{
		int iRead = 0;
		char	response[1025] = {0};
		iRead = recv(dataChannel, response, 1024, 0);
		if(!iRead || iRead == SOCKET_ERROR)
			break;
		else
		{
#ifdef SAVEASFILE
			datafile.Write(response, iRead);
#endif
			ftpParam.recvBytes += iRead;
		}
	}
	ftpParam.recvTickCount = GetTickCount() - recvBegin;
#ifdef SAVEASFILE
	datafile.Close();
#endif

	return 0;
}
bool CGUIDialogFileBrowser::OnMessage(CGUIMessage& message)
{
  switch ( message.GetMessage() )
  {
  case GUI_MSG_WINDOW_DEINIT:
    {
      if (m_thumbLoader.IsLoading())
        m_thumbLoader.StopThread();
      CGUIDialog::OnMessage(message);
      ClearFileItems();
      m_addNetworkShareEnabled = false;
      return true;
    }
    break;

  case GUI_MSG_WINDOW_INIT:
    {
      m_bConfirmed = false;
      m_bFlip = false;
      bool bIsDir = false;
      // this code allows two different selection modes for directories
      // end the path with a slash to start inside the directory
      if (URIUtils::HasSlashAtEnd(m_selectedPath))
      {
        bIsDir = true;
        bool bFool;
        int iSource = CUtil::GetMatchingSource(m_selectedPath,m_shares,bFool);
        bFool = true;
        if (iSource > -1 && iSource < (int)m_shares.size())
        {
          if (m_shares[iSource].strPath.Equals(m_selectedPath))
            bFool = false;
        }

        if (bFool && !CDirectory::Exists(m_selectedPath))
          m_selectedPath.Empty();
      }
      else
      {
        if (!CFile::Exists(m_selectedPath) && !CDirectory::Exists(m_selectedPath))
            m_selectedPath.Empty();
      }

      // find the parent folder if we are a file browser (don't do this for folders)
      m_Directory->SetPath(m_selectedPath);
      if (!m_browsingForFolders && !bIsDir)
        m_Directory->SetPath(URIUtils::GetParentPath(m_selectedPath));
      Update(m_Directory->GetPath());
      m_viewControl.SetSelectedItem(m_selectedPath);
      return CGUIDialog::OnMessage(message);
    }
    break;

  case GUI_MSG_CLICKED:
    {
      if (m_viewControl.HasControl(message.GetSenderId()))  // list control
      {
        int iItem = m_viewControl.GetSelectedItem();
        int iAction = message.GetParam1();
        if (iItem < 0) break;
        if (iAction == ACTION_SELECT_ITEM || iAction == ACTION_MOUSE_LEFT_CLICK)
        {
          OnClick(iItem);
          return true;
        }
        else if (iAction == ACTION_HIGHLIGHT_ITEM && m_multipleSelection)
        {
          CFileItemPtr pItem = (*m_vecItems)[iItem];
          if (!pItem->m_bIsShareOrDrive && !pItem->m_bIsFolder)
          {
            pItem->Select(!pItem->IsSelected());
            CGUIMessage msg(GUI_MSG_ITEM_SELECT, GetID(), message.GetSenderId(), iItem + 1);
            OnMessage(msg);
          }
        }
      }
      else if (message.GetSenderId() == CONTROL_OK)
      {
        if (m_browsingForFolders == 2)
        {
          int iItem = m_viewControl.GetSelectedItem();

          CStdString strPath;
          if (iItem == 0)
            strPath = m_selectedPath;
          else
            strPath = (*m_vecItems)[iItem]->GetPath();

          CStdString strTest = URIUtils::AddFileToFolder(strPath, "1");
          CFile file;
          if (file.OpenForWrite(strTest,true))
          {
            file.Close();
            CFile::Delete(strTest);
            m_bConfirmed = true;
            Close();
          }
          else
            CGUIDialogOK::ShowAndGetInput(257,20072,0,0);
        }
        else
        {
          if (m_multipleSelection)
          {
            for (int iItem = 0; iItem < m_vecItems->Size(); ++iItem)
            {
              CFileItemPtr pItem = (*m_vecItems)[iItem];
              if (pItem->IsSelected())
                m_markedPath.push_back(pItem->GetPath());
            }
          }
          m_bConfirmed = true;
          Close();
        }
        return true;
      }
      else if (message.GetSenderId() == CONTROL_CANCEL)
      {
        Close();
        return true;
      }
      else if (message.GetSenderId() == CONTROL_NEWFOLDER)
      {
        CStdString strInput;
        if (CGUIKeyboardFactory::ShowAndGetInput(strInput,g_localizeStrings.Get(119),false))
        {
          CStdString strPath = URIUtils::AddFileToFolder(m_vecItems->GetPath(), strInput);
          if (CDirectory::Create(strPath))
            Update(m_vecItems->GetPath());
          else
            CGUIDialogOK::ShowAndGetInput(20069,20072,20073,0);
        }
      }
      else if (message.GetSenderId() == CONTROL_FLIP)
        m_bFlip = !m_bFlip;
    }
    break;
  case GUI_MSG_SETFOCUS:
    {
      if (m_viewControl.HasControl(message.GetControlId()) && m_viewControl.GetCurrentControl() != message.GetControlId())
      {
        m_viewControl.SetFocused();
        return true;
      }
    }
    break;
  case GUI_MSG_NOTIFY_ALL:
    { // Message is received only if this window is active
      if (message.GetParam1() == GUI_MSG_REMOVED_MEDIA)
      {
        if (m_Directory->IsVirtualDirectoryRoot() && IsActive())
        {
          int iItem = m_viewControl.GetSelectedItem();
          Update(m_Directory->GetPath());
          m_viewControl.SetSelectedItem(iItem);
        }
        else if (m_Directory->IsRemovable())
        { // check that we have this removable share still
          if (!m_rootDir.IsInSource(m_Directory->GetPath()))
          { // don't have this share any more
            if (IsActive()) Update("");
            else
            {
              m_history.ClearPathHistory();
              m_Directory->SetPath("");
            }
          }
        }
        return true;
      }
      else if (message.GetParam1()==GUI_MSG_UPDATE_SOURCES)
      { // State of the sources changed, so update our view
        if (m_Directory->IsVirtualDirectoryRoot() && IsActive())
        {
          int iItem = m_viewControl.GetSelectedItem();
          Update(m_Directory->GetPath());
          m_viewControl.SetSelectedItem(iItem);
        }
        return true;
      }
      else if (message.GetParam1()==GUI_MSG_UPDATE_PATH)
      {
        if (IsActive())
        {
          if((message.GetStringParam() == m_Directory->GetPath()) ||
             (m_Directory->IsMultiPath() && XFILE::CMultiPathDirectory::HasPath(m_Directory->GetPath(), message.GetStringParam())))
          {
            int iItem = m_viewControl.GetSelectedItem();
            Update(m_Directory->GetPath());
            m_viewControl.SetSelectedItem(iItem);
          }
        }
      }
    }
    break;

  }
  return CGUIDialog::OnMessage(message);
}
Example #4
0
CMmio *CDataFile::OpenAsMMIO( const char *pFilename, const char *pRif )
{
	//  Get the relative path of the file for which to search.
	CString file( pFilename );
	CString path;
	if ( pFilename == NULL )
		path.Format( "language\\%d\\%d.rif", m_countryCode, m_countryCode );
	else
		path = file + "\\" + file + ".rif";
	path.MakeLower ();

	//  Check to see if the file exists in the patch directory.
	if ( m_pPatchDir )
	{
		CString patchPath = *m_pPatchDir + "\\" + path;

		CFile	test;
		if ( test.Open( patchPath, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary ) != FALSE )
		{
			//  Close the file so we can re-open it as an mmio file.
			//  Otherwise we'd need to keep the CFile around so it's
			//  destructor wouldn't close the file handle.
			test.Close();
			CMmio *pNewFile = new CMmio( patchPath );
			if ( pNewFile == NULL )
				ThrowError( ERR_OUT_OF_MEMORY );

			// does the version match?
			try
				{
				pNewFile->DescendRiff ( pRif );
				pNewFile->DescendList ('F', 'V', 'E', 'R');
				pNewFile->DescendChunk ('D', 'A', 'T', 'A');
				int iRifVer = pNewFile->ReadShort ();
				pNewFile->AscendChunk ();
				pNewFile->AscendList ();

				if ( iRifVer == m_iRifVer )
					{
					// go back to begining (hack!!)
					delete pNewFile;
					pNewFile = new CMmio( patchPath );
					if ( pNewFile == NULL )
						ThrowError( ERR_OUT_OF_MEMORY );
					return pNewFile;
					}
				}

			catch (...)
				{
				}

			delete pNewFile;
		}

		// we now look in the patch dir (users version)
		if ( pFilename == NULL )
			patchPath.Format( "%s\\%d.rif", (char const *) (*m_pPatchDir), m_countryCode );
		else
			patchPath = *m_pPatchDir + CString ("\\") + file + ".rif";

		if ( test.Open( patchPath, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary ) != FALSE )
		{
			//  Close the file so we can re-open it as an mmio file.
			//  Otherwise we'd need to keep the CFile around so it's
			//  destructor wouldn't close the file handle.
			test.Close();
			CMmio *pNewFile = new CMmio( patchPath );
			if ( pNewFile == NULL )
				ThrowError( ERR_OUT_OF_MEMORY );

			// does the version match?
			try
				{
				pNewFile->DescendRiff ( pRif );
				pNewFile->DescendList ('F', 'V', 'E', 'R');
				pNewFile->DescendChunk ('D', 'A', 'T', 'A');
				int iRifVer = pNewFile->ReadShort ();
				pNewFile->AscendChunk ();
				pNewFile->AscendList ();

				if ( iRifVer == m_iRifVer )
					{
					// go back to begining (hack!!)
					delete pNewFile;
					pNewFile = new CMmio( patchPath );
					if ( pNewFile == NULL )
						ThrowError( ERR_OUT_OF_MEMORY );
					return pNewFile;
					}
				}

			catch (...)
				{
				}

			delete pNewFile;
		}
	}

	//  If here, the file does not exist in the 
	//  patch directory or there is no patch directory.
	//  If a datafile was opened, look for it in the
	//  datafile.
	if ( m_pDataFile )
	{
		//  Look for the file path in the map.  If 
		//  it is not found, if searching for language 
		//  file try searching for US version;  otherwise,
		//  return NULL.
		void *	dummy;
		if ( m_pFileMap->Lookup( path, dummy ) == FALSE )
		{
			if ( pFilename == NULL && m_countryCode != DEF_COUNTRY_CODE )
			{	
				m_countryCode = DEF_COUNTRY_CODE;
				return OpenAsMMIO( NULL, pRif );
			}
			ThrowError( ERR_DATAFILE_NO_ENTRY );
		}

		//  If here, file was found in the map.  Seek to
		//  that position in the file.
		//  If negative seek checks between CMmio's are 
		//  desired, they should be done here.
		long fileOffset = ( long )dummy;
		long	offsetFromHere = fileOffset - ( long )m_pDataFile->GetPosition();

#ifdef _DEBUG
		if ( m_bNegativeSeekCheck == TRUE && fileOffset < m_lastPos )
			WarnNegativeSeek( pFilename, m_lastPos, fileOffset );
#endif

		m_pDataFile->Seek( offsetFromHere, CFile::current );

#ifdef _DEBUG
		m_lastPos = m_pDataFile->GetPosition();
#endif

		//  Create a new CMmioEmbeddedFile object.  It will be positioned 
		//  at the current file offset.
		// BUGBUG - problem
		CMmio *pNewFile = new CMmioEmbeddedFile( m_pDataFile->m_hFile, m_sFileName );
		if ( pNewFile == NULL )
			ThrowError( ERR_OUT_OF_MEMORY );

		return pNewFile;
	}

	//  If here, file was not found in patch dir ( or
	//  no patch dir was given ), and no datafile was
	//  opened, so return NULL ( no file found ).
	ThrowError( ERR_DATAFILE_NO_ENTRY );
	return NULL;
}
Example #5
0
bool CFile::Cache(const CStdString& strFileName, const CStdString& strDest, XFILE::IFileCallback* pCallback, void* pContext)
{
  CFile file;
  CAsyncFileCallback* helper = NULL;

  if (file.Open(strFileName, true, READ_TRUNCATED))
  {
    if (file.GetLength() <= 0)
    {
      CLog::Log(LOGWARNING, "FILE::cache: the file %s has a length of 0 bytes", strFileName.c_str());
      file.Close();
      
      // Never save 0 byte files from the Plex Media Server.
      if (strFileName.Find(":32400") != -1)
        return false;
    }

    CFile newFile;
    if (CUtil::IsHD(strDest)) // create possible missing dirs
    {
      std::vector<CStdString> tokens;
      CStdString strDirectory;
      CUtil::GetDirectory(strDest,strDirectory);
      CUtil::RemoveSlashAtEnd(strDirectory);  // for the test below
      if (!(strDirectory.size() == 2 && strDirectory[1] == ':'))
      {
        CUtil::Tokenize(strDirectory,tokens,"\\");
        CStdString strCurrPath = tokens[0]+"\\";
        for (std::vector<CStdString>::iterator iter=tokens.begin()+1;iter!=tokens.end();++iter)
        {
          strCurrPath += *iter+"\\";
          CDirectory::Create(strCurrPath);
        }
      }
    }
    if (CFile::Exists(strDest))
      CFile::Delete(strDest);
    if (!newFile.OpenForWrite(strDest, true, true))  // overwrite always
    {
      file.Close();
      return false;
    }

    /* larger then 1 meg, let's do rendering async */
// Async render cannot be done in Linux because of the resulting ThreadMessage deadlock
#ifndef _LINUX
    if( file.GetLength() > 1024*1024 )
      helper = new CAsyncFileCallback(pCallback, pContext);
#endif

    // 128k is optimal for xbox
    int iBufferSize = 128 * 1024;

    CAutoBuffer buffer(iBufferSize);
    int iRead, iWrite;

    UINT64 llFileSize = file.GetLength();
    UINT64 llFileSizeOrg = llFileSize;
    UINT64 llPos = 0;
    int ipercent = 0;

    CStopWatch timer;
    timer.StartZero();
    float start = 0.0f;
    while (llFileSize > 0)
    {
      g_application.ResetScreenSaver();
      unsigned int iBytesToRead = iBufferSize;
      
      /* make sure we don't try to read more than filesize*/
      if (iBytesToRead > llFileSize) iBytesToRead = llFileSize;

      iRead = file.Read(buffer.get(), iBytesToRead);
      if (iRead == 0) break;
      else if (iRead < 0) 
      {
        CLog::Log(LOGERROR, "%s - Failed read from file %s", __FUNCTION__, strFileName.c_str());
        break;
      }

      /* write data and make sure we managed to write it all */
      iWrite = 0;
      while(iWrite < iRead)
      {
        int iWrite2 = newFile.Write(buffer.get()+iWrite, iRead-iWrite);
        if(iWrite2 <=0)          
          break;
        iWrite+=iWrite2;
      }

      if (iWrite != iRead)
      {
        CLog::Log(LOGERROR, "%s - Failed write to file %s", __FUNCTION__, strDest.c_str());
        break;
      }
      
      llFileSize -= iRead;
      llPos += iRead;

      // calculate the current and average speeds
      float end = timer.GetElapsedSeconds();
      float averageSpeed = llPos / end;
      start = end;

      float fPercent = 100.0f * (float)llPos / (float)llFileSizeOrg;

      if ((int)fPercent != ipercent)
      {
        if( helper )
        {
          helper->SetStatus((int)fPercent, averageSpeed);
          if(helper->IsCanceled())
            break;
        }
        else if( pCallback )
        {
          if (!pCallback->OnFileCallback(pContext, ipercent, averageSpeed)) 
            break;
        }

        ipercent = (int)fPercent;
      }
    }

    /* close both files */
    newFile.Close();
    file.Close();
    
    if(helper)
      delete helper;

    /* verify that we managed to completed the file */
    if (llPos != llFileSizeOrg)
    {      
      CFile::Delete(strDest);
      return false;
    }
    return true;
  }
  return false;
}
Example #6
0
bool zstringEx::tools_jm_file(char *filename,bool do_add)//do_add=false表示是进行解密
{
	CFile fn;
	ULONG i;BYTE k;long jsq=0;UINT newlen;
	if(!fn.Open(filename,CFile::modeReadWrite|CFile::typeBinary))return false;    
	UINT flen=(UINT)fn.GetLength();
    //上面打开文件

	if(do_add==true)  //如果是要求加密
	{
		//下面读文件
		BYTE *buffer=(BYTE *)VirtualAlloc(0,(size_t)flen+1,MEM_COMMIT,PAGE_READWRITE);
		if(buffer==NULL){fn.Close();AfxMessageBox("file is too big!");return false;}
        fn.Read(buffer,(UINT)flen);

		//////////////////////////////////判断是否有必要加密
		bool is_already_add=true;
		for(i=0;i<16;i++){
			if(buffer[i]!=120+i){is_already_add=false;break;}
		}
        if(is_already_add==true)//如果有加密,就返回
		{
		fn.Close();
		VirtualFree((LPVOID)buffer,0,MEM_RELEASE);		
		return false;
		}
        //////////////////////////////////判断是否有必要加密


		BYTE *buffer2=(BYTE *)VirtualAlloc(0,16+2*((size_t)flen+1),MEM_COMMIT,PAGE_READWRITE);
		if(buffer2==NULL){VirtualFree((LPVOID)buffer,0,MEM_RELEASE);fn.Close();AfxMessageBox("file is too big!");return false;}
        //准备内存 
        
	    //下面开始加密
		//////////////////////////////////////////////////////////////
		for(i=0;i<flen;i++)buffer[i]=255-buffer[i];   //反码
		//////////////////////////////////////////////////////////////
		for(i=0;i<(flen-1)/2;i++){k=buffer[i];buffer[i]=buffer[flen-1-i];buffer[flen-1-i]=k;} 
		//倒序                   
		//////////////////////////////////////////////////////////////
		
		zdatetime::setRandSeed();jsq=0;
		for(i=0;i<flen-1;i+=2)  
		{     
			buffer2[16+i+jsq]=buffer[i];
			buffer2[16+i+1+jsq]=buffer[i+1];
			if(buffer[i+1]>=buffer[i]){buffer2[16+i+2+jsq]=(BYTE)zdatetime::getRand(255);jsq++;}
		}
		if(i==flen-1)buffer2[16+i+jsq]=buffer[i];
		//插值
		//////////////////////////////////////////////////////////////
		for(i=0;i<16;i++)buffer2[i]=(BYTE)(120+i);
		newlen=flen+16+jsq;
		//加16位的文件头
		//////////////////////////////////////////////////////////////
		fn.SeekToBegin();
		fn.Write(buffer2,(UINT)newlen);
		fn.Close();
		//上面重写文件
		VirtualFree((LPVOID)buffer,0,MEM_RELEASE);
		VirtualFree((LPVOID)buffer2,0,MEM_RELEASE);
		return true;
	}


	if(do_add==false)  //如果是要求解密
	{
		//下面读文件
		BYTE *buffer=(BYTE *)VirtualAlloc(0,(size_t)flen+1,MEM_COMMIT,PAGE_READWRITE);
		if(buffer==NULL){fn.Close();AfxMessageBox("file is too big!");return false;}
        fn.Read(buffer,(UINT)flen);

		//////////////////////////////////判断是否有必要解密
		bool is_already_add=true;
		for(i=0;i<16;i++){
			if(buffer[i]!=120+i){is_already_add=false;break;}
		}
        if(is_already_add==false)//如果没有加密,就返回
		{
		fn.Close();
		VirtualFree((LPVOID)buffer,0,MEM_RELEASE);
		return false;
		}
        //////////////////////////////////判断是否有必要解密


		BYTE *buffer2=(BYTE *)VirtualAlloc(0,(size_t)flen+1,MEM_COMMIT,PAGE_READWRITE);
		if(buffer2==NULL){VirtualFree((LPVOID)buffer,0,MEM_RELEASE);fn.Close();AfxMessageBox("file is too big!");return false;}
        //准备内存 
        
	    //下面开始解密
        //////////////////////////////////////////////////////////////
	    //插值还原
		jsq=0;
        for(i=16;i<flen-1;i+=2)  
		{     
			buffer2[i-16-jsq]=buffer[i];
			buffer2[i+1-16-jsq]=buffer[i+1];
			if(buffer[i+1]>=buffer[i]){i++;jsq++;}
		}
		if(i==flen-1)buffer2[i-16-jsq]=buffer[i];
		//////////////////////////////////////////////////////////////
        newlen=flen-jsq-16; //原长度求出
		//////////////////////////////////////////////////////////////
		for(i=0;i<(newlen-1)/2;i++){k=buffer2[i];buffer2[i]=buffer2[newlen-1-i];buffer2[newlen-1-i]=k;} 
		//倒序   
		for(i=0;i<newlen;i++)buffer2[i]=255-buffer2[i];   //反码
		//////////////////////////////////////////////////////////////               
			
		fn.SeekToBegin();
		fn.Write(buffer2,(UINT)newlen);
		fn.SeekToBegin();
		fn.SetLength(newlen);
		fn.Close();

		//上面重写文件
		VirtualFree((LPVOID)buffer,0,MEM_RELEASE);
		VirtualFree((LPVOID)buffer2,0,MEM_RELEASE);
		return true;
	}

return true;

}//end function
Example #7
0
int main( int argc, char *argv[] )
{
  int   rc = 0;

  fs::path pathInFileName;
  fs::path pathOutFileName;
  fs::path pathOutDirectory;

  CCmdLineProcessor proc(argv, argc);

  int nIdx = 0;
  try
  {
    proc.parseCmdLine();

    if (!proc.getFileCount())
      return 0;

    const string& strOutSpec = proc.getOutSpec();

    bool bStdOut = (strOutSpec == "-");
    bool bQuiet = proc.beQuiet() || bStdOut;

    if (strOutSpec.length() && (strOutSpec != "-")) {
      if (proc.getFileCount() > 1) {
        // More than one input file -> interpret OutSpec as a directory
        if (!fs::exists(strOutSpec)) {           // Create directory, if necessary
          if (!bQuiet) cout << endl << "Creating directory " << strOutSpec.c_str() << "." << endl;
          try {
            fs::create_directories(strOutSpec);
          }
          catch (const std::exception&) {
          }
        }
        // Check that dir exists
        if (!(fs::exists(strOutSpec) && fs::is_directory(strOutSpec))) {
          throw CSimpleException(CSimpleException::err_outdir);
        }
        pathOutDirectory = strOutSpec;
      } else {
        // Exact one input file -> interpret OutSpec as one file
        if (fs::exists(strOutSpec) && fs::is_directory(strOutSpec)) {
          throw CSimpleException(CSimpleException::err_outfileisdir);
        }
        pathOutFileName = strOutSpec;
      }
    }

    while (proc.getNextFile(pathInFileName))
    {
      COutputFilter *pOut = NULL;
      CSffFile      *pInfile = NULL;
      char           acNumber[10];

      try
      {
        fs::path outPath;

        CSffFile *pInfile = new CSffFile(pathInFileName.string());
        int nPageCount = pInfile->GetPageCount();
        if (!bQuiet)
          cout << "File " << pathInFileName.string()
               << " seems to have " << nPageCount << " page(s)." << endl;
        int nFileCountOut = nPageCount;
        time_t modTime = pInfile->GetModificationTime();

        switch (proc.getOutputFormat())
        {
          case CCmdLineProcessor::fmt_bmp:
            pOut = new CBMPFilter(nPageCount);
            break;
          case CCmdLineProcessor::fmt_pbm:
            pOut = new CPBMFilter(nPageCount);
            break;
          case CCmdLineProcessor::fmt_jpeg:
            pOut = new CJPEGFilter(nPageCount, proc.getJpegQuality());
            break;
          case CCmdLineProcessor::fmt_tiff:
            nFileCountOut = 1;  // all pages in one file
            pOut = new CTIFFFilter(nPageCount,
              proc.getTiffCompression(), modTime);
            break;
          case CCmdLineProcessor::fmt_tiff_single_pages:
            pOut = new CTIFFFilter(nPageCount,
              proc.getTiffCompression(), modTime);
            break;
        }

        CFile fileOut;
        if (bStdOut) {
          fileOut.OpenTemp();
          pOut->Init(&fileOut);
        }

        for (int nPage = 0; nPage < nPageCount; nPage++)
        {
          TSFFPage* pPage = pInfile->GetPage(nPage);
          if (pPage->height <= 0) {
            if (!bQuiet) {
              cout << "Skipping page (no lines)." << endl;
            }
            continue;
          }
          if (!bStdOut)
          {
            if (pathOutFileName.string().length()) {
              // A fixed name was given, so use it as a base name
              outPath = pathOutFileName;
              std::string orgExt = fs::extension(outPath);
              if (nFileCountOut > 1) {
                sprintf(acNumber, "_%03d", nPage+1);
                outPath = fs::change_extension(outPath, acNumber);
                if (orgExt.length()) {
                  std::string strTemp = outPath.string();
                  strTemp += orgExt;
                  outPath = fs::path(strTemp);
                }
              }
            } else {
              // Otherwise construct output filename from input filename
              outPath = pathOutDirectory / pathInFileName.leaf();
              if (nFileCountOut > 1) {
                sprintf(acNumber, "_%03d", nPage+1);
                outPath = fs::change_extension(outPath, acNumber);
                std::string strTemp = outPath.string();
                strTemp += pOut->GetExtension();
                outPath = fs::path(strTemp);
              } else {
                outPath = fs::change_extension(outPath, pOut->GetExtension());
              }
            }
            if (!proc.doOverwrite() && !((nPage > 0) && (nFileCountOut == 1)) && fs::exists(outPath)) {
              throw CSimpleException(CSimpleException::err_outfileexists);
            }
          }

          bool bIsLowRes = pInfile->IsLowRes(nPage);
          bool bDoubleLines = !proc.keepVRes() && bIsLowRes;

          if (!bQuiet) {
            if (!((nPage > 0) && (nFileCountOut == 1))) {
              cout << "- Destination File " << outPath.string() << " : " << endl;
            }
            cout << "  Converting page " << nPage+1
               << " (" << pPage->width << "x" << pPage->height << "px / ";
            cout << pPage->dpi << "x" << pPage->lpi << "dpi), ";
            cout << (bIsLowRes ? "LowRes" : "HiRes") << " ..." << endl;
          }

          if (!pInfile->SeekPage(nPage)) {
            throw CSimpleException(CSimpleException::err_corruptfile);
          }

          if (!bStdOut && !((nPage > 0) && (nFileCountOut == 1))) {
            fileOut.Open(outPath.string(), "wb+");
            pOut->Init(&fileOut);
          }

          if (bDoubleLines) {
            pOut->BeginPage(nPage, pPage->width,
              pPage->height*2, pPage->dpi, pPage->lpi*2);
          } else {
            pOut->BeginPage(nPage, pPage->width,
              pPage->height, pPage->dpi, pPage->lpi);
          }

          pOut->BlankLine();

          TSFFRecord rec;

          while (pInfile->GetRecord(rec))
          {
          switch(rec.type)
          {
            case NORMAL :
              pOut->BlankLine();
              if (pInfile->DecodeRecord(rec, pOut->GetBitSink())) {
                pOut->WriteLine();
                if (bDoubleLines) {
                  pOut->WriteLine();
                }
              }
              if (rec.pData != 0) free(rec.pData);
              break;
            case USERINFO :
              // not yet considered
              if (rec.pData != 0) free(rec.pData);
              break;
            case BADLINE :
              pOut->WriteLine();
              if (bDoubleLines) {
                pOut->WriteLine();
              }
              break;
            case WHITESKIP :
              pOut->BlankLine();
              for (int j=0; j < rec.cb; ++j) {
                pOut->WriteLine();
                if (bDoubleLines) {
                  pOut->WriteLine();
                }
              }
              break;
            }
          }
          pOut->EndPage();

          if (!bStdOut) {
            if ((nFileCountOut > 1) || ((nFileCountOut == 1) && (nPage == nPageCount-1))) {
              pOut->Finalize();
              fileOut.Close();
              if (proc.keepDate()) {
                fileOut.SetModificationTime(modTime);
              }
            }
          }
        }

        if (bStdOut) {
          fileOut.DumpToStdOut();
          fileOut.Close();
          if (pOut) {
            pOut->Finalize();
          }
        }

      }
      catch (const std::exception & e) {
        cerr << "ERROR: " << pathInFileName.string() << ": " << e.what() << endl;
        rc = 2;
      }
      catch (CSimpleException e) {
        cerr << "ERROR: " << pathInFileName.string() << ": " << e.what() << endl;
        rc = 2;
      }
      if (pOut) {
        delete pOut;
      }
      if (pInfile) {
        delete pInfile;
      }
      if (!bQuiet) cout << endl;
    }
    if (!bQuiet) cout << "Finished. " << endl << endl;
  }
  catch (const std::exception & e) {
    cerr << "ERROR: " << e.what() << endl;
    rc = 2;
  }
  catch (const CSimpleException& e) {
    cerr << "ERROR: " << e.what() << endl;
    rc = 2;
  }
  return rc;
}
Example #8
0
bool CTriMeshBuilder::Load (int nLevel)
{
	CFile					cf;
	tMeshDataHeader	mdh;
	int					nSize;
	bool					bOk;
	char					szFilename [FILENAME_LEN];
	char					*ioBuffer = NULL, *bufP;

if (!(gameStates.render.bTriangleMesh && gameStates.app.bCacheMeshes))
	return false;
if (!cf.Open (DataFilename (szFilename, nLevel), gameFolders.szCacheDir, "rb", 0))
	return false;
bOk = (cf.Read (&mdh, sizeof (mdh), 1) == 1);
if (bOk)
	bOk = (mdh.nVersion == MESH_DATA_VERSION) &&
			(mdh.nSegments == gameData.segs.nSegments) &&
			(mdh.nFaces == gameData.segs.nFaces);
if (bOk)
	nSize =
		(sizeof (*gameData.segs.vertices) +
		 sizeof (*gameData.segs.fVertices)) * mdh.nVertices +
		sizeof (*gameData.segs.faces.faces) * mdh.nFaces +
		sizeof (*gameData.segs.faces.tris) * mdh.nTris +
		(sizeof (*gameData.segs.faces.vertices) +
		 sizeof (*gameData.segs.faces.normals) +
		 sizeof (*gameData.segs.faces.texCoord) +
		 sizeof (*gameData.segs.faces.ovlTexCoord) +
		 sizeof (*gameData.segs.faces.color)) * mdh.nTris * 3 +
		 sizeof (*gameData.segs.faces.lMapTexCoord) * mdh.nFaces * 2 +
		 sizeof (*gameData.segs.faces.faceVerts) * mdh.nFaceVerts;
if (bOk)
	bOk = ((ioBuffer = (char *) D2_ALLOC (nSize)) != NULL);
if (bOk)
	bOk = cf.Read (ioBuffer, nSize, 1) == 1;
if (bOk) {
	bufP = ioBuffer;
	memcpy (gameData.segs.vertices, bufP, sizeof (*gameData.segs.vertices) * mdh.nVertices);
	bufP += sizeof (*gameData.segs.vertices) * mdh.nVertices;
	memcpy (gameData.segs.fVertices, bufP, sizeof (*gameData.segs.fVertices) * mdh.nVertices);
	bufP += sizeof (*gameData.segs.fVertices) * mdh.nVertices;
	memcpy (gameData.segs.faces.faces, bufP, sizeof (*gameData.segs.faces.faces) * mdh.nFaces);
	bufP += sizeof (*gameData.segs.faces.faces) * mdh.nFaces;
	memcpy (gameData.segs.faces.tris, bufP, sizeof (*gameData.segs.faces.tris) * mdh.nTris);
	bufP += sizeof (*gameData.segs.faces.tris) * mdh.nTris;
	memcpy (gameData.segs.faces.vertices, bufP, sizeof (*gameData.segs.faces.vertices) * mdh.nTris * 3);
	bufP +=  sizeof (*gameData.segs.faces.vertices) * mdh.nTris * 3;
	memcpy (gameData.segs.faces.normals, bufP, sizeof (*gameData.segs.faces.normals) * mdh.nTris * 3);
	bufP += sizeof (*gameData.segs.faces.normals) * mdh.nTris * 3;
	memcpy (gameData.segs.faces.texCoord, bufP, sizeof (*gameData.segs.faces.texCoord) * mdh.nTris * 3);
	bufP += sizeof (*gameData.segs.faces.texCoord) * mdh.nTris * 3;
	memcpy (gameData.segs.faces.ovlTexCoord, bufP, sizeof (*gameData.segs.faces.ovlTexCoord) * mdh.nTris * 3);
	bufP += sizeof (*gameData.segs.faces.ovlTexCoord) * mdh.nTris * 3;
	memcpy (gameData.segs.faces.color, bufP, sizeof (*gameData.segs.faces.color) * mdh.nTris * 3);
	bufP += sizeof (*gameData.segs.faces.color) * mdh.nTris * 3;
	memcpy (gameData.segs.faces.lMapTexCoord, bufP, sizeof (*gameData.segs.faces.lMapTexCoord) * mdh.nFaces * 2);
	bufP += sizeof (*gameData.segs.faces.lMapTexCoord) * mdh.nFaces * 2;
	memcpy (gameData.segs.faces.faceVerts, bufP, sizeof (*gameData.segs.faces.faceVerts) * mdh.nFaceVerts);
	}
if (ioBuffer)
	D2_FREE (ioBuffer);
if (bOk) {
	gameData.segs.nVertices = mdh.nVertices;
	gameData.segs.nTris = mdh.nTris;
	SetupVertexNormals ();
	}
cf.Close ();
CreateFaceVertLists ();
return bOk;
}
Example #9
0
void CRoutingZone::ReadFile(const wxString& specialNodesdat)
{
	if (m_superZone != NULL || (m_filename.IsEmpty() && specialNodesdat.IsEmpty())) {
		wxFAIL;
		return;
	}

	bool doHaveVerifiedContacts = false;
	// Read in the saved contact list
	try {
		uint32_t validContacts = 0;
		CFile file;
		if (CPath::FileExists(specialNodesdat.IsEmpty() ? m_filename : specialNodesdat) && file.Open(m_filename, CFile::read)) {
			// Get how many contacts in the saved list.
			// NOTE: Older clients put the number of contacts here...
			//       Newer clients always have 0 here to prevent older clients from reading it.
			uint32_t numContacts = file.ReadUInt32();
			uint32_t fileVersion = 0;
			if (numContacts == 0) {
				if (file.GetLength() >= 8) {
					fileVersion = file.ReadUInt32();
					if (fileVersion == 3) {
						uint32_t bootstrapEdition = file.ReadUInt32();
						if (bootstrapEdition == 1) {
							// this is a special bootstrap-only nodes.dat, handle it in a separate reading function
							ReadBootstrapNodesDat(file);
							file.Close();
							return;
						}
					}
					if (fileVersion >= 1 && fileVersion <= 3) {
						numContacts = file.ReadUInt32();
					}
				}
			} else {
				// Don't read version 0 nodes.dat files, because they can't tell the kad version of the contacts stored.
				AddLogLineC(_("Failed to read nodes.dat file - too old. This version (0) is not supported anymore."));
				numContacts = 0;
			}
			DEBUG_ONLY( unsigned kad1Count = 0; )
			if (numContacts != 0 && numContacts * 25 <= (file.GetLength() - file.GetPosition())) {
				for (uint32_t i = 0; i < numContacts; i++) {
					CUInt128 id = file.ReadUInt128();
					uint32_t ip = file.ReadUInt32();
					uint16_t udpPort = file.ReadUInt16();
					uint16_t tcpPort = file.ReadUInt16();
					uint8_t contactVersion = 0;
					contactVersion = file.ReadUInt8();
					CKadUDPKey kadUDPKey;
					bool verified = false;
					if (fileVersion >= 2) {
						kadUDPKey.ReadFromFile(file);
						verified = file.ReadUInt8() != 0;
						if (verified) {
							doHaveVerifiedContacts = true;
						}
					}
					// IP appears valid
					if (contactVersion > 1) {
						if(IsGoodIPPort(wxUINT32_SWAP_ALWAYS(ip),udpPort)) {
							if (!theApp->ipfilter->IsFiltered(wxUINT32_SWAP_ALWAYS(ip)) &&
							    !(udpPort == 53 && contactVersion <= 5 /*No DNS Port without encryption*/)) {
								// This was not a dead contact, inc counter if add was successful
								if (AddUnfiltered(id, ip, udpPort, tcpPort, contactVersion, kadUDPKey, verified, false, false)) {
									validContacts++;
								}
							}
						}
					} else {
						DEBUG_ONLY( kad1Count++; )
					}
				}
			}
			file.Close();
			AddLogLineN(CFormat(wxPLURAL("Read %u Kad contact", "Read %u Kad contacts", validContacts)) % validContacts);
#ifdef __DEBUG__
			if (kad1Count > 0) {
				AddDebugLogLineN(logKadRouting, CFormat(wxT("Ignored %u kad1 %s in nodes.dat file.")) % kad1Count % (kad1Count > 1 ? wxT("contacts"): wxT("contact")));
			}
#endif
			if (!doHaveVerifiedContacts) {
				AddDebugLogLineN(logKadRouting, wxT("No verified contacts found in nodes.dat - might be an old file version. Setting all contacts verified for this time to speed up Kad bootstrapping."));
				SetAllContactsVerified();
			}
		}
Example #10
0
bool CEdl::ReadVideoReDo(const CStdString& strMovie)
{
  /*
   * VideoReDo file is strange. Tags are XML like, but it isn't an XML file.
   *
   * http://www.videoredo.com/
   */

  Clear();
  CStdString videoReDoFilename(URIUtils::ReplaceExtension(strMovie, ".Vprj"));
  if (!CFile::Exists(videoReDoFilename))
    return false;

  CFile videoReDoFile;
  if (!videoReDoFile.Open(videoReDoFilename))
  {
    CLog::Log(LOGERROR, "%s - Could not open VideoReDo file: %s", __FUNCTION__, videoReDoFilename.c_str());
    return false;
  }

  char szBuffer[1024];
  if (videoReDoFile.ReadString(szBuffer, 1023)
  &&  strncmp(szBuffer, VIDEOREDO_HEADER, strlen(VIDEOREDO_HEADER)) != 0)
  {
    CLog::Log(LOGERROR, "%s - Invalid VideoReDo file: %s. Error reading line 1 - expected %s. Only version 2 files are supported.",
              __FUNCTION__, videoReDoFilename.c_str(), VIDEOREDO_HEADER);
    videoReDoFile.Close();
    return false;
  }

  int iLine = 1;
  bool bValid = true;
  while (bValid && videoReDoFile.ReadString(szBuffer, 1023))
  {
    iLine++;
    if (strncmp(szBuffer, VIDEOREDO_TAG_CUT, strlen(VIDEOREDO_TAG_CUT)) == 0) // Found the <Cut> tag
    {
      /*
       * double is used as 32 bit float would overflow.
       */
      double dStart, dEnd;
      if (sscanf(szBuffer + strlen(VIDEOREDO_TAG_CUT), "%lf:%lf", &dStart, &dEnd) == 2)
      {
        /*
         *  Times need adjusting by 1/10,000 to get ms.
         */
        Cut cut;
        cut.start = (int64_t)(dStart / 10000);
        cut.end = (int64_t)(dEnd / 10000);
        cut.action = CUT;
        bValid = AddCut(cut);
      }
      else
        bValid = false;
    }
    else if (strncmp(szBuffer, VIDEOREDO_TAG_SCENE, strlen(VIDEOREDO_TAG_SCENE)) == 0) // Found the <SceneMarker > tag
    {
      int iScene;
      double dSceneMarker;
      if (sscanf(szBuffer + strlen(VIDEOREDO_TAG_SCENE), " %i>%lf", &iScene, &dSceneMarker) == 2)
        bValid = AddSceneMarker((int64_t)(dSceneMarker / 10000)); // Times need adjusting by 1/10,000 to get ms.
      else
        bValid = false;
    }
    /*
     * Ignore any other tags.
     */
  }
  videoReDoFile.Close();

  if (!bValid)
  {
    CLog::Log(LOGERROR, "%s - Invalid VideoReDo file: %s. Error in line %i. Clearing any valid cuts or scenes found.",
              __FUNCTION__, videoReDoFilename.c_str(), iLine);
    Clear();
    return false;
  }
  else if (HasCut() || HasSceneMarker())
  {
    CLog::Log(LOGDEBUG, "%s - Read %"PRIuS" cuts and %"PRIuS" scene markers in VideoReDo file: %s", __FUNCTION__,
              m_vecCuts.size(), m_vecSceneMarkers.size(), videoReDoFilename.c_str());
    return true;
  }
  else
  {
    CLog::Log(LOGDEBUG, "%s - No cuts or scene markers found in VideoReDo file: %s", __FUNCTION__,
              videoReDoFilename.c_str());
    return false;
  }
}
UINT SQLiteRecover::GetDataFromPages(CString PageFileName, UINT PageSize_parm, UINT EncodedType_parm)
{
	CFile PageFile;
	if (PageFile.Open(PageFileName, CFile::modeRead | CFile::shareDenyNone) != TRUE)
	{
		return PROCESS_FAIL;
	}

	this->PageSize = PageSize_parm;

	UINT8 *PageBuff;
	PageBuff = (UINT8 *)malloc(this->PageSize);

	UINT totalPageCount = 0;
	UINT classifiedPageCount = 0;
	UINT pageSignature = 0;

	UINT   readSize = 0;
	UINT64 totalSize = 0;
	UINT64 srcFileSize = PageFile.GetLength();

	while(srcFileSize > totalSize)
	{
		if(srcFileSize-totalSize < this->PageSize)
			readSize = (UINT)(srcFileSize-totalSize);
		else
			readSize = this->PageSize;

		if(PageFile.Read(PageBuff, this->PageSize) != readSize)
		{
			break;
		}
		
		//-------------------------------------------------------------------------------

		RecordPageExtractor PageExtractModule(this->PageSize, EncodedType_parm);

		PageExtractModule.GetNormalRecordSet(PageBuff);
		
		UINT type = 0;
		TableData tTableData;
		tTableData.pageOffset = totalSize;
		tTableData.FieldArray = new ARRFieldArray;
		tTableData.NorRowArray = new ARRRowArray;
		tTableData.DelRowArray = new ARRRowArray; 

		// NormalTable_InPage
		for(int jdx = 0 ; jdx < PageExtractModule.NormalTable_InPage.GetCount() ; jdx++)
		{
			CRowArray RowArr;
			RowArr = PageExtractModule.NormalTable_InPage.GetAt(jdx);
			tTableData.NorRowArray->Add(RowArr);

			ARRField arrField;
			CTypeArray TypeArr;
			TypeArr = PageExtractModule.Types_InPage.GetAt(jdx);

			for(int i = 0 ; i < TypeArr.GetCount() ; i++)
			{
				type = TypeArr.GetAt(i);

				Field field;
				field.cid.Format(_T("%d"), i);

				switch(type)
				{
				case TYPE_NULL:
					field.type = _T("NULL");
					field.length = -1;	
					break;
				case TYPE_INTEGER0:
					field.type = _T("INTEGER");
					field.length = 0;
					break;
				case TYPE_INTEGER1:
					field.type = _T("INTEGER");
					field.length = 1;
					break;
				case TYPE_INTEGER2:
					field.type = _T("INTEGER");
					field.length = 2;
					break;
				case TYPE_INTEGER3:
					field.type = _T("INTEGER");
					field.length = 3;
					break;
				case TYPE_INTEGER4:
					field.type = _T("INTEGER");
					field.length = 4;
					break;
				case TYPE_INTEGER6:
					field.type = _T("INTEGER");
					field.length = 6;
					break;
				case TYPE_INTEGER8:
					field.type = _T("INTEGER");
					field.length = 8;
					break;
				case TYPE_NUMERIC:
					field.type = _T("IEEE754");
					field.length = 9;
					break;
				case TYPE_BLOB:
					field.type = _T("BLOB");
					field.length = 12;	// variable length
					break;
				case TYPE_TEXT:
					field.type = _T("TEXT");
					field.length = 13;	// variable length
					break;
				}

				arrField.Add(field);
			}

			tTableData.FieldArray->Add(arrField);
		}

		arrTableData.Add(tTableData);
		
		//-------------------------------------------------------------------------------

		ZeroMemory(PageBuff, this->PageSize);

		totalSize += readSize;
		totalPageCount++;
	}

	safe_free(PageBuff);
	PageFile.Close();
	return TRUE;
}
Example #12
0
bool CEdl::ReadComskip(const CStdString& strMovie, const float fFramesPerSecond)
{
  Clear();

  CStdString comskipFilename(URIUtils::ReplaceExtension(strMovie, ".txt"));
  if (!CFile::Exists(comskipFilename))
    return false;

  CFile comskipFile;
  if (!comskipFile.Open(comskipFilename))
  {
    CLog::Log(LOGERROR, "%s - Could not open Comskip file: %s", __FUNCTION__, comskipFilename.c_str());
    return false;
  }

  char szBuffer[1024];
  if (comskipFile.ReadString(szBuffer, 1023)
  &&  strncmp(szBuffer, COMSKIP_HEADER, strlen(COMSKIP_HEADER)) != 0) // Line 1.
  {
    CLog::Log(LOGERROR, "%s - Invalid Comskip file: %s. Error reading line 1 - expected '%s' at start.",
              __FUNCTION__, comskipFilename.c_str(), COMSKIP_HEADER);
    comskipFile.Close();
    return false;
  }

  int iFrames;
  float fFrameRate;
  if (sscanf(szBuffer, "FILE PROCESSING COMPLETE %i FRAMES AT %f", &iFrames, &fFrameRate) != 2)
  {
    /*
     * Not all generated Comskip files have the frame rate information.
     */
    fFrameRate = fFramesPerSecond;
    CLog::Log(LOGWARNING, "%s - Frame rate not in Comskip file. Using detected frames per second: %.3f",
              __FUNCTION__, fFrameRate);
  }
  else
    fFrameRate /= 100; // Reduce by factor of 100 to get fps.

  comskipFile.ReadString(szBuffer, 1023); // Line 2. Ignore "-------------"

  bool bValid = true;
  int iLine = 2;
  while (bValid && comskipFile.ReadString(szBuffer, 1023)) // Line 3 and onwards.
  {
    iLine++;
    double dStartFrame, dEndFrame;
    if (sscanf(szBuffer, "%lf %lf", &dStartFrame, &dEndFrame) == 2)
    {
      Cut cut;
      cut.start = (int64_t)(dStartFrame / fFrameRate * 1000);
      cut.end = (int64_t)(dEndFrame / fFrameRate * 1000);
      cut.action = COMM_BREAK;
      bValid = AddCut(cut);
    }
    else
      bValid = false;
  }
  comskipFile.Close();

  if (!bValid)
  {
    CLog::Log(LOGERROR, "%s - Invalid Comskip file: %s. Error on line %i. Clearing any valid commercial breaks found.",
              __FUNCTION__, comskipFilename.c_str(), iLine);
    Clear();
    return false;
  }
  else if (HasCut())
  {
    CLog::Log(LOGDEBUG, "%s - Read %"PRIuS" commercial breaks from Comskip file: %s", __FUNCTION__, m_vecCuts.size(),
              comskipFilename.c_str());
    return true;
  }
  else
  {
    CLog::Log(LOGDEBUG, "%s - No commercial breaks found in Comskip file: %s", __FUNCTION__, comskipFilename.c_str());
    return false;
  }
}
Example #13
0
bool CEdl::ReadEdl(const CStdString& strMovie, const float fFramesPerSecond)
{
  Clear();

  CStdString edlFilename(URIUtils::ReplaceExtension(strMovie, ".edl"));
  if (!CFile::Exists(edlFilename))
    return false;

  CFile edlFile;
  if (!edlFile.Open(edlFilename))
  {
    CLog::Log(LOGERROR, "%s - Could not open EDL file: %s", __FUNCTION__, edlFilename.c_str());
    return false;
  }

  bool bError = false;
  int iLine = 0;
  CStdString strBuffer;
  while (edlFile.ReadString(strBuffer.GetBuffer(1024), 1024))
  {
    strBuffer.ReleaseBuffer();

    // Log any errors from previous run in the loop
    if (bError)
      CLog::Log(LOGWARNING, "%s - Error on line %i in EDL file: %s", __FUNCTION__, iLine, edlFilename.c_str());

    bError = false;

    iLine++;

    CStdStringArray strFields(2);
    int iAction;
    int iFieldsRead = sscanf(strBuffer, "%512s %512s %i", strFields[0].GetBuffer(512),
                             strFields[1].GetBuffer(512), &iAction);
    strFields[0].ReleaseBuffer();
    strFields[1].ReleaseBuffer();

    if (iFieldsRead != 2 && iFieldsRead != 3) // Make sure we read the right number of fields
    {
      bError = true;
      continue;
    }

    if (iFieldsRead == 2) // If only 2 fields read, then assume it's a scene marker.
    {
      iAction = atoi(strFields[1]);
      strFields[1] = strFields[0];
    }

    /*
     * For each of the first two fields read, parse based on whether it is a time string
     * (HH:MM:SS.sss), frame marker (#12345), or normal seconds string (123.45).
     */
    int64_t iCutStartEnd[2];
    for (int i = 0; i < 2; i++)
    {
      if (strFields[i].Find(":") != -1) // HH:MM:SS.sss format
      {
        CStdStringArray fieldParts;
        StringUtils::SplitString(strFields[i], ".", fieldParts);
        if (fieldParts.size() == 1) // No ms
        {
          iCutStartEnd[i] = StringUtils::TimeStringToSeconds(fieldParts[0]) * 1000; // seconds to ms
        }
        else if (fieldParts.size() == 2) // Has ms. Everything after the dot (.) is ms
        {
          /*
           * Have to pad or truncate the ms portion to 3 characters before converting to ms.
           */
          if (fieldParts[1].length() == 1)
          {
            fieldParts[1] = fieldParts[1] + "00";
          }
          else if (fieldParts[1].length() == 2)
          {
            fieldParts[1] = fieldParts[1] + "0";
          }
          else if (fieldParts[1].length() > 3)
          {
            fieldParts[1] = fieldParts[1].Left(3);
          }
          iCutStartEnd[i] = StringUtils::TimeStringToSeconds(fieldParts[0]) * 1000 + atoi(fieldParts[1]); // seconds to ms
        }
        else
        {
          bError = true;
          continue;
        }
      }
      else if (strFields[i].Left(1) == "#") // #12345 format for frame number
      {
        iCutStartEnd[i] = (int64_t)(atol(strFields[i].Mid(1)) / fFramesPerSecond * 1000); // frame number to ms
      }
      else // Plain old seconds in float format, e.g. 123.45
      {
        iCutStartEnd[i] = (int64_t)(atof(strFields[i]) * 1000); // seconds to ms
      }
    }

    if (bError) // If there was an error in the for loop, ignore and continue with the next line
      continue;

    Cut cut;
    cut.start = iCutStartEnd[0];
    cut.end = iCutStartEnd[1];

    switch (iAction)
    {
    case 0:
      cut.action = CUT;
      if (!AddCut(cut))
      {
        CLog::Log(LOGWARNING, "%s - Error adding cut from line %i in EDL file: %s", __FUNCTION__,
                  iLine, edlFilename.c_str());
        continue;
      }
      break;
    case 1:
      cut.action = MUTE;
      if (!AddCut(cut))
      {
        CLog::Log(LOGWARNING, "%s - Error adding mute from line %i in EDL file: %s", __FUNCTION__,
                  iLine, edlFilename.c_str());
        continue;
      }
      break;
    case 2:
      if (!AddSceneMarker(cut.end))
      {
        CLog::Log(LOGWARNING, "%s - Error adding scene marker from line %i in EDL file: %s",
                  __FUNCTION__, iLine, edlFilename.c_str());
        continue;
      }
      break;
    case 3:
      cut.action = COMM_BREAK;
      if (!AddCut(cut))
      {
        CLog::Log(LOGWARNING, "%s - Error adding commercial break from line %i in EDL file: %s",
                  __FUNCTION__, iLine, edlFilename.c_str());
        continue;
      }
      break;
    default:
      CLog::Log(LOGWARNING, "%s - Invalid action on line %i in EDL file: %s", __FUNCTION__, iLine,
                edlFilename.c_str());
      continue;
    }
  }

  strBuffer.ReleaseBuffer();

  if (bError) // Log last line warning, if there was one, since while loop will have terminated.
    CLog::Log(LOGWARNING, "%s - Error on line %i in EDL file: %s", __FUNCTION__, iLine, edlFilename.c_str());

  edlFile.Close();

  if (HasCut() || HasSceneMarker())
  {
    CLog::Log(LOGDEBUG, "%s - Read %"PRIuS" cuts and %"PRIuS" scene markers in EDL file: %s", __FUNCTION__,
              m_vecCuts.size(), m_vecSceneMarkers.size(), edlFilename.c_str());
    return true;
  }
  else
  {
    CLog::Log(LOGDEBUG, "%s - No cuts or scene markers found in EDL file: %s", __FUNCTION__,
              edlFilename.c_str());
    return false;
  }
}
Example #14
0
void CTimeEv::OnTeTakePict() 
{
//	CWnd*		pWnd = CWnd::GetDesktopWindow();
	CWindowDC	dc(this);
	CDC			memDC;
	CRect		rect;
	CBitmap		bitmap;
	CClientDC	pDC(this);


//	pWnd->GetWindowRect(rect);
	GetWindowRect(rect);
	memDC.CreateCompatibleDC(&dc);
//	bitmap.CreateCompatibleBitmap(&dc,rect.right,rect.bottom);
	bitmap.CreateCompatibleBitmap(&dc,rect.Width(),rect.Height());

	CBitmap *oldBM = memDC.SelectObject(&bitmap);
//	memDC.BitBlt(rect.left, rect.top, rect.Width(), rect.Height(), &dc, 0, 0, SRCCOPY);
	memDC.BitBlt(0, 0, rect.Width(), rect.Height(), &dc, 0, 0, SRCCOPY);
	
	BITMAP bm;
	bitmap.GetObject(sizeof(bm),&bm);

//	pDC.BitBlt(0, 0, rect.right, rect.bottom, &memDC, 0, 0, SRCCOPY);
	pDC.BitBlt(0, 0, rect.Width(), rect.Height(), &memDC, 0, 0, SRCCOPY);

	

	CFile file;
	file.Open("a.pcx",CFile::modeWrite | CFile::modeCreate);
	CreatePCXHeader(&file,rect.Width(),rect.Height());
	
	short *bmBit;
	RGBQUAD *rgbQuad;
	bmBit = (short*) malloc (bm.bmHeight * bm.bmWidthBytes * 2);
	int n = bitmap.GetBitmapBits(bm.bmHeight * bm.bmWidthBytes, bmBit);

	rgbQuad = (RGBQUAD*) malloc (bm.bmHeight * bm.bmWidthBytes * sizeof(RGBQUAD));
	

	for (int y=0; y< rect.Height();y++)
	{
		for (char hl=0; hl<3; hl++)
		{
			for (int x=0; x < rect.Width();x++)
			{
				char byte; RGBQUAD rgb;
				rgb = QuadFromWord( bmBit[y*rect.Width() + x]);
				if (hl == 0)
					byte = rgb.rgbRed;
				if (hl == 1)
					byte = rgb.rgbGreen;
				if (hl == 2)
					byte = rgb.rgbBlue;
				char toWr;
				toWr = (char) 0xC1;
				file.Write(&toWr,1);
				file.Write(&byte,1);
			}
		}
	}		

	free(bmBit);
	free(rgbQuad);
	
	file.Close();

	char txt[300];
	sprintf(txt,"type:%d, width:%d, height:%d, widthbytes:%d, planes:%d, BitsPixel:%d,",
		bm.bmType, bm.bmWidth, bm.bmHeight, bm.bmWidthBytes, bm.bmPlanes, bm.bmBitsPixel);
//	sprintf(txt,"%d %d", rect.left,rect.right);
	pDC.TextOut(10,10,txt);

	memDC.SelectObject(oldBM);
	MessageBeep(0);
}
Example #15
0
FileState SendFile(SOCKET socket, HWND hWrapperWnd, LPCTSTR strFilePathName, ULONGLONG llStartAt)
{
	//gl_SenderStop = false;
	gl_mapSenderStop[hWrapperWnd] = false;
	PostMessage(hWrapperWnd, WM_FILE_OPERATE_BEGIN, 1, 0);

	FileState MyFileState = S_FileOK, YouFileState = S_FileOK;

	//check dir
	CString strFileName = strFilePathName;
	CDestFolderHelper folderHelper;
	if (!folderHelper.IsDestFileExist(strFileName))
		MyFileState = S_FileNotExits;

	//open file
	CFile LocalFile;
	if(!LocalFile.Open(strFileName, CFile::modeRead | CFile::typeBinary))
	{
		if(MyFileState == S_FileOK)
			MyFileState = S_OpenFileFailed;
	}

	if (MyFileState != S_OpenFileFailed)
	{
		ULONGLONG uSeeked = LocalFile.Seek(llStartAt, CFile::begin);
		if (uSeeked != llStartAt)
		{
			MyFileState = S_CreateFileFailed;
		}
	}

	//get file time
	FILETIME fileTime;
	if(!GetFileTime(LocalFile.m_hFile, NULL, NULL, &fileTime))
	{
		if(MyFileState == S_FileOK)
			MyFileState = S_GetFileInfoFailed;
	}

	//send my file operate state
	if(!SendData(socket, (char*)&MyFileState, sizeof(FileState)))
	{
		if(MyFileState != S_FileNotExits && MyFileState != S_OpenFileFailed)
			LocalFile.Close();
		return S_SocketError;
	}

	//receive you file operate state
	if(!ReceiveData(socket, (char*)&YouFileState, sizeof(FileState)))
	{
		LocalFile.Close();
		return S_SocketError;
	}

	if(MyFileState != S_FileOK) return MyFileState;
	if(YouFileState != S_FileOK) return YouFileState;

	//init basicFileInfo
	BasicFileInfo basicFileInfo;
	basicFileInfo.CreationTime = fileTime;
	char* pFileName = (LPSTR)(LPCTSTR)(LocalFile.GetFileName());
	memset(&(basicFileInfo.FileName), 0, MAX_PATH);
	CopyMemory(&(basicFileInfo.FileName), pFileName, LocalFile.GetFileName().GetLength());
	basicFileInfo.Size = LocalFile.GetLength();

	//send file info
	if (!SendData(socket, (char*)(&basicFileInfo), sizeof(basicFileInfo)))
	{
		LocalFile.Close();
		return S_SocketError;
	}
	ULONGLONG nDes = LocalFile.GetLength() > 1024 * 1024 * 1024 ? 1024 * 1024 : 1024;	//file's size larger than 1G.
	PostMessage(hWrapperWnd, WM_FILE_SETRANGE_MESSAGE, (WPARAM)(LocalFile.GetLength() / nDes), (LPARAM)0);

	ULONGLONG nRead = llStartAt;
	ULONGLONG nResCount = 0;
	ULONGLONG nFileLength = LocalFile.GetLength();
	FileDataEx fileData;
	
	PostMessage(hWrapperWnd, WM_FILE_SENDFILETOSERVER_PROGRESS_MESSAGE, (WPARAM)(nRead / nDes), 0);
	if (gl_pLogger) gl_pLogger->log_info("SendFile Begin to send: %s", strFilePathName);

	bool *pbstatus = NULL;
	SendMessage(hWrapperWnd, WM_GETSENDSTATE, 0, (LPARAM)&pbstatus);
	//send loop
	while(1)
	{
		int nCount = 0;
		try{
			nCount= LocalFile.Read(fileData.data.Buf, FILEDATASIZE);
		}
		catch(...){
			fileData.state = S_ReadFileFailed;
		}
		fileData.data.nLength = nCount;
		nRead += nCount;

		fileData.state = (*pbstatus) ? S_FileContinue : S_IStop;
		if(nRead == nFileLength)
			fileData.state = S_Finished;
		
		//if(gl_SenderStop)
		if (gl_mapSenderStop.find(hWrapperWnd) != gl_mapSenderStop.end() && gl_mapSenderStop[hWrapperWnd] == true)
		{
			fileData.state = S_IStop;
		}		

		if (!SendData(socket, (char*)(&fileData), sizeof(fileData)))
		{
			LocalFile.Close();
			return S_SocketError;
		}

		if (fileData.data.nLength == 0)
			break;

		if(fileData.state == S_IStop)// || fileData.state == S_ReadFileFailed
		{
			LocalFile.Close();
			return fileData.state;
		}
		
		if(fileData.state == S_Finished)// || fileData.state == S_ReadFileFailed
		{
			LocalFile.Close();
			return fileData.state;
		}

		nResCount++;
		if(nResCount % READWRITESTATUS == 0)
		{
			Sleep(3);
			nResCount = 0;
			
			FileState MyState,YouState;

			if(fileData.state == S_ReadFileFailed)
				MyState = S_ReadFileFailed;
			else
				MyState = (*pbstatus) ? S_FileContinue : S_IStop;

			if(!SendData(socket, (char*)&MyState, sizeof(FileState)))
			{
				LocalFile.Close();
				return S_SocketError;
			}
			if(!ReceiveData(socket, (char*)&YouState, sizeof(FileState)))
			{
				LocalFile.Close();
				return S_SocketError;
			}
			
			if(YouState == S_WriteFileFailed || YouState == S_IStop)
			{
				LocalFile.Close();
				if (YouState == S_IStop)
					return S_OtherSideStop;
				return YouState;
			}

			if(MyState == S_ReadFileFailed || MyState == S_IStop)
			{
				LocalFile.Close();
				if (MyState == S_IStop)
					return S_IStop;
				return MyState;
			}
		}

		PostMessage(hWrapperWnd, WM_FILE_SENDFILETOSERVER_PROGRESS_MESSAGE, (WPARAM)(nRead / nDes), 0);
	}

	return S_Finished;
}
Example #16
0
// Does:   Saves The Picture That Is Stored In The IPicture Object As a Bitmap
// ~~~~    (Converts From Any Known Picture Type To a Bitmap / Icon File)
//
// InPut:  sFilePathName - Path And FileName Target To Save
// ~~~~~
//
// OutPut: TRUE If Succeeded...
// ~~~~~~
//-----------------------------------------------------------------------------
BOOL CPicture_Ex::SaveAsBitmap(CString sFilePathName)
//=============================================================================
{
 BOOL bResult = FALSE;
 ILockBytes *Buffer = 0;
 IStorage   *pStorage = 0;
 IStream    *FileStream = 0;
 BYTE    *BufferBytes;
 STATSTG  BytesStatistics;
 DWORD  OutData;
 long  OutStream;
 CFile  BitmapFile; CFileException e;
 double  SkipFloat = 0;
 DWORD  ByteSkip = 0;
 _ULARGE_INTEGER RealData;



 CreateILockBytesOnHGlobal(NULL, TRUE, &Buffer); // Create ILockBytes Buffer



 HRESULT hr = ::StgCreateDocfileOnILockBytes(Buffer,
     STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, &pStorage);



 hr = pStorage->CreateStream(L"PICTURE",
   STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, 0, &FileStream);



 m_pPict->SaveAsFile(FileStream, TRUE, &OutStream); // Copy Data Stream
 FileStream->Release();
 pStorage->Release();
 Buffer->Flush(); 



 // Get Statistics For Final Size Of Byte Array
 Buffer->Stat(&BytesStatistics, STATFLAG_NONAME);



 // Cut UnNeeded Data Coming From SaveAsFile() (Leave Only "Pure" Picture Data)
 SkipFloat = (double(OutStream) / 512); // Must Be In a 512 Blocks...
 if(SkipFloat > DWORD(SkipFloat)) ByteSkip = (DWORD)SkipFloat + 1;
 else ByteSkip = (DWORD)SkipFloat;
 ByteSkip = ByteSkip * 512; // Must Be In a 512 Blocks...
 
 // Find Difference Between The Two Values
 ByteSkip = (DWORD)(BytesStatistics.cbSize.QuadPart - ByteSkip);



 // Allocate Only The "Pure" Picture Data
 RealData.LowPart = 0;
 RealData.HighPart = 0;
 RealData.QuadPart = ByteSkip;
 BufferBytes = (BYTE*)malloc(OutStream);
 if(BufferBytes == NULL)
  {
  Buffer->Release();
  HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
  MessageBoxEx(hWnd, "Can not allocate enough memory\t", "ERROR"/*ERROR_TITLE*/, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
  }



 Buffer->ReadAt(RealData, BufferBytes, OutStream, &OutData);



 if(BitmapFile.Open(sFilePathName, CFile::typeBinary | CFile::modeCreate | CFile::modeWrite, &e))
  {
  BitmapFile.Write(BufferBytes, OutData);
  BitmapFile.Close();
  bResult = TRUE;
  }
 else // Write File Failed...
  {
  TCHAR szCause[255];
  e.GetErrorMessage(szCause, 255, NULL);
  HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
  MessageBoxEx(hWnd, szCause, "ERROR"/*ERROR_TITLE*/, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
  bResult = FALSE;
  }
 
 Buffer->Release();
 free(BufferBytes);



 return(bResult);
}
BOOL CFileExecutor::ShowBitziTicket(DWORD nIndex)
{
	CString str;

	if ( ! Settings.Library.BitziOkay )
	{
		Skin.LoadString( str, IDS_LIBRARY_BITZI_MESSAGE );
		if ( AfxMessageBox( str, MB_ICONQUESTION|MB_YESNO ) != IDYES ) return FALSE;
		Settings.Library.BitziOkay = TRUE;
		Settings.Save();
	}

	CSingleLock pLock( &Library.m_pSection, TRUE );

	CLibraryFile* pFile = Library.LookupFile( nIndex );
	if ( pFile == NULL ) return FALSE;

	if ( pFile->m_bSHA1 == FALSE || pFile->m_bTiger == FALSE )
	{
		CString strFormat;
		Skin.LoadString( strFormat, IDS_LIBRARY_BITZI_HASHED );
		str.Format( strFormat, (LPCTSTR)pFile->m_sName );
		pLock.Unlock();
		AfxMessageBox( str, MB_ICONINFORMATION );
		return FALSE;
	}

	CString strURL = Settings.Library.BitziWebView;
	CFile hFile;

	if ( hFile.Open( pFile->GetPath(), CFile::modeRead|CFile::shareDenyNone ) && hFile.GetLength() > 0 )
	{
		static LPCTSTR pszHex = _T("0123456789ABCDEF");
		BYTE nBuffer[20];
		int nPeek = hFile.Read( nBuffer, 20 );
		hFile.Close();
		str.Empty();

		for ( int nByte = 0 ; nByte < nPeek ; nByte++ )
		{
			str += pszHex[ (BYTE)nBuffer[ nByte ] >> 4 ];
			str += pszHex[ (BYTE)nBuffer[ nByte ] & 15 ];
		}

		strURL = Settings.Library.BitziWebSubmit;
		Replace( strURL, _T("(FIRST20)"), str );
	}

	Replace( strURL, _T("(NAME)"), CConnection::URLEncode( pFile->m_sName ) );
	Replace( strURL, _T("(SHA1)"), CSHA::HashToString( &pFile->m_pSHA1 ) );
	Replace( strURL, _T("(TTH)"), CTigerNode::HashToString( &pFile->m_pTiger ) );
	Replace( strURL, _T("(AGENT)"), CConnection::URLEncode( Settings.SmartAgent() ) );

	str.Format( _T("%I64i"), pFile->GetSize() );
	Replace( strURL, _T("(SIZE)"), str );

	pLock.Unlock();

	DisplayURL( strURL );

	return TRUE;
}
Example #18
0
bool CmySvmArth::ChangeDataFormat(const char* pPath)
{
	CFileFind finder;
	Stringoper oper;
	if(!finder.FindFile(oper.tocstring(pPath)))
		return false;
	FILE *file = NULL;
	CFile fwrite;
	if((file=fopen(pPath,"r"))==NULL)
	{
		TRACE("Open Source file Failed\n");
		return false;
	}
	if(!fwrite.Open(TmpFileName , CFile::modeWrite|CFile::modeCreate))
	{
		TRACE("Open Dest file Failed\n");
		return false;
	}
	unsigned int num_input, num_output, num_data, i, j;
	unsigned int line = 1;
	//read the head.
	if(fscanf(file, "%u %u %u\n", &num_data, &num_input, &num_output) != 3)
	{
		TRACE("Read the File Head failed ");
		TRACE("Read error in Line:%d\n",line);
		return false;
	}
	line++;
	double *pd = new double[num_input];
	double *pt = new double[num_output];
	for (int i=0;i<num_data;i++)
	{
		for (int j=0;j<num_input;j++)
		{
			if(fscanf(file, "%le" " ",&pd[j]) != 1)
			{
				delete pd;
				delete pt;
				TRACE("Read error in Line:%d\n",line);
				return false;
			}
		}
		for (int j=0;j<num_output;j++)
		{
			if(fscanf(file, "%le" " ",&pt[j]) != 1)
			{
				delete pd;
				delete pt;
				TRACE("Read error in Line:%d\n",line);
				return false;
			}
		}
		line++;
		
		string str = pt[0]>=0?"+1 ":"-1 ";
		stringstream ss(stringstream::in | stringstream::out);
		for (int j=0;j<num_input;j++)
		{
			ss.clear();
			ss.str("");
			ss<<(j+1);
			str += ss.str();
			ss.str("");
			ss<<pd[j];
			str += ":"+ss.str()+" ";
		}
		str +="\r\n";
		fwrite.Write(str.c_str() , str.length());
	}
	delete pt;
	delete pd;
	fwrite.Close();
	fclose(file);
	return true;
}
Example #19
0
void CDlgAlarmAnalysis::OnBnClickedOutput()
{
	CFileDialog dlg(FALSE, "txt", "alarmamalyse.txt", 
		OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, 
		_T("文本文件(*.txt)|*.txt|所有文件|*.*||"), this);
	if( dlg.DoModal() == IDOK )
	{
		CString strFileName;
		strFileName = dlg.GetPathName();
		CFile file;
		int nCount;
		file.Open(strFileName, CFile::modeWrite | CFile::modeCreate);
		AlarmDisplayData* pData;
		strFileName.Format("%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n",
							HS_ALARM_ALALYSE_STK,
							HS_ALARM_ALALYSE_NAME,	
							HS_ALARM_ALALYSE_TIME,	
							HS_ALARM_ALALYSE_DATA2,	
							HS_ALARM_ALALYSE_DATA3,	
							HS_ALARM_ALALYSE_DATA4,
							HS_ALARM_ALALYSE_DESC);

		file.Write(strFileName, strFileName.GetLength());

		CString strTime;

		for( int i = 0; i < m_ayDiaplayIndex.GetSize(); i++ )
		{
			pData = m_pDisplayData->GetAt(m_ayDiaplayIndex.GetAt(i));
			nCount = pData->m_ayOtherData.GetSize();
			pData->GetStrTime(strTime);
			switch( nCount )
			{
			case 0 :
			default:
				{
					strFileName.Format("%s\t\t%s\t%s\t\t\t\t\t\t\t\t%s\r\n", 
						pData->m_Stock.GetCode(), pData->m_strName, strTime, 
						pData->m_strDesc);
				}
				break;
			case 1 :
				{
					strFileName.Format("%s\t\t%s\t%s\t\t%.2f\t\t\t\t\t\t%s\r\n", 
						pData->m_Stock.GetCode(), pData->m_strName, strTime, 
						pData->m_ayOtherData.GetAt(0), 
						pData->m_strDesc);
				}
				break;
			case 2 :
				{
					strFileName.Format("%s\t\t%s\t%s\t\t%.2f\t\t%.2f\t\t\t\t%s\r\n", 
						pData->m_Stock.GetCode(), pData->m_strName,  strTime,
						pData->m_ayOtherData.GetAt(0), 
						pData->m_ayOtherData.GetAt(1), 
						pData->m_strDesc);
				}
				break;
			case 3 :
				{
					strFileName.Format("%s\t\t%s\t%s\t\t%.2f\t\t%.2f\t\t%.2f\t\t%s\r\n", 
						pData->m_Stock.GetCode(), pData->m_strName, strTime, 
						pData->m_ayOtherData.GetAt(0), 
						pData->m_ayOtherData.GetAt(1), 
						pData->m_ayOtherData.GetAt(2), 
						pData->m_strDesc);
				}
				break;
			}
			file.Write(strFileName, strFileName.GetLength());
		}
		file.Close();
	}
}
void CTemplateWizardDialog::Render()
{
	// Enable and disable the proper buttons.
	GreyButtons();

	// Set the new title.
	CString title;
	GetWindowText(title);
	int parenPos = title.Find(" (", 0);
	if (parenPos != -1)
		title = title.Left(parenPos);
	CString newTitle;
	if (m_curPage == -1)
	{
		newTitle = title;
	}
	else
	{
		newTitle.Format("%s (Page %d of %d)", title, m_curPage + 1, m_code.GetPageCount());
	}
	SetWindowText(newTitle);

	// Get the module name and strip the module filename from it, leaving the
	// module path.
	TCHAR moduleName[_MAX_PATH];
	moduleName[0] = 0;
	::GetModuleFileName(AfxGetInstanceHandle(), (TCHAR*)&moduleName, _MAX_PATH);
	TCHAR* ptr = _tcsrchr(moduleName, '\\');
	if (ptr)
	{
		ptr++;
		*ptr = 0;
	}

	///////////////////////////////////////////////////////////////////////////
	// Render the page.
	const CString& pageStr = (m_curPage == -1) ? m_page : m_code.GetPage(m_curPage);

	CRect clientRect;
	GetClientRect(clientRect);

	int curPos = 0;
//	while (true)
//	{
		// Grab the text.
		CString staticStr = pageStr;

//	}

	// See if it is a special case of a URL.
	bool isURL = false;
	CString leftStaticStr = staticStr.Left(7);
	if (leftStaticStr == "http://"  ||  leftStaticStr == "file://")
	{
		isURL = true;
	}

	CString strURL;
	if (!isURL)
	{
		m_htmlFile.SetLength(0);
		if (strnicmp(staticStr, "<html>", 6) != 0)
		{
			WriteString("<html><head>");
			WriteString("</head><body>");
			WriteString(staticStr);
			WriteString("</body></html>");
		}
		else
		{
			WriteString(staticStr);
		}

		// Generate a unique temporary name.
		char* asciiTempName = _tempnam(NULL, "WW200_");
		m_asciiFilename = CString(asciiTempName);
		free(asciiTempName);

		DWORD size = (DWORD)m_htmlFile.GetLength();
		BYTE* mem = m_htmlFile.Detach();
		CFile asciiFile;
		asciiFile.Open(m_asciiFilename, CFile::modeCreate | CFile::modeWrite);
		asciiFile.Write(mem, size);
		asciiFile.Close();
		free(mem);

//	CComBSTR bstrURL = "about:blank";
//	m_pBrowserApp->Navigate(bstrURL, NULL, NULL, NULL, NULL);

		strURL = m_asciiFilename;
	}
	else
	{
		m_asciiFilename.Empty();
		strURL = pageStr;
		strURL = "http://workspacewhiz.com";
	}

	m_pBrowserApp->Navigate2(COleVariant(strURL), NULL, NULL, NULL, NULL);
}
Example #21
0
//打开按钮
void CChessManual::OnOpen()
{
	//获取目录
	TCHAR szPath[MAX_PATH]=TEXT("");
	GetCurrentDirectory(sizeof(szPath),szPath);

	//选择文件
	LPCTSTR pszFilter=TEXT("国际象棋棋谱文件 (*.CHM)|*.CHM||");
	CFileDialog DlgOpenManual(TRUE,TEXT("CHM"),NULL,OFN_NOCHANGEDIR|OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,pszFilter);
	DlgOpenManual.m_pOFN->lpstrInitialDir=szPath;
	if (DlgOpenManual.DoModal()!=IDOK) return;

	//打开文件
	CFile FileManual;
	if (FileManual.Open(DlgOpenManual.GetPathName(),CFile::modeRead)==FALSE)
	{
		AfxMessageBox(TEXT("无法打开文件,棋谱打开失败!"),MB_ICONSTOP);
		return;
	}

	//判断文件
	DWORD dwFileLength=(DWORD)FileManual.GetLength();
	if (dwFileLength<sizeof(tagChessManualHead))
	{
		AfxMessageBox(TEXT("棋谱文件格式错误,棋谱打开失败!"),MB_ICONSTOP);
		return;
	}

	//文件头
	tagChessManualHead ChessManualHead;
	FileManual.Read(&ChessManualHead,sizeof(ChessManualHead));

	//效验版本
	if (ChessManualHead.wVersion!=VER_MANUAL)
	{
		AfxMessageBox(TEXT("棋谱文件版本错误,棋谱打开失败!"),MB_ICONSTOP);
		return;
	}

	//效验长度
	if ((ChessManualHead.dwManualCount*sizeof(tagChessManual)+sizeof(tagChessManualHead))!=dwFileLength)
	{
		AfxMessageBox(TEXT("棋谱文件长度错误,棋谱打开失败!"),MB_ICONSTOP);
		return;
	}

	//读取棋谱
	tagChessManual * pChessManual=NULL;
	m_ChessManualInfo.SetSize(ChessManualHead.dwManualCount);
	for (DWORD i=0;i<ChessManualHead.dwManualCount;i++)
	{
		pChessManual=&m_ChessManualInfo[i];
		FileManual.Read(pChessManual,sizeof(tagChessManual));
	}

	//关闭文件
	FileManual.Close();

	//设置界面
	m_wChessStep=0;
	m_GameLogic.ResetChessBorad();
	m_ChessBorad.SetChessFrame(255,255,255,255);
	m_ChessBorad.SetChessBorad(m_GameLogic.m_ChessBorad);
	m_ChessBorad.SetChessColor(ChessManualHead.cbChessColor);

	//更新列表
	UpdateManualList();

	//更新控制
	UpdateControl();

	return;
}
void vmsFdmWebInterfaceServer::LoadDocuments()
{
	CFile file;
	CStringA str;
	int nHtmlLen = 0;
	std::auto_ptr<WCHAR> apchStr;
	WCHAR* wszStr = 0;

	LPCSTR pszVer = "1.0";

	file.Open (_T("Server/index.html"), CFile::modeRead);
	int nLen = file.GetLength ();
	LPSTR psz = new char [nLen];
	file.Read (psz, nLen);
	strncpy (str.GetBuffer (nLen + 1), psz, nLen);
	str.ReleaseBuffer (nLen);
	str.Replace ("%ver%", pszVer);
	delete [] psz;

#ifdef UNICODE
	nHtmlLen = ::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, 0, 0);
	apchStr.reset( new WCHAR[nHtmlLen + 1] );
	wszStr = apchStr.get();
	memset(wszStr, 0, (nHtmlLen + 1) * sizeof(WCHAR));
	::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, wszStr, nHtmlLen);
	m_strRootHtml = wszStr;
#else
	m_strRootHtml = str;
#endif

	file.Close ();

	file.Open (_T("Server/adddownloadres_ok.html"), CFile::modeRead);
	nLen = file.GetLength ();
	psz = new char [nLen];
	file.Read (psz, nLen);
	strncpy (str.GetBuffer (nLen + 1), psz, nLen);
	str.ReleaseBuffer (nLen);
	str.Replace ("%ver%", pszVer);
	delete [] psz;

#ifdef UNICODE
	nHtmlLen = ::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, 0, 0);
	apchStr.reset( new WCHAR[nHtmlLen + 1] );
	wszStr = apchStr.get();
	memset(wszStr, 0, (nHtmlLen + 1) * sizeof(WCHAR));
	::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, wszStr, nHtmlLen);
	m_strRootHtml = wszStr;
#else
	m_strAddDownloadRes_ok = str;
#endif

	file.Close ();

	file.Open (_T("Server/adddownloadres_err.html"), CFile::modeRead);
	nLen = file.GetLength ();
	psz = new char [nLen];
	file.Read (psz, nLen);
	strncpy (str.GetBuffer (nLen + 1), psz, nLen);
	str.ReleaseBuffer (nLen);
	str.Replace ("%ver%", pszVer);
	delete [] psz;

#ifdef UNICODE
	nHtmlLen = ::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, 0, 0);
	apchStr.reset( new WCHAR[nHtmlLen + 1] );
	wszStr = apchStr.get();
	memset(wszStr, 0, (nHtmlLen + 1) * sizeof(WCHAR));
	::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, wszStr, nHtmlLen);
	m_strRootHtml = wszStr;
#else
	m_strAddDownloadRes_err = str;
#endif

	file.Close ();

	file.Open (_T("Server/compdlds.html"), CFile::modeRead);
	nLen = file.GetLength ();
	psz = new char [nLen];
	file.Read (psz, nLen);
	strncpy (str.GetBuffer (nLen + 1), psz, nLen);
	str.ReleaseBuffer (nLen);
	str.Replace ("%ver%", pszVer);
	delete [] psz;

#ifdef UNICODE
	nHtmlLen = ::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, 0, 0);
	apchStr.reset( new WCHAR[nHtmlLen + 1] );
	wszStr = apchStr.get();
	memset(wszStr, 0, (nHtmlLen + 1) * sizeof(WCHAR));
	::MultiByteToWideChar(CP_ACP, 0, str.GetBuffer(str.GetLength()), -1, wszStr, nHtmlLen);
	m_strRootHtml = wszStr;
#else
	m_strCompDldsHtml = str;
#endif

	file.Close ();
}
Example #23
0
CArchive *CDataFile::OpenAsCArchive( const char *pFilename )
{
	ASSERT( pFilename );

	//  Get the relative path of the file for which to search.
	CString filename( pFilename );
	CString path;
	path = "files\\" + filename;
	path.MakeLower ();

	//  Check to see if the file exists in the patch directory.
	if ( m_pPatchDir )
	{
		CString patchPath = *m_pPatchDir + "\\" + path;

		CFile	test;
		if ( test.Open( patchPath, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary ) != FALSE )
		{
			//  Close the file so we can allocate a new CFile object to
			//  return to the caller.
			test.Close();

			//  Allocate a new CFile object.  By creating and opening the CFile
			//  this way, the CFile dtor will automagically close the file 
			//  handle for us.
			CFile *pNewFile = new CFile;
			if ( pNewFile->Open( patchPath, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary ) == FALSE )
				ThrowError( ERR_PATCHFILE_OPEN );
			CArchive *pNewCArchive = new CArchive( pNewFile, CArchive::load );
			if ( pNewCArchive == NULL )
				ThrowError( ERR_OUT_OF_MEMORY );

			return pNewCArchive;
		}
	}

	//  If here, the file does not exist in the 
	//  patch directory or there is no patch directory.
	//  If a datafile was opened, look for it in the
	//  datafile.
	if ( m_pDataFile )
	{
		//  Look for the file path in the map.  If 
		//  it is not found, if searching for language 
		//  file try searching for US version;  otherwise,
		//  return NULL.
		void *	dummy;
		if ( m_pFileMap->Lookup( path, dummy ) == FALSE )
			ThrowError( ERR_DATAFILE_NO_ENTRY );

		//  If here, file was found in the map.  Seek to
		//  that position in the file.
		//  If negative seek checks between CMmio's are 
		//  desired, they should be done here.
		long fileOffset = ( long )dummy;
		long	offsetFromHere = fileOffset - ( long )m_pDataFile->GetPosition();

#ifdef _DEBUG
		if ( m_bNegativeSeekCheck == TRUE && fileOffset < m_lastPos )
			WarnNegativeSeek( pFilename, m_lastPos, fileOffset );
#endif

		m_pDataFile->Seek( offsetFromHere, CFile::current );

#ifdef _DEBUG
		m_lastPos = m_pDataFile->GetPosition();
#endif

		//  Create a new CFile object.  It will be positioned 
		//  at the current file offset.  Note that this dtor will
		//  not automagically close the file handle, which is what we
		//  want.
		CFile * pNewFile = new CFile ();
		if ( pNewFile == NULL )
			ThrowError( ERR_OUT_OF_MEMORY );
		if (pNewFile->Open( m_sFileName, CFile::modeRead | CFile::shareDenyWrite | CFile::typeBinary ) == FALSE)
			ThrowError( ERR_OUT_OF_MEMORY );
		pNewFile->Seek (m_pDataFile->GetPosition (), CFile::begin);

		CArchive *pNewCArchive = new CArchive( pNewFile, CArchive::load );
		if ( pNewCArchive == NULL )
			ThrowError( ERR_OUT_OF_MEMORY );

		return pNewCArchive;
	}

	//  If here, file was not found in patch dir ( or
	//  no patch dir was given ), and no datafile was
	//  opened, so return NULL ( no file found ).
	ThrowError( ERR_DATAFILE_NO_ENTRY );
	return NULL;
}
Example #24
0
bool CCDDARipJob::DoWork()
{
  CLog::Log(LOGINFO, "Start ripping track %s to %s", m_input.c_str(),
                                                     m_output.c_str());

  // if we are ripping to a samba share, rip it to hd first and then copy it it the share
  CFileItem file(m_output, false);
  if (file.IsRemote())
    m_output = SetupTempFile();
  
  if (m_output.empty())
  {
    CLog::Log(LOGERROR, "CCDDARipper: Error opening file");
    return false;
  }

  // init ripper
  CFile reader;
  CEncoder* encoder;
  if (!reader.Open(m_input,READ_CACHED) || !(encoder=SetupEncoder(reader)))
  {
    CLog::Log(LOGERROR, "Error: CCDDARipper::Init failed");
    return false;
  }

  // setup the progress dialog
  CGUIDialogExtendedProgressBar* pDlgProgress = 
      (CGUIDialogExtendedProgressBar*)g_windowManager.GetWindow(WINDOW_DIALOG_EXT_PROGRESS);
  CGUIDialogProgressBarHandle* handle = pDlgProgress->GetHandle(g_localizeStrings.Get(605));

  int iTrack = atoi(m_input.substr(13, m_input.size() - 13 - 5).c_str());
  std::string strLine0 = StringUtils::Format("%02i. %s - %s", iTrack,
                                            StringUtils::Join(m_tag.GetArtist(), g_advancedSettings.m_musicItemSeparator).c_str(),
                                            m_tag.GetTitle().c_str());
  handle->SetText(strLine0);

  // start ripping
  int percent=0;
  int oldpercent=0;
  bool cancelled(false);
  int result;
  while (!cancelled && (result=RipChunk(reader, encoder, percent)) == 0)
  {
    cancelled = ShouldCancel(percent,100);
    if (percent > oldpercent)
    {
      oldpercent = percent;
      handle->SetPercentage(static_cast<float>(percent));
    }
  }

  // close encoder ripper
  encoder->CloseEncode();
  delete encoder;
  reader.Close();

  if (file.IsRemote() && !cancelled && result == 2)
  {
    // copy the ripped track to the share
    if (!CFile::Copy(m_output, file.GetPath()))
    {
      CLog::Log(LOGERROR, "CDDARipper: Error copying file from %s to %s", 
                m_output.c_str(), file.GetPath().c_str());
      CFile::Delete(m_output);
      return false;
    }
    // delete cached file
    CFile::Delete(m_output);
  }

  if (cancelled)
  {
    CLog::Log(LOGWARNING, "User Cancelled CDDA Rip");
    CFile::Delete(m_output);
  }
  else if (result == 1)
    CLog::Log(LOGERROR, "CDDARipper: Error ripping %s", m_input.c_str());
  else if (result < 0)
    CLog::Log(LOGERROR, "CDDARipper: Error encoding %s", m_input.c_str());
  else
  {
    CLog::Log(LOGINFO, "Finished ripping %s", m_input.c_str());
    if (m_eject)
    {
      CLog::Log(LOGINFO, "Ejecting CD");
      g_mediaManager.EjectTray();
    }
  }

  handle->MarkFinished();

  return !cancelled && result == 2;
}
Example #25
0
bool CFile::Copy(const CURL& url2, const CURL& dest, XFILE::IFileCallback* pCallback, void* pContext)
{
  CFile file;

  const std::string pathToUrl(dest.Get());
  if (pathToUrl.empty())
    return false;

  // special case for zips - ignore caching
  CURL url(url2);
  if (URIUtils::IsInZIP(url.Get()) || URIUtils::IsInAPK(url.Get()))
    url.SetOptions("?cache=no");
  if (file.Open(url.Get(), READ_TRUNCATED))
  {

    CFile newFile;
    if (URIUtils::IsHD(pathToUrl)) // create possible missing dirs
    {
      vector<std::string> tokens;
      std::string strDirectory = URIUtils::GetDirectory(pathToUrl);
      URIUtils::RemoveSlashAtEnd(strDirectory);  // for the test below
      if (!(strDirectory.size() == 2 && strDirectory[1] == ':'))
      {
        CURL url(strDirectory);
        std::string pathsep;
#ifndef TARGET_POSIX
        pathsep = "\\";
#else
        pathsep = "/";
#endif
        StringUtils::Tokenize(url.GetFileName(),tokens,pathsep.c_str());
        std::string strCurrPath;
        // Handle special
        if (!url.GetProtocol().empty()) {
          pathsep = "/";
          strCurrPath += url.GetProtocol() + "://";
        } // If the directory has a / at the beginning, don't forget it
        else if (strDirectory[0] == pathsep[0])
          strCurrPath += pathsep;
        for (vector<std::string>::iterator iter=tokens.begin();iter!=tokens.end();++iter)
        {
          strCurrPath += *iter+pathsep;
          CDirectory::Create(strCurrPath);
        }
      }
    }
    if (CFile::Exists(dest))
      CFile::Delete(dest);
    if (!newFile.OpenForWrite(dest, true))  // overwrite always
    {
      file.Close();
      return false;
    }

    static const int iBufferSize = 128 * 1024;

    auto_buffer buffer(iBufferSize);
    ssize_t iRead, iWrite;

    UINT64 llFileSize = file.GetLength();
    UINT64 llPos = 0;

    CStopWatch timer;
    timer.StartZero();
    float start = 0.0f;
    while (true)
    {
      g_application.ResetScreenSaver();

      iRead = file.Read(buffer.get(), iBufferSize);
      if (iRead == 0) break;
      else if (iRead < 0)
      {
        CLog::Log(LOGERROR, "%s - Failed read from file %s", __FUNCTION__, url.GetRedacted().c_str());
        llFileSize = (uint64_t)-1;
        break;
      }

      /* write data and make sure we managed to write it all */
      iWrite = 0;
      while(iWrite < iRead)
      {
        ssize_t iWrite2 = newFile.Write(buffer.get() + iWrite, iRead - iWrite);
        if(iWrite2 <=0)
          break;
        iWrite+=iWrite2;
      }

      if (iWrite != iRead)
      {
        CLog::Log(LOGERROR, "%s - Failed write to file %s", __FUNCTION__, dest.GetRedacted().c_str());
        llFileSize = (uint64_t)-1;
        break;
      }

      llPos += iRead;

      // calculate the current and average speeds
      float end = timer.GetElapsedSeconds();

      if (pCallback && end - start > 0.5 && end)
      {
        start = end;

        float averageSpeed = llPos / end;
        int ipercent = 0;
        if(llFileSize)
          ipercent = 100 * llPos / llFileSize;

        if(!pCallback->OnFileCallback(pContext, ipercent, averageSpeed))
        {
          CLog::Log(LOGERROR, "%s - User aborted copy", __FUNCTION__);
          llFileSize = (uint64_t)-1;
          break;
        }
      }
    }

    /* close both files */
    newFile.Close();
    file.Close();

    /* verify that we managed to completed the file */
    if (llFileSize && llPos != llFileSize)
    {
      CFile::Delete(dest);
      return false;
    }
    return true;
  }
  return false;
}
int BatterStruct::CopyBatterFile(CString inFileName, CString outFileName)
{
	int i;
	BYTE count;
	LONG lSeekPlayerFile;
	LONG lTeamSection = 74;
	CFile inFile;
	CFile outFile;
	char cTemp[41];
	CString strTemp;

	inFile.Open( inFileName, CFile::modeRead);
	outFile.Open( outFileName, CFile::modeCreate | CFile::modeWrite);
	// Read Count
	inFile.Read(&count,sizeof(count));
	outFile.Write(&count,sizeof(count));
	// Read team name
	inFile.Read(cTemp,40);
	cTemp[40]=NULL;
	strTemp = cTemp;
	outFile.Write(strTemp,40);
	// Read short team name
	inFile.Read(cTemp,3);
	cTemp[3]=NULL;
	strTemp = cTemp;
	outFile.Write(strTemp,3);
	// Read Ballpark
	inFile.Read(cTemp,30);
	cTemp[30]=NULL;
	strTemp = cTemp;
	outFile.Write(strTemp,30);
	// Read all of the players
	for (i=0; i<count; i++)
	{
		lSeekPlayerFile = lTeamSection+(i*m_RecordSize);
		inFile.Seek( lSeekPlayerFile, CFile::begin );
		BatterRead(&inFile);
		// Zero out fields
		m_2B = 0;
		m_3B = 0;
		m_AB = 0;
		m_CS = 0;
		m_Hits = 0;
		m_HomeRuns = 0;
		m_RBI = 0;
		m_ReachedOnError = 0;
		m_Runs = 0;
		m_Sacrifice = 0;
		m_StolenBase = 0;
		m_StrikeOut = 0;
		m_Walk = 0;
		m_HBP = 0;
		m_Games = 0;
		// Write Batter info at EOF, Already positioned there
		BatterWrite(&outFile);
	}
	// Close file
	inFile.Close();
	outFile.Close();
	return 1;
}
Example #27
0
BOOL TFTP_MONITOR(char *server, int port, char *file, int timeout, char *custpath, 
				  char *szReturn)
{
	SOCKET	s;
	int		nAckSeq = 0;
	int		nSaveFlag = 0;
	int		datalen = 0;
	DWORD	dwBytes = 0;
	int		i = 0, n = 0, dw = 0;
	struct	hostent *hp = NULL;
	struct	sockaddr_in serv;

	DWORD	dwbTime = 0, dweTime = 0;
	DWORD	dwbReceive = 0, dweReceive = 0;

	int		reqlen = 0;
	u_char	req[1024] = {0};
	u_char	res[1024] = {0};

	if((s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
	{
		sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_SOCKET",
            "SOCKET_CREATE_FAILED"));
		return FALSE;
	}

	if((hp = gethostbyname(server)) == NULL)
	{
		sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_DSN",
            "DNS_DOMAIN_NAME_PARSE_ERROR"));
		return FALSE;
	}

	memcpy(&serv.sin_addr,hp->h_addr_list[0],hp->h_length);
    serv.sin_family = AF_INET;
    serv.sin_port = htons(port);

	// RRQ
	req[reqlen ++] = 0x00;
	req[reqlen ++] = 0x01;

	// Filename
	for(i = 0;i < (int)strlen(file);i ++)
		req[reqlen ++] = file[i];
	req[reqlen ++] = 0x00;

	// Mode
	req[reqlen ++] = 'O';
	req[reqlen ++] = 'C';
	req[reqlen ++] = 'T';
	req[reqlen ++] = 'E';
	req[reqlen ++] = 'T';
	req[reqlen ++] = 0x00;

	dwbTime = ::GetTickCount();

	if((n = sendto(s, (char *)req, reqlen, 0, (struct sockaddr *)&serv, sizeof(serv))) == SOCKET_ERROR)
	{
		sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_SOCKET",
            "SOCKET_SEND_DATA_ERROR"));
		return FALSE;
	}

#ifdef SAVEASFILE
	CFile	datafile;
	char	szFile[256] = {0};
	
	sprintf(szFile, ".\\%s", file);
	if(!datafile.Open(szFile, CFile::modeWrite|CFile::modeCreate)) 
	{
		sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_BASIC",
            "BASIC_CREATE_FILE_FAIL"));
		return FALSE;
	}
#endif

	dwbReceive = ::GetTickCount();

	while(1)
	{
		if(RESPONSE_WAIT(s, timeout) <= 0)
		{
			sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_SOCKET",
                "SOCKET_RECV_DATA_TIMEOUT"));
			return FALSE;
		}

		dw = sizeof(serv);
		n = recvfrom(s, (char *)res, sizeof(res), 0, (struct sockaddr *)&serv, &dw);
		if(n == SOCKET_ERROR || n == 0)
		{
			sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_SCOKET",
                "SOCKET_RECV_DATA_ERROR"));
			return FALSE;
		}

		int nCode = res[0] * 0x100 + res[1];
		if(nCode == 0x05)
		{
			sprintf(szReturn, "error=%s [%d]$", res + 4, res[2] * 0x100 + res[3]);
			return FALSE;
		}

		if(nCode != 0x03)
		{
			sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_SOCKET",
                "SOCKET_UNKNOWN_ERROR"));
			return FALSE;
		}

		datalen = n;

		if(res[2] * 0x100 + res[3] > nAckSeq)
		{
			nAckSeq ++;
			nSaveFlag = 1;
		}

		reqlen = 0;
		req[reqlen ++] = 0x00;
		req[reqlen ++] = 0x04;
		req[reqlen ++] = res[2];
		req[reqlen ++] = res[3];
		if((n = sendto(s, (char *)req, reqlen, 0, (struct sockaddr *)&serv, sizeof(serv))) == SOCKET_ERROR)
		{
			sprintf(szReturn, "error=%s$", FuncGetStringFromIDS("SV_SOCKET",
                "SOCKET_SEND_DATA_EEROR"));
			return FALSE;
		}

		if(nSaveFlag) dwBytes += datalen - 4;

#ifdef SAVEASFILE
		if(nSaveFlag) datafile.Write(res + 4, datalen - 4);
#endif
		nSaveFlag = 0;

		if(datalen - 4 < 512) break;
	}
	
#ifdef SAVEASFILE
	datafile.Close();
#endif

	dweTime = ::GetTickCount();
	dweReceive = ::GetTickCount();

	DWORD dwInterval = dweReceive - dwbReceive;
	if(dwInterval == 0) dwInterval = 1;

	sprintf(szReturn, "roundTripTime=%.3f$bytes=%ld$bytesPerSec=%.3f", 
			(dweTime - dwbTime) / 1000.0, dwBytes, (dwBytes / 1024.0) / (dwInterval / 1000.0));

	return TRUE;
}
Example #28
0
FileState ReceiveFile(SOCKET socket, HWND hWrapperWnd, LPCTSTR strFilePathName, ULONGLONG llStartAt)
{

	PostMessage(hWrapperWnd, WM_FILE_OPERATE_BEGIN, 0, 0);

	FileState MyFileState = S_FileOK, YouFileState = S_FileOK;

	//open file
	CString strFileName = strFilePathName;
	CFile LocalFile;
	UINT uOpMode = llStartAt > 0 ? (CFile::modeReadWrite | CFile::typeBinary) : (CFile::modeCreate | CFile::modeReadWrite | CFile::typeBinary);

	if (IsFileExist(strFileName))
	{
		if (!DropReadOnly(strFileName))
			MyFileState = S_CreateFileFailed;
	}

	if(!LocalFile.Open(strFileName, uOpMode))
	{
		if(MyFileState == S_FileOK)
			MyFileState = S_CreateFileFailed;
	}

	if (MyFileState != S_CreateFileFailed)
	{
		ULONGLONG uSeeked = LocalFile.Seek(llStartAt, CFile::begin);
		if (uSeeked != llStartAt)
		{
			MyFileState = S_CreateFileFailed;
		}
	}

	//receive you file operate state
	if(!ReceiveData(socket, (char*)&YouFileState, sizeof(FileState)))
	{
		LocalFile.Close();
		return S_SocketError;
	}

	//send my file operate state
	if(!SendData(socket, (char*)&MyFileState, sizeof(FileState)))
	{
		if(MyFileState != S_CreateFileFailed)
			LocalFile.Close();
		return S_SocketError;
	}

	if(MyFileState != S_FileOK) return MyFileState;
	if(YouFileState != S_FileOK) return YouFileState;

	BasicFileInfo basicFileInfo;
	if(!ReceiveData(socket, (char*)(&basicFileInfo), sizeof(basicFileInfo)))
	{
		LocalFile.Close();
		//DeleteFile(strFilePathName);
		return S_SocketError;
	}
	
	ULONGLONG nTotalRead = llStartAt;
	ULONGLONG nDes = basicFileInfo.Size > 1024 * 1024 * 1024 ? 1024 * 1024 : 1024;
	PostMessage(hWrapperWnd, WM_FILE_SETRANGE_MESSAGE, (WPARAM)( basicFileInfo.Size / nDes), (LPARAM)0);

	PostMessage(hWrapperWnd, WM_FILE_SENDFILETOSERVER_PROGRESS_MESSAGE, (WPARAM)(nTotalRead / nDes), 0);
	ULONGLONG nRead = llStartAt;
	ULONGLONG nResCount = 0;
	ULONGLONG nRealRead = 0;

	FileDataEx fileData;

	if (gl_pLogger) gl_pLogger->log_info("ReceiveFile Begin to send: %s", strFilePathName);
	
	bool *pbstatus = NULL;
	SendMessage(hWrapperWnd, WM_GETSENDSTATE, 0, (LPARAM)&pbstatus);
	//receive loop
	while(1)
	{		
		if (!ReceiveData(socket, (char*)(&fileData), sizeof(fileData)))
			return S_SocketError;

		if (fileData.data.nLength == 0)
			break;

		if (fileData.state == S_IStop)
		{
			LocalFile.Close();
			//DeleteFile(strFilePathName);
			return S_OtherSideStop;
		}

		FileState MyState = S_FileOK;
		try{
			if (fileData.data.nLength > 0)
				LocalFile.Write(fileData.data.Buf, fileData.data.nLength);
		}
		catch(...){
			MyState = S_WriteFileFailed;
		}
		nRealRead = nRealRead + fileData.data.nLength;

		nTotalRead = nTotalRead + fileData.data.nLength;
		PostMessage(hWrapperWnd, WM_FILE_SENDFILETOSERVER_PROGRESS_MESSAGE, (WPARAM)(nTotalRead / nDes), 0);

		if(fileData.state == S_Finished)
		{
			if (nRealRead > 0)
				LocalFile.Flush();
			LocalFile.Close();
			return fileData.state;
		}
		
		if(fileData.state == S_ReadFileFailed)
		{
			LocalFile.Close();
			//DeleteFile(strFilePathName);
			return fileData.state;
		}


		nResCount++;
		if(nResCount % READWRITESTATUS == 0)
		{
			nResCount = 0;
			
			FileState MyState,YouState;

			MyState = (*pbstatus) ? S_FileContinue : S_IStop;
			//SendMessage(hWrapperWnd, WM_GETSENDSTATE, 0, (LPARAM)&MyState);
			
			if(!ReceiveData(socket, (char*)&YouState, sizeof(FileState)))
			{
				LocalFile.Close();
				//DeleteFile(strFilePathName);
				return S_SocketError;
			}

			if(!SendData(socket, (char*)&MyState, sizeof(FileState)))
			{
				LocalFile.Close();
				//DeleteFile(strFilePathName);
				return S_SocketError;
			}
			
			if(MyState == S_IStop)
			{
				LocalFile.Close();
				//DeleteFile(strFilePathName);
				return S_IStop;
			}

			if(YouState == S_WriteFileFailed || YouState == S_IStop)
			{
				LocalFile.Close();
				//DeleteFile(strFilePathName);
				if(YouState == S_IStop) 
					YouState = S_OtherSideStop;
				return YouState;
			}
		}
	}

	return S_Finished;
}
Example #29
0
void LoadReplacementBitmaps (const char *pszLevelName)
{
	char		szFilename [SHORT_FILENAME_LEN];
	CFile		cf;
	int		i, j;
	CBitmap	bm;

//first, free up data allocated for old bitmaps
PrintLog ("   loading replacement textures\n");
CFile::ChangeFilenameExtension (szFilename, pszLevelName, ".pog");
if (cf.Open (szFilename, gameFolders.szDataDir, "rb", 0)) {
	int					id, version, nBitmapNum, bTGA;
	int					bmDataSize, bmDataOffset, bmOffset;
	ushort				*indices;
	tPIGBitmapHeader	*bmh;

	id = cf.ReadInt ();
	version = cf.ReadInt ();
	if (id != MAKE_SIG ('G','O','P','D') || version != 1) {
		cf.Close ();
		return;
		}
	nBitmapNum = cf.ReadInt ();
	indices = new ushort [nBitmapNum];
	bmh = new tPIGBitmapHeader [nBitmapNum];
#if 0
	cf.Read (indices, nBitmapNum * sizeof (ushort), 1);
	cf.Read (bmh, nBitmapNum * sizeof (tPIGBitmapHeader), 1);
#else
	for (i = 0; i < nBitmapNum; i++)
		indices [i] = cf.ReadShort ();
	for (i = 0; i < nBitmapNum; i++)
		PIGBitmapHeaderRead (bmh + i, cf);
#endif
	bmDataOffset = cf.Tell ();
	bmDataSize = cf.Length () - bmDataOffset;

	for (i = 0; i < nBitmapNum; i++) {
		bmOffset = bmh [i].offset;
		memset (&bm, 0, sizeof (CBitmap));
		bm.AddFlags (bmh [i].flags & (BM_FLAGS_TO_COPY | BM_FLAG_TGA));
		bm.SetWidth (bmh [i].width + ((short) (bmh [i].wh_extra & 0x0f) << 8));
		bm.SetRowSize (bm.Width ());
		if ((bTGA = (bm.Flags () & BM_FLAG_TGA)) && (bm.Width () > 256))
			bm.SetHeight (bm.Width () * bmh [i].height);
		else
			bm.SetHeight (bmh [i].height + ((short) (bmh [i].wh_extra & 0xf0) << 4));
		bm.SetBPP (bTGA ? 4 : 1);
		if (!(bm.Width () * bm.Width ()))
			continue;
		bm.SetAvgColorIndex (bmh [i].avgColor);
		bm.SetType (BM_TYPE_ALT);
		if (!bm.CreateBuffer ())
			break;
		cf.Seek (bmDataOffset + bmOffset, SEEK_SET);
#if DBG
		if (indices [i] == nDbgTexture)
			nDbgTexture = nDbgTexture;
#endif
		if (bTGA) {
			int			nFrames = bm.Height () / bm.Width ();
			tTgaHeader	h;

			h.width = bm.Width ();
			h.height = bm.Width ();
			h.bits = 32;
			if (!ReadTGAImage (cf, &h, &bm, -1, 1.0, 0, 1)) {
				bm.DestroyBuffer ();
				break;
				}
			bm.SetFrameCount ((ubyte) nFrames);
			if (nFrames > 1) {
				tEffectClip	*ecP = NULL;
				tWallClip *wcP;
				tVideoClip *vcP;
				while ((ecP = FindEffect (ecP, indices [i]))) {
					//e->vc.nFrameCount = nFrames;
					ecP->flags |= EF_ALTFMT | EF_FROMPOG;
					}
				if (!ecP) {
					if ((wcP = FindWallAnim (indices [i]))) {
						//w->nFrameCount = nFrames;
						wcP->flags |= WCF_ALTFMT | WCF_FROMPOG;
						}
					else if ((vcP = FindVClip (i))) {
						//v->nFrameCount = nFrames;
						vcP->flags |= WCF_ALTFMT | WCF_FROMPOG;
						}
					}
				}
			j = indices [i];
			bm.SetId (j);
			}
		else {
#if DBG
			if (j == nDbgTexture)
				nDbgTexture = nDbgTexture;
#endif
			ReadBitmap (&bm, int (bm.Width ()) * int (bm.Height ()), &cf, true, false);
			j = indices [i];
			bm.SetId (j);
			bm.RLEExpand (NULL, 0);
			*bm.Props () = *gameData.pig.tex.bitmapP [j].Props ();
			bm.Remap (paletteManager.Game (), TRANSPARENCY_COLOR, SUPER_TRANSP_COLOR);
			}
#if DBG
		if (j == nDbgTexture)
			nDbgTexture = nDbgTexture;
#endif
		gameData.pig.tex.bitmapP [j].Unload (j, 0);
		bm.SetFromPog (1);
		char szName [20];
		if (*gameData.pig.tex.bitmapP [j].Name ())
			sprintf (szName, "[%s]", gameData.pig.tex.bitmapP [j].Name ());
		else
			sprintf (szName, "POG#%04d", j);
		bm.SetName (szName);
		gameData.pig.tex.altBitmapP [j] = bm;
		gameData.pig.tex.altBitmapP [j].SetBuffer (bm.Buffer (), 0, bm.Length ());
		bm.SetBuffer (NULL);
		gameData.pig.tex.bitmapP [j].SetOverride (gameData.pig.tex.altBitmapP + j);
		CBitmap* bmP = gameData.pig.tex.altBitmapP + j;
		tRgbColorf color;
		if (0 <= bmP->AvgColor (&color))
			bmP->SetAvgColorIndex (bmP->Palette ()->ClosestColor (&color));
		UseBitmapCache (gameData.pig.tex.altBitmapP + j, (int) bm.Width () * (int) bm.RowSize ());
		}
	delete[] indices;
	delete[] bmh;
	cf.Close ();
	paletteManager.SetLastPig ("");
	TexMergeFlush ();       //for re-merging with new textures
	}
}
void CSettingDlg::OnCompress() 
{
	CString			fullpathname, filename, errmsg, compname, compfullpath;
	DWORD dwsize;
	CFile file;
	std::string		addfilename;
	_VERSION_INFO* pInfo = NULL;

	UpdateData(TRUE);

	int count = m_FileList.GetCount();
	if( count == 0 ) return;

	BeginWaitCursor();
	compname.Format("patch%.4d.zip", m_nVersion );
	compfullpath.Format("%s\\%s", m_strDefaultPath, compname);
	
	set<int>::iterator Iter;

	while( !m_RepackingVersionList.empty() ) {
		Iter = m_RepackingVersionList.begin();
		m_RepackingVersionList.erase(Iter);
	}

	m_ZipArchive.Open(compfullpath, CZipArchive::create);

	SetDlgItemText(IDC_STATUS, "Compressing..");

	for(int i=0; i<count; i++ ) {
		m_FileList.GetText( i, filename );

		fullpathname = m_strDefaultPath;
		fullpathname += filename;
		if( !file.Open( fullpathname, CFile::modeRead ) ) {
			errmsg.Format("%s File Open Fail", filename);
			AfxMessageBox(errmsg);
			continue;
		}
		dwsize = file.GetLength();
		file.Close();
		
		if(!m_ZipArchive.AddNewFile(fullpathname, m_strDefaultPath, -1, dwsize)) {
			errmsg.Format("%s File Compress Fail", filename);
			AfxMessageBox(errmsg);
			continue;
		}
		m_Progress.SetPos(i*100/count);

		addfilename = (const char*)(LPCTSTR)filename;
		pInfo = m_pMain->m_VersionList.GetData(addfilename);
		if( pInfo )
			m_RepackingVersionList.insert(pInfo->sHistoryVersion);
	}
	SetDlgItemText(IDC_STATUS, "Compressed");

	m_ZipArchive.Close();

	if( !m_bCompressOption ) {	// Current Version 만 압축
		if( !m_RepackingVersionList.empty() )
			RepackingHistory();
	}

	m_Progress.SetPos(100);

	EndWaitCursor();
}