Esempio n. 1
0
bool CSteamProto::Relogin()
{
	ptrA token(getStringA("TokenSecret"));
	if (mir_strlen(token) <= 0)
		return false;

	HttpRequest *request = new LogonRequest(token);
	HttpResponse *response = request->Send(m_hNetlibUser);

	bool success = false;
	if (CheckResponse(response))
	{
		JSONROOT root(response->pData);
		if (root != NULL) {
			JSONNode *node = json_get(root, "error");

			ptrT error(json_as_string(node));
			if (!mir_tstrcmpi(error, _T("OK")))
			{
				node = json_get(root, "umqid");
				setString("UMQID", ptrA(mir_u2a(ptrT(json_as_string(node)))));

				node = json_get(root, "message");
				setDword("MessageID", json_as_int(node));

				success = true;
			}
		}
	}

	delete request;
	delete response;

	return success;
}
Esempio n. 2
0
static	void	create_scene(t_value val, t_object *arr, t_object *light)
{
	json_foreach_arr(json_get(val.data.obj, "scene").data.arr, &fill_arr, arr);
	arr[json_arr_length(json_get(val.data.obj, "scene").data.arr)].type = DEFAULT;
	json_foreach_arr(json_get(val.data.obj, "lights").data.arr, &fill_arr, light);
	light[json_arr_length(json_get(val.data.obj, "lights").data.arr)].type = DEFAULT;
	g_death = (int)json_get(val.data.obj, "death").data.number;
}
Esempio n. 3
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);
}
Esempio n. 4
0
void CSteamProto::OnLoggedOn(const HttpResponse *response)
{
	if (!CheckResponse(response))
	{
		if (response && response->resultCode == HTTP_CODE_UNAUTHORIZED)
		{
			// Probably expired TokenSecret
			HandleTokenExpired();
			return;
		}

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

		SetStatus(ID_STATUS_OFFLINE);
		return;
	}

	JSONROOT root(response->pData);

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

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

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

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

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

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

	// go to online now
	ProtoBroadcastAck(NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)ID_STATUS_CONNECTING, m_iStatus = m_iDesiredStatus);
}
Esempio n. 5
0
File: main.c Progetto: mbarbari/RTv1
void		init_env(t_env *env)
{
	env->mlx = mlx_init();
	env->resolution.width = WIDTH;
	env->resolution.height = HEIGHT;
	env->win = mlx_new_window(env->mlx, WIDTH, HEIGHT, "RayTracer");
	env->img.ptr = mlx_new_image(env->mlx, WIDTH, HEIGHT);
	env->img.data = mlx_get_data_addr(env->img.ptr, &env->img.bpp,
			&env->img.sizeline, &env->img.endianness);
	env->fov = 45;
	env->pos_absolute_camera = (t_vertex3){
		.x = json_get(parser(env->file).data.obj, "pos_camera.x").data.number,
		.y = json_get(parser(env->file).data.obj, "pos_camera.y").data.number,
		.z = json_get(parser(env->file).data.obj, "pos_camera.z").data.number};
	env->matrice = malloc(sizeof(t_color3) * (WIDTH * HEIGHT) + 1);
	env->angle = tanf(M_PI * 0.5f * env->fov / 180.);
	env->ratio = env->resolution.width / (float)env->resolution.height;
	env->invw = 1 / (float)env->resolution.width;
	env->invh = 1 / (float)env->resolution.height;
	env->nb_thread = 14;
	env->sampling = 4;
	env->anglex = 0;
	env->angley = 0;
}

