Re-subimission of https://codereview.chromium.org/1041213003/
[chromium-blink-merge.git] / extensions / browser / api / diagnostics / diagnostics_api_chromeos.cc
blobf14b8fb0cbe60a03643b44a350f01ca8d65a3b01
1 // Copyright 2013 The Chromium 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.
5 #include "extensions/browser/api/diagnostics/diagnostics_api.h"
7 #include "base/bind.h"
8 #include "base/callback.h"
9 #include "base/json/json_reader.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/values.h"
12 #include "chromeos/dbus/dbus_thread_manager.h"
13 #include "chromeos/dbus/debug_daemon_client.h"
15 namespace extensions {
17 namespace {
19 const char kCount[] = "count";
20 const char kDefaultCount[] = "1";
21 const char kTTL[] = "ttl";
22 const char kTimeout[] = "timeout";
23 const char kSize[] = "size";
25 typedef base::Callback<void(
26 DiagnosticsSendPacketFunction::SendPacketResultCode result_code,
27 const std::string& ip,
28 double latency)> SendPacketCallback;
30 bool ParseResult(const std::string& status, std::string* ip, double* latency) {
31 // Parses the result and returns IP and latency.
32 scoped_ptr<base::Value> parsed_value(base::JSONReader::Read(status));
33 if (!parsed_value)
34 return false;
36 base::DictionaryValue* result = NULL;
37 if (!parsed_value->GetAsDictionary(&result) || result->size() != 1)
38 return false;
40 // Returns the first item.
41 base::DictionaryValue::Iterator iterator(*result);
43 const base::DictionaryValue* info;
44 if (!iterator.value().GetAsDictionary(&info))
45 return false;
47 if (!info->GetDouble("avg", latency))
48 return false;
50 *ip = iterator.key();
51 return true;
54 void OnTestICMPCompleted(const SendPacketCallback& callback,
55 bool succeeded,
56 const std::string& status) {
57 std::string ip;
58 double latency;
59 if (!succeeded || !ParseResult(status, &ip, &latency)) {
60 callback.Run(DiagnosticsSendPacketFunction::SEND_PACKET_FAILED, "", 0.0);
61 } else {
62 callback.Run(DiagnosticsSendPacketFunction::SEND_PACKET_OK, ip, latency);
66 } // namespace
68 void DiagnosticsSendPacketFunction::AsyncWorkStart() {
69 std::map<std::string, std::string> config;
70 config[kCount] = kDefaultCount;
71 if (parameters_->options.ttl)
72 config[kTTL] = base::IntToString(*parameters_->options.ttl);
73 if (parameters_->options.timeout)
74 config[kTimeout] = base::IntToString(*parameters_->options.timeout);
75 if (parameters_->options.size)
76 config[kSize] = base::IntToString(*parameters_->options.size);
78 chromeos::DBusThreadManager::Get()
79 ->GetDebugDaemonClient()
80 ->TestICMPWithOptions(
81 parameters_->options.ip, config,
82 base::Bind(
83 OnTestICMPCompleted,
84 base::Bind(&DiagnosticsSendPacketFunction::OnCompleted, this)));
87 } // namespace extensions