int CFileListViewCtrl::CompareItemsCustom(LVCompareParam* pItem1, LVCompareParam* pItem2, int iSortCol)
{
	int result = 0;

	// Deal with all of the custom sort columns
	switch(iSortCol)
	{
	case ListColumn_Size:
		{
			// Sort based on ListColumn_SizeBytes

			// NOTE: There's other ways to use a "proxy column" for sorting, this is just one
			//  (mainly, just to give an example of CompareItemsCustom).
			//  Another way would be to have DoSortItems run on the hidden column,
			//  but then SetSortColumn for the visible column.

			CString sizeInBytesLHS, sizeInBytesRHS;
			this->GetItemText(pItem1->iItem, ListColumn_SizeBytes, sizeInBytesLHS);
			this->GetItemText(pItem2->iItem, ListColumn_SizeBytes, sizeInBytesRHS);

			__int64 difference = _ttoi64(sizeInBytesRHS) - _ttoi64(sizeInBytesLHS);
			if(difference < 0)
				result = 1;
			else if(difference > 0)
				result = -1;
			else
				result = 0;
		}
		break;
	}

	return result;
}
Exemplo n.º 2
0
void CSteamProto::OnGotHistoryMessages(const HttpResponse *response, void *arg)
{
	MCONTACT hContact = FindContact((char*)arg);
	if (!hContact)
		return;

	if (!ResponseHttpOk(response))
		return;

	JSONROOT root(response->pData);
	if (root == NULL)
		return;

	JSONNode *node = json_get(root, "response");

	JSONNode *messages = json_get(node, "messages");
	JSONNode *nmessages = json_as_array(messages);

	// Self SteamID
	ptrA steamId(getStringA("SteamID"));

	for (size_t i = json_size(nmessages); i > 0; i--)
	{
		JSONNode *message = json_at(nmessages, i - 1);

		node = json_get(message, "accountid");
		const char *authorSteamId = AccountIdToSteamId(_ttoi64(ptrT(json_as_string(node))));

		node = json_get(message, "message");
		ptrT text(json_as_string(node));
		T2Utf szMessage(text);

		node = json_get(message, "timestamp");
		time_t timestamp = _ttoi64(ptrT(json_as_string(node)));

		// Ignore already existing messages
		if (timestamp <= m_lastMessageTS)
			continue;

		PROTORECVEVENT recv = { 0 };
		recv.timestamp = timestamp;
		recv.szMessage = szMessage;

		if (strcmp(steamId, authorSteamId))
		{
			// Received message
			ProtoChainRecvMsg(hContact, &recv);
		}
		else
		{
			// Sent message
			recv.flags = PREF_SENT;
			Proto_RecvMessage(hContact, &recv);
		}
	}

	json_delete(nmessages);
}
Exemplo n.º 3
0
void CSteamProto::OnGotConversations(const HttpResponse *response)
{
	// Don't load any messages when we don't have lastMessageTS, as it may cause duplicates
	if (m_lastMessageTS <= 0)
		return;

	if (!ResponseHttpOk(response))
		return;

	JSONROOT root(response->pData);
	if (root == NULL)
		return;

	JSONNode *node = json_get(root, "response");
	JSONNode *sessions = json_get(node, "message_sessions");
	JSONNode *nsessions = json_as_array(sessions);

	if (nsessions != NULL)
	{
		ptrA token(getStringA("TokenSecret"));
		ptrA steamId(getStringA("SteamID"));
		

		for (size_t i = 0; i < json_size(nsessions); i++)
		{
			JSONNode *session = json_at(nsessions, i);

			node = json_get(session, "accountid_friend");
			const char *who = AccountIdToSteamId(_ttoi64(ptrT(json_as_string(node))));

			node = json_get(session, "last_message");
			time_t lastMessageTS = _ttoi64(ptrT(json_as_string(node)));

			/*node = json_get(session, "last_view");
			time_t last_view = _ttoi64(ptrT(json_as_string(node)));

			node = json_get(session, "unread_message_count");
			long unread_count = json_as_int(node);*/

			if (lastMessageTS > m_lastMessageTS)
			{
				PushRequest(
					new GetHistoryMessagesRequest(token, steamId, who, m_lastMessageTS),
					&CSteamProto::OnGotHistoryMessages,
					mir_strdup(who),
					MirFreeArg);
			}
		}

		json_delete(nsessions);
	}
}
Exemplo n.º 4
0
// ɾ³ý
void CExplorerDlg::OnBnClickedButton1()
{
	int tabIndex = m_tab.GetCurSel(); 
	POSITION pos = m_pages[tabIndex]->m_list.GetFirstSelectedItemPosition();
	if (pos == NULL)
		return;
	int index = m_pages[tabIndex]->m_list.GetNextSelectedItem(pos);


	CString code;
	if (tabIndex == 0) // Ö÷Ìâ
	{
		ThreadInfo& thread = m_exploreThreadPage.m_threads[index];
		code = DeleteThread(thread.tid);
		if (code == _T("0"))
			g_deletedTID.insert(_ttoi64(thread.tid));
	}
	else if (tabIndex == 1) // Ìû×Ó
		code = DeletePost(m_explorePostPage.m_tid, m_explorePostPage.m_posts[index].pid);
	else // Â¥ÖÐÂ¥
		code = DeleteLZL(m_explorePostPage.m_tid, m_exploreLzlPage.m_lzls[index].pid);


	if (code != _T("0"))
		AfxMessageBox(_T("ɾ³ýʧ°Ü£¬´íÎó´úÂë" + code + _T("(") + GetTiebaErrorText(code) + _T(")")), MB_ICONERROR);
	else
		sndPlaySound(_T("ɾÌù.wav"), SND_ASYNC | SND_NODEFAULT);
}
Exemplo n.º 5
0
INT64 CFileDownloader::_GetHttpInfoFileSize(HINTERNET hRequest)
{
	CString str;
	if(_GetHttpInfo(hRequest, HTTP_QUERY_CONTENT_LENGTH, str))
		return _ttoi64(str);
	return 0;
}
Exemplo n.º 6
0
void COrderManageDlg::OnEqualCodeEditTextChange()
{
	//用户输入错误指示
	if (m_pEqualCodeEdit->GetText().IsEmpty())
	{
		m_pEqualBuyWrongLabel->SetVisible(false);
	}
	else
	{
		CEqualBuyMethod buyMethod(m_pEqualCodeEdit->GetText().GetData(), _ttoi64(m_pEqualBuyEdit->GetText().GetData()));
		if (!buyMethod.IsCorrect())
		{
			m_pEqualBuyWrongLabel->SetVisible(true);
		}
		else
		{
			m_pEqualBuyWrongLabel->SetVisible(false);
		}
	}

	//智能给用户加上空格
	CString strTemp = m_pEqualCodeEdit->GetText().GetData();
	int nLength = strTemp.GetLength();
	int nLastLength = (int)m_pEqualCodeEdit->GetTag();  //上次长度
	if (nLength > nLastLength)  //字符是增加的
	{
		if (nLength >= 2 && strTemp[nLength-1] != _T(' ') && strTemp[nLength-2] != _T(' '))
		{
			strTemp += _T(' ');
			m_pEqualCodeEdit->SetText(strTemp);
		}
	}

	m_pEqualCodeEdit->SetTag(nLength);  //当前字符串长度保存在此
}
Exemplo n.º 7
0
__int64 CCmdLineParser::GetLongLongVal(LPCTSTR sKey) const
{
	CValsMap::const_iterator it = findKey(sKey);
	if (it == m_valueMap.end())
		return 0;
	return _ttoi64(it->second.c_str());
}
Exemplo n.º 8
0
void COrderManageDlg::OnIntervalBuyEditReturn()
{
	if (m_pIntervalStartEdit->GetText().IsEmpty() || m_pIntervalEndEdit->GetText().IsEmpty() || m_pIntervalBuyEdit->GetText().IsEmpty())
	{
		return;
	}

	//不是一个数,不继续
	CStringUtil strUtil(m_pIntervalBuyEdit->GetText().GetData());
	if (!strUtil.IsNumber())
	{
		return;
	}

	int nStartCode = _ttoi(m_pIntervalStartEdit->GetText().GetData());
	int nEndCode = _ttoi(m_pIntervalEndEdit->GetText().GetData());
	__int64 nBuyValue = _ttoi64(m_pIntervalBuyEdit->GetText().GetData());
	CIntervalBuyMethod buyMethod(nStartCode, nEndCode, nBuyValue);
	if (!COrderManager::Instance()->OrderAppend(m_pCustomerCombo->GetText().GetData(), buyMethod.Buy()))
	{
		return;
	}

	//记日志
	AddBuyLog(buyMethod.Log());		

	//清空内容
	m_pIntervalStartEdit->SetText(_T(""));
	m_pIntervalStartEdit->SetFocus();
	m_pIntervalEndEdit->SetText(_T(""));
	m_pIntervalBuyEdit->SetText(_T(""));

	//清除提示
	//m_pIntervalBuyEdit->SetExampleText(_T(""));
}
Exemplo n.º 9
0
void CRaidAnalyzerDlg::OnEnChangeMaxLba()
{

	CString strText;
	m_pEditMaxLBA->GetWindowTextW(strText);
	verifyMinMax.lTo = _ttoi64(strText);
	BOOL bAllGood = TRUE;
	if (verifyMinMax.lTo < 0 )
	{
			verifyMinMax.lTo = 0;
			AfxMessageBox(_T("Value can't accept less 0"),MB_OK);
			bAllGood = FALSE;
	}
	else
		if (verifyMinMax.lTo < verifyMinMax.lFrom)
		{
			verifyMinMax.lFrom = 0;
			m_pEditMinLBA->SetWindowTextW(_T("0"));
			AfxMessageBox(_T("MaxLBA can't less then MinLBA (MaxLBA > MinLBA)"),MB_ICONHAND);
			bAllGood = FALSE;
		}
	//if (bAllGood == TRUE)
	//	::SendMessageA(m_TabDialogs.m_pParityDlg->GetSafeHwnd(),WM_UPDATE_MAX_LBA,0,verifyMinMax.lTo);


}
Exemplo n.º 10
0
void CPage_Status::OnLimiteNum(UINT nID)
{
	CString strNum;

	if (nID <= IDC_STATUS_HP_DEF)
	{
		LONG64 l64Num;

		GetDlgItemText(nID, strNum);
		l64Num = _ttoi64(strNum);
		if (l64Num > UINT_MAX)
		{
			strNum.Format("%u", UINT_MAX);
			SetDlgItemText(nID, strNum);
			((CEdit *)GetDlgItem(nID))->SetSel(10, 10);
		}
	}
	else
	{
		DWORD dwNum;

		dwNum = GetDlgItemInt(nID);
		if (dwNum > 0xFFFF)
		{
			SetDlgItemInt(nID, 0xFFFF);
			((CEdit *)GetDlgItem(nID))->SetSel(5, 5);
		}
	}
}
Exemplo n.º 11
0
INT64 CSystemInfo::GetMemorySize()
{
    stdex::tString strValue = GetWmiInfo(TEXT("Select * from Win32_LogicalMemoryConfiguration"), TEXT("TotalPhysicalMemory"));
    if (strValue.empty())
        return -1;
    return _ttoi64(strValue.c_str());
}
Exemplo n.º 12
0
BOOL CSystemInfo::GetMemoryInfo()
{
	stdex::tString strValue = GetWmiInfo(TEXT("Select * from Win32_LogicalMemoryConfiguration"), TEXT("TotalPhysicalMemory"));
	if (strValue.empty())
		return FALSE;
	tsprintf(m_stCltHardInfo.szMemory, MAX_PATH, TEXT("%d"), __int64(_ttoi64(strValue.c_str())/1024. + .55));
	return TRUE;
}
Exemplo n.º 13
0
BOOL CWizXmlRpcStructValue::GetInt64(const CString& strName, __int64& n) const
{
	CString str;
    if (!GetStr(strName, str))
		return FALSE;
	//
	n = _ttoi64(str);
	return TRUE;
}
Exemplo n.º 14
0
// 检查更新
CheckUpdateResult CheckUpdate()
{
	static const wregex CHECK_UPDATE_REG(_T("\"fs_id\":(\\d+),\"path\":\"\\\\/\\\\u6211\\\\u7684\\\\u5206\\\\u4eab\\\\/\\\\u767e")
										 _T("\\\\u5ea6\\\\u8d34\\\\u5427\\\\u76f8\\\\u5173\\\\/\\\\u8d34\\\\u5427\\\\u7ba1\\\\u7")
										 _T("406\\\\u5668.zip\",\"server_filename\":\"\\\\u8d34\\\\u5427\\\\u7ba1\\\\u7406\\\\u5")
										 _T("668.zip\".*?\"server_ctime\":(\\d+),"));
	CString src = HTTPGet(_T("http://pan.baidu.com/share/list?channel=chunlei&clienttype=0&web=1&num=100&page=1&dir=%2F%E6%88%91")
						  _T("%E7%9A%84%E5%88%86%E4%BA%AB%2F%E7%99%BE%E5%BA%A6%E8%B4%B4%E5%90%A7%E7%9B%B8%E5%85%B3&uk=436464474&")
						  _T("shareid=497149087"), FALSE);
	std::wcmatch res;
	if (!std::regex_search((LPCTSTR)src, res, CHECK_UPDATE_REG))
		return UPDATE_FAILED_TO_GET_FILE_ID;

	// 文件ID
	CString fs_id = res[1].str().c_str();

	// 上传时间戳
	CString server_ctime = res[2].str().c_str();
	time_t tServer_ctime = _ttoi64(server_ctime);
	tm tmServer_ctime;
	localtime_s(&tmServer_ctime, &tServer_ctime);
	// 上传时间
	CString time;
	time.Format(_T("%02d-%02d-%02d"), tmServer_ctime.tm_year % 100, tmServer_ctime.tm_mon + 1, tmServer_ctime.tm_mday);
	if (time == UPDATE_CURRENT_VERSION)
		return UPDATE_NO_UPDATE;

	if (AfxMessageBox(_T("最新版本") + time + _T(",是否更新?"), MB_ICONQUESTION | MB_YESNO) == IDNO)
		return UPDATE_HAS_UPDATE;

	static const TCHAR TIME_STAMP_LEFT[] = _T("yunData.TIMESTAMP = \"");
	static const TCHAR TIME_STAMP_RIGHT[] = _T("\"");
	static const TCHAR SIGN_LEFT[] = _T("yunData.SIGN = \"");
	static const TCHAR SIGN_RIGHT[] = _T("\"");
	static const TCHAR BDSTOKEN_LEFT[] = _T("yunData.MYBDSTOKEN = \"");
	static const TCHAR BDSTOKEN_RIGHT[] = _T("\"");
	static const TCHAR DLINK_LEFT[] = _T("\"dlink\":\"");
	static const TCHAR DLINK_RIGHT[] = _T("\"");
	src = HTTPGet(UPDATE_URL, FALSE);
	CString timeStamp = GetStringBetween(src, TIME_STAMP_LEFT, TIME_STAMP_RIGHT);
	CString sign = GetStringBetween(src, SIGN_LEFT, SIGN_RIGHT);
	CString bdstoken = GetStringBetween(src, BDSTOKEN_LEFT, BDSTOKEN_RIGHT);
	CString url;
	url.Format(_T("http://pan.baidu.com/api/sharedownload?sign=%s&timestamp=%s&bdstoken=%s&channel=chunlei")
			   _T("&clienttype=0&web=1&app_id=250528"), sign, timeStamp, bdstoken);
	src = HTTPPost(url, _T("encrypt=0&product=share&uk=436464474&primaryid=497149087&fid_list=%5B") + fs_id + _T("%5D"), FALSE);

	// 文件下载链接
	CString dlink = GetStringBetween(src, DLINK_LEFT, DLINK_RIGHT);
	if (dlink == _T(""))
		return UPDATE_FAILED_TO_GET_LINK;

	dlink.Replace(_T("\\/"), _T("/"));
	ShellExecute(NULL, _T("open"), dlink, NULL, NULL, SW_NORMAL);
	AfxMessageBox(_T("下载后解压并覆盖旧版本文件,可保留当前设置"), MB_ICONINFORMATION);
	return UPDATE_HAS_UPDATE;
}
Exemplo n.º 15
0
void CSteamProto::OnLoggedOn(const HttpResponse *response)
{
	if (!CheckResponse(response))
	{
		if (response && response->resultCode == HTTP_CODE_UNAUTHORIZED)
		{
			// Probably expired TokenSecret
			HandleTokenExpired();
			return;
		}

		// Probably timeout or no connection, we can do nothing here
		ShowNotification(_T("Steam"), TranslateT("Unknown login error."));

		SetStatus(ID_STATUS_OFFLINE);
		return;
	}

	JSONROOT root(response->pData);

	JSONNode *node = json_get(root, "error");
	ptrT error(json_as_string(node));
	if (mir_tstrcmpi(error, _T("OK")))
	{
		// Probably expired TokenSecret
		HandleTokenExpired();
		return;
	}

	node = json_get(root, "umqid");
	setString("UMQID", ptrA(mir_u2a(ptrT(json_as_string(node)))));

	node = json_get(root, "message");
	setDword("MessageID", json_as_int(node));
	
	if (m_lastMessageTS <= 0) {
		node = json_get(root, "utc_timestamp");
		time_t timestamp = _ttoi64(ptrT(json_as_string(node)));
		setDword("LastMessageTS", timestamp);
	}

	// load contact list
	ptrA token(getStringA("TokenSecret"));
	ptrA steamId(getStringA("SteamID"));

	PushRequest(
		new GetFriendListRequest(token, steamId),
		&CSteamProto::OnGotFriendList);

	// start polling thread
	m_hPollingThread = ForkThreadEx(&CSteamProto::PollingThread, 0, NULL);

	// go to online now
	ProtoBroadcastAck(NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)ID_STATUS_CONNECTING, m_iStatus = m_iDesiredStatus);
}
Exemplo n.º 16
0
HRESULT CEffectsListDlg::doAddEffect()
{
	int sel = SendMessage(lHwnd, LB_GETCURSEL, 0, 0);
	if(sel == LB_ERR)return sel;
	GUID* pGUID = (GUID*)SendMessage(lHwnd, LB_GETITEMDATA, sel, 0);
	WCHAR sguid[256];
	StringFromGUID2(*pGUID, sguid, 256);
//	OutputDebugString(_bstr_t(sguid).operator wchar_t*());
//	OutputDebugString(_T("\r\n"));
	TCHAR buff[128];
	SendMessage(t1Hwnd, WM_GETTEXT, 128, (LPARAM)buff);
	REFERENCE_TIME start = _ttoi64(buff);
	SendMessage(t2Hwnd, WM_GETTEXT, 128, (LPARAM)buff);
	REFERENCE_TIME stop = _ttoi64(buff);
	SendMessage(trkHwnd, WM_GETTEXT, 128, (LPARAM)buff);
	int track = _ttoi(buff);
	if(SendMessage(swapHwnd, BM_GETCHECK, 0, 0) == BST_UNCHECKED)swap = false;
	else swap = true;

	if(type)return pem->addTransition(track, *pGUID, start, stop, 0, swap, NULL);
	else return pem->addEffect(track, *pGUID, start, stop, 0, NULL);
}
Exemplo n.º 17
0
RegistryProfileInfo::RegistryProfileInfo(CString csProfileName, CString csProfileInformation) {
    m_iNotUsedCount = 0;
    m_pLastPublished = NULL;
    m_pLastActivated = NULL;
    m_csProfileDescription.Empty();
    m_csLastPublishedDoc.Empty();
    m_lCustomProfileID = 0;

    m_csProfileName = csProfileName;
    int iBlankPos = m_csProfileName.Find(_T(" "));
    // If the profile is a custom profile there is an additional 
    // counter appended to the profile name
    if (iBlankPos > 0)
        m_csProfileName = m_csProfileName.Mid(0, iBlankPos);

    if (!csProfileInformation.IsEmpty()) {
        CString csLastPublishedDate;
        ExtractLastPublishedTime(csProfileInformation, csLastPublishedDate);
        if (!csLastPublishedDate.IsEmpty())
            ExtractTimeFromString(csLastPublishedDate, &m_pLastPublished);

        CString csNotUsedCount;
        ExtractNotUsedCountTime(csProfileInformation, csNotUsedCount);
        if (!csNotUsedCount.IsEmpty()) 
            m_iNotUsedCount = _ttoi(csNotUsedCount);

        
        CString csLastUsedDocument;
        ExtractLastUsedDocument(csProfileInformation, csLastUsedDocument);
        if (!csLastUsedDocument.IsEmpty())
            m_csLastPublishedDoc = csLastUsedDocument;

        CString csCustomProfileID;
        ExtractCustomProfileID(csProfileInformation, csCustomProfileID);
        if (!csCustomProfileID.IsEmpty()) {
            _int64 lProfileID = _ttoi64(csCustomProfileID);
            m_lCustomProfileID = lProfileID;
        }
        
        CString csLastActivatedTime;
        ExtractLastActivatedTime(csProfileInformation, csLastActivatedTime);
        if (!csLastActivatedTime.IsEmpty()) 
            ExtractTimeFromString(csLastActivatedTime, &m_pLastActivated);
    }
}
Exemplo n.º 18
0
BOOL CWizKMXmlRpcServerBase::GetValue(const QString& strMethodPrefix, const QString& strToken, const QString& strKbGUID, const QString& strKey, QString& strValue, __int64& nVersion)
{
    CWizKMTokenOnlyParam param(strToken, strKbGUID);
    //
    param.AddString(_T("key"), strKey);
    //
    QString strVersion;
    //
    if (!Call(QString(strMethodPrefix) + _T(".getValue"),  _T("value_of_key"), strValue, _T("version"), strVersion, &param))
    {
        TOLOG1(_T("Failed to get value: key=%1"), strKey);
        return FALSE;
    }
    //
    nVersion = _ttoi64(strVersion);
    //
    return TRUE;
}
Exemplo n.º 19
0
void CRaidAnalyzerDlg::OnEnChangeMinLba()
{
	CString strText;
	m_pEditMinLBA->GetWindowTextW(strText);
	verifyMinMax.lFrom = _ttoi64(strText);
	if (verifyMinMax.lFrom < 0 )
	{
		verifyMinMax.lFrom = 0;
		AfxMessageBox(_T("Value can't accept less 0"),MB_OK);
	}
	else
	{
		if (verifyMinMax.lTo < verifyMinMax.lFrom)
		if (m_vecSelDrives.size() > 0)
		{
			verifyMinMax.lFrom = 0;
			m_pEditMinLBA->SetWindowTextW(_T("0"));
			AfxMessageBox(_T("MaxLBA can't less then MinLBA (MaxLBA > MinLBA)"),MB_ICONHAND);
		
		}
	}

}
Exemplo n.º 20
0
HRESULT ProfileUtils::ParseProfileMessage(CString csMessage, bool &bCancel, __int64 &iProfileID) {
    HRESULT hr = S_OK;

    bCancel = true;
    iProfileID = 0;

    CString csPart1, csPart2, csPart3;
    int iFirstBlank = csMessage.Find(_T(" "));
    if (iFirstBlank >= 0)
        csPart1 = csMessage.Mid(0, iFirstBlank);
    else
        hr = E_FAIL;

    int iSecondBlank = 0;
    if (SUCCEEDED(hr)) {
        iSecondBlank = csMessage.Find(_T(" "), iFirstBlank+1);
        if (iSecondBlank >= 0)
            csPart2 = csMessage.Mid(iFirstBlank+1, (iSecondBlank-(iFirstBlank+1)));
        else
            hr = E_FAIL;
    }

    if (SUCCEEDED(hr) && iSecondBlank+1 < csMessage.GetLength())
        csPart3 = csMessage.Mid(iSecondBlank+1, (csMessage.GetLength()-(iSecondBlank+1)));
    else
        hr = E_FAIL;

    if (SUCCEEDED(hr) && csPart1 == _T("Profile")) {
        iProfileID = _ttoi64(csPart2);
        if (csPart3 == _T("SUCCESS")) 
            bCancel = false;
        else if (csPart3 == _T("CANCEL"))
            bCancel = true;
    }

    return hr;
}
Exemplo n.º 21
0
void COrderManageDlg::OnEqualBuyEditReturn()
{
	if (m_pEqualBuyEdit->GetText().IsEmpty() || m_pEqualCodeEdit->GetText().IsEmpty())
	{
		return;
	}

	//不是一个数,不继续
	CStringUtil strUtil(m_pEqualBuyEdit->GetText().GetData());
	if (!strUtil.IsNumber())
	{
		return;
	}

	CEqualBuyMethod buyMethod(m_pEqualCodeEdit->GetText().GetData(), _ttoi64(m_pEqualBuyEdit->GetText().GetData()));
	if (!buyMethod.IsCorrect())
	{
		return;
	}

	if (!COrderManager::Instance()->OrderAppend(m_pCustomerCombo->GetText().GetData(), buyMethod.Buy()))
	{
		return;
	}

	//记日志
	AddBuyLog(buyMethod.Log());

	//清空内容
	m_pEqualCodeEdit->SetText(_T(""));
	m_pEqualCodeEdit->SetFocus();
	m_pEqualBuyEdit->SetText(_T(""));

	//清除提示
	//m_pEqualBuyEdit->SetExampleText(_T(""));
}
Exemplo n.º 22
0
BOOL CTortoiseProcApp::InitInstance()
{
	CheckUpgrade();
	CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
	CMFCButton::EnableWindowsTheming();

	Gdiplus::GdiplusStartupInput gdiplusStartupInput;
	Gdiplus::GdiplusStartup(&m_gdiplusToken,&gdiplusStartupInput,NULL);

	//set the resource dll for the required language
	CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033);
	long langId = loc;
	CString langDll;
	CStringA langpath = CStringA(CPathUtils::GetAppParentDirectory());
	langpath += "Languages";
	HINSTANCE hInst = NULL;
	do
	{
		langDll.Format(_T("%sLanguages\\TortoiseProc%d.dll"), (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId);

		hInst = LoadLibrary(langDll);

		CString sVer = _T(STRPRODUCTVER);
		CString sFileVer = CPathUtils::GetVersionFromFile(langDll);
		if (sFileVer.Compare(sVer)!=0)
		{
			FreeLibrary(hInst);
			hInst = NULL;
		}
		if (hInst != NULL)
		{
			AfxSetResourceHandle(hInst);
		}
		else
		{
			DWORD lid = SUBLANGID(langId);
			lid--;
			if (lid > 0)
			{
				langId = MAKELANGID(PRIMARYLANGID(langId), lid);
			}
			else
				langId = 0;
		}
	} while ((hInst == NULL) && (langId != 0));
	TCHAR buf[6];
	_tcscpy_s(buf, _T("en"));
	langId = loc;
	// MFC uses a help file with the same name as the application by default,
	// which means we have to change that default to our language specific help files
	CString sHelppath = CPathUtils::GetAppDirectory() + _T("TortoiseGit_en.chm");
	free((void*)m_pszHelpFilePath);
	m_pszHelpFilePath=_tcsdup(sHelppath);
	sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseGit_en.chm");
	do
	{
		CString sLang = _T("_");
		if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf)))
		{
			sLang += buf;
			sHelppath.Replace(_T("_en"), sLang);
			if (PathFileExists(sHelppath))
			{
				free((void*)m_pszHelpFilePath);
				m_pszHelpFilePath=_tcsdup(sHelppath);
				break;
			}
		}
		sHelppath.Replace(sLang, _T("_en"));
		if (GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf)))
		{
			sLang += _T("_");
			sLang += buf;
			sHelppath.Replace(_T("_en"), sLang);
			if (PathFileExists(sHelppath))
			{
				free((void*)m_pszHelpFilePath);
				m_pszHelpFilePath=_tcsdup(sHelppath);
				break;
			}
		}
		sHelppath.Replace(sLang, _T("_en"));

		DWORD lid = SUBLANGID(langId);
		lid--;
		if (lid > 0)
		{
			langId = MAKELANGID(PRIMARYLANGID(langId), lid);
		}
		else
			langId = 0;
	} while (langId);
	setlocale(LC_ALL, "");

	if(!CheckMsysGitDir())
	{
		UINT ret = CMessageBox::Show(NULL, IDS_PROC_NOMSYSGIT, IDS_APPNAME, 3, IDI_HAND, IDS_PROC_SETMSYSGITPATH, IDS_PROC_GOTOMSYSGITWEBSITE, IDS_ABORTBUTTON);
		if(ret == 2)
		{
			ShellExecute(NULL, NULL, _T("http://code.google.com/p/msysgit/"), NULL, NULL, SW_SHOW);
		}
		else if(ret == 1)
		{
			// open settings dialog
			CSinglePropSheetDlg(CString(MAKEINTRESOURCE(IDS_PROC_SETTINGS_TITLE)), new CSetMainPage(), this->GetMainWnd()).DoModal();
		}
		return FALSE;
	}
	if (CAppUtils::GetMsysgitVersion() < 0x01070a00)
	{
		int ret = CMessageBox::ShowCheck(NULL, IDS_PROC_OLDMSYSGIT, IDS_APPNAME, 1, IDI_EXCLAMATION, IDS_PROC_GOTOMSYSGITWEBSITE, IDS_ABORTBUTTON, IDS_IGNOREBUTTON, _T("OldMsysgitVersionWarning"), IDS_PROC_NOTSHOWAGAINIGNORE);
		if (ret == 1)
		{
			CMessageBox::RemoveRegistryKey(_T("OldMsysgitVersionWarning")); // only store answer if it is "Ignore"
			ShellExecute(NULL, NULL, _T("http://code.google.com/p/msysgit/"), NULL, NULL, SW_SHOW);
			return FALSE;
		}
		else if (ret == 2)
		{
			CMessageBox::RemoveRegistryKey(_T("OldMsysgitVersionWarning")); // only store answer if it is "Ignore"
			return FALSE;
		}
	}

	// InitCommonControls() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.

	INITCOMMONCONTROLSEX used = {
		sizeof(INITCOMMONCONTROLSEX),
			ICC_ANIMATE_CLASS | ICC_BAR_CLASSES | ICC_COOL_CLASSES | ICC_DATE_CLASSES |
			ICC_HOTKEY_CLASS | ICC_INTERNET_CLASSES | ICC_LISTVIEW_CLASSES |
			ICC_NATIVEFNTCTL_CLASS | ICC_PAGESCROLLER_CLASS | ICC_PROGRESS_CLASS |
			ICC_TAB_CLASSES | ICC_TREEVIEW_CLASSES | ICC_UPDOWN_CLASS |
			ICC_USEREX_CLASSES | ICC_WIN95_CLASSES
	};
	InitCommonControlsEx(&used);
	AfxOleInit();
	AfxEnableControlContainer();
	AfxInitRichEdit2();
	CWinAppEx::InitInstance();
	SetRegistryKey(_T("TortoiseGit"));
	AfxGetApp()->m_pszProfileName = _tcsdup(_T("TortoiseProc")); // w/o this ResizableLib will store data under TortoiseGitProc which is not compatible with older versions

	CCmdLineParser parser(AfxGetApp()->m_lpCmdLine);

	hWndExplorer = NULL;
	CString sVal = parser.GetVal(_T("hwnd"));
	if (!sVal.IsEmpty())
		hWndExplorer = (HWND)_ttoi64(sVal);

	while (GetParent(hWndExplorer)!=NULL)
		hWndExplorer = GetParent(hWndExplorer);
	if (!IsWindow(hWndExplorer))
	{
		hWndExplorer = NULL;
	}

	// if HKCU\Software\TortoiseGit\Debug is not 0, show our command line
	// in a message box
	if (CRegDWORD(_T("Software\\TortoiseGit\\Debug"), FALSE)==TRUE)
		AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);

	if ( parser.HasKey(_T("path")) && parser.HasKey(_T("pathfile")))
	{
		CMessageBox::Show(NULL, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
		return FALSE;
	}

	CTGitPath cmdLinePath;
	CTGitPathList pathList;
	if (g_sGroupingUUID.IsEmpty())
		g_sGroupingUUID = parser.GetVal(L"groupuuid");
	if ( parser.HasKey(_T("pathfile")) )
	{

		CString sPathfileArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("pathfile")));

		cmdLinePath.SetFromUnknown(sPathfileArgument);
		if (pathList.LoadFromFile(cmdLinePath)==false)
			return FALSE;		// no path specified!
		if ( parser.HasKey(_T("deletepathfile")) )
		{
			// We can delete the temporary path file, now that we've loaded it
			::DeleteFile(cmdLinePath.GetWinPath());
		}
		// This was a path to a temporary file - it's got no meaning now, and
		// anybody who uses it again is in for a problem...
		cmdLinePath.Reset();

	}
	else
	{

		CString sPathArgument = CPathUtils::GetLongPathname(parser.GetVal(_T("path")));
		if (parser.HasKey(_T("expaths")))
		{
			// an /expaths param means we're started via the buttons in our Win7 library
			// and that means the value of /expaths is the current directory, and
			// the selected paths are then added as additional parameters but without a key, only a value

			// because of the "strange treatment of quotation marks and backslashes by CommandLineToArgvW"
			// we have to escape the backslashes first. Since we're only dealing with paths here, that's
			// a save bet.
			// Without this, a command line like:
			// /command:commit /expaths:"D:\" "D:\Utils"
			// would fail because the "D:\" is treated as the backslash being the escape char for the quotation
			// mark and we'd end up with:
			// argv[1] = /command:commit
			// argv[2] = /expaths:D:" D:\Utils
			// See here for more details: http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx
			CString cmdLine = GetCommandLineW();
			cmdLine.Replace(L"\\", L"\\\\");
			int nArgs = 0;
			LPWSTR *szArglist = CommandLineToArgvW(cmdLine, &nArgs);
			if (szArglist)
			{
				// argument 0 is the process path, so start with 1
				for (int i = 1; i < nArgs; ++i)
				{
					if (szArglist[i][0] != '/')
					{
						if (!sPathArgument.IsEmpty())
							sPathArgument += '*';
						sPathArgument += szArglist[i];
					}
				}
				sPathArgument.Replace(L"\\\\", L"\\");
			}
			LocalFree(szArglist);
		}
		if (sPathArgument.IsEmpty() && parser.HasKey(L"path"))
		{
			CMessageBox::Show(hWndExplorer, IDS_ERR_INVALIDPATH, IDS_APPNAME, MB_ICONERROR);
			return FALSE;
		}
		int asterisk = sPathArgument.Find('*');
		cmdLinePath.SetFromUnknown(asterisk >= 0 ? sPathArgument.Left(asterisk) : sPathArgument);
		pathList.LoadFromAsteriskSeparatedString(sPathArgument);
	}

	if (pathList.GetCount() == 0) {
		pathList.AddPath(CTGitPath::CTGitPath(g_Git.m_CurrentDir));
	}

	// Subversion sometimes writes temp files to the current directory!
	// Since TSVN doesn't need a specific CWD anyway, we just set it
	// to the users temp folder: that way, Subversion is guaranteed to
	// have write access to the CWD
	{
		DWORD len = GetCurrentDirectory(0, NULL);
		if (len)
		{
			std::unique_ptr<TCHAR[]> originalCurrentDirectory(new TCHAR[len]);
			if (GetCurrentDirectory(len, originalCurrentDirectory.get()))
			{
				sOrigCWD = originalCurrentDirectory.get();
				sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
			}
		}
		TCHAR pathbuf[MAX_PATH];
		GetTortoiseGitTempPath(MAX_PATH, pathbuf);
		SetCurrentDirectory(pathbuf);
	}

	CheckForNewerVersion();

	if (parser.HasVal(_T("configdir")))
	{
		// the user can override the location of the Subversion config directory here
		CString sConfigDir = parser.GetVal(_T("configdir"));
//		g_GitGlobal.SetConfigDir(sConfigDir);
	}

	CAutoGeneralHandle TGitMutex = ::CreateMutex(NULL, FALSE, _T("TortoiseGitProc.exe"));
	if (!g_Git.SetCurrentDir(cmdLinePath.GetWinPathString(), parser.HasKey(_T("submodule")) == TRUE))
	{
		for (int i = 0; i < pathList.GetCount(); ++i)
			if(g_Git.SetCurrentDir(pathList[i].GetWinPath()))
				break;
	}

	if(!g_Git.m_CurrentDir.IsEmpty())
	{
		sOrigCWD = g_Git.m_CurrentDir;
		SetCurrentDirectory(g_Git.m_CurrentDir);
	}

	if (g_sGroupingUUID.IsEmpty())
	{
		CRegStdDWORD groupSetting = CRegStdDWORD(_T("Software\\TortoiseGit\\GroupTaskbarIconsPerRepo"), 3);
		switch (DWORD(groupSetting))
		{
		case 1:
		case 2:
			// implemented differently to TortoiseSVN atm
			break;
		case 3:
		case 4:
			{
				CString wcroot;
				if (g_GitAdminDir.HasAdminDir(g_Git.m_CurrentDir, true, &wcroot))
				{
					git_oid oid;
					CStringA wcRootA(wcroot);
					if (!git_odb_hash(&oid, wcRootA.GetBuffer(), wcRootA.GetLength(), GIT_OBJ_BLOB))
					{
						CStringA hash;
						git_oid_tostr(hash.GetBufferSetLength(GIT_OID_HEXSZ + 1), GIT_OID_HEXSZ + 1, &oid);
						hash.ReleaseBuffer();
						g_sGroupingUUID = hash;
					}
				}
			}
		}
	}

	CString sAppID = GetTaskIDPerUUID(g_sGroupingUUID).c_str();
	InitializeJumpList(sAppID);
	EnsureGitLibrary(false);

	{
		CString err;
		try
		{
			// requires CWD to be set
			CGit::m_LogEncode = CAppUtils::GetLogOutputEncode();

			// make sure all config files are read in order to check that none contains an error
			g_Git.GetConfigValue(_T("doesnot.exist"));
		}
		catch (char* msg)
		{
			err = CString(msg);
		}

		if (!err.IsEmpty())
		{
			UINT choice = CMessageBox::Show(hWndExplorer, err, _T("TortoiseGit"), 1, IDI_ERROR, CString(MAKEINTRESOURCE(IDS_PROC_EDITLOCALGITCONFIG)), CString(MAKEINTRESOURCE(IDS_PROC_EDITGLOBALGITCONFIG)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON)));
			if (choice == 1)
			{
				// open the config file with alternative editor
				CAppUtils::LaunchAlternativeEditor(g_Git.GetGitLocalConfig());
			}
			else if (choice == 2)
			{
				// open the global config file with alternative editor
				CAppUtils::LaunchAlternativeEditor(g_Git.GetGitGlobalConfig());
			}
			return FALSE;
		}
	}

	// execute the requested command
	CommandServer server;
	Command * cmd = server.GetCommand(parser.GetVal(_T("command")));
	if (cmd)
	{
		cmd->SetExplorerHwnd(hWndExplorer);

		cmd->SetParser(parser);
		cmd->SetPaths(pathList, cmdLinePath);

		retSuccess = cmd->Execute();
		delete cmd;
	}

	// Look for temporary files left around by TortoiseSVN and
	// remove them. But only delete 'old' files because some
	// apps might still be needing the recent ones.
	{
		DWORD len = GetTortoiseGitTempPath(0, NULL);
		std::unique_ptr<TCHAR[]> path(new TCHAR[len + 100]);
		len = GetTortoiseGitTempPath (len + 100, path.get());
		if (len != 0)
		{
			CDirFileEnum finder(path.get());
			FILETIME systime_;
			::GetSystemTimeAsFileTime(&systime_);
			__int64 systime = (((_int64)systime_.dwHighDateTime)<<32) | ((__int64)systime_.dwLowDateTime);
			bool isDir;
			CString filepath;
			while (finder.NextFile(filepath, &isDir))
			{
				HANDLE hFile = ::CreateFile(filepath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, isDir ? FILE_FLAG_BACKUP_SEMANTICS : NULL, NULL);
				if (hFile != INVALID_HANDLE_VALUE)
				{
					FILETIME createtime_;
					if (::GetFileTime(hFile, &createtime_, NULL, NULL))
					{
						::CloseHandle(hFile);
						__int64 createtime = (((_int64)createtime_.dwHighDateTime)<<32) | ((__int64)createtime_.dwLowDateTime);
						if ((createtime + 864000000000) < systime)		//only delete files older than a day
						{
							::SetFileAttributes(filepath, FILE_ATTRIBUTE_NORMAL);
							if (isDir)
								::RemoveDirectory(filepath);
							else
								::DeleteFile(filepath);
						}
					}
					else
						::CloseHandle(hFile);
				}
			}
		}
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	// application, rather than start the application's message pump.
	return FALSE;
}
Exemplo n.º 23
0
BOOL CSVToolDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	ShowWindow(SW_SHOW);
	m_Font.CreatePointFont(100, _T("微软雅黑"), NULL);
	m_static.SetFont(&m_Font, true);

	// TODO: 在此添加额外的初始化代码
	SetWindowText(_T("SVTool - V1.0"));
	
	CRect tabRect;

	m_tab.InsertItem(0,_T("ACPI"));
	m_tab.InsertItem(1,_T("CCTool"));

	CCTool.Create(IDD_DIALOG_CCTool, &m_tab);
	ACPI.Create(IDD_DIALOG_ACPI, &m_tab);

	m_tab.GetClientRect(&tabRect);
	tabRect.left += 5;                  
    tabRect.right -= 5;   
    tabRect.top += 25;   
    tabRect.bottom -= 5;

	//设置子对话框尺寸并移动到指定位置

	ACPI.MoveWindow(&tabRect);
	CCTool.MoveWindow(&tabRect);

	//分别设置隐藏和显示
	ACPI.ShowWindow(true);
	CCTool.ShowWindow(false);

	m_tab.SetCurSel(0);

	// 根据调整好的tabRect放置m_jzmDlg子对话框,并设置为显示   
    // CCTool.SetWindowPos(NULL, tabRect.left, tabRect.top, tabRect.Width(), tabRect.Height(), SWP_HIDEWINDOW);   
    // 根据调整好的tabRect放置m_androidDlg子对话框,并设置为隐藏   
    //ACPI.SetWindowPos(NULL, tabRect.left, tabRect.top, tabRect.Width(), tabRect.Height(), SWP_SHOWWINDOW); 

	//ACPI
	TCHAR rbPath[MAX_PATH];
	GetModuleFileName(NULL,rbPath,MAX_PATH);
	ACPI.rootpath = rbPath;

	CString temp1;
	TCHAR TMP1[1024];
	DWORD dd;
	CRegKey KKey;
	CString HWinfo = ACPI.hardwareinfo();
	ACPI.SetDlgItemText(IDC_HWINFO,HWinfo);
	if(KKey.Open(HKEY_CURRENT_USER,_T("Software\\SVACPI\\ACPI Information")) == ERROR_SUCCESS)
	{
		AfxMessageBox(_T("1"));
		KKey.QueryStringValue(_T("OrigHWInfo"),TMP1,&dd);
		temp1 = TMP1;
		KKey.QueryStringValue(_T("ErrorPath"),TMP1,&dd);
		ACPI.errorpath = TMP1;
		if(ACPI.CheckDiffInfo(ACPI.ACPIs, temp1, HWinfo))
			ACPI.GetDlgItem(IDC_STATIC_Error)->EnableWindow(TRUE); 
	}
	KKey.Close();

	CRegKey hKey;
	if(hKey.Open(HKEY_CURRENT_USER,_T("Software\\SVACPI\\ACPI Information")) == ERROR_SUCCESS)
	{
		AfxMessageBox(_T("2"));
		TCHAR TMP[1024];
		CString temp;
		DWORD dwcount = 1024, dwType = REG_SZ;
		//从注册表中恢复设置
		hKey.QueryStringValue(_T("SetLoop"), TMP, &dwcount);
		temp = TMP;
		ACPI.SetDlgItemText(IDC_Loop, temp);

		hKey.QueryStringValue(_T("SetTime"), TMP, &dwcount);
		temp = TMP;
		ACPI.SetDlgItemText(IDC_Countdown, temp);
		ACPI.SetDlgItemText(IDC_time_to_run, temp);

		CRegKey lKey;
		if (lKey.Open(HKEY_CURRENT_USER, _T("Software\\SVACPI\\ACPI Information")) == ERROR_SUCCESS)
		{
			AfxMessageBox(_T("3"));
			lKey.QueryStringValue(_T("CurrState"), TMP, &dwcount);
			ACPI.ACPIs = TMP;
			temp = TMP;

			ULONGLONG a;
			lKey.QueryQWORDValue(_T("LastLoop"), a);
			CString Loop;
			Loop.Format(_T("%d"), a);
			ACPI.SetDlgItemText(IDC_Loop_time, Loop);
		}

		CString time;
		HKEY tKey;
		if (RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\SVACPI\\ACPI Information"), 0, KEY_READ | KEY_WRITE, &tKey) == ERROR_SUCCESS)
		{
			DWORD dwReturn = 1024;
			RegQueryValueEx(tKey, _T("RealTime"), NULL, &dwType, (LPBYTE)(&TMP), &dwReturn);
			time = TMP;
		}

		//S5开机初始化
		if(temp == _T("S5"))
		{
			ACPI.SetDlgItemText(IDC_S5BUTTON,_T("Stop S5"));
			ACPI.GetDlgItem(IDC_S4BUTTON)->EnableWindow(FALSE);
			ACPI.GetDlgItem(IDC_S3BUTTON)->EnableWindow(FALSE);
			ACPI.GetDlgItem(IDC_RbBUTTON)->EnableWindow(FALSE);
			ACPI.GetDlgItem(IDC_PBUTTON)->EnableWindow(TRUE);

			FILETIME ft; LARGE_INTEGER tmp; LONGLONG tmptime;
			SYSTEMTIME st;
			GetLocalTime(&st);

			SystemTimeToFileTime(&st, &ft);
			tmp.LowPart = ft.dwLowDateTime;
			tmp.HighPart = ft.dwHighDateTime;
			tmptime = tmp.QuadPart;

			tmptime += _ttoi64(time);
			tmp.QuadPart = tmptime;
			ft.dwLowDateTime = tmp.LowPart;
			ft.dwHighDateTime = tmp.HighPart;
			FileTimeToSystemTime(&ft, &st);
			SetLocalTime(&st);
		}
		//Reboot开机初始化
		else
		{
			ACPI.SetDlgItemText(IDC_RbBUTTON,_T("Stop Reboot"));
			ACPI.GetDlgItem(IDC_S4BUTTON)->EnableWindow(FALSE);
			ACPI.GetDlgItem(IDC_S3BUTTON)->EnableWindow(FALSE);
			ACPI.GetDlgItem(IDC_S5BUTTON)->EnableWindow(FALSE);
			ACPI.GetDlgItem(IDC_PBUTTON)->EnableWindow(TRUE);
		}
		hKey.Close();
		lKey.Close();
		ACPI.SetTimer(21,1000,NULL);
	}
	else
	{
		ACPI.SetDlgItemText(IDC_Loop,_T("9999"));
		ACPI.SetDlgItemText(IDC_Countdown,_T("15"));
		ACPI.SetDlgItemText(IDC_Loop_time,_T("0"));
		ACPI.SetDlgItemText(IDC_time_to_run,_T("-"));

		ACPI.SetDlgItemText(IDC_PBUTTON,_T("Pause"));
		ACPI.SetDlgItemText(IDC_S3BUTTON,_T("Run S1/S3"));
		ACPI.SetDlgItemText(IDC_S4BUTTON,_T("Run S4"));
		ACPI.SetDlgItemText(IDC_S5BUTTON,_T("Run S5"));
		ACPI.SetDlgItemText(IDC_RbBUTTON, _T("Reboot"));


		ACPI.GetDlgItem(IDC_PBUTTON)->EnableWindow(FALSE);
		ACPI.GetDlgItem(IDC_S3BUTTON)->EnableWindow(TRUE);
		ACPI.GetDlgItem(IDC_S4BUTTON)->EnableWindow(TRUE);
		ACPI.GetDlgItem(IDC_S5BUTTON)->EnableWindow(TRUE);
		ACPI.GetDlgItem(IDC_RbBUTTON)->EnableWindow(TRUE);
	}

	//copycompare
	CCTool.CheckDlgButton(IDC_200MS_RADIO, 1);
	CCTool.sourcepath = _T("D:\\CCData\\200MS");
	CCTool.SetDlgItemText(IDC_SOURCE_PATH_EDIT,CCTool.sourcepath);


	CString filename ;
	TCHAR SysTmpPath[MAX_PATH];
	GetTempPath(MAX_PATH,SysTmpPath);
	filename = SysTmpPath;
	filename+=_T("CCtool.bat");

	CFileFind finder;
	BOOL iffind = finder.FindFile(filename);
	if(iffind)
	{
		CFile CCbat;
		CCbat.Remove(filename);
	}
	
	CFile CCbat(filename, CFile::modeCreate|CFile::modeWrite);
	CCbat.Write("@echo off\r\necho CCLoop will start running in 10 seconds...\r\n", sizeof("@echo off\r\necho CCLoop will start running in 10 seconds...\r\n")-1);
	CCbat.Write("ping 127.0.0.1 -n 11>nul\r\n",sizeof("ping 127.0.0.1 -n 11>nul\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write("set /a looptime=0\r\n",sizeof("set /a looptime=0\r\n")-1);
	CCbat.Write("set sdisk=%2\r\n",sizeof("set sdisk=%2\r\n")-1);
	CCbat.Write("set ddisk=%3\r\n",sizeof("set ddisk=%3\r\n")-1);
	CCbat.Write("set s=%sdisk:~0,1%\r\n",sizeof("set s=%sdisk:~0,1%\r\n")-1);
	CCbat.Write("set d=%ddisk:~0,1%\r\n",sizeof("set d=%ddisk:~0,1%\r\n")-1);
	CCbat.Write("if not exist %d%:\\ color fc&echo ERROR!!! %d%:\\ is not EXIST!!!&pause\r\n",sizeof("if not exist %d%:\\ color fc&echo ERROR!!! %d%:\\ is not EXIST!!!&pause\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write("path=c:\\;c:\\windows\\command;c:\\windows\\system32;c:\\windows;C:\\WinNT\\system32;c:\\WinNT;c:\\windows\\sysWOW64;\r\n",sizeof("path=c:\\;c:\\windows\\command;c:\\windows\\system32;c:\\windows;C:\\WinNT\\system32;c:\\WinNT;c:\\windows\\sysWOW64;\r\n")-1);
	CCbat.Write("break=on\r\n",sizeof("break=on\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write("if exist c:\\%s%-%d%-%1.txt del /q c:\\%s%-%d%-%1.txt\r\n",sizeof("if exist c:\\%s%-%d%-%1.txt del /q c:\\%s%-%d%-%1.txt\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write(":start\r\n",sizeof(":start\r\n")-1);
	CCbat.Write("echo ************** (%s%) copy to (%d%) is starting ******************* >>C:\\%s%-%d%-%1.txt\r\n",sizeof("echo ************** (%s%) copy to (%d%) is starting ******************* >>C:\\%s%-%d%-%1.txt\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write(":l\r\n",sizeof(":l\r\n")-1);
	CCbat.Write("if exist %3 rd /s /q %3\r\n",sizeof("if exist %3 rd /s /q %3\r\n")-1);
	CCbat.Write("if exist D:\\%d%-%1-C rd /s /q D:\\%d%-%1-C\r\n",sizeof("if exist D:\\%d%-%1-C rd /s /q D:\\%d%-%1-C\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write(":loop\r\n",sizeof(":loop\r\n")-1);
	CCbat.Write("echo ************************************************************** >>C:\\%s%-%d%-%1.txt\r\n",sizeof("echo ************************************************************** >>C:\\%s%-%d%-%1.txt\r\n")-1);
	CCbat.Write("echo **************  Loop %looptime% is starting ****************** >>C:\\%s%-%d%-%1.txt\r\n",sizeof("echo **************  Loop %looptime% is starting ****************** >>C:\\%s%-%d%-%1.txt\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write("md %3\r\n",sizeof("md %3\r\n")-1);
	CCbat.Write("echo %time%\r\n",sizeof("echo %time%\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write("set copybgntime=%time%\r\n",sizeof("set copybgntime=%time%\r\n")-1);
	CCbat.Write("set copybgndate=%date%\r\n",sizeof("set copybgndate=%date%\r\n")-1);
	CCbat.Write("copy /Y %2 %3\r\n",sizeof("copy /Y %2 %3\r\n")-1);
	CCbat.Write("set copyendtime=%time%\r\n",sizeof("set copyendtime=%time%\r\n")-1);
	CCbat.Write("set copyenddate=%date%\r\n",sizeof("set copyenddate=%date%\r\n")-1);
	CCbat.Write("if errorlevel 1 color fc&echo ERROR happened when copy from %2 to %3 !!(no files were found) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n",sizeof("if errorlevel 1 color fc&echo ERROR happened when copy from %2 to %3 !!(no files were found) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n")-1);
	CCbat.Write("if errorlevel 4 color cf&echo ERROR happened when copy from %2 to %3 !!(there is not enough memory) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n",sizeof("if errorlevel 4 color cf&echo ERROR happened when copy from %2 to %3 !!(there is not enough memory) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write("echo n|comp %2 %3\r\n",sizeof("echo n|comp %2 %3\r\n")-1);
	CCbat.Write("set compendtime=%time%\r\n",sizeof("set compendtime=%time%\r\n")-1);
	CCbat.Write("set compenddate=%date%\r\n",sizeof("set compenddate=%date%\r\n")-1);
	CCbat.Write("if errorlevel 1 color cf&echo ERROR happened when compare %2 with %3 !!(files are different) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n",sizeof("if errorlevel 1 color cf&echo ERROR happened when compare %2 with %3 !!(files are different) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n")-1);
	CCbat.Write("if errorlevel 2 color fd&echo ERROR happened when compare %2 with %3 !!(cannot open one of the files or invalid arguments or invalid switch) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n",sizeof("if errorlevel 2 color fd&echo ERROR happened when compare %2 with %3 !!(cannot open one of the files or invalid arguments or invalid switch) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write("echo Start copy from %2 to %3: %copybgntime% %copybgndate%. >>C:\\%s%-%d%-%1.txt\r\n",sizeof("echo Start copy from %2 to %3: %copybgntime% %copybgndate%. >>C:\\%s%-%d%-%1.txt\r\n")-1);
	CCbat.Write("echo Finish copy from %2 to %3: %copyendtime% %copyenddate%. >>C:\\%s%-%d%-%1.txt\r\n",sizeof("echo Finish copy from %2 to %3: %copyendtime% %copyenddate%. >>C:\\%s%-%d%-%1.txt\r\n")-1);
	CCbat.Write("echo Finish comp from %2 to %3: %compendtime% %compenddate%. >>C:\\%s%-%d%-%1.txt\r\n",sizeof("echo Finish comp from %2 to %3: %compendtime% %compenddate%. >>C:\\%s%-%d%-%1.txt\r\n")-1);
	CCbat.Write("set info=%s%-%d%-%1-copy\r\n",sizeof("set info=%s%-%d%-%1-copy\r\n")-1);
	CCbat.Write("call %~dp0count %copybgntime% %copyendtime% C:\\%info%\r\n",sizeof("call %~dp0count %copybgntime% %copyendtime% C:\\%info%\r\n")-1);
	CCbat.Write("set info=%s%-%d%-%1-comp\r\n",sizeof("set info=%s%-%d%-%1-comp\r\n")-1);
	CCbat.Write("call %~dp0count %copyendtime% %compendtime% C:\\%info%\r\n",sizeof("call %~dp0count %copyendtime% %compendtime% C:\\%info%\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write("md D:\\%d%-%1-C\r\n",sizeof("md D:\\%d%-%1-C\r\n")-1);
	CCbat.Write("set copybgntime=%time%\r\n",sizeof("set copybgntime=%time%\r\n")-1);
	CCbat.Write("set copyenddate=%date%\r\n",sizeof("set copyenddate=%date%\r\n")-1);
	CCbat.Write("copy /Y %3 D:\\%d%-%1-C\r\n",sizeof("copy /Y %3 D:\\%d%-%1-C\r\n")-1);
	CCbat.Write("set copyendtime=%time%\r\n",sizeof("set copyendtime=%time%\r\n")-1);
	CCbat.Write("set copyenddate=%date%\r\n",sizeof("set copyenddate=%date%\r\n")-1);
	CCbat.Write("if errorlevel 1 color fc&echo ERROR happened when copy from %3 to D:\\%d%-%1-C !!(no files were found) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n",sizeof("if errorlevel 1 color fc&echo ERROR happened when copy from %3 to D:\\DataComp !!(no files were found) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n")-1);
	CCbat.Write("if errorlevel 4 color cf&echo ERROR happened when copy from %3 to D:\\%d%-%1-C !!(there is not enough memory) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n",sizeof("if errorlevel 4 color cf&echo ERROR happened when copy from %3 to D:\\DataComp !!(there is not enough memory) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n")-1);
	CCbat.Write("echo n|comp %2 D:\\%d%-%1-C\r\n",sizeof("echo n|comp %2 D:\\%d%-%1-C\r\n")-1);
	CCbat.Write("set compendtime=%time%\r\n",sizeof("set compendtime=%time%\r\n")-1);
	CCbat.Write("set compenddate=%date%\r\n",sizeof("set compenddate=%date%\r\n")-1);
	CCbat.Write("if errorlevel 1 color cf&echo ERROR happened when compare %2 with D:\\%d%-%1-C !!(files are different) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n",sizeof("if errorlevel 1 color cf&echo ERROR happened when compare %2 with D:\\DataComp !!(files are different) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n")-1);
	CCbat.Write("if errorlevel 2 color fd&echo ERROR happened when compare %2 with D:\\%d%-%1-C !!(cannot open one of the files or invalid arguments or invalid switch) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n",sizeof("if errorlevel 2 color fd&echo ERROR happened when compare %2 with D:\\DataComp !!(cannot open one of the files or invalid arguments or invalid switch) in loop %looptime% at %time% %date%>>C:\\error.txt &ping 127.0.0.1 -n 30>nul&goto l\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write("echo Start copy from %2 to D:\\%d%-%1-C: %copybgntime% %copybgndate%. >>C:\\%s%-%d%-%1.txt\r\n",sizeof("echo Start copy from %2 to D:\\%d%-%1-C: %copybgntime% %copybgndate%. >>C:\\%s%-%d%-%1.txt\r\n")-1);
	CCbat.Write("echo Finish copy from %2 to D:\\%d%-%1-C: %copyendtime% %copyenddate%. >>C:\\%s%-%d%-%1.txt\r\n",sizeof("echo Finish copy from %2 to D:\\%d%-%1-C: %copyendtime% %copyenddate%. >>C:\\%s%-%d%-%1.txt\r\n")-1);
	CCbat.Write("echo Finish comp from %2 to D:\\%d%-%1-C: %compendtime% %compenddate%. >>C:\\%s%-%d%-%1.txt\r\n",sizeof("echo Finish comp from %2 to D:\\%d%-%1-C: %compendtime% %compenddate%. >>C:\\%s%-%d%-%1.txt\r\n")-1);
	CCbat.Write("set info=%s%-%d%-%1-copy\r\n",sizeof("set info=%s%-%d%-%1-copy\r\n")-1);
	CCbat.Write("call %~dp0count %copybgntime% %copyendtime% C:\\%info%\r\n",sizeof("call %~dp0count %copybgntime% %copyendtime% C:\\%info%\r\n")-1);
	CCbat.Write("set info=%s%-%d%-%1-comp\r\n",sizeof("set info=%s%-%d%-%1-comp\r\n")-1);
	CCbat.Write("call %~dp0count %copyendtime% %compendtime% C:\\%info%\r\n",sizeof("call %~dp0count %copyendtime% %compendtime% C:\\%info%\r\n")-1);
	CCbat.Write("\r\n",sizeof("\r\n")-1);
	CCbat.Write("rd /s /q %3\r\n",sizeof("rd /s /q %3\r\n")-1);
	CCbat.Write("rd /s /q D:\\%d%-%1-C\r\n",sizeof("rd /s /q D:\\%d%-%1-C\r\n")-1);
	CCbat.Write("echo **************  Loop %looptime% has finished ***************** >>C:\\%s%-%d%-%1.txt\r\n",sizeof("echo **************  Loop %looptime% has finished ***************** >>C:\\%s%-%d%-%1.txt\r\n")-1);
	CCbat.Write("set /a looptime=looptime+1\r\n",sizeof("set /a looptime=looptime+1\r\n")-1);
	CCbat.Write("ping 127.0.0.1 -n 05>nul\r\n",sizeof("ping 127.0.0.1 -n 05>nul\r\n")-1);
	CCbat.Write("goto loop\r\n",sizeof("goto loop\r\n")-1);
	CCbat.Flush();
	CCbat.Close();

	GetTempPath(MAX_PATH,SysTmpPath);
	filename = SysTmpPath;
	filename+=_T("count.bat");
	iffind = finder.FindFile(filename);
	if(iffind)
	{
		CFile CCcount;
		CCcount.Remove(filename);
	}

	CFile Countbat(filename, CFile::modeCreate|CFile::modeWrite);

	Countbat.Write("set tmptime=%1\r\n",sizeof("set tmptime=%1\r\n")-1);
	Countbat.Write("if %tmptime:~2,1%==: (\r\n",sizeof("if %tmptime:~2,1%==: (\r\n")-1);
	Countbat.Write("set /a hour=%tmptime:~0,2%\r\n",sizeof("set /a hour=%tmptime:~0,2%\r\n")-1);
	Countbat.Write("if %tmptime:~3,1%==0 set /a min=%tmptime:~4,1%\r\n",sizeof("if %tmptime:~3,1%==0 set /a min=%tmptime:~4,1%\r\n")-1);
	Countbat.Write("if %tmptime:~3,1% NEQ 0 set /a min=%tmptime:~3,2%\r\n",sizeof("if %tmptime:~3,1% NEQ 0 set /a min=%tmptime:~3,2%\r\n")-1);
	Countbat.Write("if %tmptime:~6,1%==0 set /a sec=%tmptime:~7,1%\r\n",sizeof("if %tmptime:~6,1%==0 set /a sec=%tmptime:~7,1%\r\n")-1);
	Countbat.Write("if %tmptime:~6,1% NEQ 0 set /a sec=%tmptime:~6,2%)\r\n",sizeof("if %tmptime:~6,1% NEQ 0 set /a sec=%tmptime:~6,2%)\r\n")-1);
	Countbat.Write("if %tmptime:~1,1%==: (\r\n",sizeof("if %tmptime:~1,1%==: (\r\n")-1);
	Countbat.Write("set /a hour=%tmptime:~0,1%\r\n",sizeof("set /a hour=%tmptime:~0,1%\r\n")-1);
	Countbat.Write("if %tmptime:~2,1%==0 set /a min=%tmptime:~3,1%\r\n",sizeof("if %tmptime:~2,1%==0 set /a min=%tmptime:~3,1%\r\n")-1);
	Countbat.Write("if %tmptime:~2,1% NEQ 0 set /a min=%tmptime:~2,2%\r\n",sizeof("if %tmptime:~2,1% NEQ 0 set /a min=%tmptime:~2,2%\r\n")-1);
	Countbat.Write("if %tmptime:~5,1%==0 set /a sec=%tmptime:~6,1%\r\n",sizeof("if %tmptime:~5,1%==0 set /a sec=%tmptime:~6,1%\r\n")-1);
	Countbat.Write("if %tmptime:~5,1% NEQ 0 set /a sec=%tmptime:~5,2%)\r\n",sizeof("if %tmptime:~5,1% NEQ 0 set /a sec=%tmptime:~5,2%)\r\n")-1);
	Countbat.Write("set /a begin=%hour%*3600+%min%*60+%sec%\r\n",sizeof("set /a begin=%hour%*3600+%min%*60+%sec%\r\n")-1);
	Countbat.Write("\r\n",sizeof("\r\n")-1);
	Countbat.Write("set tmptime=%2\r\n",sizeof("set tmptime=%2\r\n")-1);
	Countbat.Write("if %tmptime:~2,1%==: (\r\n",sizeof("if %tmptime:~2,1%==: (\r\n")-1);
	Countbat.Write("set /a hour=%tmptime:~0,2%\r\n",sizeof("set /a hour=%tmptime:~0,2%\r\n")-1);
	Countbat.Write("if %tmptime:~3,1%==0 set /a min=%tmptime:~4,1%\r\n",sizeof("if %tmptime:~3,1%==0 set /a min=%tmptime:~4,1%\r\n")-1);
	Countbat.Write("if %tmptime:~3,1% NEQ 0 set /a min=%tmptime:~3,2%\r\n",sizeof("if %tmptime:~3,1% NEQ 0 set /a min=%tmptime:~3,2%\r\n")-1);
	Countbat.Write("if %tmptime:~6,1%==0 set /a sec=%tmptime:~7,1%\r\n",sizeof("if %tmptime:~6,1%==0 set /a sec=%tmptime:~7,1%\r\n")-1);
	Countbat.Write("if %tmptime:~6,1% NEQ 0 set /a sec=%tmptime:~6,2%)\r\n",sizeof("if %tmptime:~6,1% NEQ 0 set /a sec=%tmptime:~6,2%)\r\n")-1);
	Countbat.Write("if %tmptime:~1,1%==: (\r\n",sizeof("if %tmptime:~1,1%==: (\r\n")-1);
	Countbat.Write("set /a hour=%tmptime:~0,1%\r\n",sizeof("set /a hour=%tmptime:~0,1%\r\n")-1);
	Countbat.Write("if %tmptime:~2,1%==0 set /a min=%tmptime:~3,1%\r\n",sizeof("if %tmptime:~2,1%==0 set /a min=%tmptime:~3,1%\r\n")-1);
	Countbat.Write("if %tmptime:~2,1% NEQ 0 set /a min=%tmptime:~2,2%\r\n",sizeof("if %tmptime:~2,1% NEQ 0 set /a min=%tmptime:~2,2%\r\n")-1);
	Countbat.Write("if %tmptime:~5,1%==0 set /a sec=%tmptime:~6,1%\r\n",sizeof("if %tmptime:~5,1%==0 set /a sec=%tmptime:~6,1%\r\n")-1);
	Countbat.Write("if %tmptime:~5,1% NEQ 0 set /a sec=%tmptime:~5,2%)\r\n",sizeof("if %tmptime:~5,1% NEQ 0 set /a sec=%tmptime:~5,2%)\r\n")-1);
	Countbat.Write("set /a final=%hour%*3600+%min%*60+%sec%\r\n",sizeof("set /a final=%hour%*3600+%min%*60+%sec%\r\n")-1);
	Countbat.Write("\r\n",sizeof("\r\n")-1);
	Countbat.Write("set /a total=%final%-%begin%\r\n",sizeof("set /a total=%final%-%begin%\r\n")-1);
	Countbat.Write("set info=%3\r\n",sizeof("set info=%3\r\n")-1);
	Countbat.Write("echo total %info% time: %total% seconds >>%info:~0,-5%.txt\r\n",sizeof("echo total %info% time: %total% seconds >>%info:~0,-5%.txt\r\n")-1);
	Countbat.Write("echo --                            >>%info:~0,-5%.txt\r\n",sizeof("echo --                            >>%info:~0,-5%.txt\r\n")-1);
	Countbat.Flush();
	Countbat.Close();

	return FALSE;  // 除非将焦点设置到控件,否则返回 TRUE
}
int CDownloadThread::TransferDataGet()
{
	CUrlCrack url;
	if (!url.Crack(m_strDownURl.c_str()))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_URLCRACKERROR,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的url = %s Crack 异常!", m_strDownURl.c_str()));
		return ERR_URLCRACKERROR;
	}

	NEED_STOP;
	
	m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
	{
		NEED_STOP;
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPEN,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的InetOpen异常!LastErrCode = %d", GetLastError()));
		return ERR_INTOPEN;
	}
	
	NEED_STOP;
	
	DWORD dwTimeOut = 60000;
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	
	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
	if (m_hInetConnection == NULL)
	{
		NEED_STOP;
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTCONNECT,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的连接异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTCONNECT;
	}
	
	NEED_STOP;

	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;
	
	DWORD dwFlags = 0;
	if(INTERNET_DEFAULT_HTTPS_PORT == url.GetPort())
	{
		dwFlags = INTERNET_FLAG_SECURE;

	}
	else if(INTERNET_DEFAULT_HTTP_PORT == url.GetPort())
	{
		dwFlags = INTERNET_FLAG_RELOAD /*| INTERNET_FLAG_DONT_CACHE*/ | INTERNET_FLAG_KEEP_CONNECTION;
	}

	
	m_hInetFile = HttpOpenRequest(m_hInetConnection, NULL, url.GetPath(), NULL, NULL, ppszAcceptTypes, dwFlags, (DWORD)this);
	if (m_hInetFile == NULL)
	{
		NEED_STOP;
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPENREQ,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的连接异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTOPENREQ;
	}

	if(INTERNET_DEFAULT_HTTPS_PORT == url.GetPort())
	{
		DWORD dwOptionFlags;
		DWORD dwBuffLen = sizeof(dwOptionFlags);

		InternetQueryOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS,
			(LPVOID)&dwOptionFlags, &dwBuffLen);

		dwOptionFlags |= (SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID);
		InternetSetOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS,
			&dwOptionFlags, sizeof (dwOptionFlags) );

	}

	NEED_STOP;

//	m_wcsOriginalFileName = m_strSaveFile;
	TranslanteToBreakDownloadName(m_strSaveFile, m_wcsBreakFileName);
	//GetBreakDownloadName();
	
	TCHAR szHeaders[100];
	
	_stprintf_s(szHeaders, _countof(szHeaders), _T("Moneyhubuid: %s\r\n"), m_strHWID.c_str());
	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 
	HttpAddRequestHeaders(m_hInetFile, _T("User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E)\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 
	
	if(m_bBreakDownload)
	{
		_stprintf_s(szHeaders,_countof(szHeaders),_T("Range: bytes=%d-"), IsBreakPointFile(m_wcsBreakFileName.c_str()) );
  		HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW ) ;
	}
	
	BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, NULL, 0);
	if (!bSend)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTSENDREQ,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的发送请求异常!LastErrCode = %d", GetLastError()));
		int Error = GetLastError();
		CloseHandles();
		if(Error == ERROR_INTERNET_TIMEOUT && m_bBreakDownload)
			return ERROR_INTERNET_TIMEOUT;

		return ERR_INTSENDREQ;
	}

	NEED_STOP;
	
	TCHAR szStatusCode[32];
	DWORD dwInfoSize = sizeof(szStatusCode);
	if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTQUREYINFO,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的HttpQueryInfo异常!LastErrCode = %d", GetLastError()));
//		OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTQUREYINFO;
	}
	else
	{
		long nStatusCode = _ttol(szStatusCode);
		if (nStatusCode != HTTP_STATUS_PARTIAL_CONTENT && nStatusCode != HTTP_STATUS_OK)
		{
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTFILENOTFOUND,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的!= HTTP_STATUS_OK异常!LastErrCode = %d", GetLastError()));

//		OutputDebugString(strErr);
			CloseHandles();
			return ERR_INTFILENOTFOUND;
		}
	}


	TCHAR szContentLength[32];
	dwInfoSize = sizeof(szContentLength);
	if (::HttpQueryInfo(m_hInetFile, HTTP_QUERY_CONTENT_LENGTH, szContentLength, &dwInfoSize, NULL))
	{
		if(m_bBreakDownload)
			m_ui64FileSize = (UINT64)_ttoi64(szContentLength) + IsBreakPointFile(m_wcsBreakFileName.c_str());
		else
			m_ui64FileSize = (UINT64)_ttoi64(szContentLength);
		m_ui64TotalRead = 0;
	}
	else 
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTFILENOTFOUND,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的HttpQueryInfo异常!LastErrCode = %d", GetLastError()));
//		OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTFILENOTFOUND;
	}

	NEED_STOP;

	if(m_bBreakDownload)
		return DownLoadBreakpointFile();
	else
		return DownloadNoBreakFile();
}
int CDownloadThread::TransferDataGet()
{
	CUrlCrack url;
	if (!url.Crack(m_strDownURl.c_str()))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_URLCRACKERROR,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的url = %s Crack 异常!", m_strDownURl.c_str()));
		return ERR_URLCRACKERROR;
	}

	NEED_STOP;
	
	m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
	{
		NEED_STOP;
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPEN,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的InetOpen异常!LastErrCode = %d", GetLastError()));
		return ERR_INTOPEN;
	}
	
	NEED_STOP;
	
	DWORD dwTimeOut = 60000;
	if (!InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_SETOPTION,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
	}
	if (!InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_SETOPTION,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的INTERNET_OPTION_CONTROL_SEND_TIMEOUT异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
	}
	if (!InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_SETOPTION,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的INTERNET_OPTION_SEND_TIMEOUT异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
	}
	if (!InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_SETOPTION,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的INTERNET_OPTION_RECEIVE_TIMEOUT异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
	}
	if (!InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_SETOPTION,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的INTERNET_OPTION_CONNECT_TIMEOUT异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
	}
	
	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
	if (m_hInetConnection == NULL)
	{
		NEED_STOP;
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTCONNECT,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的连接异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTCONNECT;
	}
	
	NEED_STOP;

	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;
	
	m_hInetFile = HttpOpenRequest(m_hInetConnection, NULL, url.GetPath(), NULL, NULL, ppszAcceptTypes, INTERNET_FLAG_RELOAD /*| INTERNET_FLAG_DONT_CACHE*/ | INTERNET_FLAG_KEEP_CONNECTION, (DWORD)this);
	if (m_hInetFile == NULL)
	{
		NEED_STOP;
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPENREQ,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的连接异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTOPENREQ;
	}

	NEED_STOP;

//	m_wcsOriginalFileName = m_strSaveFile;
	TranslanteToBreakDownloadName(m_strSaveFile, m_wcsBreakFileName);
	//GetBreakDownloadName();
	
	TCHAR szHeaders[100];
	
	_stprintf_s(szHeaders, _countof(szHeaders), _T("MoneyhubUID: %s\r\n"), m_strHWID.c_str());
	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 
	
	_stprintf_s(szHeaders,_countof(szHeaders),_T("Range: bytes=%d-"), IsBreakPointFile(m_wcsBreakFileName.c_str()) );
  	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW ) ;
	
	BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, NULL, 0);
	if (!bSend)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTSENDREQ,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的发送请求异常!LastErrCode = %d", GetLastError()));
//		OutputDebugString(strErr);

		CloseHandles();
		return ERR_INTSENDREQ;
	}

	NEED_STOP;
	
	TCHAR szStatusCode[32];
	DWORD dwInfoSize = sizeof(szStatusCode);
	if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTQUREYINFO,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的HttpQueryInfo异常!LastErrCode = %d", GetLastError()));
//		OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTQUREYINFO;
	}
	else
	{
		long nStatusCode = _ttol(szStatusCode);
		if (nStatusCode != HTTP_STATUS_PARTIAL_CONTENT && nStatusCode != HTTP_STATUS_OK)
		{
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTFILENOTFOUND,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的!= HTTP_STATUS_OK异常!LastErrCode = %d", GetLastError()));

//		OutputDebugString(strErr);
			CloseHandles();
			return ERR_INTFILENOTFOUND;
		}
	}


	TCHAR szContentLength[32];
	dwInfoSize = sizeof(szContentLength);
	if (::HttpQueryInfo(m_hInetFile, HTTP_QUERY_CONTENT_LENGTH, szContentLength, &dwInfoSize, NULL))
	{
		m_ui64FileSize = (UINT64)_ttoi64(szContentLength) + IsBreakPointFile(m_wcsBreakFileName.c_str());
		m_ui64TotalRead = 0;
	}
	else 
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTFILENOTFOUND,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的HttpQueryInfo异常!LastErrCode = %d", GetLastError()));
//		OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTFILENOTFOUND;
	}

	NEED_STOP;

	return DownLoadBreakpointFile();
}
Exemplo n.º 26
0
BOOL CHttpDataParser::ParseRecvData( PBYTE pRecvData,int nRecvDataLen,BOOL *pbFinalData)
{
	BOOL bAddRes = FALSE;
	do 
	{
		if ( NULL == pRecvData || nRecvDataLen == 0 )
		{
			break;
		}

		//如果还没有接受到头部,则缓存数据,等待头部
		if ( FALSE == m_bHeaderOk )
		{
			m_bufHead.AppendData(pRecvData,nRecvDataLen);
		}
		else
		{
			m_bufContent.AppendData(pRecvData,nRecvDataLen);
		}

		if ( FALSE == m_bHeaderOk )
		{
			BYTE *pHeadDataBuffer = m_bufHead.GetDataBuffer();
			LONGLONG llHeadDataLen = m_bufHead.GetTotalBufferLen();
			CHttpRecvParser recvparser;
			if (recvparser.ParseData((const char *)pHeadDataBuffer,llHeadDataLen) )
			{
				m_bHeaderOk = TRUE;

				m_nContentStart = recvparser.GetContentStart();

				int nRecvContentLen = llHeadDataLen - m_nContentStart;
				if ( nRecvContentLen > 0 )
				{
					m_bufContent.AppendData(pHeadDataBuffer+m_nContentStart,nRecvContentLen);
				}

				m_pCallback(m_pCallbackParam,pHeadDataBuffer,m_nContentStart,TRUE);

				CStringA strContentLen;
				CStringA strContentEncoding;
				CStringA strTransferEncoding;

				strContentLen = recvparser.GetValueByName("Content-Length");
				strContentEncoding = recvparser.GetValueByName("Content-Encoding");
				strTransferEncoding = recvparser.GetValueByName("Transfer-Encoding");

				if ( !strContentLen.IsEmpty() )
				{
					//没有传输编码
					m_teEncoding = TE_NO_ENCODING;
					m_llTotalContentLen = _ttoi64(CString(strContentLen));
				}
				else if( !strTransferEncoding.IsEmpty() )
				{
					//有传输编码
					if ( strTransferEncoding.CompareNoCase("chunked") == 0 )
					{
						m_teEncoding = TE_CHUNKED;
					}
					else
					{
						ASSERT(FALSE);
					}
				}
				else
				{
					m_teEncoding = TE_NO_ENCODING;
					m_llTotalContentLen = 0;
				}

				if( !strContentEncoding.IsEmpty() )
				{
					//内容有压缩编码
					if ( strContentEncoding.Find("gzip") >= 0 )
					{
						m_ceEncoding = CE_GZIP;
					}
					else
					{
						m_ceEncoding = CE_UNKNOWN;
					}
				}
				else
				{
					m_ceEncoding = CE_NO_ENCODING;
				}
			}
		}

		if ( m_bHeaderOk )
		{
			BYTE *pContentDataBuffer = m_bufContent.GetDataBuffer();
			LONGLONG llContentDataLen = m_bufContent.GetTotalBufferLen();

			if ( pContentDataBuffer && llContentDataLen )
			{
				HandleContentData( pContentDataBuffer , llContentDataLen,pbFinalData);
				m_bufContent.DestoryData();
			}
		}

		bAddRes = TRUE;

	} while (FALSE);

	return bAddRes;
}
int CHttpDownloader::TransferDataGet()
{
	CUrlCrack url;
	if (!url.Crack(m_strUrl.c_str()))
		return ERR_URLCRACKERROR;

	NEED_STOP;

	//LPCTSTR lpszUserAgent = _T("Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.1)");
	//m_hInetSession = ::InternetOpen(lpszUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
		return ERR_NETWORKERROR;

	NEED_STOP;

	DWORD dwTimeOut = 60000;
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);

	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
	if (m_hInetConnection == NULL)
	{
		//服务器连接错误,反馈 
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_NAME, MY_ERROR_ID_SERVICE, MY_ERROR_DESCRIPT_SERVICE);

		CloseHandles();
		return ERR_NETWORKERROR;
	}

	NEED_STOP;

	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;

	m_hInetFile = HttpOpenRequest(m_hInetConnection, NULL, url.GetPath(), NULL, NULL, ppszAcceptTypes, INTERNET_FLAG_RELOAD /*| INTERNET_FLAG_DONT_CACHE*/ | INTERNET_FLAG_KEEP_CONNECTION, (DWORD)this);
	if (m_hInetFile == NULL)
	{
		CloseHandles();
		return ERR_NETWORKERROR;
	}

	NEED_STOP;

	getBreakDownloadName();

	TCHAR szHeaders[100];
	//_stprintf_s(szHeaders, _countof(szHeaders), _T("MoneyhubUID: %08X%08X%08X%08X\r\n"), m_hwid.dw1, m_hwid.dw2, m_hwid.dw3, m_hwid.dw4);
	_stprintf_s(szHeaders, _countof(szHeaders), _T("MoneyhubUID: %s\r\n"), m_strHWID.c_str());
	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	_stprintf_s(szHeaders,_countof(szHeaders),_T("Range: bytes=%d-"), isBreakPointFile(m_strSaveFile.c_str()) );
  	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW ) ;

	BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, NULL, 0);
	if (!bSend)
	{
		CloseHandles();
		return ERR_NETWORKERROR;
	}

	NEED_STOP;

	TCHAR szStatusCode[32];
	DWORD dwInfoSize = sizeof(szStatusCode);
	if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL))
	{
		CloseHandles();
		return ERR_FILENOTFOUND;
	}
	else
	{
		long nStatusCode = _ttol(szStatusCode);
		if (nStatusCode != HTTP_STATUS_PARTIAL_CONTENT && nStatusCode != HTTP_STATUS_OK)
		{
			CloseHandles();
			return ERR_FILENOTFOUND;
		}
	}


	TCHAR szContentLength[32];
	dwInfoSize = sizeof(szContentLength);
	if (::HttpQueryInfo(m_hInetFile, HTTP_QUERY_CONTENT_LENGTH, szContentLength, &dwInfoSize, NULL))
	{
		m_ui64FileSize = (UINT64)_ttoi64(szContentLength) + isBreakPointFile(m_strSaveFile.c_str());
		if (m_pUpdateMgr)
			m_pUpdateMgr->SetProgressVal(m_ui64FileSize, 0);
	}
	else 
	{
		CloseHandles();
		return ERR_FILENOTFOUND;
	}

	NEED_STOP;

	return this->downLoadBreakpointFile();
}
Exemplo n.º 28
0
void COptions::Init()
{
	if (m_bInitialized)
		return;
	simple_lock lock(m_mutex);
	m_bInitialized = TRUE;

	for (int i = 0; i < OPTIONS_NUM; ++i)
		m_sOptionsCache[i].bCached = FALSE;

	USES_CONVERSION;
	CStdString xmlFileName = GetExecutableDirectory() + _T("FileZilla Server.xml");
	char* bufferA = T2A(xmlFileName);
	if (!bufferA) {
		return;
	}

	TiXmlDocument document;

	WIN32_FILE_ATTRIBUTE_DATA status{};
	if (!GetStatus64(xmlFileName, status) ) {
		document.LinkEndChild(new TiXmlElement("FileZillaServer"));
		document.SaveFile(bufferA);
	}
	else if (status.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
		return;
	}

	if (!document.LoadFile(bufferA)) {
		return;
	}

	TiXmlElement* pRoot = document.FirstChildElement("FileZillaServer");
	if (!pRoot) {
		return;
	}

	TiXmlElement* pSettings = pRoot->FirstChildElement("Settings");
	if (!pSettings)
		pSettings = pRoot->LinkEndChild(new TiXmlElement("Settings"))->ToElement();

	TiXmlElement* pItem;
	for (pItem = pSettings->FirstChildElement("Item"); pItem; pItem = pItem->NextSiblingElement("Item")) {
		const char* pName = pItem->Attribute("name");
		if (!pName)
			continue;
		CStdString name(pName);

		const char* pType = pItem->Attribute("type");
		if (!pType)
			continue;
		CStdString type(pType);

		TiXmlNode* textNode = pItem->FirstChild();
		CStdString value;
		if (textNode && textNode->ToText())
			value = ConvFromNetwork(textNode->Value());
		else if (type == _T("numeric"))
			continue;

		for (int i = 0; i < OPTIONS_NUM; ++i) {
			if (!_tcscmp(name, m_Options[i].name)) {
				if (m_sOptionsCache[i].bCached)
					break;

				if (type == _T("numeric")) {
					if (m_Options[i].nType != 1)
						break;
					_int64 value64 = _ttoi64(value);
					if (IsNumeric(value))
						SetOption(i + 1, value64, false);
				}
				else {
					if (m_Options[i].nType != 0)
						break;
					SetOption(i + 1, value, false);
				}
				break;
			}
		}
	}
	ReadSpeedLimits(pSettings);

	UpdateInstances();
}
Exemplo n.º 29
0
DWORD CFileDownloader::Download( LPCTSTR lpszURL, LPCTSTR lpszFilename, LPCTSTR lpszRefererUrl, LPVOID pUserData, BOOL bUseCache, BOOL bUseProxyConfig )
{
	m_Stopped = FALSE;
	if(!SplitDownloadUrl( lpszURL, m_strHostname, m_strHostPath, m_strHostFilename ))
		return FALSE;
	
	m_pUserData = pUserData;
	m_strDownloadURL = lpszURL;
	m_strDownloadFile = lpszFilename;

	// Check the tmp file 
	m_strDownloadFileTemp = m_strDownloadFile + _T(".tmp");
	m_strDownloadFileInfo = m_strDownloadFile + _T(".nfo");		
	
	// Check if file exists 
	if( bUseCache && IsFileExist(m_strDownloadFile) )
	{
		return TRUE;
	}
	else if(!bUseCache)
	{
		DeleteFile(m_strDownloadFileTemp);
		DeleteFile(m_strDownloadFileInfo);
		DeleteFile(m_strDownloadFile);
	}
	
	CPubConfig::T_ProxySetting proxyconfig;
	CPubConfig pubconfig;
	pubconfig.LoadProxyConfig(proxyconfig);	
	SetProxySetting(proxyconfig);


	INT64 lContentSize = 0;
	INT64 lFileSize = 0;
	if( IsFileExist(m_strDownloadFileTemp) && IsFileExist(m_strDownloadFileInfo) )
	{
		CString strLastModified;
		BOOL notModified = FALSE;
		if( file_get_contents(m_strDownloadFileInfo, strLastModified) )		
		{
			LPCTSTR lpszLengthTag = _T("; length=");
			LPCTSTR pszLen = _tcsstr(strLastModified, lpszLengthTag);
			if(pszLen)
			{
				pszLen+= _tcslen(lpszLengthTag);
				lContentSize = _ttoi64(pszLen);
			}

			// 检查文件是否完全下载完成了 
			lFileSize = file_get_size( m_strDownloadFileTemp );
			if(lFileSize>0 && lFileSize==lContentSize)
			{
				MoveFile(m_strDownloadFileTemp, m_strDownloadFile);
				DeleteFile(m_strDownloadFileInfo);
				return TRUE;
			}

			if( _CheckIfModifiedSince(lpszURL, strLastModified, bUseProxyConfig, notModified) && notModified )
			{
			}
			else
			{
				lFileSize = 0;
			}
		}
	}
	// 如果文件已经过期, 或者文件的信息文件不存在, 都删除旧下载临时文件 
	if(lFileSize==0)
	{
		DeleteFile(m_strDownloadFileTemp);
		DeleteFile(m_strDownloadFileInfo);
	}
	
	// Prepare file 
	_CloseFileHandler();
	m_hFile = CreateFile(m_strDownloadFileTemp, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if( m_hFile==INVALID_HANDLE_VALUE )
		return FALSE;
	SetFilePointer( m_hFile, lFileSize, 0, FILE_BEGIN );
	
	if(m_pBuffer==NULL)
		m_pBuffer = new BYTE[HTTP_BUFFER_SIZE];	
	INT nRetry = HTTP_DEFAULT_RETYR;
	INT nRetried = 0;
	do 
	{
		INT iRet = _DownloadFileFrom(lFileSize, lContentSize, bUseProxyConfig);
		DEBUG_TRACE(_T("FD:_DownloadFileFrom %I64d/%I64d LastError:%d Ret:%d"), lFileSize, lContentSize, GetLastError(), iRet);
		_Cleanup();

		if(iRet>0)
		{
			// 考虑socket 被主动关闭 
			if(lFileSize>=lContentSize)
				break;
			nRetry = HTTP_DEFAULT_RETYR;
		}
		else if(iRet==0)
		{
			--nRetry;
		}
		else if(iRet==-1)
		{
			// 文件长度不匹配! 需要删了文件, 然后重新下载 
			_CloseFileHandler();
			DeleteFile(m_strDownloadFileTemp);
			DeleteFile(m_strDownloadFileInfo);
			lFileSize = lContentSize = 0;
			
			m_hFile = CreateFile(m_strDownloadFileTemp, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
			if( m_hFile==INVALID_HANDLE_VALUE )
				break;
			--nRetry;
		}
		else if(iRet==-2)
		{
			// 写入文件失败, 直接返回
			break;
		}
		else
		{
			ATLASSERT(FALSE);
			break;
		}
		++ nRetried;
	} while (!m_Stopped && nRetry>0 && nRetried<HTTP_DEFAULT_MAXRETYR);
	
	_CloseFileHandler();
	BOOL bFileDone = FALSE;
	if(lContentSize==0)
	{
		// 163.com 等页面
		if(lFileSize==0)
		{
			DeleteFile(m_strDownloadFileTemp);
		}
		else if(!m_Stopped)
		{
			bFileDone = TRUE;
		}
	}
	else
	{
		bFileDone = lFileSize>=lContentSize;
	}
	if(bFileDone)
	{
		MoveFile(m_strDownloadFileTemp, m_strDownloadFile);
		DeleteFile(m_strDownloadFileInfo);
	}
	BOOL bRet = PathFileExists(m_strDownloadFile);
	_FireFileDownloaderEvent(bRet ? IFileDownloaderObserver::DOWNLOAD_COMPLETE : IFileDownloaderObserver::DOWNLOAD_ERROR);
	return bRet;
}
Exemplo n.º 30
0
void ValidateArgs( int argc, TCHAR **argv )
{
	if (argc == 1)
	{
		Usage();
	}
	else
	{
		for (int i = 1;i < argc;i++)
		{
			if (argv[i][0] == _T('-') || argv[i][0] == _T('/'))
			{
				TCHAR tcFlag = argv[i][1];
				switch (tolower(tcFlag))
				{
				case _T('d'):
					if (_tcslen(argv[i]) > 3)
					{
						_tcscpy(g_szDeviceName,_T("\\\\.\\PhysicalDrive"));
						//_tcscpy(g_szDeviceName,_T("\\\\.\\"));
						_tcscat(g_szDeviceName,&argv[i][3]);
						g_nDiskNum = _ttoi64(&argv[i][3]);
					}
					break;

				case _T('r'):
					g_bRead = TRUE;
					if (_tcslen(argv[i]) > 3)
					{
						g_ullStartSector = _ttoi64(&argv[i][3]);

						TCHAR *pszSectors = _tcsrchr(argv[i],_T('-'));

						if (pszSectors != NULL && _tcslen(pszSectors) > 1)
						{
							g_ullSectors = _ttoi64(pszSectors+1);
						}
					}
					break;

				case _T('w'):
					g_bWrite = TRUE;
					if (_tcslen(argv[i]) > 3)
					{
						g_ullStartSector = _ttoi64(&argv[i][3]);

						TCHAR *pszSectors = _tcschr(argv[i],_T('-'));

						if (pszSectors != NULL)
						{
							g_ullSectors = _ttoi64(pszSectors+1);
						}
					}
					break;

				case _T('f'):
					if (_tcslen(argv[i]) > 3)
					{
						memset(g_szFileName,0,sizeof(g_szFileName));
						_tcscpy(g_szFileName,&argv[i][3]);
					}
					break;

				case _T('v'):
					g_bVerify = TRUE;
					break;

				case _T('e'):
					g_bErase = TRUE;
					break;

				default:
					Usage();
					break;

				}
			}
		}
	}
	
}