cookie_change_notifier.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (c) 2018 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "atom/browser/cookie_change_notifier.h"
  5. #include <utility>
  6. #include "atom/browser/atom_browser_context.h"
  7. #include "atom/browser/net/cookie_details.h"
  8. #include "base/bind.h"
  9. #include "content/public/browser/browser_thread.h"
  10. #include "content/public/browser/storage_partition.h"
  11. #include "net/cookies/canonical_cookie.h"
  12. using content::BrowserThread;
  13. namespace atom {
  14. CookieChangeNotifier::CookieChangeNotifier(AtomBrowserContext* browser_context)
  15. : browser_context_(browser_context), binding_(this) {
  16. StartListening();
  17. }
  18. CookieChangeNotifier::~CookieChangeNotifier() = default;
  19. std::unique_ptr<base::CallbackList<void(const CookieDetails*)>::Subscription>
  20. CookieChangeNotifier::RegisterCookieChangeCallback(
  21. const base::Callback<void(const CookieDetails*)>& cb) {
  22. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  23. return cookie_change_sub_list_.Add(cb);
  24. }
  25. void CookieChangeNotifier::StartListening() {
  26. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  27. DCHECK(!binding_.is_bound());
  28. network::mojom::CookieManager* cookie_manager =
  29. content::BrowserContext::GetDefaultStoragePartition(browser_context_)
  30. ->GetCookieManagerForBrowserProcess();
  31. // Cookie manager should be created whenever network context is created,
  32. // if this fails then there is something wrong with our context creation
  33. // cycle.
  34. CHECK(cookie_manager);
  35. network::mojom::CookieChangeListenerPtr listener_ptr;
  36. binding_.Bind(mojo::MakeRequest(&listener_ptr));
  37. binding_.set_connection_error_handler(base::BindOnce(
  38. &CookieChangeNotifier::OnConnectionError, base::Unretained(this)));
  39. cookie_manager->AddGlobalChangeListener(std::move(listener_ptr));
  40. }
  41. void CookieChangeNotifier::OnConnectionError() {
  42. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  43. binding_.Close();
  44. StartListening();
  45. }
  46. void CookieChangeNotifier::OnCookieChange(
  47. const net::CanonicalCookie& cookie,
  48. network::mojom::CookieChangeCause cause) {
  49. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  50. CookieDetails cookie_details(
  51. &cookie, cause != network::mojom::CookieChangeCause::INSERTED, cause);
  52. cookie_change_sub_list_.Notify(&cookie_details);
  53. }
  54. } // namespace atom