summaryrefslogtreecommitdiffstats
path: root/chrome/browser/devtools/device/webrtc/devtools_bridge_client.cc
blob: a1c718442f6d6c651cec1dba59b94a218ba955a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/devtools/device/webrtc/devtools_bridge_client.h"

#include <stddef.h>

#include "base/callback.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/local_discovery/gcd_api_flow.h"
#include "chrome/common/url_constants.h"
#include "components/signin/core/browser/profile_identity_provider.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
#include "ui/base/page_transition_types.h"

using content::BrowserThread;
using content::WebContents;

namespace {

const char kBackgroundWorkerURL[] =
    "chrome://webrtc-device-provider/background_worker.html";
const char kSerial[] = "webrtc";
const char kPseudoDeviceName[] = "Remote browsers";
const char kDeviceIdPrefix[] = "device-id:";

class BackgroundWorkerUserData
    : public content::WebContentsUserData<BackgroundWorkerUserData> {
 public:
  DevToolsBridgeClient* client() const { return client_; }
  void SetClient(DevToolsBridgeClient* client) { client_ = client; }

 private:
  friend WebContentsUserData<BackgroundWorkerUserData>;

  explicit BackgroundWorkerUserData(WebContents* contents) : client_(nullptr) {}

  DevToolsBridgeClient* client_;
};

}  // namespace

DEFINE_WEB_CONTENTS_USER_DATA_KEY(BackgroundWorkerUserData);

// DevToolsBridgeClient --------------------------------------------------------

// static
base::WeakPtr<DevToolsBridgeClient> DevToolsBridgeClient::Create(
    Profile* profile,
    SigninManagerBase* signin_manager,
    ProfileOAuth2TokenService* token_service) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  auto instance =
      new DevToolsBridgeClient(profile, signin_manager, token_service);
  return instance->weak_factory_.GetWeakPtr();
}

DevToolsBridgeClient::DevToolsBridgeClient(
    Profile* profile,
    SigninManagerBase* signin_manager,
    ProfileOAuth2TokenService* token_service)
    : WebContentsObserver(),
      profile_(profile),
      identity_provider_(signin_manager, token_service, base::Closure()),
      worker_is_loaded_(false),
      weak_factory_(this) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  identity_provider_.AddObserver(this);
  registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
                 content::Source<Profile>(profile_));

  if (IsAuthenticated())
    CreateBackgroundWorker();
}

DevToolsBridgeClient::~DevToolsBridgeClient() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  identity_provider_.RemoveObserver(this);
}

void DevToolsBridgeClient::DeleteSelf() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  delete this;
}

void DevToolsBridgeClient::UpdateBrowserList() {
  if (!IsAuthenticated() || browser_list_request_.get())
    return;
  browser_list_request_ = CreateGCDApiFlow();
  browser_list_request_->Start(
      make_scoped_ptr(new DevToolsBridgeInstancesRequest(this)));
}

void DevToolsBridgeClient::StartSessionIfNeeded(
    const std::string& socket_name) {
  if (!background_worker_.get() || !background_worker_->GetWebUI() ||
      !worker_is_loaded_) {
    return;
  }

  const size_t kPrefixLength = sizeof(kDeviceIdPrefix) - 1;
  if (socket_name.substr(0, kPrefixLength) != kDeviceIdPrefix)
    return;

  std::string browser_id = socket_name.substr(kPrefixLength);
  background_worker_->GetWebUI()->CallJavascriptFunction(
      "WebRTCDeviceProvider.instance.startSessionIfNeeded",
      base::StringValue(browser_id));
}

// static
DevToolsBridgeClient* DevToolsBridgeClient::FromWebContents(
    WebContents* web_contents) {
  auto user_data = BackgroundWorkerUserData::FromWebContents(web_contents);
  return user_data ? user_data->client() : nullptr;
}

void DevToolsBridgeClient::RegisterMessageHandlers(content::WebUI* web_ui) {
  web_ui->RegisterMessageCallback(
      "sendCommand", base::Bind(&DevToolsBridgeClient::HandleSendCommand,
                                base::Unretained(this)));
}

bool DevToolsBridgeClient::IsAuthenticated() {
  return !identity_provider_.GetActiveAccountId().empty();
}

