/
client.cpp
1986 lines (1731 loc) · 65.4 KB
/
client.cpp
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Hanghish
Copyright (C) 2015 Daniele Rogora
This file is part of Hangish.
Hangish 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, either version 3 of the License, or
(at your option) any later version.
Hangish 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 Nome-Programma. If not, see <http://www.gnu.org/licenses/>
*/
#include "client.h"
#include "messagefield.h"
static QString CHAT_INIT_URL = "https://talkgadget.google.com/u/0/talkgadget/_/chat";
//static QString user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0";
static QString user_agent = "hangish";
//Timeout to send for setactiveclient requests:
static int ACTIVE_TIMEOUT_SECS = 300;
//Minimum timeout between subsequent setactiveclient requests:
static int SETACTIVECLIENT_LIMIT_SECS = 30;
static QString endpoint = "https://clients6.google.com/chat/v1/";
static QString ORIGIN_URL = "https://talkgadget.google.com";
#define TIMEOUT_MS 10000
#define TIMEOUT_MS_UPLOAD 100000
void Client::sendPin(QString pin)
{
auth->sendPin(pin);
}
void Client::sendPassword(QString uname, QString pwd)
{
auth->openLoginPage(uname, pwd);
}
QString Client::getSelfChatId()
{
return myself.chat_id;
}
void Client::parseSelfConversationState(QList<MessageField> stateFields, Conversation &res)
{
//skip 6 fields
//Self read state
auto ssstate = stateFields[6].list();
//Entry 0 is my ID, not so interesting
//This is the ts representing last time I read
QString ts = ssstate[1].number();
//qDebug() << "ssstate, ts: " << ts;
res.lastReadTimestamp = QDateTime::fromMSecsSinceEpoch(ts.toLongLong() / 1000);
//qDebug() << res.lastReadTimestamp.toString();
//todo: parse this
res.status = (ConversationStatus)stateFields[7].number().toInt();
//TODO: Handle this
//qDebug() << "STATUS " << status;
//UNKNOWN_CONVERSATION_STATUS = 0
//INVITED = 1
//ACTIVE = 2
//LEFT = 3
res.notifLevel = (NotificationLevel)stateFields[8].number().toInt();
//qDebug() << res.notifLevel;
auto views = stateFields[9].list();
//qDebug() << "W size " << views.size(); SIZE IS ALWAYS 1
res.view = (ConversationView)views[0].number().toInt();
//UNKNOWN_CONVERSATION_VIEW = 0
//INBOX_VIEW = 1
//ARCHIVED_VIEW = 2
auto inviters_ids = stateFields[10].list();
QString inviter_id = inviters_ids[0].string();
//qDebug() << inviter_id;
res.creator.chat_id = inviter_id;
QString invitation_ts = stateFields[11].number();
//qDebug() << invitation_ts;
res.creation_ts.fromMSecsSinceEpoch(invitation_ts.toUInt());
QString sort_ts = stateFields[12].number();
//qDebug() << sort_ts;
QString a_ts = stateFields[13].number();
//qDebug() << a_ts;
//skip 4 fields
}
User Client::parseEntity(QList<MessageField> entity)
{
User res;
if (entity.size() >= 10) {
auto ids = entity[8].list();
if (ids.size() >= 2) {
res.chat_id = ids[0].string();
res.gaia_id = ids[1].string();
}
else {
res.chat_id = "NF";
}
auto properties = entity[9].list();
if (properties.size() >= 5) {
res.display_name = properties[1].string();
res.first_name = properties[2].string();
res.photo = properties[3].string();
auto emails = properties[4].list();
if (emails.size() >= 1)
res.email = emails[0].string();
}
else {
qDebug() << "Parsing single entity properties error " << properties.size();
res.display_name = res.first_name = res.email = "Not found";
res.photo = "";
}
/*
qDebug() << "ID: " << res.chat_id;
qDebug() << "DNAME: " << res.display_name;
qDebug() << "FNAME: " << res.first_name;
qDebug() << "EMAIL: " << res.email;
*/
}
else {
qDebug() << "Parsing single entity error " << entity.size();
res.chat_id = res.gaia_id = res.display_name = res.first_name = res.email = "NF";
res.photo = "";
}
return res;
}
QList<User> Client::parseClientEntities(QList<MessageField> entities)
{
//qDebug() << "Parsing client entities " << input;
QList<User> res;
for (auto messageField : entities) {
User tmpUser = parseEntity(messageField.list());
if (!getUserById(tmpUser.chat_id).alreadyParsed)
res.append(tmpUser);
//else //qDebug() << "User already in " << tmpUser.chat_id;
}
return res;
}
QList<User> Client::parseGroup(QList<MessageField> group)
{
// qDebug() << "Parsinggroup ";// << input;
QList<User> res;
if (group.size() >= 3) {
auto groupEntities = group[2].list();
for (auto entity : groupEntities) {
auto eentity = entity.list();
if (eentity.size()) {
User tmpUser = parseEntity(eentity[0].list());
if (!getUserById(tmpUser.chat_id).alreadyParsed)
res.append(tmpUser);
}
}
}
return res;
}
QList<User> Client::parseUsers(const QString& userString)
{
QList<User> res;
QStringRef dsData = Utils::extractArrayForDS(userString, 21);
int idx = 0;
auto parsedData = MessageField::parseListRef(dsData, idx);
//qDebug() << parsedData.size();
if (parsedData.size() >= 3) {
auto entities = parsedData[2].list();
res.append(parseClientEntities(entities));
//Now we have groups; what are these?
for (int i = 4; i < parsedData.size(); ++i) {
res.append(parseGroup(parsedData[i].list()));
}
}
return res;
}
User Client::getUserById(QString chatId)
{
//qDebug() << "Searching for user " << chatId;
foreach (User u, users)
if (u.chat_id==chatId) {
u.alreadyParsed = true;
return u;
}
User foo;
foo.alreadyParsed = false;
foo.gaia_id = foo.chat_id = chatId;
foo.display_name = "User not found";
return foo;
}
QString Client::getConversationName(QString convId)
{
return rosterModel->getConversationName(convId);
}
User Client::getEntityById(QString cid) {
User foo;
foo.chat_id = foo.gaia_id = cid;
foo.display_name = "User not found 2";
foo.first_name = "Unknown";
foo.email = "foo@foo.foo";
foo.alreadyParsed = true;
foo.photo = "";
if (!connectedToInternet) {
contactsModel->addContact(foo);
return foo;
}
QString body = "[";
body += getRequestHeader();
body += ", null, [[\"";
body += cid;
body += "\"]]]";
qDebug() << body;
QNetworkReply *reply = sendRequest("contacts/getentitybyid",body);
//Sync on te request
QEventLoop loop;
connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
timeoutTimer.stop();
QString sreply = reply->readAll();
qDebug() << "Got reply! " << sreply;
processCookies(reply);
if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()==200) {
qDebug() << "200";
int idx = 0;
auto parsedReply = MessageField::parseListRef(sreply.leftRef(-1), idx);
if (parsedReply.size() < 3) {
qDebug() << "Too short";
reply->deleteLater();
contactsModel->addContact(foo);
return foo;
}
auto entities = parsedReply[2].list();
if (entities.size() != 1) {
qDebug() << "Something went wrong, have " << entities.size();
}
else {
auto entity = entities[0].list();
User tmp = parseEntity(entity);
if (tmp.chat_id == "NF") {
tmp.chat_id = tmp.gaia_id = cid;
}
//Some users may have no info like display_name or whatsoever... Probably these have deleted their g+ account
if (tmp.display_name == "")
tmp.display_name = "Unknown";
if (tmp.first_name == "")
tmp.first_name = "Unknown";
contactsModel->addContact(tmp);
users.append(tmp); //cache the parsed user
reply->deleteLater();
return tmp;
}
}
contactsModel->addContact(foo);
reply->deleteLater();
return foo;
}
void Client::parseConversationAbstract(QList<MessageField> abstractFields, Conversation &res)
{
//First we have ID -- ignore
//Then type
if (abstractFields.size() < 2)
return;
QString type = abstractFields[1].number();
//qDebug() << "TYPE: " << type;
//Name (optional) -- need to see what happens when it is set
if (abstractFields.size() < 3)
return;
res.name = abstractFields[2].string();
//qDebug() << "Name: " << res.name;
// parse the state
if (abstractFields.size() < 4)
return;
auto conversationState = abstractFields[3].list();
parseSelfConversationState(conversationState, res);
if (abstractFields.size() < 8)
return;
//Now I have read_state
QList<ReadState> readStates;
for (auto rs : abstractFields[7].list()) {
readStates << Utils::parseReadState(rs);
}
if (abstractFields.size() < 13)
return;
//skip 4 fields
auto participants = abstractFields[12].list();
for (auto p : participants) {
Identity id = Utils::parseIdentity(p.list());
User tmp = getUserById(id.chat_id);
if ((tmp.chat_id == myself.chat_id) || (tmp.display_name != "User not found")) {
res.participants.append({tmp, {}});
}
else {
if (tmp.chat_id != myself.chat_id) {
qDebug() << "Have a UNF here " << tmp.chat_id;
User parsedUser = getEntityById(tmp.chat_id);
//Put it anyway, as a reminder that we should update it
res.participants.append({parsedUser, {}});
}
}
}
//Merge read states with participants
//THIS HOLDS INFO ONLY ABOUT MYSELF, NOT NEEDED NOW!
foreach (Participant p, res.participants)
{
foreach (ReadState r, readStates)
{
if (p.user.chat_id == r.userid.chat_id)
{
p.last_read_timestamp = r.last_read;
break;
}
}
}
}
Conversation Client::parseConversation(QList<MessageField> conversation)
{
Conversation res;
if (!conversation.size())
return res;
QList<MessageField> cconversation = conversation[0].list();
if (!cconversation.size())
return res;
res.id = cconversation[0].string();
// Abstract
if (conversation.size() < 2)
return res;
auto abstract = conversation[1].list();
parseConversationAbstract(abstract, res);
// Events
if (conversation.size() < 3)
return res;
auto details = conversation[2].list();
for (auto event : details) {
Event e = Utils::parseEvent(event.list());
if (e.notificationLevel != 0 && e.notificationLevel != res.notifLevel) {
//qDebug() << "Setting notifLev to " << e.notificationLevel;
//This can be QUIET although the conversation is not
//res.notifLevel = (NotificationLevel)e.notificationLevel;
}
if (e.value.segments.size() > 0 || e.value.attachments.size()>0) //skip empty messages (voice calls)
res.events.append(e);
}
return res;
}
void Client::parseConversationState(MessageField conv)
{
//qDebug() << "CONV_STATE: ";// << conv;
Conversation c = parseConversation(conv.list());
//Now formalize what happened:
//New messages for existing convs?
if (!rosterModel->conversationExists(c.id)) {
//A new conv was created!
//TODO: test this case
rosterModel->addConversationAbstract(c);
}
int newValidEvts = 0, validIdx=0;
bool diffConv = false;
int i=0;
foreach (Event e, c.events) {
//Eventually update the notificationLevel for this conversation
rosterModel->updateNotificationLevel(e.conversationId, e.notificationLevel);
//skip empty messages (voice calls)
if ((e.value.segments.size() > 0 || e.value.attachments.size()>0)) {
qDebug() << "I have a valid msg here";
bool added = conversationModel->addEventToConversation(c.id, e);
//I should put on top the conversation anyway
rosterModel->putOnTop(c.id);
//If I'm not the active client these messages have already been read probably
if (added && !notifier->isAnotherClientActive())
rosterModel->addUnreadMsg(c.id);
newValidEvts++;
if (i+1 < c.events.size() && c.events[i].conversationId != c.events[i+1].conversationId)
diffConv = true;
validIdx = i;
}
i++;
}
if (newValidEvts > 1) {
//More than 1 new message -> show a generic notification
if (diffConv) {
qDebug() << "Notif many, diffConv";
emit showNotification(QString(QString::number(newValidEvts) + " new messages"), "Restored channel", "You have new msgs", "Many conversations", newValidEvts, c.id);
}
else {
qDebug() << "Notif many, NO diffConv";
emit showNotification(QString(QString::number(newValidEvts) + " new messages"), "Restored channel", "You have new msgs", rosterModel->getConversationName(c.events[0].conversationId), newValidEvts, c.id);
}
}
else if (newValidEvts == 1 && c.events[validIdx].notificationLevel != QUIET) {
//Only 1 new message -> show a specific notification
emit showNotification(c.events[validIdx].value.segments[validIdx].value, c.events[validIdx].sender.chat_id, c.events[validIdx].value.segments[validIdx].value, c.events[validIdx].sender.chat_id, 1, c.id);
}
else {
qDebug() << "Not notifying";
qDebug() << "New msgs: " << newValidEvts;
}
}
QList<Conversation> Client::parseConversations(const QString& conv)
{
QList<Conversation> res;
QStringRef dsData = Utils::extractArrayForDS(conv, 20);
int idx = 0;
auto parsedData = MessageField::parseListRef(dsData, idx);
//Skip 3 fields
if (parsedData.size() >= 4) {
auto conversations = parsedData[3].list();
for (auto conversation : conversations) {
res.append(parseConversation(conversation.list()));
}
}
/*
//Debug info
foreach (Conversation c, res) {
qDebug() << "###### CONV #######";
qDebug() << c.id;
qDebug() << c.participants.size();
foreach (Participant p, c.participants) {
qDebug() << p.user.chat_id;
}
}
*/
return res;
}
User Client::parseMySelf(const QString& sreply) {
//SELF INFO
QStringRef dsData = Utils::extractArrayForDS(sreply, 36);
//qDebug() << dsData.toString();
int idx = 0;
auto parsedData = MessageField::parseListRef(dsData, idx);
User res;
//And then parse a common user
if (parsedData.size() >= 3) {
//auto entity = parsedData[2].list();
//res = parseEntity(entity);
res.chat_id = res.gaia_id = parsedData[1].string();
res.email = parsedData[2].string();
/*
qDebug() << res.chat_id;
qDebug() << res.display_name;
qDebug() << res.first_name;
qDebug() << res.photo;
*/
}
return res;
}
void Client::networkReply()
{
timeoutTimer.stop();
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
processCookies(reply);
if (reply->error() == QNetworkReply::NoError) {
if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()==302) {
qDebug() << "Redir";
QVariant possibleRedirectUrl =
reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
followRedirection(possibleRedirectUrl.toUrl());
reply->deleteLater();
}
else {
emit initializing();
initCompleted = true;
QString sreply = reply->readAll();
qDebug() << sreply;
//API KEY
QStringRef dsData = Utils::extractArrayForDS(sreply, 7);
int idx = 0;
auto ds7Parsed = MessageField::parseListRef(dsData, idx);
api_key = ds7Parsed[2].string();
//qDebug() << "API KEY: " << api_key;
if (api_key.contains("AF_initDataKeys") || api_key.size() < 10 || api_key.size() > 50) {
//qDebug() << sreply;
//qDebug() << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
//exit(-1);
qDebug() << "Auth expired!";
//Not smart for sure, but it should be safe
deleteCookies();
}
// Channel info & header_id
dsData = Utils::extractArrayForDS(sreply, 4);
idx = 0;
auto ds4Parsed = MessageField::parseListRef(dsData, idx);
channel_path = ds4Parsed[1].string();
channel_ec_param = ds4Parsed[4].string().remove("\\n").remove('\\');
channel_prop_param = ds4Parsed[5].string();
header_id = ds4Parsed[7].string();
// Header info
dsData = Utils::extractArrayForDS(sreply, 2);
idx = 0;
auto ds2Parsed = MessageField::parseListRef(dsData, idx);
header_date = ds2Parsed[4].string();
header_version = ds2Parsed[6].string();
/*
qDebug() << "HID " << header_id;
qDebug() << "HDA " << header_date;
qDebug() << "HVE " << header_version;
*/
emit initContacts();
myself = parseMySelf(sreply);
if (!myself.email.contains("@"))
{
qDebug() << "Error parsing myself info";
qDebug() << sreply;
//initChat();
//return;
}
rosterModel->setMySelf(myself);
//Parse users!
/* Temporarily disables; moved to ds:22 with some modifications
users = parseUsers(sreply);
foreach (User u, users)
contactsModel->addContact(u);
*/
emit initConvs();
//Parse conversations
QList<Conversation> convs = parseConversations(sreply);
foreach (Conversation c, convs)
{
c.unread = 0;
foreach (Event e, c.events)
if (e.timestamp > c.lastReadTimestamp)
c.unread++;
rosterModel->addConversationAbstract(c);
conversationModel->addConversation(c);
}
reply->deleteLater();
emit(initFinished());
}
}
else {
//failure
//qDebug() << "Failure" << reply->errorString();
emit authFailed("Login Failed " + reply->errorString());
reply->deleteLater();
}
}
QByteArray Client::getAuthHeader()
{
QByteArray res = "SAPISIDHASH ";
qint64 time_msec = QDateTime::currentMSecsSinceEpoch();//1000;
QString auth_string = QString::number(time_msec);
auth_string += " ";
foreach (QNetworkCookie cookie, sessionCookies) {
if (cookie.name()=="SAPISID")
auth_string += cookie.value();
}
auth_string += " ";
auth_string += ORIGIN_URL;
res += QString::number(time_msec);
res += "_";
res += QCryptographicHash::hash(auth_string.toUtf8(), QCryptographicHash::Sha1).toHex();
return res;
}
void Client::uploadPerformedReply()
{
timeoutTimer.stop();
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
processCookies(reply);
QString sreply = reply->readAll();
qDebug() << "Response " << sreply;
if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()==200) {
qDebug() << "Upload in progress";
QJsonDocument doc = QJsonDocument::fromJson(sreply.toUtf8());
QJsonObject obj = doc.object().take("sessionStatus").toObject();
QString state = obj.take("state").toString();
qDebug() << state;
if (state=="FINALIZED") {
//Completed, send the message!
//Retrieve the id of the image
QString imgId = obj.take("additionalInfo").toObject()
.take("uploader_service.GoogleRupioAdditionalInfo").toObject()
.take("completionInfo").toObject()
.take("customerSpecificInfo").toObject()
.take("photoid").toString();
qDebug() << "Sending msg with img" << imgId;
sendImageMessage(outgoingImages.at(0).conversationId, imgId, "");
outgoingImages.clear();
}
}
else {
qDebug() << "Problem uploading";
}
reply->deleteLater();
}
void Client::performImageUpload(QString url)
{
if (pvtUpdateNeeded)
getPVTToken();
OutgoingImage oi = outgoingImages.at(0);
QFile inFile(oi.filename);
if (!inFile.open(QIODevice::ReadOnly)) {
qDebug() << "File not found";
return ;
}
QNetworkRequest req(url);
req.setRawHeader("User-Agent", user_agent.toLocal8Bit().data());
req.setRawHeader("X-GUploader-Client-Info", "mechanism=scotty xhr resumable; clientVersion=82480166");
req.setRawHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");
req.setRawHeader("Content-Length", QByteArray::number(inFile.size()));
QList<QNetworkCookie> reqCookies;
foreach (QNetworkCookie cookie, sessionCookies) {
reqCookies.append(cookie);
}
req.setHeader(QNetworkRequest::CookieHeader, QVariant::fromValue(reqCookies));
QNetworkReply * reply = nam->post(req, inFile.readAll());
imageBeingUploaded = reply;
QObject::connect(reply, SIGNAL(finished()), this, SLOT(uploadPerformedReply()));
QObject::connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(slotError(QNetworkReply::NetworkError)));
//QObject::connect(this, SIGNAL(cancelAllActiveRequests()), reply, SLOT(abort()));
if (!timeoutTimer.isActive())
timeoutTimer.start(TIMEOUT_MS_UPLOAD);
}
void Client::uploadImageReply()
{
timeoutTimer.stop();
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
processCookies(reply);
QString sreply = reply->readAll();
qDebug() << "Response " << sreply;
if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()==200) {
qDebug() << "Upload ready";
QVariant v = reply->header(QNetworkRequest::LocationHeader);
QString uploadUrl = qvariant_cast<QString>(v);
qDebug() << uploadUrl;
reply->close();
reply->deleteLater();
delete reply;
performImageUpload(uploadUrl);
}
else {
qDebug() << "Problem uploading " << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
}
reply->deleteLater();
}
void Client::sendMessageReply() {
timeoutTimer.stop();
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
pendingRequests.remove(reply);
qDebug() << reply;
processCookies(reply);
QString response = reply->readAll();
qDebug() << "Response " << response;
if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()==200) {
qDebug() << "Message sent correctly";
int start = 0;
auto parsedRep = MessageField::parseListRef(response.leftRef(-1), start);
qDebug() << parsedRep.size();
auto respHeader = parsedRep[1].list();
qDebug() << respHeader.size();
if (respHeader.size()) {
qDebug() << respHeader[0].number();
if (respHeader[0].number().toInt() != 1) {
qDebug() << "Something went wrong!";
Event evt;
conversationModel->addErrorMessage(reply, "convId", evt);
emit messageNotSent();
reply->deleteLater();
return;
}
}
auto event = parsedRep[6].list();
qDebug() << event.size();
Event evt = Utils::parseEvent(event);
conversationModel->addSentMessage(reply, "convId", evt);
emit messageSent();
}
else {
qDebug() << "Problem sending msg";
Event evt;
conversationModel->addErrorMessage(reply, "convId", evt);
emit messageNotSent();
}
reply->deleteLater();
}
QNetworkReply *Client::sendRequest(QString function, QString json) {
if (pvtUpdateNeeded)
getPVTToken();
QString url = endpoint + function;
url += "?key=";
url += api_key;
//add params
QNetworkRequest req(url);
req.setRawHeader("authorization", getAuthHeader());
req.setRawHeader("x-origin", QVariant::fromValue(ORIGIN_URL).toByteArray());
req.setRawHeader("x-goog-authuser", "0");
req.setRawHeader("content-type", "application/json+protobuf");
QByteArray postDataSize = QByteArray::number(json.size());
//req.setRawHeader("Content-Length", postDataSize);
QList<QNetworkCookie> reqCookies;
foreach (QNetworkCookie cookie, sessionCookies) {
//qDebug() << "Sending cookie " << cookie.name() << " - " << cookie.value();
reqCookies.append(cookie);
}
req.setHeader(QNetworkRequest::CookieHeader, QVariant::fromValue(reqCookies));
QByteArray postData;
postData.append(json);
if (!timeoutTimer.isActive())
timeoutTimer.start(TIMEOUT_MS);
qDebug() << "Sending request " << url;
return nam->post(req, postData);
//qDebug() << "req sent " << postData;
}
QString Client::getRequestHeader()
{
QString res = "[[1, 1, \"";
res += header_version;
res += "\", \"";
res += header_date;
res += "\"], [\"";
res += clid;
res += "\", \"";
res += header_id;
res += "\"], null, \"en\"]";
return res;
}
void Client::sendImageMessage(QString convId, QString imgId, QString segments)
{
if (!connectedToInternet)
return;
rosterModel->putOnTop(convId);
QString seg = "[[0, \"";
seg += segments;
seg += "\", [0, 0, 0, 0], [null]]]";
//qDebug() << "Sending cm " << segments;
if (segments=="") seg = "[]";
//Not really random, but works well
qint64 time = QDateTime::currentMSecsSinceEpoch();
uint random = (uint)(time % qint64(4294967295u));
QString body = "[";
body += getRequestHeader();
//qDebug() << "gotH " << body;
body += ", null, null, null, [], [";
body += seg;
body += ", []], [[\"";
body += imgId;
body += "\", false]], [[\"";
body += convId;
body += "\"], ";
body += QString::number(random);
body += ", 2, [1]], null, null, null, []]";
//Eventually body += ", 2, [1]], ["chatId",null,null,null,null,[]], null, null, []]";
qDebug() << "gotH " << body;
QNetworkReply *reply = sendRequest("conversations/sendchatmessage",body);
pendingRequests.insert(reply);
QObject::connect(reply, SIGNAL(finished()), this, SLOT(sendMessageReply()));
QObject::connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(slotError(QNetworkReply::NetworkError)));
}
void Client::sendChatMessage(QString segments, QString conversationId) {
if (!connectedToInternet)
return;
//originalText is needed to push the outgoing event in the correct form
qDebug() << segments;
QString originalText = segments;
rosterModel->putOnTop(conversationId);
QString seg = "[[0, \"";
//Correct quotes
seg += segments.replace('"', "\\\"");
seg += "\", [0, 0, 0, 0], [null]]]";
//qDebug() << "Sending cm " << segments;
//Not really random, but works well
qint64 time = QDateTime::currentMSecsSinceEpoch();
uint random = (uint)(time % qint64(4294967295u));
QString body = "[";
body += getRequestHeader();
//qDebug() << "gotH " << body;
body += ", null, null, null, [], [";
body += seg;
body += ", []], null, [[\"";
body += conversationId;
body += "\"], ";
body += QString::number(random);
body += ", 2], null, null, null, []]";
qDebug() << "gotH " << body;
Event outgoingEvt;
outgoingEvt.sender.chat_id = myself.chat_id;
outgoingEvt.sender.gaia_id = myself.gaia_id;
outgoingEvt.conversationId = conversationId;
outgoingEvt.value.valid = true;
EventValueSegment evs;
evs.type = 0;
evs.value = originalText;
outgoingEvt.value.segments.append(evs);
QNetworkReply *reply = sendRequest("conversations/sendchatmessage",body);
conversationModel->addOutgoingMessage(reply, conversationId, outgoingEvt);
pendingRequests.insert(reply);
QObject::connect(reply, SIGNAL(finished()), this, SLOT(sendMessageReply()));
QObject::connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(slotError(QNetworkReply::NetworkError)));
}
void Client::sendImage(QString segments, QString conversationId, QString filename)
{
if (pvtUpdateNeeded)
getPVTToken();
QFile inFile(filename);
if (!inFile.open(QIODevice::ReadOnly)) {
qDebug() << "File not found";
return ;
}
OutgoingImage oi;
oi.conversationId = conversationId;
oi.filename = filename;
outgoingImages.append(oi);
//First upload image to gdocs
QJsonObject emptyObj;
QJsonArray jarr;
QJsonObject j1, jj1;
j1["name"] = QJsonValue(QString("file"));
j1["filename"] = QJsonValue(QString(filename.right(filename.size()-filename.lastIndexOf("/")-1)));
j1["put"] = emptyObj;
j1["size"] = QJsonValue(inFile.size());
jj1["external"] = j1;
QJsonObject j2, jj2;
j2["name"] = QJsonValue(QString("album_mode"));
j2["content"] = QJsonValue(QString("temporary"));
j2["contentType"] = QJsonValue(QString("text/plain"));
jj2["inlined"] = j2;
QJsonObject j3, jj3;
j3["name"] = QJsonValue(QString("title"));
j3["content"] = QJsonValue(QString(filename.right(filename.size()-filename.lastIndexOf("/")-1)));
j3["contentType"] = QJsonValue(QString("text/plain"));
jj3["inlined"] = j3;
qint64 time = QDateTime::currentMSecsSinceEpoch();
QJsonObject j4, jj4;
j4["name"] = QJsonValue(QString("addtime"));
j4["content"] = QJsonValue(QString::number(time));
j4["contentType"] = QJsonValue(QString("text/plain"));
jj4["inlined"] = j4;
QJsonObject j5, jj5;
j5["name"] = QJsonValue(QString("batchid"));
j5["content"] = QJsonValue(QString::number(time));
j5["contentType"] = QJsonValue(QString("text/plain"));
jj5["inlined"] = j5;
QJsonObject j6, jj6;
j6["name"] = QJsonValue(QString("album_name"));
j6["content"] = QJsonValue(QString("hangish"));
j6["contentType"] = QJsonValue(QString("text/plain"));
jj6["inlined"] = j6;
QJsonObject j7, jj7;
j7["name"] = QJsonValue(QString("album_abs_position"));
j7["content"] = QJsonValue(QString("0"));
j7["contentType"] = QJsonValue(QString("text/plain"));
jj7["inlined"] = j7;
QJsonObject j8, jj8;
j8["name"] = QJsonValue(QString("client"));
j8["content"] = QJsonValue(QString("hangouts"));
j8["contentType"] = QJsonValue(QString("text/plain"));
jj8["inlined"] = j8;
jarr.append(jj1);
jarr.append(jj2);
jarr.append(jj3);
jarr.append(jj4);
jarr.append(jj5);
jarr.append(jj6);
jarr.append(jj7);
jarr.append(jj8);
QJsonObject jjson;
jjson["fields"] = jarr;
QJsonObject json;
json["createSessionRequest"] = jjson;
json["protocolVersion"] = QJsonValue(QString("0.8"));
//url += "?alt=json&key=";
//url += api_key;
qDebug() << "Sending request for up image";
QJsonDocument doc(json);
qDebug() << doc.toJson();
QNetworkRequest req(QUrl("https://docs.google.com/upload/photos/resumable?authuser=0"));
//req.setRawHeader("authorization", getAuthHeader());
req.setRawHeader("User-Agent", user_agent.toLocal8Bit().data());
req.setRawHeader("X-GUploader-Client-Info", "mechanism=scotty xhr resumable; clientVersion=82480166");
req.setRawHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");
req.setRawHeader("Content-Length", QByteArray::number(doc.toJson().size()));
QList<QNetworkCookie> reqCookies;
foreach (QNetworkCookie cookie, sessionCookies) {
reqCookies.append(cookie);
}
req.setHeader(QNetworkRequest::CookieHeader, QVariant::fromValue(reqCookies));
QNetworkReply * reply = nam->post(req, doc.toJson());
QObject::connect(reply, SIGNAL(finished()), this, SLOT(uploadImageReply()));
QObject::connect(reply,SIGNAL(error(QNetworkReply::NetworkError)),this,SLOT(slotError(QNetworkReply::NetworkError)));
//QObject::connect(this, SIGNAL(cancelAllActiveRequests()), reply, SLOT(abort()));
if (!timeoutTimer.isActive())
timeoutTimer.start(TIMEOUT_MS);
}
void Client::syncAllNewEventsReply()
{
timeoutTimer.stop();
//The content of this reply contains CLIENT_CONVERSATION_STATE, such as lost messages
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
processCookies(reply);