Garrick Evans | e649d0e | 2021-04-27 09:57:19 +0900 | [diff] [blame] | 1 | // Copyright 2021 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "dns-proxy/chrome_features_service_client.h" |
| 6 | |
| 7 | #include <utility> |
| 8 | |
| 9 | #include <base/bind.h> |
| 10 | #include <chromeos/dbus/service_constants.h> |
| 11 | #include <dbus/message.h> |
| 12 | |
| 13 | namespace dns_proxy { |
| 14 | |
| 15 | std::unique_ptr<ChromeFeaturesServiceClient> ChromeFeaturesServiceClient::New( |
| 16 | scoped_refptr<dbus::Bus> bus) { |
| 17 | auto* proxy = bus->GetObjectProxy( |
| 18 | chromeos::kChromeFeaturesServiceName, |
| 19 | dbus::ObjectPath(chromeos::kChromeFeaturesServicePath)); |
| 20 | if (!proxy) { |
| 21 | LOG(ERROR) << "Failed to create object proxy for " |
| 22 | << chromeos::kChromeFeaturesServiceName; |
| 23 | return nullptr; |
| 24 | } |
| 25 | |
| 26 | return std::make_unique<ChromeFeaturesServiceClient>(proxy); |
| 27 | } |
| 28 | |
| 29 | ChromeFeaturesServiceClient::ChromeFeaturesServiceClient( |
| 30 | dbus::ObjectProxy* proxy) |
| 31 | : proxy_(proxy) {} |
| 32 | |
| 33 | void ChromeFeaturesServiceClient::IsDNSProxyEnabled( |
| 34 | IsFeatureEnabledCallback callback) { |
| 35 | if (!proxy_) { |
| 36 | LOG(DFATAL) << "No object proxy"; |
| 37 | return; |
| 38 | } |
| 39 | |
| 40 | proxy_->WaitForServiceToBeAvailable(base::BindOnce( |
| 41 | &ChromeFeaturesServiceClient::OnWaitForServiceAndCallMethod, |
| 42 | weak_ptr_factory_.GetWeakPtr(), |
| 43 | chromeos::kChromeFeaturesServiceIsDNSProxyEnabledMethod, |
| 44 | std::move(callback))); |
| 45 | } |
| 46 | |
| 47 | void ChromeFeaturesServiceClient::OnWaitForServiceAndCallMethod( |
| 48 | const std::string& method_name, |
| 49 | IsFeatureEnabledCallback callback, |
| 50 | bool available) { |
| 51 | if (!available) { |
| 52 | std::move(callback).Run(base::nullopt); |
| 53 | return; |
| 54 | } |
| 55 | |
| 56 | dbus::MethodCall call(chromeos::kChromeFeaturesServiceInterface, method_name); |
| 57 | dbus::MessageWriter writer(&call); |
| 58 | proxy_->CallMethod( |
| 59 | &call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, |
| 60 | base::BindOnce(&ChromeFeaturesServiceClient::HandleCallResponse, |
| 61 | weak_ptr_factory_.GetWeakPtr(), std::move(callback))); |
| 62 | } |
| 63 | |
| 64 | void ChromeFeaturesServiceClient::HandleCallResponse( |
| 65 | IsFeatureEnabledCallback callback, dbus::Response* response) { |
| 66 | if (!response) { |
| 67 | std::move(callback).Run(base::nullopt); |
| 68 | return; |
| 69 | } |
| 70 | |
| 71 | dbus::MessageReader reader(response); |
| 72 | bool feature_enabled = false; |
| 73 | if (!reader.PopBool(&feature_enabled)) { |
| 74 | std::move(callback).Run(base::nullopt); |
| 75 | return; |
| 76 | } |
| 77 | |
| 78 | std::move(callback).Run(feature_enabled); |
| 79 | } |
| 80 | |
| 81 | } // namespace dns_proxy |