Move PublishDevice rpc from LocalDeviceDataManager to CertificateManager.

PiperOrigin-RevId: 796916479
This commit is contained in:
Francis Tsui
2025-08-19 09:59:22 -07:00
committed by Copybara-Service
parent 804e1a429c
commit c0a2194ab1
24 changed files with 318 additions and 869 deletions
+4 -8
View File
@@ -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",
],
@@ -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<NearbyShareCertificateManager>
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<FakeNearbyShareCertificateManager>();
instances_.push_back(instance.get());
@@ -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<NearbyShareCertificateManager> CreateInstance(
Context* context,
NearbyShareLocalDeviceDataManager* local_device_data_manager,
NearbyShareContactManager* contact_manager,
const FilePath& profile_path,
nearby::sharing::api::SharingRpcClientFactory* client_factory) override;
@@ -21,6 +21,7 @@
#include <vector>
#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<NearbySharePrivateCertificate>
FakeNearbyShareCertificateStorage::GetPrivateCertificates() {
absl::MutexLock lock(mutex_);
return private_certificates_;
}
@@ -120,6 +122,7 @@ FakeNearbyShareCertificateStorage::NextPublicCertificateExpirationTime() const {
void FakeNearbyShareCertificateStorage::ReplacePrivateCertificates(
absl::Span<const NearbySharePrivateCertificate> private_certificates) {
absl::MutexLock lock(mutex_);
private_certificates_ = std::vector<NearbySharePrivateCertificate>(
private_certificates.begin(), private_certificates.end());
}
@@ -20,7 +20,9 @@
#include <string>
#include <vector>
#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<std::string> public_certificate_ids_;
std::vector<NearbySharePrivateCertificate> private_certificates_;
std::vector<NearbySharePrivateCertificate> private_certificates_
ABSL_GUARDED_BY(mutex_);
std::vector<PublicCertificateCallback> get_public_certificates_callbacks_;
std::function<void(
bool, std::unique_ptr<nearby::sharing::proto::PublicCertificate>)>
@@ -28,13 +28,13 @@
#include <utility>
#include <vector>
#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<DeviceVisibility, 2> kVisibilities = {
DeviceVisibility::DEVICE_VISIBILITY_ALL_CONTACTS,
DeviceVisibility::DEVICE_VISIBILITY_SELF_SHARE,
@@ -185,14 +188,13 @@ std::unique_ptr<NearbyShareCertificateManager>
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<PublicCertificateDatabase> 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<CertificateDownloadContext>(
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<PublicCertificate>& 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<NearbySharePrivateCertificate>& 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<PublicCertificate> 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<PublicCertificate> 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<NearbySharePrivateCertificate>& 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, &regenerate_certificates,
&notification](bool success, bool contact_removed) {
upload_certificates_succeeded = success;
regenerate_certificates = contact_removed;
&notification](const absl::StatusOr<PublishDeviceResponse>& 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;
}
@@ -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<NearbyShareCertificateManager> 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<nearby::sharing::api::PublicCertificateDatabase>
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<nearby::sharing::proto::PublicCertificate>&
certificates);
void AddCertifactesToPublishDeviceRequest(
const std::vector<NearbySharePrivateCertificate>& 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<nearby::sharing::api::IdentityRpcClient>
@@ -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<FakeNearbyShareLocalDeviceDataManager>(
kDefaultDeviceName);
local_device_data_manager_->set_is_sync_mode(true);
local_device_data_manager_->SetId(kDeviceId);
contact_manager_ = std::make_unique<FakeNearbyShareContactManager>();
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<absl::StatusOr<PublishDeviceResponse>> 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<QuerySharedCredentialsRequest> 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<NearbySharePrivateCertificate> 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);
}
@@ -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
+3
View File
@@ -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",
],
@@ -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<void(const absl::StatusOr<
proto::ListContactPeopleResponse>& response) &&>
absl::AnyInvocable<void(
const absl::StatusOr<proto::ListContactPeopleResponse>& 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<QuerySharedCredentialsResponse>& response) &&>
callback) {
query_shared_credentials_requests_.emplace_back(request);
if (query_shared_credentials_responses_.empty()) {
std::move(callback)(absl::NotFoundError(""));
return;
absl::StatusOr<QuerySharedCredentialsResponse> 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<PublishDeviceResponse>& response) &&>
callback) {
publish_device_requests_.emplace_back(request);
std::move(callback)(publish_device_response_);
absl::StatusOr<PublishDeviceResponse> 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<google::nearby::identity::v1::
GetAccountInfoResponse>& response) &&>
void(const absl::StatusOr<GetAccountInfoResponse>& response) &&>
callback) {
get_account_info_requests_.emplace_back(request);
std::move(callback)(get_account_info_response_);
absl::StatusOr<GetAccountInfoResponse> 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<nearby::sharing::api::SharingRpcClient>
+22 -11
View File
@@ -18,8 +18,10 @@
#include <memory>
#include <vector>
#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<google::nearby::identity::v1::PublishDeviceRequest>&
publish_device_requests() {
absl::MutexLock lock(mutex_);
return publish_device_requests_;
}
std::vector<google::nearby::identity::v1::QuerySharedCredentialsRequest>&
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<google::nearby::identity::v1::PublishDeviceResponse>
response) {
publish_device_response_ = response;
void SetPublishDeviceResponses(
std::vector<
absl::StatusOr<google::nearby::identity::v1::PublishDeviceResponse>>
responses) {
absl::MutexLock lock(mutex_);
publish_device_responses_ = responses;
}
void QuerySharedCredentials(
@@ -101,6 +107,7 @@ class FakeNearbyIdentityClient
std::vector<absl::StatusOr<
google::nearby::identity::v1::QuerySharedCredentialsResponse>>
responses) {
absl::MutexLock lock(mutex_);
query_shared_credentials_responses_ = responses;
}
@@ -114,24 +121,28 @@ class FakeNearbyIdentityClient
void SetGetAccountInfoResponse(
absl::StatusOr<google::nearby::identity::v1::GetAccountInfoResponse>
response) {
absl::MutexLock lock(mutex_);
get_account_info_response_ = response;
}
private:
absl::Mutex mutex_;
std::vector<google::nearby::identity::v1::PublishDeviceRequest>
publish_device_requests_;
absl::StatusOr<google::nearby::identity::v1::PublishDeviceResponse>
publish_device_response_;
publish_device_requests_ ABSL_GUARDED_BY(mutex_);
std::vector<
absl::StatusOr<google::nearby::identity::v1::PublishDeviceResponse>>
publish_device_responses_ ABSL_GUARDED_BY(mutex_);
std::vector<google::nearby::identity::v1::QuerySharedCredentialsRequest>
query_shared_credentials_requests_;
query_shared_credentials_requests_ ABSL_GUARDED_BY(mutex_);
std::vector<absl::StatusOr<
google::nearby::identity::v1::QuerySharedCredentialsResponse>>
query_shared_credentials_responses_;
query_shared_credentials_responses_ ABSL_GUARDED_BY(mutex_);
std::vector<google::nearby::identity::v1::GetAccountInfoRequest>
get_account_info_requests_;
get_account_info_requests_ ABSL_GUARDED_BY(mutex_);
absl::StatusOr<google::nearby::identity::v1::GetAccountInfoResponse>
get_account_info_response_;
get_account_info_response_ ABSL_GUARDED_BY(mutex_);
};
class FakeNearbyShareClientFactory
+1 -21
View File
@@ -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",
],
)
@@ -16,38 +16,19 @@
#include <memory>
#include <string>
#include <utility>
#include <vector>
#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<NearbyShareLocalDeviceDataManager>
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<FakeNearbyShareLocalDeviceDataManager>(
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<nearby::sharing::proto::PublicCertificate> 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
@@ -19,19 +19,14 @@
#include <memory>
#include <string>
#include <utility>
#include <vector>
#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<NearbyShareLocalDeviceDataManager> CreateInstance(
nearby::Context* context,
nearby::sharing::api::SharingRpcClientFactory* rpc_client_factory)
std::unique_ptr<NearbyShareLocalDeviceDataManager> CreateInstance()
override;
private:
std::vector<FakeNearbyShareLocalDeviceDataManager*> instances_;
nearby::sharing::api::SharingRpcClientFactory* latest_rpc_client_factory_ =
nullptr;
};
struct PublishDeviceCall {
PublishDeviceCall(
std::vector<nearby::sharing::proto::PublicCertificate> 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<nearby::sharing::proto::PublicCertificate> 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<nearby::sharing::proto::PublicCertificate> 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<PublishDeviceCall>& 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<PublishDeviceCall> 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_
@@ -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) {
@@ -17,9 +17,7 @@
#include <stddef.h>
#include <functional>
#include <string>
#include <vector>
#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<void(bool success)>;
using PublishDeviceCallback =
std::function<void(bool success, bool contact_removed)>;
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<nearby::sharing::proto::PublicCertificate> 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<Observer> observers_;
};
@@ -17,17 +17,11 @@
#include <stddef.h>
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#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<NearbyShareLocalDeviceDataManager>
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<nearby::sharing::proto::PublicCertificate> 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<PublishDeviceResponse>& 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<AccountManager::Account> account =
@@ -17,24 +17,16 @@
#include <memory>
#include <string>
#include <vector>
#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<NearbyShareLocalDeviceDataManager> 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<NearbyShareLocalDeviceDataManager> CreateInstance(
Context* context,
nearby::sharing::api::SharingRpcClientFactory* rpc_client_factory) = 0;
virtual std::unique_ptr<NearbyShareLocalDeviceDataManager>
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<nearby::sharing::proto::PublicCertificate> 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 "<given name>'s <device type>."
// 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::sharing::api::IdentityRpcClient>
nearby_identity_client_;
std::unique_ptr<TaskRunner> executor_;
};
} // namespace sharing
} // namespace nearby
} // namespace nearby::sharing
#endif // THIRD_PARTY_NEARBY_SHARING_LOCAL_DEVICE_DATA_NEARBY_SHARE_LOCAL_DEVICE_DATA_MANAGER_IMPL_H_
@@ -19,80 +19,31 @@
#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#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<UpdateDeviceResponse> CreateResponse(
const std::optional<std::string>& full_name,
const std::optional<std::string>& icon_url,
const std::optional<std::string>& icon_token) {
absl::StatusOr<UpdateDeviceResponse> 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<Contact> 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<ObserverNotification> notifications_;
FakeNearbyShareClientFactory nearby_client_factory_;
FakeNearbyShareSchedulerFactory scheduler_factory_;
std::unique_ptr<NearbyShareLocalDeviceDataManager> 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<nearby::sharing::proto::PublicCertificate> 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<PublishDeviceResponse>(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<PublishDeviceResponse>(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<PublishDeviceResponse>(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<PublishDeviceResponse>(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
+2 -7
View File
@@ -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();
-7
View File
@@ -209,13 +209,6 @@ void NearbyShareSettings::SetFastInitiationNotificationState(
static_cast<int>(state));
}
void NearbyShareSettings::ValidateDeviceName(
absl::string_view device_name,
std::function<void(DeviceNameValidationResult)> callback) {
std::move(callback)(
local_device_data_manager_->ValidateDeviceName(device_name));
}
void NearbyShareSettings::SetDeviceName(
absl::string_view device_name,
std::function<void(DeviceNameValidationResult)> callback) {
-3
View File
@@ -168,9 +168,6 @@ class NearbyShareSettings
void RemoveSettingsObserver(Observer* observer);
void SetFastInitiationNotificationState(
proto::FastInitiationNotificationState state);
void ValidateDeviceName(
absl::string_view device_name,
std::function<void(DeviceNameValidationResult)> callback);
void SetDeviceName(absl::string_view device_name,
std::function<void(DeviceNameValidationResult)> callback);
void SetDataUsage(proto::DataUsage data_usage);
-16
View File
@@ -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());