void CDownloadDetailDlg::SetPartFileInfo(CKnownFile	*file)
{
	if(! file) return ;
	CPartFile	*pPartFile = NULL;
	if ( file->IsKindOf(RUNTIME_CLASS(CPartFile)) )
		pPartFile = (CPartFile*) file;



	SetDlgItemText(IDC_STATIC_FILENAME, file->GetFilePath());
	

	CString strTmp;
	time_t restTime;
	if ( NULL != pPartFile )
	{
		if (!thePrefs.UseSimpleTimeRemainingComputation())
			restTime = pPartFile->getTimeRemaining();
		else
			restTime = pPartFile->getTimeRemainingSimple();

		strTmp.Format(_T("%s (%s)"), CastSecondsToHM(restTime), CastItoXBytes((pPartFile->GetFileSize() - pPartFile->GetCompletedSize()), false, false));
		SetDlgItemText(IDC_STATIC_LAST_SEEN_TIME, strTmp);
	}

}
LRESULT	CDlgMaintabDownload::OnCurSelFile(WPARAM wParam, LPARAM lParam)
{	
	if (!lParam)
	{
		theApp.emuledlg->m_mainTabWnd.m_dlgDownload.m_dlgPeerLog.m_LogListCtrl.DeleteAllItems();
		theApp.emuledlg->m_mainTabWnd.m_dlgDownload.m_dlgDetailInfo.m_ListDetail.DeleteAllItems();
		return 0;
	}

	if (wParam == 1)
	{
		CKnownFile* pKnownFile= (CKnownFile*)lParam;
		if( pKnownFile->HasNullHash() )
		{
			CFileTaskItem* pFileTaskItem = CGlobalVariable::filemgr.GetFileTaskItem(pKnownFile->GetPartFileURL());
			ASSERT(pFileTaskItem);
			if(pFileTaskItem) 
				m_dlgDetailInfo.FileInfo(pFileTaskItem);
		}
		else
		{
			m_dlgDetailInfo.UpdateInfo((CPartFile*)lParam, CDetailInfo::IM_COMBINE_DOWNLOADED);
		}

		return 0;
	}

	CPartFile *pFile = (CPartFile*) lParam;
	if (IsRemarkTabActived())
	{
		RefreshLowerPannel(pFile);
	}
	else /*if( IsLogTabActived() )*/
	{
		m_dlgPeerLog.m_LogListCtrl.ShowSelectedFileLogs(pFile);
	}

	//MODIFIED by VC-fengwen on 2008/03/17 <begin> : 无论是否处于当前页面都更新DetailInfo(为了方便处理,而且此处性能消耗不大)
	if ( IsDownloadingActived() && pFile->GetStatus() != PS_COMPLETE && pFile->GetFileSize() != (uint64)0)
	{
		m_dlgDetailInfo.UpdateInfo(pFile, CDetailInfo::IM_COMBINE_DOWNLOAD);
	}
	else if (IsDownloadingActived() && pFile->GetFileSize() == (uint64)0)
	{   
		CFileTaskItem* pFileTaskItem = CGlobalVariable::filemgr.GetFileTaskItem(pFile->GetPartFileURL());
		ASSERT(pFileTaskItem);
		if(pFileTaskItem) 
			m_dlgDetailInfo.FileInfo(pFileTaskItem);
	}
	else
	{
		m_dlgDetailInfo.UpdateInfo(pFile, CDetailInfo::IM_COMBINE_DOWNLOADED);
	}
	//MODIFIED by VC-fengwen on 2008/03/17 <end> : 无论是否处于当前页面都更新DetailInfo(为了方便处理,而且此处性能消耗不大)
		
	return 0;
}
void CDownloadQueue::ResetCatParts(uint8 cat)
{
	for (FileQueue::iterator it = m_filelist.begin(); it != m_filelist.end(); it++) {
		CPartFile* file = *it;
		file->RemoveCategory(cat);
	}
	for (FileList::iterator it = m_completedDownloads.begin(); it != m_completedDownloads.end(); it++) {
		CPartFile* file = *it;
		file->RemoveCategory(cat);
	}
}
void CSeeFileManager::POPOneSeeFile()
{
	CPartFile * pPartFile = NULL;

	pPartFile = m_SeeFiles.GetAt(m_SeeFiles.GetHeadPosition())->m_value;

	if (pPartFile)
	{
		pPartFile->SetSeeOnDownloading(NULL, false);
	}

	m_SeeFiles.RemoveAt(m_SeeFiles.GetHeadPosition());
}
void CSeeFileManager::RemoveSeeFile(FILEKEY & key)
{
	CPartFile * pPartFile = NULL;

	if(m_SeeFiles.Lookup(key, pPartFile))
	{
		if (pPartFile)
		{
			pPartFile->SetSeeOnDownloading(NULL, false);
		}

		m_SeeFiles.RemoveKey(key);
	}
}
Exemple #6
0
BOOL CUpdateInfo::DeleteUpdate(CString hash)
{
	uchar UpdateHash[16];
	CPartFile* pPartFile;

	if(!strmd4(hash,UpdateHash))
	{
		return FALSE;
	}

	CKnownFile* file = CGlobalVariable::sharedfiles->GetFileByID(UpdateHash);

	try
	{
		//共享列表中是否有
		if(file)
		{
			if(file->IsPartFile())
			{
				//共享列表有,但未下载完,移除
				pPartFile = DYNAMIC_DOWNCAST(CPartFile,file);
				if( pPartFile )
				{
					pPartFile->DeleteFile();
				}
			}
			else
			{
				//共享列表有,已经下载完成未安装,移除
				DeleteFile(file->GetFilePath());
				theApp.emuledlg->sharedfileswnd->sharedfilesctrl.RemoveFile(file);
				CGlobalVariable::sharedfiles->RemoveFile(file);
			}
		}

		if ((pPartFile = CGlobalVariable::downloadqueue->GetFileByID(UpdateHash)) != NULL)
		{
			//共享列表没有,但未下载完,移除
			pPartFile->DeleteFile();
		}
	}
	catch (CException* e)
	{
		e->Delete();
		return FALSE;
	}

	return FALSE;
}
void CDownloadQueue::OnHostnameResolved(uint32 ip)
{
	wxMutexLocker lock( m_mutex );

	wxASSERT( m_toresolve.size() );
	
	Hostname_Entry resolved = m_toresolve.front();
	m_toresolve.pop_front();

	if ( ip ) {
		CPartFile* file = GetFileByID( resolved.fileid );
		if ( file ) {
			CMemFile sources(1+4+2);
			sources.WriteUInt8(1); // No. Sources
			sources.WriteUInt32(ip);
			sources.WriteUInt16(resolved.port);
			sources.WriteUInt8(resolved.cryptoptions);
			if (resolved.cryptoptions & 0x80) {
				wxASSERT(!resolved.hash.IsEmpty());
				CMD4Hash sourcehash;
				sourcehash.Decode(resolved.hash);
				sources.WriteHash(sourcehash);
			}
			sources.Seek(0,wxFromStart);
			
			file->AddSources(sources, 0, 0, SF_LINK, true);
		}
	}
	
	while (m_toresolve.size()) {
		Hostname_Entry entry = m_toresolve.front();

		// Check if it is a simple dot address
		uint32 tmpIP = StringIPtoUint32(entry.strHostname);

		if (tmpIP) {
			OnHostnameResolved(tmpIP);
		} else {
			CAsyncDNS* dns = new CAsyncDNS(entry.strHostname, DNS_SOURCE, theApp);

			if ((dns->Create() != wxTHREAD_NO_ERROR) || (dns->Run() != wxTHREAD_NO_ERROR)) {
				dns->Delete();
				m_toresolve.pop_front();
			} else {
				break;
			}
		}
	}
}
void CFileDetailDialogName::RenameFile()
{
	if (CanRenameFile())
	{
		CString strNewFileName;
		GetDlgItem(IDC_FILENAME)->GetWindowText(strNewFileName);
		strNewFileName.Trim();
		if (strNewFileName.IsEmpty() || !IsValidEd2kString(strNewFileName))
			return;
		CPartFile* file = STATIC_DOWNCAST(CPartFile, (*m_paFiles)[0]);
		file->SetFileName(strNewFileName, true);
		file->UpdateDisplayedInfo();
		file->SavePartFile();
	}
}
void CDownloadQueue::SetCatPrio(uint8 cat, uint8 newprio)
{
	for ( uint16 i = 0; i < GetFileCount(); i++ ) {
		CPartFile* file = GetFileByIndex( i );
		
		if ( !cat || file->GetCategory() == cat ) {
			if ( newprio == PR_AUTO ) {
				file->SetAutoDownPriority(true);
			} else {
				file->SetAutoDownPriority(false);
				file->SetDownPriority(newprio);
			}
		}
	}
}
void CDownloadQueue::ClearCompleted(const ListOfUInts32 & ecids)
{
	for (ListOfUInts32::const_iterator it1 = ecids.begin(); it1 != ecids.end(); it1++) {
		uint32 ecid = *it1;
		for (FileList::iterator it = m_completedDownloads.begin(); it != m_completedDownloads.end(); it++) {
			CPartFile * file = *it;
			if (file->ECID() == ecid) {
				m_completedDownloads.erase(it);
				// get a new EC ID so it is resent and cleared in remote gui
				file->RenewECID();
				Notify_DownloadCtrlRemoveFile(file);
				break;
			}
		}
	}
}
bool CDownloadQueue::AddED2KLink( const CED2KFileLink* link, uint8 category )
{
	CPartFile* file = NULL;
	if (IsFileExisting(link->GetHashKey())) {
		// Must be a shared file if we are to add hashes or sources
		if ((file = GetFileByID(link->GetHashKey())) == NULL) {
			return false;
		}
	} else {
		if (link->GetSize() > OLD_MAX_FILE_SIZE) {
			if (!PlatformSpecific::CanFSHandleLargeFiles(thePrefs::GetTempDir())) {
				AddLogLineC(_("Filesystem for Temp directory cannot handle large files."));
				return false;
			} else if (!PlatformSpecific::CanFSHandleLargeFiles(theApp->glob_prefs->GetCatPath(category))) {
				AddLogLineC(_("Filesystem for Incoming directory cannot handle large files."));
				return false;
			}
		}

		file = new CPartFile(link);
	
		if (file->GetStatus() == PS_ERROR) {
			delete file;
			return false;
		}
		
		AddDownload(file, thePrefs::AddNewFilesPaused(), category);
	}
	
	if (link->HasValidAICHHash()) {
		CAICHHashSet* hashset = file->GetAICHHashset();
		
		if (!hashset->HasValidMasterHash() || (hashset->GetMasterHash() != link->GetAICHHash())) {
			hashset->SetMasterHash(link->GetAICHHash(), AICH_VERIFIED);
			hashset->FreeHashSet();
		}
	}
	
	const CED2KFileLink::CED2KLinkSourceList& list = link->m_sources;
	CED2KFileLink::CED2KLinkSourceList::const_iterator it = list.begin();
	for (; it != list.end(); ++it) {
		AddToResolve(link->GetHashKey(), it->addr, it->port, it->hash, it->cryptoptions);
	}

	return true;	
}
void CDownloadQueue::AddSearchToDownload(CSearchFile* toadd, uint8 category)
{
	if ( IsFileExisting(toadd->GetFileHash()) ) {
		return;
	}

	if (toadd->GetFileSize() > OLD_MAX_FILE_SIZE) {
		if (!PlatformSpecific::CanFSHandleLargeFiles(thePrefs::GetTempDir())) {
			AddLogLineC(_("Filesystem for Temp directory cannot handle large files."));
			return;
		} else if (!PlatformSpecific::CanFSHandleLargeFiles(theApp->glob_prefs->GetCatPath(category))) {
			AddLogLineC(_("Filesystem for Incoming directory cannot handle large files."));
			return;
		}
	}

	CPartFile* newfile = NULL;
	try {
		newfile = new CPartFile(toadd);
	} catch (const CInvalidPacket& WXUNUSED(e)) {
		AddDebugLogLineC(logDownloadQueue, wxT("Search-result contained invalid tags, could not add"));
	}
	
	if ( newfile && newfile->GetStatus() != PS_ERROR ) {
		AddDownload( newfile, thePrefs::AddNewFilesPaused(), category );
		// Add any possible sources
		if (toadd->GetClientID() && toadd->GetClientPort()) {
			CMemFile sources(1+4+2);
			sources.WriteUInt8(1);
			sources.WriteUInt32(toadd->GetClientID());
			sources.WriteUInt16(toadd->GetClientPort());
			sources.Reset();
			newfile->AddSources(sources, toadd->GetClientServerIP(), toadd->GetClientServerPort(), SF_SEARCH_RESULT, false);
		}
		for (std::list<CSearchFile::ClientStruct>::const_iterator it = toadd->GetClients().begin(); it != toadd->GetClients().end(); ++it) {
			CMemFile sources(1+4+2);
			sources.WriteUInt8(1);
			sources.WriteUInt32(it->m_ip);
			sources.WriteUInt16(it->m_port);
			sources.Reset();
			newfile->AddSources(sources, it->m_serverIP, it->m_serverPort, SF_SEARCH_RESULT, false);
		}
	} else {
		delete newfile;
	}
}
LRESULT CBufferMovieDlg::OnUpdateGUIFileProgress(WPARAM /*wParam*/, LPARAM lParam)
{
	static time_t tLast = 0;
	if(time(NULL) - tLast < 1)
		return S_OK;
	tLast = time(NULL);
	CPartFile* partfile = (CPartFile*)lParam;

	if (partfile)
	{
		CString strInfo;
		float percent = 100.0f - 100.0f * (float)partfile->GetTotalGapSizeInRange(0, 1024 * 1024 - 1) / (float)(1024 * 1024);
		strInfo.Format(GetResString(IDS_PLAY), percent);
		CWnd * wnd = GetDlgItem(IDC_STATIC_BUFFERMOVIE);
		wnd->SetWindowText(strInfo);
		if(percent >= 100.0f)
		{
			m_Parent->SendMessage(WM_UPDATE_GUI_STOP, 0, 0);
			OnOK();
		}
	}

	return S_OK;
}
void CDownloadQueue::CheckDiskspace( const CPath& path )
{
	if ( ::GetTickCount() - m_lastDiskCheck < DISKSPACERECHECKTIME ) {
		return;
	}
	
	m_lastDiskCheck = ::GetTickCount();

	uint64 min = 0;
	// Check if the user has set an explicit limit
	if ( thePrefs::IsCheckDiskspaceEnabled() ) {
		min = thePrefs::GetMinFreeDiskSpace();
	}

	// The very least acceptable diskspace is a single PART
	if ( min < PARTSIZE ) {
		min = PARTSIZE;
	}

	uint64 free = CPath::GetFreeSpaceAt(path);
	if (free == static_cast<uint64>(wxInvalidOffset)) {
		return;
	} else if (free < min) {
		CUserEvents::ProcessEvent(
			CUserEvents::OutOfDiskSpace,
			wxT("Temporary partition"));
	}
	
	for (unsigned int i = 0; i < m_filelist.size(); ++i) {
		CPartFile* file = m_filelist[i];
		
		switch ( file->GetStatus() ) {
			case PS_ERROR:
			case PS_COMPLETING:
			case PS_COMPLETE:
				continue;
		}
	
		if ( free >= min && file->GetInsufficient() ) {
			// We'll try to resume files if there is enough free space
			if ( free - file->GetNeededSpace() > min ) {
				file->ResumeFile();
			}
		} else if ( free < min && !file->IsPaused() ) {
			// No space left, stop the files.
			file->PauseFile( true );
		}
	}
}
Exemple #15
0
void CDownloadQueue::ResetCatParts(uint8 cat)
{
	for ( uint16 i = 0; i < GetFileCount(); i++ ) {
		CPartFile* file = GetFileByIndex( i );
		
		if ( file->GetCategory() == cat ) {
			// Reset the category
			file->SetCategory( 0 );
		} else if ( file->GetCategory() > cat ) {
			// Set to the new position of the original category
			file->SetCategory( file->GetCategory() - 1 );
		}
	}
}
Exemple #16
0
void CMMServer::ProcessFileCommand(CMMData* data, CMMSocket* sender){
	uint8 byCommand = data->ReadByte();
	uint8 byFileIndex = data->ReadByte();
	if (byFileIndex >= m_SentFileList.GetSize()
		|| !theApp.downloadqueue->IsPartFile(m_SentFileList[byFileIndex]))
	{
		CMMPacket* packet = new CMMPacket(MMP_GENERALERROR);
		sender->SendPacket(packet);
		ASSERT ( false );
		return;		
	}
	CPartFile* selFile = m_SentFileList[byFileIndex];
	switch (byCommand){
		case MMT_PAUSE:
			selFile->PauseFile();
			break;
		case MMT_RESUME:
			selFile->ResumeFile();
			break;
		case MMT_CANCEL:{
			switch(selFile->GetStatus()) { 
				case PS_WAITINGFORHASH: 
				case PS_HASHING: 
				case PS_COMPLETING: 
				case PS_COMPLETE:  
					break;
				case PS_PAUSED:
					selFile->DeleteFile(); 
					break;
				default:
                    theApp.downloadqueue->StartNextFileIfPrefs(selFile->GetCategory());
					selFile->DeleteFile(); 
			}
			break;
		}
		default:
			CMMPacket* packet = new CMMPacket(MMP_GENERALERROR);
			sender->SendPacket(packet);
			return;
	}
	CMMPacket* packet = new CMMPacket(MMP_FILECOMMANDANS);
	ProcessFileListRequest(sender,packet); 

}
Exemple #17
0
void CDownloadQueue::Process()
{
	// send src requests to local server
	ProcessLocalRequests();
	
	{
		wxMutexLocker lock(m_mutex);

		uint32 downspeed = 0;
		if (thePrefs::GetMaxDownload() != UNLIMITED && m_datarate > 1500) {
			downspeed = (((uint32)thePrefs::GetMaxDownload())*1024*100)/(m_datarate+1); 
			if (downspeed < 50) {
				downspeed = 50;
			} else if (downspeed > 200) {
				downspeed = 200;
			}
		}
	
		m_datarate = 0;
		m_udcounter++;
		uint32 cur_datarate = 0;
		uint32 cur_udcounter = m_udcounter;
		
		for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
			CPartFile* file = m_filelist[i];
	
			CMutexUnlocker unlocker(m_mutex);
			
			if ( file->GetStatus() == PS_READY || file->GetStatus() == PS_EMPTY ){
				cur_datarate += file->Process( downspeed, cur_udcounter );
			} else {
				//This will make sure we don't keep old sources to paused and stoped files..
				file->StopPausedFile();
			}
		}
	
		m_datarate += cur_datarate;
	
	
		if (m_udcounter == 5) {
			if (theApp->serverconnect->IsUDPSocketAvailable()) {
				if( (::GetTickCount() - m_lastudpstattime) > UDPSERVERSTATTIME) {
					m_lastudpstattime = ::GetTickCount();
					
					CMutexUnlocker unlocker(m_mutex);
					theApp->serverlist->ServerStats();
				}
			}
		}
	
		if (m_udcounter == 10) {
			m_udcounter = 0;
			if (theApp->serverconnect->IsUDPSocketAvailable()) {
				if ( (::GetTickCount() - m_lastudpsearchtime) > UDPSERVERREASKTIME) {
					SendNextUDPPacket();
				}
			}
		}
	
		if ( (::GetTickCount() - m_lastsorttime) > 10000 ) {
			
			
			DoSortByPriority();
		}
		// Check if any paused files can be resumed
			
		CheckDiskspace(thePrefs::GetTempDir());
	}
	
	
	// Check for new links once per second.
	if ((::GetTickCount() - m_nLastED2KLinkCheck) >= 1000) {
		theApp->AddLinksFromFile();
		m_nLastED2KLinkCheck = ::GetTickCount();
	}
}
Exemple #18
0
CString	CDetailInfo::GetLink(CKnownFile* pFile)
{
	//ADDED by fengwen on 2007/07/12 <begin>	:	如果是url下载,则返回源url。
	if (NULL == pFile)
		return _T("");

	if (pFile->IsPartFile())
	{
		CPartFile	*pPartFile = (CPartFile	*) pFile;
		if ( pPartFile->HasNullHash() )
			return pPartFile->GetPartFileURL();
	}
	//ADDED by fengwen on 2007/07/12 <end>	:	如果是url下载,则返回源url。

	CString strLinks;
	CString strBuffer;

	bool bHashset = false;
	bool bHTML = false;
//	bool bSource = true;
//	bool bHostname  = true;
	bool bEMHash = true;

	if (!strLinks.IsEmpty())
		strLinks += _T("\r\n\r\n");

	if (bHTML)
		strLinks += _T("<a href=\"");

	//const CKnownFile* file = STATIC_DOWNCAST(CKnownFile, (*pFile)[i]);
	const CKnownFile* file = pFile;
	strLinks += CreateED2kLink(file, false);

	if (bHashset && file->GetHashCount() > 0 && file->GetHashCount() == file->GetED2KPartHashCount())
	{
		strLinks += _T("p=");
		for (UINT j = 0; j < file->GetHashCount(); j++)
		{
			if (j > 0)
				strLinks += _T(':');
			strLinks += EncodeBase16(file->GetPartHash(j), 16);
		}
		strLinks += _T('|');
	}

	if (bEMHash && file->GetAICHHashset()->HasValidMasterHash() && 
		(file->GetAICHHashset()->GetStatus() == AICH_VERIFIED || file->GetAICHHashset()->GetStatus() == AICH_HASHSETCOMPLETE))
	{
		strBuffer.Format(_T("h=%s|"), file->GetAICHHashset()->GetMasterHash().GetString() );
		strLinks += strBuffer;			
	}
    if(!strLinks.IsEmpty())
	    strLinks += _T('/');
	//if (bHostname)
	//{
	//	strBuffer.Format(_T("|sources,%s:%i|/"), thePrefs.GetYourHostname(), thePrefs.GetPort() );
	//	strLinks += strBuffer;
	//}
	//else if(bSource)
	//{
	//	uint32 dwID = CGlobalVariable::GetID();
	//	strBuffer.Format(_T("|sources,%i.%i.%i.%i:%i|/"),(uint8)dwID,(uint8)(dwID>>8),(uint8)(dwID>>16),(uint8)(dwID>>24), thePrefs.GetPort() );
	//	strLinks += strBuffer;
	//}

	if (bHTML)
		strLinks += _T("\">") + StripInvalidFilenameChars(file->GetFileName(), true) + _T("</a>");

	return strLinks;
}
Exemple #19
0
void CFileDetailDialogInfo::RefreshData()
{
	CString str;

	if (m_paFiles->GetSize() == 1)
	{
		CPartFile* file = STATIC_DOWNCAST(CPartFile, (*m_paFiles)[0]);

		// if file is completed, we output the 'file path' and not the 'part.met file path'
		if (file->GetStatus(true) == PS_COMPLETE)
			GetDlgItem(IDC_FD_X2)->SetWindowText(GetResString(IDS_DL_FILENAME));

		SetDlgItemText(IDC_FNAME, file->GetFileName());
		SetDlgItemText(IDC_METFILE, file->GetFullName());
		SetDlgItemText(IDC_FHASH, md4str(file->GetFileHash()));

		if (file->GetTransferringSrcCount() > 0)
			str.Format(GetResString(IDS_PARTINFOS2), file->GetTransferringSrcCount());
		else
			str = file->getPartfileStatus();
		SetDlgItemText(IDC_PFSTATUS, str);

		str.Format(_T("%u;  %s: %u (%.1f%%)"), file->GetPartCount(), GetResString(IDS_AVAILABLE) , file->GetAvailablePartCount(), (float)((file->GetAvailablePartCount()*100)/file->GetPartCount()));
		SetDlgItemText(IDC_PARTCOUNT, str);

		// date created
		if (file->GetCrFileDate() != 0) {
			str.Format(_T("%s   ") + GetResString(IDS_TIMEBEFORE),
						file->GetCrCFileDate().Format(thePrefs.GetDateTimeFormat()),
						CastSecondsToLngHM(time(NULL) - file->GetCrFileDate()));
		}
		else
			str = GetResString(IDS_UNKNOWN);
		SetDlgItemText(IDC_FILECREATED, str);

		// active download time
		time_t nDlActiveTime = file->GetDlActiveTime(); //vs2005
		if (nDlActiveTime)
			str = CastSecondsToLngHM(nDlActiveTime);
		else
			str = GetResString(IDS_UNKNOWN);
		SetDlgItemText(IDC_DL_ACTIVE_TIME, str);

		// last seen complete
		struct tm tmTemp;
		struct tm* ptimLastSeenComplete = file->lastseencomplete.GetLocalTm(&tmTemp);
		if (file->lastseencomplete == NULL || ptimLastSeenComplete == NULL)
			str.Format(GetResString(IDS_NEVER));
		else {
			str.Format(_T("%s   ") + GetResString(IDS_TIMEBEFORE),
						file->lastseencomplete.Format(thePrefs.GetDateTimeFormat()),
						CastSecondsToLngHM(time(NULL) - safe_mktime(ptimLastSeenComplete)));
		}
		SetDlgItemText(IDC_LASTSEENCOMPL, str);

		// last receive
		if (file->GetFileDate() != 0 && file->GetRealFileSize() > (uint64)0)
		{
			// 'Last Modified' sometimes is up to 2 seconds greater than the current time ???
			// If it's related to the FAT32 seconds time resolution the max. failure should still be only 1 sec.
			// Happens at least on FAT32 with very high download speed.
			uint32 tLastModified = file->GetFileDate();
			time_t tNow = time(NULL); //vs2005
			uint32 tAgo;
			if (tNow >= tLastModified)
				tAgo = tNow - tLastModified;
			else{
				TRACE("tNow = %s\n", CTime(tNow).Format("%X"));
				TRACE("tLMd = %s, +%u\n", CTime(tLastModified).Format("%X"), tLastModified - tNow);
				TRACE("\n");
				tAgo = 0;
			}
			str.Format(_T("%s   ") + GetResString(IDS_TIMEBEFORE),
						file->GetCFileDate().Format(thePrefs.GetDateTimeFormat()),
						CastSecondsToLngHM(tAgo));
		}
		else
			str = GetResString(IDS_NEVER);
		SetDlgItemText(IDC_LASTRECEIVED, str);

		// AICH Hash
		switch (file->GetAICHRecoveryHashSet()->GetStatus()) {
			case AICH_TRUSTED:
			case AICH_VERIFIED:
			case AICH_HASHSETCOMPLETE:
				if (file->GetAICHRecoveryHashSet()->HasValidMasterHash()) {
					SetDlgItemText(IDC_FD_AICHHASH, file->GetAICHRecoveryHashSet()->GetMasterHash().GetString());
					break;
				}
			default:
				SetDlgItemText(IDC_FD_AICHHASH, GetResString(IDS_UNKNOWN));
		}

		// file type
		CString ext;
		bool showwarning = false;
		int pos = file->GetFileName().ReverseFind(_T('.'));
		if (file->GetFileName().ReverseFind(_T('\\')) < pos) {
			ext = file->GetFileName().Mid(pos + 1);
			ext.MakeUpper();
		}
		
		EFileType bycontent = GetFileTypeEx((CKnownFile *)file, false, true);
		if (bycontent != FILETYPE_UNKNOWN) {
			str = GetFileTypeName(bycontent) + _T("  (");
			str.Append(GetResString(IDS_VERIFIED) + _T(')'));

			int extLevel = IsExtensionTypeOf(bycontent, ext);
			if (extLevel == -1) {
				showwarning = true;
				str.Append(_T(" - "));
				str.Append(GetResString(IDS_INVALIDFILEEXT) + _T(": "));
				str.Append(ext);
			}
			else if (extLevel == 0) {
				str.Append(_T(" - "));
				str.Append(GetResString(IDS_UNKNOWNFILEEXT) + _T(": "));
				str.Append(ext);
			}
		}
		else {
			// not verified
			if (pos != -1) {
				str =file->GetFileName().Mid(pos + 1);
				str.MakeUpper();
				str.Append(_T("  (") );
				str.Append( GetResString(IDS_UNVERIFIED) + _T(')'));
			}
			else
				str = GetResString(IDS_UNKNOWN);
		}
		m_bShowFileTypeWarning = showwarning;
		SetDlgItemText(IDC_FD_X11,str);
	}
	else
	{
		SetDlgItemText(IDC_FNAME, sm_pszNotAvail);
		SetDlgItemText(IDC_METFILE, sm_pszNotAvail);
		SetDlgItemText(IDC_FHASH, sm_pszNotAvail);

		SetDlgItemText(IDC_PFSTATUS, sm_pszNotAvail);
		SetDlgItemText(IDC_PARTCOUNT, sm_pszNotAvail);
		SetDlgItemText(IDC_FD_X11, sm_pszNotAvail);

		SetDlgItemText(IDC_FILECREATED, sm_pszNotAvail);
		SetDlgItemText(IDC_DL_ACTIVE_TIME, sm_pszNotAvail);
		SetDlgItemText(IDC_LASTSEENCOMPL, sm_pszNotAvail);
		SetDlgItemText(IDC_LASTRECEIVED, sm_pszNotAvail);
		SetDlgItemText(IDC_FD_AICHHASH, sm_pszNotAvail);
	}

	uint64 uFileSize = 0;
	uint64 uRealFileSize = 0;
	uint64 uTransferred = 0;
	uint64 uCorrupted = 0;
	uint32 uRecoveredParts = 0;
	uint64 uCompression = 0;
	uint64 uCompleted = 0;
	int iMD4HashsetAvailable = 0;
	int iAICHHashsetAvailable = 0;
	uint32 uDataRate = 0;
	UINT uSources = 0;
	UINT uValidSources = 0;
	UINT uNNPSources = 0;
	UINT uA4AFSources = 0;
	for (int i = 0; i < m_paFiles->GetSize(); i++)
	{
		CPartFile* file = STATIC_DOWNCAST(CPartFile, (*m_paFiles)[i]);

		uFileSize += (uint64)file->GetFileSize();
		uRealFileSize += (uint64)file->GetRealFileSize();
		uTransferred += (uint64)file->GetTransferred();
		uCorrupted += file->GetCorruptionLoss();
		uRecoveredParts += file->GetRecoveredPartsByICH();
		uCompression += file->GetCompressionGain();
		uDataRate += file->GetDatarate();
		uCompleted += (uint64)file->GetCompletedSize();
		iMD4HashsetAvailable += (file->GetFileIdentifier().HasExpectedMD4HashCount()) ? 1 : 0;
		iAICHHashsetAvailable += (file->GetFileIdentifier().HasExpectedAICHHashCount()) ? 1 : 0;

		if (file->IsPartFile())
		{
			uSources += file->GetSourceCount();
			uValidSources += file->GetValidSourcesCount();
			uNNPSources += file->GetSrcStatisticsValue(DS_NONEEDEDPARTS);
			uA4AFSources += file->GetSrcA4AFCount();
		}
	}

	str.Format(_T("%s  (%s %s);  %s %s"), CastItoXBytes(uFileSize, false, false), GetFormatedUInt64(uFileSize), GetResString(IDS_BYTES), GetResString(IDS_ONDISK), CastItoXBytes(uRealFileSize, false, false));
	SetDlgItemText(IDC_FSIZE, str);

	if (m_paFiles->GetSize() == 1)
	{
		if (iAICHHashsetAvailable == 0 && iMD4HashsetAvailable == 0)
			SetDlgItemText(IDC_HASHSET, GetResString(IDS_NO));
		else if (iAICHHashsetAvailable == 1 && iMD4HashsetAvailable == 1)
			SetDlgItemText(IDC_HASHSET, GetResString(IDS_YES) + _T(" (eD2K + AICH)"));
		else if (iAICHHashsetAvailable == 1)
			SetDlgItemText(IDC_HASHSET, GetResString(IDS_YES) + _T(" (AICH)"));
		else if (iMD4HashsetAvailable == 1)
			SetDlgItemText(IDC_HASHSET, GetResString(IDS_YES) + _T(" (eD2K)"));
	}
	else
	{
		if (iAICHHashsetAvailable == 0 && iMD4HashsetAvailable == 0)
			SetDlgItemText(IDC_HASHSET, GetResString(IDS_NO));
		else if (iMD4HashsetAvailable == m_paFiles->GetSize() && iAICHHashsetAvailable == m_paFiles->GetSize())
			SetDlgItemText(IDC_HASHSET, GetResString(IDS_YES) +  + _T(" (eD2K + AICH)"));
		else
			SetDlgItemText(IDC_HASHSET, _T(""));
	}

	str.Format(GetResString(IDS_SOURCESINFO), uSources, uValidSources, uNNPSources, uA4AFSources);
	SetDlgItemText(IDC_SOURCECOUNT, str);

	SetDlgItemText(IDC_DATARATE, CastItoXBytes(uDataRate, false, true));

	SetDlgItemText(IDC_TRANSFERRED, CastItoXBytes(uTransferred, false, false));

	str.Format(_T("%s (%.1f%%)"), CastItoXBytes(uCompleted, false, false), uFileSize!=0 ? (uCompleted * 100.0 / uFileSize) : 0.0);
	SetDlgItemText(IDC_COMPLSIZE, str);

	str.Format(_T("%s (%.1f%%)"), CastItoXBytes(uCorrupted, false, false), uTransferred!=0 ? (uCorrupted * 100.0 / uTransferred) : 0.0);
	SetDlgItemText(IDC_CORRUPTED, str);

	str.Format(_T("%s (%.1f%%)"), CastItoXBytes(uFileSize - uCompleted, false, false), uFileSize!=0 ? ((uFileSize - uCompleted) * 100.0 / uFileSize) : 0.0);
	SetDlgItemText(IDC_REMAINING, str);

	str.Format(_T("%u %s"), uRecoveredParts, GetResString(IDS_FD_PARTS));
	SetDlgItemText(IDC_RECOVERED, str);

	str.Format(_T("%s (%.1f%%)"), CastItoXBytes(uCompression, false, false), uTransferred!=0 ? (uCompression * 100.0 / uTransferred) : 0.0);
	SetDlgItemText(IDC_COMPRESSION, str);
}
bool CDownloadQueue::SendNextUDPPacket()
{
	if ( m_filelist.empty() || !theApp->serverconnect->IsUDPSocketAvailable() || !theApp->IsConnectedED2K()) {
		return false;
	}

	// Start monitoring the server and the files list
	if ( !m_queueServers.IsActive() ) {
		AddObserver( &m_queueFiles );
		
		theApp->serverlist->AddObserver( &m_queueServers );
	}
	

 	bool packetSent = false;
 	while ( !packetSent ) {
 		// Get max files ids per packet for current server
 		int filesAllowed = GetMaxFilesPerUDPServerPacket();
 
 		if (filesAllowed < 1 || !m_udpserver || IsConnectedServer(m_udpserver)) {
 			// Select the next server to ask, must not be the connected server
 			do {
				m_udpserver = m_queueServers.GetNext();
			} while (IsConnectedServer(m_udpserver));
	
 			m_cRequestsSentToServer = 0;
 			filesAllowed = GetMaxFilesPerUDPServerPacket();
  		}
 
 		
 		// Check if we have asked all servers, in which case we are done
 		if (m_udpserver == NULL) {
 			DoStopUDPRequests();
 			
 			return false;
  		}
  
 		// Memoryfile containing the hash of every file to request
		// 28bytes allocation because 16b + 4b + 8b is the worse case scenario.
 		CMemFile hashlist( 28 );
 		
		CPartFile* file = m_queueFiles.GetNext();
		
		while ( file && filesAllowed ) {
 			uint8 status = file->GetStatus();
 			
			if ( ( status == PS_READY || status == PS_EMPTY ) && file->GetSourceCount() < thePrefs::GetMaxSourcePerFileUDP() ) {
				if (file->IsLargeFile() && !m_udpserver->SupportsLargeFilesUDP()) {
					AddDebugLogLineN(logDownloadQueue, wxT("UDP Request for sources on a large file ignored: server doesn't support it"));
				} else {
					++m_cRequestsSentToServer;
					hashlist.WriteHash( file->GetFileHash() );
					// See the notes on TCP packet
					if ( m_udpserver->GetUDPFlags() & SRV_UDPFLG_EXT_GETSOURCES2 ) {
						if (file->IsLargeFile()) {
							wxASSERT(m_udpserver->SupportsLargeFilesUDP());
							hashlist.WriteUInt32( 0 );
							hashlist.WriteUInt64( file->GetFileSize() );
						} else {
							hashlist.WriteUInt32( file->GetFileSize() );
						}
					}
					--filesAllowed;
				}
  			}
		
			// Avoid skipping a file if we can't send any more currently
			if ( filesAllowed ) {
				file = m_queueFiles.GetNext();
			}
		}
		
		// See if we have anything to send
 		if ( hashlist.GetLength() ) {
 			packetSent = SendGlobGetSourcesUDPPacket(hashlist);
		}
 		
 		// Check if we've covered every file
		if ( file == NULL ) {
 			// Reset the list of asked files so that the loop will start over
			m_queueFiles.Reset();
			
 			// Unset the server so that the next server will be used
 			m_udpserver = NULL;
  		}
  	}
	
	return true;
}
Exemple #21
0
void CDetailInfo::UpdateInfo(CPartFile* pFile, DWORD dwMask)
{
	try
	{
		m_ListDetail.DeleteAllItems();

		if (NULL == pFile || 0 == dwMask)
			return;

		m_pCurFile = pFile;
		m_dwCurMask = dwMask;

		int	iItem;
		CString	str;
		CPartFile	*lpPartFile = pFile;//DYNAMIC_DOWNCAST(CPartFile, pFile);

		iItem = 0;

		if (IM_FILENAME & dwMask)
		{
			str = pFile->GetFileName();
			m_ListDetail.InsertItem(iItem, GetResString(IDS_DL_FILENAME));
			m_ListDetail.SetItemText(iItem, 1, str);
			iItem++;
		}
		if (IM_FILESIZE & dwMask)
		{
			str = CastItoXBytes(pFile->GetFileSize(), false, false);
			m_ListDetail.InsertItem(iItem, GetResString(IDS_DL_SIZE));
			if(!str.IsEmpty())
			    m_ListDetail.SetItemText(iItem, 1, str);
			else
				m_ListDetail.SetItemText(iItem, 1, GetResString(IDS_UNKNOWN));
			iItem++;
		}
		if (IM_FILETYPE & dwMask)
		{
			str = pFile->GetFileTypeDisplayStr();
			m_ListDetail.InsertItem(iItem, GetResString(IDS_TYPE));
			if(!str.IsEmpty())
			    m_ListDetail.SetItemText(iItem, 1, str);
			else
				m_ListDetail.SetItemText(iItem, 1, GetResString(IDS_UNKNOWN));
			iItem++;
		}
		
		if (IM_LINK & dwMask)
		{   
			str = GetLink(pFile);
			bool bRefer = false;
			if(str.Left(7).CompareNoCase(_T("http://")) == 0)
			{  
				if(str.Find(_T('<'))>0)
				{   
					bRefer = true;
					str = str.Left(str.Find(_T('<')));
				}
				if(str.Find(_T('#'))>0)
					str = str.Left(str.Find(_T('#')));
			}
			if(!str.IsEmpty())
			{
				m_ListDetail.InsertItem(iItem, GetResString(IDS_DOWNLOAD_LINK));
				m_ListDetail.SetItemText(iItem, 1, str);
				iItem++;
			}
			if(bRefer)
			{
				
				CString refer = GetLink(pFile);
				refer = refer.Right(refer.GetLength() - 1 - refer.Find(_T('=')));
				if(refer.Find(_T('>')) > 0)
					refer.Remove(_T('>'));
				m_ListDetail.InsertItem(iItem,GetResString(IDS_REFER_LINK));
				m_ListDetail.SetItemText(iItem,1,refer);
				iItem++;
			}
		}
		if (IM_SOURCEURL & dwMask)
		{
			str = pFile->GetPartFileURL();
			bool bRefer = false;
			if(str.Find(_T('<'))>0)
			{   
				bRefer = true;
				str = str.Left(str.Find(_T('<')));
			}
			if(str.Find(_T('#'))>0)
				str = str.Left(str.Find(_T('#')));
			if(!str.IsEmpty())
			{
		       m_ListDetail.InsertItem(iItem, GetResString(IDS_URL_LINK));
		       m_ListDetail.SetItemText(iItem, 1, str);
			   iItem++;
			}
			if(bRefer)
			{   
			   CString strRefer = pFile->GetPartFileURL();
			   strRefer = strRefer.Right(strRefer.GetLength() -1 - strRefer.Find(_T('=')  ));
			   if(strRefer.Find(_T('>'))>0)
				   strRefer.Remove(_T('>'));
				m_ListDetail.InsertItem(iItem,GetResString(IDS_REFER_LINK));
				m_ListDetail.SetItemText(iItem,1,strRefer);
				iItem++;
			}
		}
		if (IM_PRIORITY & dwMask)
		{ 
			if(dwMask == CDetailInfo::IM_COMBINE_DOWNLOAD)
			      str = PriorityToString(pFile->GetDownPriority(), pFile->IsAutoDownPriority());
			if(dwMask == CDetailInfo::IM_COMBINE_SHARE)
				str = PriorityToString(pFile->GetUpPriority(),pFile->IsAutoUpPriority());
			m_ListDetail.InsertItem(iItem, GetResString(IDS_PRIORITY));
			m_ListDetail.SetItemText(iItem, 1, str);
			iItem++;
		}
		if (IM_FILEHASH & dwMask)
		{
			if (pFile->HasNullHash())
			{
				str = _T("-");
			}
			else
			{
				str = md4str(pFile->GetFileHash());
			}
			
			m_ListDetail.InsertItem(iItem, GetResString(IDS_FILEID));
			m_ListDetail.SetItemText(iItem, 1, str);
			iItem++;
		}
		if (IM_REQUEST & dwMask)
		{
			str.Format(_T("%u (%u)"), pFile->statistic.GetRequests(), pFile->statistic.GetAllTimeRequests());
			m_ListDetail.InsertItem(iItem, GetResString(IDS_SF_REQUESTS));
			m_ListDetail.SetItemText(iItem, 1, str);
			iItem++;
		}
		if (IM_TRANSFERED & dwMask)
		{
			str.Format(_T("%s (%s)"), CastItoXBytes(pFile->statistic.GetTransferred(), false, false), CastItoXBytes(pFile->statistic.GetAllTimeTransferred(), false, false));
			m_ListDetail.InsertItem(iItem, GetResString(IDS_SF_TRANSFERRED));
			m_ListDetail.SetItemText(iItem, 1, str);
			iItem++;
		}
		if (IM_FILEPATH & dwMask)
		{
			str = pFile->GetPath();
			PathRemoveBackslash(str.GetBuffer());
			str.ReleaseBuffer();
			m_ListDetail.InsertItem(iItem, GetResString(IDS_FOLDER));
			m_ListDetail.SetItemText(iItem, 1, str);
			iItem++;
		}
		if (IM_ACCEPT & dwMask)
		{
			str.Format(_T("%u (%u)"), pFile->statistic.GetAccepts(), pFile->statistic.GetAllTimeAccepts());
			m_ListDetail.InsertItem(iItem, GetResString(IDS_SF_ACCEPTS));
			m_ListDetail.SetItemText(iItem, 1, str);
			iItem++;
		}
		if (IM_SOURCE & dwMask)
		{
			str.Format(_T("%u - %u"), pFile->m_nCompleteSourcesCountLo, pFile->m_nCompleteSourcesCountHi);
			m_ListDetail.InsertItem(iItem, GetResString(IDS_COMPLSOURCES));
			m_ListDetail.SetItemText(iItem, 1, str);
			iItem++;
		}
		if (IM_REMAIN & dwMask)
		{
			if (NULL != lpPartFile)
			{
				str.Empty();
				if (lpPartFile->GetStatus() != PS_COMPLETING && lpPartFile->GetStatus() != PS_COMPLETE )
				{
					// time 
					time_t restTime;
					if (!thePrefs.UseSimpleTimeRemainingComputation())
						restTime = lpPartFile->getTimeRemaining();
					else
						restTime = lpPartFile->getTimeRemainingSimple();

					str.Format(_T("%s (%s)"), CastSecondsToHM(restTime), CastItoXBytes((lpPartFile->GetFileSize() - lpPartFile->GetCompletedSize()), false, false));
				}
				else
				{
					str.Format(_T("%s (%s)"), _T("0"), CastItoXBytes((lpPartFile->GetFileSize() - lpPartFile->GetCompletedSize()), false, false));
				}
				m_ListDetail.InsertItem(iItem, GetResString(IDS_DL_REMAINS));
				if(!str.IsEmpty())
				   m_ListDetail.SetItemText(iItem, 1, str);
				else
					m_ListDetail.SetItemText(iItem,1,GetResString(IDS_UNKNOWN));
				iItem++;
			}

		}
		if (IM_LASTCOMPLETE & dwMask)
		{
			if (NULL != lpPartFile)
			{
//				CString tempbuffer;
//				if (lpPartFile->m_nCompleteSourcesCountLo == 0)
//				{
//					tempbuffer.Format(_T("< %u"), lpPartFile->m_nCompleteSourcesCountHi);
//				}
//				else if (lpPartFile->m_nCompleteSourcesCountLo == lpPartFile->m_nCompleteSourcesCountHi)
//				{
//					tempbuffer.Format(_T("%u"), lpPartFile->m_nCompleteSourcesCountLo);
//				}
//				else
//				{
//					tempbuffer.Format(_T("%u - %u"), lpPartFile->m_nCompleteSourcesCountLo, lpPartFile->m_nCompleteSourcesCountHi);
//				}
				if (lpPartFile->lastseencomplete==NULL)
					str.Format(_T("%s" /*(%s)*/),GetResString(IDS_NEVER)/*,tempbuffer*/);
				else
					str.Format(_T("%s" /*(%s)*/),lpPartFile->lastseencomplete.Format( thePrefs.GetDateTimeFormat())/*,tempbuffer*/);

				m_ListDetail.InsertItem(iItem, GetResString(IDS_LASTSEENCOMPL));
				m_ListDetail.SetItemText(iItem, 1, str);
				iItem++;
			}

		}
		if (IM_LASTRECV & dwMask)
		{
			if (NULL != lpPartFile)
			{
				if(lpPartFile->GetFileDate()!=NULL && lpPartFile->GetRealFileSize()/*GetCompletedSize() */> (uint64)0)
					str = lpPartFile->GetCFileDate().Format( thePrefs.GetDateTimeFormat());
				else
					str.Format(_T("%s"),GetResString(IDS_NEVER));

				m_ListDetail.InsertItem(iItem, GetResString(IDS_FD_LASTCHANGE));
				m_ListDetail.SetItemText(iItem, 1, str);
				iItem++;
			}
		}
		if (IM_CATEGORY & dwMask)
		{
			if (NULL != lpPartFile)
			{
				str = (lpPartFile->GetCategory()!=0) ? thePrefs.GetCategory(lpPartFile->GetCategory())->strTitle:_T("");

				m_ListDetail.InsertItem(iItem, GetResString(IDS_CAT));
				m_ListDetail.SetItemText(iItem, 1, str);
				iItem++;
			}
		}
	}
	catch(...)
	{
	}
}
void CDownloadQueue::Process()
{
	// send src requests to local server
	ProcessLocalRequests();
	
	{
		wxMutexLocker lock(m_mutex);

		uint32 downspeed = 0;
		if (thePrefs::GetMaxDownload() != UNLIMITED && m_datarate > 1500) {
			downspeed = (((uint32)thePrefs::GetMaxDownload())*1024*100)/(m_datarate+1); 
			if (downspeed < 50) {
				downspeed = 50;
			} else if (downspeed > 200) {
				downspeed = 200;
			}
		}
	
		m_datarate = 0;
		m_udcounter++;
		uint32 cur_datarate = 0;
		uint32 cur_udcounter = m_udcounter;
		
		std::list<int> m_sourcecountlist;

		bool mustPreventSleep = false;

		for ( uint16 i = 0; i < m_filelist.size(); i++ ) {
			CPartFile* file = m_filelist[i];
	
			CMutexUnlocker unlocker(m_mutex);
			
			uint8 status = file->GetStatus();
			mustPreventSleep |= !(status == PS_ERROR || status == PS_INSUFFICIENT || status == PS_PAUSED || status == PS_COMPLETE);

			if (status == PS_READY || status == PS_EMPTY ){
				cur_datarate += file->Process( downspeed, cur_udcounter );
			} else {
				//This will make sure we don't keep old sources to paused and stoped files..
				file->StopPausedFile();
			}

			if (!file->IsPaused() && !file->IsStopped()) {
				m_sourcecountlist.push_back(file->GetSourceCount());
			}
		}

		if (thePrefs::GetPreventSleepWhileDownloading()) {
			if ((mustPreventSleep == false) && (theStats::GetSessionSentBytes() < theStats::GetSessionReceivedBytes())) {
				// I can see right through your clever plan.
				mustPreventSleep = true;
			}

			if (mustPreventSleep) {
				PlatformSpecific::PreventSleepMode();
			} else {
				PlatformSpecific::AllowSleepMode();
			}
		} else {
			// Just in case the value changes while we're preventing. Calls to this function are totally inexpensive anwyay
			PlatformSpecific::AllowSleepMode();
		}


		// Set the source rarity thresholds
		int nSourceGroups = m_sourcecountlist.size();
		if (nSourceGroups) {
			m_sourcecountlist.sort();
			if (nSourceGroups == 1) {
				// High anyway.
				m_rareFileThreshold = m_sourcecountlist.front() + 1;
				m_commonFileThreshold = m_rareFileThreshold + 1;
			} else if (nSourceGroups == 2) {
				// One high, one low (unless they're both 0, then both high)
				m_rareFileThreshold = (m_sourcecountlist.back() > 0) ? (m_sourcecountlist.back() - 1) : 1;
				m_commonFileThreshold = m_rareFileThreshold + 1;
			} else {
				// More than two, time to do some math.

				// Lower 25% with the current #define values.
				int rarecutpoint = (nSourceGroups / RARITY_FACTOR); 
				for (int i = 0; i < rarecutpoint; ++ i) {
					m_sourcecountlist.pop_front();
				}
				m_rareFileThreshold = (m_sourcecountlist.front() > 0) ? (m_sourcecountlist.front() - 1) : 1;

				// 50% of the non-rare ones, with the curent #define values.
				int commoncutpoint = (nSourceGroups - rarecutpoint) / NORMALITY_FACTOR;
				for (int i = 0; i < commoncutpoint; ++ i) {
					m_sourcecountlist.pop_front();
				}
				m_commonFileThreshold = (m_sourcecountlist.front() > 0) ? (m_sourcecountlist.front() - 1) : 1;
			}
		} else {
			m_rareFileThreshold = RARE_FILE;
			m_commonFileThreshold = 100;
		}
	
		m_datarate += cur_datarate;

		if (m_udcounter == 5) {
			if (theApp->serverconnect->IsUDPSocketAvailable()) {
				if( (::GetTickCount() - m_lastudpstattime) > UDPSERVERSTATTIME) {
					m_lastudpstattime = ::GetTickCount();
					
					CMutexUnlocker unlocker(m_mutex);
					theApp->serverlist->ServerStats();
				}
			}
		}
	
		if (m_udcounter == 10) {
			m_udcounter = 0;
			if (theApp->serverconnect->IsUDPSocketAvailable()) {
				if ( (::GetTickCount() - m_lastudpsearchtime) > UDPSERVERREASKTIME) {
					SendNextUDPPacket();
				}
			}
		}
	
		if ( (::GetTickCount() - m_lastsorttime) > 10000 ) {
			DoSortByPriority();
		}
		// Check if any paused files can be resumed
			
		CheckDiskspace(thePrefs::GetTempDir());
	}
	
	
	// Check for new links once per second.
	if ((::GetTickCount() - m_nLastED2KLinkCheck) >= 1000) {
		theApp->AddLinksFromFile();
		m_nLastED2KLinkCheck = ::GetTickCount();
	}
}
CString CDlgMainTabRss::GetCurrentFileCommentString()
{
	if (!m_pwndRssFeed || !::IsWindow(m_pwndRssFeed->m_hWnd))
	{
		return CString(_T(""));
	}
	
	POSITION Pos = NULL;

	if (m_pwndRssFeed->m_ListShowMode == LISTSTYLE_ICO)
	{
		Pos = m_pwndRssFeed->m_listIcoFeedItem.GetFirstSelectedItemPosition();
	}
	else if (m_pwndRssFeed->m_ListShowMode == LISTSTYLE_ITEM)
	{
		Pos = m_pwndRssFeed->m_listFeedItem.GetFirstSelectedItemPosition();
	}
	else if(m_pwndRssFeed->m_ListShowMode == LISTSTYLE_SINGLE)
	{
		Pos = m_pwndRssFeed->m_listSingleFeedItem.GetFirstSelectedItemPosition();
	}

	if (!Pos)
	{
		return CString(_T(""));
	}

	int nIndex;
	CRssFeed::Item* pItem;

	if (m_pwndRssFeed->m_ListShowMode == LISTSTYLE_ICO)
	{//ICO模式没有item
		nIndex = m_pwndRssFeed->m_listIcoFeedItem.GetNextSelectedItem(Pos);
		pItem = NULL;
	}
	else if (m_pwndRssFeed->m_ListShowMode == LISTSTYLE_ITEM)
	{
		nIndex = m_pwndRssFeed->m_listFeedItem.GetNextSelectedItem(Pos);
		pItem =  m_pwndRssFeed->m_listFeedItem.GetFeedItem(nIndex);
	}
	else if(m_pwndRssFeed->m_ListShowMode == LISTSTYLE_SINGLE)
	{
		nIndex = m_pwndRssFeed->m_listSingleFeedItem.GetNextSelectedItem(Pos);
		pItem =  m_pwndRssFeed->m_listSingleFeedItem.GetFeedItem(nIndex);
	}

	if (pItem && pItem->GetPartFile())
	{
		CPartFile * pPartFile = pItem->GetPartFile();
		
		CString strFileEd2k = CreateED2kLink(pPartFile, false);
		if( strFileEd2k.IsEmpty() )
		{
			return CString(_T(""));
		}

		bool bFileisFinished = true;
		if( pPartFile->IsKindOf(RUNTIME_CLASS(CPartFile)) )
		{
			if( ((CPartFile*)pPartFile)->GetStatus()!=PS_COMPLETE )
				bFileisFinished = false;
		}

		CString strCommentUrl = bFileisFinished ? thePrefs.m_strFinishedFileCommentUrl : thePrefs.m_strPartFileCommentUrl;
		strCommentUrl.Replace(_T("[ed2k]"),strFileEd2k);
		strCommentUrl.Replace(_T("|"), _T("%7C"));

		CString sVersion;
		sVersion.Format(_T("&v=%u"),VC_VERSION_BUILD);
		strCommentUrl += sVersion;
		return strCommentUrl;
	}
	else if (pItem)
	{
		CString strED2KUrl = pItem->m_strEnclosure;
		if( strED2KUrl.IsEmpty() || strED2KUrl.Left(7).CompareNoCase(_T("ed2k://")))
		{
			return CString(_T(""));
		}

		CString strCommentUrl = thePrefs.m_strPartFileCommentUrl;
		strCommentUrl.Replace(_T("[ed2k]"),strED2KUrl);
		strCommentUrl.Replace(_T("|"), _T("%7C"));

		CString sVersion;
		sVersion.Format(_T("&v=%u"),VC_VERSION_BUILD);
		strCommentUrl += sVersion;
		return strCommentUrl;
	}
	else
	{
		CRssFeed* pFeed;
		if (m_pwndRssFeed->m_ListShowMode == LISTSTYLE_ITEM)
		{
			pFeed = m_pwndRssFeed->m_listFeedItem.GetFeed(nIndex);
		}
		else if(m_pwndRssFeed->m_ListShowMode == LISTSTYLE_SINGLE)
		{
			pFeed = m_pwndRssFeed->m_listSingleFeedItem.GetFeed(nIndex);
		}
		
		if ( pFeed == NULL )
		{
			pFeed = m_pwndRssFeed->m_listFeedItem.GetBlankLineFeed(nIndex - 1);
		}

		if (pFeed)
		{
			CString strCommentUrl = pFeed->m_strFeedUrl;
			strCommentUrl.MakeLower();
			int nPos = strCommentUrl.Find(_T("/feed"));
			if (nPos != -1)
			{
				strCommentUrl = strCommentUrl.Left(nPos);
				strCommentUrl +=_T("/comments/");
				return strCommentUrl;	
			}
		}

		return CString();
		//CString strFilePath;
		//strFilePath = thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("Default.htm");
		//return strFilePath;
	}
}
BOOL CFeedIcoItemListCtrl::OnCommand(WPARAM wParam, LPARAM lParam)
{
	// TODO: 在此添加专用代码和/或调用基类

	if (  /*LOWORD(wParam) == MP_STOP
		||*/LOWORD(wParam) == MP_DOWNLOAD_ALL
		||LOWORD(wParam) == MP_OPEN
		||LOWORD(wParam) == MP_OPENFOLDER
		||LOWORD(wParam) == MP_RESUME
		||LOWORD(wParam) == MP_PAUSE
		||LOWORD(wParam) == MP_CANCEL
		||LOWORD(wParam) == MP_OPTIONS)
	{
		POSITION Pos = this->GetFirstSelectedItemPosition();
		if (Pos == NULL)
		{
			return 0;
		}
		int nIndex = this->GetNextSelectedItem(Pos);

		if( CRssFeed* pFeed = this->GetFeed(nIndex) )
		{
			if ( LOWORD(wParam) == MP_OPENFOLDER)
			{
				if( CRssFeed* pFeed = this->GetFeed(nIndex) )
				{
					if(PathFileExists(pFeed->m_strSaveDir))
						ShellExecute(NULL, _T("open"), _T("explorer.exe"), pFeed->m_strSaveDir, NULL, SW_SHOW);
				}
			}

			if ( LOWORD(wParam) == MP_DOWNLOAD_ALL )
			{
				((CRssFeedWnd*)GetParent())->DownloadAllItem(nIndex);
			}
			if ( LOWORD(wParam) == MP_RESUME )
			{
				((CRssFeedWnd*)GetParent())->ResumeAllItem(nIndex);
			}
			if ( LOWORD(wParam) == MP_PAUSE)
			{
				for ( CRssFeed::ItemIterator it = pFeed->GetItemIterBegin();
					it != pFeed->GetItemIterEnd();
					++it
					)
				{
					CPartFile* pPartFile = it->second.GetPartFile();
					if (pPartFile != NULL)
					{
						if (pPartFile->CanPauseFile())
							pPartFile->PauseFile();		
					}
				}
			}

			if ( LOWORD(wParam) == MP_CANCEL)
			{
				::SendMessage(CGlobalVariable::s_wndRssCtrl->GetSafeHwnd(), WM_COMMAND, wParam, lParam);
			}

			if ( LOWORD(wParam) == MP_OPTIONS)
			{
				CDlgFeedConfig dlgFeedConfig(*pFeed);
				if ( dlgFeedConfig.DoModal() == IDOK )
				{
					// 保存设置
					pFeed->SetUpdateInterval(dlgFeedConfig.m_uUpdateInterval);
					pFeed->SetAutoDownload(dlgFeedConfig.m_uAutoDownload);
					CGlobalVariable::s_wndRssCtrl->SaveFeed(*pFeed);
					//RedrawItems(nIndex, nIndex);
				}
			}

			CDownloadTabWnd & wd = theApp.emuledlg->m_mainTabWnd.m_dlgDownload.m_DownloadTabWnd;
			UpdateToolBarState(wd.m_Toolbar);

			return 0;
		}
	}

	::SendMessage(CGlobalVariable::s_wndRssCtrl->GetSafeHwnd(), WM_COMMAND, wParam, lParam);
	
	return CListCtrl::OnCommand(wParam, lParam);
}
void CDownloadQueue::KademliaSearchFile(uint32_t searchID, const Kademlia::CUInt128* pcontactID, const Kademlia::CUInt128* pbuddyID, uint8_t type, uint32_t ip, uint16_t tcp, uint16_t udp, uint32_t buddyip, uint16_t buddyport, uint8_t byCryptOptions)
{
	AddDebugLogLineN(logKadSearch, CFormat(wxT("Search result sources (type %i)")) % type);

	//Safety measure to make sure we are looking for these sources
	CPartFile* temp = GetFileByKadFileSearchID(searchID);
	if( !temp ) {
		AddDebugLogLineN(logKadSearch, wxT("This is not the file we're looking for..."));
		return;
	}

	//Do we need more sources?
	if(!(!temp->IsStopped() && thePrefs::GetMaxSourcePerFile() > temp->GetSourceCount())) {
		AddDebugLogLineN(logKadSearch, wxT("No more sources needed for this file"));
		return;
	}

	uint32_t ED2KID = wxUINT32_SWAP_ALWAYS(ip);

	if (theApp->ipfilter->IsFiltered(ED2KID)) {
		AddDebugLogLineN(logKadSearch, wxT("Source ip got filtered"));
		AddDebugLogLineN(logIPFilter, CFormat(wxT("IPfiltered source IP=%s received from Kademlia")) % Uint32toStringIP(ED2KID));
		return;
	}

	if( (ip == Kademlia::CKademlia::GetIPAddress() || ED2KID == theApp->GetED2KID()) && tcp == thePrefs::GetPort()) {
		AddDebugLogLineN(logKadSearch, wxT("Trying to add myself as source, ignore"));
		return;
	}

	CUpDownClient* ctemp = NULL; 
	switch (type) {
		case 4:
		case 1: {
			// NonFirewalled users
			if(!tcp) {
				AddDebugLogLineN(logKadSearch, CFormat(wxT("Ignored source (IP=%s) received from Kademlia, no tcp port received")) % Uint32toStringIP(ip));
				return;
			}
			if (!IsGoodIP(ED2KID,thePrefs::FilterLanIPs())) {
				AddDebugLogLineN(logKadSearch, CFormat(wxT("%s got filtered")) % Uint32toStringIP(ED2KID));
				AddDebugLogLineN(logIPFilter, CFormat(wxT("Ignored source (IP=%s) received from Kademlia, filtered")) % Uint32toStringIP(ED2KID));
				return;
			}
			ctemp = new CUpDownClient(tcp, ip, 0, 0, temp, false, true);
			ctemp->SetSourceFrom(SF_KADEMLIA);
			// not actually sent or needed for HighID sources
			//ctemp->SetServerIP(serverip);
			//ctemp->SetServerPort(serverport);
			ctemp->SetKadPort(udp);
			byte cID[16];
			pcontactID->ToByteArray(cID);
			ctemp->SetUserHash(CMD4Hash(cID));
			break;
		}
		case 2: {
			// Don't use this type... Some clients will process it wrong..
			break;
		}
		case 5:
		case 3: {
			// This will be a firewalled client connected to Kad only.
			// We set the clientID to 1 as a Kad user only has 1 buddy.
			ctemp = new CUpDownClient(tcp, 1, 0, 0, temp, false, true);
			// The only reason we set the real IP is for when we get a callback
			// from this firewalled source, the compare method will match them.
			ctemp->SetSourceFrom(SF_KADEMLIA);
			ctemp->SetKadPort(udp);
			byte cID[16];
			pcontactID->ToByteArray(cID);
			ctemp->SetUserHash(CMD4Hash(cID));
			pbuddyID->ToByteArray(cID);
			ctemp->SetBuddyID(cID);
			ctemp->SetBuddyIP(buddyip);
			ctemp->SetBuddyPort(buddyport);
			break;
		}
		case 6: {
			// firewalled source which supports direct UDP callback
			// if we are firewalled ourself, the source is useless to us
			if (theApp->IsFirewalled()) {
				break;
			}

			if ((byCryptOptions & 0x08) == 0){
				AddDebugLogLineN(logKadSearch, CFormat(wxT("Received Kad source type 6 (direct callback) which has the direct callback flag not set (%s)")) % Uint32toStringIP(ED2KID));
				break;
			}

			ctemp = new CUpDownClient(tcp, 1, 0, 0, temp, false, true);
			ctemp->SetSourceFrom(SF_KADEMLIA);
			ctemp->SetKadPort(udp);
			ctemp->SetIP(ED2KID); // need to set the IP address, which cannot be used for TCP but for UDP
			byte cID[16];
			pcontactID->ToByteArray(cID);
			ctemp->SetUserHash(CMD4Hash(cID));
		}
	}

	if (ctemp) {
		// add encryption settings
		ctemp->SetConnectOptions(byCryptOptions);

		AddDebugLogLineN(logKadSearch, CFormat(wxT("Happily adding a source (%s) type %d")) % Uint32_16toStringIP_Port(ED2KID, ctemp->GetUserPort()) % type);
		CheckAndAddSource(temp, ctemp);
	}
}
Exemple #26
0
BOOL CUpdateInfo::ClearUpdateHistory(const uchar * hashkey)//清除历史升级任务
{
	for (int i = 0; i < CGlobalVariable::sharedfiles->GetCount(); i++)
	{
		CKnownFile* file = CGlobalVariable::sharedfiles->GetFileByIndex(i);
		CPartFile* pPartFile;

		try
		{
			//共享列表中是否有
			if(file)
			{
				if ( IsUpdateTask( file->GetFilePath() ) && file->GetFileHash() != hashkey )
				{
					if(file->IsPartFile())
					{
						//共享列表有,但未下载完,移除
						pPartFile = DYNAMIC_DOWNCAST(CPartFile,file);
						if( pPartFile )
						{
							pPartFile->DeleteFile();
						}
					}
					else
					{
						//共享列表有,已经下载完成未安装,移除
						DeleteFile(file->GetFilePath());
						theApp.emuledlg->sharedfileswnd->sharedfilesctrl.RemoveFile(file);
						CGlobalVariable::sharedfiles->RemoveFile(file);

						CGlobalVariable::filemgr.RemoveFileItem(file);
					}
				}
				else
					continue;
			}
		}
		catch (CException* e)
		{
			e->Delete();
			//return FALSE;
		}
	}

	for (int i = 0; i < CGlobalVariable::downloadqueue->GetFileCount(); i++)
	{
		CPartFile* pFile = CGlobalVariable::downloadqueue->GetFileByIndex(i);
		try
		{
			if (pFile)
			{
				if ( IsUpdateTask( pFile->GetFilePath() ) && pFile->GetFileHash() != hashkey )
				{
					//共享列表没有,但未下载完,移除
					pFile->DeleteFile();
				}
			}
		}
		catch (CException* e)
		{
			e->Delete();
			//return FALSE;
		}
	}

	return TRUE;
}
Exemple #27
0
ConvStatus CPartFileConvert::performConvertToeMule(const CPath& fileName)
{
    wxString filepartindex;

    CPath folder	= fileName.GetPath();
    CPath partfile	= fileName.GetFullName();
    CPath newfilename;

    CDirIterator finder(folder);

    Notify_ConvertUpdateProgressFull(0, _("Reading temp folder"), s_pfconverting->folder.GetPrintable());

    filepartindex = partfile.RemoveAllExt().GetRaw();

    Notify_ConvertUpdateProgress(4, _("Retrieving basic information from download info file"));

    CPartFile* file = new CPartFile();
    s_pfconverting->partmettype = file->LoadPartFile(folder, partfile, false, true);

    switch (s_pfconverting->partmettype) {
    case PMT_UNKNOWN:
    case PMT_BADFORMAT:
        delete file;
        return CONV_BADFORMAT;
    }

    CPath oldfile = folder.JoinPaths(partfile.RemoveExt());

    {
        wxMutexLocker lock(s_mutex);
        s_pfconverting->size = file->GetFileSize();
        s_pfconverting->filename = file->GetFileName();
        s_pfconverting->filehash = file->GetFileHash().Encode();
    }

    Notify_ConvertUpdateJobInfo(s_pfconverting);

    if (theApp->downloadqueue->GetFileByID(file->GetFileHash())) {
        delete file;
        return CONV_ALREADYEXISTS;
    }

    if (s_pfconverting->partmettype == PMT_SPLITTED) {
        unsigned fileindex;
        char *ba = new char [PARTSIZE];

        try {
            CFile inputfile;

            // just count
            unsigned maxindex = 0;
            unsigned partfilecount = 0;
            CPath filePath = finder.GetFirstFile(CDirIterator::File, filepartindex + wxT(".*.part"));
            while (filePath.IsOk()) {
                long l;
                ++partfilecount;
                filePath.GetFullName().RemoveExt().GetExt().ToLong(&l);
                fileindex = (unsigned)l;
                filePath = finder.GetNextFile();
                if (fileindex > maxindex) maxindex = fileindex;
            }
            float stepperpart;
            {
                wxMutexLocker lock(s_mutex);
                if (partfilecount > 0) {
                    stepperpart = (80.0f / partfilecount);
                    if (maxindex * PARTSIZE <= s_pfconverting->size) {
                        s_pfconverting->spaceneeded = maxindex * PARTSIZE;
                    } else {
                        s_pfconverting->spaceneeded = s_pfconverting->size;
                    }
                } else {
                    stepperpart = 80.0f;
                    s_pfconverting->spaceneeded = 0;
                }
            }

            Notify_ConvertUpdateJobInfo(s_pfconverting);

            sint64 freespace = CPath::GetFreeSpaceAt(thePrefs::GetTempDir());
            if (freespace != wxInvalidOffset) {
                if (static_cast<uint64>(freespace) < maxindex * PARTSIZE) {
                    delete file;
                    delete [] ba;
                    return CONV_OUTOFDISKSPACE;
                }
            }

            // create new partmetfile, and remember the new name
            file->CreatePartFile();
            newfilename = file->GetFullName();

            Notify_ConvertUpdateProgress(8, _("Creating destination file"));

            file->m_hpartfile.SetLength( s_pfconverting->spaceneeded );

            unsigned curindex = 0;
            CPath filename = finder.GetFirstFile(CDirIterator::File, filepartindex + wxT(".*.part"));
            while (filename.IsOk()) {
                // stats
                ++curindex;

                Notify_ConvertUpdateProgress(10 + (curindex * stepperpart), CFormat(_("Loading data from old download file (%u of %u)")) % curindex % partfilecount);

                long l;
                filename.GetFullName().RemoveExt().GetExt().ToLong(&l);
                fileindex = (unsigned)l;
                if (fileindex == 0) {
                    filename = finder.GetNextFile();
                    continue;
                }

                uint32 chunkstart = (fileindex - 1) * PARTSIZE;

                // open, read data of the part-part-file into buffer, close file
                inputfile.Open(filename, CFile::read);
                uint64 toReadWrite = std::min<uint64>(PARTSIZE, inputfile.GetLength());
                inputfile.Read(ba, toReadWrite);
                inputfile.Close();

                Notify_ConvertUpdateProgress(10 + (curindex * stepperpart), CFormat(_("Saving data block into new single download file (%u of %u)")) % curindex % partfilecount);

                // write the buffered data
                file->m_hpartfile.WriteAt(ba, chunkstart, toReadWrite);

                filename = finder.GetNextFile();
            }
            delete[] ba;
        } catch (const CSafeIOException& e) {
            AddDebugLogLineC(logPfConvert, wxT("IO error while converting partfiles: ") + e.what());

            delete[] ba;
            file->Delete();
            return CONV_IOERROR;
        }

        file->m_hpartfile.Close();
    }
    // import an external common format partdownload
    else //if (pfconverting->partmettype==PMT_DEFAULTOLD || pfconverting->partmettype==PMT_NEWOLD || Shareaza  )
    {
        if (!s_pfconverting->removeSource) {
            wxMutexLocker lock(s_mutex);
            s_pfconverting->spaceneeded = oldfile.GetFileSize();
        }

        Notify_ConvertUpdateJobInfo(s_pfconverting);

        sint64 freespace = CPath::GetFreeSpaceAt(thePrefs::GetTempDir());
        if (freespace == wxInvalidOffset) {
            delete file;
            return CONV_IOERROR;
        } else if (freespace < s_pfconverting->spaceneeded) {
            delete file;
            return CONV_OUTOFDISKSPACE;
        }

        file->CreatePartFile();
        newfilename = file->GetFullName();

        file->m_hpartfile.Close();

        bool ret = false;

        Notify_ConvertUpdateProgress(92, _("Copy"));

        CPath::RemoveFile(newfilename.RemoveExt());
        if (!oldfile.FileExists()) {
            // data file does not exist. well, then create a 0 byte big one
            CFile datafile;
            ret = datafile.Create(newfilename.RemoveExt());
        } else if (s_pfconverting->removeSource) {
            ret = CPath::RenameFile(oldfile, newfilename.RemoveExt());
        } else {
            ret = CPath::CloneFile(oldfile, newfilename.RemoveExt(), false);
        }
        if (!ret) {
            file->Delete();
            //delete file;
            return CONV_FAILED;
        }

    }

    Notify_ConvertUpdateProgress(94, _("Retrieving source downloadfile information"));

    CPath::RemoveFile(newfilename);
    if (s_pfconverting->removeSource) {
        CPath::RenameFile(folder.JoinPaths(partfile), newfilename);
    } else {
        CPath::CloneFile(folder.JoinPaths(partfile), newfilename, false);
    }

    file->m_hashlist.clear();

    if (!file->LoadPartFile(thePrefs::GetTempDir(), file->GetPartMetFileName(), false)) {
        //delete file;
        file->Delete();
        return CONV_BADFORMAT;
    }

    if (s_pfconverting->partmettype == PMT_NEWOLD || s_pfconverting->partmettype == PMT_SPLITTED) {
        file->SetCompletedSize(file->transferred);
        file->m_iGainDueToCompression = 0;
        file->m_iLostDueToCorruption = 0;
    }

    Notify_ConvertUpdateProgress(100, _("Adding download and saving new partfile"));

    theApp->downloadqueue->AddDownload(file, thePrefs::AddNewFilesPaused(), 0);
    file->SavePartFile();

    if (file->GetStatus(true) == PS_READY) {
        theApp->sharedfiles->SafeAddKFile(file); // part files are always shared files
    }

    if (s_pfconverting->removeSource) {
        CPath oldFile = finder.GetFirstFile(CDirIterator::File, filepartindex + wxT(".*"));
        while (oldFile.IsOk()) {
            CPath::RemoveFile(folder.JoinPaths(oldFile));
            oldFile = finder.GetNextFile();
        }

        if (s_pfconverting->partmettype == PMT_SPLITTED) {
            CPath::RemoveDir(folder);
        }
    }

    return CONV_OK;
}
void CDownloadQueue::LoadMetFiles(const CPath& path)
{
	AddLogLineNS(CFormat(_("Loading temp files from %s.")) % path.GetPrintable());
	
	std::vector<CPath> files;

	// Locate part-files to be loaded
	CDirIterator TempDir(path);
	CPath fileName = TempDir.GetFirstFile(CDirIterator::File, wxT("*.part.met"));
	while (fileName.IsOk()) {
		files.push_back(path.JoinPaths(fileName));

		fileName = TempDir.GetNextFile();
	}

	// Loading in order makes it easier to figure which
	// file is broken in case of crashes, or the like.
	std::sort(files.begin(), files.end());

	// Load part-files	
	for ( size_t i = 0; i < files.size(); i++ ) {
		AddLogLineNS(CFormat(_("Loading PartFile %u of %u")) % (i + 1) % files.size());
		fileName = files[i].GetFullName();
		CPartFile *toadd = new CPartFile();
		bool result = toadd->LoadPartFile(path, fileName) != 0;
		if (!result) {
			// Try from backup
			result = toadd->LoadPartFile(path, fileName, true) != 0;
		}
		if (result && !IsFileExisting(toadd->GetFileHash())) {
			{
				wxMutexLocker lock(m_mutex);
				m_filelist.push_back(toadd);
			}
			NotifyObservers(EventType(EventType::INSERTED, toadd));
			Notify_DownloadCtrlAddFile(toadd);
		} else {
			wxString msg;
			if (result) {
				msg << CFormat(wxT("WARNING: Duplicate partfile with hash '%s' found, skipping: %s"))
					% toadd->GetFileHash().Encode() % fileName;
			} else {
				// If result is false, then reading of both the primary and the backup .met failed
				AddLogLineN(_("ERROR: Failed to load backup file. Search http://forum.amule.org for .part.met recovery solutions."));
				msg << CFormat(wxT("ERROR: Failed to load PartFile '%s'")) % fileName;
			}
			AddLogLineCS(msg);

			// Delete the partfile object in the end.
			delete toadd;
		}
	}
	AddLogLineNS(_("All PartFiles Loaded."));
	
	if ( GetFileCount() == 0 ) {
		AddLogLineN(_("No part files found"));
	} else {
		AddLogLineN(CFormat(wxPLURAL("Found %u part file", "Found %u part files", GetFileCount())) % GetFileCount());

		DoSortByPriority();
		CheckDiskspace( path );
		Notify_ShowUpdateCatTabTitles();
	}
}