Exemplo n.º 1
0
void CVkProto::OnReceiveMyInfo(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq)
{
	debugLogA("CVkProto::OnReceiveMyInfo %d", reply->resultCode);
	if (reply->resultCode != 200) {
		ConnectionFailed(LOGINERR_WRONGPASSWORD);
		return;
	}

	JSONROOT pRoot;
	JSONNODE *pResponse = CheckJsonResponse(pReq, reply, pRoot);
	if (pResponse == NULL)
		return;

	for (size_t i = 0; i < json_size(pResponse); i++) {
		JSONNODE *it = json_at(pResponse, i);
		LPCSTR id = json_name(it);
		if (!_stricmp(id, "user_id")) {
			m_myUserId = json_as_int(it);
			setDword("ID", m_myUserId);
		}
	}

	OnLoggedIn();
	RetrieveUserInfo(m_myUserId);
	RetrieveFriends();
	RetrieveUnreadMessages();
	RetrievePollingInfo();
}
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 CVkProto::PollUpdates(JSONNODE *pUpdates)
{
	debugLogA("CVkProto::PollUpdates");

	CMStringA mids;
	int msgid, uid, flags;
	MCONTACT hContact;

	JSONNODE *pChild;
	for (int i = 0; (pChild = json_at(pUpdates, i)) != NULL; i++) {
		switch (json_as_int(json_at(pChild, 0))) {
		case VKPOLL_MSG_ADDED: // new message
			msgid = json_as_int(json_at(pChild, 1));

			// skip outgoing messages sent from a client
			flags = json_as_int(json_at(pChild, 2));
			if ((flags & VKFLAG_MSGOUTBOX) && !(flags & VKFLAG_MSGCHAT))
				if (CheckMid(msgid))
					break;

			if (!mids.IsEmpty())
				mids.AppendChar(',');
			mids.AppendFormat("%d", msgid);
			break;

		case VKPOLL_USR_ONLINE:
			uid = -json_as_int(json_at(pChild, 1));
			if ((hContact = FindUser(uid)) != NULL)
				setWord(hContact, "Status", ID_STATUS_ONLINE);
			break;

		case VKPOLL_USR_OFFLINE:
			uid = -json_as_int(json_at(pChild, 1));
			if ((hContact = FindUser(uid)) != NULL)
				setWord(hContact, "Status", ID_STATUS_OFFLINE);
			break;

		case VKPOLL_USR_UTN:
			uid = json_as_int(json_at(pChild, 1));
			if ((hContact = FindUser(uid)) != NULL)
				CallService(MS_PROTO_CONTACTISTYPING, hContact, 5);
			break;

		case VKPOLL_CHAT_CHANGED:
			int chat_id = json_as_int(json_at(pChild, 1));
			CVkChatInfo *cc = m_chats.find((CVkChatInfo*)&chat_id);
			if (cc)
				RetrieveChatInfo(cc);
			break;
		}
	}

	RetrieveMessagesByIds(mids);
}
Exemplo n.º 4
0
void CVkProto::OnReceiveUserInfo(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq)
{
	debugLogA("CVkProto::OnReceiveUserInfo %d", reply->resultCode);
	if (reply->resultCode != 200)
		return;

	JSONROOT pRoot;
	JSONNODE *pResponse = CheckJsonResponse(pReq, reply, pRoot);
	if (pResponse == NULL)
		return;

	for (size_t i=0; ; i++) {
		JSONNODE *pRecord = json_at(pResponse, i);
		if (pRecord == NULL) break;

		LONG userid = json_as_int( json_get(pRecord, "uid"));
		if (userid == 0)
			return;

		MCONTACT hContact;
		if (userid == m_myUserId)
			hContact = NULL;
		else if ((hContact = FindUser(userid, false)) == NULL)
			return;

		CMString tszNick;
		ptrT szValue( json_as_string( json_get(pRecord, "first_name")));
		if (szValue) {
			setTString(hContact, "FirstName", szValue);
			tszNick.Append(szValue);
			tszNick.AppendChar(' ');
		}

		if (szValue = json_as_string( json_get(pRecord, "last_name"))) {
			setTString(hContact, "LastName", szValue);
			tszNick.Append(szValue);
		}

		if (!tszNick.IsEmpty())
			setTString(hContact, "Nick", tszNick);
	
		setByte(hContact, "Gender", json_as_int( json_get(pRecord, "sex")) == 2 ? 'M' : 'F');
	
		if (szValue = json_as_string( json_get(pRecord, "bdate"))) {
			int d, m, y;
			if ( _stscanf(szValue, _T("%d.%d.%d"), &d, &m, &y) == 3) {
				setByte(hContact, "BirthDay", d);
				setByte(hContact, "BirthMonth", m);
				setWord(hContact, "BirthYear", y);
			}
		}

		szValue = json_as_string( json_get(pRecord, "photo_medium"));
		SetAvatarUrl(hContact, szValue);
	}
}
Exemplo n.º 5
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);
	}
}
void Callback(JSONNODE * test, void *){
    ++counter;
    switch(counter){
	   case 1:
		  assertEquals(json_type(test), JSON_NODE);
		  assertTrue(json_empty(test));
		  break;
	   case 2:
		  assertEquals(json_type(test), JSON_ARRAY);
		  assertTrue(json_empty(test));
		  break;
	   case 3:{
		  assertEquals(json_type(test), JSON_NODE);
		  assertEquals(json_size(test), 1);
		  json_char * temp = json_name(json_at(test, 0));
		  assertCStringSame(temp, JSON_TEXT("hello"));
		  json_free(temp);
		  assertEquals(json_as_int(json_at(test, 0)), 1);
		  break;}
	   case 4:
		  assertEquals(json_type(test), JSON_ARRAY);
		  assertEquals(json_size(test), 3);
		  break;
	   case 5:{
		  assertEquals(json_type(test), JSON_NODE);
		  assertEquals(json_size(test), 1);
		  json_char * temp = json_name(json_at(test, 0));
		  assertCStringSame(temp, JSON_TEXT("hi"));
		  json_free(temp);
		  assertEquals(json_size(json_at(test, 0)), 1);
		  assertEquals(json_type(json_at(json_at(test, 0),0)), JSON_NUMBER);
		  temp = json_name(json_at(json_at(test, 0),0));
		  assertCStringSame(temp, JSON_TEXT("one"));
		  json_free(temp);
		  assertEquals(json_as_int(json_at(json_at(test, 0),0)), 1);
		  break;}
    }
}
void JSON_Get_child_by_position(sLONG_PTR *pResult, PackagePtr pParams)
{
	C_TEXT json;
	C_LONGINT pos;
	C_TEXT returnValue;
	
	json.fromParamAtIndex(pParams, 1);
	pos.fromParamAtIndex(pParams, 2);
	
	JSONNODE *n = _fromHex(json);
	
	if(n){
		JSONNODE *node = json_at(n, pos.getIntValue()-1);
		_toHex(node, returnValue);
	}
	
	returnValue.setReturn(pResult);
}
Exemplo n.º 8
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.º 9
0
void CVkProto::OnReceiveChatInfo(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq)
{
	debugLogA("CVkProto::OnReceiveChatInfo %d", reply->resultCode);
	if (reply->resultCode != 200)
		return;

	JSONROOT pRoot;
	JSONNODE *pResponse = CheckJsonResponse(pReq, reply, pRoot);
	if (pResponse == NULL)
		return;

	CVkChatInfo *cc = (CVkChatInfo*)pReq->pUserInfo;
	if (m_chats.indexOf(cc) == -1)
		return;

	JSONNODE *info = json_get(pResponse, "info");
	if (info != NULL) {
		ptrT tszTitle(json_as_string(json_get(info, "title")));
		if (lstrcmp(tszTitle, cc->m_tszTopic)) {
			cc->m_tszTopic = mir_tstrdup(tszTitle);
			setTString(cc->m_hContact, "Nick", tszTitle);

			GCDEST gcd = { m_szModuleName, cc->m_tszId, GC_EVENT_CHANGESESSIONAME };
			GCEVENT gce = { sizeof(GCEVENT), &gcd };
			gce.ptszText = tszTitle;
			CallServiceSync(MS_GC_EVENT, 0, (LPARAM)&gce);
		}
		
		cc->m_admin_id = json_as_int(json_get(info, "admin_id"));
	}

	JSONNODE *users = json_as_array(json_get(pResponse, "users"));
	if (users != NULL) {
		for (int i = 0; i < cc->m_users.getCount(); i++)
			cc->m_users[i].m_bDel = true;

		for (int i = 0;; i++) {
			JSONNODE *pUser = json_at(users, i);
			if (pUser == NULL)
				break;

			int uid = json_as_int(json_get(pUser, "uid"));
			TCHAR tszId[20];
			_itot(uid, tszId, 10);

			bool bNew;
			CVkChatUser *cu = cc->m_users.find((CVkChatUser*)&uid);
			if (cu == NULL) {
				cc->m_users.insert(cu = new CVkChatUser(uid));
				bNew = true;
			}
			else bNew = cu->m_bUnknown;
			cu->m_bDel = false;

			ptrT fName(json_as_string(json_get(pUser, "first_name")));
			ptrT lName(json_as_string(json_get(pUser, "last_name")));
			CMString tszNick = CMString(fName).Trim() + _T(" ") + CMString(lName).Trim();
			cu->m_tszNick = mir_tstrdup(tszNick);
			cu->m_bUnknown = false;
			
			if (bNew) {
				GCDEST gcd = { m_szModuleName, cc->m_tszId, GC_EVENT_JOIN };
				GCEVENT gce = { sizeof(GCEVENT), &gcd };
				gce.bIsMe = uid == m_myUserId;
				gce.ptszUID = tszId;
				gce.ptszNick = tszNick;
				gce.ptszStatus = TranslateTS(sttStatuses[uid == cc->m_admin_id]);
				gce.dwItemData = (INT_PTR)cu;
				CallServiceSync(MS_GC_EVENT, 0, (LPARAM)&gce);
			}
		}

		for (int i = cc->m_users.getCount() - 1; i >= 0; i--) {
			CVkChatUser &cu = cc->m_users[i];
			if (!cu.m_bDel)
				continue;

			TCHAR tszId[20];
			_itot(cu.m_uid, tszId, 10);

			GCDEST gcd = { m_szModuleName, cc->m_tszId, GC_EVENT_PART };
			GCEVENT gce = { sizeof(GCEVENT), &gcd };
			gce.ptszUID = tszId;
			CallServiceSync(MS_GC_EVENT, 0, (LPARAM)&gce);

			cc->m_users.remove(i);
		}
	}

	JSONNODE *msgs = json_as_array(json_get(pResponse, "msgs"));
	if (msgs != NULL) {
		for (int i = 1;; i++) {
			JSONNODE *pMsg = json_at(msgs, i);
			if (pMsg == NULL)
				break;

			AppendChatMessage(cc->m_chatid, pMsg, true);
		}
		cc->m_bHistoryRead = true;
	}

	for (int j = 0; j < cc->m_msgs.getCount(); j++) {
		CVkChatMessage &p = cc->m_msgs[j];
		AppendChatMessage(cc, p.m_mid, p.m_uid, p.m_date, p.m_tszBody, p.m_bHistory);
	}
	cc->m_msgs.destroy();
}
Exemplo n.º 10
0
bool Omegle_client::events()
{
	HANDLE_ENTRY;

	std::string data = "id=" + this->chat_id_;

	// Get update
	http::response resp = flap(OMEGLE_REQUEST_EVENTS, &data);

	// Return
	switch (resp.code)
	{
	case HTTP_CODE_OK:
	{
		if (resp.data == "null") {
			// Everything is OK, no new message received -- OR it is a problem
			// TODO: if we are waiting for Stranger with common likes, then we should try standard Stranger if this takes too long
			return HANDLE_ERROR(false);
		}
		else if (resp.data == "fail") {
			// Something went wrong
			return HANDLE_ERROR(false);
		}

		JSONROOT root(resp.data.c_str());
		if (root == NULL)
			return HANDLE_ERROR(false);

		bool newStranger = false;
		bool waiting = false;

		for (size_t i = 0; i < json_size(root); i++) {
			JSONNode *item = json_at(root, i);
			if (item == NULL)
				continue;

			std::string name = _T2A(json_as_string(json_at(item, 0)));
		
			if (name == "waiting") {
				// We are just waiting for new Stranger
				waiting = true;
			}
			else if (name == "identDigests") {
				// We get some comma separated hashes, I'm not sure what for
			}
			else if (name == "statusInfo") {
				JSONNode *data = json_at(item, 1);

				// We got some object as second parameter
				//data["antinudepercent"]; // probably 1 by default
				//data["antinudeservers"]; // array of server names, like "waw3.omegle.com"
				//data["rtmfp"]; // some rtmfp protocol address
				//data["servers"]; // array of server names, like "front5.omegle.com"
				//data["spyeeQueueTime"]; // some float number, e.g. 0.0701999903
				//data["spyQueueTime"]; // some float number, e.g. 4.7505000114
				//data["timestamp"]; // e.g. 1445336566.0196209

				// We got info about count of connected people there
				ptrT count(json_as_string(json_get(data, "count")));
				TCHAR strT[255];
				mir_sntprintf(strT, TranslateT("On whole Omegle are %s strangers online now."), count);

				parent->UpdateChat(NULL, strT);
			}
			else if (name == "serverMessage") {
				ptrT message(json_as_string(json_at(item, 1)));
				parent->UpdateChat(NULL, TranslateTS(message));
			}
			else if (name == "connected") {
				// Stranger connected
				if (this->spy_mode_ && !this->question_.empty()) {
					parent->AddChatContact(TranslateT("Stranger 1"));
					parent->AddChatContact(TranslateT("Stranger 2"));
					this->state_ = STATE_SPY;
				}
				else {
					parent->AddChatContact(TranslateT("Stranger"));
					this->state_ = STATE_ACTIVE;
				}

				newStranger = true;
				waiting = false;
			}
			else if (name == "commonLikes") {
				std::tstring likes = TranslateT("You and the Stranger both like: ");

				JSONNode *items = json_at(item, 1);
				size_t size = json_size(items);
				for (size_t i = 0; i < size; i++) {
					likes += ptrT(json_as_string(json_at(items, i)));
					if (i < size - 1)
						likes += _T(", ");
				}
				
				parent->debugLog(_T("Got common likes: '%s'"), likes.c_str());
				parent->SetTopic(likes.c_str());
			}
			else if (name == "question") {
				ptrT question(json_as_string(json_at(item, 1)));
				parent->SetTopic(question);
			}
			else if (name == "typing" || name == "spyTyping") {
				// Stranger is typing, not supported by chat module yet
				SkinPlaySound("StrangerTyp");

				StatusTextData st = { 0 };
				st.cbSize = sizeof(st);
				st.hIcon = IcoLib_GetIconByHandle(GetIconHandle("typing_on"));

				ptrT who(name == "spyTyping" ? json_as_string(json_at(item, 1)) : mir_tstrdup(_T("Stranger")));
				mir_sntprintf(st.tszText, TranslateT("%s is typing."), TranslateTS(who));

				CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)parent->GetChatHandle(), (LPARAM)&st);
			}
			else if (name == "stoppedTyping" || name == "spyStoppedTyping") {
				// Stranger stopped typing, not supported by chat module yet
				SkinPlaySound("StrangerTypStop");

				StatusTextData st = { 0 };
				st.cbSize = sizeof(st);
				st.hIcon = IcoLib_GetIconByHandle(GetIconHandle("typing_off"));

				ptrT who(name == "spyTyping" ? json_as_string(json_at(item, 1)) : mir_tstrdup(_T("Stranger")));
				mir_sntprintf(st.tszText, TranslateT("%s stopped typing."), TranslateTS(who));

				CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)parent->GetChatHandle(), (LPARAM)&st);
			}
			else if (name == "gotMessage") {
				CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)parent->GetChatHandle(), NULL);

				// Play sound as we received message
				SkinPlaySound("StrangerMessage");

				if (state_ == STATE_ACTIVE) {
					ptrT msg(json_as_string(json_at(item, 1)));
					parent->UpdateChat(TranslateT("Stranger"), msg);
				}
			}
			else if (name == "spyMessage") {
				CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)parent->GetChatHandle(), NULL);

				// Play sound as we received message
				SkinPlaySound("StrangerMessage");

				if (state_ == STATE_SPY) {
					ptrT stranger(json_as_string(json_at(item, 1)));
					ptrT msg(json_as_string(json_at(item, 2)));
					parent->UpdateChat(stranger, msg);
				}
			}
			else if (name == "strangerDisconnected") {
				CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)parent->GetChatHandle(), NULL);

				// Stranger disconnected
				if (db_get_b(NULL, parent->m_szModuleName, OMEGLE_KEY_DONT_STOP, 0))
				{
					SkinPlaySound("StrangerChange");
					parent->NewChat();
				}
				else
					parent->StopChat(false);
			}
			else if (name == "spyDisconnected") {
				CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)parent->GetChatHandle(), NULL);

				ptrT stranger(json_as_string(json_at(item, 1)));

				TCHAR strT[255];
				mir_sntprintf(strT, TranslateT("%s disconnected."), TranslateTS(stranger));
				parent->UpdateChat(NULL, strT);

				// Stranger disconnected
				if (db_get_b(NULL, parent->m_szModuleName, OMEGLE_KEY_DONT_STOP, 0))
				{
					SkinPlaySound("StrangerChange");
					parent->NewChat();
				}
				else
					parent->StopChat(false);
			}
			else if (name == "recaptchaRequired") {
				// Nothing to do with recaptcha
				parent->UpdateChat(NULL, TranslateT("Recaptcha is required.\nOpen http://omegle.com , solve Recaptcha and try again."));
				parent->StopChat(false);
			}
			else if (name == "recaptchaRejected") {
				// Nothing to do with recaptcha
				parent->StopChat(false);
			}
			else if (name == "error") {
				ptrT error(json_as_string(json_at(item, 1)));

				TCHAR strT[255];
				mir_sntprintf(strT, TranslateT("Error: %s"), TranslateTS(error));
				parent->UpdateChat(NULL, strT);
			}
		}
		
		if (newStranger && !spy_mode_) {
			// We got new stranger in this event, lets say him "Hi message" if enabled			
			if (db_get_b(NULL, parent->m_szModuleName, OMEGLE_KEY_HI_ENABLED, 0)) {
				DBVARIANT dbv;
				if (!db_get_utf(NULL, parent->m_szModuleName, OMEGLE_KEY_HI, &dbv)) {
					std::vector<std::string> messages;
					utils::text::explode(std::string(dbv.pszVal), "\r\n", &messages);
					db_free(&dbv);

					int pos = rand() % messages.size();
					std::string *message = new std::string(messages.at(pos));

					parent->debugLogA("**Chat - saying Hi! message");
					parent->ForkThread(&OmegleProto::SendMsgWorker, message);
				}
				else parent->debugLogA("**Chat - Hi message is enabled but not used");
			}
		}

		if (waiting) {
			// If we are only waiting in this event...
			parent->UpdateChat(NULL, TranslateT("We are still waiting..."));
		}

		return HANDLE_SUCCESS;
	}

	case HTTP_CODE_FAKE_DISCONNECTED:
		// timeout
		return HANDLE_SUCCESS;

	case HTTP_CODE_FAKE_ERROR:
	default:
		return HANDLE_ERROR(false);
	}
}
Exemplo n.º 11
0
CMString CVkProto::GetAttachmentDescr(JSONNODE *pAttachments)
{
	CMString res;
	res.AppendChar('\n');
	res += TranslateT("Attachments:");
	res.AppendChar('\n');
	JSONNODE *pAttach;
	for (int k = 0; (pAttach = json_at(pAttachments, k)) != NULL; k++) {
		res.AppendChar('\t');
		ptrT ptszType(json_as_string(json_get(pAttach, "type")));
		if (!lstrcmp(ptszType, _T("photo"))) {
			JSONNODE *pPhoto = json_get(pAttach, "photo");
			if (pPhoto == NULL) continue;

			ptrT ptszLink;
			for (int i = 0; i < SIZEOF(szImageTypes); i++) {
				JSONNODE *n = json_get(pPhoto, szImageTypes[i]);
				if (n != NULL) {
					ptszLink = json_as_string(n);
					break;
				}
			}

			int iWidth = json_as_int(json_get(pPhoto, "width"));
			int iHeight = json_as_int(json_get(pPhoto, "height"));
			res.AppendFormat(_T("%s: %s (%dx%d)"), TranslateT("Photo"), ptszLink, iWidth, iHeight);
		}
		else if (!lstrcmp(ptszType, _T("audio"))) {
			JSONNODE *pAudio = json_get(pAttach, "audio");
			if (pAudio == NULL) continue;

			int  aid = json_as_int(json_get(pAudio, "aid"));
			int  ownerID = json_as_int(json_get(pAudio, "owner_id"));
			ptrT ptszArtist(json_as_string(json_get(pAudio, "artist")));
			ptrT ptszTitle(json_as_string(json_get(pAudio, "title")));
			res.AppendFormat(_T("%s: (%s - %s) - http://vk.com/audio%d_%d"),
				TranslateT("Audio"), ptszArtist, ptszTitle, ownerID, aid);
		}
		else if (!lstrcmp(ptszType, _T("video"))) {
			JSONNODE *pVideo = json_get(pAttach, "video");
			if (pVideo == NULL) continue;

			ptrT ptszTitle(json_as_string(json_get(pVideo, "title")));
			int  vid = json_as_int(json_get(pVideo, "vid"));
			int  ownerID = json_as_int(json_get(pVideo, "owner_id"));
			res.AppendFormat(_T("%s: %s - http://vk.com/video%d_%d"),
				TranslateT("Video"), ptszTitle, ownerID, vid);
		}
		else if (!lstrcmp(ptszType, _T("doc"))) {
			JSONNODE *pDoc = json_get(pAttach, "doc");
			if (pDoc == NULL) continue;

			ptrT ptszTitle(json_as_string(json_get(pDoc, "title")));
			ptrT ptszUrl(json_as_string(json_get(pDoc, "url")));
			res.AppendFormat(_T("%s: (%s) - %s"),
				TranslateT("Document"), ptszTitle, ptszUrl);
		}
		else if (!lstrcmp(ptszType, _T("wall"))) {
			JSONNODE *pWall = json_get(pAttach, "wall");
			if (pWall == NULL) continue;

			ptrT ptszText(json_as_string(json_get(pWall, "text")));
			int  id = json_as_int(json_get(pWall, "id"));
			int  fromID = json_as_int(json_get(pWall, "from_id"));
			res.AppendFormat(_T("%s: %s - http://vk.com/wall%d_%d"),
				TranslateT("Wall post"), ptszText, fromID, id);
		}
		else res.AppendFormat(TranslateT("Unsupported or unknown attachment type: %s"), ptszType);

		res.AppendChar('\n');
	}

	return res;
}
Exemplo n.º 12
0
void CVkProto::OnReceiveMessages(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq)
{
	debugLogA("CVkProto::OnReceiveMessages %d", reply->resultCode);
	if (reply->resultCode != 200)
		return;

	JSONROOT pRoot;
	JSONNODE *pResponse = CheckJsonResponse(pReq, reply, pRoot);
	if (pResponse == NULL)
		return;

	JSONNODE *pDlgs = json_as_array(json_get(pResponse, "dlgs"));
	if (pDlgs != NULL) {
		int numDialogs = json_as_int(json_at(pDlgs, 0));
		for (int i = 1; i <= numDialogs; i++) {
			JSONNODE *pDlg = json_at(pDlgs, i);
			if (pDlg == NULL)
				continue;

			int chatid = json_as_int(json_get(pDlg, "chat_id"));
			if (chatid != 0)
			if (m_chats.find((CVkChatInfo*)&chatid) == NULL) {
				AppendChat(chatid, pDlg);
			}
		}
	}

	CMStringA mids, lmids;
	bool bDirectArray = false;

	JSONNODE *pMsgs = json_as_array(json_get(pResponse, "msgs"));
	if (pMsgs == NULL) {
		pMsgs = pResponse;
		bDirectArray = true;
	}

	int numMessages = json_as_int(json_at(pMsgs, 0));
	for (int i = 1; i <= numMessages; i++) {
		JSONNODE *pMsg = json_at(pMsgs, i);
		if (pMsg == NULL)
			continue;

		char szMid[40];
		int mid = json_as_int(json_get(pMsg, "mid"));
		_itoa(mid, szMid, 10);
		if (!mids.IsEmpty())
			mids.AppendChar(',');
		mids.Append(szMid);

		int chat_id = json_as_int(json_get(pMsg, "chat_id"));
		if (chat_id != 0) {
			AppendChatMessage(chat_id, pMsg, false);
			continue;
		}

		// VK documentation lies: even if you specified preview_length=0, 
		// long messages get cut out. So we need to retrieve them from scratch
		ptrT ptszBody(json_as_string(json_get(pMsg, "body")));
		if (!bDirectArray && _tcslen(ptszBody) > 1000) {
			if (!lmids.IsEmpty())
				lmids.AppendChar(',');
			lmids.Append(szMid);
			continue;
		}

		int datetime = json_as_int(json_get(pMsg, "date"));
		int isOut = json_as_int(json_get(pMsg, "out"));
		int uid = json_as_int(json_get(pMsg, "uid"));
		int isRead = json_as_int(json_get(pMsg, "read_state"));

		JSONNODE *pAttachments = json_get(pMsg, "attachments");
		if (pAttachments != NULL)
			ptszBody = mir_tstrdup(CMString(ptszBody) + GetAttachmentDescr(pAttachments));

		MCONTACT hContact = FindUser(uid, true);

		PROTORECVEVENT recv = { 0 };
		recv.flags = PREF_TCHAR;
		if (isRead)
			recv.flags |= PREF_CREATEREAD;
		if (isOut)
			recv.flags |= PREF_SENT;
		recv.timestamp = datetime;
		recv.tszMessage = ptszBody;
		recv.lParam = isOut;
		recv.pCustomData = szMid;
		recv.cbCustomDataSize = (int)strlen(szMid);
		ProtoChainRecvMsg(hContact, &recv);
	}

	MarkMessagesRead(mids);
	RetrieveMessagesByIds(lmids);
}
Exemplo n.º 13
0
void CVkProto::OnReceiveFriends(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq)
{
	debugLogA("CVkProto::OnReceiveFriends %d", reply->resultCode);
	if (reply->resultCode != 200)
		return;

	JSONROOT pRoot;
	JSONNODE *pResponse = CheckJsonResponse(pReq, reply, pRoot), *pInfo;
	if (pResponse == NULL)
		return;

	bool bCleanContacts = getByte("AutoClean", 0) != 0;
	LIST<void> arContacts(10, PtrKeySortT);
	if (bCleanContacts)
		for (MCONTACT hContact = db_find_first(m_szModuleName); hContact; hContact = db_find_next(hContact, m_szModuleName))
			if (!isChatRoom(hContact))
				arContacts.insert((HANDLE)hContact);

	for (int i = 0; (pInfo = json_at(pResponse, i)) != NULL; i++) {
		ptrT szValue(json_as_string(json_get(pInfo, "uid")));
		if (szValue == NULL)
			continue;

		CMString tszNick;
		MCONTACT hContact = FindUser(_ttoi(szValue), true);
		arContacts.remove((HANDLE)hContact);
		szValue = json_as_string(json_get(pInfo, "first_name"));
		if (szValue) {
			setTString(hContact, "FirstName", szValue);

			tszNick.Append(szValue);
			tszNick.AppendChar(' ');
		}

		if (szValue = json_as_string(json_get(pInfo, "last_name"))) {
			setTString(hContact, "LastName", szValue);
			tszNick.Append(szValue);
		}

		if (!tszNick.IsEmpty())
			setTString(hContact, "Nick", tszNick);

		szValue = json_as_string(json_get(pInfo, "photo_medium"));
		SetAvatarUrl(hContact, szValue);

		setWord(hContact, "Status", (json_as_int(json_get(pInfo, "online")) == 0) ? ID_STATUS_OFFLINE : ID_STATUS_ONLINE);

		int iValue = json_as_int(json_get(pInfo, "sex"));
		if (iValue)
			setByte(hContact, "Gender", (iValue == 2) ? 'M' : 'F');

		if ((iValue = json_as_int(json_get(pInfo, "timezone"))) != 0)
			setByte(hContact, "Timezone", iValue * -2);

		szValue = json_as_string(json_get(pInfo, "mobile_phone"));
		if (szValue && *szValue)
			setTString(hContact, "Cellular", szValue);
		szValue = json_as_string(json_get(pInfo, "home_phone"));
		if (szValue && *szValue)
			setTString(hContact, "Phone", szValue);
	}

	if (bCleanContacts)
		for (int i = 0; i < arContacts.getCount(); i++)
			CallService(MS_DB_CONTACT_DELETE, (WPARAM)arContacts[i], 0);
}
void TestSuite::TestFunctions(void){
    UnitTest::SetPrefix("TestFunctions.cpp - Swap");
    #ifdef JSON_LIBRARY
		  JSONNODE * test1 = json_new(JSON_NODE);
		  JSONNODE * test2 = json_new(JSON_NODE);
		  json_set_i(test1, 14);
		  json_set_i(test2, 35);
		  json_swap(test1, test2);
		  assertEquals_Primitive(json_as_int(test1), 35);
		  assertEquals_Primitive(json_as_int(test2), 14);

		  UnitTest::SetPrefix("TestFunctions.cpp - Duplicate");
		  json_delete(test1);
		  test1 = json_duplicate(test2);
		  #ifdef JSON_UNIT_TEST
			 assertNotEquals(((JSONNode*)test1) -> internal, ((JSONNode*)test2) -> internal);
		  #endif
		  assertTrue(json_equal(test1, test2));


		  UnitTest::SetPrefix("TestFunctions.cpp - Duplicate with children");
		  JSONNODE * node = json_new(JSON_NODE);
		  json_push_back(node, json_new_i(JSON_TEXT(""), 15));
		  json_push_back(node, json_new_f(JSON_TEXT(""), 27.4f));
		  json_push_back(node, json_new_b(JSON_TEXT(""), true));

		  TestSuite::testParsingItself(node);

		  JSONNODE * dup = json_duplicate(node);
		  assertEquals(json_size(dup), 3);
		  #ifdef JSON_UNIT_TEST
			 assertNotEquals(((JSONNode*)node) -> internal, ((JSONNode*)dup) -> internal);
		  #endif
		  assertEquals(json_type(dup), JSON_NODE);

		  TestSuite::testParsingItself(node);
		  TestSuite::testParsingItself(dup);

		  assertEquals_Primitive(json_as_int(json_at(dup, 0)), 15);
		  assertEquals_Primitive(json_as_float(json_at(dup, 1)), 27.4f);
		  assertEquals(json_as_bool(json_at(dup, 2)), true);
		  assertTrue(json_equal(json_at(dup, 0), json_at(node, 0)));
		  assertTrue(json_equal(json_at(dup, 1), json_at(node, 1)));
		  assertTrue(json_equal(json_at(dup, 2), json_at(node, 2)));


		  TestSuite::testParsingItself(dup);

		  #ifdef JSON_ITERATORS
			 for(JSONNODE_ITERATOR it = json_begin(node), end = json_end(node), dup_it = json_begin(dup);
				it != end;
				++it, ++dup_it){
				assertTrue(json_equal(*it, *dup_it));
				#ifdef JSON_UNIT_TEST
				    assertNotEquals(((JSONNode*)(*it)) -> internal, ((JSONNode*)(*dup_it)) -> internal);
				#endif
			 }
		  #endif

		  UnitTest::SetPrefix("TestFunctions.cpp - Nullify");
		  json_nullify(test1);
		  assertEquals(json_type(test1), JSON_NULL);
		  json_char * res = json_name(test1);
		  assertCStringSame(res, JSON_TEXT(""));
		  json_free(res);

		  #ifdef JSON_CASTABLE
			  UnitTest::SetPrefix("TestFunctions.cpp - Cast");
			  json_cast(test1, JSON_NULL);
			  json_set_i(test2, 1);
			  json_cast(test2, JSON_BOOL);
			  assertEquals(json_type(test1), JSON_NULL);
			  assertEquals(json_type(test2), JSON_BOOL);
			  assertEquals(json_as_bool(test2), true);
			  json_set_b(test2, true);
			  assertEquals(json_as_bool(test2), true);

			  json_cast(test2, JSON_NUMBER);
			  assertEquals_Primitive(json_as_float(test2), 1.0f);
			  json_set_f(test2, 0.0f);
			  assertEquals_Primitive(json_as_float(test2), 0.0f);
			  json_cast(test2, JSON_BOOL);
			  assertEquals(json_as_bool(test2), false);
		  #endif

		  UnitTest::SetPrefix("TestFunctions.cpp - Merge");
		  json_set_a(test1, JSON_TEXT("hello"));
		  json_set_a(test2, JSON_TEXT("hello"));
		  #ifdef JSON_UNIT_TEST
			 assertNotEquals(((JSONNode*)test1) -> internal, ((JSONNode*)test2) -> internal);
		  #endif
		  assertTrue(json_equal(test1, test2));
		  json_merge(test1, test2);
		  #ifdef JSON_UNIT_TEST
			 #ifdef JSON_REF_COUNT
				  assertEquals(((JSONNode*)test1) -> internal, ((JSONNode*)test2) -> internal);
			 #else
				  assertNotEquals(((JSONNode*)test1) -> internal, ((JSONNode*)test2) -> internal);
			 #endif
		  #endif

		#ifdef JSON_CASTABLE
			  json_cast(test1, JSON_NODE);
			  json_cast(test2, JSON_NODE);
			  assertEquals(json_type(test1), JSON_NODE);
			  assertEquals(json_type(test2), JSON_NODE);
			  json_push_back(test1, json_new_a(JSON_TEXT("hi"), JSON_TEXT("world")));
			  json_push_back(test2, json_new_a(JSON_TEXT("hi"), JSON_TEXT("world")));

			  TestSuite::testParsingItself(test1);
			  TestSuite::testParsingItself(test2);

			  json_merge(test1, test2);
			  #ifdef JSON_UNIT_TEST
				 #ifdef JSON_REF_COUNT
					  assertEquals(((JSONNode*)test1) -> internal, ((JSONNode*)test2) -> internal);
				 #else
					  assertNotEquals(((JSONNode*)test1) -> internal, ((JSONNode*)test2) -> internal);
				 #endif
			  #endif

			  TestSuite::testParsingItself(test1);
			  TestSuite::testParsingItself(test2);
		#endif

		  json_delete(test1);
		  json_delete(test2);
		  json_delete(node);
		  json_delete(dup);
    #else
		  JSONNode test1;
		  JSONNode test2;
		  test1 = JSON_TEXT("hello");
		  test2 = JSON_TEXT("world");
		  test1.swap(test2);
		  assertEquals(test1, JSON_TEXT("world"));
		  assertEquals(test2, JSON_TEXT("hello"));

		  UnitTest::SetPrefix("TestFunctions.cpp - Duplicate");
		  test1 = test2.duplicate();
		  #ifdef JSON_UNIT_TEST
			 assertNotEquals(test1.internal, test2.internal);
		  #endif
		  assertEquals(test1, test2);

		  UnitTest::SetPrefix("TestFunctions.cpp - Duplicate with children");
		  JSONNode node = JSONNode(JSON_NODE);
		  node.push_back(JSONNode(JSON_TEXT(""), 15));
		  node.push_back(JSONNode(JSON_TEXT(""), JSON_TEXT("hello world")));
		  node.push_back(JSONNode(JSON_TEXT(""), true));

		  TestSuite::testParsingItself(node);

		  JSONNode dup = node.duplicate();
		  assertEquals(dup.size(), 3);
		  #ifdef JSON_UNIT_TEST
			 assertNotEquals(node.internal, dup.internal);
		  #endif
		  assertEquals(dup.type(), JSON_NODE);

		  TestSuite::testParsingItself(node);
		  TestSuite::testParsingItself(dup);

		  try {
			 assertEquals(dup.at(0), 15);
			 assertEquals(dup.at(1), JSON_TEXT("hello world"));
			 assertEquals(dup.at(2), true);
			 assertEquals(dup.at(0), node.at(0));
			 assertEquals(dup.at(1), node.at(1));
			 assertEquals(dup.at(2), node.at(2));
		  } catch (std::out_of_range){
			 FAIL("exception caught");
		  }

		  TestSuite::testParsingItself(dup);

		  #ifdef JSON_ITERATORS
			 for(JSONNode::iterator it = node.begin(), end = node.end(), dup_it = dup.begin();
				it != end;
				++it, ++dup_it){
				assertEquals(*it, *dup_it);
				#ifdef JSON_UNIT_TEST
				    assertNotEquals((*it).internal, (*dup_it).internal);
				#endif
			 }
		  #endif

		  UnitTest::SetPrefix("TestFunctions.cpp - Nullify");
		  test1.nullify();
		  assertEquals(test1.type(), JSON_NULL);
		  assertEquals(test1.name(), JSON_TEXT(""));

		  #ifdef JSON_CASTABLE
			 UnitTest::SetPrefix("TestFunctions.cpp - Cast");
			 test1.cast(JSON_NULL);
			 test2 = 1;
			 test2.cast(JSON_BOOL);
			 assertEquals(test1.type(), JSON_NULL);
			 assertEquals(test2.type(), JSON_BOOL);
			 assertEquals(test2, true);
			 test2 = true;
			 assertEquals(test2, true);
			 test2.cast(JSON_NUMBER);
			 assertEquals(test2, 1.0f);
			 test2 = 0.0f;
			 assertEquals(test2, 0.0f);
			 test2.cast(JSON_BOOL);
			 assertEquals(test2, false);
		  #endif
    
		  UnitTest::SetPrefix("TestFunctions.cpp - Merge");
		  test1 = JSON_TEXT("hello");
		  test2 = JSON_TEXT("hello");
		  #ifdef JSON_UNIT_TEST
			 assertNotEquals(test1.internal, test2.internal);
		  #endif
		  assertEquals(test1, test2);
		  test1.merge(test2);
		  #ifdef JSON_UNIT_TEST
			 #ifdef JSON_REF_COUNT
				  assertEquals(test1.internal, test2.internal);
			 #else
				  assertNotEquals(test1.internal, test2.internal);
			 #endif
		  #endif

		  #ifdef JSON_CASTABLE
			 test1.cast(JSON_NODE);
			 test2.cast(JSON_NODE);
		  #else
			 test1 = JSONNode(JSON_NODE);
			 test2 = JSONNode(JSON_NODE);
		  #endif
		  assertEquals(test1.type(), JSON_NODE);
		  assertEquals(test2.type(), JSON_NODE);
		  test1.push_back(JSONNode(JSON_TEXT("hi"), JSON_TEXT("world")));
		  test2.push_back(JSONNode(JSON_TEXT("hi"), JSON_TEXT("world")));

		  TestSuite::testParsingItself(test1);
		  TestSuite::testParsingItself(test2);

		  test1.merge(test2);
		  #ifdef JSON_UNIT_TEST
			 #ifdef JSON_REF_COUNT
				  assertEquals(test1.internal, test2.internal);
			 #else
				  assertNotEquals(test1.internal, test2.internal);
			 #endif
		  #endif

		  TestSuite::testParsingItself(test1);
		  TestSuite::testParsingItself(test2);
    #endif
}
Exemplo n.º 15
0
SEXP 
processJSONNode(JSONNODE *n, int parentType, int simplify, SEXP nullValue, int simplifyWithNames, cetype_t charEncoding,
                 SEXP r_stringCall, StringFunctionType str_fun_type)
{
    
    if (n == NULL){
        PROBLEM "invalid JSON input"
	    ERROR;
    }
 
    JSONNODE *i;
    int len = 0, ctr = 0;
    int nprotect = 0;
    int numNulls = 0;
    len = json_size(n);
    char startType = parentType; // was 127
    
    int isNullHomogeneous = (TYPEOF(nullValue) == LGLSXP || TYPEOF(nullValue) == REALSXP ||
                                TYPEOF(nullValue) == STRSXP || TYPEOF(nullValue) == INTSXP);
    int numStrings = 0;
    int numLogicals = 0;
    int numNumbers = 0;

    SEXP ans, names = NULL;
    PROTECT(ans = NEW_LIST(len)); nprotect++;

    int homogeneous = 0;
    int elType = NILSXP;
    while (ctr < len){  // i != json_end(n)

	i = json_at(n, ctr);

        if (i == NULL){
            PROBLEM "Invalid JSON Node"
		ERROR;
        }

	json_char *node_name = json_name(i);
	
	char type = json_type(i);
	if(startType == 127)
	    startType = type;

	SEXP el;
	switch(type) {
   	   case JSON_NULL:
	       el = nullValue; /* R_NilValue; */
	       numNulls++;
	       if(isNullHomogeneous) {
		   homogeneous++;
		   elType = setType(elType, TYPEOF(nullValue));
	       } else
		   elType = TYPEOF(nullValue);
	       break;
   	   case JSON_ARRAY:
  	   case JSON_NODE:
	       el = processJSONNode(i, type, simplify, nullValue, simplifyWithNames, charEncoding, r_stringCall, str_fun_type);
	       if(Rf_length(el) > 1)
		   elType = VECSXP;
	       else
		   elType = setType(elType, TYPEOF(el));
	       break;
 	   case JSON_NUMBER:
	       el = ScalarReal(json_as_float(i));
	       homogeneous++;
	       elType = setType(elType, REALSXP);
	       numNumbers++;
	       break;
 	   case JSON_BOOL:
	       el = ScalarLogical(json_as_bool(i));
	       elType = setType(elType, LGLSXP);
	       numLogicals++;
	       break;
 	   case JSON_STRING:
	   {
//XXX Garbage collection
#if 0 //def JSON_UNICODE
	       wchar_t *wtmp = json_as_string(i);
	       char *tmp;
	       int len = wcslen(wtmp);
	       int size = sizeof(char) * (len * MB_LEN_MAX + 1);
	       tmp = (char *)malloc(size);
	       if (tmp == NULL) {
                   PROBLEM "Cannot allocate memory"
                   ERROR;
               }
	       wcstombs(tmp, wtmp, size);
#else
    char *tmp = json_as_string(i);
//    tmp = reEnc(tmp, CE_BYTES, CE_UTF8, 1);
#endif


    if(r_stringCall != NULL && TYPEOF(r_stringCall) == EXTPTRSXP) {
        if(str_fun_type == SEXP_STR_ROUTINE) {
	    SEXPStringRoutine fun;
	    fun = (SEXPStringRoutine) R_ExternalPtrAddr(r_stringCall);	    
	    el = fun(tmp, charEncoding);
	} else {
	    char *tmp1;
	    StringRoutine fun;
	    fun = (StringRoutine) R_ExternalPtrAddr(r_stringCall);
	    tmp1 = fun(tmp);
	    if(tmp1 != tmp)
		json_free(tmp);
	    tmp = tmp1;
	    el = ScalarString(mkCharCE(tmp, charEncoding));
	}
    } else {
	el = ScalarString(mkCharCE(tmp, charEncoding));
    	     /* Call the R function if there is one. */
	if(r_stringCall != NULL) {
	    SETCAR(CDR(r_stringCall), el);
	    el = Rf_eval(r_stringCall, R_GlobalEnv);
	}
	/* XXX compute with elType. */
    }

	       json_free(tmp);
	       
	       elType = setType(elType, 
   				     /* If we have a class, not a primitive type */
                                  Rf_length(getAttrib(el, Rf_install("class"))) ? LISTSXP : TYPEOF(el));
               if(r_stringCall != NULL && str_fun_type != NATIVE_STR_ROUTINE) {
		   switch(TYPEOF(el)) {
			  case REALSXP:
   			     numNumbers++;
			  break;
			  case LGLSXP:
   			     numLogicals++;
			  break;
			  case STRSXP:
   			     numStrings++;
			  break;
		   }
	       } else if(TYPEOF(el) == STRSXP) 
		   numStrings++;
      }
	       break;
	default:
	    PROBLEM "shouldn't be here"
		WARN;
	    el = R_NilValue;
	    break;
	}
	SET_VECTOR_ELT(ans, ctr, el);

	if(parentType == JSON_NODE || (node_name && node_name[0])) {
	    if(names == NULL) {
	        PROTECT(names = NEW_CHARACTER(len)); nprotect++;
	    }
	    if(node_name && node_name[0])
		SET_STRING_ELT(names, ctr, mkChar(node_name));
	}
	json_free(node_name);
	ctr++;
    }

    /* If we have an empty object, we try to make it into a form equivalent to emptyNamedList
       if it is a {},  or as an AsIs object in R if an empty array. */
    if(len == 0 && (parentType == -1 || parentType == JSON_ARRAY || parentType == JSON_NODE)) {
        if(parentType == -1) 
            parentType = startType;

        if(parentType == JSON_NODE)
	   SET_NAMES(ans, NEW_CHARACTER(0));
        else  {
	   SET_CLASS(ans, ScalarString(mkChar("AsIs")));
	}

    } else if(simplifyWithNames || names == NULL || Rf_length(names) == 0) {
	int allSame = (numNumbers == len || numStrings == len || numLogicals == len) || 
	    ((TYPEOF(nullValue) == LGLSXP && LOGICAL(nullValue)[0] == NA_INTEGER) && 
	     ((numNumbers + numNulls) == len || (numStrings + numNulls) == len || (numLogicals + numNulls) == len));
        homogeneous = allSame ||  ( (numNumbers + numStrings + numLogicals + numNulls) == len);
        if(simplify == NONE) {
	} else if(allSame && 
 		   (numNumbers == len && (simplify & STRICT_NUMERIC)) ||
  		      ((numLogicals == len) && (simplify & STRICT_LOGICAL)) ||
		      ( (numStrings == len) && (simplify & STRICT_CHARACTER))) {
   	       ans = makeVector(ans, len, elType, nullValue);
	} else if((simplify == ALL && homogeneous) || (simplify == STRICT && allSame)) {
   	       ans = makeVector(ans, len, elType, nullValue);
	}
    }
      

    if(names)
	SET_NAMES(ans, names);
	
    UNPROTECT(nprotect);
    return(ans);
}
Exemplo n.º 16
0
    void TestSuite::TestWriter(void){
	   UnitTest::SetPrefix("Writing");
	   #ifdef JSON_LIBRARY	   
		  #define assertWrite(node, func, expected)\
			 {\
				json_char * _temp = func(node);\
				assertCStringSame(_temp, expected);\
				json_free(_temp);\
			 }
		  
		  JSONNODE * test1 = json_new(JSON_NODE);
		  assertWrite(test1, json_write, JSON_TEXT("{}"));
		  json_push_back(test1, json_new_a(JSON_TEXT("Hello"), JSON_TEXT("World")));
		  json_push_back(test1, json_new_b(JSON_TEXT("libjson"), true));
		  assertWrite(test1, json_write, JSON_TEXT("{\"Hello\":\"World\",\"libjson\":true}"));
		  #ifdef JSON_NEWLINE
			 assertEquals(JSON_NEWLINE, JSON_TEXT("\r\n"));
			 #ifdef JSON_INDENT
				assertEquals(JSON_INDENT, JSON_TEXT("    "))
				assertWrite(test1, json_write_formatted, JSON_TEXT("{\r\n    \"Hello\" : \"World\",\r\n    \"libjson\" : true\r\n}"));
			 #else
				assertWrite(test1, json_write_formatted, JSON_TEXT("{\r\n\t\"Hello\" : \"World\",\r\n\t\"libjson\" : true\r\n}"));
			 #endif
		  #else
			 #ifdef JSON_INDENT
				assertEquals(JSON_INDENT, JSON_TEXT("    "))
				assertWrite(test1, json_write_formatted, JSON_TEXT("{\n    \"Hello\" : \"World\",\n    \"libjson\" : true\n}"));
			 #else
				assertWrite(test1, json_write_formatted, JSON_TEXT("{\n\t\"Hello\" : \"World\",\n\t\"libjson\" : true\n}"));
			 #endif
		  #endif
		  json_delete(test1);
		  
		  JSONNODE * test2 = json_new(JSON_ARRAY);
		  assertWrite(test2, json_write, JSON_TEXT("[]"));
		  json_delete(test2);
	   
	   
	   JSONNODE * card = json_new(JSON_ARRAY);
	   
	   
	   
	   
	   JSONNODE *c = json_new(JSON_ARRAY);
	   json_push_back(c, json_new_a(JSON_TEXT("name"), JSON_TEXT("Entrée Audio Intégrée 1")));
	   json_push_back(c, json_new_i(NULL, 0));
	   json_push_back(card, c);
	   #ifdef JSON_UNICODE
		  assertWrite(card, json_write, JSON_TEXT("[[\"Entr\\u00E9e Audio Int\\u00E9gr\\u00E9e 1\",0]]"))
		  JSONNODE * ass = json_parse(JSON_TEXT("[[\"Entr\\u00E9e Audio Int\\u00E9gr\\u00E9e 1\",0]]"));
		  JSONNODE * item = json_at(json_at(ass, 0), 0);
		  assertWrite(item, json_as_string, JSON_TEXT("Entrée Audio Intégrée 1"));
	   #else
		  assertWrite(card, json_write, JSON_TEXT("[[\"Entr\\u00C3\\u00A9e Audio Int\\u00C3\\u00A9gr\\u00C3\\u00A9e 1\",0]]"))
		  JSONNODE * ass = json_parse(JSON_TEXT("[[\"Entr\\u00C3\\u00A9e Audio Int\\u00C3\\u00A9gr\\u00C3\\u00A9e 1\",0]]"));
		  JSONNODE * item = json_at(json_at(ass, 0), 0);
		  assertWrite(item, json_as_string, JSON_TEXT("Entrée Audio Intégrée 1"));
	   #endif
	   json_delete(card);
	   json_delete(ass);
	   
	   
	   
		  
		  #ifdef JSON_COMMENTS
			 JSONNODE * test3 = json_new(JSON_NODE);
			 json_push_back(test3, json_new_a(JSON_TEXT("Hi"), JSON_TEXT("There")));
			 json_push_back(test3, json_new_a(JSON_TEXT("Hello"), JSON_TEXT("World")));
			 json_set_comment(json_at(test3, 0), JSON_TEXT("Testing stuff"));
			 json_set_comment(json_at(test3, 1), JSON_TEXT("Multi\r\nLine\nUnix and Windows"));
			 assertWrite(test3, json_write, JSON_TEXT("{\"Hi\":\"There\",\"Hello\":\"World\"}"));
			 #if !defined( JSON_INDENT) && !defined(JSON_NEWLINE)
				#ifdef JSON_WRITE_BASH_COMMENTS
				    assertWrite(test3, json_write_formatted, JSON_TEXT("{\n\t\n\t#Testing stuff\n\t\"Hi\" : \"There\",\n\t\n\t#Multi\n\t#Line\n\t#Unix and Windows\n\t\"Hello\" : \"World\"\n}"));
				#elif defined(JSON_WRITE_SINGLE_LINE_COMMENTS)
				    assertWrite(test3, json_write_formatted, JSON_TEXT("{\n\t\n\t//Testing stuff\n\t\"Hi\" : \"There\",\n\t\n\t//Multi\n\t//Line\n\t//Unix and Windows\n\t\"Hello\" : \"World\"\n}"));
				#else
				    assertWrite(test3, json_write_formatted, JSON_TEXT("{\n\t\n\t//Testing stuff\n\t\"Hi\" : \"There\",\n\t\n\t/*\n\t\tMulti\n\t\tLine\n\t\tUnix and Windows\n\t*/\n\t\"Hello\" : \"World\"\n}"));
				#endif
			 #endif
			 json_delete(test3);
		  #endif
		  
		  
	   #else
		  JSONNode test1(JSON_NODE);
		  assertEquals(test1.write(), JSON_TEXT("{}"));
		  test1.push_back(JSONNode(JSON_TEXT("Hello"), JSON_TEXT("World")));
		  test1.push_back(JSONNode(JSON_TEXT("libjson"), true));
		  assertEquals(test1.write(), JSON_TEXT("{\"Hello\":\"World\",\"libjson\":true}"));
		  #ifdef JSON_NEWLINE
			 assertEquals(JSON_NEWLINE, JSON_TEXT("\r\n"));
			 #ifdef JSON_INDENT
				assertEquals(JSON_INDENT, JSON_TEXT("    "))
				assertEquals(test1.write_formatted(), JSON_TEXT("{\r\n    \"Hello\" : \"World\",\r\n    \"libjson\" : true\r\n}"));
			 #else
				assertEquals(test1.write_formatted(), JSON_TEXT("{\r\n\t\"Hello\" : \"World\",\r\n\t\"libjson\" : true\r\n}"));
			 #endif
		  #else
			 #ifdef JSON_INDENT
				assertEquals(JSON_INDENT, JSON_TEXT("    "))
				assertEquals(test1.write_formatted(), JSON_TEXT("{\n    \"Hello\" : \"World\",\n    \"libjson\" : true\n}"));
			 #else
				assertEquals(test1.write_formatted(), JSON_TEXT("{\n\t\"Hello\" : \"World\",\n\t\"libjson\" : true\n}"));
			 #endif
		  #endif
		  
		  JSONNode test2(JSON_ARRAY);
		  assertEquals(test2.write(), JSON_TEXT("[]"));
		  
		  #ifdef JSON_COMMENTS
			 JSONNode test3(JSON_NODE);
			 test3.push_back(JSONNode(JSON_TEXT("Hi"), JSON_TEXT("There")));
			 test3.push_back(JSONNode(JSON_TEXT("Hello"), JSON_TEXT("World")));
			 test3[0].set_comment(JSON_TEXT("Testing stuff"));
			 test3[1].set_comment(JSON_TEXT("Multi\r\nLine\nUnix and Windows"));
			 assertEquals(test3.write(), JSON_TEXT("{\"Hi\":\"There\",\"Hello\":\"World\"}"));
			 #if !defined( JSON_INDENT) && !defined(JSON_NEWLINE)
				#ifdef JSON_WRITE_BASH_COMMENTS
				    assertEquals(test3.write_formatted(), JSON_TEXT("{\n\t\n\t#Testing stuff\n\t\"Hi\" : \"There\",\n\t\n\t#Multi\n\t#Line\n\t#Unix and Windows\n\t\"Hello\" : \"World\"\n}"));
				#elif defined(JSON_WRITE_SINGLE_LINE_COMMENTS)
				    assertEquals(test3.write_formatted(), JSON_TEXT("{\n\t\n\t//Testing stuff\n\t\"Hi\" : \"There\",\n\t\n\t//Multi\n\t//Line\n\t//Unix and Windows\n\t\"Hello\" : \"World\"\n}"));
				#else
				    assertEquals(test3.write_formatted(), JSON_TEXT("{\n\t\n\t//Testing stuff\n\t\"Hi\" : \"There\",\n\t\n\t/*\n\t\tMulti\n\t\tLine\n\t\tUnix and Windows\n\t*/\n\t\"Hello\" : \"World\"\n}"));
				#endif
			 #endif
			 
		  #endif
	   #endif
    }