forked from viewfinderco/viewfinder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNetworkManager.cc
3932 lines (3467 loc) · 126 KB
/
NetworkManager.cc
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
// Copyright 2012 Viewfinder. All rights reserved.
// Author: Peter Mattis.
#import <algorithm>
#import <memory>
#import <unordered_set>
#import <errno.h>
#import <fcntl.h>
#import <unistd.h>
#import "ActivityTable.h"
#import "Analytics.h"
#import "AppState.h"
#import "AsyncState.h"
#import "ContactManager.h"
#import "DB.h"
#import "Defines.h"
#import "DigestUtils.h"
#import "FileUtils.h"
#import "IdentityManager.h"
#import "Logging.h"
#import "NetworkManager.h"
#import "NetworkQueue.h"
#import "NotificationManager.h"
#import "PathUtils.h"
#import "Server.pb.h"
#import "ServerId.h"
#import "ServerUtils.h"
#import "StringUtils.h"
#import "SubscriptionManager.h"
#import "Timer.h"
const WallTime NetworkManager::kMinBackoffDelay = 1;
namespace {
// Disable NETLOG statements in APPSTORE builds as they contain Personally
// Identifiable Information.
#ifdef APPSTORE
#define NETLOG if (0) VLOG
#else
#define NETLOG VLOG
#endif
const string kAccessCodeKey = DBFormat::metadata_key("access_code/");
const string kPushDeviceTokenKey = DBFormat::metadata_key("apn_device_token");
const string kQueryFollowedDoneKey =
DBFormat::metadata_key("query_followed_done_key");
const string kQueryFollowedLastKey =
DBFormat::metadata_key("query_followed_last_key");
const WallTime kMaxBackoffDelay = 60 * 10;
const WallTime kLogUploadInterval = 10;
const int kQueryContactsLimit = 1000;
const int kQueryUsersLimit = 500;
const int kQueryObjectsLimit = 200;
const int kQueryEpisodesLimit = 100;
const int kQueryFollowedLimit = 100;
const int kQueryNotificationsLimit = 100;
const int kQueryViewpointsLimit = 100;
const WallTime kPingPeriodDefault = 12 * 60 * 60;
const WallTime kPingPeriodFast = 10 * 60;
const WallTime kProspectiveUserCreationDelay = 2;
// For maximum compatibility with uncooperative proxies (e.g. hotel wifi), this should be under a minute.
const WallTime kQueryNotificationsMaxLongPoll = 58;
const WallTime kQueryNotificationsMaxRetryAfter = 3600;
#if defined(APPSTORE) && !defined(ENTERPRISE)
const int kUploadLogOptOutGracePeriod = 600;
#else
const int kUploadLogOptOutGracePeriod = 0;
#endif
const string kJsonContentType = "application/json";
const string kJpegContentType = "image/jpeg";
const string kOctetStreamContentType = "application/octet-stream";
const string kDefaultNetworkErrorMessage =
"The network is unavailable. Please try again later.";
const string kDefaultLoginErrorMessage =
"Your Viewfinder login failed. Please try again later.";
const string kDefaultVerifyErrorMessage =
"Couldn't verify your identity…";
const string kDefaultChangePasswordErrorMessage =
"Couldn't change your password…";
const string kDownloadBenchmarkURLPrefix = "https://public-ro-viewfinder-co.s3.amazonaws.com/";
const string kDownloadBenchmarkFiles[] = {
"10KB.test",
"50KB.test",
"100KB.test",
"200KB.test",
"500KB.test",
"1MB.test",
"2MB.test",
};
string FormatUrl(AppState* state, const string& path) {
return Format("%s://%s:%s%s",
state->server_protocol(),
state->server_host(),
state->server_port(),
path);
}
string FormatRequest(const JsonDict& dict, int min_required_version = 0,
bool synchronous = false) {
JsonDict headers_dict = JsonDict("version", AppState::protocol_version());
if (min_required_version > 0) {
headers_dict.insert("min_required_version", min_required_version);
}
if (synchronous) {
headers_dict.insert("synchronous", synchronous);
}
JsonDict req_dict = dict;
req_dict.insert("headers", headers_dict);
return req_dict.Format();
}
string FormatRequest(const JsonDict& dict, const OpHeaders& op_headers,
AppState* state, int min_required_version = 0) {
JsonDict headers_dict = JsonDict("version", AppState::protocol_version());
if (min_required_version > 0) {
headers_dict.insert("min_required_version", min_required_version);
}
if (op_headers.has_op_id()) {
headers_dict.insert(
"op_id", EncodeOperationId(state->device_id(), op_headers.op_id()));
}
if (op_headers.has_op_timestamp()) {
headers_dict.insert("op_timestamp", op_headers.op_timestamp());
}
JsonDict req_dict = dict;
req_dict.insert("headers", headers_dict);
return req_dict.Format();
}
JsonDict FormatDeviceDict(AppState* state) {
JsonDict device({
{ "os", state->device_os() },
{ "platform", state->device_model() },
{ "version", AppVersion() }
});
if (!state->device_name().empty()) {
device.insert("name", state->device_name());
}
if (state->device_id() != 0) {
device.insert("device_id", state->device_id());
}
string push_token;
if (state->db()->Get(kPushDeviceTokenKey, &push_token)) {
device.insert("push_token", push_token);
}
device.insert("device_uuid", state->device_uuid());
device.insert("language", state->locale_language());
device.insert("country", state->locale_country());
if (!state->test_udid().empty()) {
device.insert("test_udid", state->test_udid());
}
return device;
}
// Create an activity dictionary suitable for passing to the server with ops
// that must create an activity.
const JsonDict FormatActivityDict(const ActivityHandle& ah) {
return JsonDict({
{ "activity_id", ah->activity_id().server_id() },
{ "timestamp", ah->timestamp() }
});
}
// Creates a new activity server id using the specified local id and timestamp.
const JsonDict FormatActivityDict(
AppState* state, int64_t local_id, WallTime timestamp) {
const string activity_id = EncodeActivityId(
state->device_id(), local_id, timestamp);
return JsonDict({
{ "activity_id", activity_id },
{ "timestamp", timestamp }
});
}
JsonDict FormatAccountSettingsDict(AppState* state) {
// TODO: add 'email_alerts' field when settable on the client.
JsonDict account_settings;
vector<string> storage_options;
// We use the raw "cloud storage" toggle since we care about user-specified
// settings, not additional logic.
if (state->cloud_storage()) {
storage_options.push_back("use_cloud");
}
if (state->store_originals()) {
storage_options.push_back("store_originals");
}
// We need to specify 'storage_options' even if all are off,
// otherwise the backend would never know.
account_settings.insert("storage_options",
JsonArray(storage_options.size(), [&](int i) {
return storage_options[i];
}));
return account_settings;
}
const char* PhotoURLSuffix(NetworkQueue::PhotoType type) {
switch (type) {
case NetworkQueue::THUMBNAIL:
return ".t";
case NetworkQueue::MEDIUM:
return ".m";
case NetworkQueue::FULL:
return ".f";
case NetworkQueue::ORIGINAL:
return ".o";
}
return "";
}
const char* PhotoTypeName(NetworkQueue::PhotoType type) {
switch (type) {
case NetworkQueue::THUMBNAIL:
return "thumbnail";
case NetworkQueue::MEDIUM:
return "medium";
case NetworkQueue::FULL:
return "full";
case NetworkQueue::ORIGINAL:
return "original";
}
return "";
}
} // namespace
class AddFollowersRequest : public NetworkRequest {
public:
AddFollowersRequest(NetworkManager* net, const NetworkQueue::UploadActivity* u)
: NetworkRequest(net, NETWORK_QUEUE_SYNC),
upload_(u),
needs_invalidate_(false) {
}
// Start is called with NetworkManager::mu_ held.
void Start() {
const NetworkQueue::UploadActivity* u = upload_;
JsonDict d({
{ "viewpoint_id", u->viewpoint->id().server_id() },
{ "activity", FormatActivityDict(u->activity) },
{ "contacts", JsonArray(u->contacts.size(), [&](int i) {
JsonDict d;
const ContactMetadata& c = u->contacts[i];
if (c.has_primary_identity()) {
d.insert("identity", c.primary_identity());
}
if (c.has_user_id()) {
d.insert("user_id", c.user_id());
} else {
// If we upload followers without user ids (prospective users), they will have user ids
// assigned by this operation. The DayTable does not display followers that do not yet
// have user ids, so we need to fetch notifications once this is done.
needs_invalidate_ = true;
}
if (c.has_name()) {
d.insert("name", c.name());
}
return d;
}) }
});
const string json = FormatRequest(d, u->headers, state());
NETLOG("network: add followers: %s", json);
SendPost(FormatUrl(state(), "/service/add_followers"),
json, kJsonContentType);
}
protected:
// The various Handle*() methods are called on the NetworkManager
// thread.
void HandleError(const string& e) {
LOG("network: add_followers error: %s", e);
state()->analytics()->NetworkAddFollowers(0, timer_.Get());
}
bool HandleDone(int status_code) {
state()->analytics()->NetworkAddFollowers(status_code, timer_.Get());
if (status_code != 200) {
LOG("network: add_followers error: %d status: %s\n%s",
status_code, url(), data_);
if ((status_code / 100) == 5) {
// Retry on 5xx errors.
return false;
}
}
if (upload_ == state()->net_queue()->queued_upload_activity()) {
if (status_code == 200) {
const NetworkQueue::UploadActivity* u = upload_;
LOG("network: added %d contact%s: %.03f",
u->contacts.size(), Pluralize(u->contacts.size()),
timer_.Milliseconds());
}
state()->net_queue()->CommitQueuedUploadActivity(status_code != 200);
if (needs_invalidate_) {
AppState* const s = state();
dispatch_after_main(kProspectiveUserCreationDelay, [s] {
DBHandle updates = s->NewDBTransaction();
s->notification_manager()->Invalidate(updates);
updates->Commit();
});
}
}
return true;
}
private:
const NetworkQueue::UploadActivity* const upload_;
bool needs_invalidate_;
};
class AuthRequest : public NetworkRequest {
public:
AuthRequest(NetworkManager* net)
: NetworkRequest(net, NETWORK_QUEUE_REFRESH) {
}
protected:
void SendAuth(const string& url, const JsonDict& auth,
bool include_device_info = true) {
JsonDict augmented_auth = auth;
if (include_device_info) {
augmented_auth.insert("device", FormatDeviceDict(state()));
}
const string json = FormatRequest(augmented_auth);
NETLOG("network: auth: %s\n%s", url, json);
SendPost(url, json, kJsonContentType);
}
void SendAuth(const string& url) {
SendAuth(url, JsonDict());
}
void HandleError(const string& e) {
LOG("network: auth error: %s", e);
}
bool HandleDone(int status_code) {
AuthResponse a;
if (!ParseAuthResponse(&a, data_)) {
LOG("network: unable to parse auth response: %s", data_);
return false;
}
return HandleDone(a);
}
bool HandleDone(const AuthResponse& a) {
// LOG("network: auth: %s", a);
const int64_t user_id = a.has_user_id() ? a.user_id() : state()->user_id();
const int64_t device_id = a.has_device_id() ? a.device_id() : state()->device_id();
state()->SetUserAndDeviceId(user_id, device_id);
if (state()->is_registered()) {
net_->AuthDone();
}
return true;
}
};
class AuthViewfinderRequest : public AuthRequest {
public:
AuthViewfinderRequest(
NetworkManager* net, const string& endpoint, const string& identity,
const string& password, const string& first, const string& last,
const string& name, bool error_if_linked,
const NetworkManager::AuthCallback& done)
: AuthRequest(net),
endpoint_(endpoint),
identity_(identity),
password_(password),
first_(first),
last_(last),
name_(name),
error_if_linked_(error_if_linked),
done_(done) {
}
// Start is called with NetworkManager::mu_ held.
void Start() {
JsonDict auth;
bool include_device_info = true;
if (endpoint_ == AppState::kMergeTokenEndpoint) {
LOG("network: %s viewfinder, identity=\"%s\"", endpoint_, identity_);
auth.insert("identity", identity_);
auth.insert("error_if_linked", error_if_linked_);
include_device_info = false;
} else {
JsonDict auth_info("identity", identity_);
if (endpoint_ == AppState::kRegisterEndpoint) {
LOG("network: %s viewfinder, identity=\"%s\", first=\"%s\", "
"last=\"%s\", name=\"%s\"",
endpoint_, identity_, first_, last_, name_);
if (!name_.empty()) {
auth_info.insert("name", name_);
}
if (!first_.empty()) {
auth_info.insert("given_name", first_);
}
if (!last_.empty()) {
auth_info.insert("family_name", last_);
}
} else {
LOG("network: %s viewfinder, identity=\"%s\"", endpoint_, identity_);
}
if (endpoint_ == AppState::kRegisterEndpoint ||
endpoint_ == AppState::kLoginEndpoint) {
if (!password_.empty()) {
auth_info.insert("password", password_);
}
}
auth.insert("auth_info", auth_info);
}
SendAuth(FormatUrl(state(), Format("/%s/viewfinder", endpoint_)),
auth, include_device_info);
}
protected:
// The various Handle*() methods are called on the NetworkManager
// thread.
void HandleError(const string& e) {
state()->analytics()->NetworkAuthViewfinder(0, timer_.Get());
AuthRequest::HandleError(e);
done_(-1, ErrorResponse::UNKNOWN, e);
}
bool HandleDone(int status_code) {
state()->analytics()->NetworkAuthViewfinder(status_code, timer_.Get());
if (status_code != 200) {
LOG("network: auth viewfinder error: %d status: %s\n%s",
status_code, url(), data_);
// Note, unlike most other network requests, we do not retry on 5xx
// errors and instead pass back the error to the caller so an error can
// be displayed to the user.
ErrorResponse err;
if (!ParseErrorResponse(&err, data_)) {
done_(status_code, ErrorResponse::UNKNOWN, kDefaultLoginErrorMessage);
} else {
done_(status_code, err.error().error_id(), err.error().text());
}
return true;
}
AuthResponse a;
if (!ParseAuthResponse(&a, data_)) {
LOG("network: unable to parse auth response: %s", data_);
// We just fumble ahead if we're unable to parse the AuthResponse.
}
LOG("network: authenticated viewfinder identity");
// TODO(peter): Passing AuthResponse::token_digits() in the error_id field
// is a hack. Yo! Clean this shit up.
done_(status_code, a.token_digits(), "");
return AuthRequest::HandleDone(a);
}
private:
const string endpoint_;
const string identity_;
const string password_;
const string first_;
const string last_;
const string name_;
const bool error_if_linked_;
const NetworkManager::AuthCallback done_;
};
class VerifyViewfinderRequest : public AuthRequest {
public:
VerifyViewfinderRequest(NetworkManager* net, const string& identity,
const string& access_token, bool manual_entry,
const NetworkManager::AuthCallback& done)
: AuthRequest(net),
identity_(identity),
access_token_(access_token),
manual_entry_(manual_entry),
done_(done) {
}
// Start is called with NetworkManager::mu_ held.
void Start() {
LOG("network: verify viewfinder, identity=\"%s\", access_token=\"%s\"",
identity_, access_token_);
JsonDict auth({
{ "identity", identity_ },
{ "access_token", access_token_ } });
const string json = FormatRequest(auth, 0, true);
const string url = FormatUrl(
state(), Format("/%s/viewfinder", AppState::kVerifyEndpoint));
NETLOG("network: verify_id: %s\n%s", url, json);
SendPost(url, json, kJsonContentType);
}
protected:
// The various Handle*() methods are called on the NetworkManager
// thread.
void HandleError(const string& e) {
state()->analytics()->NetworkVerifyViewfinder(0, timer_.Get(), manual_entry_);
AuthRequest::HandleError(e);
done_(-1, ErrorResponse::UNKNOWN, e);
}
bool HandleDone(int status_code) {
state()->analytics()->NetworkVerifyViewfinder(status_code, timer_.Get(), manual_entry_);
if (status_code != 200) {
LOG("network: verify viewfinder error: %d status: %s\n%s",
status_code, url(), data_);
// Note, unlike most other network requests, we do not retry on 5xx
// errors and instead pass back the error to the caller so an error can
// be displayed to the user.
ErrorResponse err;
if (!ParseErrorResponse(&err, data_)) {
done_(status_code, ErrorResponse::UNKNOWN, kDefaultVerifyErrorMessage);
} else {
done_(status_code, err.error().error_id(), err.error().text());
}
return true;
}
AuthResponse a;
if (!ParseAuthResponse(&a, data_)) {
LOG("network: unable to parse auth response: %s", data_);
return false;
}
done_(status_code, ErrorResponse::OK, a.cookie());
if (state()->registration_version() < AppState::REGISTRATION_EMAIL) {
state()->set_registration_version(AppState::current_registration_version());
}
return AuthRequest::HandleDone(a);
}
private:
const string identity_;
const string access_token_;
const bool manual_entry_;
const NetworkManager::AuthCallback done_;
};
class BenchmarkDownloadRequest : public NetworkRequest {
public:
BenchmarkDownloadRequest(NetworkManager* net, const string& url)
: NetworkRequest(net, NETWORK_QUEUE_SYNC),
url_(url),
total_bytes_(0) {
}
~BenchmarkDownloadRequest() {
}
// Start is called with NetworkManager::mu_ held.
void Start() {
NETLOG("network: starting benchmark download: up=%d wifi=%d: %s",
net_->network_up(), net_->network_wifi(), url_);
SendGet(url_);
}
protected:
// The various Handle*() methods are called on the NetworkManager
// thread.
void HandleData(const Slice& d) {
total_bytes_ += d.size();
LOG("network: benchmark received %d bytes, %d bytes total: %s, %.03f ms",
d.size(), total_bytes_, url_, timer_.Milliseconds());
}
void HandleError(const string& e) {
LOG("network: benchmark download error: %s", e);
state()->analytics()->NetworkBenchmarkDownload(0, net_->network_up(), net_->network_wifi(),
url_, -1, timer_.Get());
}
bool HandleDone(int status_code) {
state()->analytics()->NetworkBenchmarkDownload(status_code, net_->network_up(), net_->network_wifi(),
url_, total_bytes_, timer_.Get());
LOG("network: benchmark download finished with %d: %d bytes: %s: %.03f ms",
status_code, total_bytes_, url_, timer_.Milliseconds());
return true;
}
private:
string url_;
int64_t total_bytes_;
};
class DownloadPhotoRequest : public NetworkRequest {
public:
DownloadPhotoRequest(NetworkManager* net, const NetworkQueue::DownloadPhoto* d)
: NetworkRequest(net, NETWORK_QUEUE_SYNC),
download_(d),
path_(d->path),
url_(d->url),
delete_file_(true),
fd_(FileCreate(path_)) {
MD5_Init(&md5_ctx_);
CHECK_GE(fd_, 0) << "file descriptor is invalid";
}
~DownloadPhotoRequest() {
if (fd_ != -1) {
close(fd_);
fd_ = -1;
}
if (delete_file_) {
FileRemove(path_);
}
}
// Start is called with NetworkManager::mu_ held.
void Start() {
const NetworkQueue::DownloadPhoto* d = download_;
if (url_.empty()) {
url_ = FormatUrl(
state(), Format("/episodes/%s/photos/%s%s",
d->episode->id().server_id(),
d->photo->id().server_id(),
PhotoURLSuffix(d->type)));
}
NETLOG("network: downloading photo: %s: %s", d->photo->id(), url_);
SendGet(url_);
}
protected:
// The various Handle*() methods are called on the NetworkManager
// thread.
void HandleData(const Slice& d) {
MD5_Update(&md5_ctx_, d.data(), d.size());
// TODO(pmattis): Gracefully handle out-of-space errors.
const char* p = d.data();
int n = d.size();
while (n > 0) {
ssize_t res = write(fd_, p, n);
if (res < 0) {
LOG("write failed: %s: %d (%s)", path_, errno, strerror(errno));
break;
}
p += res;
n -= res;
}
}
void HandleError(const string& e) {
LOG("network: photo download error: %s", e);
state()->analytics()->NetworkDownloadPhoto(0, -1, PhotoTypeName(download_->type), timer_.Get());
}
bool HandleDone(int status_code) {
state()->analytics()->NetworkDownloadPhoto(status_code, status_code == 200 ? FileSize(path_) : -1,
PhotoTypeName(download_->type), timer_.Get());
if (fd_ != -1) {
close(fd_);
fd_ = -1;
}
if (download_ == state()->net_queue()->queued_download_photo()) {
const NetworkQueue::DownloadPhoto* d = download_;
if (status_code == 403 && url_ == d->url) {
// Our download was forbidden and we were talking directly to s3. Tell
// the photo manager to retry.
LOG("network: photo download error: %d status (retrying): %s: %s",
status_code, d->photo->id(), url_);
state()->net_queue()->CommitQueuedDownloadPhoto(string(), true);
} else if (status_code != 200) {
// The photo doesn't exist. Mark it with an error.
LOG("network: photo download error: %d status (not-retrying): %s: %s",
status_code, d->photo->id(), url_);
state()->net_queue()->CommitQueuedDownloadPhoto(string(), false);
} else {
const string md5 = GetMD5();
LOG("network: downloaded photo: %s: %d bytes: %s: %.03f ms",
d->photo->id(), FileSize(path_), url_, timer_.Milliseconds());
state()->net_queue()->CommitQueuedDownloadPhoto(md5, false);
delete_file_ = false;
}
}
return true;
}
string GetMD5() {
uint8_t digest[MD5_DIGEST_LENGTH];
MD5_Final(&md5_ctx_, digest);
return BinaryToHex(Slice((const char*)digest, ARRAYSIZE(digest)));
}
private:
const NetworkQueue::DownloadPhoto* const download_;
MD5_CTX md5_ctx_;
const string path_;
string url_;
bool delete_file_;
int fd_;
};
class FetchContactsRequest : public NetworkRequest {
public:
FetchContactsRequest(NetworkManager* net,
const NetworkManager::FetchContactsCallback& done)
: NetworkRequest(net, NETWORK_QUEUE_REFRESH),
done_(done) {
}
protected:
void SendFetch(const string& url) {
JsonDict auth("device", FormatDeviceDict(state()));
const string json = FormatRequest(auth);
NETLOG("network: fetch contacts: %s\n%s", url, json);
SendPost(url, json, kJsonContentType);
}
void HandleError(const string& e) {
LOG("network: fetch contacts error: %s", e);
done_("");
}
bool HandleDone(int status_code) {
AuthResponse a;
if (!ParseAuthResponse(&a, data_)) {
LOG("network: unable to parse auth response: %s", data_);
return false;
}
LOG("network: initiated fetch contacts: %s", a.headers().op_id());
done_(a.headers().op_id());
return true;
}
private:
const NetworkManager::FetchContactsCallback done_;
};
class FetchFacebookContactsRequest : public FetchContactsRequest {
public:
FetchFacebookContactsRequest(NetworkManager* net,
const NetworkManager::FetchContactsCallback& done,
const string& access_token)
: FetchContactsRequest(net, done),
access_token_(access_token) {
}
// Start is called with NetworkManager::mu_ held.
void Start() {
LOG("network: fetch facebook contacts");
SendFetch(FormatUrl(state(),
Format("/%s/facebook?access_token=%s",
state()->kLinkEndpoint,
access_token_)));
}
protected:
// The various Handle*() methods are called on the NetworkManager
// thread.
void HandleError(const string& e) {
state()->analytics()->NetworkFetchFacebookContacts(0, timer_.Get());
FetchContactsRequest::HandleError(e);
}
bool HandleDone(int status_code) {
state()->analytics()->NetworkFetchFacebookContacts(status_code, timer_.Get());
return FetchContactsRequest::HandleDone(status_code);
}
private:
const string access_token_;
};
class FetchGoogleContactsRequest : public FetchContactsRequest {
public:
FetchGoogleContactsRequest(NetworkManager* net,
const NetworkManager::FetchContactsCallback& done,
const string& refresh_token)
: FetchContactsRequest(net, done),
refresh_token_(refresh_token) {
}
// Start is called with NetworkManager::mu_ held.
void Start() {
LOG("network: fetch google contacts");
SendFetch(FormatUrl(state(),
Format("/%s/google?refresh_token=%s",
state()->kLinkEndpoint,
refresh_token_)));
}
protected:
// The various Handle*() methods are called on the NetworkManager
// thread.
void HandleError(const string& e) {
state()->analytics()->NetworkFetchGoogleContacts(0, timer_.Get());
FetchContactsRequest::HandleError(e);
}
bool HandleDone(int status_code) {
state()->analytics()->NetworkFetchGoogleContacts(status_code, timer_.Get());
return FetchContactsRequest::HandleDone(status_code);
}
private:
const string refresh_token_;
};
class MergeAccountsRequest : public NetworkRequest {
public:
MergeAccountsRequest(NetworkManager* net,
const string& identity,
const string& access_token,
const string& completion_db_key,
const NetworkManager::AuthCallback& done)
: NetworkRequest(net, NETWORK_QUEUE_REFRESH),
identity_(identity),
access_token_(access_token),
completion_db_key_(completion_db_key),
op_id_(state()->NewLocalOperationId()),
done_(done) {
}
// Start is called with NetworkManager::mu_ held.
void Start() {
OpHeaders headers;
headers.set_op_id(op_id_);
headers.set_op_timestamp(WallTime_Now());
JsonDict dict({
{ "source_identity",
JsonDict({
{ "identity", identity_ },
{ "access_token", access_token_ } }) },
{ "activity", FormatActivityDict(
state(), headers.op_id(), headers.op_timestamp()) } });
const string json = FormatRequest(dict, headers, state());
NETLOG("network: merge accounts: %s", json);
SendPost(FormatUrl(state(), "/service/merge_accounts"),
json, kJsonContentType);
}
protected:
// The various Handle*() methods are called on the NetworkManager
// thread.
void HandleError(const string& e) {
LOG("network: merge accounts error: %s", e);
state()->analytics()->NetworkMergeAccounts(0, timer_.Get());
if (done_) {
done_(-1, ErrorResponse::UNKNOWN, e);
}
}
bool HandleDone(int status_code) {
state()->analytics()->NetworkMergeAccounts(status_code, timer_.Get());
if (status_code != 200) {
LOG("network: merge account error: %d status: %s\n%s",
status_code, url(), data_);
if ((status_code / 100) == 5) {
// Retry on 5xx errors.
return false;
}
ErrorResponse err;
if (!ParseErrorResponse(&err, data_)) {
done_(status_code, ErrorResponse::UNKNOWN, kDefaultChangePasswordErrorMessage);
} else {
done_(status_code, err.error().error_id(), err.error().text());
}
return true;
}
DBHandle updates = state()->NewDBTransaction();
const string encoded_op_id = EncodeOperationId(state()->device_id(), op_id_);
state()->contact_manager()->ProcessMergeAccounts(
encoded_op_id, completion_db_key_, updates);
updates->Commit();
LOG("network: merge accounts: %s", encoded_op_id);
done_(status_code, ErrorResponse::OK, "");
return true;
}
private:
const string identity_;
const string access_token_;
const string completion_db_key_;
const int64_t op_id_;
const NetworkManager::AuthCallback done_;
};
class PingRequest : public NetworkRequest {
public:
PingRequest(NetworkManager* net)
: NetworkRequest(net, NETWORK_QUEUE_PING) {
}
// Start is called with NetworkManager::mu_ held.
void Start() {
JsonDict ping("device", FormatDeviceDict(state()));
const string json = FormatRequest(ping);
NETLOG("network: ping:\n%s", json);
SendPost(FormatUrl(state(), "/ping"), json, kJsonContentType);
}
protected:
// The various Handle*() methods are called on the NetworkManager
// thread.
void HandleError(const string& e) {
LOG("network: ping error: %s", e);
state()->analytics()->NetworkPing(0, timer_.Get());
}
bool HandleDone(int status_code) {
state()->analytics()->NetworkPing(status_code, timer_.Get());
if (status_code != 200) {
LOG("network: ping error: %d status: %s\n%s",
status_code, url(), data_);
if ((status_code / 100) == 5) {
// Retry on 5xx errors.
return false;
}
return true;
}
PingResponse p;
if (!ParsePingResponse(&p, data_)) {
// Don't retry, we could be a really old version that can't handle the response.
// Reset the system message on bad responses. This ensures that we won't remain stuck
// in the DISABLE_NETWORK state.
LOG("network: unable to parse ping reponse");
state()->clear_system_message();
net_->SetNetworkDisallowed(false);
return true;
}
if (!p.has_message()) {
state()->clear_system_message();
VLOG("Got empty ping response");
net_->SetNetworkDisallowed(false);
return true;
}
// Set disallowed variable from here, no need to register a callback.
net_->SetNetworkDisallowed(p.message().severity() == SystemMessage::DISABLE_NETWORK);
VLOG("Got ping response: %s", p);
state()->set_system_message(p.message());
return true;
}
};
class PostCommentRequest : public NetworkRequest {
public:
PostCommentRequest(NetworkManager* net, const NetworkQueue::UploadActivity* u)
: NetworkRequest(net, NETWORK_QUEUE_SYNC),
upload_(u) {
}
// Start is called with NetworkManager::mu_ held.
void Start() {
const NetworkQueue::UploadActivity* u = upload_;
JsonDict d({
{ "viewpoint_id", u->viewpoint->id().server_id() },
{ "comment_id", u->comment->comment_id().server_id() },
{ "activity", FormatActivityDict(u->activity) } });
if (!u->comment->asset_id().empty()) {
d.insert("asset_id", u->comment->asset_id());
}
if (u->comment->has_timestamp()) {
d.insert("timestamp", u->comment->timestamp());
}
if (!u->comment->message().empty()) {
d.insert("message", u->comment->message());
}
const string json = FormatRequest(d, u->headers, state());
NETLOG("network: post comment %s", u->activity->activity_id());
SendPost(FormatUrl(state(), "/service/post_comment"),
json, kJsonContentType);
}
protected:
// The various Handle*() methods are called on the NetworkManager
// thread.