cookie_change_notifier.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 "shell/browser/cookie_change_notifier.h"
  5. #include <utility>
  6. #include "base/bind.h"
  7. #include "content/public/browser/browser_thread.h"
  8. #include "content/public/browser/storage_partition.h"
  9. #include "net/cookies/canonical_cookie.h"
  10. #include "shell/browser/atom_browser_context.h"
  11. #include "shell/browser/net/cookie_details.h"
  12. using content::BrowserThread;
  13. namespace electron {
  14. CookieChangeNotifier::CookieChangeNotifier(AtomBrowserContext* browser_context)
  15. : browser_context_(browser_context), receiver_(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(!receiver_.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. cookie_manager->AddGlobalChangeListener(receiver_.BindNewPipeAndPassRemote());
  36. receiver_.set_disconnect_handler(base::BindOnce(
  37. &CookieChangeNotifier::OnConnectionError, base::Unretained(this)));
  38. }
  39. void CookieChangeNotifier::OnConnectionError() {
  40. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  41. receiver_.reset();
  42. StartListening();
  43. }
  44. void CookieChangeNotifier::OnCookieChange(
  45. const net::CanonicalCookie& cookie,
  46. network::mojom::CookieChangeCause cause) {
  47. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  48. CookieDetails cookie_details(
  49. &cookie, cause != network::mojom::CookieChangeCause::INSERTED, cause);
  50. cookie_change_sub_list_.Notify(&cookie_details);
  51. }
  52. } // namespace electron