Exemplo n.º 1
0
void CSkypeProto::ProcessUserPresence(const JSONNode &node)
{
	debugLogA("CSkypeProto::ProcessUserPresenceRes");

	std::string selfLink = node["selfLink"].as_string();
	std::string status = node["status"].as_string();
	CMStringA skypename = UrlToSkypename(selfLink.c_str());

	if (!skypename.IsEmpty())
	{
		if (IsMe(skypename))
		{
			int iNewStatus = SkypeToMirandaStatus(status.c_str());
			if (iNewStatus == ID_STATUS_OFFLINE) return;
			int old_status = m_iStatus;
			m_iDesiredStatus = iNewStatus;
			m_iStatus = iNewStatus;
			if (old_status != iNewStatus)
			{
				ProtoBroadcastAck(NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)old_status, iNewStatus);
			}
		}
		else
		{
			MCONTACT hContact = FindContact(skypename);
			if (hContact != NULL)
				SetContactStatus(hContact, SkypeToMirandaStatus(status.c_str()));
		}
	}
}
Exemplo n.º 2
0
int NewsAggrInit(WPARAM wParam, LPARAM lParam)
{
	hNewsAggregatorFolder = FoldersRegisterCustomPathT(LPGEN("Avatars"), LPGEN("News Aggregator"), MIRANDA_USERDATAT _T("\\Avatars\\")_T(DEFAULT_AVATARS_FOLDER));
	if (hNewsAggregatorFolder)
		FoldersGetCustomPathT(hNewsAggregatorFolder, tszRoot, MAX_PATH, _T(""));
	else
		lstrcpyn(tszRoot, VARST( _T("%miranda_userdata%\\Avatars\\"_T(DEFAULT_AVATARS_FOLDER))), SIZEOF(tszRoot));

	for (MCONTACT hContact = db_find_first(MODULE); hContact; hContact = db_find_next(hContact, MODULE)) {
		if (!db_get_b(NULL, MODULE, "StartupRetrieve", 1))
			db_set_dw(hContact, MODULE, "LastCheck", time(NULL));
		SetContactStatus(hContact, ID_STATUS_ONLINE);
	}

	NetlibInit();
	InitIcons();
	InitMenu();

	HookEvent(ME_TTB_MODULELOADED, OnToolbarLoaded);
	HookEvent(ME_FOLDERS_PATH_CHANGED, OnFoldersChanged);

	// timer for the first update
	timerId = SetTimer(NULL, 0, 10000, timerProc2); // first update is 10 sec after load

	return 0;
}
Exemplo n.º 3
0
static void __cdecl WorkingThread(void* param)
{
	int nStatus = (int)param;

	for (MCONTACT hContact = db_find_first(MODULE); hContact; hContact = db_find_next(hContact, MODULE))
		SetContactStatus(hContact, nStatus);
}
Exemplo n.º 4
0
void CSkypeProto::SetAllContactsStatus(WORD status)
{
	for (MCONTACT hContact = db_find_first(m_szModuleName); hContact; hContact = db_find_next(hContact, m_szModuleName))
	{
		if (!isChatRoom(hContact))
			SetContactStatus(hContact, status);
	}
	if (status == ID_STATUS_OFFLINE)
		CloseAllChatChatSessions();
}
Exemplo n.º 5
0
INT_PTR NewsAggrSetStatus(WPARAM wp, LPARAM)
{
	int nStatus = wp;
	if ((ID_STATUS_ONLINE == nStatus) || (ID_STATUS_OFFLINE == nStatus)) {
		int nOldStatus = g_nStatus;
		if(nStatus != g_nStatus) {
			g_nStatus = nStatus;

			for (MCONTACT hContact = db_find_first(MODULE); hContact; hContact = db_find_next(hContact, MODULE))
				SetContactStatus(hContact, nStatus);

			ProtoBroadcastAck(MODULE, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)nOldStatus, g_nStatus);
		}
	}

	return 0;
}
Exemplo n.º 6
0
void GotoOffline()
{
	// Подтверждение текущего статуса
	SetPluginStatus (ID_STATUS_OFFLINE);

	if (pluginBusy)
		// Двойной вызов
		return;
	pluginBusy = true;

	// Перевод всех контактов в оффлайн
	FOR_EACH_CONTACT( hContact ) {
		SetContactStatus (hContact, ID_STATUS_OFFLINE, true);
	}

	// Начало отсоединения
	mir_forkthread( GotoOfflineTread, NULL );
}
Exemplo n.º 7
0
void CQuotesProviderBase::WriteContactRate(MCONTACT hContact, double dRate, const tstring& rsSymbol/* = ""*/)
{
	time_t nTime = ::time(NULL);

	if (false == rsSymbol.empty())
		db_set_ts(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_SYMBOL, rsSymbol.c_str());

	double dPrev = 0.0;
	bool bValidPrev = Quotes_DBReadDouble(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_CURR_VALUE, dPrev);
	if (true == bValidPrev)
		Quotes_DBWriteDouble(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_PREV_VALUE, dPrev);

	Quotes_DBWriteDouble(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_CURR_VALUE, dRate);
	db_set_dw(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_FETCH_TIME, nTime);

	tstring sSymbol = rsSymbol;

	tostringstream oNick;
	oNick.imbue(GetSystemLocale());
	if (false == m_sContactListFormat.empty()) {
		tstring s = format_rate(this, hContact, m_sContactListFormat);
		oNick << s;
	}
	else {
		if (true == sSymbol.empty())
			sSymbol = Quotes_DBGetStringT(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_SYMBOL);

		oNick << std::setfill(_T(' ')) << std::setw(10) << std::left << sSymbol << std::setw(6) << std::right << dRate;
	}
	CTendency tendency;

	if (true == tendency.Parse(this, m_sTendencyFormat, hContact))
		do_set_contact_extra_icon(hContact, tendency);

	db_set_ts(hContact, LIST_MODULE_NAME, CONTACT_LIST_NAME, oNick.str().c_str());

	tstring sStatusMsg = format_rate(this, hContact, m_sStatusMsgFormat);
	if (false == sStatusMsg.empty())
		db_set_ts(hContact, LIST_MODULE_NAME, STATUS_MSG_NAME, sStatusMsg.c_str());
	else
		db_unset(hContact, LIST_MODULE_NAME, STATUS_MSG_NAME);

	bool bUseContactSpecific = (db_get_b(hContact, QUOTES_PROTOCOL_NAME, DB_STR_CONTACT_SPEC_SETTINGS, 0) > 0);

	CAdvProviderSettings global_settings(this);

	WORD dwMode = (bUseContactSpecific)
		? db_get_w(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_LOG, static_cast<WORD>(lmDisabled))
		: global_settings.GetLogMode();
	if (dwMode&lmExternalFile) {
		bool bAdd = true;
		bool bOnlyIfChanged = (bUseContactSpecific)
			? (db_get_w(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_LOG_FILE_CONDITION, 1) > 0)
			: global_settings.GetLogOnlyChangedFlag();
		if (true == bOnlyIfChanged) {
			bAdd = ((false == bValidPrev) || (false == IsWithinAccuracy(dRate, dPrev)));
		}
		if (true == bAdd) {
			tstring sLogFileName = (bUseContactSpecific)
				? Quotes_DBGetStringT(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_LOG_FILE, global_settings.GetLogFileName().c_str())
				: global_settings.GetLogFileName();

			if (true == sSymbol.empty()) {
				sSymbol = Quotes_DBGetStringT(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_SYMBOL);
			}

			sLogFileName = GenerateLogFileName(sLogFileName, sSymbol);

			tstring sFormat = global_settings.GetLogFormat();
			if (bUseContactSpecific) {
				CQuotesProviderVisitorDbSettings visitor;
				Accept(visitor);
				sFormat = Quotes_DBGetStringT(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_FORMAT_LOG_FILE, visitor.m_pszDefLogFileFormat);
			}

			log_to_file(this, hContact, sLogFileName, sFormat);
		}
	}
	if (dwMode&lmInternalHistory) {
		bool bAdd = true;
		bool bOnlyIfChanged = (bUseContactSpecific)
			? (db_get_w(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_HISTORY_CONDITION, 1) > 0)
			: global_settings.GetHistoryOnlyChangedFlag();

		if (true == bOnlyIfChanged) {
			bAdd = ((false == bValidPrev) || (false == IsWithinAccuracy(dRate, dPrev)));
		}
		if (true == bAdd) {
			tstring sFormat = (bUseContactSpecific)
				? Quotes_DBGetStringT(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_FORMAT_HISTORY, global_settings.GetHistoryFormat().c_str())
				: global_settings.GetHistoryFormat();

			log_to_history(this, hContact, nTime, sFormat);
		}
	}

	if (dwMode&lmPopup) {
		bool bOnlyIfChanged = (bUseContactSpecific)
			? (1 == db_get_b(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_POPUP_CONDITION, 1) > 0)
			: global_settings.GetShowPopupIfValueChangedFlag();
		if ((false == bOnlyIfChanged)
			|| ((true == bOnlyIfChanged) && (true == bValidPrev) && (false == IsWithinAccuracy(dRate, dPrev)))) {
			tstring sFormat = (bUseContactSpecific)
				? Quotes_DBGetStringT(hContact, QUOTES_PROTOCOL_NAME, DB_STR_QUOTE_FORMAT_POPUP, global_settings.GetPopupFormat().c_str())
				: global_settings.GetPopupFormat();

			CPopupSettings ps = *(global_settings.GetPopupSettingsPtr());
			ps.InitForContact(hContact);
			show_popup(this, hContact, tendency, sFormat, ps);
		}
	}

	SetContactStatus(hContact, ID_STATUS_ONLINE);
}
Exemplo n.º 8
0
void netbios_name::DatagramReceiver()
{
	UCHAR* SMBBlock = (UCHAR*)mir_alloc( 65536 );
	if ( ! SMBBlock )
	{
		m_error = true;
		return;
	}

	m_error = false;
	while ( WaitForSingleObject ( m_term, 50 ) == WAIT_TIMEOUT )
	{
		ZeroMemory( SMBBlock, 65536 );

		WORD iReadedBytes = 65535;
		netbios_name nname_from;
		UCHAR ret = pluginNetBIOS.RecvDatagram( nname_from, *this, SMBBlock, iReadedBytes );
		if ( ret != NRC_GOODRET )
		{
			// Ошибка - выход
			m_error = true;
			break;
		}

		nname_from.m_lana = m_lana;

		LOG( "Got datagram from \"%s\" to \"%s\"", nname_from.GetANSIFullName(), GetANSIFullName() );

		// Свое собственное сообщение?
		if ( IsItMe ( CA2T( nname_from.original ) ) )
		{
			LOG( "DatagramReceiver : Ignoring my datagram" );
			continue;
		}

		// Обработка датаграмм
		if ( iReadedBytes > 2 && *(WORD*)SMBBlock == SM_MAGIC )
		{
			UCHAR iMsgType = SMBBlock[ 2 ];
			switch ( iMsgType )
			{
			case SM_GETSTATUS:
				// Отвечаем своим статусом
				LOG( "DatagramReceiver : It's status request" );
				pluginNetBIOS.SendStatus( *this, nname_from );
				break;

			case SM_SENDSTATUS:
				// Находим контакт и ставим его статус
				if ( iReadedBytes == 2 + 1 + 4 )
				{
					HANDLE hContact = GetContact(  CA2T( nname_from.original ) );
					if ( hContact )
					{
						LOG( "DatagramReceiver : It's status answer" );
						SetContactStatus( hContact, *(__int32*)(SMBBlock + 2 + 1), false );
					}
					else
						LOG( "DatagramReceiver : Unknown contact" );
				}
				else
					LOG( "DatagramReceiver : Invalid format" );
				break;

			case SM_GETAWAYMESSAGE:
				// Отвечаем своим эвей-сообщением
				LOG( "DatagramReceiver : It's away request" );
				pluginNetBIOS.SendAway( *this, nname_from );
				break;

			case SM_SENDAWAYMESSAGE:
				// Находим контакт и ставим его эвей-сообщение
				if ( iReadedBytes >= 2 + 1 + 4 )
				{
					if ( HANDLE hContact = GetContact( CA2T( nname_from.original ) ) )
					{
						LPCSTR szAway = (LPCSTR)( SMBBlock + 2 + 1 + 4 );
						SMBBlock[ iReadedBytes ] = 0;	// ASCII -> ASCIIZ

						LOG( "DatagramReceiver : It's away answer \"%s\"", szAway );
						SetContactAway( hContact, szAway );
					}
					else
						LOG( "DatagramReceiver : Unknown contact" );
				}
				else
					LOG( "DatagramReceiver : Invalid format" );
				break;

			case SM_GETAVATAR:
				// Отвечаем своим аватаром
				LOG( "DatagramReceiver : It's avatar request." );
				pluginNetBIOS.SendAvatar( *this, nname_from );
				break;

			case SM_SENDAVATAR:
				// Находим контакт и ставим его аватар
				if ( iReadedBytes >= 2 + 1 && iReadedBytes < MAX_AVATAR_SIZE + 3 )
				{
					if ( HANDLE hContact = GetContact( CA2T( nname_from.original ) ) )
					{
						LOG( "DatagramReceiver : It's avatar answer" );
						SetContactAvatar( hContact, SMBBlock + 2 + 1, (DWORD)iReadedBytes - 3 );
					}
					else
						LOG( "DatagramReceiver : Unknown contact" );
				}
				else
					LOG( "DatagramReceiver : Invalid format or too big avatar" );
				break;

			default:
				LOG( "DatagramReceiver : Unsupported message type 0x%02x", iMsgType );
			}
		}
		else
			LOG( "DatagramReceiver : Unsupported data 0x%04x", *(WORD*)SMBBlock );
	}

	mir_free( SMBBlock );
}
Exemplo n.º 9
0
void CSteamProto::ParsePollData(JSONNode *data)
{
	JSONNode *node, *item = NULL;

	std::string steamIds;
	for (size_t i = 0; i < json_size(data); i++)
	{
		item = json_at(data, i);
		if (item == NULL)
			break;

		node = json_get(item, "steamid_from");
		ptrA steamId(mir_t2a(ptrT(json_as_string(node))));

		node = json_get(item, "utc_timestamp");
		time_t timestamp = atol(ptrA(mir_t2a(ptrT(json_as_string(node)))));

		node = json_get(item, "type");
		ptrT type(json_as_string(node));
		if (!lstrcmpi(type, _T("saytext")) || !lstrcmpi(type, _T("emote")) ||
			!lstrcmpi(type, _T("my_saytext")) || !lstrcmpi(type, _T("my_emote")))
		{
			MCONTACT hContact = FindContact(steamId);
			if (!hContact)
				continue;

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

			if (_tcsstr(type, _T("my_")) == NULL)
			{
				PROTORECVEVENT recv = { 0 };
				recv.timestamp = timestamp;
				recv.szMessage = szMessage;
				ProtoChainRecvMsg(hContact, &recv);
			}
			else
			{
				AddDBEvent(hContact, EVENTTYPE_MESSAGE, timestamp, DBEF_UTF | DBEF_SENT, (int)mir_strlen(szMessage) + 1, (PBYTE)(char*)szMessage);
			}
		}
		else if (!lstrcmpi(type, _T("typing")))
		{
			MCONTACT hContact = FindContact(steamId);
			if (hContact)
			{
				CallService(MS_PROTO_CONTACTISTYPING, hContact, (LPARAM)STEAM_TYPING_TIME);
			}
		}
		else if (!lstrcmpi(type, _T("personastate")))
		{
			node = json_get(item, "persona_state");
			int status = node ? SteamToMirandaStatus(json_as_int(node)) : -1;

			if (IsMe(steamId))
			{
				node = json_get(item, "persona_name");
				setTString("Nick", ptrT(json_as_string(node)));

				if (status == -1 || status == ID_STATUS_OFFLINE)
					continue;

				if (status != m_iStatus)
				{
					debugLog(_T("CSteamProto::ParsePollData: Change own status to %i"), status);
					int oldStatus = m_iStatus;
					m_iStatus = m_iDesiredStatus = status;
					ProtoBroadcastAck(NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)oldStatus, m_iStatus);
				}

				continue;
			}
			
			MCONTACT hContact = FindContact(steamId);
			if (hContact == NULL)
				continue; // probably this is info about random player playing on same server, so we ignore it

			if (status != -1)
				SetContactStatus(hContact, status);

			node = json_get(item, "persona_name");
			setTString(hContact, "Nick", ptrT(json_as_string(node)));

			// todo: find difference between state changing and info changing
			steamIds.append(steamId).append(",");
		}
		else if (!lstrcmpi(type, _T("personarelationship")))
		{
			node = json_get(item, "persona_state");
			int state = json_as_int(node);

			switch (state)
			{
			case 0:
				{// removed
					MCONTACT hContact = FindContact(steamId);
					if (hContact)
					{
						ContactIsRemoved(hContact);
					}
				}
				break;

			case 1:
				{// ignored
					MCONTACT hContact = FindContact(steamId);
					if (hContact)
					{
						ContactIsIgnored(hContact);
					}
				}
				break;

			case 2:
				{// auth request
					/*MCONTACT hContact = FindContact(steamId);
					if (!hContact)
						hContact = AddContact(steamId, true);*/

					//RaiseAuthRequestThread((void*)hContact);

					ptrA token(getStringA("TokenSecret"));

					PushRequest(
						new GetUserSummariesRequest(token, steamId),
						&CSteamProto::OnAuthRequested,
						mir_strdup(steamId),
						MirFreeArg);
				}
				break;

			case 3:
				// add to list
				// todo
				break;

			default: continue;
			}
		}
		/*else if (!lstrcmpi(type, _T("leftconversation")))
		{
		}*/
		else
		{
			continue;
		}
	}

	if (!steamIds.empty())
	{
		steamIds.pop_back();
		ptrA token(getStringA("TokenSecret"));

		PushRequest(
			new GetUserSummariesRequest(token, steamIds.c_str()),
			&CSteamProto::OnGotUserSummaries);
	}
}
Exemplo n.º 10
0
void ReceiveContactMessage(LPCTSTR msg_from, LPCTSTR msg_to, LPCTSTR msg_text, int msg_len)
{
	if ( ! pluginInstalled )
		return;

	CString from( msg_from );
	CString to( msg_to );
	CString text( msg_text, msg_len );

	from.MakeUpper();
	to.MakeUpper();

	// Свое собственное сообщение?
	if ( IsItMe( from ) )
	{
		LOG ( "Ignoring my message." );
		return;
	}

	// Нормализация разбиения сообщения на строки
	Normalize( text );

	// Дубликат?
	if (db_get_b (NULL, modname, "Filter-dups", TRUE))
	{		
		// Вычисление прошедшего времени с последнего сообщения
		static FILETIME last_time = { 0, 0 };
		FILETIME current_time;
		GetSystemTimeAsFileTime (&current_time);
		ULONGLONG elapsed =
			((ULONGLONG) current_time.dwLowDateTime |
				(ULONGLONG) current_time.dwHighDateTime << 32) -
			((ULONGLONG) last_time.dwLowDateTime |
				(ULONGLONG) last_time.dwHighDateTime << 32);

		// Вычисление MD5-хэшей отправителя
		MD5Context ctx;
		md5init (&ctx);
		md5update (&ctx, (const unsigned char*)(LPCTSTR)from,
			from.GetLength() * sizeof (TCHAR));
		unsigned char digest_from_current [16] = {0};
		static unsigned char digest_from_last [16] = {0};
		md5final (digest_from_current, &ctx);

		// Вычисление MD5-хэшей сообщения
		md5init (&ctx);
		md5update (&ctx, (const unsigned char*)(LPCTSTR)text,
			text.GetLength() * sizeof (TCHAR));
		unsigned char digest_text_current [16] = {0};
		static unsigned char digest_text_last [16] = {0};
		md5final (digest_text_current, &ctx);

		// Если прошло менее 2 секунд между сообщениями
		if (elapsed < 20000000)
		{
			// И отправители совпадают
			if (memcmp (digest_from_current, digest_from_last, 16) == 0)
			{
				// И сообщение совпадает
				if (memcmp (digest_text_current, digest_text_last, 16) == 0)
				{
					// то пропускаем такое сообщение
					LOG ("Duplicate message detected");
					return;
				}
			}
		}
		last_time = current_time;
		CopyMemory (digest_from_last, digest_from_current, 16);
		CopyMemory (digest_text_last, digest_text_current, 16);
	}

#ifdef CHAT_ENABLED
	if ( ! IsItMe( to ) && pluginChatEnabled ) // Групповой адрес?
	{
		// Формирование группового сообщения
		if ( ChatNewSession( to ) )
		{
			// Добавить группу
			ATLVERIFY( ChatAddGroup( to, _T("Normal") ) );

			// Добавить себя
			ATLVERIFY( ChatJoinMe( to, _T("Normal") ) );

			// Добавить "От Кого"
			ATLVERIFY( ChatJoinUser( to, from, _T("Normal") ) );

			// Завершение создания чата
			ATLVERIFY( ChatInitDone( to ) );

			// Перевод чат-контакта в онлайн
			ATLVERIFY( ChatOnline( to ) );

			// Сообщение
			ATLVERIFY( ChatMessage( to, from, text ) );
		}
	}
	else
#endif // CHAT_ENABLED
	{
		// Формирование приватного сообщения
		HANDLE hContact = AddToListByName( from, 0, NULL, false, false );
		if ( hContact )
		{
			PROTORECVEVENT pre = { 0 };
			pre.timestamp = time ();
			CT2A textA( text );
			pre.szMessage = (LPSTR)(LPCSTR)textA;
			CCSDATA ccs = { 0 };
			ccs.szProtoService = PSR_MESSAGE;
			ccs.hContact = hContact;
			db_unset (ccs.hContact, "CList", "Hidden");
			ccs.lParam = (LPARAM) &pre;
			CallServiceSync (MS_PROTO_CHAINRECV, 0, (LPARAM) &ccs);

			// Переводим контакт в онлайн
			SetContactStatus( hContact, contact_scanner::ScanContact( hContact ), true );

			// Авто-ответчик
			if ( db_get_b( NULL, modname, "Auto-answer", FALSE ) )
				Autoanswer( hContact );
		}
	}
}