Exemplo n.º 1
0
void CFriendList::LoadList()
{
  	CPath metfile = CPath(theApp->ConfigDir + wxT("emfriends.met"));
	
	if (!metfile.FileExists()) {
		return;
	}
	
	CFile file;
	try {
		if ( file.Open(metfile) ) {
			if ( file.ReadUInt8() /*header*/ == MET_HEADER ) {
				uint32 nRecordsNumber = file.ReadUInt32();
				for (uint32 i = 0; i < nRecordsNumber; i++) {
					CFriend* Record = new CFriend();
					Record->LoadFromFile(&file);
					m_FriendList.push_back(Record);
					Notify_ChatUpdateFriend(Record);
				}				
			}
		} else {
			AddLogLineN(_("Failed to open friend list file 'emfriends.met' for reading!"));
		}
	} catch (const CInvalidPacket& e) {
		AddDebugLogLineC(logGeneral, wxT("Invalid entry in friend list, file may be corrupt: ") + e.what());
	} catch (const CSafeIOException& e) {
		AddDebugLogLineC(logGeneral, wxT("IO error while reading 'emfriends.met': ") + e.what());
	}
	
}
Exemplo n.º 2
0
    bool BackupTaskState(void) throw()
    {
        CPath path;
        bool bRet = false;

        if (GetIniFile(path))
        {
            CString temp;
            bRet = true;

            // get storage name
            if (GetConfigString(temp, path, _T("storage"), STORAGE_NAME))
            {
                path.RemoveFileSpec();
                path.Append(temp);

                if (path.FileExists())
                {
                    temp = (LPCTSTR)path; // store existing
                    path.RenameExtension(_T(".bak"));
                    bRet = (::MoveFileEx(temp, path, MOVEFILE_REPLACE_EXISTING) != 0);
                } 
            }
        }
        return bRet;
    }
Exemplo n.º 3
0
bool CDownloadQueue::IsFileExisting( const CMD4Hash& fileid ) const 
{
	if (CKnownFile* file = theApp->sharedfiles->GetFileByID(fileid)) {
		if (file->IsPartFile()) {
			AddLogLineC(CFormat( _("You are already trying to download the file '%s'") ) % file->GetFileName());
		} else {
			// Check if the file exists, since otherwise the user is forced to 
			// manually reload the shares to download a file again.
			CPath fullpath = file->GetFilePath().JoinPaths(file->GetFileName());
			if (!fullpath.FileExists()) {
				// The file is no longer available, unshare it
				theApp->sharedfiles->RemoveFile(file);
				
				return false;
			}
			
			AddLogLineC(CFormat( _("You already have the file '%s'") ) % file->GetFileName());
		}
		
		return true;
	} else if ((file = GetFileByID(fileid))) {
		AddLogLineC(CFormat( _("You are already trying to download the file %s") ) % file->GetFileName());
		return true;
	}
	
	return false;
}
Exemplo n.º 4
0
bool CFile::Create(const CPath& path, bool overwrite, int accessMode)
{
	if (!overwrite && path.FileExists()) {
		return false;
	}

	return Open(path, write, accessMode);
}
Exemplo n.º 5
0
	virtual void setUp()
	{
		const CPath path = CPath(wxT("testfile.txt"));
		if (path.FileExists()) {
			ASSERT_TRUE(CPath::RemoveFile(path));
		}

	}
