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 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); }
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); } }
bool Json::Parse(const string& str) { JSONNODE* node = json_parse(str.c_str()); if (node == NULL) return false; JSONNODE_ITERATOR iter = json_begin(node); while (iter != json_end(node)) { json_char* nodeName = json_name(*iter); if(string(nodeName) == "" || json_type(*iter) == JSON_NULL) { json_free(nodeName); break; } if (json_type(*iter) == JSON_NODE) { if(!Parse(nodeName, *iter)) return false; } else if(json_type(*iter) == JSON_ARRAY) { JSONNODE_ITERATOR i = json_begin(*iter); while (i != json_end(*iter)) { if(json_type(*iter) == JSON_NUMBER) { mDataFloatArray[nodeName].push_back(json_as_float(*i)); } else { mDataStrArray[nodeName].push_back(json_as_string(*i)); } i++; } } else if(json_type(*iter) == JSON_NUMBER) { mDataFloat[nodeName] = json_as_float(*iter); } else if(json_type(*iter) == JSON_BOOL) { mDataBool[nodeName] = json_as_bool(*iter); } else if(json_type(*iter) == JSON_STRING) { mDataStr[nodeName] = json_as_string(*iter); } json_free(nodeName); iter++; } json_delete(node); return true; }
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 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); } }
int json_wlparam_strset_proc(JSONNODE* node, wlp_descr_t* wlp, void* param) { int i; wlp_strset_t* ss = (wlp_strset_t*) param; char* js = NULL; if(json_type(node) != JSON_STRING) return WLPARAM_JSON_WRONG_TYPE; js = json_as_string(node); for(i = 0; i < wlp->range.ss_num; ++i) { if(strcmp(wlp->range.ss_strings[i], js) == 0) { *ss = i; json_free(js); return WLPARAM_JSON_OK; } } /* No match found - wrong value provided*/ json_free(js); *ss = -1; return WLPARAM_JSON_OUTSIDE_RANGE; }
void JSON_GET_TEXT_ARRAY(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT json; ARRAY_TEXT 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){ json_char *s = json_as_string(*i); std::wstring w = std::wstring(s); C_TEXT t; _copyString(w, t); CUTF16String u; t.copyUTF16String(&u); values.appendUTF16String(&u); json_free(s); } ++i; } } } values.toParamAtIndex(pParams, 2); }
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 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); }
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); }
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 k8s_api_handler::handle_json(Json::Value&& root) { if(g_logger.get_severity() >= sinsp_logger::SEV_TRACE) { g_logger.log("K8S API handler: \n" + json_as_string(root), sinsp_logger::SEV_TRACE); } handle_component(root); }
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; } }
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; }
void JSON_Get_text(sLONG_PTR *pResult, PackagePtr pParams) { C_TEXT json; C_TEXT returnValue; json.fromParamAtIndex(pParams, 1); JSONNODE *n = _fromHex(json); if(n){ json_char *s = json_as_string(n); std::wstring w = std::wstring(s); _copyString(w, returnValue); json_free(s); } returnValue.setReturn(pResult); }
int json_wlparam_string_proc(JSONNODE* node, wlp_descr_t* wlp, void* param) { wlp_string_t* str = (wlp_string_t*) param; char* js = NULL; if(json_type(node) != JSON_STRING) return WLPARAM_JSON_WRONG_TYPE; js = json_as_string(node); if(strlen(js) > wlp->range.str_length) return WLPARAM_JSON_OUTSIDE_RANGE; strcpy(param, js); json_free(js); return WLPARAM_JSON_OK; }
bool admJsonToCouple::scan( void *xnode,string name) { JSONNODE *node=(JSONNODE *)xnode; if (!node){ ADM_error("Invalid JSON Node\n"); return false; } JSONNODE_ITERATOR i = json_begin(node); while (i != json_end(node)){ if (*i == NULL){ ADM_error("Invalid JSON Node\n"); return false; } json_char *node_name = json_name(*i); //printf("Node :%s\n",node_name); // recursively call ourselves to dig deeper into the tree if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE) { if(name=="") scan(*i,string(node_name)); else scan(*i,name+string(".")+string(node_name)); } else { keyVal k; json_char *node_value = json_as_string(*i); if(name=="") k.key=string(node_name); else k.key=string(name)+string(".")+string(node_name); k.value=string(node_value); readItems.push_back(k); json_free(node_value); } json_free(node_name); ++i; } return true; }
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 test_object_many(void) { json_buffer_t* buf = JSON_BUFFER(" [true, 10,\"hi!\"] "); json_node_t* obj; json_node_t* el; assert(json_parse(buf, &obj) == JSON_OK); assert(json_size(obj) == 3); el = json_getitem(obj, 0); assert(el != NULL); assert(json_as_boolean(el) == B_TRUE); el = json_getitem(obj, 1); assert(el != NULL); assert(json_as_integer(el) == 10); el = json_getitem(obj, 2); assert(el != NULL); assert(strcmp(json_as_string(el), "hi!") == 0); json_node_destroy(obj); }
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 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); }
UINT CDropbox::RequestAcceessTokenAsync(void *owner, void* param) { HWND hwndDlg = (HWND)param; CDropbox *instance = (CDropbox*)owner; EnableWindow(GetDlgItem(hwndDlg, IDC_AUTHORIZE), FALSE); SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("in process...")); if (instance->HasAccessToken()) instance->DestroyAcceessToken(); char requestToken[128]; GetDlgItemTextA(hwndDlg, IDC_REQUEST_CODE, requestToken, SIZEOF(requestToken)); char data[1024]; mir_snprintf( data, SIZEOF(data), "grant_type=authorization_code&code=%s", requestToken); HttpRequest *request = new HttpRequest(instance->hNetlibUser, REQUEST_POST, DROPBOX_API_URL "/oauth2/token"); request->AddBasicAuthHeader(DROPBOX_API_KEY, DROPBOX_API_SECRET); request->AddHeader("Content-Type", "application/x-www-form-urlencoded"); request->pData = mir_strdup(data); request->dataLength = (int)strlen(data); mir_ptr<NETLIBHTTPREQUEST> response(request->Send()); delete request; MCONTACT hContact = instance->GetDefaultContact(); if (response) { JSONROOT root(response->pData); if (root) { if (response->resultCode == HTTP_STATUS_OK) { JSONNODE *node = json_get(root, "access_token"); ptrA access_token = ptrA(mir_u2a(json_as_string(node))); db_set_s(NULL, MODULE, "TokenSecret", access_token); if (hContact) { if (db_get_w(hContact, MODULE, "Status", ID_STATUS_OFFLINE) == ID_STATUS_OFFLINE) db_set_w(hContact, MODULE, "Status", ID_STATUS_ONLINE); } instance->RequestAccountInfo(); if (hwndDlg) SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("you have been authorized")); /*else ShowNotification(TranslateT("you have been authorized"), MB_ICONINFORMATION);*/ } else { JSONNODE *node = json_get(root, "error_description"); ptrW error_description(json_as_string(node)); if (hwndDlg) SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, error_description); /*else ShowNotification((wchar_t*)error_description, MB_ICONERROR);*/ } } } else { if (hwndDlg) SetDlgItemText(hwndDlg, IDC_AUTH_STATUS, TranslateT("server does not respond")); HandleHttpResponseError(instance->hNetlibUser, response); } SetDlgItemTextA(hwndDlg, IDC_REQUEST_CODE, ""); return 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); } }
const char *json_get_string(JSON *j, const char *name) { JSON *v = json_get_member(j, name); if(v) return json_as_string(v); return NULL; }
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 CVkProto::OnReceiveFriends(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq) { debugLogA("CVkProto::OnReceiveFriends %d", reply->resultCode); if (reply->resultCode != 200) return; JSONROOT pRoot; JSONNODE *pResponse = CheckJsonResponse(pReq, reply, pRoot), *pInfo; if (pResponse == NULL) return; bool bCleanContacts = getByte("AutoClean", 0) != 0; LIST<void> arContacts(10, PtrKeySortT); if (bCleanContacts) for (MCONTACT hContact = db_find_first(m_szModuleName); hContact; hContact = db_find_next(hContact, m_szModuleName)) if (!isChatRoom(hContact)) arContacts.insert((HANDLE)hContact); for (int i = 0; (pInfo = json_at(pResponse, i)) != NULL; i++) { ptrT szValue(json_as_string(json_get(pInfo, "uid"))); if (szValue == NULL) continue; CMString tszNick; MCONTACT hContact = FindUser(_ttoi(szValue), true); arContacts.remove((HANDLE)hContact); szValue = json_as_string(json_get(pInfo, "first_name")); if (szValue) { setTString(hContact, "FirstName", szValue); tszNick.Append(szValue); tszNick.AppendChar(' '); } if (szValue = json_as_string(json_get(pInfo, "last_name"))) { setTString(hContact, "LastName", szValue); tszNick.Append(szValue); } if (!tszNick.IsEmpty()) setTString(hContact, "Nick", tszNick); szValue = json_as_string(json_get(pInfo, "photo_medium")); SetAvatarUrl(hContact, szValue); setWord(hContact, "Status", (json_as_int(json_get(pInfo, "online")) == 0) ? ID_STATUS_OFFLINE : ID_STATUS_ONLINE); int iValue = json_as_int(json_get(pInfo, "sex")); if (iValue) setByte(hContact, "Gender", (iValue == 2) ? 'M' : 'F'); if ((iValue = json_as_int(json_get(pInfo, "timezone"))) != 0) setByte(hContact, "Timezone", iValue * -2); szValue = json_as_string(json_get(pInfo, "mobile_phone")); if (szValue && *szValue) setTString(hContact, "Cellular", szValue); szValue = json_as_string(json_get(pInfo, "home_phone")); if (szValue && *szValue) setTString(hContact, "Phone", szValue); } if (bCleanContacts) for (int i = 0; i < arContacts.getCount(); i++) CallService(MS_DB_CONTACT_DELETE, (WPARAM)arContacts[i], 0); }
void 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); }
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); } }
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(); }