Example #1
0
int CPartFileConvert::ScanFolderToAdd(const CPath& folder, bool deletesource)
{
    int count = 0;
    CDirIterator finder(folder);

    CPath file = finder.GetFirstFile(CDirIterator::File, wxT("*.part.met"));
    while (file.IsOk()) {
        ConvertToeMule(folder.JoinPaths(file), deletesource);
        file = finder.GetNextFile();
        count++;
    }
    /* Shareaza
    file = finder.GetFirstFile(CDirIterator::File, wxT("*.sd"));
    while (!file.IsEmpty()) {
    	ConvertToeMule(file, deletesource);
    	file = finder.GetNextFile();
    	count++;
    }
    */

    file = finder.GetFirstFile(CDirIterator::Dir, wxT("*.*"));
    while (file.IsOk()) {
        ScanFolderToAdd(folder.JoinPaths(file), deletesource);

        file = finder.GetNextFile();
    }

    return count;
}
Example #2
0
TEST(CPath, CopyConstructor)
{
	const wxChar* tmpPath = wxT("foobar.tgz");

	{
		CPath a(tmpPath);

		ASSERT_TRUE(a.IsOk());
		ASSERT_EQUALS(a.GetRaw(), tmpPath);
		ASSERT_EQUALS(a.GetPrintable(), tmpPath);
		ASSERT_EQUALS(a.GetPath(), CPath());
		ASSERT_EQUALS(a.GetFullName(), CPath(tmpPath));

		CPath b(a);
		ASSERT_TRUE(b.IsOk());
		ASSERT_EQUALS(b.GetRaw(), tmpPath);
		ASSERT_EQUALS(b.GetPrintable(), tmpPath);
		ASSERT_EQUALS(b.GetPath(), CPath());
		ASSERT_EQUALS(b.GetFullName(), CPath(tmpPath));

		ASSERT_EQUALS(a, b);
	}

	{
		CPath a(tmpPath);

		ASSERT_TRUE(a.IsOk());
		ASSERT_EQUALS(a.GetRaw(), tmpPath);
		ASSERT_EQUALS(a.GetPrintable(), tmpPath);
		ASSERT_EQUALS(a.GetPath(), CPath());
		ASSERT_EQUALS(a.GetFullName(), CPath(tmpPath));

		CPath b(a);
		ASSERT_TRUE(b.IsOk());
		ASSERT_EQUALS(b.GetRaw(), tmpPath);
		ASSERT_EQUALS(b.GetPrintable(), tmpPath);
		ASSERT_EQUALS(b.GetPath(), CPath());
		ASSERT_EQUALS(b.GetFullName(), CPath(tmpPath));

		ASSERT_EQUALS(a, b);
	}

	{
		CPath a;
		CPath b(a);
		
		ASSERT_EQUALS(a, b);
		ASSERT_FALSE(a.IsOk());
		ASSERT_FALSE(b.IsOk());
	}
}
Example #3
0
CPath CPath::JoinPaths(const CPath& other) const
{
	if (!IsOk()) {
		return CPath(other);
	} else if (!other.IsOk()) {
		return CPath(*this);
	} 

	CPath joinedPath;
	// DeepCopy shouldn't be needed, as JoinPaths results in the creation of a new string.
	joinedPath.m_printable = ::JoinPaths(m_printable, other.m_printable);
	joinedPath.m_filesystem = ::JoinPaths(m_filesystem, other.m_filesystem);

	return joinedPath;
}
Example #4
0
void CFileDetailDialog::OnBnClickedApply(wxCommandEvent& WXUNUSED(evt))
{
	CPath fileName = CPath(CastChild(IDC_FILENAME, wxTextCtrl)->GetValue());

	if (fileName.IsOk() && (fileName != m_file->GetFileName())) {
		if (theApp->sharedfiles->RenameFile(m_file, fileName)) {
			FindWindow(IDC_FNAME)->SetLabel(MakeStringEscaped(m_file->GetFileName().GetPrintable()));
			FindWindow(IDC_METFILE)->SetLabel(m_file->GetFullName().GetPrintable());
			
			resetValueForFilenameTextEdit();
	
			Layout();
		}
	}
}
Example #5
0
TEST(CPath, DefaultConstructor)
{
	CPath tmp;

	ASSERT_FALSE(tmp.IsOk());
	ASSERT_EQUALS(tmp, CPath());

	ASSERT_FALSE(tmp.FileExists());
	ASSERT_FALSE(tmp.DirExists());

	ASSERT_EQUALS(wxEmptyString, tmp.GetRaw());
	ASSERT_EQUALS(wxEmptyString, tmp.GetPrintable());
	ASSERT_EQUALS(CPath(), tmp.GetPath());
	ASSERT_EQUALS(CPath(), tmp.GetFullName());
}
Example #6
0
void CSharedFilesCtrl::OnRename( wxCommandEvent& WXUNUSED(event) )
{
	int item = GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
	if ( item != -1 ) {
		CKnownFile* file = (CKnownFile*)GetItemData(item);

		wxString strNewName = ::wxGetTextFromUser(
			_("Enter new name for this file:"),
			_("File rename"), file->GetFileName().GetPrintable());

		CPath newName = CPath(strNewName);
		if (newName.IsOk() && (newName != file->GetFileName())) {
			theApp->sharedfiles->RenameFile(file, newName);
		}
	}
}
Example #7
0
bool CPath::StartsWith(const CPath& other) const
{
	// It doesn't make sense comparing invalid paths,
	// especially since if 'other' was empty, it would
	// be considered a prefix of any path.
	if ((IsOk() && other.IsOk()) == false) {
		return false;
	}

	// Adding an seperator to avoid partial matches, such as
	// "/usr/bi" matching "/usr/bin". TODO: Paths should be
	// normalized first (in the constructor).
	const wxString a = StripSeparators(m_filesystem, wxString::trailing) + wxFileName::GetPathSeparator();
	const wxString b = StripSeparators(other.m_filesystem, wxString::trailing) + wxFileName::GetPathSeparator();
	
	if (a.Length() < b.Length()) {
		// Cannot possibly be a prefix.
		return false;
	}

	const size_t checkLen = std::min(a.Length(), b.Length());
	return PATHNCMP(a.c_str(), b.c_str(), checkLen) == 0;
}
Example #8
0
bool CFile::Open(const CPath& fileName, OpenMode mode, int accessMode)
{
	MULE_VALIDATE_PARAMS(fileName.IsOk(), wxT("CFile: Cannot open, empty path."));

	if (IsOpened()) {
		Close();
	}

	m_safeWrite = false;
	m_filePath = fileName;

#ifdef __linux__
	int flags = O_BINARY | O_LARGEFILE;
#else
	int flags = O_BINARY;
#endif
	switch ( mode ) {
		case read:
			flags |= O_RDONLY;
			break;

		case write_append:
			if (fileName.FileExists())
			{
				flags |= O_WRONLY | O_APPEND;
				break;
			}
			//else: fall through as write_append is the same as write if the
			//      file doesn't exist

		case write:
			flags |= O_WRONLY | O_CREAT | O_TRUNC;
			break;

		case write_safe:
			flags |= O_WRONLY | O_CREAT | O_TRUNC;
			m_filePath = m_filePath.AppendExt(wxT(".new"));
			m_safeWrite = true;
			break;

		case write_excl:
			flags |= O_WRONLY | O_CREAT | O_EXCL;
			break;

		case read_write:
			flags |= O_RDWR;
		break;
	}

	// Windows needs wide character file names
#ifdef __WINDOWS__
	m_fd = _wopen(m_filePath.GetRaw().c_str(), flags, accessMode);
#else
	Unicode2CharBuf tmpFileName = filename2char(m_filePath.GetRaw());
	wxASSERT_MSG(tmpFileName, wxT("Convertion failed in CFile::Open"));
	m_fd = open(tmpFileName, flags, accessMode);
#endif
	syscall_check(m_fd != fd_invalid, m_filePath, wxT("opening file"));

	return IsOpened();
}
Example #9
0
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();
	}
}
Example #10
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;
}
Example #11
0
bool CKnownFile::LoadTagsFromFile(const CFileDataIO* file)
{
	uint32 tagcount = file->ReadUInt32();
	for (uint32 j = 0; j != tagcount; ++j) {
		CTag newtag(*file, true);
		switch(newtag.GetNameID()){
			case FT_FILENAME:
				if (GetFileName().IsOk()) {
					// Unlike eMule, we actually prefer the second
					// filename tag, since we use it to specify the
					// 'universial' filename (see CPath::ToUniv).
					CPath path = CPath::FromUniv(newtag.GetStr());

					// May be invalid, if from older versions where
					// unicoded filenames be saved as empty-strings.
					if (path.IsOk()) {
						SetFileName(path);
					}
				} else {
					SetFileName(CPath(newtag.GetStr()));
				}
				break;
			
			case FT_FILESIZE:
				SetFileSize(newtag.GetInt());
				m_AvailPartFrequency.clear();
				m_AvailPartFrequency.insert(
					m_AvailPartFrequency.begin(),
					GetPartCount(), 0);
				break;
			
			case FT_ATTRANSFERRED:
				statistic.alltimetransferred += newtag.GetInt();
				break;
			
			case FT_ATTRANSFERREDHI:
				statistic.alltimetransferred =
					(((uint64)newtag.GetInt()) << 32) +
					((uint64)statistic.alltimetransferred);
				break;
			
			case FT_ATREQUESTED:
				statistic.alltimerequested = newtag.GetInt();
				break;
			
			case FT_ATACCEPTED:
				statistic.alltimeaccepted = newtag.GetInt();
				break;
			
			case FT_ULPRIORITY:
				m_iUpPriority = newtag.GetInt();
				if( m_iUpPriority == PR_AUTO ){
					m_iUpPriority = PR_HIGH;
					m_bAutoUpPriority = true;
				} else {
					if (	m_iUpPriority != PR_VERYLOW &&
						m_iUpPriority != PR_LOW &&
						m_iUpPriority != PR_NORMAL &&
						m_iUpPriority != PR_HIGH &&
						m_iUpPriority != PR_VERYHIGH &&
						m_iUpPriority != PR_POWERSHARE) {
						m_iUpPriority = PR_NORMAL;
					}
					
					m_bAutoUpPriority = false;
				}
				break;
			
			case FT_PERMISSIONS:
				// Ignore it, it's not used anymore.
				break;
			
			case FT_AICH_HASH: {
				CAICHHash hash;
				bool hashSizeOk =
					hash.DecodeBase32(newtag.GetStr()) == CAICHHash::GetHashSize();
				wxASSERT(hashSizeOk);
				if (hashSizeOk) {
					m_pAICHHashSet->SetMasterHash(hash, AICH_HASHSETCOMPLETE);
				}
				break;
			}
			
			case FT_KADLASTPUBLISHSRC:
				SetLastPublishTimeKadSrc( newtag.GetInt(), 0 );
				
				if(GetLastPublishTimeKadSrc() > (uint32)time(NULL)+KADEMLIAREPUBLISHTIMES) {
					//There may be a posibility of an older client that saved a random number here.. This will check for that..
					SetLastPublishTimeKadSrc(0, 0);
				}
				break;
			
			case FT_KADLASTPUBLISHNOTES:
				SetLastPublishTimeKadNotes( newtag.GetInt() );
				break;
			
			case FT_KADLASTPUBLISHKEY:
				// Just purge it
				wxASSERT( newtag.IsInt() );
				break;
				
			default:
				// Store them here and write them back on saving.
				m_taglist.push_back(newtag);
		}	
	}
	
	return true;
}