int			main(int argc, char **argv)
{
	t_env		env;
	struct stat	file_stat;

	if (argc == 2)
	{
		env.file = argv[1];
		if (stat(env.file, &file_stat) < 0)
		{
			ft_printf("file not exists\n");
			exit(0);
		}
		file_is_modified(env.file, &env.oldtime, 1);
		init_env(&env);
		ft_setup_inter(env.fctinter);
		ft_setup_normal(env.fctnormal);
		mlx_do_key_autorepeatoff(env.mlx);
		mlx_hook(env.win, 2, (1L << 0), &key_press, &env);
		mlx_loop_hook(env.mlx, &loop_hook, &env);
		mlx_expose_hook(env.win, &rt_expose_hook, &env);
		mlx_loop(env.mlx);
		free(env.matrice);
	}
	else
		ft_printf("Usage: %s scene.json\n", argv[0]);
	return (0);
}
Esempio n. 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);
	}
}
Esempio n. 7
0
int test_main () {
	Rangstr rs ;

	rs = json_get ("{\"hello\":\"world\"}", "hello");
printf ("OUT: ");
rangstr_print (&rs);
printf ("\n");

printf ("--\n");
	rs = json_get ("{\"hello\":{\"world\":123}}", "hello.world");
printf ("OUT: ");
rangstr_print (&rs);
printf ("\n");
	return 0;
}
void JSON_Get_child_by_name(sLONG_PTR *pResult, PackagePtr pParams)
{
	C_TEXT json;
	C_TEXT name;
	C_LONGINT option;
	C_TEXT returnValue;
	
	json.fromParamAtIndex(pParams, 1);
	name.fromParamAtIndex(pParams, 2);
	option.fromParamAtIndex(pParams, 3);
	
	JSONNODE *n = _fromHex(json);
	
	if(n){
		std::wstring w;
		_copyString(name, w);
		JSONNODE *node = NULL;
		switch (option.getIntValue()) {
			case 1:
				node = json_get_nocase(n, w.c_str());
				break;
			default:
				node = json_get(n, w.c_str());
				break;
		}
		
		_toHex(node, returnValue);
	}
	
	returnValue.setReturn(pResult);
}
Esempio n. 9
0
SDB_VISIBLE int sdb_json_geti (Sdb *s, const char *k, const char *p) {
	char *v = sdb_get (s, k, 0); // XXX cas
	if (v) {
		Rangstr rs = json_get (v, p);
		return rangstr_int (&rs);
	}
	return 0;
}
Esempio n. 10
0
SDB_API int sdb_json_geti (Sdb *s, const char *k, const char *p, ut32 *cas) {
	char *v = sdb_get (s, k, cas);
	if (v) {
		Rangstr rs = json_get (v, p);
		return rangstr_int (&rs);
	}
	return 0;
}
Esempio n. 11
0
void CVkProto::OnReceivePollingInfo(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq)
{
	debugLogA("CVkProto::OnReceivePollingInfo %d", reply->resultCode);
	if (reply->resultCode != 200)
		return;

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

	m_pollingTs = mir_t2a(ptrT(json_as_string(json_get(pResponse, "ts"))));
	m_pollingKey = mir_t2a(ptrT(json_as_string(json_get(pResponse, "key"))));
	m_pollingServer = mir_t2a(ptrT(json_as_string(json_get(pResponse, "server"))));
	if (!m_hPollingThread && m_pollingTs != NULL && m_pollingKey != NULL && m_pollingServer != NULL)
		m_hPollingThread = ForkThreadEx(&CVkProto::PollingThread, NULL, NULL);
}
Esempio n. 12
0
SDB_API char *sdb_json_get (Sdb *s, const char *k, const char *p, ut32 *cas) {
	Rangstr rs;
	char *u, *v = sdb_get (s, k, cas);
	if (!v) return NULL;
	rs = json_get (v, p);
	u = rangstr_dup (&rs);
	free (v);
	return u;
}
Esempio n. 13
0
int CVkProto::PollServer()
{
	debugLogA("CVkProto::PollServer");

	NETLIBHTTPREQUEST req = { sizeof(req) };
	req.requestType = REQUEST_GET;
	req.szUrl = NEWSTR_ALLOCA(CMStringA().Format("http://%s?act=a_check&key=%s&ts=%s&wait=25&access_token=%s", m_pollingServer, m_pollingKey, m_pollingTs, m_szAccessToken));
	req.flags = VK_NODUMPHEADERS | NLHRF_PERSISTENT;
	req.timeout = 30000;
	req.nlc = m_pollingConn;

	NETLIBHTTPREQUEST *reply = (NETLIBHTTPREQUEST*)CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM)m_hNetlibUser, (LPARAM)&req);
	if (reply == NULL) {
		m_pollingConn = NULL;
		return 0;
	}

	int retVal = 0;
	if (reply->resultCode == 200) {
		JSONROOT pRoot(reply->pData);
		JSONNODE *pFailed = json_get(pRoot, "failed");
		if (pFailed != NULL && json_as_int(pFailed) == 2) {
			RetrievePollingInfo();
			retVal = -1;
			debugLogA("Polling key expired, restarting polling thread");
		}
		else if (CheckJsonResult(NULL, reply, pRoot)) {
			m_pollingTs = mir_t2a(ptrT(json_as_string(json_get(pRoot, "ts"))));
			JSONNODE *pUpdates = json_get(pRoot, "updates");
			if (pUpdates != NULL)
				PollUpdates(pUpdates);
			retVal = 1;
		}
	}

	m_pollingConn = reply->nlc;

	CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)reply);
	return retVal;
}
Esempio n. 14
0
void CVkProto::AppendChatMessage(int id, JSONNODE *pMsg, bool bIsHistory)
{
	CVkChatInfo *cc = AppendChat(id, NULL);
	if (cc == NULL)
		return;

	int mid = json_as_int(json_get(pMsg, "mid"));
	int isOut = json_as_int(json_get(pMsg, "out"));
	int uid = json_as_int(json_get(pMsg, "uid"));

	int msgTime = json_as_int(json_get(pMsg, "date"));
	time_t now = time(NULL);
	if (!msgTime || msgTime > now)
		msgTime = now;

	ptrT tszBody(json_as_string(json_get(pMsg, "body")));
	JSONNODE *pAttachments = json_get(pMsg, "attachments");
	if (pAttachments != NULL)
		tszBody = mir_tstrdup(CMString(tszBody) + GetAttachmentDescr(pAttachments));

	if (cc->m_bHistoryRead)
		AppendChatMessage(cc, mid, uid, msgTime, tszBody, bIsHistory);
	else {
		CVkChatMessage *cm = cc->m_msgs.find((CVkChatMessage *)&mid);
		if (cm == NULL)
			cc->m_msgs.insert(cm = new CVkChatMessage(mid));

		cm->m_uid = uid;
		cm->m_date = msgTime;
		cm->m_tszBody = tszBody.detouch();
		cm->m_bHistory = bIsHistory;
	}
}
Esempio n. 15
0
CVkChatInfo* CVkProto::AppendChat(int id, JSONNODE *pDlg)
{
	if (id == 0)
		return NULL;

	CVkChatInfo *c = m_chats.find((CVkChatInfo*)&id);
	if (c != NULL)
		return c;

	ptrT tszTitle;
	c = new CVkChatInfo(id);
	if (pDlg != NULL) {
		tszTitle = json_as_string(json_get(pDlg, "title"));
		c->m_tszTopic = mir_tstrdup((tszTitle != NULL) ? tszTitle : _T(""));
	}

	CMString sid; sid.Format(_T("%S_%d"), m_szModuleName, id);
	c->m_tszId = mir_tstrdup(sid);

	GCSESSION gcw = { sizeof(gcw) };
	gcw.iType = GCW_CHATROOM;
	gcw.pszModule = m_szModuleName;
	gcw.ptszName = tszTitle;
	gcw.ptszID = sid;
	CallServiceSync(MS_GC_NEWSESSION, NULL, (LPARAM)&gcw);

	GC_INFO gci = { 0 };
	gci.pszModule = m_szModuleName;
	gci.pszID = sid;
	gci.Flags = BYID | HCONTACT;
	CallServiceSync(MS_GC_GETINFO, 0, (LPARAM)&gci);
	c->m_hContact = gci.hContact;

	setTString(gci.hContact, "Nick", tszTitle);
	m_chats.insert(c);

	GCDEST gcd = { m_szModuleName, sid, GC_EVENT_ADDGROUP };
	GCEVENT gce = { sizeof(gce), &gcd };
	for (int i = SIZEOF(sttStatuses)-1; i >= 0; i--) {
		gce.ptszStatus = TranslateTS(sttStatuses[i]);
		CallServiceSync(MS_GC_EVENT, NULL, (LPARAM)&gce);
	}

	gcd.iType = GC_EVENT_CONTROL;
	gce.ptszStatus = 0;
	CallServiceSync(MS_GC_EVENT, (m_bHideChats) ? WINDOW_HIDDEN : SESSION_INITDONE, (LPARAM)&gce);
	CallServiceSync(MS_GC_EVENT, SESSION_ONLINE, (LPARAM)&gce);

	RetrieveChatInfo(c);
	return c;
}
Esempio n. 16
0
int
main (void) {
  const char *file = "test/fixtures/large-structure.json";
  const char *src = NULL;
  json_value_t *value = NULL;
  json_value_t *arr = NULL;
  json_value_t *obj = NULL;

  src = fs_read(file);
  assert(src);

  arr = json_parse(file, src);
  assert(arr);
  assert(arr->size);

  obj = json_get(arr, "0");
  assert(obj);

  value = json_get(obj, "_id");
  assert(value);
  assert(EQ("549754844fc63f4e60cf27b0", value->as.string));

  value = json_get(obj, "friends");
  assert(value);
  assert(JSON_ARRAY == value->type);

  value = json_get(value, "0");
  assert(value);
  assert(JSON_OBJECT == value->type);

  value = json_get(value, "name");
  assert(value);
  assert(EQ("Cora Burns", value->as.string));

  ok_done();
  return 0;
}
Esempio n. 17
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);
	}
}
Esempio n. 18
0
SDB_API int sdb_json_set (Sdb *s, const char *k, const char *p, const char *v, ut32 cas) {
	const char *beg[3];
	const char *end[3];
	int l, idx, len[3];
	char *str = NULL;
	Rangstr rs;
	ut32 c;
	char *js = sdb_get (s, k, &c);
	if (!js) return 0;
	if (cas && c != cas) {
		free (js);
		return 0;
	}
	rs = json_get (js, p);
	if (!rs.p) {
		free (js);
		return 0;
	}
#define WLEN(x) (int)(size_t)(end[x]-beg[x])

	beg[0] = js;
	end[0] = rs.p + rs.f;
	len[0] = WLEN (0);

	beg[1] = v;
	end[1] = v + strlen (v);
	len[1] = WLEN (1);

	beg[2] = rs.p + rs.t;
	end[2] = js + strlen (js);
	len[2] = WLEN (2);

	// TODO: accelerate with small buffer in stack for small jsons
	str = malloc (len[0]+len[1]+len[2]+1);
	idx = len[0];
	memcpy (str, beg[0], idx);
	l = len[1];
	memcpy (str+idx, beg[1], l);
	idx += len[1];
	l = len[2];
	memcpy (str+idx, beg[2], l);
	str[idx+l] = 0;

	sdb_set (s, k, str, cas);
	free (str);
	free (js);
	return 1;
}
Esempio n. 19
0
t_value		json_get(t_json *x, char *str)
{
	t_value value;
	char *split;
	
	while (x != NULL)
	{
		split = ft_strchr(str,'.');
		if (split == NULL && ft_strcmp(str, x->key) == 0)
			return (x->value);
		else if (split != NULL && ft_strncmp(str, x->key, split - str) == 0)
			return json_get(x->value.data.obj, split + 1);
		x = x->next;
	}
	ft_printf("error in the json scene\n");
	exit(0);
	return (value);
}
Esempio n. 20
0
void		new_cone(t_value val, t_object *data)
{
	ft_memcpy(data, &(t_cone){
		CONE,
		new_material(val),
		json_get(val.data.obj, "reflection_index").data.number,
		json_get(val.data.obj, "refraction_index").data.number,
		json_get(val.data.obj, "ambient").data.number,
		json_get(val.data.obj, "diffuse").data.number,
		json_get(val.data.obj, "specular").data.number,
		json_get(val.data.obj, "light").data.boolean,
		new_position(val),
		new_direction(val),
		json_get(val.data.obj, "radius").data.number,
		0
	}, sizeof(t_cone));
}
Esempio n. 21
0
int main(int argc, char **argv) {
	Rangstr rs;
	char buf[4096];
	int n = fread (buf, 1, sizeof (buf), stdin);
	buf[n] = 0;
//return test_glossary (buf);
//return test_main ();
	char *path = argv[1];

#if 1
	printf (">>>> %s <<<<\n", sdb_json_unindent (buf));
	printf (">>>> %s <<<<\n", sdb_json_indent (buf));
// set value //
	path = "glossary.title";
	char *s = api_json_set (buf, path, "patata");
	if (s) {
		printf ("%s\n", s);
		free (s);
	} else printf ("set failed\n");
#endif
//printf ("%s\n", str); return 0;

//	s = "[1,3,4]";
#if 0
	char *a = "{}";
	a = json_seti (a, "id", 123);
	a = json_seti (a, "user.name", "blah");
	printf ("id = %d\n", json_geti ("{'id':123}", "id"));
#endif
	//json_walk (buf);

	path = argv[1];
	rs = json_get (buf, path);
	printf ("-- output --\n");
	rangstr_print(&rs);
	printf ("\n");
	return 0;
}
Esempio n. 22
0
void CDropbox::RequestAccountInfo()
{
	HttpRequest *request = new HttpRequest(hNetlibUser, REQUEST_GET, DROPBOX_API_URL "/account/info");
	request->AddBearerAuthHeader(db_get_sa(NULL, MODULE, "TokenSecret"));
	mir_ptr<NETLIBHTTPREQUEST> response(request->Send());

	delete request;

	MCONTACT hContact = CDropbox::GetDefaultContact();

	if (response && response->resultCode == HTTP_STATUS_OK)
	{
		JSONROOT root(response->pData);
		if (root)
		{
			JSONNODE *node = json_get(root, "referral_link");
			if (node)
			{
				ptrW referral_link = ptrW(json_as_string(node));
				db_set_ws(hContact, MODULE, "Homepage", referral_link);
			}

			node = json_get(root, "display_name");
			if (node)
			{
				ptrW display_name = ptrW(json_as_string(node));
				wchar_t *sep = wcsrchr(display_name, L' ');
				if (sep)
				{
					db_set_ws(hContact, MODULE, "LastName", sep + 1);
					display_name[wcslen(display_name) - wcslen(sep)] = '\0';
					db_set_ws(hContact, MODULE, "FirstName", display_name);
				}
				else
				{
					db_set_ws(hContact, MODULE, "FirstName", display_name);
					db_unset(hContact, MODULE, "LastName");
				}
			}

			node = json_get(root, "country");
			if (node)
			{
				ptrW isocodeW(json_as_string(node));
				ptrA isocode(mir_u2a(isocodeW));

				if (!strlen(isocode))
					db_unset(hContact, MODULE, "Country");
				else
				{
					char *country = (char *)CallService(MS_UTILS_GETCOUNTRYBYISOCODE, (WPARAM)isocode, 0);
					db_set_s(hContact, MODULE, "Country", country);
				}
			}

			node = json_get(root, "quota_info");
			JSONNODE *nroot = json_as_node(node);
			if (nroot)
			{
				node = json_get(nroot, "shared");
				if (node)
					db_set_dw(hContact, MODULE, "SharedQuota", json_as_int(node));
				node = json_get(nroot, "normal");
				if (node)
					db_set_dw(hContact, MODULE, "NormalQuota", json_as_int(node));
				node = json_get(nroot, "quota");
				if (node)
					db_set_dw(hContact, MODULE, "TotalQuota", json_as_int(node));
			}
		}
	}

	HandleHttpResponseError(hNetlibUser, response);
}
Esempio n. 23
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();
}
Esempio n. 24
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);
}
Esempio n. 25
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);
}
Esempio n. 26
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;
}
Esempio n. 27
0
static void		fill_arr(t_value val, int idx, t_object *data)
{
	if (ft_strequ(json_get(val.data.obj, "type").data.s, "SPHERE"))
	{
		ft_memcpy(data + idx, &(t_sphere){
			SPHERE,
			color_new(json_get(val.data.obj, "color.red").data.number, json_get(val.data.obj, "color.green").data.number, json_get(val.data.obj, "color.blue").data.number),
			json_get(val.data.obj, "reflection_index").data.number,
			json_get(val.data.obj, "diffuse").data.number,
			vector_new(json_get(val.data.obj, "pos.x").data.number, json_get(val.data.obj, "pos.y").data.number, json_get(val.data.obj, "pos.z").data.number),
			json_get(val.data.obj, "radius").data.number
		}, sizeof(t_sphere));
	}
	if (ft_strequ(json_get(val.data.obj, "type").data.s, "PLANE"))
	{
		ft_memcpy(data + idx, &(t_plan){
			PLANE,
			color_new(json_get(val.data.obj, "color.red").data.number, json_get(val.data.obj, "color.green").data.number, json_get(val.data.obj, "color.blue").data.number),
			json_get(val.data.obj, "reflection_index").data.number,
			json_get(val.data.obj, "diffuse").data.number,
			vector_new(json_get(val.data.obj, "pos.x").data.number, json_get(val.data.obj, "pos.y").data.number, json_get(val.data.obj, "pos.z").data.number),
			vector_unit(vector_new(json_get(val.data.obj, "normal.x").data.number, json_get(val.data.obj, "normal.y").data.number, json_get(val.data.obj, "normal.z").data.number))
		}, sizeof(t_plan));
	}
	if (ft_strequ(json_get(val.data.obj, "type").data.s, "CYLINDER"))
	{
		ft_memcpy(data + idx, &(t_cylinder){
			CYLINDER,
			color_new(json_get(val.data.obj, "color.red").data.number, json_get(val.data.obj, "color.green").data.number, json_get(val.data.obj, "color.blue").data.number),
			json_get(val.data.obj, "reflection_index").data.number,
			json_get(val.data.obj, "diffuse").data.number,
			vector_new(json_get(val.data.obj, "pos.x").data.number, json_get(val.data.obj, "pos.y").data.number, json_get(val.data.obj, "pos.z").data.number),
			vector_unit(vector_new(json_get(val.data.obj, "normal.x").data.number, json_get(val.data.obj, "normal.y").data.number, json_get(val.data.obj, "normal.z").data.number)),
			json_get(val.data.obj, "radius").data.number
		}, sizeof(t_cylinder));
	}
	if (ft_strequ(json_get(val.data.obj, "type").data.s, "CONE"))
	{
		ft_memcpy(data + idx, &(t_cone){
			CONE,
			color_new(json_get(val.data.obj, "color.red").data.number, json_get(val.data.obj, "color.green").data.number, json_get(val.data.obj, "color.blue").data.number),
			json_get(val.data.obj, "reflection_index").data.number,
			json_get(val.data.obj, "diffuse").data.number,
			vector_new(json_get(val.data.obj, "pos.x").data.number, json_get(val.data.obj, "pos.y").data.number, json_get(val.data.obj, "pos.z").data.number),
			vector_unit(vector_new(json_get(val.data.obj, "normal.x").data.number, json_get(val.data.obj, "normal.y").data.number, json_get(val.data.obj, "normal.z").data.number)),
			json_get(val.data.obj, "radius").data.number,
			0
		}, sizeof(t_cone));
	}
	if (ft_strequ(json_get(val.data.obj, "type").data.s, "SPOTLIGHT"))
	{
		ft_memcpy(data + idx, &(t_spotlight){
			SPOTLIGHT,
			color_new(json_get(val.data.obj, "color.red").data.number, json_get(val.data.obj, "color.green").data.number, json_get(val.data.obj, "color.blue").data.number),
			json_get(val.data.obj, "reflection_index").data.number,
			json_get(val.data.obj, "diffuse").data.number,
			vector_new(json_get(val.data.obj, "pos.x").data.number, json_get(val.data.obj, "pos.y").data.number, json_get(val.data.obj, "pos.z").data.number),
			vector_new(json_get(val.data.obj, "dir.x").data.number, json_get(val.data.obj, "dir.y").data.number, json_get(val.data.obj, "dir.z").data.number),
			json_get(val.data.obj, "intensity").data.number
		}, sizeof(t_spotlight));
	}
}
Esempio n. 28
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);
	}
}
Esempio n. 29
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);
	}
}
Esempio n. 30
0
void CSteamProto::PollingThread(void*)
{
	debugLog(_T("CSteamProto::PollingThread: entering"));

	ptrA token(getStringA("TokenSecret"));
	ptrA umqId(getStringA("UMQID"));
	UINT32 messageId = getDword("MessageID", 0);

	//PollApi::PollResult pollResult;
	int errors = 0;
	bool breaked = false;
	while (!isTerminated && !breaked && errors < POLLING_ERRORS_LIMIT)
	{
		PollRequest *request = new PollRequest(token, umqId, messageId, IdleSeconds());
		//request->nlc = m_pollingConnection;
		HttpResponse *response = request->Send(m_hNetlibUser);
		delete request;

		if (response == NULL || response->resultCode != HTTP_CODE_OK)
		{
			if (response != NULL)
				delete response;

			errors++;
			continue;
		}
		else
			errors = 0;

		JSONROOT root(response->pData);
		JSONNode *node = json_get(root, "error");
		ptrT error(json_as_string(node));

		if (!lstrcmpi(error, _T("OK")))
		{
			node = json_get(root, "messagelast");
			messageId = json_as_int(node);

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

			if (nroot != NULL)
			{
				ParsePollData(nroot);
				json_delete(nroot);
			}

			m_pollingConnection = response->nlc;
		}
		else if (!lstrcmpi(error, _T("Timeout")))
		{
			continue;
		}
		/*else if (!lstrcmpi(error, _T("Not Logged On"))) // 'else' below will handle this error, we don't need this particular check right now
		{
			if (!IsOnline())
			{
				// need to relogin
				debugLog(_T("CSteamProto::PollingThread: not logged on"));

				SetStatus(ID_STATUS_OFFLINE);
			}

			breaked = true;
		}*/
		else
		{
			// something wrong
			debugLog(_T("CSteamProto::PollingThread: %s (%d)"), error, response->resultCode);

			// token has expired
			if (response->resultCode == HTTP_CODE_UNAUTHORIZED)
				delSetting("TokenSecret");

			// too low timeout?
			node = json_get(root, "sectimeout");
			int timeout = json_as_int(node);
			if (timeout < STEAM_API_TIMEOUT)
				debugLog(_T("CSteamProto::PollingThread: Timeout is too low (%d)"), timeout);

			breaked = true;
		}

		delete response;
	}

	setDword("MessageID", messageId);

	m_hPollingThread = NULL;
	debugLog(_T("CSteamProto::PollingThread: leaving"));

	if (!isTerminated)
	{
		debugLog(_T("CSteamProto::PollingThread: unexpected termination; switching protocol to offline"));
		SetStatus(ID_STATUS_OFFLINE);
	}
}