1// Copyright (c) 2012 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.
4
5#include "chrome/browser/signin/signin_manager_cookie_helper.h"
6
7#include <vector>
8
9#include "content/public/browser/browser_thread.h"
10#include "google_apis/gaia/gaia_urls.h"
11#include "net/cookies/cookie_monster.h"
12#include "net/url_request/url_request_context.h"
13
14using content::BrowserThread;
15
16SigninManagerCookieHelper::SigninManagerCookieHelper(
17    net::URLRequestContextGetter* request_context_getter)
18    : request_context_getter_(request_context_getter) {
19  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
20}
21
22SigninManagerCookieHelper::~SigninManagerCookieHelper() {
23}
24
25void SigninManagerCookieHelper::StartFetchingGaiaCookiesOnUIThread(
26    const base::Callback<void(const net::CookieList& cookies)>& callback) {
27  StartFetchingCookiesOnUIThread(
28      GaiaUrls::GetInstance()->gaia_url(), callback);
29}
30
31void SigninManagerCookieHelper::StartFetchingCookiesOnUIThread(
32    const GURL& url,
33    const base::Callback<void(const net::CookieList& cookies)>& callback) {
34  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
35  DCHECK(!callback.is_null());
36  DCHECK(completion_callback_.is_null());
37
38  completion_callback_ = callback;
39  BrowserThread::PostTask(
40      BrowserThread::IO, FROM_HERE,
41      base::Bind(&SigninManagerCookieHelper::FetchCookiesOnIOThread, this,
42                 url));
43}
44
45void SigninManagerCookieHelper::FetchCookiesOnIOThread(const GURL& url) {
46  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
47
48  scoped_refptr<net::CookieMonster> cookie_monster =
49      request_context_getter_->GetURLRequestContext()->
50      cookie_store()->GetCookieMonster();
51  if (cookie_monster.get()) {
52    cookie_monster->GetAllCookiesForURLAsync(
53        url, base::Bind(&SigninManagerCookieHelper::OnCookiesFetched, this));
54  } else {
55    OnCookiesFetched(net::CookieList());
56  }
57}
58
59void SigninManagerCookieHelper::OnCookiesFetched(
60    const net::CookieList& cookies) {
61  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
62  BrowserThread::PostTask(
63      BrowserThread::UI, FROM_HERE,
64      base::Bind(&SigninManagerCookieHelper::NotifyOnUIThread, this, cookies));
65}
66
67void SigninManagerCookieHelper::NotifyOnUIThread(
68    const net::CookieList& cookies) {
69  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
70  base::ResetAndReturn(&completion_callback_).Run(cookies);
71}
72