void CMHttpSNotify::OnRecv(UINT32 nCode, INT32 nLen)
{
    if (nCode == MER_OK)
    {
        //是不是请求头
        INT32 nTmp = nLen;
        if (!m_cReqHeader.Parse(m_pHeadBuf, nTmp))
        {
            m_nHeadPos += nLen;
            if (nTmp == -1 && m_nHeadPos < REQ_HEAD_MAX_LEN)
            {
                //可能头还没收全,继续收
                CM_LOGP(CM_LOGL_DEBUG, "CMHttpSNotify::OnRecv header part %d",  nLen);
                m_pSocketC->Recv(m_pHeadBuf + m_nHeadPos , REQ_HEAD_MAX_LEN - m_nHeadPos);
                return;
            }
            CM_LOGP(CM_LOGL_DEBUG, "CMHttpSNotify::OnRecv header failed is %s", (const CHAR*)CMString((const CHAR*)m_pHeadBuf, nLen));
            return;
        }

        CMString sRange;
        m_cReqHeader.GetValue(HH_RANGER, sRange);

        //是外部请求,构造CMHttp请求
        m_rUrl = m_pHttpS->ToRemote(m_cReqHeader.GetUrl());
        if (!m_rUrl.Url().IsEmpty())
        {
            CMHTTPReqHeader header;
            header.CreateDefault();

            if (sRange.IsEmpty())
            {
				if(CMNetConnMgr::Instance().CurrentType() == CMNetConnMgr::CMWAP)
	            {
    	            sRange.Format(L"bytes = 0-%d", REQ_SIZE - 1);
                    header.AddValue(HH_RANGER, sRange);
	            }
	            else
                {
                    //请求没有指定range,不发送此参数	
                }
            }
            else
            {
                //暂时此流程不支持
                ASSERT(FALSE);
             //   if(CMGlobal::TheOne().NetConnMgr().CurrentType() == CMNetConnMgr::CMWAP)
	            //{
             //       //如果请求包含range信息,对于跨CMWAP网关也需要处理
             //       UINT32 nStart = 0;
             //       UINT32 nEnd = 0;

             //       INT32 nPos1 = sRange.Find(L"-");
             //       if (nPos1 > 0)
             //       {
             //           INT32 nPos2 = sRange.Find(L"=");
             //           nStart= _mwtoi((const WCHAR*)sRange.Mid(nPos2 + 2, nPos1 - nPos2 - 2));
             //           INT32 nLen = sRange.GetLength();
             //           if (nLen > nPos1 + 1)
             //           {
             //               nEnd = _mwtoi((const WCHAR*)sRange.Mid(nPos2 + 1, nLen - 1));
             //           }
             //       }

             //       if (nEnd != 0)
             //       {
             //           m_nSendSize = nEnd - nStart + 1;
             //       }
             //       else
             //       {
             //           m_nSendSize = m_pFile->GetLength() - nStart;
             //           nEnd = nStart + m_nSendSize - 1;
             //       }
             //   }
             //   else
             //       header.AddValue(HH_RANGER, sRange);
            }

            header.SetUrl(m_rUrl);
            m_pHttpC->Request(header);
            m_nStatus = 1;
            return;
        }

        //是本地文件请求,构造发送信息
        //const CMString* pFile = m_pHttpS->GetFile(m_cReqHeader.GetUrl());
        //if (pFile)
        //{
        //    if (!m_pFile)
        //    {
        //        m_pFile = new CMFile();
        //    }
        //    if (!m_pFile->Open(*pFile, CMFile::OPEN_R_EXIST, CMFile::SHARE_R))
        //    {
        //        //打开失败
        //        CM_ERRP("CMHttpSNotify::OnRecv Open file  %s not exist", (const CHAR*)CMString(*pFile));
        //        return;
        //    }

        //    UINT32 nStart = 0;
        //    UINT32 nEnd = 0;
        //    if (!sRange.IsEmpty())
        //    {
        //        INT32 nPos1 = sRange.Find(L"-");
        //        if (nPos1 > 0)
        //        {
        //            INT32 nPos2 = sRange.Find(L"=");
        //            nStart= _mwtoi((const WCHAR*)sRange.Mid(nPos2 + 2, nPos1 - nPos2 - 2));
        //            INT32 nLen = sRange.GetLength();
        //            if (nLen > nPos1 + 1)
        //            {
        //                nEnd = _mwtoi((const WCHAR*)sRange.Mid(nPos2 + 1, nLen - 1));
        //            }
        //        }
        //    }

        //    if (nStart != 0)
        //        m_pFile->Seek(nStart);
        //    if (nEnd != 0)
        //    {
        //        m_nSendSize = nEnd - nStart + 1;
        //    }
        //    else
        //    {
        //        m_nSendSize = m_pFile->GetLength() - nStart;
        //        nEnd = nStart + m_nSendSize - 1;
        //    }

        //    //获取成功,返回响应头结果到Socket处
        //    CMHTTPRspHeader resp;
        //    resp.SetRet(200, CMString("OK"));
        //    if (!sRange.IsEmpty())
        //    {
        //        //如果有range,就要返回range,  bytes 0-2668566/2668567
        //        CMString sSendRange;
        //        sSendRange.Format(L"bytes %d-%d/%d", nStart, nEnd, m_nSendSize);
        //        resp.AddValue(HH_CRANGE, sSendRange);
        //    }
        //    else
        //    {
        //        //否则返回content-lengthW
        //        CMString sSendSize;
        //        sSendSize.Format(L"%d", m_nSendSize);
        //        resp.AddValue(HH_CLENGTH, sSendSize);
        //    }
        //    resp.AddValue(HH_CTYPE, L"application/x-shockwave-flash");
        //    CMString sHeader = resp.ToString();
        //    CM_LOGP(CM_LOGL_DEBUG, "%s", (const CHAR*)sHeader);

        //    m_pSocketC->Send((const INT8*)(const CHAR*)sHeader, sHeader.GetLength());

        //    m_nStatus = 3;
        //    return;
        //}
    }
    else
    {
        CM_ERRP("CMHttpSNotify::OnRecv ret %d error", nCode);
    }
err:
    //未成功获取信息,清理,等待下次获取

    m_bInService = FALSE;
    m_nSize = 0;

    if (nCode == MERN_TIMEOUT)
    {
        m_pSocketC->Close();
    }
    else
    {
        char response[] = "HTTP/1.1 404 NOT FOUND\r\n\r\n";
        m_pSocketC->Send((INT8*)response, strlen(response));
    }

    //重置http
    m_pHttpC->Cancel();

}
void CMHttpSNotify::OnSend(UINT32 nCode, INT32 nLen)
{
    if (nCode == MER_OK)
    {
        switch(m_nStatus)
        {
        case 1:
            if (m_nSize != 0)
            {
                nLen = m_nSize; //重用nLen
                if (m_nSize > BUF_SIZE)
                {
                    nLen = BUF_SIZE;
                }

                m_pHttpC->Read(m_pBuf, nLen);

                m_nStatus = 2;
            }
            else
            {
                //m_nSize为0表示有错误,中止继续操作
                CM_ERR("CMHttpSNotify::OnSend 0");
                m_pSocketC->Close();
            }
            break;
        case 2:
            if (nLen < m_nSendSize)
            {
                m_nPos += nLen;
                m_nSendSize -= nLen;
                m_pSocketC->Send(m_pBuf + m_nPos, m_nSendSize);
            }
            else
            {
                //判断是否完成
                if (m_nSize > 0)
                {
                    //还有剩余,继续请求
                    nLen = m_nSize;  //nLen无意义了,复用下
                    if (m_nSize > BUF_SIZE)
                    {
                        nLen = BUF_SIZE;
                    }
                    m_pHttpC->Read(m_pBuf, nLen);
                }
                else if (m_nTotalSize > 0 && m_nEnd < m_nTotalSize - 1)
                {
                    //仅当前http请求完毕,
                    CMHTTPReqHeader header;
                    header.CreateDefault();

                    CMString sRange;
                    if (m_nEnd + REQ_SIZE < m_nTotalSize - 1)
                        sRange.Format(L"bytes = %d-%d", m_nEnd + 1, m_nEnd + REQ_SIZE);
                    else
                        sRange.Format(L"bytes = %d-", m_nEnd + 1);
                    header.AddValue(HH_RANGER, sRange);
                    header.SetUrl(m_rUrl);
                    m_pHttpC->Request(header);
                }
                else
                {
                    //已完成,开始等待后续接收
                    Start();
                    //m_bInService = FALSE;
                    //m_pSocketC->Close();
                    //m_pHttpC->Cancel();
                }
            }
            break;
        case 3:

            if (m_nSendSize > BUF_SIZE)
            {
                nLen = BUF_SIZE;
            }
            else
            {
                nLen = m_nSendSize;
            }
            //if (m_pBuf)
            //{
            //    delete m_pBuf;
            //    m_pBuf = NULL;
            //}
            //m_pBuf = new INT8[nLen + 1];
            m_nPos = 0;
            m_pFile->Read((CHAR*)m_pBuf, nLen);
            m_pSocketC->Send(m_pBuf, nLen);
            m_nStatus = 4;
            break;
        case 4:
            if (nLen < m_nSendSize && m_nPos + nLen < BUF_SIZE)   
            {
                //没有发送完
                m_nPos += nLen;
                m_nSendSize -= nLen;
                m_pSocketC->Send(m_pBuf + m_nPos, m_nSendSize);
            }
            else
            {
                m_nSendSize -= nLen;
                if (m_nSendSize > 0)
                {
                    nLen = m_nSendSize;
                    if (m_nSendSize > BUF_SIZE)
                    {
                        nLen = BUF_SIZE;
                    }
                    m_nPos = 0;
                    m_pFile->Read((CHAR*)m_pBuf, nLen);
                    m_pSocketC->Send(m_pBuf, nLen);
                }
                else
                {
                    //已完成,开始等待后续接收
                    Start();
                    //m_bInService = FALSE;
                    //m_pHttpC->Cancel();
                }
            }
            break;
        default:
            CM_ERR("CMHttpSNotify::OnSend status 0");
        }

        return;
    }

    CM_ERRP("CMHttpSNotify::OnSend ret %d error", nCode);
    m_bInService = FALSE;
    m_pSocketC->Close();
    m_pHttpC->Cancel();

}
void CMHttpSNotify::OnResponse(UINT32 nCode, const CMHTTPRspHeader* pRespHeader)
{
    UINT32 nRet = MER_OK;
    if (nCode == MER_OK)
    {
        ASSERT(pRespHeader != NULL);

        UINT32 httpRet = pRespHeader->GetHttpReturn();

        if (httpRet == 200 || httpRet == 206)
        {
            CMString sVal;

            //判断是否wap网关的无聊返回,如果是则继续请求一次
            if (pRespHeader->GetValue(HH_CTYPE, sVal))
            {
                if (sVal.Find(L"text/vnd.wap.wml") >= 0)
                {
                    m_pHttpC->Request();
                    return;
                }
            }            

            sVal.Empty();
            pRespHeader->GetValue(HH_CRANGE, sVal);

            sVal.Trim();

            CMHTTPRspHeader header;
            header.SetRet(200, CMString("OK"));
            header.AddValue(HH_CTYPE, L"application/x-shockwave-flash");

            if (!sVal.IsEmpty())
            {
                INT32 nPos1 = sVal.Find(L" ");
                INT32 nPos2 = sVal.Find(L"-");
                INT32 nPos3 = sVal.Find(L"/");
                if (nPos1 <= 0 || nPos2 <= 0 || nPos3 <= 0)
                {
                    CM_ERRP("CMHttpSNotify::OnResponse wrong content-range %s", (const CHAR*)sVal);
                    goto err;
                }

                m_nStart= _mwtoi((const WCHAR*)sVal.Mid(nPos1 + 1, nPos2 - nPos1 - 1));
                m_nEnd = _mwtoi((const WCHAR*)sVal.Mid(nPos2 + 1, nPos3 - nPos2 - 1));
                m_nSize = m_nEnd - m_nStart + 1;

                if (m_nTotalSize == 0)
                {
                    //对于第一次http返回,需要返回结果给socket
                    m_nTotalSize = _mwtoi((const WCHAR*)sVal.Mid(nPos3 + 1));
                    CMString sSendSize;
                    sSendSize.Format(L"%d", m_nTotalSize);
                    header.AddValue(HH_CLENGTH, sSendSize);
                    CMString sHeader = header.ToString();

                    CM_LOGP(CM_LOGL_INFO, "%s", (const CHAR*)sHeader);

                    m_pSocketC->Send((INT8*)(const CHAR*)sHeader, sHeader.GetLength());
                }
                else
                {
                    ASSERT(m_nTotalSize == _mwtoi((const WCHAR*)sVal.Mid(nPos3 + 1)));
                    ASSERT(m_nStatus == 2);
                    ASSERT(m_nEnd - m_nStart < REQ_SIZE);

                    UINT32 nLen = m_nSize;
                    if (m_nSize > BUF_SIZE)
                    {
                        nLen = BUF_SIZE;
                    }
                    m_pHttpC->Read(m_pBuf, nLen);
                }
            }
            else
            {
                if (!pRespHeader->GetValue(HH_CLENGTH, sVal))
                {
                    CM_ERR("CMHttpSNotify::OnResponse no content-length");
                    goto err;
                }

                m_nTotalSize = 0;  //此值无效
                m_nSize = _mwtoi(sVal);

                //获取响应头成功,返回结果到Socket处
                CMString sSendSize;
                sSendSize.Format(L"%d", m_nSize);
                header.AddValue(HH_CLENGTH, sSendSize);
                CMString sHeader = header.ToString();

                CM_LOGP(CM_LOGL_INFO, "%s", (const CHAR*)sHeader);

                m_pSocketC->Send((INT8*)(const CHAR*)sHeader, sHeader.GetLength());
            }
           
            return;
        }
        else
        {
            CM_ERRP("CMHttpSNotify::OnResponse http ret %d error", httpRet);
            nRet = httpRet;
        }
    }
    else
    {
        CM_ERRP("CMHttpSNotify::OnResponse ret %d error", nCode);
        nRet = nCode;
    }

err:
    //未成功获取信息,清理,等待下次获取
    //if (m_pBuf)
    //{
    //    delete m_pBuf;
    //    m_pBuf = NULL;
    //}

    m_bInService = FALSE;

    //if (nCode == MERN_TIMEOUT)
    //{
    //    m_pSocketC->Close();
    //}
    //else
    //{
        char response[] = "HTTP/1.1 404 NOT FOUND\r\n\r\n";
        m_nSize = 0;
        m_pSocketC->Send((INT8*)response, strlen(response));
    //}

    //重置http
    m_pHttpC->Cancel();
}
Example #4
0
INT addEvent(WPARAM hContact, LPARAM hDBEvent)
{
	BOOL fEnabled = db_get_b(NULL, protocolname, KEY_ENABLED, 1);
	if (!fEnabled || !hContact || !hDBEvent)
		return FALSE;	/// unspecifyed error

	char* pszProto = GetContactProto(hContact);
	int status = CallProtoService(pszProto, PS_GETSTATUS, 0, 0);
	if (status == ID_STATUS_ONLINE || status == ID_STATUS_FREECHAT || status == ID_STATUS_INVISIBLE)
		return FALSE;

	// detect size of msg
	DBEVENTINFO dbei = { sizeof(dbei) };
	if (db_event_get(hDBEvent, &dbei))
		return 0;

	if ((dbei.eventType != EVENTTYPE_MESSAGE) || (dbei.flags == DBEF_READ)) {
		// we need EVENTTYPE_MESSAGE event..
		return FALSE;
	}
	else {
		// needed event has occured..
		if (!dbei.cbBlob)	/// invalid size
			return FALSE;

		TCHAR *ptszVal = db_get_tsa(hContact, "Protocol", "p");
		if (ptszVal == NULL) // Contact with no protocol ?!!
			return FALSE;
		mir_free(ptszVal);

		if (db_get_b(hContact, "CList", "NotOnList", 0))
			return FALSE;

		if (db_get_b(hContact, protocolname, "TurnedOn", 0))
			return FALSE;

		if (!(dbei.flags & DBEF_SENT)) {
			int timeBetween = time(NULL) - db_get_dw(hContact, protocolname, "LastReplyTS", 0);
			if (timeBetween > interval || db_get_w(hContact, protocolname, "LastStatus", 0) != status) {
				size_t msgLen = 1;
				int isQun = db_get_b(hContact, pszProto, "IsQun", 0);
				if (isQun)
					return FALSE;

				char szStatus[6] = { 0 };
				mir_snprintf(szStatus, "%d", status);
				ptszVal = db_get_tsa(NULL, protocolname, szStatus);
				if (ptszVal) {
					if (*ptszVal) {
						CMString ptszTemp;

						TCHAR *ptszNick = db_get_tsa(hContact, pszProto, "Nick");
						if (ptszNick == 0) {
							mir_free(ptszVal);
							return FALSE;
						}

						msgLen += mir_tstrlen(ptszVal);

						TCHAR *ptszHead = db_get_tsa(NULL, protocolname, KEY_HEADING);
						if (ptszHead != NULL) {
							ptszTemp = ptszHead;
							ptszTemp.Replace(_T("%user%"), ptszNick);
							msgLen += mir_tstrlen(ptszTemp);
							mir_free(ptszHead);
						}

						TCHAR *ptszTemp2 = (TCHAR*)mir_alloc(sizeof(TCHAR) * (msgLen + 5));
						mir_sntprintf(ptszTemp2, msgLen + 5, _T("%s\r\n\r\n%s"), ptszTemp.c_str(), ptszVal);
						if (ServiceExists(MS_VARS_FORMATSTRING)) {
							ptszTemp = variables_parse(ptszTemp2, 0, hContact);
						}
						else ptszTemp = Utils_ReplaceVarsT(ptszTemp2);

						T2Utf pszUtf(ptszTemp);
						CallContactService(hContact, PSS_MESSAGE, 0, pszUtf);

						dbei.cbSize = sizeof(dbei);
						dbei.eventType = EVENTTYPE_MESSAGE;
						dbei.flags = DBEF_UTF | DBEF_SENT; //DBEF_READ;
						dbei.szModule = pszProto;
						dbei.timestamp = time(NULL);
						dbei.cbBlob = (int)mir_strlen(pszUtf) + 1;
						dbei.pBlob = (PBYTE)pszUtf;
						db_event_add(hContact, &dbei);

						mir_free(ptszTemp2);
						mir_free(ptszNick);
					}
					mir_free(ptszVal);
				}
			}
		}

		db_set_dw(hContact, protocolname, "LastReplyTS", time(NULL));
		db_set_w(hContact, protocolname, "LastStatus", status);
	}
	return 0;
}
Example #5
0
BOOL CIrcProto::CList_AddDCCChat(const CMString& name, const CMString& hostmask, unsigned long adr, int port) 
{
	HANDLE hContact;
	HANDLE hc;
	TCHAR szNick[256];
	char szService[256];
	bool bFlag = false;

	CONTACT usertemp = { (TCHAR*)name.c_str(), NULL, NULL, false, false, true};
	hc = CList_FindContact( &usertemp );
	if ( hc && db_get_b( hc, "CList", "NotOnList", 0) == 0
		&& db_get_b(hc,"CList", "Hidden", 0) == 0)
	{
		bFlag = true;
	}

	CMString contactname = name; contactname += _T(DCCSTRING);

	CONTACT user = { (TCHAR*)contactname.c_str(), NULL, NULL, false, false, true};
	hContact = CList_AddContact(&user, false, false);
	setByte(hContact, "DCC", 1);

	DCCINFO* pdci = new DCCINFO;
	pdci->sHostmask = hostmask;
	pdci->hContact = hContact;
	pdci->dwAdr = (DWORD) adr;
	pdci->iPort = port;
	pdci->iType = DCC_CHAT;
	pdci->bSender = false;
	pdci->sContactName = name;

	if ( m_DCCChatAccept == 3 || m_DCCChatAccept == 2 && bFlag ) {
		CDccSession* dcc = new CDccSession( this, pdci );

		CDccSession* olddcc = FindDCCSession(hContact);
		if ( olddcc )
			olddcc->Disconnect();

		AddDCCSession(hContact, dcc);
		dcc->Connect();
		if (getByte( "MirVerAutoRequest", 1))
		  PostIrcMessage( _T("/PRIVMSG %s \001VERSION\001"), name.c_str());
	}
	else {
		CLISTEVENT cle = {0};
		cle.cbSize = sizeof(cle);
		cle.hContact = (HANDLE)hContact;
		cle.hDbEvent = (HANDLE)"dccchat";	
		cle.flags = CLEF_TCHAR;
		cle.hIcon = LoadIconEx(IDI_DCC);
		mir_snprintf(szService, sizeof(szService),"%s/DblClickEvent", m_szModuleName);
		cle.pszService = szService;
		mir_sntprintf(szNick, SIZEOF(szNick), TranslateT("CTCP chat request from %s"), name.c_str());
		cle.ptszTooltip = szNick;
		cle.lParam = (LPARAM)pdci;

		if ( CallService(MS_CLIST_GETEVENT, (WPARAM)hContact, 0))
			CallService(MS_CLIST_REMOVEEVENT, (WPARAM)hContact, (LPARAM)"dccchat");
		CallService(MS_CLIST_ADDEVENT,(WPARAM) hContact,(LPARAM) &cle);
	}
	return TRUE;
}
Example #6
0
void CVkProto::OnReciveUpload(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq)
{
	CVkFileUploadParam *fup = (CVkFileUploadParam *)pReq->pUserInfo;
	if (!IsOnline()) {
		SendFileFiled(fup, VKERR_OFFLINE);
		return;
	}

	debugLogA("CVkProto::OnReciveUploadServer %d", reply->resultCode);
	if (reply->resultCode != 200) {
		SendFileFiled(fup, VKERR_FILE_NOT_UPLOADED);
		return;
	}

	JSONNode jnRoot;
	CheckJsonResponse(pReq, reply, jnRoot);

	if (pReq->m_iErrorCode) {
		SendFileFiled(fup, pReq->m_iErrorCode);
		return;
	}

	if ((!jnRoot["server"] || !jnRoot["hash"]) && !jnRoot["file"]) {
		SendFileFiled(fup, VKERR_INVALID_PARAMETERS);
		return;
	}

	CMString server(jnRoot["server"].as_mstring());
	CMString hash(jnRoot["hash"].as_mstring());
	CMString upload;

	AsyncHttpRequest *pUploadReq;

	ProtoBroadcastAck(fup->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTED, (HANDLE)fup);

	switch (fup->GetType()) {
	case CVkFileUploadParam::typeImg:
		upload = jnRoot["photo"].as_mstring();
		if (upload == _T("[]")) {
			SendFileFiled(fup, VKERR_INVALID_PARAMETERS);
			return;
		}
		pUploadReq = new AsyncHttpRequest(this, REQUEST_GET, "/method/photos.saveMessagesPhoto.json", true, &CVkProto::OnReciveUploadFile)
			<< TCHAR_PARAM("server", server)
			<< TCHAR_PARAM("photo", upload)
			<< TCHAR_PARAM("hash", hash)
			<< VER_API;
		break;
	case CVkFileUploadParam::typeAudio:
		upload = jnRoot["audio"].as_mstring();
		if (upload == _T("[]")) {
			SendFileFiled(fup, VKERR_INVALID_PARAMETERS);
			return;
		}
		pUploadReq = new AsyncHttpRequest(this, REQUEST_GET, "/method/audio.save.json", true, &CVkProto::OnReciveUploadFile)
			<< TCHAR_PARAM("server", server)
			<< TCHAR_PARAM("audio", upload)
			<< TCHAR_PARAM("hash", hash)
			<< VER_API;
		break;
	case CVkFileUploadParam::typeDoc:
		upload = jnRoot["file"].as_mstring();
		if (upload.IsEmpty()) {
			SendFileFiled(fup, VKERR_INVALID_PARAMETERS);
			return;
		}
		pUploadReq = new AsyncHttpRequest(this, REQUEST_GET, "/method/docs.save.json", true, &CVkProto::OnReciveUploadFile)
			<< CHAR_PARAM("title", fup->fileName())
			<< TCHAR_PARAM("file", upload)	
			<< VER_API;
		break;
	default:
		SendFileFiled(fup, VKERR_FTYPE_NOT_SUPPORTED);
		return;
	}

	pUploadReq->pUserInfo = pReq->pUserInfo;
	Push(pUploadReq);
}
Example #7
0
bool SmileyPackType::LoadSmileyFile(const CMString& filename, const CMString& packname, bool onlyInfo, bool noerr)
{
	Clear();

	if (filename.IsEmpty()) {
		m_Name = _T("Nothing loaded");
		return false;
	}

	CMString modpath;
	pathToAbsolute(filename, modpath);

	// Load xep file
	int fh = _topen(modpath.c_str(), _O_BINARY | _O_RDONLY);
	if (fh == -1) {
		if (!noerr) {
			static const TCHAR errmsg[] = LPGENT("Smiley pack %s for category \"%s\" not found.\nSelect correct smiley pack in the Options -> Customize -> Smileys.");
			TCHAR msgtxt[1024];
			mir_sntprintf(msgtxt, TranslateTS(errmsg), modpath.c_str(), packname);
			ReportError(msgtxt);
		}

		m_Name = _T("Nothing loaded");
		return false;
	}

	m_Filename = filename;

	// Find file size
	const long flen = _filelength(fh);

	// Allocate file buffer
	char* buf = new char[flen + sizeof(wchar_t)];

	// Read xep file in
	int len = _read(fh, buf, flen);
	*(wchar_t*)(buf + len) = 0;

	// Close file
	_close(fh);

	CMString tbuf;

	if (len > 2 && *(wchar_t*)buf == 0xfeff)
		tbuf = W2T_SM((wchar_t*)buf + 1);
	else if (len > 3 && buf[0] == '\xef' && buf[1] == '\xbb' && buf[2] == '\xbf')
		tbuf = W2T_SM(A2W_SM(buf + 3, CP_UTF8));
	else
		tbuf = A2T_SM(buf);

	delete[] buf;

	bool res;
	if (filename.Find(_T(".xep")) == -1)
		res = LoadSmileyFileMSL(tbuf, onlyInfo, modpath);
	else
		res = LoadSmileyFileXEP(tbuf, onlyInfo, modpath);

	if (errorFound)
		ReportError(TranslateT("There were problems loading smiley pack (it should be corrected).\nSee network log for details."));

	return res;
}
Example #8
0
void PrintVersionInfo(CMString& buffer, unsigned flags)
{
	GetProcessorString(buffer);
	buffer.Append(TEXT("\r\n"));

	GetFreeMemoryString(buffer);
	buffer.Append(TEXT("\r\n"));

	GetOSDisplayString(buffer);
	buffer.Append(TEXT("\r\n"));

	GetInternetExplorerVersion(buffer);
	buffer.Append(TEXT("\r\n"));

	GetAdminString(buffer);
	buffer.Append(TEXT("\r\n"));

	GetLanguageString(buffer);
	buffer.Append(TEXT("\r\n"));

	TCHAR *profpathfull = Utils_ReplaceVarsT(profpath);
	if (flags & VI_FLAG_PRNVAR) {
		GetFreeDiskString(profpathfull, buffer);
		buffer.Append(TEXT("\r\n"));
	}

	buffer.AppendFormat(TEXT("\r\nMiranda NG Version: %s"), vertxt);
	GetWow64String(buffer);
	buffer.Append(TEXT("\r\n"));

	TCHAR path[MAX_PATH], mirtime[30];
	GetModuleFileName(NULL, path, MAX_PATH);
	GetLastWriteTime(path, mirtime, 30);
	buffer.AppendFormat(TEXT("Build time: %s\r\n"), mirtime);

	TCHAR profpn[MAX_PATH];
	mir_sntprintf(profpn, SIZEOF(profpn), TEXT("%s\\%s"), profpathfull, profname);

	buffer.AppendFormat(TEXT("Profile: %s\r\n"), profpn);

	if (flags & VI_FLAG_PRNVAR) {
		WIN32_FIND_DATA FindFileData;

		HANDLE hFind = FindFirstFile(profpn, &FindFileData);
		if (hFind != INVALID_HANDLE_VALUE) {
			FindClose(hFind);

			unsigned __int64 fsize = (unsigned __int64)FindFileData.nFileSizeHigh << 32 | FindFileData.nFileSizeLow;
			buffer.AppendFormat(TEXT("Profile size: %I64u Bytes\r\n"), fsize),

				GetLastWriteTime(&FindFileData.ftCreationTime, mirtime, 30);
			buffer.AppendFormat(TEXT("Profile creation date: %s\r\n"), mirtime);
		}
	}
	mir_free(profpathfull);

	GetLanguagePackString(buffer);
	buffer.Append(TEXT("\r\n"));

	// buffer.AppendFormat(TEXT("Nightly: %s\r\n"), _tcsstr(vertxt, TEXT("alpha")) ? TEXT("Yes") : TEXT("No")); 
	// buffer.AppendFormat(TEXT("Unicode: %s\r\n"), _tcsstr(vertxt, TEXT("Unicode")) ? TEXT("Yes") : TEXT("No")); 

	GetPluginsString(buffer, flags);

	if (flags & VI_FLAG_WEATHER) {
		buffer.AppendFormat(TEXT("\r\n%sWeather ini files:%s\r\n-------------------------------------------------------------------------------\r\n"),
			(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""),
			(flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""));
		GetWeatherStrings(buffer, flags);
	}

	if (flags & VI_FLAG_PRNVAR && !servicemode) {
		buffer.AppendFormat(TEXT("\r\n%sProtocols and Accounts:%s\r\n-------------------------------------------------------------------------------\r\n"),
			(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""),
			(flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""));
		GetProtocolStrings(buffer);
	}

	if (flags & VI_FLAG_PRNVAR) {
		buffer.AppendFormat(TEXT("\r\n%sIcon Packs:%s\r\n-------------------------------------------------------------------------------\r\n"),
			(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""),
			(flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""));
		GetIconStrings(buffer);
	}

	if (flags & VI_FLAG_PRNDLL) {
		__try {
			buffer.Append(TEXT("\r\nLoaded Modules:\r\n-------------------------------------------------------------------------------\r\n"));
			EnumerateLoadedModules64(GetCurrentProcess(), LoadedModules64, &buffer);
		}
		__except (EXCEPTION_EXECUTE_HANDLER) {}
	}
Example #9
0
INT_PTR ExtraIcon_Register(WPARAM wParam, LPARAM lParam)
{
	if (wParam == 0)
		return 0;

	EXTRAICON_INFO *ei = (EXTRAICON_INFO *)wParam;
	if (ei->cbSize < (int)sizeof(EXTRAICON_INFO))
		return 0;
	if (ei->type != EXTRAICON_TYPE_CALLBACK && ei->type != EXTRAICON_TYPE_ICOLIB)
		return 0;
	if (IsEmpty(ei->name) || IsEmpty(ei->description))
		return 0;
	if (ei->type == EXTRAICON_TYPE_CALLBACK && (ei->ApplyIcon == NULL || ei->RebuildIcons == NULL))
		return 0;

	ptrT tszDesc(mir_a2t(ei->description));
	TCHAR *desc = TranslateTH(lParam, tszDesc);

	BaseExtraIcon *extra = GetExtraIconByName(ei->name);
	if (extra != NULL) {
		if (ei->type != extra->getType() || ei->type != EXTRAICON_TYPE_ICOLIB)
			return 0;

		// Found one, now merge it
		if (_tcsicmp(extra->getDescription(), desc)) {
			CMString newDesc = extra->getDescription();
			newDesc += _T(" / ");
			newDesc += desc;
			extra->setDescription(newDesc.c_str());
		}

		if (!IsEmpty(ei->descIcon))
			extra->setDescIcon(ei->descIcon);

		if (ei->OnClick != NULL)
			extra->setOnClick(ei->OnClick, ei->onClickParam);

		if (extra->getSlot() > 0) {
			if (clistRebuildAlreadyCalled)
				extra->rebuildIcons();
			if (clistApplyAlreadyCalled)
				extraIconsByHandle[extra->getID() - 1]->applyIcons();
		}

		return extra->getID();
	}

	int id = registeredExtraIcons.getCount() + 1;

	switch (ei->type) {
	case EXTRAICON_TYPE_CALLBACK:
		extra = new CallbackExtraIcon(id, ei->name, desc, ei->descIcon == NULL ? "" : ei->descIcon,
			ei->RebuildIcons, ei->ApplyIcon, ei->OnClick, ei->onClickParam);
		break;
	case EXTRAICON_TYPE_ICOLIB:
		extra = new IcolibExtraIcon(id, ei->name, desc, ei->descIcon == NULL ? "" : ei->descIcon, ei->OnClick,
			ei->onClickParam);
		break;
	default:
		return 0;
	}

	char setting[512];
	mir_snprintf(setting, SIZEOF(setting), "Position_%s", ei->name);
	extra->setPosition(db_get_w(NULL, MODULE_NAME, setting, 1000));

	mir_snprintf(setting, SIZEOF(setting), "Slot_%s", ei->name);
	int slot = db_get_w(NULL, MODULE_NAME, setting, 1);
	if (slot == (WORD)-1)
		slot = -1;
	extra->setSlot(slot);

	extra->hLangpack = (int)lParam;

	registeredExtraIcons.insert(extra);
	extraIconsByHandle.insert(extra);

	LIST<ExtraIconGroup> groups(1);
	LoadGroups(groups);

	ExtraIconGroup *group = IsInGroup(groups, extra);
	if (group != NULL)
		RebuildListsBasedOnGroups(groups);
	else {
		for (int i = 0; i < groups.getCount(); i++)
			delete groups[i];

		extraIconsBySlot.insert(extra);
	}

	if (slot >= 0 || group != NULL) {
		if (clistRebuildAlreadyCalled)
			extra->rebuildIcons();

		slot = 0;
		for (int i = 0; i < extraIconsBySlot.getCount(); i++) {
			ExtraIcon *ex = extraIconsBySlot[i];
			if (ex->getSlot() < 0)
				continue;

			int oldSlot = ex->getSlot();
			ex->setSlot(slot++);

			if (clistApplyAlreadyCalled && (ex == group || ex == extra || oldSlot != slot))
				extra->applyIcons();
		}
	}

	return id;
}
Example #10
0
static void GetPluginsString(CMString& buffer, unsigned& flags)
{
	buffer.AppendFormat(TEXT("Service Mode: %s\r\n"), servicemode ? TEXT("Yes") : TEXT("No"));

	TCHAR path[MAX_PATH];
	GetModuleFileName(NULL, path, MAX_PATH);

	LPTSTR fname = _tcsrchr(path, TEXT('\\'));
	if (fname == NULL) fname = path;
	mir_sntprintf(fname, MAX_PATH - (fname - path), TEXT("\\plugins\\*.dll"));

	WIN32_FIND_DATA FindFileData;
	HANDLE hFind = FindFirstFile(path, &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE) return;

	size_t count = 0, ucount = 0;

	CMString ubuffer;
	ListItem* dlllist = NULL;

	static const TCHAR format[] = TEXT("%c %s v.%s%d.%d.%d.%d%s [%s] - %S %s\r\n");

	do {
		bool loaded = false;
		mir_sntprintf(fname, MAX_PATH - (fname - path), TEXT("\\plugins\\%s"), FindFileData.cFileName);
		HMODULE hModule = GetModuleHandle(path);
		if (hModule == NULL && servicemode) {
			hModule = LoadLibrary(path);
			loaded = true;
		}
		if (hModule == NULL) {
			if ((flags & VI_FLAG_PRNVAR) && IsPluginEnabled(FindFileData.cFileName)) {
				TCHAR timebuf[30] = TEXT("");
				GetLastWriteTime(&FindFileData.ftLastWriteTime, timebuf, 30);

				ubuffer.AppendFormat(format, TEXT(' '), FindFileData.cFileName,
					(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""),
					0, 0, 0, 0,
					(flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""),
					timebuf, "<unknown>", TEXT(""));

				GetLinkedModulesInfo(path, ubuffer);
				ubuffer.Append(TEXT("\r\n"));

				++ucount;
			}
			continue;
		}

		PLUGININFOEX* pi = GetMirInfo(hModule);
		if (pi != NULL) {
			TCHAR timebuf[30] = TEXT("");
			GetLastWriteTime(&FindFileData.ftLastWriteTime, timebuf, 30);

			bool ep = (size_t)pi->cbSize > sizeof(PLUGININFOEX);
			const TCHAR *unica = (ep && ((PLUGININFOEX*)pi)->flags & 1) ? TEXT("|Unicode aware|") : TEXT("");

			ListItem* lst = new ListItem;
			int v1, v2, v3, v4;

			DWORD unused, verInfoSize = GetFileVersionInfoSize(path, &unused);
			if (verInfoSize != 0) {
				UINT blockSize;
				VS_FIXEDFILEINFO* fi;
				void* pVerInfo = mir_alloc(verInfoSize);
				GetFileVersionInfo(path, 0, verInfoSize, pVerInfo);
				VerQueryValue(pVerInfo, _T("\\"), (LPVOID*)&fi, &blockSize);
				v1 = HIWORD(fi->dwProductVersionMS), v2 = LOWORD(fi->dwProductVersionMS),
					v3 = HIWORD(fi->dwProductVersionLS), v4 = LOWORD(fi->dwProductVersionLS);
				mir_free(pVerInfo);
			}
			else {
				DWORD ver = pi->version;
				v1 = HIBYTE(HIWORD(ver)), v2 = LOBYTE(HIWORD(ver)), v3 = HIBYTE(LOWORD(ver)), v4 = LOBYTE(LOWORD(ver));
			}

			lst->str.AppendFormat(format, ep ? TEXT('\xa4') : TEXT(' '), FindFileData.cFileName,
				(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""),
				v1, v2, v3, v4,
				(flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""),
				timebuf, pi->shortName ? pi->shortName : "", unica);

			ListItem* lsttmp = dlllist;
			ListItem* lsttmppv = NULL;
			while (lsttmp != NULL) {
				if (lsttmp->str.CompareNoCase(lst->str) > 0)
					break;
				lsttmppv = lsttmp;
				lsttmp = lsttmp->next;
			}
			lst->next = lsttmp;
			if (lsttmppv == NULL)
				dlllist = lst;
			else
				lsttmppv->next = lst;

			if (_tcsicmp(FindFileData.cFileName, TEXT("weather.dll")) == 0)
				flags |= VI_FLAG_WEATHER;

			++count;
		}
		if (loaded) FreeLibrary(hModule);
	} while (FindNextFile(hFind, &FindFileData));
	FindClose(hFind);

	buffer.AppendFormat(TEXT("\r\n%sActive Plugins (%u):%s\r\n"),
		(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""), count, (flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""));

	ListItem* lsttmp = dlllist;
	while (lsttmp != NULL) {
		buffer.Append(lsttmp->str);
		ListItem* lsttmp1 = lsttmp->next;
		delete lsttmp;
		lsttmp = lsttmp1;
	}

	if (ucount) {
		buffer.AppendFormat(TEXT("\r\n%sUnloadable Plugins (%u):%s\r\n"),
			(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""), ucount, (flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""));
		buffer.Append(ubuffer);
	}
}
Example #11
0
static void GetWeatherStrings(CMString& buffer, unsigned flags)
{
	TCHAR path[MAX_PATH];
	GetModuleFileName(NULL, path, MAX_PATH);

	LPTSTR fname = _tcsrchr(path, TEXT('\\'));
	if (fname == NULL) fname = path;
	mir_sntprintf(fname, MAX_PATH - (fname - path), TEXT("\\plugins\\weather\\*.ini"));

	WIN32_FIND_DATA FindFileData;
	HANDLE hFind = FindFirstFile(path, &FindFileData);
	if (hFind == INVALID_HANDLE_VALUE) return;

	do {
		if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;

		mir_sntprintf(fname, MAX_PATH - (fname - path), TEXT("\\plugins\\weather\\%s"), FindFileData.cFileName);
		HANDLE hDumpFile = CreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL,
			OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

		if (hDumpFile != INVALID_HANDLE_VALUE) {
			char buf[8192];

			DWORD bytes = 0;
			ReadFile(hDumpFile, buf, 8190, &bytes, NULL);
			buf[bytes] = 0;

			char* ver = strstr(buf, "Version=");
			if (ver != NULL) {
				char *endid = strchr(ver, '\r');
				if (endid != NULL) *endid = 0;
				else {
					endid = strchr(ver, '\n');
					if (endid != NULL) *endid = 0;
				}
				ver += 8;
			}

			char *id = strstr(buf, "Name=");
			if (id != NULL) {
				char *endid = strchr(id, '\r');
				if (endid != NULL) *endid = 0;
				else {
					endid = strchr(id, '\n');
					if (endid != NULL) *endid = 0;
				}
				id += 5;
			}

			TCHAR timebuf[30] = TEXT("");
			GetLastWriteTime(&FindFileData.ftLastWriteTime, timebuf, 30);


			static const TCHAR format[] = TEXT(" %s v.%s%S%s [%s] - %S\r\n");

			buffer.AppendFormat(format, FindFileData.cFileName,
				(flags & VI_FLAG_FORMAT) ? TEXT("[b]") : TEXT(""),
				ver,
				(flags & VI_FLAG_FORMAT) ? TEXT("[/b]") : TEXT(""),
				timebuf, id);
			CloseHandle(hDumpFile);
		}
	} while (FindNextFile(hFind, &FindFileData));
	FindClose(hFind);
}
Example #12
0
INT_PTR CALLBACK UserDetailsDlgProc(HWND m_hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	UserDetailsDlgProcParam* p = ( UserDetailsDlgProcParam* )GetWindowLongPtr( m_hwnd, GWLP_USERDATA );
	switch (msg) {
	case WM_INITDIALOG:
		p = new UserDetailsDlgProcParam( NULL, ( HANDLE )lParam );
		SetWindowLongPtr( m_hwnd, GWLP_USERDATA, ( LPARAM )p );
		break;

	case WM_NOTIFY:
		if ((( LPNMHDR )lParam )->idFrom == 0 && (( LPNMHDR )lParam )->code == PSN_PARAMCHANGED ) {
			p->ppro = ( CIrcProto* )(( PSHNOTIFY* )lParam )->lParam;

			DBVARIANT dbv;
			BYTE bAdvanced = p->ppro->getByte( p->hContact, "AdvancedMode", 0);

			TranslateDialogDefault( m_hwnd);

			CheckDlgButton( m_hwnd, IDC_RADIO1, bAdvanced?BST_UNCHECKED:BST_CHECKED);
			CheckDlgButton( m_hwnd, IDC_RADIO2, bAdvanced?BST_CHECKED:BST_UNCHECKED);
			EnableWindow(GetDlgItem( m_hwnd, IDC_WILDCARD), bAdvanced);

			if ( !bAdvanced ) {
				SetDlgItemText( m_hwnd, IDC_DEFAULT, TranslateT(STR_BASIC));
				if ( !p->ppro->getTString( p->hContact, "Default", &dbv)) {
					SetDlgItemText( m_hwnd, IDC_WILDCARD, dbv.ptszVal);
					DBFreeVariant(&dbv);
				}
			}
			else {
				SetDlgItemText( m_hwnd, IDC_DEFAULT, TranslateT(STR_ADVANCED));
				if ( !p->ppro->getTString( p->hContact, "UWildcard", &dbv)) {
					SetDlgItemText( m_hwnd, IDC_WILDCARD, dbv.ptszVal);
					DBFreeVariant(&dbv);
			}	}

			if ( !p->ppro->getTString( p->hContact, "UUser", &dbv)) {
				SetDlgItemText( m_hwnd, IDC_USER, dbv.ptszVal);
				DBFreeVariant(&dbv);
			}

			if ( !p->ppro->getTString( p->hContact, "UHost", &dbv)) {
				SetDlgItemText( m_hwnd, IDC_HOST, dbv.ptszVal);
				DBFreeVariant(&dbv);
			}
			ProtoBroadcastAck(p->ppro->m_szModuleName, p->hContact, ACKTYPE_GETINFO, ACKRESULT_SUCCESS, (HANDLE) 1, 0);
		}
		break;

	case WM_COMMAND:
		if (( LOWORD(wParam) == IDC_WILDCARD || LOWORD(wParam) == IDC_USER || LOWORD(wParam) == IDC_HOST ) &&
			 ( HIWORD(wParam) != EN_CHANGE || (HWND)lParam != GetFocus()))
			return true;

		EnableWindow(GetDlgItem( m_hwnd, IDC_BUTTON), true);
		EnableWindow(GetDlgItem( m_hwnd, IDC_BUTTON2), true);

		if( HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_BUTTON ) {
			TCHAR temp[500];
			GetDlgItemText( m_hwnd, IDC_WILDCARD, temp, SIZEOF(temp));
			DBVARIANT dbv;

			BYTE bAdvanced = IsDlgButtonChecked( m_hwnd, IDC_RADIO1)?0:1;
			if ( bAdvanced ) {
				if ( GetWindowTextLength(GetDlgItem( m_hwnd, IDC_WILDCARD)) == 0 ||
					  GetWindowTextLength(GetDlgItem( m_hwnd, IDC_USER)) == 0 ||
					  GetWindowTextLength(GetDlgItem( m_hwnd, IDC_HOST)) == 0)
				{
					MessageBox( NULL, TranslateT(STR_ERROR2), TranslateT("IRC error"), MB_OK|MB_ICONERROR);
					return FALSE;
				}

				if ( !p->ppro->getTString( p->hContact, "Default", &dbv )) {
					CMString S = _T(STR_ERROR);
					S += _T(" (");
					S += dbv.ptszVal;
					S += _T(")");
					if (( lstrlen(temp) < 4 && lstrlen(temp)) || !WCCmp(CharLower(temp), CharLower(dbv.ptszVal))) {
						MessageBox( NULL, TranslateTS( S.c_str()), TranslateT( "IRC error" ), MB_OK | MB_ICONERROR );
						DBFreeVariant( &dbv );
						return FALSE;
					}
					DBFreeVariant( &dbv );
				}

				GetDlgItemText( m_hwnd, IDC_WILDCARD, temp, SIZEOF(temp));
				if ( lstrlen( GetWord(temp, 0).c_str()))
					p->ppro->setTString( p->hContact, "UWildcard", GetWord(temp, 0).c_str());
				else
					DBDeleteContactSetting( p->hContact, p->ppro->m_szModuleName, "UWildcard");
			}

			p->ppro->setByte( p->hContact, "AdvancedMode", bAdvanced);

			GetDlgItemText( m_hwnd, IDC_USER, temp, SIZEOF(temp));
			if (lstrlen(GetWord(temp, 0).c_str()))
				p->ppro->setTString( p->hContact, "UUser", GetWord(temp, 0).c_str());
			else
				DBDeleteContactSetting( p->hContact, p->ppro->m_szModuleName, "UUser");

			GetDlgItemText( m_hwnd, IDC_HOST, temp, SIZEOF(temp));
			if (lstrlen(GetWord(temp, 0).c_str()))
				p->ppro->setTString( p->hContact, "UHost", GetWord(temp, 0).c_str());
			else
				DBDeleteContactSetting( p->hContact, p->ppro->m_szModuleName, "UHost");

			EnableWindow(GetDlgItem( m_hwnd, IDC_BUTTON), FALSE);
		}

		if ( HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_BUTTON2 ) {
			if ( IsDlgButtonChecked( m_hwnd, IDC_RADIO2 ))
				SetDlgItemTextA( m_hwnd, IDC_WILDCARD, "");
			SetDlgItemTextA( m_hwnd, IDC_HOST, "" );
			SetDlgItemTextA( m_hwnd, IDC_USER, "" );
			DBDeleteContactSetting( p->hContact, p->ppro->m_szModuleName, "UWildcard");
			DBDeleteContactSetting( p->hContact, p->ppro->m_szModuleName, "UUser");
			DBDeleteContactSetting( p->hContact, p->ppro->m_szModuleName, "UHost");
			EnableWindow(GetDlgItem( m_hwnd, IDC_BUTTON), FALSE );
			EnableWindow(GetDlgItem( m_hwnd, IDC_BUTTON2), FALSE );
		}

		if ( HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_RADIO1 ) {
			SetDlgItemText( m_hwnd, IDC_DEFAULT, TranslateT(STR_BASIC));

			DBVARIANT dbv;
			if ( !p->ppro->getTString( p->hContact, "Default", &dbv )) {
				SetDlgItemText( m_hwnd, IDC_WILDCARD, dbv.ptszVal );
				DBFreeVariant( &dbv );
			}
			EnableWindow(GetDlgItem( m_hwnd, IDC_WILDCARD), FALSE );
		}

		if ( HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_RADIO2 ) {
			DBVARIANT dbv;
			SetDlgItemText( m_hwnd, IDC_DEFAULT, TranslateT(STR_ADVANCED));
			if ( !p->ppro->getTString( p->hContact, "UWildcard", &dbv )) {
				SetDlgItemText( m_hwnd, IDC_WILDCARD, dbv.ptszVal );
				DBFreeVariant( &dbv );
			}
			EnableWindow(GetDlgItem( m_hwnd, IDC_WILDCARD), true);
		}
		break;
	}
	return FALSE;
}
Example #13
0
INT_PTR CALLBACK DlgProcView(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	RECT rc;

	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);
		{
			SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM)LoadIconEx(IDI_VI, true));
			SendMessage(hwndDlg, WM_SETICON, ICON_SMALL, (LPARAM)LoadIconEx(IDI_VI));

			CHARFORMAT2 chf;
			chf.cbSize = sizeof(chf);
			SendDlgItemMessage(hwndDlg, IDC_VIEWVERSIONINFO, EM_GETCHARFORMAT, SCF_DEFAULT, (LPARAM)&chf);
			mir_tstrcpy(chf.szFaceName, TEXT("Courier New"));
			SendDlgItemMessage(hwndDlg, IDC_VIEWVERSIONINFO, EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&chf);

			CMString buffer;
			PrintVersionInfo(buffer, (unsigned int)lParam);
			SetDlgItemText(hwndDlg, IDC_VIEWVERSIONINFO, buffer.c_str());
			SetWindowLongPtr(hwndDlg, GWLP_USERDATA, lParam);
		}

		if (lParam & VI_FLAG_PRNDLL)
			SetWindowText(hwndDlg, TranslateT("View Version Information (with DLLs)"));

		Utils_RestoreWindowPositionNoMove(hwndDlg, NULL, PluginName, "ViewInfo_");
		ShowWindow(hwndDlg, SW_SHOW);
		break;

	case WM_SIZE:
		GetWindowRect(GetDlgItem(hwndDlg, IDC_FILEVER), &rc);

		int dx, dy;
		if (MyResizeGetOffset(GetDlgItem(hwndDlg, IDC_VIEWVERSIONINFO), LOWORD(lParam) - 20, HIWORD(lParam) - 30 - (rc.bottom - rc.top), &dx, &dy)) {
			HDWP hDwp = BeginDeferWindowPos(4);
			hDwp = MyResizeWindow(hDwp, hwndDlg, GetDlgItem(hwndDlg, IDC_FILEVER), 0, dy, 0, 0);
			hDwp = MyResizeWindow(hDwp, hwndDlg, GetDlgItem(hwndDlg, IDC_CLIPVER), dx / 2, dy, 0, 0);
			hDwp = MyResizeWindow(hDwp, hwndDlg, GetDlgItem(hwndDlg, IDCANCEL), dx, dy, 0, 0);
			hDwp = MyResizeWindow(hDwp, hwndDlg, GetDlgItem(hwndDlg, IDC_VIEWVERSIONINFO), 0, 0, dx, dy);
			EndDeferWindowPos(hDwp);
		}
		break;

	case WM_GETMINMAXINFO:
		{
			LPMINMAXINFO mmi = (LPMINMAXINFO)lParam;
			mmi->ptMinTrackSize.x = 400; // The minimum width in points
			mmi->ptMinTrackSize.y = 300; // The minimum height in points
		}
		break;

	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case IDC_CLIPVER:
			CallService(MS_CRASHDUMPER_STORETOCLIP, 0, GetWindowLongPtr(hwndDlg, GWLP_USERDATA));
			break;

		case IDC_FILEVER:
			CallService(MS_CRASHDUMPER_STORETOFILE, 0, GetWindowLongPtr(hwndDlg, GWLP_USERDATA));
			break;

		case IDCANCEL:
			DestroyWindow(hwndDlg);
			break;
		}
		break;

	case WM_CONTEXTMENU:
		{
			HWND hView = GetDlgItem(hwndDlg, IDC_VIEWVERSIONINFO);
			GetWindowRect(hView, &rc);

			POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
			if (PtInRect(&rc, pt)) {
				static const CHARRANGE all = { 0, -1 };

				HMENU hMenu = LoadMenu(hInst, MAKEINTRESOURCE(IDR_CONTEXT));
				HMENU hSubMenu = GetSubMenu(hMenu, 0);
				TranslateMenu(hSubMenu);

				CHARRANGE sel;
				SendMessage(hView, EM_EXGETSEL, 0, (LPARAM)&sel);
				if (sel.cpMin == sel.cpMax)
					EnableMenuItem(hSubMenu, IDM_COPY, MF_BYCOMMAND | MF_GRAYED);

				switch (TrackPopupMenu(hSubMenu, TPM_RETURNCMD, pt.x, pt.y, 0, hwndDlg, NULL)) {
				case IDM_COPY:
					SendMessage(hView, WM_COPY, 0, 0);
					break;

				case IDM_COPYALL:
					SendMessage(hView, EM_EXSETSEL, 0, (LPARAM)&all);
					SendMessage(hView, WM_COPY, 0, 0);
					SendMessage(hView, EM_EXSETSEL, 0, (LPARAM)&sel);
					break;

				case IDM_SELECTALL:
					SendMessage(hView, EM_EXSETSEL, 0, (LPARAM)&all);
					break;
				}
				DestroyMenu(hMenu);
			}
		}
		break;

	case WM_DESTROY:
		hViewWnd = NULL;
		IcoLib_ReleaseIcon((HICON)SendMessage(hwndDlg, WM_SETICON, ICON_BIG, 0));
		IcoLib_ReleaseIcon((HICON)SendMessage(hwndDlg, WM_SETICON, ICON_SMALL, 0));
		Utils_SaveWindowPosition(hwndDlg, NULL, PluginName, "ViewInfo_");
		if (servicemode)
			PostQuitMessage(0);
		break;
	}
	return FALSE;
}
Example #14
0
TCHAR* fnTrayIconMakeTooltip(const TCHAR *szPrefix, const char *szProto)
{
	initcheck NULL;

	mir_cslock lck(trayLockCS);
	TCHAR *szSeparator = _T("\n");

	if (szProto == NULL) {
		if (accounts.getCount() == 0)
			return NULL;

		if (accounts.getCount() == 1)
			return cli.pfnTrayIconMakeTooltip(szPrefix, accounts[0]->szModuleName);

		CMString tszTip;

		if (szPrefix && szPrefix[0]) {
			if (!db_get_b(NULL, "CList", "AlwaysStatus", SETTING_ALWAYSSTATUS_DEFAULT)) {
				_tcsncpy_s(cli.szTip, MAX_TIP_SIZE, szPrefix, _TRUNCATE);
				return cli.szTip;
			}
			tszTip.Append(szPrefix);
		}

		for (int t = 0; t < accounts.getCount(); t++) {
			int i = cli.pfnGetAccountIndexByPos(t);
			if (i == -1)
				continue;

			PROTOACCOUNT *pa = accounts[i];
			if (!cli.pfnGetProtocolVisibility(pa->szModuleName))
				continue;

			TCHAR *szStatus = cli.pfnGetStatusModeDescription(CallProtoServiceInt(NULL, pa->szModuleName, PS_GETSTATUS, 0, 0), 0);
			if (!szStatus)
				continue;

			if (!tszTip.IsEmpty())
				tszTip.AppendChar('\n');
			if (mToolTipTrayTips) {
				tszTip.AppendFormat(_T("<b>%-12.12s</b>\t%s"), pa->tszAccountName, szStatus);

				ptrT ProtoXStatus(sttGetXStatus(pa->szModuleName));
				if (ProtoXStatus != NULL) {
					if (!tszTip.IsEmpty())
						tszTip.AppendChar('\n');
					tszTip.AppendFormat(_T("%-24.24s\n"), ProtoXStatus);
				}
			}
			else tszTip.AppendFormat(_T("%s %s"), pa->tszAccountName, szStatus);
		}

		_tcsncpy_s(cli.szTip, MAX_TIP_SIZE, tszTip, _TRUNCATE);
	}
	else {
		PROTOACCOUNT *pa = Proto_GetAccount(szProto);
		if (pa != NULL) {
			ptrT ProtoXStatus(sttGetXStatus(szProto));
			TCHAR *szStatus = cli.pfnGetStatusModeDescription(CallProtoServiceInt(NULL, szProto, PS_GETSTATUS, 0, 0), 0);
			if (szPrefix && szPrefix[0]) {
				if (db_get_b(NULL, "CList", "AlwaysStatus", SETTING_ALWAYSSTATUS_DEFAULT)) {
					if (mToolTipTrayTips) {
						if (ProtoXStatus != NULL)
							mir_sntprintf(cli.szTip, MAX_TIP_SIZE, _T("%s%s<b>%-12.12s</b>\t%s%s%-24.24s"), szPrefix, szSeparator, pa->tszAccountName, szStatus, szSeparator, ProtoXStatus);
						else
							mir_sntprintf(cli.szTip, MAX_TIP_SIZE, _T("%s%s<b>%-12.12s</b>\t%s"), szPrefix, szSeparator, pa->tszAccountName, szStatus);
					}
					else mir_sntprintf(cli.szTip, MAX_TIP_SIZE, _T("%s%s%s %s"), szPrefix, szSeparator, pa->tszAccountName, szStatus);
				}
				else mir_tstrncpy(cli.szTip, szPrefix, MAX_TIP_SIZE);
			}
			else {
				if (mToolTipTrayTips) {
					if (ProtoXStatus != NULL)
						mir_sntprintf(cli.szTip, MAX_TIP_SIZE, _T("<b>%-12.12s</b>\t%s\n%-24.24s"), pa->tszAccountName, szStatus, ProtoXStatus);
					else
						mir_sntprintf(cli.szTip, MAX_TIP_SIZE, _T("<b>%-12.12s</b>\t%s"), pa->tszAccountName, szStatus);
				}
				else mir_sntprintf(cli.szTip, MAX_TIP_SIZE, _T("%s %s"), pa->tszAccountName, szStatus);
			}
		}
	}

	return cli.szTip;
}
Example #15
0
INT_PTR __cdecl CIrcProto::Scripting_GetIrcData(WPARAM, LPARAM lparam)
{
	if (m_scriptingEnabled && lparam) {
		CMStringA sString = (char*)lparam, sRequest;
		CMString sOutput, sChannel;

		int i = sString.Find("|");
		if (i != -1) {
			sRequest = sString.Mid(0, i);
			TCHAR* p = mir_a2t(sString.Mid(i + 1));
			sChannel = p;
			mir_free(p);
		}
		else sRequest = sString;

		sRequest.MakeLower();

		if (sRequest == "ownnick" && IsConnected())
			sOutput = m_info.sNick;

		else if (sRequest == "network" && IsConnected())
			sOutput = m_info.sNetwork;

		else if (sRequest == "primarynick")
			sOutput = m_nick;

		else if (sRequest == "secondarynick")
			sOutput = m_alternativeNick;

		else if (sRequest == "myip")
			return (INT_PTR)mir_strdup(m_manualHost ? m_mySpecifiedHostIP :
			(m_IPFromServer) ? m_myHost : m_myLocalHost);

		else if (sRequest == "usercount" && !sChannel.IsEmpty()) {
			CMString S = MakeWndID(sChannel.c_str());
			GC_INFO gci = { 0 };
			gci.Flags = GCF_BYID | GCF_COUNT;
			gci.pszModule = m_szModuleName;
			gci.pszID = S.c_str();
			if (!CallServiceSync(MS_GC_GETINFO, 0, (LPARAM)&gci)) {
				TCHAR szTemp[40];
				mir_sntprintf(szTemp, _T("%u"), gci.iCount);
				sOutput = szTemp;
			}
		}
		else if (sRequest == "userlist" && !sChannel.IsEmpty()) {
			CMString S = MakeWndID(sChannel.c_str());
			GC_INFO gci = { 0 };
			gci.Flags = GCF_BYID | GCF_USERS;
			gci.pszModule = m_szModuleName;
			gci.pszID = S.c_str();
			if (!CallServiceSync(MS_GC_GETINFO, 0, (LPARAM)&gci))
				return (INT_PTR)mir_strdup(gci.pszUsers);
		}
		else if (sRequest == "channellist") {
			CMString S = _T("");
			int n = CallServiceSync(MS_GC_GETSESSIONCOUNT, 0, (LPARAM)m_szModuleName);
			if (n >= 0) {
				int j = 0;
				while (j < n) {
					GC_INFO gci = { 0 };
					gci.Flags = GCF_BYINDEX | GCF_ID;
					gci.pszModule = m_szModuleName;
					gci.iItem = j;
					if (!CallServiceSync(MS_GC_GETINFO, 0, (LPARAM)&gci)) {
						if (mir_tstrcmpi(gci.pszID, SERVERWINDOW)) {
							CMString S1 = gci.pszID;
							int k = S1.Find(_T(" "));
							if (k != -1)
								S1 = S1.Mid(0, k);
							S += S1 + _T(" ");
						}
					}
					j++;
				}
			}

			if (!S.IsEmpty())
				sOutput = (TCHAR*)S.c_str();
		}
		// send it to mbot
		if (!sOutput.IsEmpty())
			return (INT_PTR)mir_t2a(sOutput.c_str());
	}
	return 0;
}
Example #16
0
static void FilterGetStrings(CMString &filter, BOOL xml, BOOL swf)
{
	filter.AppendFormat(_T("%s (*.bmp;*.jpg;*.gif;*.png"), TranslateT("All Files"));
	if (swf) filter.Append(_T(";*.swf"));
	if (xml) filter.Append(_T(";*.xml"));

	filter.AppendFormat(_T(")%c*.BMP;*.RLE;*.JPG;*.JPEG;*.GIF;*.PNG"), 0);
	if (swf) filter.Append(_T(";*.SWF"));
	if (xml) filter.Append(_T(";*.XML"));
	filter.AppendChar(0);

	filter.AppendFormat(_T("%s (*.bmp;*.rle)%c*.BMP;*.RLE%c"), TranslateT("Windows Bitmaps"), 0, 0);
	filter.AppendFormat(_T("%s (*.jpg;*.jpeg)%c*.JPG;*.JPEG%c"), TranslateT("JPEG Bitmaps"), 0, 0);
	filter.AppendFormat(_T("%s (*.gif)%c*.GIF%c"), TranslateT("GIF Bitmaps"), 0, 0);
	filter.AppendFormat(_T("%s (*.png)%c*.PNG%c"), TranslateT("PNG Bitmaps"), 0, 0);

	if (swf)
		filter.AppendFormat(_T("%s (*.swf)%c*.SWF%c"), TranslateT("Flash Animations"), 0, 0);

	if (xml)
		filter.AppendFormat(_T("%s (*.xml)%c*.XML%c"), TranslateT("XML Files"), 0, 0);

	filter.AppendChar(0);
}
Example #17
0
int CSkypeProto::OnGroupChatEventHook(WPARAM, LPARAM lParam)
{
	GCHOOK *gch = (GCHOOK*)lParam;
	if (!gch)
	{
		return 1;
	}
	else if (mir_strcmp(gch->pDest->pszModule, m_szModuleName) != 0)
	{
		return 0;
	}

	ptrA chat_id(mir_t2a(gch->pDest->ptszID));

	switch (gch->pDest->iType)
	{
	case GC_USER_MESSAGE:
	{
		OnSendChatMessage(gch->pDest->ptszID, gch->ptszText);
		break;
	}

	case GC_USER_PRIVMESS:
	{
		MCONTACT hContact = FindContact(_T2A(gch->ptszUID));
		if (hContact == NULL)
		{
			hContact = AddContact(_T2A(gch->ptszUID), true);
			setWord(hContact, "Status", ID_STATUS_ONLINE);
			db_set_b(hContact, "CList", "Hidden", 1);
			setTString(hContact, "Nick", gch->ptszUID);
			db_set_dw(hContact, "Ignore", "Mask1", 0);
		}
		CallService(MS_MSG_SENDMESSAGET, hContact, 0);
		break;
	}

	case GC_USER_LOGMENU:
	{
		switch (gch->dwData)
		{
		case 10: {
			CSkypeInviteDlg dlg(this);
			if(!dlg.DoModal())
			{
				break;
			}
			MCONTACT hContact = dlg.m_hContact;
			if (hContact != NULL)
			{
				ptrA username(db_get_sa(hContact, m_szModuleName, SKYPE_SETTINGS_ID));
				SendRequest(new InviteUserToChatRequest(m_szRegToken, chat_id, username, "User", m_szServer));
			}
			break;
		}
		case 20:
			OnLeaveChatRoom(FindChatRoom(chat_id), NULL);
			break;
		case 30:
			CMString newTopic = ChangeTopicForm();
			if (!newTopic.IsEmpty())
				SendRequest(new SetChatPropertiesRequest(m_szRegToken, chat_id, "topic", ptrA(mir_utf8encodeT(newTopic.GetBuffer())), m_szServer));
			break;
		}
		break;
	}

	case GC_USER_NICKLISTMENU:
	{
		ptrA user_id;
		if (gch->dwData == 10 || gch->dwData == 30 || gch->dwData == 40)
		{
			user_id = mir_t2a_cp(gch->ptszUID, CP_UTF8);
		}

		switch (gch->dwData)
		{
		case 10:
			SendRequest(new KickUserRequest(m_szRegToken, chat_id, user_id, m_szServer));
			break;
		case 30:
			SendRequest(new InviteUserToChatRequest(m_szRegToken, chat_id, user_id, "Admin", m_szServer));
			break;
		case 40:
			SendRequest(new InviteUserToChatRequest(m_szRegToken, chat_id, user_id, "User", m_szServer));
			break;
		}

		break;

	}
	}
	return 0;
}
Example #18
0
int CJabberProto::OnPrebuildContactMenu(WPARAM hContact, LPARAM)
{
    if (hContact == NULL)
        return 0;

    bool bIsChatRoom = isChatRoom(hContact);
    bool bIsTransport = getBool(hContact, "IsTransport", false);

    if ((bIsChatRoom == GCW_CHATROOM) || bIsChatRoom == 0) {
        if (ptrT(getTStringA(hContact, bIsChatRoom ? (char*)"ChatRoomID" : (char*)"jid")) != NULL) {
            Menu_ShowItem(g_hMenuConvert, TRUE);
            Menu_ModifyItem(g_hMenuConvert, bIsChatRoom ? LPGENT("&Convert to Contact") : LPGENT("&Convert to Chat Room"));
        }
    }

    if (!m_bJabberOnline)
        return 0;

    Menu_ShowItem(g_hMenuDirectPresence[0], TRUE);
    for (int i = 0; i < _countof(PresenceModeArray); i++)
        Menu_ModifyItem(g_hMenuDirectPresence[i + 1], NULL, Skin_LoadProtoIcon(m_szModuleName, PresenceModeArray[i].mode));

    if (bIsChatRoom) {
        ptrT roomid(getTStringA(hContact, "ChatRoomID"));
        if (roomid != NULL) {
            Menu_ShowItem(g_hMenuRosterAdd, FALSE);

            if (ListGetItemPtr(LIST_BOOKMARK, roomid) == NULL)
                if (m_ThreadInfo && m_ThreadInfo->jabberServerCaps & JABBER_CAPS_PRIVATE_STORAGE)
                    Menu_ShowItem(g_hMenuAddBookmark, TRUE);
        }
    }

    if (bIsChatRoom == GCW_CHATROOM)
        return 0;

    if (bIsTransport) {
        Menu_ShowItem(g_hMenuLogin, TRUE);
        Menu_ShowItem(g_hMenuRefresh, TRUE);
    }

    ptrT jid(getTStringA(hContact, "jid"));
    if (jid == NULL)
        return 0;

    JabberCapsBits jcb = GetTotalJidCapabilites(jid);
    JABBER_LIST_ITEM *item = ListGetItemPtr(LIST_ROSTER, jid);
    if (item == NULL)
        return 0;

    bool bCtrlPressed = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
    Menu_ShowItem(g_hMenuRequestAuth, item->subscription == SUB_FROM || item->subscription == SUB_NONE || bCtrlPressed);
    Menu_ShowItem(g_hMenuGrantAuth, bCtrlPressed);
    Menu_ShowItem(g_hMenuRevokeAuth, item->subscription == SUB_FROM || item->subscription == SUB_BOTH || bCtrlPressed);
    Menu_ShowItem(g_hMenuCommands, ((jcb & JABBER_CAPS_COMMANDS) != 0) || bCtrlPressed);
    Menu_ShowItem(g_hMenuSendNote, TRUE);

    if (item->arResources.getCount() == 0)
        return 0;

    Menu_ShowItem(g_hMenuResourcesRoot, TRUE);
    Menu_ModifyItem(g_hMenuResourcesRoot, NULL, m_hProtoIcon);
    Menu_ModifyItem(g_hMenuResourcesActive, NULL, m_hProtoIcon, (item->resourceMode == RSMODE_LASTSEEN) ? CMIF_CHECKED : 0);
    Menu_ModifyItem(g_hMenuResourcesServer, NULL, m_hProtoIcon, (item->resourceMode == RSMODE_SERVER) ? CMIF_CHECKED : 0);

    int nMenuResourceItemsNew = m_nMenuResourceItems;
    if (m_nMenuResourceItems < item->arResources.getCount()) {
        m_phMenuResourceItems = (HGENMENU*)mir_realloc(m_phMenuResourceItems, item->arResources.getCount() * sizeof(HGENMENU));
        nMenuResourceItemsNew = item->arResources.getCount();
    }

    char text[256];
    CMenuItem mi;
    mi.pszService = text;

    CMString szTmp;
    for (int i = 0; i < nMenuResourceItemsNew; i++) {
        mir_snprintf(text, "/UseResource_%d", i);
        if (i >= m_nMenuResourceItems) {
            CreateProtoServiceParam(text, &CJabberProto::OnMenuHandleResource, MENUITEM_RESOURCES + i);
            mi.name.a = "";
            mi.position = i;
            mi.root = g_hMenuResourcesRoot;
            m_phMenuResourceItems[i] = Menu_AddContactMenuItem(&mi, m_szModuleName);
        }
        if (i < item->arResources.getCount()) {
            pResourceStatus r(item->arResources[i]);

            HICON hIcon = (HICON)INVALID_HANDLE_VALUE;
            Menu_SetChecked(m_phMenuResourceItems[i], item->resourceMode == RSMODE_MANUAL && item->m_pManualResource == r);

            if (ServiceExists(MS_FP_GETCLIENTICONT)) {
                FormatMirVer(r, szTmp);
                hIcon = Finger_GetClientIcon(szTmp, 0);
            }
            szTmp.Format(_T("%s [%s, %d]"), r->m_tszResourceName, pcli->pfnGetStatusModeDescription(r->m_iStatus, 0), r->m_iPriority);
            Menu_ModifyItem(m_phMenuResourceItems[i], szTmp, hIcon);
            DestroyIcon(hIcon);
        }
        else Menu_ShowItem(m_phMenuResourceItems[i], FALSE);
    }

    m_nMenuResourceItems = nMenuResourceItemsNew;
    return 0;
}
Example #19
0
void CVkProto::OnReciveUploadFile(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq)
{
	CVkFileUploadParam *fup = (CVkFileUploadParam *)pReq->pUserInfo;
	if (!IsOnline()) {
		SendFileFiled(fup, VKERR_OFFLINE);
		return;
	}

	debugLogA("CVkProto::OnReciveUploadFile %d", reply->resultCode);
	if (reply->resultCode != 200) {
		SendFileFiled(fup, VKERR_FILE_NOT_UPLOADED);
		return;
	}

	JSONNode jnRoot;
	const JSONNode &jnResponse = CheckJsonResponse(pReq, reply, jnRoot);
	if (!jnResponse || pReq->m_iErrorCode) {
		SendFileFiled(fup, pReq->m_iErrorCode);
		return;
	}

	int id = fup->GetType() == CVkFileUploadParam::typeAudio ? jnResponse["id"].as_int() : (*jnResponse.begin())["id"].as_int();
	int owner_id = fup->GetType() == CVkFileUploadParam::typeAudio ? jnResponse["owner_id"].as_int() : (*jnResponse.begin())["owner_id"].as_int(); 	
	if ((id == 0) || (owner_id == 0)) {
		SendFileFiled(fup, VKERR_INVALID_PARAMETERS);
		return;
	}

	CMString Attachment;

	switch (fup->GetType()) {
	case CVkFileUploadParam::typeImg:
		Attachment.AppendFormat(_T("photo%d_%d"), owner_id, id);
		break;
	case CVkFileUploadParam::typeAudio:
		Attachment.AppendFormat(_T("audio%d_%d"), owner_id, id);
		break;
	case CVkFileUploadParam::typeDoc:
		Attachment.AppendFormat(_T("doc%d_%d"), owner_id, id);
		break;
	default:
		SendFileFiled(fup, VKERR_FTYPE_NOT_SUPPORTED);
		return;
	}

	AsyncHttpRequest *pMsgReq;

	if (isChatRoom(fup->hContact)) {

		ptrT tszChatID(getTStringA(fup->hContact, "ChatRoomID"));
		if (!tszChatID) {
			SendFileFiled(fup, VKERR_INVALID_USER);
			return;
		}

		CVkChatInfo *cc = GetChatById(tszChatID);
		if (cc == NULL) {
			SendFileFiled(fup, VKERR_INVALID_USER);
			return;
		}

		pMsgReq = new AsyncHttpRequest(this, REQUEST_POST, "/method/messages.send.json", true, &CVkProto::OnSendChatMsg, AsyncHttpRequest::rpHigh)
			<< INT_PARAM("chat_id", cc->m_chatid);
		pMsgReq->pUserInfo = pReq->pUserInfo;

	}
	else {
		LONG userID = getDword(fup->hContact, "ID", -1);
		if (userID == -1 || userID == VK_FEED_USER) {
			SendFileFiled(fup, VKERR_INVALID_USER);
			return;
		}

		pMsgReq = new AsyncHttpRequest(this, REQUEST_POST, "/method/messages.send.json", true, &CVkProto::OnSendMessage, AsyncHttpRequest::rpHigh)
			<< INT_PARAM("user_id", userID);
		pMsgReq->pUserInfo = new CVkSendMsgParam(fup->hContact, fup);
		
	}

	pMsgReq << TCHAR_PARAM("message", fup->Desc) << TCHAR_PARAM("attachment", Attachment) << VER_API;
	pMsgReq->AddHeader("Content-Type", "application/x-www-form-urlencoded");

	Push(pMsgReq);
}
void CMSocketC::Connect(const CMString& sHost, UINT16 nPort)
{
    //网络接入连接检查
    CMNetConnMgr& mgr = CMNetConnMgr::Instance();

    if (mgr.CurrentType() == CMNetConnMgr::NONE)
    {
        //未接入,开始接入
        m_cTimer.SetTimerID(1); //使用TimerID来记重复次数
        m_cTimer.Set(3*1000);   //3秒检查
        m_sHost = sHost;
        m_nPort = nPort;
        m_cTimer.Start();
        return;
    }

    if (m_status != NOTCONNECTED)
    {//当前已有连接
//       if (m_sHost == sHost && m_nPort == nPort)
//        {
//            //新连接于原始连接相同,重用
//            if (m_status == CONNECTED)
//            {//取消现有操作
//				CM_ERR("CMSocketC::Connect connect reserved");
//                m_status = CONNECTED;
//                m_pNotify->OnConnect(MER_OK);
//                return;
//            }
//            CM_ERR("CMSocketC::Connect cancel!");
//            Cancel();
			
//       }
       // else
        {
            //关闭连接
            Close();
        }
    }

    CMString sTmp;
    if (!CMUrl::IsIP(sHost))
    {
        CM_LOGP(CM_LOGL_DEBUG, "CMSocketC::Connect HostNameToIP %s", (const CHAR*)(CMString)sHost);        
        sTmp = mgr.HostNameToIP(sHost);
        if (sTmp.IsEmpty())
        {
            CM_ERRP("Host %s can't to addr", (const CHAR*)(CMString)sHost);
            m_pNotify->OnConnect(MERN_WRONG_PARAM);
            return;
        }
    }
    else
    {
        sTmp = sHost;
    }
    TInetAddr addr;
    TBuf<20> buf;
    buf = (const UINT16*)((const WCHAR*)(sTmp));
    addr.SetPort(nPort);
    INT32 nErr = addr.Input(buf);
    if (nErr != KErrNone)
    {
        m_pNotify->OnConnect(MERN_WRONG_PARAM);
        return;
    }
    
    CM_LOGP(CM_LOGL_DEBUG, "CMSocketC::Connect Open start ip %s, port %d", (const CHAR*)sTmp, nPort);
    nErr = m_sk.Open(mgr.SocketServer(), KAfInet, KSockStream, KProtocolInetTcp
//#if !defined(__WINSCW__)
            , mgr.Connection());
//#else
//            );
//#endif
    
    if (nErr != KErrNone && nErr != KErrAlreadyExists)
    {
        m_pNotify->OnConnect(MERN_INITIALIZE);
        return;            
    }
    
//    iStatus = KErrNone;
    m_sk.Connect(addr, iStatus);
    m_status = CONNECTING;
    m_sHost = sHost;
    m_nPort = nPort;
    m_cTimer.Stop();
    m_cTimer.Set(60 * 1000); //超时默认60秒
    m_cTimer.Start();
    SetActive();
    return;
}
Example #21
0
bool SmileyPackType::LoadSmileyFileMSL(CMString &tbuf, bool onlyInfo, CMString &modpath)
{
	CMString pathstr, packstr;
	{
		_TPattern *pathsplit = _TPattern::compile(_T("(.*\\\\)(.*)\\.|$"));
		_TMatcher *m0 = pathsplit->createTMatcher(modpath);
		m0->findFirstMatch();
		pathstr = m0->getGroup(1);
		packstr = m0->getGroup(2);
		delete m0;
		delete pathsplit;
	}
	{
		_TPattern *otherf = _TPattern::compile(
			_T("^\\s*(Name|Author|Date|Version|ButtonSmiley)\\s*=\\s*\"(.*)\""),
			_TPattern::MULTILINE_MATCHING);

		_TMatcher *m0 = otherf->createTMatcher(tbuf);
		while (m0->findNextMatch()) {
			if (m0->getGroup(1) == _T("Name")) m_Name = m0->getGroup(2);
			if (m0->getGroup(1) == _T("Author")) m_Author = m0->getGroup(2);
			if (m0->getGroup(1) == _T("Date")) m_Date = m0->getGroup(2);
			if (m0->getGroup(1) == _T("Version")) m_Version = m0->getGroup(2);
			if (m0->getGroup(1) == _T("ButtonSmiley")) m_ButtonSmiley = m0->getGroup(2);
		}
		delete m0;
		delete otherf;
	}

	if (!onlyInfo) {
		selec.x = selec.y = win.x = win.y = 0;
		{
			_TPattern *pat = _TPattern::compile(
				_T("^\\s*(Selection|Window)Size\\s*=\\s*(\\d+)\\s*,\\s*(\\d+)"),
				_TPattern::MULTILINE_MATCHING);
			_TMatcher *m0 = pat->createTMatcher(tbuf);
			while (m0->findNextMatch()) {
				POINT tpt;
				tpt.x = _ttol(m0->getGroup(2).c_str());
				tpt.y = _ttol(m0->getGroup(3).c_str());

				if (m0->getGroup(1) == _T("Selection"))
					selec = tpt;
				else if (m0->getGroup(1) == _T("Window"))
					win = tpt;
			}
			delete m0;
			delete pat;
		}

		_TPattern *smiley = _TPattern::compile(
			_T("^\\s*Smiley(\\*)?\\s*=")	// Is Hidden
			_T("(?:\\s*\"(.*)\")")			// Smiley file name
			_T("(?:[\\s,]+(\\-?\\d+))")		// Icon resource id
			_T("(?:[\\s,]+(R|S)?\"(.*?)\")")	// Trigger text
			_T("(?:[\\s,]+\"(.*?)\")?")		// Tooltip or insert text
			_T("(?:[\\s,]+\"(.*?)\")?"),		// Tooltip text
			_TPattern::MULTILINE_MATCHING);

		SmileyVectorType hiddenSmileys;
		unsigned smnum = 0;
		{
			_TMatcher *m0 = smiley->createTMatcher(tbuf);
			while (m0->findNextMatch()) {
				CMString resname = m0->getGroup(2);
				if (resname.Find(_T("http://")) != -1) {
					if (GetSmileyFile(resname, packstr))
						continue;
				}
				else if (!resname.IsEmpty())
					resname.Insert(0, pathstr);

				SmileyType *dat = new SmileyType;

				const int iconIndex = _ttol(m0->getGroup(3).c_str());

				dat->SetHidden(m0->getStartingIndex(1) >= 0);
				if (m0->getStartingIndex(4) >= 0) {
					dat->SetRegEx(m0->getGroup(4) == _T("R"));
					dat->SetService(m0->getGroup(4) == _T("S"));
				}
				dat->m_TriggerText = m0->getGroup(5);
				if (dat->IsRegEx()) {
					if (m0->getStartingIndex(6) >= 0)
						ReplaceAllSpecials(m0->getGroup(6), dat->m_InsertText);

					if (m0->getStartingIndex(7) >= 0)
						ReplaceAllSpecials(m0->getGroup(7), dat->m_ToolText);
					else
						dat->m_ToolText = dat->m_InsertText;
				}
				else {
					if (m0->getStartingIndex(6) >= 0)
						ReplaceAllSpecials(m0->getGroup(6), dat->m_ToolText);
					else
						ReplaceAllSpecials(dat->m_TriggerText, dat->m_ToolText);
				}

				bool noerr;
				if (resname.IsEmpty()) {
					dat->SetHidden(true);
					dat->SetText(true);
					noerr = true;
				}
				else noerr = dat->LoadFromResource(resname, iconIndex);

				if (dat->IsHidden())
					hiddenSmileys.insert(dat);
				else
					m_SmileyList.insert(dat);

				if (!noerr) {
					static const TCHAR errmsg[] = LPGENT("Smiley #%u in file %s for smiley pack %s not found.");
					TCHAR msgtxt[1024];
					mir_sntprintf(msgtxt, TranslateTS(errmsg), smnum, resname.c_str(), modpath.c_str());
					CallService(MS_NETLIB_LOG, (WPARAM)hNetlibUser, _T2A(msgtxt));
					errorFound = true;
				}
				smnum++;
			}
			delete smiley;
			delete m0;
		}

		m_VisibleCount = m_SmileyList.getCount();

		m_SmileyList.splice(hiddenSmileys);

		AddTriggersToSmileyLookup();
	}

	return true;
}
Example #22
0
CVKNewsItem* CVkProto::GetVkParent(const JSONNode &jnParent, VKObjType vkParentType, LPCTSTR ptszReplyText, LPCTSTR ptszReplyLink)
{
	debugLogA("CVkProto::GetVkParent");
	CMString tszRes;
	if (!jnParent || !vkParentType)
		return NULL;

	CVKNewsItem * vkNotificationItem = new CVKNewsItem();
			
	if (vkParentType == vkPhoto) {
		CMString tszPhoto = GetVkPhotoItem(jnParent, m_iBBCForNews);
		LONG iOwnerId = jnParent["owner_id"].as_int();
		LONG iId = jnParent["id"].as_int();
		vkNotificationItem->tszId.AppendFormat(_T("%d_%d"), iOwnerId, iId);
		vkNotificationItem->tszLink.AppendFormat(_T("https://vk.com/photo%s"), vkNotificationItem->tszId);
		vkNotificationItem->tszText.AppendFormat(_T("\n%s"), tszPhoto);

		if (ptszReplyText)
			vkNotificationItem->tszText.AppendFormat(_T("\n>> %s"), SetBBCString(ptszReplyText, m_iBBCForNews, vkbbcI));
		
		vkNotificationItem->tszText.AppendFormat(_T("\n%s"), SetBBCString(TranslateT("Link"), m_iBBCForNews, vkbbcUrl, vkNotificationItem->tszLink));
	}
	else if (vkParentType == vkVideo) {
		LONG iOwnerId = jnParent["owner_id"].as_int();
		LONG iId = jnParent["id"].as_int();
		CMString tszTitle(jnParent["title"].as_mstring());
		vkNotificationItem->tszId.AppendFormat(_T("%d_%d"), iOwnerId, iId);
		vkNotificationItem->tszLink.AppendFormat(_T("https://vk.com/video%s"), vkNotificationItem->tszId);
		
		CMString tszText(jnParent["text"].as_mstring());
		ClearFormatNick(tszText);
		
		if (!tszText.IsEmpty())
			vkNotificationItem->tszText.AppendFormat(_T("\n%s: %s"), SetBBCString(TranslateT("Video description:"), m_iBBCForNews, vkbbcB), SetBBCString(tszText, m_iBBCForNews, vkbbcI));

		if (ptszReplyText)
			vkNotificationItem->tszText.AppendFormat(_T("\n>> %s"), SetBBCString(ptszReplyText, m_iBBCForNews, vkbbcI));
		
		vkNotificationItem->tszText.AppendFormat(_T("\n%s"), SetBBCString(tszTitle, m_iBBCForNews, vkbbcUrl, vkNotificationItem->tszLink));
	}
	else if (vkParentType == vkPost) {
		LONG iToId = jnParent["to_id"].as_int();
		LONG iId = jnParent["id"].as_int();
		vkNotificationItem->tszId.AppendFormat(_T("%d_%d"), iToId, iId);
		vkNotificationItem->tszLink.AppendFormat(_T("https://vk.com/wall%s%s"), vkNotificationItem->tszId, ptszReplyLink ? ptszReplyLink : _T(""));
		
		CMString tszText(jnParent["text"].as_mstring());
		ClearFormatNick(tszText);
		
		if (!tszText.IsEmpty())
			vkNotificationItem->tszText.AppendFormat(_T("\n%s: %s"), SetBBCString(TranslateT("Post text:"), m_iBBCForNews, vkbbcB), SetBBCString(tszText, m_iBBCForNews, vkbbcI));

		if (ptszReplyText)
			vkNotificationItem->tszText.AppendFormat(_T("\n>> %s"), SetBBCString(ptszReplyText, m_iBBCForNews, vkbbcI));

		vkNotificationItem->tszText.AppendFormat(_T("\n%s"), SetBBCString(TranslateT("Link"), m_iBBCForNews, vkbbcUrl, vkNotificationItem->tszLink));
	}
	else if (vkParentType == vkTopic) {
		LONG iOwnerId = jnParent["owner_id"].as_int();
		LONG iId = jnParent["id"].as_int();
		CMString tszTitle(jnParent["title"].as_mstring());
		vkNotificationItem->tszId.AppendFormat(_T("%d_%d"), iOwnerId, iId);
		vkNotificationItem->tszLink.AppendFormat(_T("https://vk.com/topic%s%s"), 
		vkNotificationItem->tszId, ptszReplyLink ? ptszReplyLink : _T(""));
		
		CMString tszText(jnParent["text"].as_mstring());
		ClearFormatNick(tszText);
		
		if (!tszText.IsEmpty())
			vkNotificationItem->tszText.AppendFormat(_T("\n%s: %s"), SetBBCString(TranslateT("Topic text:"), m_iBBCForNews, vkbbcB), SetBBCString(tszText, m_iBBCForNews, vkbbcI));

		if (ptszReplyText)
			vkNotificationItem->tszText.AppendFormat(_T("\n>> %s"), SetBBCString(ptszReplyText, m_iBBCForNews, vkbbcI));
		
		vkNotificationItem->tszText.AppendFormat(_T("\n%s"), SetBBCString(tszTitle, m_iBBCForNews, vkbbcUrl, vkNotificationItem->tszLink));
	}
	else if (vkParentType == vkComment) {
		CMString tszText(jnParent["text"].as_mstring());
		ClearFormatNick(tszText);

		const JSONNode &jnPhoto = jnParent["photo"];
		if (!jnPhoto.isnull()) {
			delete vkNotificationItem;
			return GetVkParent(jnPhoto, vkPhoto, tszText);
		}

		const JSONNode &jnVideo = jnParent["video"];
		if (!jnVideo.isnull()) {
			delete vkNotificationItem;
			return GetVkParent(jnVideo, vkVideo, tszText);
		}

		LONG iId = jnParent["id"].as_int();

		const JSONNode &jnPost = jnParent["post"];
		if (!jnPost.isnull()) {
			CMString tszRepl;
			tszRepl.AppendFormat(_T("?reply=%d"), iId);		
			delete vkNotificationItem;
			return GetVkParent(jnPost, vkPost, tszText, tszRepl);
		}

		const JSONNode &jnTopic = jnParent["topic"];
		if (!jnTopic.isnull()) {
			CMString tszRepl;		
			tszRepl.AppendFormat(_T("?reply=%d"), iId);
			delete vkNotificationItem;
			return GetVkParent(jnTopic, vkTopic, tszText, tszRepl);
		}
	}

	return vkNotificationItem;
}
Example #23
0
void pathToRelative(const CMString& pSrc, CMString& pOut)
{
	TCHAR szOutPath[MAX_PATH];
	PathToRelativeT(pSrc.c_str(), szOutPath);
	pOut = szOutPath;
}
Example #24
0
int Meta_ModifyMenu(WPARAM hMeta, LPARAM)
{
	DBCachedContact *cc = currDb->m_cache->GetCachedContact(hMeta);
	if (cc == NULL)
		return 0;
		
	Menu_ShowItem(hMenuRoot, false);

	if (cc->IsMeta()) {
		// save the mouse pos in case they open a subcontact menu
		GetCursorPos(&menuMousePoint);

		// This is a MetaContact, show the edit, force default, and the delete menu, and hide the others
		Menu_ShowItem(hMenuEdit, true);
		Menu_ShowItem(hMenuAdd, false);
		Menu_ShowItem(hMenuConvert, false);
		Menu_ShowItem(hMenuDefault, false);

		Menu_ShowItem(hMenuDelete, false);
		Menu_ModifyItem(hMenuDelete, LPGENT("Remove from metacontact"));

		// show subcontact menu items
		CMString tszNick;
		for (int i = 0; i < MAX_CONTACTS; i++) {
			if (i >= cc->nSubs) {
				Menu_ShowItem(hMenuContact[i], false);
				continue;
			}

			MCONTACT hContact = Meta_GetContactHandle(cc, i);
			LPCTSTR ptszName;

			if (options.menu_contact_label == DNT_UID) {
				Meta_GetSubNick(hMeta, i, tszNick);
				ptszName = tszNick.GetBuffer();
			}
			else ptszName = cli.pfnGetContactDisplayName(hContact, 0);

			int iconIndex = CallService(MS_CLIST_GETCONTACTICON, hContact, 0);
			HICON hIcon = ImageList_GetIcon((HIMAGELIST)CallService(MS_CLIST_GETICONSIMAGELIST, 0, 0), iconIndex, 0);
			Menu_ModifyItem(hMenuContact[i], ptszName, hIcon, 0);
			DestroyIcon(hIcon);
			
			Menu_ShowItem(hMenuRoot, true);
		}

		// show hide nudge menu item
		char serviceFunc[256];
		mir_snprintf(serviceFunc, _countof(serviceFunc), "%s%s", GetContactProto(Meta_GetMostOnline(cc)), PS_SEND_NUDGE);
		CallService(MS_NUDGE_SHOWMENU, (WPARAM)META_PROTO, ServiceExists(serviceFunc));
		return 0;
	}

	PROTOACCOUNT *pa = Proto_GetAccount(cc->szProto);
	if (!db_mc_isEnabled() || !pa || pa->bIsVirtual) {
		// groups disabled - all meta menu options hidden
		Menu_ShowItem(hMenuDefault, false);
		Menu_ShowItem(hMenuDelete, false);
		Menu_ShowItem(hMenuAdd, false);
		Menu_ShowItem(hMenuConvert, false);
		Menu_ShowItem(hMenuEdit, false);
		return 0;
	}
	
	// the contact is affected to a metacontact
	if (cc->IsSub()) {
		Menu_ShowItem(hMenuDefault, true);

		Menu_ModifyItem(hMenuDelete, LPGENT("Remove from metacontact"));
		Menu_ShowItem(hMenuDelete, true);

		Menu_ShowItem(hMenuAdd, false);
		Menu_ShowItem(hMenuConvert, false);
		Menu_ShowItem(hMenuEdit, false);
	}
	else {
		// The contact is neutral
		bool bHideChat = db_get_b(hMeta, cc->szProto, "ChatRoom", 0) == 0;
		Menu_ShowItem(hMenuAdd, bHideChat);
		Menu_ShowItem(hMenuConvert, bHideChat);
		Menu_ShowItem(hMenuEdit, false);
		Menu_ShowItem(hMenuDelete, false);
		Menu_ShowItem(hMenuDefault, false);
	}

	for (int i = 0; i < MAX_CONTACTS; i++)
		Menu_ShowItem(hMenuContact[i], false);

	return 0;
}