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; } }
void SdkHandler::passwordFinished(char *bufferchar) { CCLOG("in function:[%s], buff:[%s]", __FUNCTION__, bufferchar); int state = 0; int userId = 0; int flag = 0; JSONNODE *n = json_parse(bufferchar); if (n == NULL){ return; } JSONNODE_ITERATOR i = json_begin(n); while (i != json_end(n)){ CCLOG("Start Parse Json in [%s]", __FUNCTION__); if (*i == NULL){ break; } // recursively call ourselves to dig deeper into the tree if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE){ break; } // get the node name and value as a string json_char *node_name = json_name(*i); // find out where to store the values if (strcmp(node_name, "STATE") == 0){ json_int_t node_value = json_as_int(*i); state = node_value; } else if (strcmp(node_name, "USER_ID") == 0){ json_int_t node_value = json_as_int(*i); userId = node_value; } else if (strcmp(node_name, "LOGIN_KEY") == 0){ json_char *node_value = json_as_string(*i); json_free(node_value); } else if (strcmp(node_name, "ERROR_TYPE") == 0){ json_int_t node_value = json_as_int(*i); flag = node_value; } // cleanup and increment the iterator json_free(node_name); ++i; } CCLOG("state:[%d], flag:[%d]", state, flag); SdkInfoData *sdkLoginData = new SdkInfoData(); sdkLoginData->state = state; sdkLoginData->errorFlag = flag; SGNotificationCenter::sharedNotificationCenter()->postNotification(PASSWORDLAG,sdkLoginData,false); }
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); } }
void SdkHandler::destroyGuestFinished(char *bufferchar) { CCLOG("in function:[%s], buff:[%s]", __FUNCTION__, bufferchar); int state = 0; int userId = 0; int flag = 0; JSONNODE *n = json_parse(bufferchar); if (n == NULL){ return; } JSONNODE_ITERATOR i = json_begin(n); while (i != json_end(n)){ CCLOG("Start Parse Json in [%s]", __FUNCTION__); if (*i == NULL){ break; } // recursively call ourselves to dig deeper into the tree if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE){ break; } // get the node name and value as a string json_char *node_name = json_name(*i); // find out where to store the values if (strcmp(node_name, "STATE") == 0){ json_int_t node_value = json_as_int(*i); state = node_value; } else if (strcmp(node_name, "USER_ID") == 0){ json_int_t node_value = json_as_int(*i); userId = node_value; } else if (strcmp(node_name, "LOGIN_KEY") == 0){ json_char *node_value = json_as_string(*i); json_free(node_value); } else if (strcmp(node_name, "ERROR_TYPE") == 0){ json_int_t node_value = json_as_int(*i); flag = node_value; } // cleanup and increment the iterator json_free(node_name); ++i; } }
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(); }
void jsonNodeComplete(JSONNODE *root, void *identifier) { Config *cfg = (Config *)identifier; wchar_t logstr[1024]; if (root == NULL) return; KickLog(L"config JSON Knoten korrekt"); // ------------ URL ------------ JSONNODE *n_url = json_get_nocase(root, "project_url"); if (n_url == NULL && json_type(n_url) != JSON_STRING) return; const char *url = json_as_string(n_url); const size_t cSize = strlen(url) + 1; wchar_t* wc = new wchar_t[cSize]; mbstowcs(wc, url, cSize); cfg->SetUrl(wc); swprintf(logstr, L"url: %s", wc); KickLog(logstr); // ------------ request interval ------------ JSONNODE *n_req = json_get_nocase(root, "requesttime"); if (n_req == NULL && json_type(n_req) != JSON_NUMBER) return; unsigned long nReq = json_as_int(n_req); cfg->SetRequestInterval(nReq); swprintf(logstr, L"request interval: %d", nReq); KickLog(logstr); }
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; }
void CVkProto::OnSendChatMsg(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq) { debugLogA("CVkProto::OnSendChatMsg %d", reply->resultCode); if (reply->resultCode == 200) { JSONROOT pRoot; JSONNODE *pResponse = CheckJsonResponse(pReq, reply, pRoot); if (pResponse != NULL) m_sendIds.insert((void*)json_as_int(pResponse)); } }
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); }
void JSON_Get_long(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT json; C_LONGINT returnValue; json.fromParamAtIndex(pParams, 1); JSONNODE *n = _fromHex(json); if(n) returnValue.setIntValue(json_as_int(n)); returnValue.setReturn(pResult); }
void CVkProto::PollUpdates(JSONNODE *pUpdates) { debugLogA("CVkProto::PollUpdates"); CMStringA mids; int msgid, uid, flags; MCONTACT hContact; JSONNODE *pChild; for (int i = 0; (pChild = json_at(pUpdates, i)) != NULL; i++) { switch (json_as_int(json_at(pChild, 0))) { case VKPOLL_MSG_ADDED: // new message msgid = json_as_int(json_at(pChild, 1)); // skip outgoing messages sent from a client flags = json_as_int(json_at(pChild, 2)); if ((flags & VKFLAG_MSGOUTBOX) && !(flags & VKFLAG_MSGCHAT)) if (CheckMid(msgid)) break; if (!mids.IsEmpty()) mids.AppendChar(','); mids.AppendFormat("%d", msgid); break; case VKPOLL_USR_ONLINE: uid = -json_as_int(json_at(pChild, 1)); if ((hContact = FindUser(uid)) != NULL) setWord(hContact, "Status", ID_STATUS_ONLINE); break; case VKPOLL_USR_OFFLINE: uid = -json_as_int(json_at(pChild, 1)); if ((hContact = FindUser(uid)) != NULL) setWord(hContact, "Status", ID_STATUS_OFFLINE); break; case VKPOLL_USR_UTN: uid = json_as_int(json_at(pChild, 1)); if ((hContact = FindUser(uid)) != NULL) CallService(MS_PROTO_CONTACTISTYPING, hContact, 5); break; case VKPOLL_CHAT_CHANGED: int chat_id = json_as_int(json_at(pChild, 1)); CVkChatInfo *cc = m_chats.find((CVkChatInfo*)&chat_id); if (cc) RetrieveChatInfo(cc); break; } } RetrieveMessagesByIds(mids); }
void Callback(JSONNODE * test, void *){ ++counter; switch(counter){ case 1: assertEquals(json_type(test), JSON_NODE); assertTrue(json_empty(test)); break; case 2: assertEquals(json_type(test), JSON_ARRAY); assertTrue(json_empty(test)); break; case 3:{ assertEquals(json_type(test), JSON_NODE); assertEquals(json_size(test), 1); json_char * temp = json_name(json_at(test, 0)); assertCStringSame(temp, JSON_TEXT("hello")); json_free(temp); assertEquals(json_as_int(json_at(test, 0)), 1); break;} case 4: assertEquals(json_type(test), JSON_ARRAY); assertEquals(json_size(test), 3); break; case 5:{ assertEquals(json_type(test), JSON_NODE); assertEquals(json_size(test), 1); json_char * temp = json_name(json_at(test, 0)); assertCStringSame(temp, JSON_TEXT("hi")); json_free(temp); assertEquals(json_size(json_at(test, 0)), 1); assertEquals(json_type(json_at(json_at(test, 0),0)), JSON_NUMBER); temp = json_name(json_at(json_at(test, 0),0)); assertCStringSame(temp, JSON_TEXT("one")); json_free(temp); assertEquals(json_as_int(json_at(json_at(test, 0),0)), 1); break;} } }
void CVkProto::OnCreateNewChat(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq) { debugLogA("CVkProto::OnCreateNewChat %d", reply->resultCode); if (reply->resultCode != 200) return; JSONROOT pRoot; JSONNODE *pResponse = CheckJsonResponse(pReq, reply, pRoot); if (pResponse == NULL) return; int chat_id = json_as_int(pResponse); if (chat_id != NULL) AppendChat(chat_id, NULL); }
void CVkProto::OnSendMessage(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq) { int iResult = ACKRESULT_FAILED; debugLogA("CVkProto::OnSendMessage %d", reply->resultCode); if (reply->resultCode == 200) { JSONROOT pRoot; JSONNODE *pResponse = CheckJsonResponse(pReq, reply, pRoot); if (pResponse != NULL) { m_sendIds.insert((HANDLE)json_as_int(pResponse)); iResult = ACKRESULT_SUCCESS; } } if (m_bServerDelivery) ProtoBroadcastAck(pReq->pData, ACKTYPE_MESSAGE, iResult, pReq->pUserInfo, 0); pReq->pData = NULL; }
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; }
void JSON_GET_LONG_ARRAY(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT json; ARRAY_LONGINT values; json.fromParamAtIndex(pParams, 1); values.setSize(1); JSONNODE *n = _fromHex(json); if(n){ if(json_type(n) == JSON_ARRAY){ JSONNODE_ITERATOR i = json_begin(n); while (i != json_end(n)){ if (*i){ values.appendIntValue(json_as_int(*i)); } ++i; } } } values.toParamAtIndex(pParams, 2); }
void SdkHandler::thirdLoginFinished(char *bufferchar) { CCLOG("in function:[%s], buff:[%s]", __FUNCTION__, bufferchar); CCLOG("userName:[%s], password:[%s]", userName.c_str(), password.c_str()); int state = 0; int userId = 0; int flag = 0; const char* loginKey = NULL; JSONNODE *n = json_parse(bufferchar); if (n == NULL){ return; } JSONNODE_ITERATOR i = json_begin(n); while (i != json_end(n)){ CCLOG("Start Parse Json in [%s]", __FUNCTION__); if (*i == NULL){ break; } // recursively call ourselves to dig deeper into the tree if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE){ break; } // get the node name and value as a string json_char *node_name = json_name(*i); // find out where to store the values if (strcmp(node_name, "STATE") == 0){ json_int_t node_value = json_as_int(*i); state = node_value; } else if (strcmp(node_name, "USER_ID") == 0){ json_int_t node_value = json_as_int(*i); userId = node_value; } else if (strcmp(node_name, "LOGIN_KEY") == 0){ json_char *node_value = json_as_string(*i); loginKey = node_value; } else if (strcmp(node_name, "ERROR_TYPE") == 0){ json_int_t node_value = json_as_int(*i); flag = node_value; } // cleanup and increment the iterator json_free(node_name); ++i; } if (flag == 20) { SGNotificationCenter::sharedNotificationCenter()->postNotification(INVALID_INFO_TIP,new CCInteger(20),false); return ; } CCLOG("state:[%d], err_type:[%d]", state, flag); if (state == 1) { SdkInfoData *sdkLoginData = new SdkInfoData(); sdkLoginData->accountId = userId; sdkLoginData->errorFlag = flag; sdkLoginData->loginKey = std::string(loginKey); sdkLoginData->userName = this->userName; sdkLoginData->password = this->password; sdkLoginData->isEx = this->isExist; CCLOG("loginKey:[%s]", loginKey); //需要将登陆数据写入本地,在此非主线程,需要将当前数据发至主线程写入本地文件 SGNotificationCenter::sharedNotificationCenter()->postNotification(THIRDPARTYLOGIN,sdkLoginData,false); } else if (flag == 13) { SGNotificationCenter::sharedNotificationCenter()->postNotification(BIND_FAILED, false); } else { CCLOG("Login Failed!"); } }
void SdkHandler::registFinished(char *bufferchar) { CCLOG("in function:[%s], buff:[%s]", __FUNCTION__, bufferchar); int state = 0; int userId = 0; int flag = 0; const char* loginKey = NULL; JSONNODE *n = json_parse(bufferchar); if (n == NULL){ return; } JSONNODE_ITERATOR i = json_begin(n); while (i != json_end(n)){ CCLOG("Start Parse Json in [%s]", __FUNCTION__); if (*i == NULL){ break; } // recursively call ourselves to dig deeper into the tree if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE){ break; } // get the node name and value as a string json_char *node_name = json_name(*i); // find out where to store the values if (strcmp(node_name, "STATE") == 0){ json_int_t node_value = json_as_int(*i); state = node_value; } else if (strcmp(node_name, "USER_ID") == 0){ json_int_t node_value = json_as_int(*i); userId = node_value; } else if (strcmp(node_name, "LOGIN_KEY") == 0){ json_char *node_value = json_as_string(*i); loginKey = node_value; } else if (strcmp(node_name, "ERROR_TYPE") == 0){ json_int_t node_value = json_as_int(*i); flag = node_value; } // cleanup and increment the iterator json_free(node_name); ++i; } //这里做状态判定 if (flag == 10) { SGNotificationCenter::sharedNotificationCenter()->postNotification(INVALID_INFO_TIP,new CCInteger(10),false); return ; } else if (flag == 11) { SGNotificationCenter::sharedNotificationCenter()->postNotification(INVALID_INFO_TIP,new CCInteger(11),false); return ; } else if (flag == 12) { SGNotificationCenter::sharedNotificationCenter()->postNotification(INVALID_INFO_TIP,new CCInteger(12),false); return ; } CCLOG("Json parse completed! in fun : [%s]", __FUNCTION__); SdkInfoData *sdkLoginData = new SdkInfoData(); sdkLoginData->state = state; sdkLoginData->accountId = userId; sdkLoginData->flag = flag; sdkLoginData->loginKey = std::string(loginKey); sdkLoginData->userName = userName; sdkLoginData->password = password; sdkLoginData->isEx = true; CCLOG("####state:[%d]m accountId : [%d], flag : [%d], loginKey:[%s]####", state, userId, flag, loginKey); SGNotificationCenter::sharedNotificationCenter()->postNotification(REREGISTFLAG,sdkLoginData,false); }
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); } }
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); } }
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 }
string WhatsAppProto::Register(int state, string cc, string number, string code) { string idx; string ret; DBVARIANT dbv; if ( WASocketConnection::hNetlibUser == NULL) { NotifyEvent(m_tszUserName, TranslateT("Network-connection error."), NULL, WHATSAPP_EVENT_CLIENT); return ret; } if ( !getString(WHATSAPP_KEY_IDX, &dbv)) { idx = dbv.pszVal; db_free(&dbv); } if (idx.empty()) { std::stringstream tm; tm << time(NULL); BYTE idxBuf[16]; utils::md5string(tm.str(), idxBuf); idx = std::string((const char*) idxBuf, 16); setString(WHATSAPP_KEY_IDX, idx.c_str()); } string url; if (state == REG_STATE_REQ_CODE) { unsigned char digest[16]; utils::md5string(std::string(ACCOUNT_TOKEN_PREFIX1) + ACCOUNT_TOKEN_PREFIX2 + number, digest); url = string(ACCOUNT_URL_CODEREQUESTV2); url += "?lc=US&lg=en&mcc=000&mnc=000&method=sms&token=" + Utilities::bytesToHex(digest, 16); } else if (state == REG_STATE_REG_CODE) { url = string(ACCOUNT_URL_REGISTERREQUESTV2); url += "?code="+ code; } url += "&cc="+ cc +"&in="+ number +"&id="+ idx; NETLIBHTTPREQUEST nlhr = {sizeof(NETLIBHTTPREQUEST)}; nlhr.requestType = REQUEST_POST; nlhr.szUrl = (char*) url.c_str(); nlhr.headers = s_registerHeaders; nlhr.headersCount = SIZEOF(s_registerHeaders); nlhr.flags = NLHRF_HTTP11 | NLHRF_GENERATEHOST | NLHRF_REMOVEHOST | NLHRF_SSL; NETLIBHTTPREQUEST* pnlhr = (NETLIBHTTPREQUEST*) CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM) WASocketConnection::hNetlibUser, (LPARAM)&nlhr); string title = this->TranslateStr("Registration"); if (pnlhr == NULL) { this->NotifyEvent(title, this->TranslateStr("Registration failed. Invalid server response."), NULL, WHATSAPP_EVENT_CLIENT); return ret; } debugLogA("Server response: %s", pnlhr->pData); MessageBoxA(NULL, pnlhr->pData, "Debug", MB_OK); JSONROOT resp(pnlhr->pData); if (resp == NULL) { this->NotifyEvent(title, this->TranslateStr("Registration failed. Invalid server response."), NULL, WHATSAPP_EVENT_CLIENT); return ret; } // Status = fail JSONNODE *val = json_get(resp, "status"); if (!lstrcmp( ptrT(json_as_string(val)), _T("fail"))) { JSONNODE *tmpVal = json_get(resp, "reason"); if (!lstrcmp( ptrT(json_as_string(tmpVal)), _T("stale"))) this->NotifyEvent(title, this->TranslateStr("Registration failed due to stale code. Please request a new code"), NULL, WHATSAPP_EVENT_CLIENT); else this->NotifyEvent(title, this->TranslateStr("Registration failed."), NULL, WHATSAPP_EVENT_CLIENT); tmpVal = json_get(resp, "retry_after"); if (tmpVal != NULL) this->NotifyEvent(title, this->TranslateStr("Please try again in %i seconds", json_as_int(tmpVal)), NULL, WHATSAPP_EVENT_OTHER); } // Request code else if (state == REG_STATE_REQ_CODE) { if ( !lstrcmp( ptrT(json_as_string(val)), _T("sent"))) this->NotifyEvent(title, this->TranslateStr("Registration code has been sent to your phone."), NULL, WHATSAPP_EVENT_OTHER); } // Register else if (state == REG_STATE_REG_CODE) { val = json_get(resp, "pw"); if (val == NULL) this->NotifyEvent(title, this->TranslateStr("Registration failed."), NULL, WHATSAPP_EVENT_CLIENT); else ret = _T2A( ptrT(json_as_string(val))); } json_delete(resp); return ret; }
/** * Called by serial_eventloop, this calls the relevant commands. * * This calls the next command in the stack. By default, the command * is cmd_main_menu. * * New in 12.17 onwards: we accept json-formatted commands as well. Those * commands are parsed & dispatched below. * * Important remark: the CLI does not support multiple commands in one * line. For instance { "get": "guid", "get": "rtc" } will not work. * * JSON commands are as follow: * * Settings not linked to setting keys * "set" { * "rtc": integer (Unix timestamp) * "devicetag": string (device tag) * } * * Get/set settings keys (Work in progress not implemented yet): * "setkey" { "name": string, "value": value } * "getkey": "name" * * Getting values not linked to setting keys * "get": * - "guid" * - "rtc" * - "devicetag" * - "settings" * - "cpm" * */ void serial_process_command(char *line) { JSONNODE *n = json_parse(line); if (n == NULL) { // Old style commands (*command_stack[command_stack_size-1])(line); } else { // Dispatch: int err = true; ///// // get ///// JSONNODE *cmd = json_get_nocase(n,"get"); if (cmd != 0 && json_type(cmd) == JSON_STRING) { json_char *val = json_as_string(cmd); if (strcmp(val, "cpm") == 0) { err = false; cmd_cpm(0); } else if (strcmp(val, "guid") == 0) { err = false; cmd_guid(0); } else if (strcmp(val,"rtc") == 0) { err = false; cmd_getrtc(); } else if (strcmp(val,"devicetag") == 0) { err = false; cmd_getdevicetag(0); } else if (strcmp(val, "settings") == 0) { err = false; cmd_keyvaldump(0); } else if (strcmp(val, "version") == 0) { err = false; cmd_version(0); } else if (strcmp(val,"logstatus") == 0) { err = false; cmd_logstatus(0); } json_free(val); } ///// // set ///// cmd = json_get_nocase(n,"set"); if (cmd !=0 && json_type(cmd) == JSON_NODE) { // Find what set operation we wanted: JSONNODE *op = json_get_nocase(cmd, "devicetag"); if (op != 0 && json_type(op) == JSON_STRING) { err = false; json_char *tag = json_as_string(op); flashstorage_keyval_set("DEVICETAG",tag); json_keyval("ok", "devicetag"); } op = json_get_nocase(cmd, "rtc"); if (op != 0 && json_type(op) == JSON_NUMBER) { err = false; uint32_t time = json_as_int(op); if (time != 0) { realtime_set_unixtime(time); json_keyval("ok", "rtc"); } } } if (err) { json_keyval("error", "unknown command"); } } json_delete(n); }
ProjectStats *KickStats::GetProjectStats() { JSONNODE *n = json_parse(m_sContent.c_str()); if (n == NULL) { KickLog(L"Invalid JSON Node"); return NULL; } // {"project":{"id":375955643, "state_changed_at" : 1452521021, "state" : "live", "backers_count" : 239, "pledged" : "5307.0", "comments_count" : 6}} JSONNODE *n_pro = json_get_nocase(n, "project"); if (n_pro == NULL && json_type(n_pro) != JSON_NODE) { KickLog(L"Invalid JSON structure (project not found)"); return NULL; } JSONNODE *n_backers = json_get_nocase(n_pro, "backers_count"); long backers = -1; if (n_backers == NULL) { KickLog(L"Invalid JSON structure (backers_count not found)"); return NULL; } if (json_type(n_backers) == JSON_NUMBER) { backers = json_as_int(n_backers); } JSONNODE *n_comments = json_get_nocase(n_pro, "comments_count"); long comments = -1; if (n_comments == NULL) { KickLog(L"Invalid JSON structure (comments_count not found)"); return NULL; } if (json_type(n_comments) == JSON_NUMBER) { comments = json_as_int(n_comments); } JSONNODE *n_pledged = json_get_nocase(n_pro, "pledged"); double pledged = -2.0; if (n_pledged == NULL) { KickLog(L"Invalid JSON structure (pledged not found)"); return NULL; } if (json_type(n_pledged) == JSON_STRING) { pledged = atof(json_as_string(n_pledged)); } ProjectStats *stats = new ProjectStats; stats->nBackers = backers; stats->nComments = comments; stats->fPledged = pledged; return stats; }
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(); }
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 }
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); }
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); }
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; }
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); }