libweave: Buffet includes only weave/include files

External components should include only weave/include files

BUG=brillo:1242
TEST='FEATURES=test emerge-gizmo buffet'

Change-Id: I39edb5662694be23afa2a09aaca39f041e2d009b
Reviewed-on: https://chromium-review.googlesource.com/285673
Trybot-Ready: Vitaly Buka <vitalybuka@chromium.org>
Tested-by: Vitaly Buka <vitalybuka@chromium.org>
Reviewed-by: Alex Vakulenko <avakulenko@chromium.org>
Commit-Queue: Vitaly Buka <vitalybuka@chromium.org>
diff --git a/buffet/manager.cc b/buffet/manager.cc
index f7ecc0e..3ba5f5f 100644
--- a/buffet/manager.cc
+++ b/buffet/manager.cc
@@ -23,34 +23,35 @@
 #include <dbus/object_path.h>
 #include <dbus/values_util.h>
 
-#include "libweave/src/base_api_handler.h"
-#include "libweave/src/commands/command_instance.h"
-#include "libweave/src/commands/schema_constants.h"
-#include "libweave/src/privet/constants.h"
-#include "libweave/src/privet/security_manager.h"
-#include "libweave/src/privet/shill_client.h"
-#include "libweave/src/privet/wifi_bootstrap_manager.h"
-#include "libweave/src/states/state_change_queue.h"
-#include "libweave/src/states/state_manager.h"
-#include "libweave/src/storage_impls.h"
-
 using chromeos::dbus_utils::AsyncEventSequencer;
 using chromeos::dbus_utils::ExportedObjectManager;
