1 // Copyright 2015 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 #ifndef CHROMECAST_NET_CONNECTIVITY_CHECKER_H_
6 #define CHROMECAST_NET_CONNECTIVITY_CHECKER_H_
8 #include "base/memory/ref_counted.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/memory/weak_ptr.h"
11 #include "net/base/network_change_notifier.h"
12 #include "net/url_request/url_request.h"
17 class MessageLoopProxy
;
21 class URLRequestContext
;
24 namespace chromecast
{
26 // Simple class to check network connectivity by sending a HEAD http request
28 class ConnectivityChecker
29 : public base::RefCountedThreadSafe
<ConnectivityChecker
>,
30 public net::URLRequest::Delegate
,
31 public net::NetworkChangeNotifier::ConnectionTypeObserver
,
32 public net::NetworkChangeNotifier::IPAddressObserver
{
34 class ConnectivityObserver
{
36 // Will be called when internet connectivity changes
37 virtual void OnConnectivityChanged(bool connected
) = 0;
40 ConnectivityObserver() {}
41 virtual ~ConnectivityObserver() {}
44 DISALLOW_COPY_AND_ASSIGN(ConnectivityObserver
);
47 explicit ConnectivityChecker(
48 const scoped_refptr
<base::MessageLoopProxy
>& loop_proxy
);
50 void AddConnectivityObserver(ConnectivityObserver
* observer
);
51 void RemoveConnectivityObserver(ConnectivityObserver
* observer
);
53 // Returns if there is internet connectivity
54 bool Connected() const;
56 // Checks for connectivity
60 ~ConnectivityChecker() override
;
63 friend class base::RefCountedThreadSafe
<ConnectivityChecker
>;
65 // UrlRequest::Delegate implementation:
66 void OnResponseStarted(net::URLRequest
* request
) override
;
67 void OnReadCompleted(net::URLRequest
* request
, int bytes_read
) override
;
69 // Initializes ConnectivityChecker
72 // NetworkChangeNotifier::ConnectionTypeObserver implementation:
73 void OnConnectionTypeChanged(
74 net::NetworkChangeNotifier::ConnectionType type
) override
;
76 // net::NetworkChangeNotifier::IPAddressObserver implementation:
77 void OnIPAddressChanged() override
;
79 // Cancels current connectivity checking in progress.
82 // Sets connectivity and alerts observers if it has changed
83 void SetConnectivity(bool connected
);
85 scoped_ptr
<GURL
> connectivity_check_url_
;
86 scoped_ptr
<net::URLRequestContext
> url_request_context_
;
87 scoped_ptr
<net::URLRequest
> url_request_
;
88 const scoped_refptr
<ObserverListThreadSafe
<ConnectivityObserver
> >
89 connectivity_observer_list_
;
90 const scoped_refptr
<base::MessageLoopProxy
> loop_proxy_
;
92 unsigned int bad_responses_
;
94 DISALLOW_COPY_AND_ASSIGN(ConnectivityChecker
);
97 } // namespace chromecast
99 #endif // CHROMECAST_NET_CONNECTIVITY_CHECKER_H_