Exemplo n.º 6
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());
}
Exemplo n.º 7
0
bool CKnownFileList::Init()
{
	CFile file;

	CPath fullpath = CPath(theApp->ConfigDir + m_filename);
	if (!fullpath.FileExists()) {
		// This is perfectly normal. The file was probably either
		// deleted, or this is the first time running aMule.
		return false;
	}

	if (!file.Open(fullpath)) {
		AddLogLineC(CFormat(_("WARNING: %s cannot be opened.")) % m_filename);
		return false;
	}

	try {
		uint8 version = file.ReadUInt8();
		if ((version != MET_HEADER) && (version != MET_HEADER_WITH_LARGEFILES)) {
			AddLogLineC(_("WARNING: Known file list corrupted, contains invalid header."));
			return false;
		}

		wxMutexLocker sLock(list_mut);
		uint32 RecordsNumber = file.ReadUInt32();
		AddDebugLogLineN(logKnownFiles, CFormat(wxT("Reading %i known files from file format 0x%2.2x."))
			% RecordsNumber % version);
		for (uint32 i = 0; i < RecordsNumber; i++) {
			CScopedPtr<CKnownFile> record;
			if (record->LoadFromFile(&file)) {
				AddDebugLogLineN(logKnownFiles,
					CFormat(wxT("Known file read: %s")) % record->GetFileName());
				Append(record.release());
			} else {
				AddLogLineC(_("Failed to load entry in known file list, file may be corrupt"));
			}
		}
		AddDebugLogLineN(logKnownFiles, wxT("Finished reading known files"));

		return true;
	} catch (const CInvalidPacket& e) {
		AddLogLineC(_("Invalid entry in known file list, file may be corrupt: ") + e.what());
	} catch (const CSafeIOException& e) {
		AddLogLineC(CFormat(_("IO error while reading %s file: %s")) % m_filename % e.what());
	}

	return false;
}
Exemplo n.º 8
0
void CPartFileConvert::ConvertToeMule(const CPath& file, bool deletesource)
{
    if (!file.FileExists()) {
        return;
    }

    ConvertJob* newjob = new ConvertJob(file, deletesource, CONV_QUEUE);

    wxMutexLocker lock(s_mutex);

    s_jobs.push_back(newjob);

    Notify_ConvertUpdateJobInfo(newjob);

    StartThread();
}
Exemplo n.º 9
0
bool CCanceledFileList::Init()
{
	CFile file;
	
	CPath fullpath = CPath(theApp->ConfigDir + m_filename);
	if (!fullpath.FileExists()) {
		// This is perfectly normal. The file was probably either
		// deleted, or this is the first time running aMule.
		return false;
	}

	if (!file.Open(fullpath)) {
		AddLogLineM(true, CFormat(_("WARNING: %s cannot be opened.")) % m_filename);
		return false;
	}
	
	try {
		uint8 version = file.ReadUInt8();
		if (version != CANCELEDFILE_VERSION) {
			AddLogLineM(true, _("WARNING: Canceled file list corrupted, contains invalid header."));
			return false;
		}
		
		uint32 RecordsNumber = file.ReadUInt32();
		AddDebugLogLineM(false, logKnownFiles,
			CFormat(wxT("Reading %i canceled files from file format 0x%02x."))
			% RecordsNumber % version);
		for (uint32 i = 0; i < RecordsNumber; i++) {
			CMD4Hash hash;
			file.Read(hash.GetHash(), 16);
			AddDebugLogLineM(false, logKnownFiles, CFormat(wxT("Canceled file read: %s")) % hash.Encode());
			if (!hash.IsEmpty()) {
				m_canceledFileList.insert(hash);
			}
		}
		AddDebugLogLineM(false, logKnownFiles, wxT("Finished reading canceled files"));
	
		return true;
	} catch (const CSafeIOException& e) {
		AddLogLineM(true, CFormat(_("IO error while reading %s file: %s")) % m_filename % e.what());
	}	
	
	return false;
}
Exemplo n.º 10
0
bool CTextFile::Open(const CPath& path, EOpenMode mode)
{
	// wxFFile doesn't call close itself, but asserts instead.
	Close();

	m_mode = mode;
	
	if (mode == read) {
		if (path.FileExists()) {
			m_file.Open(path.GetRaw(), wxT("r"));
		}
	} else if (mode == write) {
		m_file.Open(path.GetRaw(), wxT("w"));
	} else {
		wxFAIL;
	}

	return IsOpened();
}
Exemplo n.º 11
0
void CPrefs::ReadFile()
{
	const CPath path = CPath(m_filename);

	try {
		CFile file;
		if (path.FileExists() && file.Open(path, CFile::read)) {
			m_ip = file.ReadUInt32();
			file.ReadUInt16();
			m_clientID = file.ReadUInt128();
			// get rid of invalid kad IDs which may have been stored by older versions
			if (m_clientID == 0)
				m_clientID = GetRandomUint128();
			file.Close();
		}
	} catch (const CSafeIOException& e) {
		AddDebugLogLineC(logKadPrefs, wxT("IO error while reading prefs: ") + e.what());
	}
}
Exemplo n.º 12
0
void CPlayerPlaylistBar::LoadPlaylist(LPCTSTR filename)
{
    CString base;

    if (AfxGetMyApp()->GetAppSavePath(base)) {
        CPath p;
        p.Combine(base, _T("default.mpcpl"));

        if (p.FileExists()) {
            if (AfxGetAppSettings().bRememberPlaylistItems) {
                ParseMPCPlayList(p);
                Refresh();
                SelectFileInPlaylist(filename);
            } else {
                ::DeleteFile(p);
            }
        }
    }
}
Exemplo n.º 13
0
bool CWebServer::ToLocalPath(CString& path, CString& redir)
{
	if(!path.IsEmpty() && m_webroot.IsDirectory())
	{
		CString str = path;
		str.Replace('/', '\\');
		str.TrimLeft('\\');

		CPath p;
		p.Combine(m_webroot, str);
		p.Canonicalize();

		if(p.IsDirectory())
		{
			CAtlList<CString> sl;
			Explode(AfxGetAppSettings().WebDefIndex, sl, ';');
			POSITION pos = sl.GetHeadPosition();
			while(pos)
			{
				str = sl.GetNext(pos);
				CPath p2 = p;
				p2.Append(str);
				if(p2.FileExists())
				{
					p = p2;
					redir = path;
					if(redir.GetAt(redir.GetLength()-1) != '/') redir += '/';
					redir += str;
					break;
				}
			}
		}

		if(_tcslen(p) > _tcslen(m_webroot) && p.FileExists())
		{
			path = (LPCTSTR)p;
			return true;
		}
	}

	return false;
}
Exemplo n.º 14
0
void CPlayerPlaylistBar::SavePlaylist()
{
    CString base;

    if (AfxGetMyApp()->GetAppSavePath(base)) {
        CPath p;
        p.Combine(base, _T("default.mpcpl"));

        if (AfxGetAppSettings().bRememberPlaylistItems) {
            // Only create this folder when needed
            if (!::PathFileExists(base)) {
                ::CreateDirectory(base, NULL);
            }

            SaveMPCPlayList(p, CTextFile::UTF8, false);
        } else if (p.FileExists()) {
            ::DeleteFile(p);
        }
    }
}
Exemplo n.º 15
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();
}
Exemplo n.º 16
0
/**
 *  \brief
 */
