forked from viewfinderco/viewfinder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContactManager.cc
2307 lines (2064 loc) · 77.7 KB
/
ContactManager.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 <unordered_map>
#import <unordered_set>
#import <re2/re2.h>
#import "Analytics.h"
#import "AppState.h"
#import "AsyncState.h"
#import "ContactManager.h"
#import "ContactMetadata.pb.h"
#import "DB.h"
#import "DigestUtils.h"
#import "FullTextIndex.h"
#import "IdentityManager.h"
#import "InvalidateMetadata.pb.h"
#import "LazyStaticPtr.h"
#import "LocaleUtils.h"
#import "Logging.h"
#import "NetworkManager.h"
#import "NotificationManager.h"
#import "PeopleRank.h"
#import "PhoneUtils.h"
#import "STLUtils.h"
#import "StringUtils.h"
#import "Timer.h"
const string ContactManager::kContactSourceGmail = "gm";
const string ContactManager::kContactSourceFacebook = "fb";
const string ContactManager::kContactSourceIOSAddressBook = "ip";
const string ContactManager::kContactSourceManual = "m";
const string ContactManager::kContactIndexName = "con";
const string ContactManager::kUserIndexName = "usr";
const string ContactManager::kUserTokenPrefix = "_user";
namespace {
const string kContactSelectionKey = DBFormat::metadata_key("contact_selection");
// The contacts_format key is no longer used but may exist in old databases.
// Leaving it commented out here as a reminder to not re-use the name.
// const string kFormatKey = DBFormat::metadata_key("contacts_format");
const string kMergeAccountsCompletionKey =
DBFormat::metadata_key("merge_accounts_completion_key");
const string kMergeAccountsOpIdKey =
DBFormat::metadata_key("merge_accounts_op_id_key");
const string kQueuedUpdateSelfKey = DBFormat::metadata_key("queued_update_self");
const string kNewUserCallbackTriggerKey = "ContactManagerNewUsers";
const int kUploadContactsLimit = 50;
// Parse everything between unicode separator characters. This
// will include all punctuation, both internal to the string and
// leading and trailing.
LazyStaticPtr<RE2, const char*> kWordUnicodeRE = { "([^\\pZ]+)" };
LazyStaticPtr<RE2, const char*> kWhitespaceUnicodeRE = { "([\\pZ]+)" };
LazyStaticPtr<RE2, const char*> kIdRE = { "u/([[:digit:]]+)" };
LazyStaticPtr<RE2, const char*> kQueueRE = { "cq/([[:digit:]]+)" };
LazyStaticPtr<RE2, const char*> kUpdateQueueRE = { "cuq/([[:digit:]]+)" };
LazyStaticPtr<RE2, const char*> kContactUploadQueueRE = { "ccuq/(.*)" };
LazyStaticPtr<RE2, const char*> kContactRemoveQueueRE = { "ccrq/(.*)" };
LazyStaticPtr<RE2, const char*> kNewUserRE = { "nu/([[:digit:]]+)" };
// Format used to build filter regexp (case-insensitve match) on the filter
// string or on the filter string alone or with a leading separator character.
const char* kFilterREFormat = "(?i)(?:^|[\\s]|[[:punct:]])(%s)";
// kEmailFullRE is used to decide when to start a ResolveContact
// operation. We require at least one dot in the domain portion, and
// at least two characters after the last dot.
LazyStaticPtr<RE2, const char*> kEmailFullRE = { "^[^ @]+@[^ @]+\\.[^. @]{2,}" };
LazyStaticPtr<RE2, const char*> kUserTokenRE = { "_user([0-9]+)_" };
const DBRegisterKeyIntrospect kContactKeyIntrospect(
DBFormat::contact_key(""), NULL, [](Slice value) {
return DBIntrospect::FormatProto<ContactMetadata>(value);
});
const DBRegisterKeyIntrospect kDeprecatedContactIdKeyIntrospect(
DBFormat::deprecated_contact_id_key(), NULL, [](Slice value) {
return DBIntrospect::FormatProto<ContactMetadata>(value);
});
const DBRegisterKeyIntrospect kContactSelectionKeyIntrospect(
kContactSelectionKey, NULL, [](Slice value) {
return DBIntrospect::FormatProto<ContactSelection>(value);
});
const DBRegisterKeyIntrospect kContactSourceKeyIntrospect(
DBFormat::contact_source_key(""), NULL, [](Slice value) {
return DBIntrospect::FormatProto<ContactSourceMetadata>(value);
});
const DBRegisterKeyIntrospect kUserIdKeyIntrospect(
DBFormat::user_id_key(), NULL, [](Slice value) {
return DBIntrospect::FormatProto<ContactMetadata>(value);
});
const DBRegisterKeyIntrospect kUserIdentityKeyIntrospect(
DBFormat::user_identity_key(""), NULL, [](Slice value) {
return ToString(value);
});
// Identities with higher priority should be given preference when choosing
// the primary identity.
int PrimaryIdentityPriority(const Slice& identity) {
if (IdentityManager::IsEmailIdentity(identity)) {
return 3;
} else if (IdentityManager::IsPhoneIdentity(identity)) {
return 2;
} else {
// Facebook, etc.
return 1;
}
}
struct ContactMatchRankLess {
AppState* state;
WallTime now;
ContactMatchRankLess(AppState* s)
: state(s),
now(state->WallTime_Now()) {
}
bool operator()(const ContactManager::ContactMatch* a, const ContactManager::ContactMatch* b) const {
// TODO(pmattis): This sorts identities with viewfinder user ids to the
// top. Not clear if this is the right thing to do long term.
if (a->metadata.has_user_id() != b->metadata.has_user_id()) {
return !a->metadata.has_user_id() < !b->metadata.has_user_id();
} else {
// This sorts identities which are registered before ones that
// are still prospective.
if (a->metadata.label_registered() != b->metadata.label_registered()) {
return !a->metadata.label_registered() < !b->metadata.label_registered();
}
}
// Contacts with non-viewfinder identities came from the user's own contact import,
// so rank them above contacts that are only known because of transitive viewfinder
// connections.
if (IdentityManager::IsViewfinderIdentity(a->metadata.primary_identity()) !=
IdentityManager::IsViewfinderIdentity(b->metadata.primary_identity())) {
return IdentityManager::IsViewfinderIdentity(a->metadata.primary_identity()) <
IdentityManager::IsViewfinderIdentity(b->metadata.primary_identity());
}
// Ranks are considered in order of email, phone & facebook.
const int a_priority = PrimaryIdentityPriority(a->metadata.primary_identity());
const int b_priority = PrimaryIdentityPriority(b->metadata.primary_identity());
if (a_priority != b_priority) {
return a_priority > b_priority;
}
// Use people rank weight (sort descending) if user ids are available.
if (a->metadata.has_user_id() && b->metadata.has_user_id()) {
const double a_weight = state->people_rank()->UserRank(a->metadata.user_id(), now);
const double b_weight = state->people_rank()->UserRank(b->metadata.user_id(), now);
if (a_weight != b_weight) {
return a_weight > b_weight;
}
}
if (a->metadata.has_rank() != b->metadata.has_rank()) {
return !a->metadata.has_rank() < !b->metadata.has_rank();
}
// If identity type is the same, use rank for direct comparison.
if (a->metadata.rank() != b->metadata.rank()) {
return a->metadata.rank() < b->metadata.rank();
}
if (a->metadata.name() != b->metadata.name()) {
return a->metadata.name() < b->metadata.name();
}
return a->metadata.primary_identity() < b->metadata.primary_identity();
}
};
struct ContactMatchNameLess {
bool operator()(ContactManager::ContactMatch* a, ContactManager::ContactMatch* b) const {
// This method inlines parts of ContactNameLessThan so it can cache the sort keys.
if (!a->sort_key_initialized) {
a->sort_key_initialized = true;
a->sort_key = ContactManager::ContactNameForSort(a->metadata);
}
if (!b->sort_key_initialized) {
b->sort_key_initialized = true;
b->sort_key = ContactManager::ContactNameForSort(b->metadata);
}
if (a->sort_key != b->sort_key) {
return ContactManager::NameLessThan(a->sort_key, b->sort_key);
}
return a->metadata.primary_identity() < b->metadata.primary_identity();
}
};
// Returns true if the given user can be shown as a user (rather than a contact) in search results.
bool IsViewfinderUser(const ContactMetadata& m) {
if (!m.has_user_id() ||
m.has_merged_with() ||
m.label_terminated() ||
m.label_system()) {
// Non-users, merged accounts, terminated accounts, and system users are never shown.
return false;
}
if (m.label_friend()) {
// For friends, we receive terminate and merge notifications so the above data should always be
// accurate. Unregistered friends (i.e. prospective users in one of your conversations) will be
// shown as invited users.
return true;
} else {
// For non-friends, our information comes because we have their linked identity as a contact.
// If the user is unlinked from that identity, we will never find out whether the user is
// terminated, so we must not show it.
if (m.identities_size() == 0) {
return false;
}
// Non-friends should not be shown as users unless they are fully registered.
return m.label_registered();
}
}
void HashString(SHA256_CTX* ctx, const Slice& s) {
SHA256_Update(ctx, s.data(), s.size());
const char delimiter = 0;
SHA256_Update(ctx, &delimiter, 1);
}
string ComputeContactId(const ContactMetadata& metadata) {
SHA256_CTX ctx;
SHA256_Init(&ctx);
HashString(&ctx, metadata.primary_identity());
for (int i = 0; i < metadata.identities_size(); i++) {
if (metadata.identities(i).identity().empty()) {
continue;
}
HashString(&ctx, metadata.identities(i).identity());
HashString(&ctx, metadata.identities(i).description());
}
HashString(&ctx, "\0"); // Mark the end of the list
HashString(&ctx, metadata.name());
HashString(&ctx, metadata.first_name());
HashString(&ctx, metadata.last_name());
HashString(&ctx, metadata.nickname());
int64_t rank = metadata.rank();
SHA256_Update(&ctx, &rank, sizeof(rank));
uint8_t digest[SHA256_DIGEST_LENGTH];
SHA256_Final(&ctx, digest);
// 256 bits is far more than we need for this case (and its size
// affects the fulltext index size, so truncate to 128 bits (22
// bytes after b64 without padding).
const string contact_id = Format("%s:%s", metadata.contact_source(),
Base64HexEncode(Slice((const char*)digest, 16), false));
if (metadata.has_contact_id()) {
CHECK_EQ(contact_id, metadata.contact_id());
}
return contact_id;
}
// Adds the given identity to the contact, updating primary_identity if necessary.
void AddIdentity(ContactMetadata* metadata, const string& identity) {
metadata->add_identities()->set_identity(identity);
if (metadata->primary_identity().empty() ||
(PrimaryIdentityPriority(identity) > PrimaryIdentityPriority(metadata->primary_identity()))) {
metadata->set_primary_identity(identity);
}
}
// Adds the given identity to the contact (which must be a user) and updates the identity-to-user index.
void AddIdentityAndSave(ContactMetadata* metadata, const string& identity, const DBHandle& updates) {
AddIdentity(metadata, identity);
updates->Put(DBFormat::user_identity_key(identity), ToString(metadata->user_id()));
}
// Copies any identities from source to target if they are not already present.
// Does not update indexes so should only be used for transient objects.
void MergeIdentities(const ContactMetadata& source, ContactMetadata* target) {
StringSet identities;
for (int i = 0; i < target->identities_size(); i++) {
identities.insert(target->identities(i).identity());
}
if (!source.primary_identity().empty() &&
!ContainsKey(identities, source.primary_identity())) {
AddIdentity(target, source.primary_identity());
identities.insert(source.primary_identity());
}
for (int i = 0; i < source.identities_size(); i++) {
if (!ContainsKey(identities, source.identities(i).identity())) {
AddIdentity(target, source.identities(i).identity());
}
}
}
// Returns true if the two objects have at least one identity in common.
bool IdentitiesOverlap(const ContactMetadata& a, const ContactMetadata& b) {
StringSet identities;
if (!a.primary_identity().empty()) {
identities.insert(a.primary_identity());
}
for (int i = 0; i < a.identities_size(); i++) {
identities.insert(a.identities(i).identity());
}
if (!b.primary_identity().empty()) {
if (ContainsKey(identities, b.primary_identity())) {
return true;
}
}
for (int i = 0; i < b.identities_size(); i++) {
if (ContainsKey(identities, b.identities(i).identity())) {
return true;
}
}
return false;
}
bool IsUploadableContactSource(const Slice& contact_source) {
return (contact_source == ContactManager::kContactSourceIOSAddressBook ||
contact_source == ContactManager::kContactSourceManual);
}
bool DecodeNewUserKey(Slice key, int64_t* user_id) {
return RE2::FullMatch(key, *kNewUserRE, user_id);
}
} // namespace
bool DecodeUserIdKey(Slice key, int64_t* user_id) {
return RE2::FullMatch(key, *kIdRE, user_id);
}
bool IsValidEmailAddress(const Slice& address, string* error) {
vector<string> parts = SplitAllowEmpty(address.ToString(), "@");
if (parts.size() <= 1) {
*error = "You seem to be missing an \"@\" symbol.";
return false;
}
if (parts.size() > 2) {
*error = Format("I found %d \"@\" symbols. That's %d too many.",
parts.size() - 1, parts.size() - 2);
return false;
}
if (RE2::FullMatch(address, ".*[\\pZ\\pC].*")) {
*error = "There's a space in your email address - please remove it.";
return false;
}
const Slice user(parts[0]);
if (user.empty()) {
*error = "This email is missing a username (you know, the bit before the \"@\").";
return false;
}
const Slice domain(parts[1]);
if (domain.empty()) {
*error = "This email is missing a domain (you know, the bit after the \"@\").";
return false;
}
parts = SplitAllowEmpty(parts[1], ".");
if (parts.size() <= 1) {
*error = "This email is missing a domain (maybe it's .com? .edu?).";
return false;
}
for (int i = 0; i < parts.size(); ++i) {
if (parts[i].empty()) {
if (i == parts.size() - 1) {
*error = "This email is missing a domain (maybe it's .com? .edu?).";
} else {
*error = "I'm not sure what to do with \"..\".";
}
return false;
}
}
if (address.size() > 1000) {
// Officially the limit is 254 characters; allow some extra room for non-compliant servers, unicode, etc.
// http://stackoverflow.com/questions/386294/what-is-the-maximum-length-of-a-valid-email-address
*error = "That's too long to be an email address.";
return false;
}
return true;
}
ContactManager::ContactManager(AppState* state)
: state_(state),
count_(0),
viewfinder_count_(0),
queued_update_self_(false),
queued_update_friend_(0),
user_index_(new FullTextIndex(state_, kUserIndexName)),
contact_index_(new FullTextIndex(state_, kContactIndexName)) {
DBHandle updates = state_->NewDBTransaction();
for (DB::PrefixIterator iter(updates, DBFormat::contact_key(""));
iter.Valid();
iter.Next()) {
++count_;
}
// Count contacts with viewfinder user ids.
for (DB::PrefixIterator iter(updates, DBFormat::user_id_key());
iter.Valid();
iter.Next()) {
ContactMetadata m;
if (!m.ParseFromArray(iter.value().data(), iter.value().size())) {
LOG("contacts: unable to parse contact metadata: %s", iter.key());
continue;
}
if (m.user_id() != state_->user_id() && IsViewfinderUser(m)) {
++viewfinder_count_;
}
}
LOG("contacts: %d contact%s, %d VF",
count_, Pluralize(count_), viewfinder_count_);
queued_update_self_ = state_->db()->Get<bool>(kQueuedUpdateSelfKey, false);
QueueUpdateFriend(0);
// Re-initialize any merge accounts operation watch.
ProcessMergeAccounts(updates->Get<string>(kMergeAccountsOpIdKey),
updates->Get<string>(kMergeAccountsCompletionKey),
NULL);
state_->network_ready()->Add([this](int priority) {
MaybeQueueUploadContacts();
MaybeQueueRemoveContacts();
});
// Set up callbacks for handling notification mgr callbacks.
state_->notification_manager()->process_notifications()->Add(
[this](const QueryNotificationsResponse& p, const DBHandle& updates) {
ProcessQueryNotifications(p, updates);
});
state_->notification_manager()->nuclear_invalidations()->Add(
[this](const DBHandle& updates) {
InvalidateAll(updates);
});
// We do not want to send the settings to the server if the
// "settings changed" callback was triggered by a download.
state_->settings_changed()->Add(
[this](bool downloaded) {
if (!downloaded) {
QueueUpdateSelf();
}
});
}
ContactManager::~ContactManager() {
// Free cache entries.
Clear(&user_cache_);
Clear(&resolved_contact_cache_);
}
void ContactManager::ProcessMergeAccounts(
const string& op_id, const string& completion_db_key,
const DBHandle& updates) {
if (op_id.empty() || completion_db_key.empty()) {
return;
}
if (updates.get()) {
updates->Put(kMergeAccountsOpIdKey, op_id);
updates->Put(kMergeAccountsCompletionKey, completion_db_key);
// Force a query notification.
state_->notification_manager()->Invalidate(updates);
}
// We're abusing the fetch contacts infrastructure here, which handles
// watching for an op id in the query notifications stream.
pending_fetch_ops_[op_id].push_back([this, completion_db_key] {
LOG("merge accounts complete");
DBHandle updates = state_->NewDBTransaction();
updates->Delete(kMergeAccountsOpIdKey);
updates->Delete(kMergeAccountsCompletionKey);
updates->Delete(completion_db_key);
updates->Commit();
state_->async()->dispatch_main([this] {
state_->settings_changed()->Run(true);
});
});
}
void ContactManager::ProcessAddressBookImport(
const vector<ContactMetadata>& contacts,
const DBHandle& updates, FetchCallback done) {
CHECK(!dispatch_is_main_thread());
StringSet existing;
for (DB::PrefixIterator iter(updates, DBFormat::contact_key(""));
iter.Valid(); iter.Next()) {
ContactMetadata m;
if (!m.ParseFromArray(iter.value().data(), iter.value().size())) {
continue;
}
if (m.contact_source() != kContactSourceIOSAddressBook) {
continue;
}
DCHECK(!m.contact_id().empty());
existing.insert(m.contact_id());
}
const WallTime now = WallTime_Now();
for (int i = 0; i < contacts.size(); ++i) {
const string contact_id = SaveContact(contacts[i], true, now, updates);
existing.erase(contact_id);
}
for (StringSet::iterator it = existing.begin(); it != existing.end(); ++it) {
RemoveContact(*it, true, updates);
}
LOG("contacts: %d contact%s, %d VF, updated %d entr%s, deleted/replaced %d entr%s",
count_, Pluralize(count_), viewfinder_count_,
contacts.size(), Pluralize(contacts.size(), "y", "ies"),
existing.size(), Pluralize(existing.size(), "y", "ies"));
updates->AddCommitTrigger("ProcessAddressBookImport", [this, done] {
// The next time we reach the end of the upload-contacts queue, schedule our callback.
MutexLock lock(&fetch_ops_mu_);
pending_upload_ops_.push_back(done);
state_->async()->dispatch_main([this] {
state_->net_manager()->Dispatch();
});
});
}
void ContactManager::ProcessQueryContacts(
const QueryContactsResponse& r,
const ContactSelection& cs, const DBHandle& updates) {
// Validate the contact selection based on queried contacts.
Validate(cs, updates);
const WallTime now = WallTime_Now();
for (int i = 0; i < r.contacts_size(); ++i) {
const ContactMetadata& u = r.contacts(i);
if (u.label_contact_removed()) {
CHECK(u.has_server_contact_id());
RemoveServerContact(u.server_contact_id(), updates);
continue;
}
if (!u.has_primary_identity()) {
continue;
}
SaveContact(u, false, now, updates);
// If the server gave us any identities with no associated user id, this is our indication that
// that identity is no longer bound to any user, so unlink it if necessary.
// We do this in ProcessQueryContacts instead of SaveContact because the absence of a user id
// in other contexts does not imply that the identity is unbound.
for (int j = 0; j < u.identities_size(); ++j) {
if (!u.identities(j).has_user_id()) {
UnlinkIdentity(u.identities(j).identity(), updates);
}
}
}
LOG("contacts: %d contact%s, %d VF, updated %d entr%s",
count_, Pluralize(count_), viewfinder_count_,
r.contacts_size(), Pluralize(r.contacts_size(), "y", "ies"));
updates->AddCommitTrigger("SaveContacts", [this] {
MutexLock lock(&fetch_ops_mu_);
MaybeRunFetchCallbacksLocked();
});
}
void ContactManager::ProcessQueryNotifications(
const QueryNotificationsResponse& r, const DBHandle& updates) {
MutexLock lock(&fetch_ops_mu_);
for (int i = 0; i < r.notifications_size(); ++i) {
const QueryNotificationsResponse::Notification& n = r.notifications(i);
if (n.has_invalidate()) {
const InvalidateMetadata& invalidate = n.invalidate();
if (invalidate.has_contacts()) {
Invalidate(invalidate.contacts(), updates);
}
for (int j = 0; j < invalidate.users_size(); ++j) {
InvalidateUser(invalidate.users(j), updates);
}
}
if (n.has_op_id()) {
// The query notifications processing is performed on the network thread,
// the same thread that manipulates the fetch_op_ map in FetchContacts().
auto ops = pending_fetch_ops_[n.op_id()];
for (auto it = ops.begin(); it != ops.end(); ++it) {
VLOG("contacts: got notification that op %s is complete; awaiting contact fetch", n.op_id());
const FetchCallback& done = *it;
updates->AddCommitTrigger(
Format("FetchContacts:%s", n.op_id()), [this, done] {
MutexLock lock(&fetch_ops_mu_);
VLOG("contacts: moving callback from notification to contact queue");
completed_fetch_ops_.push_back(done);
MaybeRunFetchCallbacksLocked();
});
}
pending_fetch_ops_.erase(n.op_id());
}
}
}
void ContactManager::ProcessQueryUsers(
const QueryUsersResponse& r,
const vector<int64_t>& q, const DBHandle& updates) {
typedef std::unordered_set<int64_t> UserIdSet;
UserIdSet user_ids(q.begin(), q.end());
const WallTime now = WallTime_Now();
for (int i = 0; i < r.user_size(); ++i) {
ContactMetadata u = r.user(i).contact();
if (!u.has_user_id()) {
continue;
}
user_ids.erase(u.user_id());
// Update the metadata.
SaveUser(u, now, updates);
}
// Delete any user that was queried but not returned in the
// result. Presumably we don't have permission to retrieve their info and we
// want to avoid looping attempting retrieval that will never succeed.
for (UserIdSet::iterator iter(user_ids.begin());
iter != user_ids.end();
++iter) {
updates->Delete(DBFormat::user_queue_key(*iter));
}
LOG("contacts: %d contact%s, %d VF, updated %d entr%s (%d user%s not returned)",
count_, Pluralize(count_), viewfinder_count_,
r.user_size(), Pluralize(r.user_size(), "y", "ies"),
user_ids.size(), Pluralize(user_ids.size()));
updates->AddCommitTrigger("SaveUsers", [this] {
MutexLock lock(&fetch_ops_mu_);
MaybeRunFetchCallbacksLocked();
});
process_users_.Run(r, q, updates);
}
void ContactManager::ProcessResolveContact(
const string& identity, const ContactMetadata* metadata) {
{
MutexLock lock(&cache_mu_);
resolving_contacts_.erase(identity);
}
// The network manager runs these callbacks on its thread, but everything else wants to run
// on the main thread. Copy the arguments and dispatch to the main thread.
const ContactMetadata* metadata_copy = NULL;
if (metadata) {
LOG("contacts: resolved identity %s to user_id %d", identity, metadata->user_id());
MutexLock lock(&cache_mu_);
delete FindOrNull(resolved_contact_cache_, identity);
resolved_contact_cache_[identity] = new ContactMetadata(*metadata);
if (resolved_contact_cache_.size() % 100 == 0) {
LOG("contact: resolved contact cache at %d entries", resolved_contact_cache_.size());
}
// Copy the metadata for use in the callback
metadata_copy = new ContactMetadata(*metadata);
} else {
LOG("contacts: error resolving identity %s", identity);
}
dispatch_main([this, identity, metadata_copy] {
contact_resolved_.Run(identity, metadata_copy);
delete metadata_copy;
});
}
void ContactManager::SearchUsers(const FullTextQuery& query, int search_options,
UserMatchMap* user_matches, StringSet* all_terms) const {
if (query.empty() && (search_options & ALLOW_EMPTY_SEARCH)) {
// Special case handling of empty searches. We could just search for the
// term "", but that would match every name key and be unacceptably slow.
for (DB::PrefixIterator iter(state_->db(), DBFormat::user_id_key());
iter.Valid();
iter.Next()) {
const Slice value = iter.value();
ContactMetadata c;
if (c.ParseFromArray(value.data(), value.size()) &&
IsViewfinderUser(c)) {
ContactMatch& m = (*user_matches)[c.user_id()];
m.metadata.Swap(&c);
}
}
return;
}
for (ScopedPtr<FullTextResultIterator> iter(user_index_->Search(state_->db(), query));
iter->Valid();
iter->Next()) {
// The search process gave us ids; map those to ContactMetadata.
const int64_t user_id = FromString<int64_t>(iter->doc_id());
ContactMetadata m;
if (!LookupUser(user_id, &m)) {
LOG("contacts: unable to lookup contact metadata for id %s", user_id);
continue;
}
if (!IsViewfinderUser(m)) {
continue;
}
ContactMatch& c = (*user_matches)[m.user_id()];
c.metadata.MergeFrom(m);
iter->GetRawTerms(all_terms);
}
}
void ContactManager::SearchContacts(const FullTextQuery& query, int search_options,
ContactMatchMap* contact_matches, StringSet* all_terms) const {
if (search_options & VIEWFINDER_USERS_ONLY) {
return;
}
if (query.empty() && (search_options & ALLOW_EMPTY_SEARCH)) {
for (DB::PrefixIterator iter(state_->db(), DBFormat::contact_key(""));
iter.Valid();
iter.Next()) {
const Slice value = iter.value();
ContactMetadata c;
if (c.ParseFromArray(value.data(), value.size())) {
ContactMatch& m = (*contact_matches)[c.contact_id()];
m.metadata.Swap(&c);
}
}
return;
}
for (ScopedPtr<FullTextResultIterator> iter(contact_index_->Search(state_->db(), query));
iter->Valid();
iter->Next()) {
const string contact_id = iter->doc_id().as_string();
ContactMetadata m;
if (!state_->db()->GetProto(DBFormat::contact_key(contact_id), &m)) {
LOG("contacts: unable to lookup contact metadata for contact id %s", contact_id);
continue;
}
if ((search_options & SKIP_FACEBOOK_CONTACTS) &&
m.contact_source() == kContactSourceFacebook) {
continue;
}
ContactMatch& c = (*contact_matches)[m.contact_id()];
c.metadata.MergeFrom(m);
iter->GetRawTerms(all_terms);
}
}
// The MatchMaps are non-const because we need access to the non-const ContactMatches they contain;
// this method does not modify the maps themselves.
void ContactManager::MergeSearchResults(UserMatchMap* user_matches, ContactMatchMap* contact_matches,
vector<ContactMatch*>* match_vec) const {
// Build up a vector of the matches. Combine users and contacts with heuristic deduping.
StringSet registered_user_identities;
StringSet prospective_user_identities;
for (UserMatchMap::iterator iter(user_matches->begin());
iter != user_matches->end();
++iter) {
ContactMatch* m = &iter->second;
match_vec->push_back(m);
StringSet* identity_set = m->metadata.label_registered() ?
®istered_user_identities :
&prospective_user_identities;
if (!m->metadata.primary_identity().empty()) {
identity_set->insert(m->metadata.primary_identity());
}
for (int i = 0; i < m->metadata.identities_size(); i++) {
identity_set->insert(m->metadata.identities(i).identity());
}
}
typedef std::unordered_multimap<string, ContactMatch*> ContactByNameMap;
ContactByNameMap contact_by_name;
for (ContactMatchMap::iterator iter(contact_matches->begin());
iter != contact_matches->end();
++iter) {
ContactMatch* m = &iter->second;
// Hide any contacts for which we have a matching registered user.
// Remove any contact identities that match a prospective user.
if (!m->metadata.primary_identity().empty()) {
if (ContainsKey(registered_user_identities, m->metadata.primary_identity())) {
continue;
}
if (ContainsKey(prospective_user_identities, m->metadata.primary_identity())) {
m->metadata.clear_primary_identity();
}
}
bool seen_registered_identity = false;
for (int i = 0; i < m->metadata.identities_size(); i++) {
const string& identity = m->metadata.identities(i).identity();
if (ContainsKey(registered_user_identities, identity)) {
seen_registered_identity = true;
break;
}
if (ContainsKey(prospective_user_identities, identity)) {
ProtoRepeatedFieldRemoveElement(m->metadata.mutable_identities(), i--);
}
}
if (seen_registered_identity || m->metadata.identities_size() == 0) {
continue;
}
if (m->metadata.primary_identity().empty()) {
ChoosePrimaryIdentity(&m->metadata);
}
// Heuristically dedupe non-user contacts by name.
string name;
if (!m->metadata.name().empty()) {
name = m->metadata.name();
} else if (!m->metadata.primary_identity().empty()) {
name = IdentityManager::IdentityToName(m->metadata.primary_identity());
}
if (!name.empty()) {
pair<ContactByNameMap::iterator, ContactByNameMap::iterator> match_by_name(
contact_by_name.equal_range(name));
ContactMatch* overlap = NULL;
for (ContactByNameMap::iterator i = match_by_name.first; i != match_by_name.second; ++i) {
// Facebook contacts don't convey any useful information (they're only used for the name
// and the user is prompted to enter an email address if they select one), so hide
// them if there are any real contacts with the same name.
if (m->metadata.contact_source() == kContactSourceFacebook &&
i->second->metadata.contact_source() != kContactSourceFacebook) {
// We have a non-facebook contact, so skip this one.
continue;
} else if (m->metadata.contact_source() != kContactSourceFacebook &&
i->second->metadata.contact_source() == kContactSourceFacebook) {
// This contact can replace an earlier facebook one.
i->second->metadata.Swap(&m->metadata);
continue;
}
// Non-facebook contacts can be combined if they have at least one identity in common.
if (IdentitiesOverlap(m->metadata, i->second->metadata)) {
overlap = i->second;
break;
}
}
if (overlap != NULL) {
MergeIdentities(m->metadata, &overlap->metadata);
continue;
}
contact_by_name.insert(ContactByNameMap::value_type(name, m));
}
match_vec->push_back(m);
}
}
void ContactManager::BuildSearchResults(const vector<ContactMatch*>& match_vec, int search_options,
ContactVec* results) const {
// Output the matching contact metadata.
std::unordered_set<int64_t> user_ids;
for (int i = 0; i < match_vec.size(); ++i) {
ContactMetadata* m = &match_vec[i]->metadata;
if ((search_options & VIEWFINDER_USERS_ONLY) &&
!m->has_user_id()) {
continue;
}
if ((m->has_user_id() && !user_ids.insert(m->user_id()).second) ||
m->has_merged_with() ||
m->label_terminated()) {
continue;
}
if (m->has_user_id() && m->user_id() == state_->user_id()) {
// Skip any contact/user records for the current user. This happens at the end of the process
// rather than when this user record is first read so that any matching contact records can be
// merged into it rather than displayed separately.
continue;
}
results->push_back(ContactMetadata());
results->back().Swap(m);
}
}
void ContactManager::Search(
const string& query, ContactVec* contacts,
ScopedPtr<RE2>* filter_re, int search_options) const {
WallTimer timer;
int parse_options = 0;
if (search_options & ContactManager::PREFIX_MATCH) {
parse_options |= FullTextQuery::PREFIX_MATCH;
}
ScopedPtr<FullTextQuery> parsed_query(FullTextQuery::Parse(query, parse_options));
StringSet all_terms;
UserMatchMap user_matches;
SearchUsers(*parsed_query, search_options, &user_matches, &all_terms);
ContactMatchMap contact_matches;
SearchContacts(*parsed_query, search_options, &contact_matches, &all_terms);
vector<ContactMatch*> match_vec;
MergeSearchResults(&user_matches, &contact_matches, &match_vec);
// Sort the match vector.
DCHECK_NE((search_options & SORT_BY_RANK) != 0,
(search_options & SORT_BY_NAME) != 0);
if (search_options & SORT_BY_RANK) {
std::sort(match_vec.begin(), match_vec.end(), ContactMatchRankLess(state_));
} else {
std::sort(match_vec.begin(), match_vec.end(), ContactMatchNameLess());
}
BuildSearchResults(match_vec, search_options, contacts);
// Build up a regular expression that will match the start of any filter
// terms.
if (filter_re) {
FullTextQueryTermExtractor extractor(&all_terms);
extractor.VisitNode(*parsed_query);
filter_re->reset(FullTextIndex::BuildFilterRE(all_terms));
}
//LOG("contact: searched for [%s] (with options 0x%x). Found %d results in %f milliseconds",
// query, search_options, contacts->size(), timer.Milliseconds());
}
string ContactManager::FirstName(int64_t user_id, bool allow_nickname) {
ContactMetadata c;
if (user_id == 0 || !LookupUser(user_id, &c)) {
return "";
}
return FirstName(c, allow_nickname);
}
string ContactManager::FirstName(const ContactMetadata& c, bool allow_nickname) {
if (c.user_id() == state_->user_id()) {
return "You";
}
if (allow_nickname && !c.nickname().empty()) {
return c.nickname();
} else if (c.has_first_name()) {
return c.first_name();
} else if (c.has_name()) {
return c.name();
} else if (c.has_email()) {
return c.email();
} else {
string email;
if (ContactManager::EmailForContact(c, &email)) {
return email;
}
string phone;
if (ContactManager::PhoneForContact(c, &phone)) {
return phone;
}
}
return string();
}
string ContactManager::FullName(int64_t user_id, bool allow_nickname) {
ContactMetadata c;
if (user_id == 0 || !LookupUser(user_id, &c)) {
return "";
}
return FullName(c, allow_nickname);
}
string ContactManager::FullName(const ContactMetadata& c, bool allow_nickname) {
if (c.user_id() == state_->user_id()) {
return "You";
}
if (allow_nickname && !c.nickname().empty()) {
return c.nickname();
} else if (c.has_name()) {
return c.name();
} else if (c.has_first_name()) {
return c.first_name();
} else if (c.has_email()) {
return c.email();
} else {
string email;
if (ContactManager::EmailForContact(c, &email)) {
return email;
}
string phone;
if (ContactManager::PhoneForContact(c, &phone)) {
return phone;
}
}
return string();
}
vector<int64_t> ContactManager::ViewfinderContacts() {
vector<int64_t> ids;
for (DB::PrefixIterator iter(state_->db(), DBFormat::user_id_key());
iter.Valid();
iter.Next()) {
int64_t v;
if (DecodeUserIdKey(iter.key(), &v)) {
ids.push_back(v);
}
}
sort(ids.begin(), ids.end());
return ids;
}
void ContactManager::Reset() {
count_ = 0;