-namespace privet = weave::privet;
 
 namespace buffet {
 
 namespace {
 
-// Max of 100 state update events should be enough in the queue.
-const size_t kMaxStateChangeQueueSize = 100;
-// The number of seconds each HTTP request will be allowed before timing out.
-const int kRequestTimeoutSeconds = 30;
-
 const char kPairingSessionIdKey[] = "sessionId";
 const char kPairingModeKey[] = "mode";
 const char kPairingCodeKey[] = "code";
 
+const char kErrorDomain[] = "buffet";
+const char kNotImplemented[] = "notImplemented";
+
+std::string StatusToString(weave::RegistrationStatus status) {
+  switch (status) {
+    case weave::RegistrationStatus::kUnconfigured:
+      return "unconfigured";
+    case weave::RegistrationStatus::kConnecting:
+      return "connecting";
+    case weave::RegistrationStatus::kConnected:
+      return "connected";
+    case weave::RegistrationStatus::kInvalidCredentials:
+      return "invalid_credentials";
+  }
+  CHECK(0) << "Unknown status";
+  return "unknown";
+}
+
 }  // anonymous namespace
 
 Manager::Manager(const base::WeakPtr<ExportedObjectManager>& object_manager)
@@ -62,108 +63,57 @@
 Manager::~Manager() {
 }
 
-void Manager::Start(const Options& options, AsyncEventSequencer* sequencer) {
-  command_manager_ =
-      std::make_shared<weave::CommandManager>(dbus_object_.GetObjectManager());
-  command_manager_->AddOnCommandDefChanged(base::Bind(
+void Manager::Start(const weave::Device::Options& options,
+                    AsyncEventSequencer* sequencer) {
+  device_ = weave::Device::Create();
+  device_->Start(options, &dbus_object_, sequencer);
+
+  device_->GetCommands()->AddOnCommandDefChanged(base::Bind(
       &Manager::OnCommandDefsChanged, weak_ptr_factory_.GetWeakPtr()));
-  command_manager_->Startup(base::FilePath{"/etc/buffet"},
-                            options.test_definitions_path);
-  state_change_queue_.reset(
-      new weave::StateChangeQueue(kMaxStateChangeQueueSize));
-  state_manager_ =
-      std::make_shared<weave::StateManager>(state_change_queue_.get());
-  state_manager_->AddOnChangedCallback(
+
+  device_->GetState()->AddOnChangedCallback(
       base::Bind(&Manager::OnStateChanged, weak_ptr_factory_.GetWeakPtr()));
-  state_manager_->Startup();
 
-  std::unique_ptr<weave::BuffetConfig> config{
-      new weave::BuffetConfig{options.state_path}};
-  config->AddOnChangedCallback(
+  device_->GetConfig()->AddOnChangedCallback(
       base::Bind(&Manager::OnConfigChanged, weak_ptr_factory_.GetWeakPtr()));
-  config->Load(options.config_path);
 
-  auto transport = chromeos::http::Transport::CreateDefault();
-  transport->SetDefaultTimeout(base::TimeDelta::FromSeconds(
-      kRequestTimeoutSeconds));
-
-  shill_client_.reset(new weave::privet::ShillClient(dbus_object_.GetBus(),
-                                                     options.device_whitelist));
-
-  // TODO(avakulenko): Figure out security implications of storing
-  // device info state data unencrypted.
-  device_info_.reset(new weave::DeviceRegistrationInfo(
-      command_manager_, state_manager_, std::move(config), transport,
-      base::MessageLoop::current()->task_runner(), options.xmpp_enabled,
-      shill_client_.get()));
-  device_info_->AddOnRegistrationChangedCallback(base::Bind(
+  device_->GetCloud()->AddOnRegistrationChangedCallback(base::Bind(
       &Manager::OnRegistrationChanged, weak_ptr_factory_.GetWeakPtr()));
 
-  base_api_handler_.reset(new weave::BaseApiHandler{
-      device_info_->AsWeakPtr(), state_manager_, command_manager_});
+  device_->GetPrivet()->AddOnWifiSetupChangedCallback(base::Bind(
+      &Manager::UpdateWiFiBootstrapState, weak_ptr_factory_.GetWeakPtr()));
 
-  device_info_->Start();
+  device_->GetPrivet()->AddOnPairingChangedCallbacks(
+      base::Bind(&Manager::OnPairingStart, weak_ptr_factory_.GetWeakPtr()),
+      base::Bind(&Manager::OnPairingEnd, weak_ptr_factory_.GetWeakPtr()));
 
   dbus_adaptor_.RegisterWithDBusObject(&dbus_object_);
   dbus_object_.RegisterAsync(
       sequencer->GetHandler("Manager.RegisterAsync() failed.", true));
-
-  if (!options.privet.disable_privet)
-    StartPrivet(options.privet, sequencer);
-}
-
-void Manager::StartPrivet(const weave::privet::Manager::Options& options,
-                          AsyncEventSequencer* sequencer) {
-  privet_.reset(new weave::privet::Manager{});
-  privet_->Start(options, dbus_object_.GetBus(), shill_client_.get(),
-                 device_info_.get(), command_manager_.get(),
-                 state_manager_.get(), sequencer);
-
-  if (privet_->GetWifiBootstrapManager()) {
-    privet_->GetWifiBootstrapManager()->RegisterStateListener(base::Bind(
-        &Manager::UpdateWiFiBootstrapState, weak_ptr_factory_.GetWeakPtr()));
-  } else {
-    UpdateWiFiBootstrapState(weave::privet::WifiBootstrapManager::kDisabled);
-  }
-
-  privet_->GetSecurityManager()->RegisterPairingListeners(
-      base::Bind(&Manager::OnPairingStart, weak_ptr_factory_.GetWeakPtr()),
-      base::Bind(&Manager::OnPairingEnd, weak_ptr_factory_.GetWeakPtr()));
-  // TODO(wiley) Watch for appropriate state variables from |cloud_delegate|.
 }
 
 void Manager::Stop() {
-  if (privet_)
-    privet_->OnShutdown();
+  device_.reset();
 }
 
+// TODO(vitalybuka): Remove, it's just duplicate of property.
 void Manager::CheckDeviceRegistered(
     DBusMethodResponsePtr<std::string> response) {
   LOG(INFO) << "Received call to Manager.CheckDeviceRegistered()";
-  chromeos::ErrorPtr error;
-  bool registered = device_info_->VerifyRegistrationCredentials(&error);
-  // If it fails due to any reason other than 'device not registered',
-  // treat it as a real error and report it to the caller.
-  if (!registered &&
-      !error->HasError(weave::kErrorDomainGCD, "device_not_registered")) {
-    response->ReplyWithError(error.get());
-    return;
-  }
-
-  response->Return(registered ? device_info_->GetConfig().device_id()
-                              : std::string());
+  response->Return(dbus_adaptor_.GetDeviceId());
 }
 
+// TODO(vitalybuka): Remove or rename to leave for testing.
 void Manager::GetDeviceInfo(DBusMethodResponsePtr<std::string> response) {
   LOG(INFO) << "Received call to Manager.GetDeviceInfo()";
   std::shared_ptr<DBusMethodResponse<std::string>> shared_response =
       std::move(response);
 
-  device_info_->GetDeviceInfo(
+  device_->GetCloud()->GetDeviceInfo(
       base::Bind(&Manager::OnGetDeviceInfoSuccess,
                  weak_ptr_factory_.GetWeakPtr(), shared_response),
-      base::Bind(&Manager::OnGetDeviceInfoError,
-                 weak_ptr_factory_.GetWeakPtr(), shared_response));
+      base::Bind(&Manager::OnGetDeviceInfoError, weak_ptr_factory_.GetWeakPtr(),
+                 shared_response));
 }
 
 void Manager::OnGetDeviceInfoSuccess(
@@ -186,32 +136,27 @@
   LOG(INFO) << "Received call to Manager.RegisterDevice()";
 
   chromeos::ErrorPtr error;
-  std::string device_id = device_info_->RegisterDevice(ticket_id, &error);
+  std::string device_id =
+      device_->GetCloud()->RegisterDevice(ticket_id, &error);
   if (!device_id.empty()) {
     response->Return(device_id);
     return;
   }
-  if (!error) {
-    // TODO(zeuthen): This can be changed to CHECK(error) once
-    // RegisterDevice() has been fixed to set |error| when failing.
-    chromeos::Error::AddTo(&error, FROM_HERE, weave::kErrorDomainGCD,
-                           "internal_error",
-                           "device_id empty but error not set");
-  }
+  CHECK(error);
   response->ReplyWithError(error.get());
 }
 
 void Manager::UpdateState(DBusMethodResponsePtr<> response,
                           const chromeos::VariantDictionary& property_set) {
   chromeos::ErrorPtr error;
-  if (!state_manager_->SetProperties(property_set, &error))
+  if (!device_->GetState()->SetProperties(property_set, &error))
     response->ReplyWithError(error.get());
   else
     response->Return();
 }
 
 bool Manager::GetState(chromeos::ErrorPtr* error, std::string* state) {
-  auto json = state_manager_->GetStateValuesAsJson(error);
+  auto json = device_->GetState()->GetStateValuesAsJson(error);
   if (!json)
     return false;
   base::JSONWriter::WriteWithOptions(
@@ -240,7 +185,7 @@
     return response->ReplyWithError(error.get());
 
   std::string id;
-  if (!command_manager_->AddCommand(*command, role, &id, &error))
+  if (!device_->GetCommands()->AddCommand(*command, role, &id, &error))
     return response->ReplyWithError(error.get());
 
   response->Return(id);
@@ -248,10 +193,10 @@
 
 void Manager::GetCommand(DBusMethodResponsePtr<std::string> response,
                          const std::string& id) {
-  const weave::CommandInstance* command = command_manager_->FindCommand(id);
+  const weave::CommandInstance* command =
+      device_->GetCommands()->FindCommand(id);
   if (!command) {
-    response->ReplyWithError(FROM_HERE, weave::kErrorDomainGCD,
-                             "unknown_command",
+    response->ReplyWithError(FROM_HERE, kErrorDomain, "unknown_command",
                              "Can't find command with id: " + id);
     return;
   }
@@ -270,7 +215,8 @@
     response->ReplyWithError(error.get());
     return;
   }
-  if (!command_manager_->SetCommandVisibility(in_names, visibility, &error)) {
+  if (!device_->GetCommands()->SetCommandVisibility(in_names, visibility,
+                                                    &error)) {
     response->ReplyWithError(error.get());
     return;
   }
@@ -286,15 +232,13 @@
     chromeos::ErrorPtr* error,
     const dbus::ObjectPath& in_listener_path,
     const chromeos::VariantDictionary& in_options) {
-  chromeos::Error::AddTo(error, FROM_HERE, weave::privet::errors::kDomain,
-                         weave::privet::errors::kNotImplemented,
+  chromeos::Error::AddTo(error, FROM_HERE, kErrorDomain, kNotImplemented,
                          "Manual WiFi bootstrapping is not implemented");
   return false;
 }
 
 bool Manager::DisableWiFiBootstrapping(chromeos::ErrorPtr* error) {
-  chromeos::Error::AddTo(error, FROM_HERE, weave::privet::errors::kDomain,
-                         weave::privet::errors::kNotImplemented,
+  chromeos::Error::AddTo(error, FROM_HERE, kErrorDomain, kNotImplemented,
                          "Manual WiFi bootstrapping is not implemented");
   return false;
 }
@@ -303,25 +247,23 @@
     chromeos::ErrorPtr* error,
     const dbus::ObjectPath& in_listener_path,
     const chromeos::VariantDictionary& in_options) {
-  chromeos::Error::AddTo(error, FROM_HERE, weave::privet::errors::kDomain,
-                         weave::privet::errors::kNotImplemented,
+  chromeos::Error::AddTo(error, FROM_HERE, kErrorDomain, kNotImplemented,
                          "Manual GCD bootstrapping is not implemented");
   return false;
 }
 
 bool Manager::DisableGCDBootstrapping(chromeos::ErrorPtr* error) {
-  chromeos::Error::AddTo(error, FROM_HERE, weave::privet::errors::kDomain,
-                         weave::privet::errors::kNotImplemented,
+  chromeos::Error::AddTo(error, FROM_HERE, kErrorDomain, kNotImplemented,
                          "Manual GCD bootstrapping is not implemented");
   return false;
 }
 
 bool Manager::UpdateDeviceInfo(chromeos::ErrorPtr* error,
-                               const std::string& in_name,
-                               const std::string& in_description,
-                               const std::string& in_location) {
-  return device_info_->UpdateDeviceInfo(in_name, in_description, in_location,
-                                        error);
+                               const std::string& name,
+                               const std::string& description,
+                               const std::string& location) {
+  return device_->GetCloud()->UpdateDeviceInfo(name, description, location,
+                                               error);
 }
 
 bool Manager::UpdateServiceConfig(chromeos::ErrorPtr* error,
@@ -330,17 +272,18 @@
                                   const std::string& api_key,
                                   const std::string& oauth_url,
                                   const std::string& service_url) {
-  return device_info_->UpdateServiceConfig(client_id, client_secret, api_key,
-                                           oauth_url, service_url, error);
+  return device_->GetCloud()->UpdateServiceConfig(
+      client_id, client_secret, api_key, oauth_url, service_url, error);
 }
 
 void Manager::OnCommandDefsChanged() {
   // Limit only to commands that are visible to the local clients.
-  auto commands = command_manager_->GetCommandDictionary().GetCommandsAsJson(
-      [](const weave::CommandDefinition* def) {
-        return def->GetVisibility().local;
-      },
-      true, nullptr);
+  auto commands =
+      device_->GetCommands()->GetCommandDictionary().GetCommandsAsJson(
+          [](const weave::CommandDefinition* def) {
+            return def->GetVisibility().local;
+          },
+          true, nullptr);
   CHECK(commands);
   std::string json;
   base::JSONWriter::WriteWithOptions(
@@ -349,7 +292,7 @@
 }
 
 void Manager::OnStateChanged() {
-  auto state = state_manager_->GetStateValuesAsJson(nullptr);
+  auto state = device_->GetState()->GetStateValuesAsJson(nullptr);
   CHECK(state);
   std::string json;
   base::JSONWriter::WriteWithOptions(
@@ -374,38 +317,30 @@
 
 void Manager::UpdateWiFiBootstrapState(
     weave::privet::WifiBootstrapManager::State state) {
-  if (auto wifi = privet_->GetWifiBootstrapManager()) {
-    const std::string& ssid{wifi->GetCurrentlyConnectedSsid()};
-    if (ssid != device_info_->GetConfig().last_configured_ssid()) {
-      weave::BuffetConfig::Transaction change{device_info_->GetMutableConfig()};
-      change.set_last_configured_ssid(ssid);
-    }
-  }
-
   switch (state) {
-    case weave::privet::WifiBootstrapManager::kDisabled:
+    case weave::WifiSetupState::kDisabled:
       dbus_adaptor_.SetWiFiBootstrapState("disabled");
       break;
-    case weave::privet::WifiBootstrapManager::kBootstrapping:
+    case weave::WifiSetupState::kBootstrapping:
       dbus_adaptor_.SetWiFiBootstrapState("waiting");
       break;
-    case weave::privet::WifiBootstrapManager::kMonitoring:
+    case weave::WifiSetupState::kMonitoring:
       dbus_adaptor_.SetWiFiBootstrapState("monitoring");
       break;
-    case weave::privet::WifiBootstrapManager::kConnecting:
+    case weave::WifiSetupState::kConnecting:
       dbus_adaptor_.SetWiFiBootstrapState("connecting");
       break;
   }
 }
 
 void Manager::OnPairingStart(const std::string& session_id,
-                             privet::PairingType pairing_type,
+                             weave::PairingType pairing_type,
                              const std::vector<uint8_t>& code) {
   // For now, just overwrite the exposed PairInfo with
   // the most recent pairing attempt.
   dbus_adaptor_.SetPairingInfo(chromeos::VariantDictionary{
       {kPairingSessionIdKey, session_id},
-      {kPairingModeKey, PairingTypeToString(pairing_type)},
+      {kPairingModeKey, weave::privet::PairingTypeToString(pairing_type)},
       {kPairingCodeKey, code},
   });
 }