diff --git a/sharing/certificates/BUILD b/sharing/certificates/BUILD index acfdb882..28afdb51 100644 --- a/sharing/certificates/BUILD +++ b/sharing/certificates/BUILD @@ -42,29 +42,25 @@ cc_library( "//internal/base", "//internal/base:file_path", "//internal/crypto_cros", - "//internal/flags:nearby_flags", "//internal/platform:types", "//internal/platform/implementation:account_manager", "//proto/identity/v1:resources_cc_proto", "//proto/identity/v1:rpcs_cc_proto", "//sharing/common", - "//sharing/common:enum", - "//sharing/contacts", - "//sharing/flags/generated:generated_flags", "//sharing/internal/api:platform", "//sharing/internal/base", - "//sharing/internal/impl/common:nearby_identity_grpc_client", "//sharing/internal/public:logging", "//sharing/internal/public:types", "//sharing/local_device_data", "//sharing/proto:enums_cc_proto", "//sharing/proto:share_cc_proto", "//sharing/scheduling", + "//util/hash:highway_fingerprint", + "@com_google_absl//absl/algorithm", "@com_google_absl//absl/container:btree", "@com_google_absl//absl/container:flat_hash_map", "@com_google_absl//absl/container:flat_hash_set", "@com_google_absl//absl/functional:any_invocable", - "@com_google_absl//absl/functional:bind_front", "@com_google_absl//absl/memory", "@com_google_absl//absl/random", "@com_google_absl//absl/status:statusor", @@ -72,7 +68,6 @@ cc_library( "@com_google_absl//absl/synchronization", "@com_google_absl//absl/time", "@com_google_absl//absl/types:span", - "@com_google_protobuf//:protobuf_lite", ], ) @@ -96,13 +91,14 @@ cc_library( "//internal/base:file_path", "//internal/crypto_cros", "//sharing/common:enum", - "//sharing/contacts", "//sharing/internal/api:platform", "//sharing/internal/public:types", "//sharing/local_device_data", "//sharing/proto:enums_cc_proto", "//sharing/proto:share_cc_proto", + "@com_google_absl//absl/base:core_headers", "@com_google_absl//absl/strings", + "@com_google_absl//absl/synchronization", "@com_google_absl//absl/time", "@com_google_absl//absl/types:span", ], diff --git a/sharing/certificates/fake_nearby_share_certificate_manager.cc b/sharing/certificates/fake_nearby_share_certificate_manager.cc index 3b96689b..20f8a49a 100644 --- a/sharing/certificates/fake_nearby_share_certificate_manager.cc +++ b/sharing/certificates/fake_nearby_share_certificate_manager.cc @@ -28,7 +28,6 @@ #include "sharing/certificates/nearby_share_encrypted_metadata_key.h" #include "sharing/certificates/nearby_share_private_certificate.h" #include "sharing/certificates/test_util.h" -#include "sharing/contacts/nearby_share_contact_manager.h" #include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/public/context.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" @@ -50,7 +49,7 @@ std::unique_ptr FakeNearbyShareCertificateManager::Factory::CreateInstance( nearby::Context* context, NearbyShareLocalDeviceDataManager* local_device_data_manager, - NearbyShareContactManager* contact_manager, const FilePath& profile_path, + const FilePath& profile_path, nearby::sharing::api::SharingRpcClientFactory* client_factory) { auto instance = std::make_unique(); instances_.push_back(instance.get()); diff --git a/sharing/certificates/fake_nearby_share_certificate_manager.h b/sharing/certificates/fake_nearby_share_certificate_manager.h index af249f82..5ff4da64 100644 --- a/sharing/certificates/fake_nearby_share_certificate_manager.h +++ b/sharing/certificates/fake_nearby_share_certificate_manager.h @@ -29,7 +29,6 @@ #include "sharing/certificates/nearby_share_certificate_manager_impl.h" #include "sharing/certificates/nearby_share_encrypted_metadata_key.h" #include "sharing/certificates/nearby_share_private_certificate.h" -#include "sharing/contacts/nearby_share_contact_manager.h" #include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/public/context.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" @@ -61,7 +60,6 @@ class FakeNearbyShareCertificateManager : public NearbyShareCertificateManager { std::unique_ptr CreateInstance( Context* context, NearbyShareLocalDeviceDataManager* local_device_data_manager, - NearbyShareContactManager* contact_manager, const FilePath& profile_path, nearby::sharing::api::SharingRpcClientFactory* client_factory) override; diff --git a/sharing/certificates/fake_nearby_share_certificate_storage.cc b/sharing/certificates/fake_nearby_share_certificate_storage.cc index d803ff18..f06fecf3 100644 --- a/sharing/certificates/fake_nearby_share_certificate_storage.cc +++ b/sharing/certificates/fake_nearby_share_certificate_storage.cc @@ -21,6 +21,7 @@ #include #include "absl/strings/string_view.h" +#include "absl/synchronization/mutex.h" #include "absl/time/time.h" #include "absl/types/span.h" #include "sharing/certificates/nearby_share_certificate_storage.h" @@ -110,6 +111,7 @@ void FakeNearbyShareCertificateStorage::GetPublicCertificate( std::vector FakeNearbyShareCertificateStorage::GetPrivateCertificates() { + absl::MutexLock lock(mutex_); return private_certificates_; } @@ -120,6 +122,7 @@ FakeNearbyShareCertificateStorage::NextPublicCertificateExpirationTime() const { void FakeNearbyShareCertificateStorage::ReplacePrivateCertificates( absl::Span private_certificates) { + absl::MutexLock lock(mutex_); private_certificates_ = std::vector( private_certificates.begin(), private_certificates.end()); } diff --git a/sharing/certificates/fake_nearby_share_certificate_storage.h b/sharing/certificates/fake_nearby_share_certificate_storage.h index bcd5c478..a86a2d43 100644 --- a/sharing/certificates/fake_nearby_share_certificate_storage.h +++ b/sharing/certificates/fake_nearby_share_certificate_storage.h @@ -20,7 +20,9 @@ #include #include +#include "absl/base/thread_annotations.h" #include "absl/strings/string_view.h" +#include "absl/synchronization/mutex.h" #include "absl/time/time.h" #include "absl/types/span.h" #include "sharing/certificates/nearby_share_certificate_storage.h" @@ -151,9 +153,11 @@ class FakeNearbyShareCertificateStorage : public NearbyShareCertificateStorage { } private: + absl::Mutex mutex_; absl::Time next_public_certificate_expiration_time_ = absl::InfiniteFuture(); std::vector public_certificate_ids_; - std::vector private_certificates_; + std::vector private_certificates_ + ABSL_GUARDED_BY(mutex_); std::vector get_public_certificates_callbacks_; std::function)> diff --git a/sharing/certificates/nearby_share_certificate_manager_impl.cc b/sharing/certificates/nearby_share_certificate_manager_impl.cc index ede9ad73..0a62c434 100644 --- a/sharing/certificates/nearby_share_certificate_manager_impl.cc +++ b/sharing/certificates/nearby_share_certificate_manager_impl.cc @@ -28,13 +28,13 @@ #include #include +#include "absl/algorithm/algorithm.h" #include "absl/container/flat_hash_map.h" #include "absl/memory/memory.h" #include "absl/status/statusor.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" -#include "absl/strings/strip.h" #include "absl/synchronization/notification.h" #include "absl/time/time.h" #include "absl/types/span.h" @@ -51,7 +51,6 @@ #include "sharing/certificates/nearby_share_encrypted_metadata_key.h" #include "sharing/certificates/nearby_share_private_certificate.h" #include "sharing/common/nearby_share_prefs.h" -#include "sharing/contacts/nearby_share_contact_manager.h" #include "sharing/internal/api/bluetooth_adapter.h" #include "sharing/internal/api/preference_manager.h" #include "sharing/internal/api/public_certificate_database.h" @@ -65,15 +64,21 @@ #include "sharing/proto/encrypted_metadata.pb.h" #include "sharing/proto/enums.pb.h" #include "sharing/proto/rpc_resources.pb.h" +#include "sharing/proto/timestamp.pb.h" #include "sharing/scheduling/nearby_share_scheduler.h" #include "sharing/scheduling/nearby_share_scheduler_factory.h" +#include "util/hash/highway_fingerprint.h" namespace nearby { namespace sharing { namespace { +using ::google::nearby::identity::v1::PerVisibilitySharedCredentials; +using ::google::nearby::identity::v1::PublishDeviceRequest; +using ::google::nearby::identity::v1::PublishDeviceResponse; using ::google::nearby::identity::v1::QuerySharedCredentialsRequest; using ::google::nearby::identity::v1::QuerySharedCredentialsResponse; +using ::google::nearby::identity::v1::SharedCredential; using ::nearby::sharing::api::PreferenceManager; using ::nearby::sharing::api::PublicCertificateDatabase; using ::nearby::sharing::api::SharingPlatform; @@ -81,8 +86,6 @@ using ::nearby::sharing::proto::DeviceVisibility; using ::nearby::sharing::proto::EncryptedMetadata; using ::nearby::sharing::proto::PublicCertificate; -constexpr char kDeviceIdPrefix[] = "users/me/devices/"; - constexpr std::array kVisibilities = { DeviceVisibility::DEVICE_VISIBILITY_ALL_CONTACTS, DeviceVisibility::DEVICE_VISIBILITY_SELF_SHARE, @@ -185,14 +188,13 @@ std::unique_ptr NearbyShareCertificateManagerImpl::Factory::Create( Context* context, SharingPlatform& sharing_platform, NearbyShareLocalDeviceDataManager* local_device_data_manager, - NearbyShareContactManager* contact_manager, const FilePath& profile_path, + const FilePath& profile_path, nearby::sharing::api::SharingRpcClientFactory* client_factory) { DCHECK(context); if (test_factory_) { return test_factory_->CreateInstance(context, local_device_data_manager, - contact_manager, profile_path, - client_factory); + profile_path, client_factory); } FilePath database_path = profile_path; @@ -201,7 +203,7 @@ NearbyShareCertificateManagerImpl::Factory::Create( context, sharing_platform.GetPreferenceManager(), sharing_platform.GetAccountManager(), sharing_platform.CreatePublicCertificateDatabase(database_path), - local_device_data_manager, contact_manager, client_factory)); + local_device_data_manager, client_factory)); } // static @@ -217,12 +219,11 @@ NearbyShareCertificateManagerImpl::NearbyShareCertificateManagerImpl( AccountManager& account_manager, std::unique_ptr public_certificate_database, NearbyShareLocalDeviceDataManager* local_device_data_manager, - NearbyShareContactManager* contact_manager, nearby::sharing::api::SharingRpcClientFactory* client_factory) : context_(context), account_manager_(account_manager), local_device_data_manager_(local_device_data_manager), - contact_manager_(contact_manager), + preference_manager_(preference_manager), nearby_identity_client_(client_factory->CreateIdentityInstance()), certificate_storage_(NearbyShareCertificateStorageImpl::Factory::Create( preference_manager, std::move(public_certificate_database))), @@ -297,14 +298,17 @@ NearbyShareCertificateManagerImpl::~NearbyShareCertificateManagerImpl() { local_device_data_manager_->RemoveObserver(this); } +std::string NearbyShareCertificateManagerImpl::GetId() { + return preference_manager_.GetString(prefs::kNearbySharingDeviceIdName, ""); +} + void NearbyShareCertificateManagerImpl::CertificateDownloadContext:: QuerySharedCredentialsFetchNextPage() { page_number_++; LOG(INFO) << __func__ - << ": [Call Identity API] Downloading page=" << page_number_; + << ": Downloading public certificates page=" << page_number_; QuerySharedCredentialsRequest request; - request.set_name( - absl::StrCat("devices/", absl::StripPrefix(device_id_, kDeviceIdPrefix))); + request.set_name(absl::StrCat("devices/", device_id_)); if (next_page_token_.has_value()) { request.set_page_token(*next_page_token_); } @@ -314,39 +318,36 @@ void NearbyShareCertificateManagerImpl::CertificateDownloadContext:: if (!response.ok()) { LOG(WARNING) << __func__ - << ": [Call Identity API] Failed to download certificates: " + << ": Failed to download public certificates: " << response.status(); std::move(download_failure_callback_)(); return; } for (const auto& credential : response->shared_credentials()) { if (credential.data_type() != - google::nearby::identity::v1::SharedCredential:: - DATA_TYPE_PUBLIC_CERTIFICATE) { - LOG(WARNING) << __func__ - << ": [Call Identity API] skipping non " - "DATA_TYPE_PUBLIC_CERTIFICATE, credential.id: " - << credential.id(); + SharedCredential::DATA_TYPE_PUBLIC_CERTIFICATE) { + VLOG(1) << __func__ + << ": skipping non " + "DATA_TYPE_PUBLIC_CERTIFICATE, credential.id: " + << credential.id(); continue; } PublicCertificate certificate; if (!certificate.ParseFromString(credential.data())) { - LOG(ERROR) << __func__ - << ": [Call Identity API] Failed parsing to " - "PublicCertificate, credential.id: " - << credential.id() << " data: " - << absl::BytesToHexString(credential.data()); + LOG(ERROR) + << __func__ + << ": Failed parsing to PublicCertificate, credential.id: " + << credential.id() + << " data: " << absl::BytesToHexString(credential.data()); continue; } VLOG(1) << __func__ - << ": [Call Identity API] Successfully parsed credential: " - << credential.id(); + << ": Successfully parsed credential: " << credential.id(); certificates_.push_back(certificate); } if (response->next_page_token().empty()) { - LOG(INFO) << __func__ - << ": [Call Identity API] Completed to download " + LOG(INFO) << __func__ << ": Completed download of " << certificates_.size() << " certificates"; std::move(download_success_callback_)(certificates_); return; @@ -392,9 +393,10 @@ bool NearbyShareCertificateManagerImpl::DownloadPublicCertificatesInExecutor() { return false; } - std::string device_id = local_device_data_manager_->GetId(); - if (!account_manager_.GetCurrentAccount().has_value() || device_id.empty()) { + std::string device_id = GetId(); + if (device_id.empty() || !account_manager_.GetCurrentAccount().has_value()) { LOG(WARNING) << "Ignore certificates download, no logged in account."; + // Return true to prevent retry. return true; } @@ -402,7 +404,7 @@ bool NearbyShareCertificateManagerImpl::DownloadPublicCertificatesInExecutor() { // Currently certificates download is synchronous. It completes after // QuerySharedCredentialsFetchNextPage() returns. auto context = std::make_unique( - nearby_identity_client_.get(), kDeviceIdPrefix + device_id, + nearby_identity_client_.get(), std::move(device_id), [&download_succeeded]() { download_succeeded = false; }, [this, &download_succeeded]( const std::vector& certificates) { @@ -415,6 +417,8 @@ bool NearbyShareCertificateManagerImpl::DownloadPublicCertificatesInExecutor() { download_succeeded = UpdatePublicCertificates(certificates); }); context->QuerySharedCredentialsFetchNextPage(); + LOG(INFO) << "Public certificates downloadws, success: " + << download_succeeded; return download_succeeded; } @@ -427,30 +431,20 @@ void NearbyShareCertificateManagerImpl::RegeneratePrivateCertificates() { }); } -bool NearbyShareCertificateManagerImpl::UploadDeviceCertificatesInExecutor( +void NearbyShareCertificateManagerImpl::AddCertifactesToPublishDeviceRequest( const std::vector& private_certs, - bool force_update_contacts) { - LOG(INFO) << "Start to upload local device certificates in executor."; + PublishDeviceRequest& request) { + PerVisibilitySharedCredentials* new_self_credential = + request.mutable_device()->add_per_visibility_shared_credentials(); + new_self_credential->set_visibility( + PerVisibilitySharedCredentials::VISIBILITY_SELF); + PerVisibilitySharedCredentials* new_contacts_credential = + request.mutable_device()->add_per_visibility_shared_credentials(); + new_contacts_credential->set_visibility( + PerVisibilitySharedCredentials::VISIBILITY_CONTACTS); - if (!is_running()) { - LOG(WARNING) - << "Ignore local device certificates upload, manager is not running."; - return false; - } - - if (!account_manager_.GetCurrentAccount().has_value()) { - LOG(WARNING) - << "Ignore local device certificates upload, no logged in account."; - return true; - } - - if (private_certs.empty()) { - LOG(WARNING) << "Ignore local device certificates upload, no private " - "certificates found."; - return false; - } - std::vector public_certs; - public_certs.reserve(private_certs.size()); + int self_share_credential_count = 0; + int contacts_share_credential_count = 0; for (const NearbySharePrivateCertificate& private_cert : private_certs) { std::optional public_cert = private_cert.ToPublicCertificate(); @@ -460,37 +454,104 @@ bool NearbyShareCertificateManagerImpl::UploadDeviceCertificatesInExecutor( continue; } VLOG(1) << "Uploading public certificate id: " - << absl::BytesToHexString(public_cert->secret_id()); - public_certs.push_back(*public_cert); + << absl::BytesToHexString(public_cert->secret_id()) << "for " + << (public_cert->for_self_share() ? "self" : "contact"); + SharedCredential* shared_credential; + if (public_cert->for_self_share()) { + shared_credential = new_self_credential->add_shared_credentials(); + self_share_credential_count++; + } else { + shared_credential = new_contacts_credential->add_shared_credentials(); + contacts_share_credential_count++; + } + shared_credential->set_id( + util_hash::HighwayFingerprint64(public_cert->secret_id())); + shared_credential->set_data(public_cert->SerializeAsString()); + shared_credential->set_data_type( + SharedCredential::DATA_TYPE_PUBLIC_CERTIFICATE); + *shared_credential->mutable_expiration_time() = public_cert->end_time(); + } + LOG(INFO) << __func__ << ": PublishDevice: uploaded " + << self_share_credential_count << " self share credentials and " + << contacts_share_credential_count << " contacts credentials"; +} + +bool NearbyShareCertificateManagerImpl::UploadDeviceCertificatesInExecutor( + const std::vector& private_certs, + bool force_update_contacts) { + LOG(INFO) << "Start to upload local device certificates in executor."; + if (private_certs.empty()) { + LOG(WARNING) << "Ignore local device certificates upload, no private " + "certificates found."; + return false; } - LOG(INFO) << "Uploading " << public_certs.size() - << " local device certificates."; + if (!is_running()) { + LOG(WARNING) + << "Ignore local device certificates upload, manager is not running."; + return false; + } + std::string device_id = GetId(); + if (device_id.empty() || !account_manager_.GetCurrentAccount().has_value()) { + LOG(WARNING) + << "Ignore local device certificates upload, no logged in account."; + // Return true to prevent retry. + return true; + } + + PublishDeviceRequest request; + request.mutable_device()->set_name(absl::StrCat("devices/", device_id)); + VLOG(1) << __func__ << ": PublishDeviceRequest with Device.name: " + << request.device().name(); + request.mutable_device()->set_display_name( + local_device_data_manager_->GetDeviceName()); + // Force update contacts call is right after CONTACT_GOOGLE_CONTACT_LATEST + // call and can use CONTACT_GOOGLE_CONTACT to save server side computation. + request.mutable_device()->set_contact( + force_update_contacts + ? google::nearby::identity::v1::Device::CONTACT_GOOGLE_CONTACT_LATEST + : google::nearby::identity::v1::Device::CONTACT_GOOGLE_CONTACT); + + AddCertifactesToPublishDeviceRequest(private_certs, request); bool upload_certificates_succeeded = false; bool regenerate_certificates = false; absl::Notification notification; - LOG(INFO) << __func__ << ": [Call Identity API] PublishDevice: upload " - << public_certs.size() - << " local device certificates, force_update_contacts = " - << force_update_contacts; - local_device_data_manager_->PublishDevice( - std::move(public_certs), force_update_contacts, + nearby_identity_client_->PublishDevice( + request, [&upload_certificates_succeeded, ®enerate_certificates, - ¬ification](bool success, bool contact_removed) { - upload_certificates_succeeded = success; - regenerate_certificates = contact_removed; + ¬ification](const absl::StatusOr& response) { + upload_certificates_succeeded = response.ok(); + if (!response.ok()) { + LOG(WARNING) << __func__ + << ": PublishDevice failed: " << response.status(); + } else { + // If contacts are removed, regenerate all Private certificates and + // make a 2nd PublishDevice RPC call. + if (absl::linear_search( + response.value().contact_updates().begin(), + response.value().contact_updates().end(), + google::nearby::identity::v1::PublishDeviceResponse:: + CONTACT_UPDATE_REMOVED)) { + regenerate_certificates = true; + } + LOG(INFO) << __func__ + << ": PublishDevice succeeded. contact_removed: " + << regenerate_certificates; + } notification.Notify(); }); notification.WaitForNotification(); - LOG(INFO) << "Upload local device certificates " - << (upload_certificates_succeeded ? "succeeded" : "failed") - << " contact_removed = " << regenerate_certificates; + // check whether the manager is still running + if (!is_running()) { + LOG(WARNING) << __func__ << ": manager is stopped after call."; + return false; + } if (!upload_certificates_succeeded) { return false; } if (regenerate_certificates) { LOG(INFO) << __func__ - << ": [Call Identity API] Another call to PublishDevice after " + << ": Need to make another call to PublishDevice after " "regenerating all Private certificates: "; RegeneratePrivateCertificates(); } @@ -733,7 +794,12 @@ bool NearbyShareCertificateManagerImpl::RefreshPrivateCertificatesInExecutor( if (force_upload) { force_contacts_update_scheduler_->MakeImmediateRequest(); } else { - UploadDeviceCertificatesInExecutor(certs, /*force_update_contacts=*/false); + executor_->PostTask([this]() { + LOG(INFO) << "Begin UploadDeviceCertificatesInExecutor"; + UploadDeviceCertificatesInExecutor( + certificate_storage_->GetPrivateCertificates(), + /*force_update_contacts=*/false); + }); } return true; } diff --git a/sharing/certificates/nearby_share_certificate_manager_impl.h b/sharing/certificates/nearby_share_certificate_manager_impl.h index 76d16642..8ff291a6 100644 --- a/sharing/certificates/nearby_share_certificate_manager_impl.h +++ b/sharing/certificates/nearby_share_certificate_manager_impl.h @@ -32,7 +32,6 @@ #include "sharing/certificates/nearby_share_certificate_storage.h" #include "sharing/certificates/nearby_share_encrypted_metadata_key.h" #include "sharing/certificates/nearby_share_private_certificate.h" -#include "sharing/contacts/nearby_share_contact_manager.h" #include "sharing/internal/api/preference_manager.h" #include "sharing/internal/api/public_certificate_database.h" #include "sharing/internal/api/sharing_platform.h" @@ -66,7 +65,6 @@ class NearbyShareCertificateManagerImpl Context* context, nearby::sharing::api::SharingPlatform& sharing_platform, NearbyShareLocalDeviceDataManager* local_device_data_manager, - NearbyShareContactManager* contact_manager, const FilePath& profile_path, nearby::sharing::api::SharingRpcClientFactory* client_factory); static void SetFactoryForTesting(Factory* test_factory); @@ -76,7 +74,6 @@ class NearbyShareCertificateManagerImpl virtual std::unique_ptr CreateInstance( Context* context, NearbyShareLocalDeviceDataManager* local_device_data_manager, - NearbyShareContactManager* contact_manager, const FilePath& profile_path, nearby::sharing::api::SharingRpcClientFactory* client_factory) = 0; @@ -141,7 +138,6 @@ class NearbyShareCertificateManagerImpl std::unique_ptr public_certificate_database, NearbyShareLocalDeviceDataManager* local_device_data_manager, - NearbyShareContactManager* contact_manager, nearby::sharing::api::SharingRpcClientFactory* client_factory); // NearbyShareCertificateManager: @@ -187,10 +183,18 @@ class NearbyShareCertificateManagerImpl const std::vector& certificates); + void AddCertifactesToPublishDeviceRequest( + const std::vector& private_certs, + google::nearby::identity::v1::PublishDeviceRequest& request); + + // Returns the device id use to identify the local device in BE. + std::string GetId(); + + Context* const context_; AccountManager& account_manager_; NearbyShareLocalDeviceDataManager* const local_device_data_manager_; - NearbyShareContactManager* const contact_manager_; + nearby::sharing::api::PreferenceManager& preference_manager_; int32_t vendor_id_ = 0; // Defaults to GOOGLE. std::unique_ptr< nearby::sharing::api::SharingRpcClient> nearby_client_; std::unique_ptr diff --git a/sharing/certificates/nearby_share_certificate_manager_impl_test.cc b/sharing/certificates/nearby_share_certificate_manager_impl_test.cc index f44b2776..c559edc4 100644 --- a/sharing/certificates/nearby_share_certificate_manager_impl_test.cc +++ b/sharing/certificates/nearby_share_certificate_manager_impl_test.cc @@ -51,7 +51,6 @@ #include "sharing/contacts/fake_nearby_share_contact_manager.h" #include "sharing/internal/api/fake_nearby_share_client.h" #include "sharing/internal/api/mock_sharing_platform.h" -#include "sharing/internal/public/logging.h" #include "sharing/internal/test/fake_bluetooth_adapter.h" #include "sharing/internal/test/fake_context.h" #include "sharing/internal/test/fake_preference_manager.h" @@ -67,6 +66,9 @@ namespace nearby { namespace sharing { namespace { +using ::google::nearby::identity::v1::Device; +using ::google::nearby::identity::v1::PublishDeviceRequest; +using ::google::nearby::identity::v1::PublishDeviceResponse; using ::google::nearby::identity::v1::QuerySharedCredentialsRequest; using ::google::nearby::identity::v1::QuerySharedCredentialsResponse; using ::nearby::sharing::proto::DeviceVisibility; @@ -105,13 +107,10 @@ class NearbyShareCertificateManagerImplTest .WillByDefault(ReturnRef(fake_account_manager_)); // Set time to t0. FastForward(t0 - fake_context_.GetClock()->Now()); - + preference_manager_.SetString(prefs::kNearbySharingDeviceIdName, kDeviceId); local_device_data_manager_ = std::make_unique( kDefaultDeviceName); - local_device_data_manager_->set_is_sync_mode(true); - local_device_data_manager_->SetId(kDeviceId); - contact_manager_ = std::make_unique(); AccountManager::Account account{ @@ -145,7 +144,7 @@ class NearbyShareCertificateManagerImplTest // Setup Identity API. cert_manager_ = NearbyShareCertificateManagerImpl::Factory::Create( &fake_context_, mock_sharing_platform_, - local_device_data_manager_.get(), contact_manager_.get(), + local_device_data_manager_.get(), /*profile_path=*/{}, &client_factory_); cert_manager_->AddObserver(this); @@ -188,6 +187,10 @@ class NearbyShareCertificateManagerImplTest ++num_private_certs_changed_notifications_; } + FakeNearbyIdentityClient* GetIdentityClient() { + return client_factory_.identity_instances().back(); + } + protected: enum class DownloadPublicCertificatesResult { kSuccess, @@ -233,15 +236,27 @@ class NearbyShareCertificateManagerImplTest } void VerifyCertificatesUpload(bool expected_force_update_contacts) { - ASSERT_FALSE(local_device_data_manager_->publish_device_calls().empty()); - EXPECT_EQ(local_device_data_manager_->publish_device_calls() - .back() - .certificates.size(), - 2 * kNearbyShareNumPrivateCertificates); - EXPECT_EQ(local_device_data_manager_->publish_device_calls() - .back() - .force_update_contacts, - expected_force_update_contacts); + FakeNearbyIdentityClient* identity_client = GetIdentityClient(); + ASSERT_FALSE(identity_client->publish_device_requests().empty()); + const PublishDeviceRequest& publish_device_request = + identity_client->publish_device_requests().back(); + EXPECT_EQ(publish_device_request.device().name(), + absl::StrCat("devices/", kDeviceId)); + EXPECT_EQ(publish_device_request.device() + .per_visibility_shared_credentials_size(), + 2); + EXPECT_EQ(publish_device_request.device() + .per_visibility_shared_credentials(0) + .shared_credentials_size(), + kNearbyShareNumPrivateCertificates); + EXPECT_EQ(publish_device_request.device() + .per_visibility_shared_credentials(1) + .shared_credentials_size(), + kNearbyShareNumPrivateCertificates); + EXPECT_EQ(publish_device_request.device().contact(), + expected_force_update_contacts + ? Device::CONTACT_GOOGLE_CONTACT_LATEST + : Device::CONTACT_GOOGLE_CONTACT); } void InvokePrivateCertificateRefresh(bool expected_success) { @@ -253,6 +268,7 @@ class NearbyShareCertificateManagerImplTest EXPECT_EQ(expected_success ? 1u : 0u, num_private_certs_changed_notifications_); EXPECT_EQ(0u, upload_scheduler_->num_immediate_requests()); + Sync(); if (expected_success) { VerifyCertificatesUpload(/*expected_force_update_contacts=*/false); } @@ -308,17 +324,29 @@ class NearbyShareCertificateManagerImplTest void InvokeCertUploadPublishDevice(bool contacts_removed, bool publish_device_success) { - local_device_data_manager_->SetPublishDeviceResult(publish_device_success); - local_device_data_manager_->SetPublishDeviceContactsRemoved( - contacts_removed); + FakeNearbyIdentityClient* identity_client = GetIdentityClient(); + std::vector> responses; + if (contacts_removed) { + // When contacts are removed, a second publish device call is scheduled. + PublishDeviceResponse response; + response.add_contact_updates( + PublishDeviceResponse::CONTACT_UPDATE_REMOVED); + responses.push_back(response); + } + PublishDeviceResponse response; + response.add_contact_updates( + PublishDeviceResponse::CONTACT_UPDATE_ADDED); + responses.push_back(response); + identity_client->SetPublishDeviceResponses(std::move(responses)); upload_scheduler_->InvokeRequestCallback(); Sync(); // If contacts are removed, a second publish device call is scheduled. if (contacts_removed) { Sync(); + Sync(); } - EXPECT_EQ(local_device_data_manager_->publish_device_calls().size(), + EXPECT_EQ(identity_client->publish_device_requests().size(), contacts_removed ? 2 : 1); VerifyCertificatesUpload( @@ -352,18 +380,15 @@ class NearbyShareCertificateManagerImplTest BuildQuerySharedCredentialsResponse(page_number, page_token)); } - client_factory_.identity_instances() - .back() - ->SetQuerySharedCredentialsResponses(responses); + FakeNearbyIdentityClient* identity_client = GetIdentityClient(); + identity_client->SetQuerySharedCredentialsResponses(responses); cert_store_->SetAddPublicCertificatesResult( result != DownloadPublicCertificatesResult::kStorageError); download_scheduler_->InvokeRequestCallback(); Sync(); std::vector requests = - client_factory_.identity_instances() - .back() - ->query_shared_credentials_requests(); + identity_client->query_shared_credentials_requests(); EXPECT_EQ(requests.size(), num_pages); EXPECT_EQ(requests.back().name(), absl::StrCat("devices/", kDeviceId)); ASSERT_EQ(download_scheduler_->handled_results().size(), @@ -713,8 +738,6 @@ TEST_F(NearbyShareCertificateManagerImplTest, Initialize(); // All private certificates are valid. cert_store_->ReplacePrivateCertificates(private_certificates_); - local_device_data_manager_->SetPublishDeviceContactsRemoved( - /*contact_removed=*/true); cert_manager_->ForceUploadPrivateCertificates(); Sync(); @@ -734,7 +757,7 @@ TEST_F(NearbyShareCertificateManagerImplTest, EXPECT_EQ(0, upload_scheduler_->num_immediate_requests()); EXPECT_TRUE(cert_store_->GetPrivateCertificates().empty()); - EXPECT_TRUE(local_device_data_manager_->publish_device_calls().empty()); + EXPECT_TRUE(GetIdentityClient()->publish_device_requests().empty()); } TEST_F(NearbyShareCertificateManagerImplTest, @@ -807,7 +830,6 @@ TEST_F(NearbyShareCertificateManagerImplTest, cert_manager_->SetVendorId(12345); - Sync(); std::vector certs = cert_store_->GetPrivateCertificates(); @@ -914,7 +936,7 @@ TEST_F(NearbyShareCertificateManagerImplTest, upload_scheduler_->InvokeRequestCallback(); Sync(); - EXPECT_EQ(local_device_data_manager_->publish_device_calls().size(), 0); + EXPECT_TRUE(GetIdentityClient()->publish_device_requests().empty()); EXPECT_EQ(upload_scheduler_->handled_results().size(), 1); EXPECT_EQ(upload_scheduler_->handled_results().back(), false); } diff --git a/sharing/contacts/nearby_share_contact_manager_impl_test.cc b/sharing/contacts/nearby_share_contact_manager_impl_test.cc index a5fb4262..1c3049a1 100644 --- a/sharing/contacts/nearby_share_contact_manager_impl_test.cc +++ b/sharing/contacts/nearby_share_contact_manager_impl_test.cc @@ -38,8 +38,7 @@ #include "sharing/scheduling/fake_nearby_share_scheduler_factory.h" #include "sharing/scheduling/nearby_share_scheduler_factory.h" -namespace nearby { -namespace sharing { +namespace nearby::sharing { namespace { using ::nearby::sharing::proto::ContactRecord; @@ -63,9 +62,7 @@ class NearbyShareContactManagerImplTest }; NearbyShareContactManagerImplTest() - : local_device_data_manager_(kTestDefaultDeviceName) { - local_device_data_manager_.set_is_sync_mode(true); - } + : local_device_data_manager_(kTestDefaultDeviceName) {} ~NearbyShareContactManagerImplTest() override = default; @@ -136,5 +133,4 @@ class NearbyShareContactManagerImplTest }; } // namespace -} // namespace sharing -} // namespace nearby +} // namespace nearby::sharing diff --git a/sharing/internal/api/BUILD b/sharing/internal/api/BUILD index 027bc2c3..17c7ecd2 100644 --- a/sharing/internal/api/BUILD +++ b/sharing/internal/api/BUILD @@ -77,11 +77,14 @@ cc_library( "//internal/platform:types", "//internal/platform/implementation:account_manager", "//sharing/analytics", + "//sharing/internal/public:logging", "//sharing/proto:share_cc_proto", + "@com_google_absl//absl/base:core_headers", "@com_google_absl//absl/functional:any_invocable", "@com_google_absl//absl/status", "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings", + "@com_google_absl//absl/synchronization", "@com_google_absl//absl/types:span", "@com_google_googletest//:gtest_for_library_testonly", ], diff --git a/sharing/internal/api/fake_nearby_share_client.cc b/sharing/internal/api/fake_nearby_share_client.cc index 23536542..4a99b91f 100644 --- a/sharing/internal/api/fake_nearby_share_client.cc +++ b/sharing/internal/api/fake_nearby_share_client.cc @@ -20,7 +20,9 @@ #include "absl/functional/any_invocable.h" #include "absl/status/status.h" #include "absl/status/statusor.h" +#include "absl/synchronization/mutex.h" #include "sharing/internal/api/sharing_rpc_client.h" +#include "sharing/internal/public/logging.h" #include "sharing/proto/certificate_rpc.pb.h" #include "sharing/proto/contact_rpc.pb.h" #include "sharing/proto/device_rpc.pb.h" @@ -28,10 +30,17 @@ namespace nearby { namespace sharing { +using ::google::nearby::identity::v1::GetAccountInfoRequest; +using ::google::nearby::identity::v1::GetAccountInfoResponse; +using ::google::nearby::identity::v1::PublishDeviceRequest; +using ::google::nearby::identity::v1::PublishDeviceResponse; +using ::google::nearby::identity::v1::QuerySharedCredentialsRequest; +using ::google::nearby::identity::v1::QuerySharedCredentialsResponse; + void FakeNearbyShareClient::ListContactPeople( const proto::ListContactPeopleRequest& request, - absl::AnyInvocable& response) &&> + absl::AnyInvocable& response) &&> callback) { list_contact_people_requests_.emplace_back(request); if (list_contact_people_responses_.empty()) { @@ -44,41 +53,53 @@ void FakeNearbyShareClient::ListContactPeople( } void FakeNearbyIdentityClient::QuerySharedCredentials( - const google::nearby::identity::v1::QuerySharedCredentialsRequest& request, + const QuerySharedCredentialsRequest& request, absl::AnyInvocable< - void(const absl::StatusOr< - google::nearby::identity::v1::QuerySharedCredentialsResponse>& - response) &&> + void(const absl::StatusOr& response) &&> callback) { - query_shared_credentials_requests_.emplace_back(request); - if (query_shared_credentials_responses_.empty()) { - std::move(callback)(absl::NotFoundError("")); - return; + absl::StatusOr response = + absl::NotFoundError(""); + { + absl::MutexLock lock(mutex_); + query_shared_credentials_requests_.emplace_back(request); + if (!query_shared_credentials_responses_.empty()) { + response = query_shared_credentials_responses_[0]; + query_shared_credentials_responses_.erase( + query_shared_credentials_responses_.begin()); + } } - auto response = query_shared_credentials_responses_[0]; - query_shared_credentials_responses_.erase( - query_shared_credentials_responses_.begin()); std::move(callback)(response); } void FakeNearbyIdentityClient::PublishDevice( - const google::nearby::identity::v1::PublishDeviceRequest& request, + const PublishDeviceRequest& request, absl::AnyInvocable< - void(const absl::StatusOr< - google::nearby::identity::v1::PublishDeviceResponse>& response) &&> + void(const absl::StatusOr& response) &&> callback) { - publish_device_requests_.emplace_back(request); - std::move(callback)(publish_device_response_); + absl::StatusOr response = absl::NotFoundError(""); + { + absl::MutexLock lock(mutex_); + publish_device_requests_.emplace_back(request); + if (!publish_device_responses_.empty()) { + response = publish_device_responses_[0]; + publish_device_responses_.erase(publish_device_responses_.begin()); + } + } + std::move(callback)(response); } void FakeNearbyIdentityClient::GetAccountInfo( - const google::nearby::identity::v1::GetAccountInfoRequest& request, + const GetAccountInfoRequest& request, absl::AnyInvocable< - void(const absl::StatusOr& response) &&> + void(const absl::StatusOr& response) &&> callback) { - get_account_info_requests_.emplace_back(request); - std::move(callback)(get_account_info_response_); + absl::StatusOr response = absl::NotFoundError(""); + { + absl::MutexLock lock(mutex_); + get_account_info_requests_.emplace_back(request); + response = get_account_info_response_; + } + std::move(callback)(response); } std::unique_ptr diff --git a/sharing/internal/api/fake_nearby_share_client.h b/sharing/internal/api/fake_nearby_share_client.h index 03cc0fde..310db71f 100644 --- a/sharing/internal/api/fake_nearby_share_client.h +++ b/sharing/internal/api/fake_nearby_share_client.h @@ -18,8 +18,10 @@ #include #include +#include "absl/base/thread_annotations.h" #include "absl/functional/any_invocable.h" #include "absl/status/statusor.h" +#include "absl/synchronization/mutex.h" #include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/proto/certificate_rpc.pb.h" #include "sharing/proto/contact_rpc.pb.h" @@ -67,11 +69,13 @@ class FakeNearbyIdentityClient std::vector& publish_device_requests() { + absl::MutexLock lock(mutex_); return publish_device_requests_; } std::vector& query_shared_credentials_requests() { + absl::MutexLock lock(mutex_); return query_shared_credentials_requests_; } @@ -82,10 +86,12 @@ class FakeNearbyIdentityClient PublishDeviceResponse>& response) &&> callback) override; - void SetPublishDeviceResponse( - absl::StatusOr - response) { - publish_device_response_ = response; + void SetPublishDeviceResponses( + std::vector< + absl::StatusOr> + responses) { + absl::MutexLock lock(mutex_); + publish_device_responses_ = responses; } void QuerySharedCredentials( @@ -101,6 +107,7 @@ class FakeNearbyIdentityClient std::vector> responses) { + absl::MutexLock lock(mutex_); query_shared_credentials_responses_ = responses; } @@ -114,24 +121,28 @@ class FakeNearbyIdentityClient void SetGetAccountInfoResponse( absl::StatusOr response) { + absl::MutexLock lock(mutex_); get_account_info_response_ = response; } + private: + absl::Mutex mutex_; std::vector - publish_device_requests_; - absl::StatusOr - publish_device_response_; + publish_device_requests_ ABSL_GUARDED_BY(mutex_); + std::vector< + absl::StatusOr> + publish_device_responses_ ABSL_GUARDED_BY(mutex_); std::vector - query_shared_credentials_requests_; + query_shared_credentials_requests_ ABSL_GUARDED_BY(mutex_); std::vector> - query_shared_credentials_responses_; + query_shared_credentials_responses_ ABSL_GUARDED_BY(mutex_); std::vector - get_account_info_requests_; + get_account_info_requests_ ABSL_GUARDED_BY(mutex_); absl::StatusOr - get_account_info_response_; + get_account_info_response_ ABSL_GUARDED_BY(mutex_); }; class FakeNearbyShareClientFactory diff --git a/sharing/local_device_data/BUILD b/sharing/local_device_data/BUILD index 5d59d3ab..7981d658 100644 --- a/sharing/local_device_data/BUILD +++ b/sharing/local_device_data/BUILD @@ -36,15 +36,9 @@ cc_library( "//sharing/common:enum", "//sharing/internal/api:platform", "//sharing/internal/base:utf_utils", - "//sharing/internal/impl/common:nearby_identity_grpc_client", "//sharing/internal/public:logging", - "//sharing/internal/public:types", "//sharing/proto:share_cc_proto", - "//util/hash:highway_fingerprint", - "@com_google_absl//absl/algorithm", "@com_google_absl//absl/memory", - "@com_google_absl//absl/random", - "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings", ], ) @@ -62,9 +56,6 @@ cc_library( deps = [ ":local_device_data", "//sharing/common:enum", - "//sharing/internal/api:platform", - "//sharing/internal/public:types", - "//sharing/proto:share_cc_proto", "@com_google_absl//absl/strings", ], ) @@ -77,24 +68,13 @@ cc_test( deps = [ ":local_device_data", "//internal/platform/implementation:account_manager", - "//internal/platform/implementation/g3", # fixdeps: keep + "//internal/platform/implementation:platform_impl", "//internal/test", - "//proto/identity/v1:resources_cc_proto", - "//proto/identity/v1:rpcs_cc_proto", "//sharing/common", "//sharing/common:enum", - "//sharing/internal/api:mock_sharing_platform", - "//sharing/internal/public:logging", "//sharing/internal/test:nearby_test", - "//sharing/proto:share_cc_proto", - "//sharing/scheduling", - "//sharing/scheduling:test_support", "@com_github_protobuf_matchers//protobuf-matchers", - "@com_google_absl//absl/status", - "@com_google_absl//absl/status:statusor", "@com_google_absl//absl/strings", - "@com_google_absl//absl/time", - "@com_google_absl//absl/types:optional", "@com_google_googletest//:gtest_main", ], ) diff --git a/sharing/local_device_data/fake_nearby_share_local_device_data_manager.cc b/sharing/local_device_data/fake_nearby_share_local_device_data_manager.cc index e5973846..0c740fcb 100644 --- a/sharing/local_device_data/fake_nearby_share_local_device_data_manager.cc +++ b/sharing/local_device_data/fake_nearby_share_local_device_data_manager.cc @@ -16,38 +16,19 @@ #include #include -#include #include #include "absl/strings/string_view.h" #include "sharing/common/nearby_share_enums.h" -#include "sharing/internal/api/sharing_rpc_client.h" -#include "sharing/internal/public/context.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" -#include "sharing/proto/rpc_resources.pb.h" - -namespace nearby { -namespace sharing { -class NearbyShareClientFactory; +namespace nearby::sharing { namespace { - -using ::nearby::sharing::api::SharingRpcClientFactory; - -constexpr absl::string_view kDefaultId = "123456789A"; constexpr absl::string_view kDefaultDeviceName = "Barack's Chromebook"; - } // namespace -FakeNearbyShareLocalDeviceDataManager::Factory::Factory() = default; - -FakeNearbyShareLocalDeviceDataManager::Factory::~Factory() = default; - std::unique_ptr -FakeNearbyShareLocalDeviceDataManager::Factory::CreateInstance( - nearby::Context* context, SharingRpcClientFactory* rpc_client_factory) { - latest_rpc_client_factory_ = rpc_client_factory; - +FakeNearbyShareLocalDeviceDataManager::Factory::CreateInstance() { auto instance = std::make_unique( kDefaultDeviceName); instances_.push_back(instance.get()); @@ -57,23 +38,12 @@ FakeNearbyShareLocalDeviceDataManager::Factory::CreateInstance( FakeNearbyShareLocalDeviceDataManager::FakeNearbyShareLocalDeviceDataManager( absl::string_view default_device_name) - : id_(kDefaultId), device_name_(default_device_name) {} - -FakeNearbyShareLocalDeviceDataManager:: - ~FakeNearbyShareLocalDeviceDataManager() = default; - -std::string FakeNearbyShareLocalDeviceDataManager::GetId() { return id_; } + : device_name_(default_device_name) {} std::string FakeNearbyShareLocalDeviceDataManager::GetDeviceName() const { return device_name_; } -DeviceNameValidationResult -FakeNearbyShareLocalDeviceDataManager::ValidateDeviceName( - absl::string_view name) { - return next_validation_result_; -} - DeviceNameValidationResult FakeNearbyShareLocalDeviceDataManager::SetDeviceName( absl::string_view name) { if (next_validation_result_ != DeviceNameValidationResult::kValid) @@ -90,17 +60,4 @@ DeviceNameValidationResult FakeNearbyShareLocalDeviceDataManager::SetDeviceName( return DeviceNameValidationResult::kValid; } -void FakeNearbyShareLocalDeviceDataManager::PublishDevice( - std::vector certificates, - bool force_update_contacts, PublishDeviceCallback callback) { - publish_device_calls_.emplace_back(std::move(certificates), - force_update_contacts, callback); - if (is_sync_mode_) { - callback(publish_device_result_, publish_device_contact_removed_); - // publish_device_contact_removed_ resets to false after the first call. - publish_device_contact_removed_ = false; - } -}; - -} // namespace sharing -} // namespace nearby +} // namespace nearby::sharing diff --git a/sharing/local_device_data/fake_nearby_share_local_device_data_manager.h b/sharing/local_device_data/fake_nearby_share_local_device_data_manager.h index 81c0bc66..12980bc6 100644 --- a/sharing/local_device_data/fake_nearby_share_local_device_data_manager.h +++ b/sharing/local_device_data/fake_nearby_share_local_device_data_manager.h @@ -19,19 +19,14 @@ #include #include -#include #include #include "absl/strings/string_view.h" #include "sharing/common/nearby_share_enums.h" -#include "sharing/internal/api/sharing_rpc_client.h" -#include "sharing/internal/public/context.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager_impl.h" -#include "sharing/proto/rpc_resources.pb.h" -namespace nearby { -namespace sharing { +namespace nearby::sharing { // A fake implementation of NearbyShareLocalDeviceDataManager, along with a fake // factory, to be used in tests. @@ -43,8 +38,8 @@ class FakeNearbyShareLocalDeviceDataManager // in unit tests. class Factory : public NearbyShareLocalDeviceDataManagerImpl::Factory { public: - Factory(); - ~Factory() override; + Factory() = default; + ~Factory() override = default; // Returns all FakeNearbyShareLocalDeviceDataManager instances created by // CreateInstance(). @@ -52,94 +47,36 @@ class FakeNearbyShareLocalDeviceDataManager return instances_; } - nearby::sharing::api::SharingRpcClientFactory* latest_rpc_client_factory() - const { - return latest_rpc_client_factory_; - } - protected: - std::unique_ptr CreateInstance( - nearby::Context* context, - nearby::sharing::api::SharingRpcClientFactory* rpc_client_factory) + std::unique_ptr CreateInstance() override; private: std::vector instances_; - nearby::sharing::api::SharingRpcClientFactory* latest_rpc_client_factory_ = - nullptr; - }; - - struct PublishDeviceCall { - PublishDeviceCall( - std::vector certificates, - bool force_update_contacts, PublishDeviceCallback callback) - : certificates(std::move(certificates)), - callback(std::move(callback)), - force_update_contacts(force_update_contacts){} - PublishDeviceCall(PublishDeviceCall&&) = default; - ~PublishDeviceCall() = default; - - std::vector certificates; - PublishDeviceCallback callback; - bool force_update_contacts = false; }; explicit FakeNearbyShareLocalDeviceDataManager( absl::string_view default_device_name); - ~FakeNearbyShareLocalDeviceDataManager() override; + ~FakeNearbyShareLocalDeviceDataManager() override = default; // NearbyShareLocalDeviceDataManager: - std::string GetId() override; std::string GetDeviceName() const override; - DeviceNameValidationResult ValidateDeviceName( - absl::string_view name) override; DeviceNameValidationResult SetDeviceName(absl::string_view name) override; - void PublishDevice( - std::vector certificates, - bool force_update_contacts, PublishDeviceCallback callback) override; - // Make protected observer-notification methods from the base class public in // this fake class. using NearbyShareLocalDeviceDataManager::NotifyLocalDeviceDataChanged; - void SetId(absl::string_view id) { id_ = std::string(id); } - - std::vector& publish_device_calls() { - return publish_device_calls_; - } - void set_next_validation_result(DeviceNameValidationResult result) { next_validation_result_ = result; } - // methods for synchronization test. - void set_is_sync_mode(bool is_sync_mode) { is_sync_mode_ = is_sync_mode; } - - void SetPublishDeviceResult(bool publish_device_result) { - publish_device_result_ = publish_device_result; - } - - void SetPublishDeviceContactsRemoved(bool contact_removed) { - publish_device_contact_removed_ = contact_removed; - } - private: - // NearbyShareLocalDeviceDataManager: - - std::string id_; std::string device_name_; - std::vector publish_device_calls_; DeviceNameValidationResult next_validation_result_ = DeviceNameValidationResult::kValid; - - // Used to indicate whether the class is running in synchronization mode. - bool is_sync_mode_ = false; - bool publish_device_result_ = false; - bool publish_device_contact_removed_ = false; }; -} // namespace sharing -} // namespace nearby +} // namespace nearby::sharing #endif // THIRD_PARTY_NEARBY_SHARING_LOCAL_DEVICE_DATA_FAKE_NEARBY_SHARE_LOCAL_DEVICE_DATA_MANAGER_H_ diff --git a/sharing/local_device_data/nearby_share_local_device_data_manager.cc b/sharing/local_device_data/nearby_share_local_device_data_manager.cc index 843dc46c..ce2961a4 100644 --- a/sharing/local_device_data/nearby_share_local_device_data_manager.cc +++ b/sharing/local_device_data/nearby_share_local_device_data_manager.cc @@ -43,18 +43,6 @@ void NearbyShareLocalDeviceDataManager::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } -void NearbyShareLocalDeviceDataManager::Start() { - if (is_running_) return; - - is_running_ = true; -} - -void NearbyShareLocalDeviceDataManager::Stop() { - if (!is_running_) return; - - is_running_ = false; -} - void NearbyShareLocalDeviceDataManager::NotifyLocalDeviceDataChanged( bool did_device_name_change, bool did_full_name_change, bool did_icon_change) { diff --git a/sharing/local_device_data/nearby_share_local_device_data_manager.h b/sharing/local_device_data/nearby_share_local_device_data_manager.h index f850135c..5b57416a 100644 --- a/sharing/local_device_data/nearby_share_local_device_data_manager.h +++ b/sharing/local_device_data/nearby_share_local_device_data_manager.h @@ -17,9 +17,7 @@ #include -#include #include -#include #include "absl/strings/string_view.h" #include "internal/base/observer_list.h" @@ -45,34 +43,16 @@ class NearbyShareLocalDeviceDataManager { bool did_icon_change) = 0; }; - using UploadCompleteCallback = std::function; - using PublishDeviceCallback = - std::function; - NearbyShareLocalDeviceDataManager(); virtual ~NearbyShareLocalDeviceDataManager(); void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); - // Starts/Stops local-device-data task scheduling. - void Start(); - void Stop(); - bool is_running() { return is_running_; } - - // Returns the immutable ID generated for the local device, used to - // differentiate a user's devices when communicating with the Nearby server. - virtual std::string GetId() = 0; - // Returns the name of the local device, for example, "Josh's Chromebook." // This can be modified by SetDeviceName(). virtual std::string GetDeviceName() const = 0; - // Validates the provided device name and returns an error if validation - // fails. This is just a check and the device name is not persisted. - virtual DeviceNameValidationResult ValidateDeviceName( - absl::string_view name) = 0; - // Sets and persists the device name in prefs. The device name is first // validated and if validation fails and error is returned and the device name // is not persisted. The device name is *not* uploaded to the Nearby Share @@ -80,19 +60,12 @@ class NearbyShareLocalDeviceDataManager { // are notified via OnLocalDeviceDataChanged() if the device name changes. virtual DeviceNameValidationResult SetDeviceName(absl::string_view name) = 0; - // Calls Identity PublishDevice RPC to upload local device's public - // certificates. - virtual void PublishDevice( - std::vector certificates, - bool force_update_contacts, PublishDeviceCallback callback) = 0; - protected: void NotifyLocalDeviceDataChanged(bool did_device_name_change, bool did_full_name_change, bool did_icon_change); private: - bool is_running_ = false; nearby::ObserverList observers_; }; diff --git a/sharing/local_device_data/nearby_share_local_device_data_manager_impl.cc b/sharing/local_device_data/nearby_share_local_device_data_manager_impl.cc index 72bea149..deedc608 100644 --- a/sharing/local_device_data/nearby_share_local_device_data_manager_impl.cc +++ b/sharing/local_device_data/nearby_share_local_device_data_manager_impl.cc @@ -17,17 +17,11 @@ #include #include -#include #include #include #include -#include -#include -#include "absl/algorithm/algorithm.h" #include "absl/memory/memory.h" -#include "absl/status/statusor.h" -#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "internal/platform/device_info.h" @@ -38,25 +32,18 @@ #include "sharing/common/nearby_share_enums.h" #include "sharing/common/nearby_share_prefs.h" #include "sharing/internal/api/preference_manager.h" -#include "sharing/internal/api/sharing_rpc_client.h" #include "sharing/internal/base/utf_string_conversions.h" -#include "sharing/internal/public/context.h" -#include "sharing/internal/public/logging.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" #include "sharing/proto/device_rpc.pb.h" #include "sharing/proto/field_mask.pb.h" #include "sharing/proto/rpc_resources.pb.h" #include "sharing/proto/timestamp.pb.h" -#include "util/hash/highway_fingerprint.h" namespace nearby { namespace sharing { namespace { -using ::google::nearby::identity::v1::PublishDeviceRequest; -using ::google::nearby::identity::v1::PublishDeviceResponse; using ::nearby::api::DeviceInfo; using ::nearby::sharing::api::PreferenceManager; -using ::nearby::sharing::api::SharingRpcClientFactory; constexpr absl::string_view kDefaultDeviceName = "$0\'s $1"; @@ -86,16 +73,14 @@ NearbyShareLocalDeviceDataManagerImpl::Factory* // static std::unique_ptr NearbyShareLocalDeviceDataManagerImpl::Factory::Create( - Context* context, PreferenceManager& preference_manager, - AccountManager& account_manager, nearby::DeviceInfo& device_info, - SharingRpcClientFactory* rpc_client_factory) { + PreferenceManager& preference_manager, + AccountManager& account_manager, nearby::DeviceInfo& device_info) { if (test_factory_) { - return test_factory_->CreateInstance(context, rpc_client_factory); + return test_factory_->CreateInstance(); } return absl::WrapUnique(new NearbyShareLocalDeviceDataManagerImpl( - context, preference_manager, account_manager, device_info, - rpc_client_factory)); + preference_manager, account_manager, device_info)); } // static @@ -107,22 +92,15 @@ void NearbyShareLocalDeviceDataManagerImpl::Factory::SetFactoryForTesting( NearbyShareLocalDeviceDataManagerImpl::Factory::~Factory() = default; NearbyShareLocalDeviceDataManagerImpl::NearbyShareLocalDeviceDataManagerImpl( - Context* context, PreferenceManager& preference_manager, - AccountManager& account_manager, nearby::DeviceInfo& device_info, - SharingRpcClientFactory* rpc_client_factory) + PreferenceManager& preference_manager, AccountManager& account_manager, + nearby::DeviceInfo& device_info) : preference_manager_(preference_manager), account_manager_(account_manager), - device_info_(device_info), - nearby_identity_client_(rpc_client_factory->CreateIdentityInstance()), - executor_(context->CreateSequencedTaskRunner()) {} + device_info_(device_info) {} NearbyShareLocalDeviceDataManagerImpl:: ~NearbyShareLocalDeviceDataManagerImpl() = default; -std::string NearbyShareLocalDeviceDataManagerImpl::GetId() { - return preference_manager_.GetString(prefs::kNearbySharingDeviceIdName, ""); -} - std::string NearbyShareLocalDeviceDataManagerImpl::GetDeviceName() const { std::string device_name = preference_manager_.GetString( prefs::kNearbySharingDeviceNameName, std::string()); @@ -159,119 +137,6 @@ DeviceNameValidationResult NearbyShareLocalDeviceDataManagerImpl::SetDeviceName( return DeviceNameValidationResult::kValid; } -void NearbyShareLocalDeviceDataManagerImpl::PublishDevice( - std::vector certificates, - bool force_update_contacts, PublishDeviceCallback callback) { - executor_->PostTask([this, force_update_contacts, - certificates = std::move(certificates), - callback = std::move(callback)]() mutable { - if (!is_running()) { - LOG(WARNING) << __func__ - << ": [Call Identity API] no-op as manager is stopped."; - callback(/*success=*/false, /*contact_removed=*/false); - return; - } - std::string device_id = GetId(); - if (device_id.empty()) { - LOG(WARNING) << __func__ - << ": [Call Identity API] failed, device id is empty."; - callback(/*success=*/false, /*contact_removed=*/false); - return; - } - LOG(INFO) << __func__ << ": [Call Identity API] Upload " - << certificates.size() << " certificates."; - - PublishDeviceRequest request; - request.mutable_device()->set_name(absl::StrCat("devices/", device_id)); - LOG(INFO) << __func__ - << ": [Call Identity API] PublishDeviceRequest with Device.name: " - << request.device().name(); - request.mutable_device()->set_display_name(GetDeviceName()); - // Force update contacts call is right after CONTACT_GOOGLE_CONTACT_LATEST - // call and can use CONTACT_GOOGLE_CONTACT to save server side computation. - - request.mutable_device()->set_contact( - force_update_contacts - ? google::nearby::identity::v1::Device::CONTACT_GOOGLE_CONTACT - : google::nearby::identity::v1::Device:: - CONTACT_GOOGLE_CONTACT_LATEST); - - auto* new_self_credential = - request.mutable_device()->add_per_visibility_shared_credentials(); - new_self_credential->set_visibility( - google::nearby::identity::v1::PerVisibilitySharedCredentials:: - VISIBILITY_SELF); - auto* new_contacts_credential = - request.mutable_device()->add_per_visibility_shared_credentials(); - new_contacts_credential->set_visibility( - google::nearby::identity::v1::PerVisibilitySharedCredentials:: - VISIBILITY_CONTACTS); - - for (const auto& certificate : certificates) { - // Skip the certificate for deprecated SELECTED_CONTACTS. - if (certificate.for_selected_contacts()) { - continue; - } - google::nearby::identity::v1::SharedCredential* shared_credential; - if (certificate.for_self_share()) { - shared_credential = new_self_credential->add_shared_credentials(); - LOG(INFO) << __func__ << ": [Call Identity API] self_share"; - } else { - shared_credential = new_contacts_credential->add_shared_credentials(); - LOG(INFO) << __func__ << ": [Call Identity API] contacts_share"; - } - - shared_credential->set_id( - util_hash::HighwayFingerprint64(certificate.secret_id())); - shared_credential->set_data(certificate.SerializeAsString()); - shared_credential->set_data_type( - ::google::nearby::identity::v1::SharedCredential:: - DATA_TYPE_PUBLIC_CERTIFICATE); - *shared_credential->mutable_expiration_time() = certificate.end_time(); - LOG(INFO) << __func__ - << ": shared_credential.id(): " << shared_credential->id(); - } - nearby_identity_client_->PublishDevice( - request, [this, callback = std::move(callback)]( - const absl::StatusOr& response) { - // check whether the manager is running again - if (!is_running()) { - LOG(WARNING) - << __func__ - << ": [Call Identity API] manager is stopped after call."; - callback(/*success=*/false, /*contact_removed=*/false); - return; - } - if (!response.ok()) { - LOG(WARNING) - << __func__ - << ": [Call Identity API] Failed to get response from backend: " - << response.status(); - callback(/*success=*/false, /*contact_removed=*/false); - return; - } - - LOG(INFO) << __func__ - << ": [Call Identity API] Successfully published device."; - - // If contacts are removed, regenerate all Private certificates and - // make a 2nd PublishDevice RPC call. - bool need_another_call = false; - if (absl::linear_search( - response.value().contact_updates().begin(), - response.value().contact_updates().end(), - google::nearby::identity::v1::PublishDeviceResponse:: - CONTACT_UPDATE_REMOVED)) { - need_another_call = true; - LOG(INFO) - << __func__ - << ": [Call Identity API] need another PublishDevice call"; - } - callback(/*success=*/true, /*contact_removed=*/need_another_call); - }); - }); -} - std::string NearbyShareLocalDeviceDataManagerImpl::GetDefaultDeviceName() const { std::optional account = diff --git a/sharing/local_device_data/nearby_share_local_device_data_manager_impl.h b/sharing/local_device_data/nearby_share_local_device_data_manager_impl.h index 2b209b1f..176b3b94 100644 --- a/sharing/local_device_data/nearby_share_local_device_data_manager_impl.h +++ b/sharing/local_device_data/nearby_share_local_device_data_manager_impl.h @@ -17,24 +17,16 @@ #include #include -#include #include "absl/strings/string_view.h" #include "internal/platform/device_info.h" #include "internal/platform/implementation/account_manager.h" -#include "internal/platform/task_runner.h" #include "sharing/common/nearby_share_enums.h" #include "sharing/internal/api/preference_manager.h" -#include "sharing/internal/api/sharing_rpc_client.h" -#include "sharing/internal/public/context.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" #include "sharing/proto/rpc_resources.pb.h" -namespace nearby { -namespace sharing { - -class NearbyShareProfileInfoProvider; -class NearbyShareScheduler; +namespace nearby::sharing { // Implementation of NearbyShareLocalDeviceDataManager that persists device data // in prefs. All RPC-related calls are guarded by a timeout, so callbacks are @@ -47,17 +39,14 @@ class NearbyShareLocalDeviceDataManagerImpl class Factory { public: static std::unique_ptr Create( - Context* context, nearby::sharing::api::PreferenceManager& preference_manager, - AccountManager& account_manager, nearby::DeviceInfo& device_info, - nearby::sharing::api::SharingRpcClientFactory* rpc_client_factory); + AccountManager& account_manager, nearby::DeviceInfo& device_info); static void SetFactoryForTesting(Factory* test_factory); protected: virtual ~Factory(); - virtual std::unique_ptr CreateInstance( - Context* context, - nearby::sharing::api::SharingRpcClientFactory* rpc_client_factory) = 0; + virtual std::unique_ptr + CreateInstance() = 0; private: static Factory* test_factory_; @@ -65,23 +54,16 @@ class NearbyShareLocalDeviceDataManagerImpl ~NearbyShareLocalDeviceDataManagerImpl() override; - private: - NearbyShareLocalDeviceDataManagerImpl( - Context* context, - nearby::sharing::api::PreferenceManager& preference_manager, - AccountManager& account_manager, nearby::DeviceInfo& device_info, - nearby::sharing::api::SharingRpcClientFactory* rpc_client_factory); - // NearbyShareLocalDeviceDataManager: - std::string GetId() override; std::string GetDeviceName() const override; - DeviceNameValidationResult ValidateDeviceName( - absl::string_view name) override; DeviceNameValidationResult SetDeviceName(absl::string_view name) override; - void PublishDevice( - std::vector certificates, - bool force_update_contacts, PublishDeviceCallback callback) override; + private: + NearbyShareLocalDeviceDataManagerImpl( + nearby::sharing::api::PreferenceManager& preference_manager, + AccountManager& account_manager, nearby::DeviceInfo& device_info); + + DeviceNameValidationResult ValidateDeviceName(absl::string_view name); // Creates a default device name of the form "'s ." // For example, "Josh's Chromebook." If a given name cannot be found, returns @@ -92,12 +74,8 @@ class NearbyShareLocalDeviceDataManagerImpl nearby::sharing::api::PreferenceManager& preference_manager_; AccountManager& account_manager_; nearby::DeviceInfo& device_info_; - std::unique_ptr - nearby_identity_client_; - std::unique_ptr executor_; }; -} // namespace sharing -} // namespace nearby +} // namespace nearby::sharing #endif // THIRD_PARTY_NEARBY_SHARING_LOCAL_DEVICE_DATA_NEARBY_SHARE_LOCAL_DEVICE_DATA_MANAGER_IMPL_H_ diff --git a/sharing/local_device_data/nearby_share_local_device_data_manager_impl_test.cc b/sharing/local_device_data/nearby_share_local_device_data_manager_impl_test.cc index fa597d55..ca3fcdad 100644 --- a/sharing/local_device_data/nearby_share_local_device_data_manager_impl_test.cc +++ b/sharing/local_device_data/nearby_share_local_device_data_manager_impl_test.cc @@ -19,80 +19,31 @@ #include #include #include -#include #include #include "gtest/gtest.h" -#include "absl/status/status.h" -#include "absl/status/statusor.h" -#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" -#include "absl/time/time.h" #include "internal/platform/implementation/account_manager.h" #include "internal/test/fake_account_manager.h" #include "internal/test/fake_device_info.h" -#include "internal/test/fake_task_runner.h" -#include "proto/identity/v1/resources.pb.h" -#include "proto/identity/v1/rpcs.pb.h" #include "sharing/common/nearby_share_enums.h" #include "sharing/common/nearby_share_prefs.h" -#include "sharing/internal/api/fake_nearby_share_client.h" -#include "sharing/internal/public/logging.h" -#include "sharing/internal/test/fake_context.h" #include "sharing/internal/test/fake_preference_manager.h" #include "sharing/local_device_data/nearby_share_local_device_data_manager.h" -#include "sharing/proto/device_rpc.pb.h" -#include "sharing/proto/rpc_resources.pb.h" -#include "sharing/proto/timestamp.pb.h" -#include "sharing/scheduling/fake_nearby_share_scheduler_factory.h" -#include "sharing/scheduling/nearby_share_scheduler_factory.h" -namespace nearby { -namespace sharing { +namespace nearby::sharing { namespace { -using UpdateDeviceResponse = nearby::sharing::proto::UpdateDeviceResponse; -using google::nearby::identity::v1::PublishDeviceResponse; -using Contact = nearby::sharing::proto::Contact; - const char kDefaultDeviceName[] = "$0\'s $1"; const char kFakeDeviceName[] = "My Cool Chromebook"; const char kFakeEmptyDeviceName[] = ""; -const char kFakeFullName[] = "Barack Obama"; const char kFakeGivenName[] = "Barack奥巴马"; -const char kFakeIconUrl[] = "https://www.google.com"; -const char kFakeIconToken[] = "token"; const char kFakeInvalidDeviceName[] = "\xC0"; const char kFakeTooLongDeviceName[] = "this string is 33 bytes in UTF-8!"; const char kFakeTooLongGivenName[] = "this is a 33-byte string in utf-8"; constexpr char kTestAccountId[] = "test_account_id"; constexpr char kTestProfileUserName[] = "test@google.com"; -constexpr absl::string_view kTestDeviceId = "1234567890"; - -absl::StatusOr CreateResponse( - const std::optional& full_name, - const std::optional& icon_url, - const std::optional& icon_token) { - absl::StatusOr result; - UpdateDeviceResponse response; - if (full_name) response.set_person_name(*full_name); - - if (icon_url) response.set_image_url(*icon_url); - - if (icon_token) response.set_image_token(*icon_token); - - result = response; - return result; -} - -std::vector GetFakeContacts() { - Contact contact1; - Contact contact2; - contact1.mutable_identifier()->set_account_name("account1"); - contact2.mutable_identifier()->set_account_name("account2"); - return {std::move(contact1), std::move(contact2)}; -} class NearbyShareLocalDeviceDataManagerImplTest : public ::testing::Test, @@ -122,7 +73,6 @@ class NearbyShareLocalDeviceDataManagerImplTest void SetUp() override { prefs::RegisterNearbySharingPrefs(preference_manager_); - NearbyShareSchedulerFactory::SetFactoryForTesting(&scheduler_factory_); AccountManager::Account account; account.id = kTestAccountId; @@ -131,10 +81,6 @@ class NearbyShareLocalDeviceDataManagerImplTest fake_account_manager_.SetAccount(account); } - void TearDown() override { - NearbyShareSchedulerFactory::SetFactoryForTesting(nullptr); - } - // NearbyShareLocalDeviceDataManager::Observer: void OnLocalDeviceDataChanged(bool did_device_name_change, bool did_full_name_change, @@ -145,12 +91,8 @@ class NearbyShareLocalDeviceDataManagerImplTest void CreateManager() { manager_ = NearbyShareLocalDeviceDataManagerImpl::Factory::Create( - &context_, preference_manager_, fake_account_manager_, - fake_device_info_, &nearby_client_factory_); + preference_manager_, fake_account_manager_, fake_device_info_); manager_->AddObserver(this); - ++num_manager_creations_; - num_download_device_data_ = 0; - manager_->Start(); } void DestroyManager() { @@ -174,50 +116,14 @@ class NearbyShareLocalDeviceDataManagerImplTest return fake_device_info_.GetDeviceTypeName(); } - FakeNearbyShareClient* client() { - return nearby_client_factory_.instances().back(); - } - - FakeNearbyIdentityClient* identity_client() { - return nearby_client_factory_.identity_instances().back(); - } - - void SetDeviceId(absl::string_view id) { - preference_manager_.SetString(prefs::kNearbySharingDeviceIdName, id); - } - - void Sync() { - EXPECT_TRUE(context_.last_sequenced_task_runner()->SyncWithTimeout( - absl::Milliseconds(1000))); - } - protected: nearby::FakePreferenceManager preference_manager_; nearby::FakeAccountManager fake_account_manager_; nearby::FakeDeviceInfo fake_device_info_; - nearby::FakeContext context_; - size_t num_manager_creations_ = 0; - size_t num_download_device_data_ = 0; std::vector notifications_; - FakeNearbyShareClientFactory nearby_client_factory_; - FakeNearbyShareSchedulerFactory scheduler_factory_; std::unique_ptr manager_; }; -TEST_F(NearbyShareLocalDeviceDataManagerImplTest, DeviceId) { - CreateManager(); - SetDeviceId(kTestDeviceId); - // A 10-character alphanumeric ID is automatically generated if one doesn't - // already exist. - std::string id = manager()->GetId(); - EXPECT_EQ(id, kTestDeviceId); - - // The ID is persisted. - DestroyManager(); - CreateManager(); - EXPECT_EQ(manager()->GetId(), id); -} - TEST_F(NearbyShareLocalDeviceDataManagerImplTest, DefaultDeviceName) { CreateManager(); @@ -242,18 +148,6 @@ TEST_F(NearbyShareLocalDeviceDataManagerImplTest, DefaultDeviceName) { EXPECT_EQ(kNearbyShareDeviceNameMaxLength, manager()->GetDeviceName().size()); } -TEST_F(NearbyShareLocalDeviceDataManagerImplTest, ValidateDeviceName) { - CreateManager(); - EXPECT_EQ(manager()->ValidateDeviceName(kFakeDeviceName), - DeviceNameValidationResult::kValid); - EXPECT_EQ(manager()->ValidateDeviceName(kFakeEmptyDeviceName), - DeviceNameValidationResult::kErrorEmpty); - EXPECT_EQ(manager()->ValidateDeviceName(kFakeTooLongDeviceName), - DeviceNameValidationResult::kErrorTooLong); - EXPECT_EQ(manager()->ValidateDeviceName(kFakeInvalidDeviceName), - DeviceNameValidationResult::kErrorNotValidUtf8); -} - TEST_F(NearbyShareLocalDeviceDataManagerImplTest, SetDeviceName) { CreateManager(); @@ -292,220 +186,5 @@ TEST_F(NearbyShareLocalDeviceDataManagerImplTest, SetDeviceName) { EXPECT_EQ(manager()->GetDeviceName(), kFakeDeviceName); } -std::vector GetTestCertificates() { - nearby::sharing::proto::PublicCertificate cert1; - cert1.set_secret_id("id1"); - cert1.set_for_self_share(true); - cert1.mutable_end_time()->set_seconds(1000); - cert1.mutable_end_time()->set_nanos(2000); - - nearby::sharing::proto::PublicCertificate cert3; - cert3.set_secret_id("id3"); - cert3.set_for_self_share(true); - cert3.mutable_end_time()->set_seconds(3000); - cert3.mutable_end_time()->set_nanos(300); - - nearby::sharing::proto::PublicCertificate cert2; - cert2.set_secret_id("id2"); - cert2.set_for_self_share(false); - cert2.mutable_end_time()->set_seconds(2000); - cert2.mutable_end_time()->set_nanos(200); - - nearby::sharing::proto::PublicCertificate cert4; - cert4.set_secret_id("id4"); - cert4.set_for_self_share(false); - cert4.mutable_end_time()->set_seconds(4000); - cert4.mutable_end_time()->set_nanos(400); - - nearby::sharing::proto::PublicCertificate cert5; - cert5.set_secret_id("id5"); - cert5.set_for_self_share(false); - cert5.set_for_selected_contacts(true); - cert5.mutable_end_time()->set_seconds(2500); - cert5.mutable_end_time()->set_nanos(250); - - nearby::sharing::proto::PublicCertificate cert6; - cert6.set_secret_id("id6"); - cert6.set_for_self_share(false); - cert6.set_for_selected_contacts(true); - cert6.mutable_end_time()->set_seconds(4500); - cert6.mutable_end_time()->set_nanos(450); - return {cert1, cert2, cert3, cert4, cert5, cert6}; -} - -TEST_F(NearbyShareLocalDeviceDataManagerImplTest, - PublishDeviceInitialCall_ContactUpdateAdded) { - CreateManager(); - SetDeviceId(kTestDeviceId); - bool returned_success; - bool returned_make_another_call; - PublishDeviceResponse response; - response.add_contact_updates(google::nearby::identity::v1:: - PublishDeviceResponse::CONTACT_UPDATE_ADDED); - - identity_client()->SetPublishDeviceResponse( - absl::StatusOr(response)); - manager()->PublishDevice(GetTestCertificates(), /*is_second_call=*/false, - [&returned_success, &returned_make_another_call]( - bool success, bool make_another_call) { - returned_success = success; - returned_make_another_call = make_another_call; - }); - - Sync(); - auto request = identity_client()->publish_device_requests().back(); - EXPECT_EQ(request.device().name(), - absl::StrCat("devices/", manager()->GetId())); - EXPECT_EQ(request.device().display_name(), "Barack奥巴马's PC"); - EXPECT_EQ( - request.device().contact(), - google::nearby::identity::v1::Device::CONTACT_GOOGLE_CONTACT_LATEST); - ASSERT_EQ(request.device().per_visibility_shared_credentials_size(), 2); - - auto self_credential = request.device().per_visibility_shared_credentials(0); - EXPECT_EQ(self_credential.visibility(), - google::nearby::identity::v1::PerVisibilitySharedCredentials:: - VISIBILITY_SELF); - EXPECT_EQ(self_credential.shared_credentials_size(), 2); - EXPECT_EQ(self_credential.shared_credentials(0).id(), 4993322223562966528); - - ASSERT_EQ(GetTestCertificates().size(), 6); - EXPECT_EQ(self_credential.shared_credentials(0).data(), - GetTestCertificates().at(0).SerializeAsString()); - EXPECT_EQ(self_credential.shared_credentials(0).data_type(), - google::nearby::identity::v1::SharedCredential:: - DATA_TYPE_PUBLIC_CERTIFICATE); - EXPECT_EQ(self_credential.shared_credentials(0).expiration_time().seconds(), - 1000); - EXPECT_EQ(self_credential.shared_credentials(0).expiration_time().nanos(), - 2000); - - EXPECT_EQ(self_credential.shared_credentials(1).id(), 2903692628687846585); - EXPECT_EQ(self_credential.shared_credentials(1).data(), - GetTestCertificates().at(2).SerializeAsString()); - EXPECT_EQ(self_credential.shared_credentials(1).data_type(), - google::nearby::identity::v1::SharedCredential:: - DATA_TYPE_PUBLIC_CERTIFICATE); - EXPECT_EQ(self_credential.shared_credentials(1).expiration_time().seconds(), - 3000); - EXPECT_EQ(self_credential.shared_credentials(1).expiration_time().nanos(), - 300); - - auto contact_credential = - request.device().per_visibility_shared_credentials(1); - EXPECT_EQ(contact_credential.visibility(), - google::nearby::identity::v1::PerVisibilitySharedCredentials:: - VISIBILITY_CONTACTS); - ASSERT_EQ(contact_credential.shared_credentials_size(), 2); - EXPECT_EQ(contact_credential.shared_credentials(0).id(), - -5684021477085783942); - EXPECT_EQ(contact_credential.shared_credentials(0).data(), - GetTestCertificates().at(1).SerializeAsString()); - EXPECT_EQ(contact_credential.shared_credentials(0).data_type(), - google::nearby::identity::v1::SharedCredential:: - DATA_TYPE_PUBLIC_CERTIFICATE); - EXPECT_EQ( - contact_credential.shared_credentials(0).expiration_time().seconds(), - 2000); - EXPECT_EQ(contact_credential.shared_credentials(0).expiration_time().nanos(), - 200); - - EXPECT_TRUE(returned_success); - EXPECT_FALSE(returned_make_another_call); -} - -TEST_F(NearbyShareLocalDeviceDataManagerImplTest, - PublishDeviceInitialCall_ContactUpdateRemoved) { - CreateManager(); - SetDeviceId(kTestDeviceId); - bool returned_success; - bool returned_make_another_call; - PublishDeviceResponse response; - response.add_contact_updates( - google::nearby::identity::v1::PublishDeviceResponse:: - CONTACT_UPDATE_REMOVED); - - identity_client()->SetPublishDeviceResponse( - absl::StatusOr(response)); - manager()->PublishDevice(GetTestCertificates(), /*is_second_call=*/false, - [&returned_success, &returned_make_another_call]( - bool success, bool make_another_call) { - returned_success = success; - returned_make_another_call = make_another_call; - }); - - Sync(); - - EXPECT_TRUE(returned_success); - // 2nd call is needed to regenerate all Private certificates. - EXPECT_TRUE(returned_make_another_call); -} - -TEST_F(NearbyShareLocalDeviceDataManagerImplTest, - PublishDeviceSecondCall_ContactUnchanged) { - CreateManager(); - SetDeviceId(kTestDeviceId); - bool returned_success; - bool returned_make_another_call; - PublishDeviceResponse response; - - identity_client()->SetPublishDeviceResponse( - absl::StatusOr(response)); - manager()->PublishDevice(GetTestCertificates(), /*is_second_call=*/true, - [&returned_success, &returned_make_another_call]( - bool success, bool make_another_call) { - returned_success = success; - returned_make_another_call = make_another_call; - }); - - Sync(); - auto request = identity_client()->publish_device_requests().back(); - - EXPECT_EQ(request.device().contact(), - google::nearby::identity::v1::Device::CONTACT_GOOGLE_CONTACT); - - EXPECT_TRUE(returned_success); - // Contacts are not changed, no need to make another call. - EXPECT_FALSE(returned_make_another_call); -} - -TEST_F(NearbyShareLocalDeviceDataManagerImplTest, PublishDevice_Failure) { - CreateManager(); - SetDeviceId(kTestDeviceId); - bool returned_success; - bool returned_make_another_call; - identity_client()->SetPublishDeviceResponse(absl::InternalError("")); - manager()->PublishDevice(GetTestCertificates(), /*is_second_call=*/false, - [&returned_success, &returned_make_another_call]( - bool success, bool make_another_call) { - returned_success = success; - returned_make_another_call = make_another_call; - }); - - Sync(); - EXPECT_FALSE(returned_success); - EXPECT_FALSE(returned_make_another_call); -} - -TEST_F(NearbyShareLocalDeviceDataManagerImplTest, - PublishDevice_FailsWithEmptyDeviceId) { - CreateManager(); - bool returned_success; - PublishDeviceResponse response; - - identity_client()->SetPublishDeviceResponse( - absl::StatusOr(response)); - manager()->PublishDevice(GetTestCertificates(), /*is_second_call=*/true, - [&returned_success]( - bool success, bool make_another_call) { - returned_success = success; - }); - - Sync(); - EXPECT_FALSE(returned_success); - ASSERT_EQ(identity_client()->publish_device_requests().size(), 0); -} - } // namespace -} // namespace sharing -} // namespace nearby +} // namespace nearby::sharing diff --git a/sharing/nearby_sharing_service_impl.cc b/sharing/nearby_sharing_service_impl.cc index 047b71ff..1b90f1a0 100644 --- a/sharing/nearby_sharing_service_impl.cc +++ b/sharing/nearby_sharing_service_impl.cc @@ -226,8 +226,7 @@ NearbySharingServiceImpl::NearbySharingServiceImpl( &analytics_recorder_)), local_device_data_manager_( NearbyShareLocalDeviceDataManagerImpl::Factory::Create( - context_, preference_manager_, account_manager_, device_info_, - nearby_share_client_factory_.get())), + preference_manager_, account_manager_, device_info_)), contact_manager_(NearbyShareContactManagerImpl::Factory::Create( context_, account_manager_, nearby_share_client_factory_.get())), nearby_fast_initiation_( @@ -247,7 +246,7 @@ NearbySharingServiceImpl::NearbySharingServiceImpl( certificate_manager_ = NearbyShareCertificateManagerImpl::Factory::Create( context_, sharing_platform, local_device_data_manager_.get(), - contact_manager_.get(), profile_path, nearby_share_client_factory_.get()), + profile_path, nearby_share_client_factory_.get()), certificate_manager_->AddObserver(this); context_->GetConnectivityManager()->RegisterConnectionListener( @@ -275,7 +274,6 @@ NearbySharingServiceImpl::NearbySharingServiceImpl( LOG(INFO) << __func__ << ": Set custom save path: " << custom_save_path; nearby_connections_manager_->SetCustomSavePath(custom_save_path); - local_device_data_manager_->Start(); certificate_manager_->Start(); update_file_paths_in_progress_ = false; @@ -316,7 +314,6 @@ void NearbySharingServiceImpl::Shutdown( settings_->RemoveSettingsObserver(this); - local_device_data_manager_->Stop(); certificate_manager_->Stop(); is_shutting_down_ = nullptr; @@ -3493,7 +3490,6 @@ void NearbySharingServiceImpl::ResetAllSettings(bool logout) { StopAdvertising(); StopScanning(); nearby_connections_manager_->Shutdown(); - local_device_data_manager_->Stop(); certificate_manager_->Stop(); // Reset preferences for logout. @@ -3538,7 +3534,6 @@ void NearbySharingServiceImpl::ResetAllSettings(bool logout) { } // Start services again. - local_device_data_manager_->Start(); certificate_manager_->Start(); InvalidateSurfaceState(); diff --git a/sharing/nearby_sharing_settings.cc b/sharing/nearby_sharing_settings.cc index 0592b970..38897605 100644 --- a/sharing/nearby_sharing_settings.cc +++ b/sharing/nearby_sharing_settings.cc @@ -209,13 +209,6 @@ void NearbyShareSettings::SetFastInitiationNotificationState( static_cast(state)); } -void NearbyShareSettings::ValidateDeviceName( - absl::string_view device_name, - std::function callback) { - std::move(callback)( - local_device_data_manager_->ValidateDeviceName(device_name)); -} - void NearbyShareSettings::SetDeviceName( absl::string_view device_name, std::function callback) { diff --git a/sharing/nearby_sharing_settings.h b/sharing/nearby_sharing_settings.h index 7105977b..09fa7016 100644 --- a/sharing/nearby_sharing_settings.h +++ b/sharing/nearby_sharing_settings.h @@ -168,9 +168,6 @@ class NearbyShareSettings void RemoveSettingsObserver(Observer* observer); void SetFastInitiationNotificationState( proto::FastInitiationNotificationState state); - void ValidateDeviceName( - absl::string_view device_name, - std::function callback); void SetDeviceName(absl::string_view device_name, std::function callback); void SetDataUsage(proto::DataUsage data_usage); diff --git a/sharing/nearby_sharing_settings_test.cc b/sharing/nearby_sharing_settings_test.cc index 422c662e..7dd3e1f0 100644 --- a/sharing/nearby_sharing_settings_test.cc +++ b/sharing/nearby_sharing_settings_test.cc @@ -188,22 +188,6 @@ TEST_F(NearbyShareSettingsTest, GetAndSetIsFastInitiationHardwareSupported) { EXPECT_TRUE(settings()->is_fast_initiation_hardware_supported()); } -TEST_F(NearbyShareSettingsTest, ValidateDeviceName) { - auto result = DeviceNameValidationResult::kValid; - local_device_data_manager_.set_next_validation_result( - DeviceNameValidationResult::kErrorEmpty); - settings()->ValidateDeviceName( - "", [&result](DeviceNameValidationResult res) { result = res; }); - EXPECT_EQ(result, DeviceNameValidationResult::kErrorEmpty); - - local_device_data_manager_.set_next_validation_result( - DeviceNameValidationResult::kValid); - settings()->ValidateDeviceName( - "this string is 32 bytes in UTF-8", - [&result](DeviceNameValidationResult res) { result = res; }); - EXPECT_EQ(result, DeviceNameValidationResult::kValid); -} - TEST_F(NearbyShareSettingsTest, GetAndSetDeviceName) { std::string name = "not_the_default"; EXPECT_EQ(kDefaultDeviceName, settings()->GetDeviceName());