1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
|
/*
Copyright (c) 2013-16 Miranda NG project (http://miranda-ng.org)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation version 2
of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "stdafx.h"
//////////////////////////////////////////////////////////////////////////////
int CVkProto::RecvMsg(MCONTACT hContact, PROTORECVEVENT *pre)
{
debugLogA("CVkProto::RecvMsg");
Proto_RecvMessage(hContact, pre);
return 0;
}
//////////////////////////////////////////////////////////////////////////////
void CVkProto::SendMsgAck(void *param)
{
debugLogA("CVkProto::SendMsgAck");
CVkSendMsgParam *ack = (CVkSendMsgParam *)param;
Sleep(100);
ProtoBroadcastAck(ack->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, (HANDLE)ack->iMsgID);
delete ack;
}
int CVkProto::SendMsg(MCONTACT hContact, int, const char *szMsg)
{
debugLogA("CVkProto::SendMsg");
if (!IsOnline())
return 0;
bool bIsChat = isChatRoom(hContact);
LONG iUserID = getDword(hContact, bIsChat ? "vk_chat_id" : "ID" , VK_INVALID_USER);
if (iUserID == VK_INVALID_USER || iUserID == VK_FEED_USER) {
ForkThread(&CVkProto::SendMsgAck, new CVkSendMsgParam(hContact));
return 0;
}
int StickerId = 0;
ptrA pszRetMsg(GetStickerId(szMsg, StickerId));
ULONG uMsgId = ::InterlockedIncrement(&m_msgId);
AsyncHttpRequest *pReq = new AsyncHttpRequest(this, REQUEST_POST, "/method/messages.send.json", true, bIsChat? &CVkProto::OnSendChatMsg : &CVkProto::OnSendMessage, AsyncHttpRequest::rpHigh)
<< INT_PARAM(bIsChat ? "chat_id" : "peer_id", iUserID)
<< INT_PARAM("random_id", ((LONG) time(NULL)) * 100 + uMsgId % 100);
pReq->AddHeader("Content-Type", "application/x-www-form-urlencoded");
if (StickerId)
pReq << INT_PARAM("sticker_id", StickerId);
else {
pReq << CHAR_PARAM("message", szMsg);
if (m_vkOptions.bSendVKLinksAsAttachments) {
CMStringA szAttachments = GetAttachmentsFromMessage(szMsg);
if (!szAttachments.IsEmpty()) {
debugLogA("CVkProto::SendMsg Attachments = %s", szAttachments);
pReq << CHAR_PARAM("attachment", szAttachments);
}
}
}
if (!bIsChat)
pReq->pUserInfo = new CVkSendMsgParam(hContact, uMsgId);
Push(pReq);
if (!m_bServerDelivery && !bIsChat)
ForkThread(&CVkProto::SendMsgAck, new CVkSendMsgParam(hContact, uMsgId));
if (!IsEmpty(pszRetMsg))
SendMsg(hContact, 0, pszRetMsg);
return uMsgId;
}
void CVkProto::OnSendMessage(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq)
{
int iResult = ACKRESULT_FAILED;
if (pReq->pUserInfo == NULL) {
debugLogA("CVkProto::OnSendMessage failed! (pUserInfo == NULL)");
return;
}
CVkSendMsgParam *param = (CVkSendMsgParam *)pReq->pUserInfo;
debugLogA("CVkProto::OnSendMessage %d", reply->resultCode);
if (reply->resultCode == 200) {
JSONNode jnRoot;
const JSONNode &jnResponse = CheckJsonResponse(pReq, reply, jnRoot);
if (jnResponse) {
UINT mid;
if (jnResponse.type() != JSON_STRING)
mid = jnResponse.as_int();
else if (swscanf(jnResponse.as_mstring(), L"%d", &mid) != 1)
mid = 0;
if (param->iMsgID != -1)
m_sendIds.insert((HANDLE)mid);
if (mid > getDword(param->hContact, "lastmsgid"))
setDword(param->hContact, "lastmsgid", mid);
if (m_vkOptions.iMarkMessageReadOn >= MarkMsgReadOn::markOnReply)
MarkMessagesRead(param->hContact);
iResult = ACKRESULT_SUCCESS;
}
}
if (param->pFUP) {
ProtoBroadcastAck(param->hContact, ACKTYPE_FILE, iResult, (HANDLE)(param->pFUP));
if (!pReq->bNeedsRestart || m_bTerminated)
delete param->pFUP;
}
else if (m_bServerDelivery)
ProtoBroadcastAck(param->hContact, ACKTYPE_MESSAGE, iResult, (HANDLE)(param->iMsgID));
if (!pReq->bNeedsRestart || m_bTerminated) {
delete param;
pReq->pUserInfo = NULL;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
int CVkProto::OnDbEventRead(WPARAM, LPARAM hDbEvent)
{
debugLogA("CVkProto::OnDbEventRead");
MCONTACT hContact = db_event_getContact(hDbEvent);
if (!hContact)
return 0;
CMStringA szProto(ptrA(db_get_sa(hContact, "Protocol", "p")));
if (szProto.IsEmpty() || szProto != m_szModuleName)
return 0;
if (m_vkOptions.iMarkMessageReadOn == MarkMsgReadOn::markOnRead)
MarkMessagesRead(hContact);
return 0;
}
INT_PTR CVkProto::SvcMarkMessagesAsRead(WPARAM hContact, LPARAM)
{
MarkDialogAsRead(hContact);
MarkMessagesRead(hContact);
return 0;
}
void CVkProto::MarkMessagesRead(const CMStringA &mids)
{
debugLogA("CVkProto::MarkMessagesRead (mids)");
if (!IsOnline() || mids.IsEmpty())
return;
Push(new AsyncHttpRequest(this, REQUEST_GET, "/method/messages.markAsRead.json", true, &CVkProto::OnReceiveSmth, AsyncHttpRequest::rpLow)
<< CHAR_PARAM("message_ids", mids));
}
void CVkProto::MarkMessagesRead(const MCONTACT hContact)
{
debugLogA("CVkProto::MarkMessagesRead (hContact)");
if (!IsOnline() || !hContact)
return;
LONG userID = getDword(hContact, "ID", VK_INVALID_USER);
if (userID == VK_INVALID_USER || userID == VK_FEED_USER)
return;
Push(new AsyncHttpRequest(this, REQUEST_GET, "/method/messages.markAsRead.json", true, &CVkProto::OnReceiveSmth, AsyncHttpRequest::rpLow)
<< INT_PARAM("peer_id", userID));
}
void CVkProto::RetrieveMessagesByIds(const CMStringA &mids)
{
debugLogA("CVkProto::RetrieveMessagesByIds");
if (!IsOnline() || mids.IsEmpty())
return;
CMStringA code(FORMAT, "var Mids=\"%s\";"
"var Msgs=API.messages.getById({\"message_ids\":Mids});"
"var FMsgs=Msgs.items@.fwd_messages;"
"var Idx=0;var Uids=[];"
"while(Idx<FMsgs.length){"
"var Jdx=0;var CFMsgs=parseInt(FMsgs[Idx].length);"
"while(Jdx<CFMsgs){Uids.unshift(FMsgs[Idx][Jdx].user_id);"
"Jdx=Jdx+1;};Idx=Idx+1;};"
"var FUsers=API.users.get({\"user_ids\":Uids,\"name_case\":\"gen\"});"
"return{\"Msgs\":Msgs,\"fwd_users\":FUsers};",
mids
);
Push(new AsyncHttpRequest(this, REQUEST_GET, "/method/execute.json", true, &CVkProto::OnReceiveMessages, AsyncHttpRequest::rpHigh)
<< CHAR_PARAM("code", code));
}
void CVkProto::RetrieveUnreadMessages()
{
debugLogA("CVkProto::RetrieveUnreadMessages");
if (!IsOnline())
return;
Push(new AsyncHttpRequest(this, REQUEST_GET, "/method/messages.getDialogs.json", true, &CVkProto::OnReceiveDlgs)
<< INT_PARAM ("count", 200));
}
void CVkProto::OnReceiveMessages(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq)
{
debugLogA("CVkProto::OnReceiveMessages %d", reply->resultCode);
if (reply->resultCode != 200)
return;
JSONNode jnRoot;
const JSONNode &jnResponse = CheckJsonResponse(pReq, reply, jnRoot);
if (!jnResponse)
return;
if (!jnResponse["Msgs"])
return;
CMStringA mids;
int numMessages = jnResponse["Msgs"]["count"].as_int();
const JSONNode &jnMsgs = jnResponse["Msgs"]["items"];
const JSONNode &jnFUsers = jnResponse["fwd_users"];
debugLogA("CVkProto::OnReceiveMessages numMessages = %d", numMessages);
for (auto it = jnMsgs.begin(); it != jnMsgs.end(); ++it) {
const JSONNode &jnMsg = (*it);
if (!jnMsg) {
debugLogA("CVkProto::OnReceiveMessages pMsg == NULL");
break;
}
UINT mid = jnMsg["id"].as_int();
CMStringW wszBody(jnMsg["body"].as_mstring());
int datetime = jnMsg["date"].as_int();
int isOut = jnMsg["out"].as_int();
int isRead = jnMsg["read_state"].as_int();
int uid = jnMsg["user_id"].as_int();
const JSONNode &jnFwdMessages = jnMsg["fwd_messages"];
if (jnFwdMessages) {
CMStringW wszFwdMessages = GetFwdMessages(jnFwdMessages, jnFUsers, m_vkOptions.BBCForAttachments());
if (!wszBody.IsEmpty())
wszFwdMessages = L"\n" + wszFwdMessages;
wszBody += wszFwdMessages;
}
CMStringW wszAttachmentDescr;
const JSONNode &jnAttachments = jnMsg["attachments"];
if (jnAttachments) {
wszAttachmentDescr = GetAttachmentDescr(jnAttachments, m_vkOptions.BBCForAttachments());
if (!wszBody.IsEmpty())
wszBody += L"\n";
wszBody += wszAttachmentDescr;
}
MCONTACT hContact = NULL;
int chat_id = jnMsg["chat_id"].as_int();
if (chat_id == 0)
hContact = FindUser(uid, true);
char szMid[40];
_itoa(mid, szMid, 10);
if (m_vkOptions.iMarkMessageReadOn == MarkMsgReadOn::markOnReceive || chat_id != 0) {
if (!mids.IsEmpty())
mids.AppendChar(',');
mids.Append(szMid);
}
if (chat_id != 0) {
debugLogA("CVkProto::OnReceiveMessages chat_id != 0");
CMStringW action_chat = jnMsg["action"].as_mstring();
int action_mid = _wtoi(jnMsg["action_mid"].as_mstring());
if ((action_chat == L"chat_kick_user") && (action_mid == m_myUserId))
KickFromChat(chat_id, uid, jnMsg, jnFUsers);
else {
MCONTACT chatContact = FindChat(chat_id);
if (chatContact && getBool(chatContact, "kicked", true))
db_unset(chatContact, m_szModuleName, "kicked");
AppendChatMessage(chat_id, jnMsg, jnFUsers, false);
}
continue;
}
PROTORECVEVENT recv = { 0 };
bool bUseServerReadFlag = m_vkOptions.bSyncReadMessageStatusFromServer ? true : !m_vkOptions.bMesAsUnread;
if (isRead && bUseServerReadFlag)
recv.flags |= PREF_CREATEREAD;
if (isOut)
recv.flags |= PREF_SENT;
else if (m_vkOptions.bUserForceInvisibleOnActivity && time(NULL) - datetime < 60 * m_vkOptions.iInvisibleInterval)
SetInvisible(hContact);
T2Utf pszBody(wszBody);
recv.timestamp = m_vkOptions.bUseLocalTime ? time(NULL) : datetime;
recv.szMessage = pszBody;
recv.lParam = isOut;
recv.pCustomData = szMid;
recv.cbCustomDataSize = (int)mir_strlen(szMid);
Sleep(100);
debugLogA("CVkProto::OnReceiveMessages mid = %d, datetime = %d, isOut = %d, isRead = %d, uid = %d", mid, datetime, isOut, isRead, uid);
if (!CheckMid(m_sendIds, mid)) {
debugLogA("CVkProto::OnReceiveMessages ProtoChainRecvMsg");
ProtoChainRecvMsg(hContact, &recv);
if (mid > getDword(hContact, "lastmsgid", -1))
setDword(hContact, "lastmsgid", mid);
if (!isOut)
m_incIds.insert((HANDLE)mid);
}
else if (m_vkOptions.bLoadSentAttachments && !wszAttachmentDescr.IsEmpty() && isOut) {
T2Utf pszAttach(wszAttachmentDescr);
recv.timestamp = time(NULL); // only local time
recv.szMessage = pszAttach;
ProtoChainRecvMsg(hContact, &recv);
}
}
if (!mids.IsEmpty())
MarkMessagesRead(mids);
}
void CVkProto::OnReceiveDlgs(NETLIBHTTPREQUEST *reply, AsyncHttpRequest *pReq)
{
debugLogA("CVkProto::OnReceiveDlgs %d", reply->resultCode);
if (reply->resultCode != 200)
return;
JSONNode jnRoot;
const JSONNode &jnResponse = CheckJsonResponse(pReq, reply, jnRoot);
if (!jnResponse)
return;
const JSONNode &jnDlgs = jnResponse["items"];
if (!jnDlgs)
return;
CMStringA szGroupIds;
for (auto it = jnDlgs.begin(); it != jnDlgs.end(); ++it) {
if (!(*it))
break;
int numUnread = (*it)["unread"].as_int();
const JSONNode &jnDlg = (*it)["message"];
if (jnDlg == NULL)
break;
int uid = 0;
MCONTACT hContact(NULL);
int chatid = jnDlg["chat_id"].as_int();
if (!chatid) {
uid = jnDlg["user_id"].as_int();
hContact = FindUser(uid, true);
if (IsGroupUser(hContact))
szGroupIds.AppendFormat(szGroupIds.IsEmpty() ? "%d" : ",%d", -1 * uid);
if (ServiceExists(MS_MESSAGESTATE_UPDATE)) {
time_t tLastReadMessageTime = jnDlg["date"].as_int();
bool isOut = jnDlg["out"].as_bool();
bool isRead = jnDlg["read_state"].as_bool();
if (isRead && isOut) {
MessageReadData data(tLastReadMessageTime, MRD_TYPE_MESSAGETIME);
CallService(MS_MESSAGESTATE_UPDATE, hContact, (LPARAM)&data);
}
}
}
if (chatid) {
debugLogA("CVkProto::OnReceiveDlgs chatid = %d", chatid);
if (m_chats.find((CVkChatInfo*)&chatid) == NULL)
AppendChat(chatid, jnDlg);
}
else if (m_vkOptions.iSyncHistoryMetod) {
int mid = jnDlg["id"].as_int();
m_bNotifyForEndLoadingHistory = false;
if (getDword(hContact, "lastmsgid", -1) == -1 && numUnread)
GetServerHistory(hContact, 0, numUnread, 0, 0, true);
else
GetHistoryDlg(hContact, mid);
if (m_vkOptions.iMarkMessageReadOn == MarkMsgReadOn::markOnReceive && numUnread)
MarkMessagesRead(hContact);
}
else if (numUnread) {
m_bNotifyForEndLoadingHistory = false;
GetServerHistory(hContact, 0, numUnread, 0, 0, true);
if (m_vkOptions.iMarkMessageReadOn == MarkMsgReadOn::markOnReceive)
MarkMessagesRead(hContact);
}
}
RetrieveUsersInfo();
RetrieveGroupInfo(szGroupIds);
}
|