示例#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();
}
示例#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);
}
示例#3
0
文件: object.c 项目: myaut/tsload
void test_object_empty(void) {
	json_buffer_t* buf = JSON_BUFFER(" [] ");
	json_node_t* obj;

	assert(json_parse(buf, &obj) == JSON_OK);
	assert(json_size(obj) == 0);

	json_node_destroy(obj);
}
示例#4
0
文件: object.c 项目: myaut/tsload
void test_object_embed(void) {
	json_buffer_t* buf = JSON_BUFFER(" { \"a\":{},  \"b\":[] } ");
	json_node_t* obj;

	assert(json_parse(buf, &obj) == JSON_OK);
	assert(json_size(obj) == 2);

	json_node_destroy(obj);
}
示例#5
0
文件: object.c 项目: myaut/tsload
void test_object_one(void) {
	json_buffer_t* buf = JSON_BUFFER(" [true] ");
	json_node_t* obj;
	json_node_t* el1;

	assert(json_parse(buf, &obj) == JSON_OK);
	assert(json_size(obj) == 1);

	json_node_destroy(obj);
}
示例#6
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;}
    }
}
示例#8
0
文件: tsfile.c 项目: myaut/tsload
void json_tsfile_put_array(tsfile_t* file, json_node_t* node_array) {
	int size = json_size(node_array);
	int i;
	json_node_t* node;

	for(i = 0; i < size; ++i) {
		node = json_popitem(node_array, 0);

		if(!tsfile_put_node(file, node)) {
			/* Filled "death row" array. Abandon other nodes
			 * They will be deallocated in json_node_destroy() call below */
			break;
		}
	}

	json_node_destroy(node_array);
}
示例#9
0
文件: object.c 项目: myaut/tsload
void test_object_node(void) {
	json_buffer_t* buf = JSON_BUFFER(" { \"b\":true,  \"_int\":  10,   \"str\":\"hi!\" } ");
	json_node_t* obj;

	boolean_t b = B_FALSE;
	int i = -1;
	const char* s = "bye!";

	assert(json_parse(buf, &obj) == JSON_OK);
	assert(json_size(obj) == 3);

	assert(json_get_boolean(obj, "b", &b) == JSON_OK);
	assert(b == B_TRUE);

	assert(json_get_integer_i(obj, "_int", &i) == JSON_OK);
	assert(i == 10);

	assert(json_get_string(obj, "str", &s) == JSON_OK);
	assert(strcmp(s, "hi!") == 0);

	json_node_destroy(obj);
}
示例#10
0
文件: object.c 项目: myaut/tsload
void test_object_many(void) {
	json_buffer_t* buf = JSON_BUFFER(" [true,  10,\"hi!\"] ");
	json_node_t* obj;
	json_node_t* el;

	assert(json_parse(buf, &obj) == JSON_OK);
	assert(json_size(obj) == 3);

	el = json_getitem(obj, 0);
	assert(el != NULL);
	assert(json_as_boolean(el) == B_TRUE);

	el = json_getitem(obj, 1);
	assert(el != NULL);
	assert(json_as_integer(el) == 10);

	el = json_getitem(obj, 2);
	assert(el != NULL);
	assert(strcmp(json_as_string(el), "hi!") == 0);

	json_node_destroy(obj);
}
示例#11
0
文件: tsfile.c 项目: myaut/tsload
int json_tsfile_add_array(tsfile_t* file, json_node_t* node_array) {
	unsigned long entry_size = file->header->schema.hdr.entry_size;
	void* entries = NULL;
	void* entry;
	int count = json_size(node_array);
	int ni = 0;
	int ret;

	json_node_t* node = json_first(node_array, &ni);

	entries = mp_malloc(entry_size * count);

	while(!json_is_end(node_array, node, &ni)) {
		entry = ((char*) entries) + entry_size * ni;
		tsfile_fill_entry(file, node, entry);

		node = json_next(node, &ni);
	}

	ret = tsfile_add(file, entries, count);

	mp_free(entries);
	return ret;
}
void TestSuite::TestInspectors(void){
    UnitTest::SetPrefix("TestInspectors.cpp - Inspectors");
    #ifdef JSON_LIBRARY
		  JSONNODE * test = json_new(JSON_NULL);
		  assertEquals(json_type(test), JSON_NULL);
		  json_char * res = json_as_string(test);
		  assertCStringSame(res, JSON_TEXT(""));
		  json_free(res);
		  assertEquals_Primitive(json_as_int(test), 0);
		  assertEquals_Primitive(json_as_float(test), 0.0f);
		  assertEquals(json_as_bool(test), false);

		  json_set_f(test, 15.5f);
		  assertEquals(json_type(test), JSON_NUMBER);
		#ifdef JSON_CASTABLE
		  res = json_as_string(test);
		  assertCStringSame(res, JSON_TEXT("15.5"));
		  json_free(res);
		#endif
		  assertEquals_Primitive(json_as_int(test), 15);
		  assertEquals_Primitive(json_as_float(test), 15.5f);
		  #ifdef JSON_CASTABLE
				assertEquals(json_as_bool(test), true);
		  #endif

		  json_set_f(test, 0.0f);
		  assertEquals(json_type(test), JSON_NUMBER);
		#ifdef JSON_CASTABLE
		  res = json_as_string(test);
		  assertCStringSame(res, JSON_TEXT("0"));
		  json_free(res);
		#endif
		  assertEquals_Primitive(json_as_int(test), 0);
		  assertEquals_Primitive(json_as_float(test), 0.0f);
		  #ifdef JSON_CASTABLE
			assertEquals(json_as_bool(test), false);
		  #endif
	
		  json_set_b(test, true);
		  assertEquals(json_type(test), JSON_BOOL);
		  #ifdef JSON_CASTABLE
			res = json_as_string(test);
			assertCStringSame(res, JSON_TEXT("true"));
			json_free(res);
			assertEquals_Primitive(json_as_int(test), 1);
			assertEquals_Primitive(json_as_float(test), 1.0f);
		  #endif
		  assertEquals(json_as_bool(test), true);

		  json_set_b(test, false);
		  assertEquals(json_type(test), JSON_BOOL);
		  #ifdef JSON_CASTABLE
			res = json_as_string(test);
			assertCStringSame(res, JSON_TEXT("false"));
			json_free(res);
			assertEquals_Primitive(json_as_int(test), 0);
			assertEquals_Primitive(json_as_float(test), 0.0f);
		  #endif
		  assertEquals(json_as_bool(test), false);
		  #ifdef JSON_CASTABLE
				  json_cast(test, JSON_NODE);
				  assertEquals(json_type(test), JSON_NODE);
				  assertEquals(json_size(test), 0);
				  json_push_back(test, json_new_a(JSON_TEXT("hi"), JSON_TEXT("world")));
				  json_push_back(test, json_new_a(JSON_TEXT("hello"), JSON_TEXT("mars")));
				  json_push_back(test, json_new_a(JSON_TEXT("salut"), JSON_TEXT("france")));
				  assertEquals(json_size(test), 3);
				  TestSuite::testParsingItself(test);

				  JSONNODE * casted = json_as_array(test);
				  #ifdef JSON_UNIT_TEST
					 assertNotEquals(((JSONNode*)casted) -> internal, ((JSONNode*)test) -> internal);
				  #endif
				  assertEquals(json_type(casted), JSON_ARRAY);
				  assertEquals(json_type(test), JSON_NODE);
				  assertEquals(json_size(test), 3);
				  assertEquals(json_size(casted), 3);
				  TestSuite::testParsingItself(casted);
		   #endif
				  UnitTest::SetPrefix("TestInspectors.cpp - Location");

		   #ifdef JSON_CASTABLE
				  #define CheckAt(parent, locale, text)\
					 if(JSONNODE * temp = json_at(parent, locale)){\
						json_char * _res = json_as_string(temp);\
						assertCStringSame(_res, text);\
						json_free(_res);\
					 } else {\
						FAIL(std::string("CheckAt: ") + #parent + "[" + #locale + "]");\
					 }

				  #define CheckNameAt(parent, locale, text)\
					 if(JSONNODE * temp = json_at(parent, locale)){\
						json_char * _res = json_name(temp);\
						assertCStringSame(_res, text);\
						json_free(_res);\
					 } else {\
						FAIL(std::string("CheckNameAt: ") + #parent + "[" + #locale + "]");\
					 }

		          CheckAt(casted, 0, JSON_TEXT("world"));
				  CheckAt(casted, 1, JSON_TEXT("mars"));
				  CheckAt(casted, 2, JSON_TEXT("france"));
				  CheckNameAt(casted, 0, JSON_TEXT(""));
				  CheckNameAt(casted, 1, JSON_TEXT(""));
				  CheckNameAt(casted, 2, JSON_TEXT(""));
	
				  CheckAt(test, 0, JSON_TEXT("world"));
				  CheckAt(test, 1, JSON_TEXT("mars"));
				  CheckAt(test, 2, JSON_TEXT("france"));
				  CheckNameAt(test, 0, JSON_TEXT("hi"));
				  CheckNameAt(test, 1, JSON_TEXT("hello"));
				  CheckNameAt(test, 2, JSON_TEXT("salut"));
		  

				  #define CheckGet(parent, locale, text)\
					 if(JSONNODE * temp = json_get(parent, locale)){\
						json_char * _res = json_as_string(temp);\
						assertCStringSame(_res, text);\
						json_free(_res);\
					 } else {\
						FAIL(std::string("CheckGet: ") + #parent + "[" + #locale + "]");\
					 }

				  #ifdef JSON_CASE_INSENSITIVE_FUNCTIONS
					 #define CheckGetNoCase(parent, locale, text)\
						if(JSONNODE * temp = json_get_nocase(parent, locale)){\
							json_char * _res = json_as_string(temp);\
							assertCStringSame(_res, text);\
							json_free(_res);\
						} else {\
							FAIL(std::string("CheckGetNoCase: ") + #parent + "[" + #locale + "]");\
						}
				  #else
					 #define CheckGetNoCase(parent, locale, text)
				  #endif

				  CheckGet(test, JSON_TEXT("hi"), JSON_TEXT("world"));
				  CheckGetNoCase(test, JSON_TEXT("HI"), JSON_TEXT("world"));
				  CheckGet(test, JSON_TEXT("hello"), JSON_TEXT("mars"));
				  CheckGetNoCase(test, JSON_TEXT("HELLO"), JSON_TEXT("mars"));
				  CheckGet(test, JSON_TEXT("salut"), JSON_TEXT("france"));
				  CheckGetNoCase(test, JSON_TEXT("SALUT"), JSON_TEXT("france"));
	
				assertNull(json_get(test, JSON_TEXT("meh")));
				#ifdef JSON_CASE_INSENSITIVE_FUNCTIONS
					assertNull(json_get_nocase(test, JSON_TEXT("meh")));
				#endif
			#endif


		  #ifdef JSON_ITERATORS
			#ifdef JSON_CASTABLE
			 UnitTest::SetPrefix("TestInspectors.cpp - Iterators");
			 for(JSONNODE_ITERATOR it = json_begin(casted), end = json_end(casted); it != end; ++it){
				json_char * _res = json_name(*it);
				assertCStringSame(_res, JSON_TEXT(""));
				json_free(_res);
			 }
			#endif
		  #endif

		  #ifdef JSON_BINARY
			 UnitTest::SetPrefix("TestInspectors.cpp - Binary");
			 json_set_binary(test, (const unsigned char *)"Hello World", 11);
			 assertEquals(json_type(test), JSON_STRING);
			 json_char * _res = json_as_string(test);
			 assertCStringSame(_res, JSON_TEXT("SGVsbG8gV29ybGQ="));
			 json_free(_res);

			 unsigned long i;
			 if(char * bin = (char*)json_as_binary(test, &i)){
				assertEquals(i, 11);
				char * terminated = (char*)std::memcpy(std::malloc(i + 1), bin, i);
				terminated[i] = '\0';
				assertCStringEquals(terminated, "Hello World");
				json_free(bin);
				std::free(terminated);
			 } else {
				FAIL("as_binary failed");
			 }

			 json_set_a(test, JSON_TEXT("Hello World"));
			 assertEquals(json_type(test), JSON_STRING);
			 _res = json_as_string(test);
			 assertCStringSame(_res, JSON_TEXT("Hello World"));
			 json_free(_res);

			 #ifdef JSON_SAFE
				assertEquals(json_as_binary(test, &i), 0);
				assertEquals(i, 0);
			 #endif
		  #endif


		  json_delete(test);
		  #ifdef JSON_CASTABLE
			json_delete(casted);
		  #endif
    #else
		  JSONNode test = JSONNode(JSON_NULL);
		  #ifdef JSON_CASTABLE
			 assertEquals(test.as_string(), JSON_TEXT(""));
			 assertEquals(test.as_int(), 0);
			 assertEquals(test.as_float(), 0.0f);
			 assertEquals(test.as_bool(), false);
		  #endif

		  test = 15.5f;
		  assertEquals(test.type(), JSON_NUMBER);
		#ifdef JSON_CASTABLE
		  assertEquals(test.as_string(), JSON_TEXT("15.5"));
		#endif
		  assertEquals(test.as_int(), 15);
		  assertEquals(test.as_float(), 15.5f);
		  #ifdef JSON_CASTABLE
			 assertEquals(test.as_bool(), true);
		  #endif

		  test = 0.0f;
		  assertEquals(test.type(), JSON_NUMBER);
		#ifdef JSON_CASTABLE
		  assertEquals(test.as_string(), JSON_TEXT("0"));
		#endif
		  assertEquals(test.as_int(), 0);
		  assertEquals(test.as_float(), 0.0f);
		  #ifdef JSON_CASTABLE
			 assertEquals(test.as_bool(), false);
		  #endif

		  test = true;
		  assertEquals(test.type(), JSON_BOOL);
		  #ifdef JSON_CASTABLE
			 assertEquals(test.as_string(), JSON_TEXT("true"));
			 assertEquals(test.as_int(), 1);
			 assertEquals(test.as_float(), 1.0f);
		  #endif
		  assertEquals(test.as_bool(), true);

		  test = false;
		  assertEquals(test.type(), JSON_BOOL);
		  #ifdef JSON_CASTABLE
			 assertEquals(test.as_string(), JSON_TEXT("false"));
			 assertEquals(test.as_int(), 0);
			 assertEquals(test.as_float(), 0.0f);
		  #endif
		  assertEquals(test.as_bool(), false);

		  #ifdef JSON_CASTABLE
			 test.cast(JSON_NODE);
		  #else
			 test = JSONNode(JSON_NODE);
		  #endif
		  assertEquals(test.type(), JSON_NODE);
		  assertEquals(test.size(), 0);
		  test.push_back(JSONNode(JSON_TEXT("hi"), JSON_TEXT("world")));
		  test.push_back(JSONNode(JSON_TEXT("hello"), JSON_TEXT("mars")));
		  test.push_back(JSONNode(JSON_TEXT("salut"), JSON_TEXT("france")));
		  assertEquals(test.size(), 3);
		  TestSuite::testParsingItself(test);

		  #ifdef JSON_CASTABLE
			 JSONNode casted = test.as_array();
			 #ifdef JSON_UNIT_TEST
				assertNotEquals(casted.internal, test.internal);
			 #endif
			 assertEquals(casted.type(), JSON_ARRAY);
			 assertEquals(test.type(), JSON_NODE);
			 assertEquals(test.size(), 3);
			 assertEquals(casted.size(), 3);
			 TestSuite::testParsingItself(casted);
		  #endif

		  UnitTest::SetPrefix("TestInspectors.cpp - Location");

		  try {
			 #ifdef JSON_CASTABLE
				assertEquals(casted.at(0), JSON_TEXT("world"));
				assertEquals(casted.at(1), JSON_TEXT("mars"));
				assertEquals(casted.at(2), JSON_TEXT("france"));
				assertEquals(casted.at(0).name(), JSON_TEXT(""));
				assertEquals(casted.at(1).name(), JSON_TEXT(""));
				assertEquals(casted.at(2).name(), JSON_TEXT(""));
			 #endif
			 assertEquals(test.at(0), JSON_TEXT("world"));
			 assertEquals(test.at(1), JSON_TEXT("mars"));
			 assertEquals(test.at(2), JSON_TEXT("france"));
			 assertEquals(test.at(0).name(), JSON_TEXT("hi"));
			 assertEquals(test.at(1).name(), JSON_TEXT("hello"));
			 assertEquals(test.at(2).name(), JSON_TEXT("salut"));
		  } catch (std::out_of_range){
			 FAIL("exception caught");
		  }

		  try {
			 assertEquals(test.at(JSON_TEXT("hi")), JSON_TEXT("world"));
			 assertEquals(test.at(JSON_TEXT("hello")), JSON_TEXT("mars"));
			 assertEquals(test.at(JSON_TEXT("salut")), JSON_TEXT("france"));
			 #ifdef JSON_CASE_INSENSITIVE_FUNCTIONS
				assertEquals(test.at_nocase(JSON_TEXT("SALUT")), JSON_TEXT("france"));
				assertEquals(test.at_nocase(JSON_TEXT("HELLO")), JSON_TEXT("mars"));
				assertEquals(test.at_nocase(JSON_TEXT("HI")), JSON_TEXT("world"));
			 #endif
		  } catch (std::out_of_range){
			 FAIL("exception caught");
		  }

		  assertException(test.at(JSON_TEXT("meh")), std::out_of_range);
		  #ifdef JSON_CASE_INSENSITIVE_FUNCTIONS
			 assertException(test.at_nocase(JSON_TEXT("meh")), std::out_of_range);
		  #endif

		  assertEquals(test[JSON_TEXT("hi")], json_string(JSON_TEXT("world")));
		  assertEquals(test[JSON_TEXT("hello")], json_string(JSON_TEXT("mars")));
		  assertEquals(test[JSON_TEXT("salut")], json_string(JSON_TEXT("france")));
		  assertEquals(test[0], JSON_TEXT("world"));
		  assertEquals(test[1], JSON_TEXT("mars"));
		  assertEquals(test[2], JSON_TEXT("france"));

		  #ifdef JSON_ITERATORS
			#ifdef JSON_CASTABLE
			 UnitTest::SetPrefix("TestInspectors.cpp - Iterators");
			 for(JSONNode::iterator it = casted.begin(), end = casted.end(); it != end; ++it){
				assertEquals((*it).name(), JSON_TEXT(""));
			 }
			#endif
		  #endif

		  #ifdef JSON_BINARY
			 UnitTest::SetPrefix("TestInspectors.cpp - Binary");
			 test.set_binary((const unsigned char *)"Hello World", 11);
			 assertEquals(test.type(), JSON_STRING);
			 assertEquals(test.as_string(), JSON_TEXT("SGVsbG8gV29ybGQ="));
			 assertEquals(test.as_binary(), "Hello World");
			 assertEquals(test.as_binary().size(), 11);

			 test = JSON_TEXT("Hello World");
			 assertEquals(test.type(), JSON_STRING);
			 assertEquals(test.as_string(), JSON_TEXT("Hello World"));
			 #ifdef JSON_SAFE
				assertEquals(test.as_binary(), "");
			 #endif
		  #endif
		  
         #ifdef JSON_READ_PRIORITY
			//This is a regression test for a bug in at()
			json_string buffer(JSON_TEXT("{ \"myValue1\" : \"foo\", \"myValue2\" : \"bar\"}"));
			JSONNode current = libjson::parse(buffer);
			try {
				JSONNode & value1 = current[JSON_TEXT("myValue1")];
				assertEquals(value1.as_string(), JSON_TEXT("foo"));
				JSONNode & value2 = current[JSON_TEXT("myValue2")];
				assertEquals(value2.as_string(), JSON_TEXT("bar"));
			} catch (...){
				assertTrue(false);
			}
        #endif
    #endif
}
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
}
示例#14
0
// master不保存settings,直接传给plugin_init()
int load_task_setting(ls_master_t* master) {
    LOG("load_task_setting()\n");
    const char* setting_file = "task/setting.json";

    char* buf;
    long len;
    FILE* f = fopen(setting_file, "r");
    if (f == NULL) {
        LOGE("Failed to open setting_file: %s\n", setting_file);// TODO errno
        return -1;
    }

    fseek(f, 0, SEEK_END);
    len = ftell(f);
    rewind(f);

    buf = (char*) malloc(len + 1);
    if (NULL == buf) {
        LOGE("Failed to malloc for task_setting: %s\n", strerror(errno));
        return -1;
    }

    len = fread(buf, 1, len, f);
    buf[len] = '\0';

    JSONNODE* setting = json_parse(buf);

    master->num_plugins = json_size(setting);
    master->plugins = (ls_plugin_t*)malloc(master->num_plugins * sizeof(ls_plugin_t));

    ls_plugin_t* plugin;
    size_t plugin_index = 0;
    char plugin_path[128];
    for (JSONNODE_ITERATOR i = json_begin(setting); i != json_end(setting); ++i, ++plugin_index) {
        plugin = master->plugins + plugin_index;
        plugin->plugin_index = plugin_index;

        json_char* plugin_name = json_name(*i);
        if (NULL == plugin_name) {
            LOGE("Failed to get plugin_name from task_setting\n");
            return -1;
        }

        snprintf(plugin_path, sizeof(plugin_path), "plugin/%s/%s.so", plugin_name, plugin_name);

        if (uv_dlopen(plugin_path, &plugin->plugin_lib) < 0) {
            LOGE("  Failed to uv_dlopen: %s\n", uv_dlerror(&plugin->plugin_lib));
            return -1;
        }

        if (uv_dlsym(&(plugin->plugin_lib), "plugin_declare", (void**)&(plugin->plugin_declare)) < 0) {
            LOGE("  Failed to uv_dlsym\n");
            return -1;
        }

        if ((plugin->plugin_declare(plugin) < 0)) {
            LOGE("  Failed to plugin_declare\n");
            return -1;
        }

        JSONNODE* settings = *i;
        // if (plugin->master_init != NULL && (plugin->master_init)(master, settings) < 0)
        if (plugin->plugin_init != NULL && (plugin->plugin_init)(settings) < 0) {
            LOGE("ERROR failed to plugin_init()\n");
            return -1;
        }
    }

    // TODO json_free
    return 0;
}
示例#15
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);
	}
}
示例#16
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);
	}
}
示例#17
0
文件: rlibjson.c 项目: wyngit/RJSONIO
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);
}