void DevToolsBridgeClient::HandleSendCommand(const base::ListValue* args) {
  if (args->GetSize() != 1)
    return;

  const base::DictionaryValue* command_value;
  if (!args->GetDictionary(0, &command_value))
    return;

  send_command_request_ = CreateGCDApiFlow();
  send_command_request_->Start(
      make_scoped_ptr(new SendCommandRequest(command_value, this)));
}

scoped_ptr<local_discovery::GCDApiFlow>
DevToolsBridgeClient::CreateGCDApiFlow() {
  DCHECK(IsAuthenticated());
  return local_discovery::GCDApiFlow::Create(
      profile_->GetRequestContext(), identity_provider_.GetTokenService(),
      identity_provider_.GetActiveAccountId());
}

// static
DevToolsBridgeClient::SerialList DevToolsBridgeClient::GetDevices(
    base::WeakPtr<DevToolsBridgeClient> weak_ptr) {
  SerialList result;
  if (auto* ptr = weak_ptr.get()) {
    if (ptr->background_worker_.get())
      result.push_back(kSerial);

    ptr->UpdateBrowserList();
  }
  return result;
}

// static
DevToolsBridgeClient::DeviceInfo DevToolsBridgeClient::GetDeviceInfo(
    base::WeakPtr<DevToolsBridgeClient> weak_self,
    const std::string& serial) {
  DeviceInfo result;
  if (auto* self = weak_self.get()) {
    result.connected = !!self->background_worker_.get();
    result.model = kPseudoDeviceName;
    result.browser_info = self->browsers_;
  }
  return result;
}

void DevToolsBridgeClient::CreateBackgroundWorker() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  background_worker_.reset(
      WebContents::Create(WebContents::CreateParams(profile_)));

  BackgroundWorkerUserData::CreateForWebContents(background_worker_.get());
  BackgroundWorkerUserData::FromWebContents(background_worker_.get())
      ->SetClient(this);
  WebContentsObserver::Observe(background_worker_.get());

  GURL url(kBackgroundWorkerURL);
  DCHECK_EQ(chrome::kChromeUIWebRTCDeviceProviderHost, url.host());

  background_worker_->GetController().LoadURL(url, content::Referrer(),
                                              ui::PAGE_TRANSITION_AUTO_TOPLEVEL,
                                              std::string());
}

void DevToolsBridgeClient::DocumentOnLoadCompletedInMainFrame() {
  worker_is_loaded_ = true;
}

void DevToolsBridgeClient::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK_EQ(chrome::NOTIFICATION_PROFILE_DESTROYED, type);

  delete this;
}

void DevToolsBridgeClient::OnActiveAccountLogin() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  CreateBackgroundWorker();
}

void DevToolsBridgeClient::OnActiveAccountLogout() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  background_worker_.reset();
  browser_list_request_.reset();
  send_command_request_.reset();
  BrowserInfoList().swap(browsers_);
  worker_is_loaded_ = false;
}

void DevToolsBridgeClient::OnCommandSucceeded(
    const base::DictionaryValue& response) {
  if (background_worker_.get() && background_worker_->GetWebUI()) {
    background_worker_->GetWebUI()->CallJavascriptFunction(
        "WebRTCDeviceProvider.instance.handleCommandSuccess", response);
  }
  send_command_request_.reset();
}

void DevToolsBridgeClient::OnCommandFailed() {
  if (background_worker_.get() && background_worker_->GetWebUI()) {
    background_worker_->GetWebUI()->CallJavascriptFunction(
        "WebRTCDeviceProvider.instance.handleCommandFailure");
  }
  send_command_request_.reset();
}

void DevToolsBridgeClient::OnDevToolsBridgeInstancesRequestSucceeded(
    const DevToolsBridgeInstancesRequest::InstanceList& instances) {
  BrowserInfoList browsers;
  for (const auto& instance : instances) {
    BrowserInfo browser;
    browser.type = BrowserInfo::kTypeChrome;
    browser.display_name = instance.display_name;
    browser.socket_name = kDeviceIdPrefix + instance.id;
    browsers.push_back(browser);
  }
  browsers_.swap(browsers);

  browser_list_request_.reset();

  OnBrowserListUpdatedForTests();
}

void DevToolsBridgeClient::OnDevToolsBridgeInstancesRequestFailed() {
  // We keep the list of remote browsers even if the request failed.
  browser_list_request_.reset();
}