[Cronet] Delay StartNetLog and StopNetLog until native request context is initialized
[chromium-blink-merge.git] / chrome / browser / local_discovery / privet_notifications.cc
blob716a5183325bd5b13529b5161988b6c61a0af1a6
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 "chrome/browser/local_discovery/privet_notifications.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/message_loop/message_loop.h"
10 #include "base/metrics/histogram.h"
11 #include "base/prefs/pref_service.h"
12 #include "base/rand_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "chrome/browser/browser_process.h"
15 #include "chrome/browser/local_discovery/privet_device_lister_impl.h"
16 #include "chrome/browser/local_discovery/privet_http_asynchronous_factory.h"
17 #include "chrome/browser/local_discovery/service_discovery_shared_client.h"
18 #include "chrome/browser/notifications/notification.h"
19 #include "chrome/browser/notifications/notification_ui_manager.h"
20 #include "chrome/browser/profiles/profile.h"
21 #include "chrome/browser/signin/signin_manager_factory.h"
22 #include "chrome/browser/ui/browser.h"
23 #include "chrome/browser/ui/browser_finder.h"
24 #include "chrome/browser/ui/browser_window.h"
25 #include "chrome/browser/ui/host_desktop.h"
26 #include "chrome/browser/ui/tabs/tab_strip_model.h"
27 #include "chrome/browser/ui/webui/local_discovery/local_discovery_ui_handler.h"
28 #include "chrome/common/chrome_switches.h"
29 #include "chrome/common/pref_names.h"
30 #include "chrome/grit/generated_resources.h"
31 #include "components/signin/core/browser/signin_manager_base.h"
32 #include "content/public/browser/browser_context.h"
33 #include "content/public/browser/navigation_controller.h"
34 #include "content/public/browser/web_contents.h"
35 #include "grit/theme_resources.h"
36 #include "ui/base/l10n/l10n_util.h"
37 #include "ui/base/page_transition_types.h"
38 #include "ui/base/resource/resource_bundle.h"
39 #include "ui/message_center/notifier_settings.h"
41 #if defined(ENABLE_MDNS)
42 #include "chrome/browser/local_discovery/privet_traffic_detector.h"
43 #endif
45 namespace local_discovery {
47 namespace {
49 const int kTenMinutesInSeconds = 600;
50 const char kPrivetInfoKeyUptime[] = "uptime";
51 const char kPrivetNotificationID[] = "privet_notification";
52 const char kPrivetNotificationOriginUrl[] = "chrome://devices";
53 const int kStartDelaySeconds = 5;
55 enum PrivetNotificationsEvent {
56 PRIVET_SERVICE_STARTED,
57 PRIVET_LISTER_STARTED,
58 PRIVET_DEVICE_CHANGED,
59 PRIVET_INFO_DONE,
60 PRIVET_NOTIFICATION_SHOWN,
61 PRIVET_NOTIFICATION_CANCELED,
62 PRIVET_NOTIFICATION_CLICKED,
63 PRIVET_DISABLE_NOTIFICATIONS_CLICKED,
64 PRIVET_EVENT_MAX,
67 void ReportPrivetUmaEvent(PrivetNotificationsEvent privet_event) {
68 UMA_HISTOGRAM_ENUMERATION("LocalDiscovery.PrivetNotificationsEvent",
69 privet_event, PRIVET_EVENT_MAX);
72 } // namespace
74 PrivetNotificationsListener::PrivetNotificationsListener(
75 scoped_ptr<PrivetHTTPAsynchronousFactory> privet_http_factory,
76 Delegate* delegate)
77 : delegate_(delegate), devices_active_(0) {
78 privet_http_factory_.swap(privet_http_factory);
81 PrivetNotificationsListener::~PrivetNotificationsListener() {
84 void PrivetNotificationsListener::DeviceChanged(
85 bool added,
86 const std::string& name,
87 const DeviceDescription& description) {
88 ReportPrivetUmaEvent(PRIVET_DEVICE_CHANGED);
89 DeviceContextMap::iterator found = devices_seen_.find(name);
90 if (found != devices_seen_.end()) {
91 if (!description.id.empty() && // Device is registered
92 found->second->notification_may_be_active) {
93 found->second->notification_may_be_active = false;
94 NotifyDeviceRemoved();
96 return; // Already saw this device.
99 linked_ptr<DeviceContext> device_context(new DeviceContext);
101 device_context->notification_may_be_active = false;
102 device_context->registered = !description.id.empty();
104 devices_seen_.insert(make_pair(name, device_context));
106 if (!device_context->registered) {
107 device_context->privet_http_resolution =
108 privet_http_factory_->CreatePrivetHTTP(name);
109 device_context->privet_http_resolution->Start(
110 description.address,
111 base::Bind(&PrivetNotificationsListener::CreateInfoOperation,
112 base::Unretained(this)));
116 void PrivetNotificationsListener::CreateInfoOperation(
117 scoped_ptr<PrivetHTTPClient> http_client) {
118 if (!http_client) {
119 // Do nothing if resolution fails.
120 return;
123 std::string name = http_client->GetName();
124 DeviceContextMap::iterator device_iter = devices_seen_.find(name);
125 if (device_iter == devices_seen_.end())
126 return;
127 DeviceContext* device = device_iter->second.get();
128 device->privet_http.swap(http_client);
129 device->info_operation = device->privet_http->CreateInfoOperation(
130 base::Bind(&PrivetNotificationsListener::OnPrivetInfoDone,
131 base::Unretained(this),
132 device));
133 device->info_operation->Start();
136 void PrivetNotificationsListener::OnPrivetInfoDone(
137 DeviceContext* device,
138 const base::DictionaryValue* json_value) {
139 int uptime;
141 if (!json_value ||
142 !json_value->GetInteger(kPrivetInfoKeyUptime, &uptime) ||
143 uptime > kTenMinutesInSeconds) {
144 return;
147 DCHECK(!device->notification_may_be_active);
148 device->notification_may_be_active = true;
149 devices_active_++;
150 delegate_->PrivetNotify(devices_active_ > 1, true);
153 void PrivetNotificationsListener::DeviceRemoved(const std::string& name) {
154 DeviceContextMap::iterator device_iter = devices_seen_.find(name);
155 if (device_iter == devices_seen_.end())
156 return;
157 DeviceContext* device = device_iter->second.get();
159 device->info_operation.reset();
160 device->privet_http_resolution.reset();
161 device->notification_may_be_active = false;
162 NotifyDeviceRemoved();
165 void PrivetNotificationsListener::DeviceCacheFlushed() {
166 for (DeviceContextMap::iterator i = devices_seen_.begin();
167 i != devices_seen_.end(); ++i) {
168 DeviceContext* device = i->second.get();
170 device->info_operation.reset();
171 device->privet_http_resolution.reset();
172 if (device->notification_may_be_active) {
173 device->notification_may_be_active = false;
177 devices_active_ = 0;
178 delegate_->PrivetRemoveNotification();
181 void PrivetNotificationsListener::NotifyDeviceRemoved() {
182 devices_active_--;
183 if (devices_active_ == 0) {
184 delegate_->PrivetRemoveNotification();
185 } else {
186 delegate_->PrivetNotify(devices_active_ > 1, false);
190 PrivetNotificationsListener::DeviceContext::DeviceContext() {
193 PrivetNotificationsListener::DeviceContext::~DeviceContext() {
196 PrivetNotificationService::PrivetNotificationService(
197 content::BrowserContext* profile)
198 : profile_(profile) {
199 base::MessageLoop::current()->PostDelayedTask(
200 FROM_HERE,
201 base::Bind(&PrivetNotificationService::Start, AsWeakPtr()),
202 base::TimeDelta::FromSeconds(kStartDelaySeconds +
203 base::RandInt(0, kStartDelaySeconds/4)));
206 PrivetNotificationService::~PrivetNotificationService() {
209 void PrivetNotificationService::DeviceChanged(
210 bool added,
211 const std::string& name,
212 const DeviceDescription& description) {
213 privet_notifications_listener_->DeviceChanged(added, name, description);
216 void PrivetNotificationService::DeviceRemoved(const std::string& name) {
217 privet_notifications_listener_->DeviceRemoved(name);
220 void PrivetNotificationService::DeviceCacheFlushed() {
221 privet_notifications_listener_->DeviceCacheFlushed();
224 // static
225 bool PrivetNotificationService::IsEnabled() {
226 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
227 return !command_line->HasSwitch(
228 switches::kDisableDeviceDiscoveryNotifications);
231 // static
232 bool PrivetNotificationService::IsForced() {
233 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
234 return command_line->HasSwitch(switches::kEnableDeviceDiscoveryNotifications);
237 void PrivetNotificationService::PrivetNotify(bool has_multiple,
238 bool added) {
239 base::string16 product_name = l10n_util::GetStringUTF16(
240 IDS_LOCAL_DISOCVERY_SERVICE_NAME_PRINTER);
242 int title_resource = has_multiple ?
243 IDS_LOCAL_DISOCVERY_NOTIFICATION_TITLE_PRINTER_MULTIPLE :
244 IDS_LOCAL_DISOCVERY_NOTIFICATION_TITLE_PRINTER;
246 int body_resource = has_multiple ?
247 IDS_LOCAL_DISOCVERY_NOTIFICATION_CONTENTS_PRINTER_MULTIPLE :
248 IDS_LOCAL_DISOCVERY_NOTIFICATION_CONTENTS_PRINTER;
250 base::string16 title = l10n_util::GetStringUTF16(title_resource);
251 base::string16 body = l10n_util::GetStringUTF16(body_resource);
253 Profile* profile_object = Profile::FromBrowserContext(profile_);
254 message_center::RichNotificationData rich_notification_data;
256 rich_notification_data.buttons.push_back(
257 message_center::ButtonInfo(l10n_util::GetStringUTF16(
258 IDS_LOCAL_DISOCVERY_NOTIFICATION_BUTTON_PRINTER)));
260 rich_notification_data.buttons.push_back(
261 message_center::ButtonInfo(l10n_util::GetStringUTF16(
262 IDS_LOCAL_DISCOVERY_NOTIFICATIONS_DISABLE_BUTTON_LABEL)));
264 Notification notification(
265 message_center::NOTIFICATION_TYPE_SIMPLE,
266 GURL(kPrivetNotificationOriginUrl),
267 title,
268 body,
269 ui::ResourceBundle::GetSharedInstance().GetImageNamed(
270 IDR_LOCAL_DISCOVERY_CLOUDPRINT_ICON),
271 message_center::NotifierId(GURL(kPrivetNotificationOriginUrl)),
272 product_name,
273 kPrivetNotificationID,
274 rich_notification_data,
275 new PrivetNotificationDelegate(profile_));
277 bool updated = g_browser_process->notification_ui_manager()->Update(
278 notification, profile_object);
279 if (!updated && added && !LocalDiscoveryUIHandler::GetHasVisible()) {
280 ReportPrivetUmaEvent(PRIVET_NOTIFICATION_SHOWN);
281 g_browser_process->notification_ui_manager()->Add(notification,
282 profile_object);
286 void PrivetNotificationService::PrivetRemoveNotification() {
287 ReportPrivetUmaEvent(PRIVET_NOTIFICATION_CANCELED);
288 Profile* profile_object = Profile::FromBrowserContext(profile_);
289 g_browser_process->notification_ui_manager()->CancelById(
290 kPrivetNotificationID,
291 NotificationUIManager::GetProfileID(profile_object));
294 void PrivetNotificationService::Start() {
295 #if defined(CHROMEOS)
296 SigninManagerBase* signin_manager =
297 SigninManagerFactory::GetForProfileIfExists(
298 Profile::FromBrowserContext(profile_));
300 if (!signin_manager || !signin_manager->IsAuthenticated())
301 return;
302 #endif
304 enable_privet_notification_member_.Init(
305 prefs::kLocalDiscoveryNotificationsEnabled,
306 Profile::FromBrowserContext(profile_)->GetPrefs(),
307 base::Bind(&PrivetNotificationService::OnNotificationsEnabledChanged,
308 base::Unretained(this)));
309 OnNotificationsEnabledChanged();
312 void PrivetNotificationService::OnNotificationsEnabledChanged() {
313 #if defined(ENABLE_MDNS)
314 if (IsForced()) {
315 StartLister();
316 } else if (*enable_privet_notification_member_) {
317 ReportPrivetUmaEvent(PRIVET_SERVICE_STARTED);
318 traffic_detector_ =
319 new PrivetTrafficDetector(
320 net::ADDRESS_FAMILY_IPV4,
321 base::Bind(&PrivetNotificationService::StartLister, AsWeakPtr()));
322 traffic_detector_->Start();
323 } else {
324 traffic_detector_ = NULL;
325 device_lister_.reset();
326 service_discovery_client_ = NULL;
327 privet_notifications_listener_.reset();
329 #else
330 if (IsForced() || *enable_privet_notification_member_) {
331 StartLister();
332 } else {
333 device_lister_.reset();
334 service_discovery_client_ = NULL;
335 privet_notifications_listener_.reset();
337 #endif
340 void PrivetNotificationService::StartLister() {
341 ReportPrivetUmaEvent(PRIVET_LISTER_STARTED);
342 #if defined(ENABLE_MDNS)
343 traffic_detector_ = NULL;
344 #endif // ENABLE_MDNS
345 service_discovery_client_ = ServiceDiscoverySharedClient::GetInstance();
346 device_lister_.reset(
347 new PrivetDeviceListerImpl(service_discovery_client_.get(), this));
348 device_lister_->Start();
349 device_lister_->DiscoverNewDevices(false);
351 scoped_ptr<PrivetHTTPAsynchronousFactory> http_factory(
352 PrivetHTTPAsynchronousFactory::CreateInstance(
353 profile_->GetRequestContext()));
355 privet_notifications_listener_.reset(new PrivetNotificationsListener(
356 http_factory.Pass(), this));
359 PrivetNotificationDelegate::PrivetNotificationDelegate(
360 content::BrowserContext* profile)
361 : profile_(profile) {
364 PrivetNotificationDelegate::~PrivetNotificationDelegate() {
367 std::string PrivetNotificationDelegate::id() const {
368 return kPrivetNotificationID;
371 void PrivetNotificationDelegate::ButtonClick(int button_index) {
372 if (button_index == 0) {
373 ReportPrivetUmaEvent(PRIVET_NOTIFICATION_CLICKED);
374 OpenTab(GURL(kPrivetNotificationOriginUrl));
375 } else if (button_index == 1) {
376 ReportPrivetUmaEvent(PRIVET_DISABLE_NOTIFICATIONS_CLICKED);
377 DisableNotifications();
381 void PrivetNotificationDelegate::OpenTab(const GURL& url) {
382 Profile* profile_obj = Profile::FromBrowserContext(profile_);
384 chrome::NavigateParams params(profile_obj,
385 url,
386 ui::PAGE_TRANSITION_AUTO_TOPLEVEL);
387 params.disposition = NEW_FOREGROUND_TAB;
388 chrome::Navigate(&params);
391 void PrivetNotificationDelegate::DisableNotifications() {
392 Profile* profile_obj = Profile::FromBrowserContext(profile_);
394 profile_obj->GetPrefs()->SetBoolean(
395 prefs::kLocalDiscoveryNotificationsEnabled,
396 false);
399 } // namespace local_discovery