bool Settings::Load()
{
    SetDefaults();

    CPath cfgFile;
    INpp::Get().GetPluginsConfDir(cfgFile);
    cfgFile += cPluginCfgFileName;

    if (!cfgFile.FileExists())
        return false;

    FILE* fp;
    _tfopen_s(&fp, cfgFile.C_str(), _T("rt"));
    if (fp == NULL)
        return false;

    bool success = true;

    TCHAR line[8192];
    while (_fgetts(line, _countof(line), fp))
    {
        // Comment or empty line
        if (line[0] == _T('#') || line[0] == _T('\n'))
            continue;

        // Strip newline from the end of the line
        line[_tcslen(line) - 1] = 0;

        if (!_tcsncmp(line, cUseDefDbKey, _countof(cUseDefDbKey) - 1))
        {
            const unsigned pos = _countof(cUseDefDbKey) - 1;
            if (!_tcsncmp(&line[pos], _T("yes"), _countof(_T("yes")) - 1))
                _useDefDb = true;
            else
                _useDefDb = false;
        }
        else if (!_tcsncmp(line, cDefDbPathKey, _countof(cDefDbPathKey) - 1))
        {
            const unsigned pos = _countof(cDefDbPathKey) - 1;
            _defDbPath = &line[pos];
            _defDbPath.AsFolder();
            if (!_defDbPath.Exists())
                _defDbPath.Clear();
        }
        else if (!_tcsncmp(line, cREOptionKey, _countof(cREOptionKey) - 1))
        {
            const unsigned pos = _countof(cREOptionKey) - 1;
            if (!_tcsncmp(&line[pos], _T("yes"), _countof(_T("yes")) - 1))
                _re = true;
            else
                _re = false;
        }
        else if (!_tcsncmp(line, cICOptionKey, _countof(cICOptionKey) - 1))
        {
            const unsigned pos = _countof(cICOptionKey) - 1;
            if (!_tcsncmp(&line[pos], _T("yes"), _countof(_T("yes")) - 1))
                _ic = true;
            else
                _ic = false;
        }
        else if (!_genericDbCfg.ReadOption(line))
        {
            success = false;
            SetDefaults();
            break;
        }
    }

    fclose(fp);

    return success;
}
Exemplo n.º 17
0
int RunConverter( int argc, _TCHAR* * argv )
{
#ifdef _DEBUG
	// sleep a bit so we can have time to attach a debugger
	Tell(_T("Sleeping for %d seconds in debug mode."), startupTimeout / 1000);
	Sleep(startupTimeout);
#endif
	int ret = 0;
	wstring name;
	wstring title;
	HANDLE conversionHandle = NULL;

	po::options_description desc("Converts an MPEG-2 Program Stream to a DVR-MS, WMV, or WTV file.");
	po::positional_options_description pos;

	string input;
	string output;
	LONGLONG length;
	bool disableFileLogging;
	bool disableConsoleLogging;
	bool disableAllLogging;
	string interruptName;
	string interruptDirectory;
	string outputDirectory;
	string contentTitle;
	__int64 contentDuration = -1i64;

	desc.add_options()
		("help,?", "Display help message.")
		("input,i", po::value<string>(&input), "an MPEG2 input path. Can be a url.")
		("output,o", po::value<string>(&output), "output path.<type>. Where <type> can be one of \"dvr-ms\", \"wmv\", or \"wtv\"")
		("length,l", po::value<LONGLONG>(&length)->default_value(-1), "the length of the input content in bytes. Only required for a network path such as http." )
		("interrupt-name", po::value<string>(&interruptName), "the file name (without path or extension) of a file that will be created when conversion is to be interrupted.")
		("interrupt-directory", po::value<string>(&interruptDirectory), "the path for this app to look for an interrupt file. An interrupt file is the interrupt_file name with a .interrupt extension. The file itself can be empty.")
		("disable-file-logging", po::value<bool>(&disableFileLogging)->zero_tokens()->default_value(false), "indicates that logging to a file will be disabled.")
		("disable-console-logging", po::value<bool>(&disableConsoleLogging)->zero_tokens()->default_value(false), "indicates that logging to the console will be disabled.")
		("disable-all-logging", po::value<bool>(&disableAllLogging)->zero_tokens()->default_value(false), "indicates that all logging will be disabled.")
		("output-directory,d", po::value<string>(&outputDirectory), "the directory for this app to place conversion output. Only valid if output_path is omitted.")
		("content-title,t", po::value<string>(&contentTitle), "the Title that will be assigned to the output path.<type>.")
		("version,v", po::value<string>()->zero_tokens(), "prints the version of this app.")
		//("content-duration,d", po::value<__int64>(&contentDuration)->default_value(-1i64), "the duration of the input content in seconds." )
		;

	pos.add("input", 1);
	pos.add("output", 1);
	pos.add("length", 1);

	vector<string> args;

	for (int i = 1; i < argc; i++)
		args.push_back(WStringToString(argv[i]));

	po::variables_map variables;

	try
	{
		po::basic_parsed_options<char> oo = po::command_line_parser(args).
			options(desc).positional(pos).run();
		po::store(oo, variables);
		po::notify(variables);
	}
	catch (std::exception e)
	{
		Tell(_T("Invalid command line. Use --help to see options."));
		return -1;
	}

	if (!variables.count("input"))
	{
		bool display = false;
		wstring message;
		if (variables.count("version"))
		{
			message = _T("Version: ");
			message += MPEG2DVRMS_VERSION;
			display = true;
		}
		if (variables.count("help"))
		{
			message = _T("eh... help message not available yet. Hope you have the source!");
			display = true;
		}
		if (!display)
			message = _T("No input file was specified.");
		ret = 100;
		Tell(message);
	}
	else
	{
		try
		{
			//////////////////////////////////////////////////////////////////////////
			// command-line option handling

			LONGLONG contentLength = -1;

			if (variables.count("length"))
				contentLength = length;

			if (variables.count("interrupt-name"))
				name = StringToWString(interruptName);
			else
			{
				name = NewGuid();
				Tell(_T("Generated interrupt name is %s"), name.c_str());
			}

			if (variables.count("interrupt-directory"))
				_conversionFileStoragePath = StringToWString(interruptDirectory);

			if (variables.count("content-title"))
				title = StringToWString(contentTitle);
			else
				title = _T("");

#pragma region input output file handling
			wstring defaultExtension;

			if (IsVista())
				defaultExtension = _T(".dvr-ms");
			else
				defaultExtension = _T(".wtv");

			ATL_URL_SCHEME urlScheme;
			CUrl inputUrl;

			if (!inputUrl.CrackUrl(StringToWString(input).c_str()))
				urlScheme = ATL_URL_SCHEME_FILE;
			else
				urlScheme = inputUrl.GetScheme();

			if (urlScheme == -1)
				urlScheme = ATL_URL_SCHEME_FILE;

			wstring inputPath = StringToWString(input);
			CPath outputPath;

			if (urlScheme == ATL_URL_SCHEME_FILE)
			{
				CPath input = inputPath.c_str();

				if (input.IsFileSpec())
				{
					TCHAR szCurrentDirectory[MAX_PATH];
					if (!GetCurrentDirectory(MAX_PATH, szCurrentDirectory))
						throw CarverLab::Exception(GetLastError());
					wstring currentDirectory = (LPCTSTR)szCurrentDirectory;
					inputPath = currentDirectory + _T("\\") + inputPath.c_str();
					input = inputPath.c_str();
				}
				if (!input.FileExists())
					throw CarverLab::Exception(_T("MPEG2 input path does not exist."));

				if (!variables.count("output"))
					outputPath = inputPath.c_str();
				else
					outputPath = StringToWString(output).c_str();
			}
			else if (urlScheme == ATL_URL_SCHEME_HTTP ||
				urlScheme == ATL_URL_SCHEME_HTTPS)
			{
				if (!variables.count("output"))
				{
					wstring thefullpath;
					CString envString;
					envString.GetEnvironmentVariable(_T("PUBLIC"));
					thefullpath = envString;
					thefullpath += _T("\\Videos\\mpeg2dvrms-output");
					thefullpath += defaultExtension;
					outputPath = thefullpath.c_str();
				}
				else
					outputPath = StringToWString(output).c_str();
			}
			else
				throw CarverLab::Exception(_T("Only http or https URL schemes are supported."));

			bool isUrl = urlScheme != ATL_URL_SCHEME_FILE;

			CPath inPath = inputPath.c_str();

			if (outputPath.GetExtension().MakeLower() == inPath.GetExtension().MakeLower())
				outputPath.RenameExtension(defaultExtension.c_str());

			if (outputPath.GetExtension().MakeLower() == _T(".dvrms"))
			{
				outputPath.RemoveExtension();
				outputPath.AddExtension(_T(".dvr-ms"));
			}
#pragma endregion input output file handling

			//////////////////////////////////////////////////////////////////////////

			conversionHandle = CreateConversion(false, CComBSTR(name.c_str()));

			if (!conversionHandle)
				throw CarverLab::Exception();

			SetConsoleTitle(outputPath);

			Tell(_T("Press ENTER to interrupt and exit."));

			_done = false;
			HANDLE stdinput = GetStdHandle(STD_INPUT_HANDLE);

			std::auto_ptr<InternalThreadData> threadData(new InternalThreadData);
			threadData->activityCallback = ActivityCallback;
			threadData->contentLength = contentLength;
			threadData->conversionHandle = conversionHandle;
			threadData->inputPath = inPath;
			threadData->isUrl = isUrl;
			threadData->outputPath = outputPath;
			threadData->threadData = NULL;
			threadData->userData = NULL;
			threadData->contentTitle = StringToWString(contentTitle);
			threadData->contentDuration = contentDuration;

			_lastConvertedFilePath = outputPath;

			HANDLE thread = CreateThread(NULL, 0, BeginConversion, threadData.get(), 0, NULL);
			if (thread == NULL)
				throw CarverLab::Exception();

			bool shuttingDown = false;
			bool interruptSuccessful = false;	// will be true if the conversion is inactive after InterruptConversion is called

			while (!_done)
			{
				if (!shuttingDown && ((_kbhit() && _getch() == 13) || InterruptNow(name.c_str())))
				{
					shuttingDown = true;
					interruptSuccessful = InterruptConversion(conversionHandle, 30000);	// will wait 30 seconds for the conversion to die
				}

				Sleep(10);
			}

			if (!interruptSuccessful)
			{	// TODO: will need to kill this puppy in an unnice way... awwww
				Tell(_T("InterruptConversion was unsusccessful."));
			}
			// TODO: INFINITE? um... nope. this will need an intervention
			WaitForSingleObject(thread, INFINITE);

			CloseHandle(thread);
		}
		catch (CarverLab::Exception exception)
		{
			Tell(_T("*** Error: %s"), exception.GetErrorString());
			Tell(_T("Exiting..."));
			ret = exception.GetHRESULT();
		}
		catch (...)
		{
			DWORD errorCode = GetLastError();
			wstring error = Exception::GetLastErrorString(errorCode);
			Tell(_T("*** Unhandled Exception: %s"), error.c_str());
			Tell(_T("Exiting..."));
			ret = errorCode;
		}
		if (conversionHandle != NULL)
			CloseConversion(conversionHandle);
	}
#ifdef _DEBUG
	// sleep a bit so we can see any errors
	Tell(_T("Sleeping for %d seconds in debug mode."), sleepTimeout / 1000);
	Sleep(sleepTimeout);
#endif
	return ret;
}
Exemplo n.º 18
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;
}
Exemplo n.º 19
0
bool CServerList::LoadServerMet(const CPath& path)
{
	AddLogLineN(CFormat(_("Loading server.met file: %s")) % path);
	
	bool merge = !m_servers.empty();
	
	if (!path.FileExists()) {
		AddLogLineN(_("Server.met file not found!"));
		return false;
	}

	// Try to unpack the file, might be an archive
	const wxChar* mets[] = { wxT("server.met"), NULL };
	// Try to unpack the file, might be an archive
	if (UnpackArchive(path, mets).second != EFT_Met) {
		AddLogLineC(CFormat(_("Failed to load server.met file '%s', unknown format encountered.")) % path);
		return false;
	}	

	CFile servermet(path, CFile::read);
	if ( !servermet.IsOpened() ){ 
		AddLogLineN(_("Failed to open server.met!") );
		return false;
	}

	
	try {
		Notify_ServerFreeze();
		
		byte version = servermet.ReadUInt8();
		
		if (version != 0xE0 && version != MET_HEADER) {
			AddLogLineC(CFormat(_("Server.met file corrupt, found invalid versiontag: 0x%x, size %i")) % version % sizeof(version));
			Notify_ServerThaw();
			return false;
		}

		uint32 fservercount = servermet.ReadUInt32();

		ServerMet_Struct sbuffer;
		uint32 iAddCount = 0;

		for ( uint32 j = 0; j < fservercount; ++j ) {
			sbuffer.ip		= servermet.ReadUInt32();
			sbuffer.port		= servermet.ReadUInt16();
			sbuffer.tagcount	= servermet.ReadUInt32();
			
			CServer* newserver = new CServer(&sbuffer);

			// Load tags
			for ( uint32 i = 0; i < sbuffer.tagcount; ++i ) {
				newserver->AddTagFromFile(&servermet);
			}

			// Server priorities are not in sorted order
			// High = 1, Low = 2, Normal = 0, so we have to check 
			// in a less logical fashion.
			int priority = newserver->GetPreferences();
			if (priority < SRV_PR_MIN || priority > SRV_PR_MAX) {
				newserver->SetPreference(SRV_PR_NORMAL);
			}
			
			// set listname for server
			if ( newserver->GetListName().IsEmpty() ) {
				newserver->SetListName(wxT("Server ") +newserver->GetAddress());
			}
			
			
			if ( !theApp->AddServer(newserver) ) {
				CServer* update = GetServerByAddress(newserver->GetAddress(), newserver->GetPort());
				if(update) {
					update->SetListName( newserver->GetListName());
					if(!newserver->GetDescription().IsEmpty()) {
						update->SetDescription( newserver->GetDescription());
					}
					Notify_ServerRefresh(update);
				}
				delete newserver;
			} else {
				++iAddCount;
			}

		}
		
		Notify_ServerThaw();
    
		if (!merge) {
			AddLogLineC(CFormat(wxPLURAL("%i server in server.met found", "%i servers in server.met found", fservercount)) % fservercount);
		} else {
			AddLogLineC(CFormat(wxPLURAL("%d server added", "%d servers added", iAddCount)) % iAddCount);
		}
	} catch (const CInvalidPacket& err) {
		AddLogLineC(_("Error: the file 'server.met' is corrupted: ") + err.what());
		Notify_ServerThaw();
		return false;
	} catch (const CSafeIOException& err) {
		AddLogLineC(_("IO error while reading 'server.met': ") + err.what());
		Notify_ServerThaw();
		return false;
	}
	
	return true;
}
Exemplo n.º 20
0
bool CServerList::SaveServerMet()
{
	CPath curservermet = CPath(theApp->ConfigDir + wxT("server.met"));
	
	CFile servermet(curservermet, CFile::write_safe);
	if (!servermet.IsOpened()) {
		AddLogLineN(_("Failed to save server.met!"));
		return false;
	}

	try {
		servermet.WriteUInt8(0xE0);
		servermet.WriteUInt32( m_servers.size() );

		for ( CInternalList::const_iterator it = m_servers.begin(); it != m_servers.end(); ++it) {
			const CServer* const server = *it;

			uint16 tagcount = 12;
			if (!server->GetListName().IsEmpty()) {
				++tagcount;
			}
			if (!server->GetDynIP().IsEmpty()) {
				++tagcount;
			}
			if (!server->GetDescription().IsEmpty()) {
				++tagcount;
			}
			if (server->GetConnPort() != server->GetPort()) {
				++tagcount;
			}

			// For unicoded name, description, and dynip
			if ( !server->GetListName().IsEmpty() ) {
				++tagcount;
			}
			if ( !server->GetDynIP().IsEmpty() ) {
				++tagcount;
			}
			if ( !server->GetDescription().IsEmpty() ) {
				++tagcount;
			}
			if (!server->GetVersion().IsEmpty()) {
				++tagcount;
			}
			
			if (server->GetServerKeyUDP(true)) {
				++tagcount;
			}

			if (server->GetServerKeyUDPIP()) {
				++tagcount;
			}

			if (server->GetObfuscationPortTCP()) {
				++tagcount;
			}

			if (server->GetObfuscationPortUDP()) {
				++tagcount;
			}
			
			servermet.WriteUInt32(server->GetIP());
			servermet.WriteUInt16(server->GetPort());
			servermet.WriteUInt32(tagcount);
						
			if ( !server->GetListName().IsEmpty() ) {
				// This is BOM to keep eMule compatibility
				CTagString( ST_SERVERNAME, server->GetListName()).WriteTagToFile( &servermet,  utf8strOptBOM);
				CTagString( ST_SERVERNAME, server->GetListName()).WriteTagToFile( &servermet );
			}
			
			if ( !server->GetDynIP().IsEmpty() ) {
				// This is BOM to keep eMule compatibility
				CTagString( ST_DYNIP, server->GetDynIP()).WriteTagToFile( &servermet, utf8strOptBOM );
				CTagString( ST_DYNIP, server->GetDynIP()).WriteTagToFile( &servermet );
			}
			
			if ( !server->GetDescription().IsEmpty() ) {
				// This is BOM to keep eMule compatibility
				CTagString( ST_DESCRIPTION, server->GetDescription()).WriteTagToFile( &servermet, utf8strOptBOM );
				CTagString( ST_DESCRIPTION, server->GetDescription()).WriteTagToFile( &servermet );
			}
			
			if ( server->GetConnPort() != server->GetPort() ) {
				CTagString( ST_AUXPORTSLIST,	server->GetAuxPortsList()	).WriteTagToFile( &servermet );
			}
			
			CTagInt32( ST_FAIL,       server->GetFailedCount()   ).WriteTagToFile( &servermet );
			CTagInt32( ST_PREFERENCE, server->GetPreferences()   ).WriteTagToFile( &servermet );
			CTagInt32( wxT("users"),  server->GetUsers()         ).WriteTagToFile( &servermet );
			CTagInt32( wxT("files"),  server->GetFiles()         ).WriteTagToFile( &servermet );
			CTagInt32( ST_PING,       server->GetPing()          ).WriteTagToFile( &servermet );
			CTagInt32( ST_LASTPING,   server->GetLastPingedTime()).WriteTagToFile( &servermet );
			CTagInt32( ST_MAXUSERS,   server->GetMaxUsers()      ).WriteTagToFile( &servermet );
			CTagInt32( ST_SOFTFILES,  server->GetSoftFiles()     ).WriteTagToFile( &servermet );
			CTagInt32( ST_HARDFILES,  server->GetHardFiles()     ).WriteTagToFile( &servermet );
			if (!server->GetVersion().IsEmpty()){
				CTagString( ST_VERSION,	server->GetVersion() ).WriteTagToFile( &servermet, utf8strOptBOM );
				CTagString( ST_VERSION,	server->GetVersion() ).WriteTagToFile( &servermet );
			}
			CTagInt32( ST_UDPFLAGS,   server->GetUDPFlags()      ).WriteTagToFile( &servermet );
			CTagInt32( ST_LOWIDUSERS, server->GetLowIDUsers()    ).WriteTagToFile( &servermet );
			
			if (server->GetServerKeyUDP(true)) {
				CTagInt32(ST_UDPKEY, server->GetServerKeyUDP(true)).WriteTagToFile( &servermet );
			}

			if (server->GetServerKeyUDPIP()) {
				CTagInt32(ST_UDPKEYIP, server->GetServerKeyUDPIP()).WriteTagToFile( &servermet );
			}

			if (server->GetObfuscationPortTCP()) {
				CTagInt16(ST_TCPPORTOBFUSCATION, server->GetObfuscationPortTCP()).WriteTagToFile( &servermet );
			}

			if (server->GetObfuscationPortUDP()) {
				CTagInt16(ST_UDPPORTOBFUSCATION, server->GetObfuscationPortUDP()).WriteTagToFile( &servermet );
			}
			
		}
		// Now server.met.new is ready to be closed and renamed to server.met.
		// But first rename existing server.met to server.met.bak (replacing old .bak file).
		const CPath oldservermet = CPath(theApp->ConfigDir + wxT("server.met.bak"));
		if (curservermet.FileExists()) {
			CPath::RenameFile(curservermet, oldservermet, true);
		}

		servermet.Close();

	} catch (const CIOFailureException& e) {
		AddLogLineC(wxT("IO failure while writing 'server.met': ") + e.what());
		return false;
	}
	
	return true;
}