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. 4 5 #include "chrome/browser/ui/app_list/search/webstore_search_fetcher.h" 6 7 #include "base/bind.h" 8 #include "base/values.h" 9 #include "chrome/browser/safe_json_parser.h" 10 #include "chrome/common/extensions/extension_constants.h" 11 #include "net/base/load_flags.h" 12 #include "net/url_request/url_fetcher.h" 13 #include "net/url_request/url_request_status.h" 14 15 namespace app_list { 16 17 const char kBadResponse[] = "Bad Web Store search response"; 18 19 WebstoreSearchFetcher::WebstoreSearchFetcher( 20 const Callback& callback, 21 net::URLRequestContextGetter* context_getter) 22 : callback_(callback), 23 context_getter_(context_getter), 24 weak_factory_(this) { 25 DCHECK(!callback_.is_null()); 26 } 27 28 WebstoreSearchFetcher::~WebstoreSearchFetcher() {} 29 30 void WebstoreSearchFetcher::Start(const std::string& query, 31 const std::string& hl) { 32 Stop(); 33 34 fetcher_.reset(net::URLFetcher::Create( 35 extension_urls::GetWebstoreJsonSearchUrl(query, hl), 36 net::URLFetcher::GET, 37 this)); 38 fetcher_->SetRequestContext(context_getter_); 39 fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES | 40 net::LOAD_DISABLE_CACHE); 41 fetcher_->Start(); 42 } 43 44 void WebstoreSearchFetcher::Stop() { 45 fetcher_.reset(); 46 weak_factory_.InvalidateWeakPtrs(); 47 } 48 49 void WebstoreSearchFetcher::OnJsonParseSuccess( 50 scoped_ptr<base::Value> parsed_json) { 51 if (!parsed_json->IsType(base::Value::TYPE_DICTIONARY)) { 52 OnJsonParseError(kBadResponse); 53 return; 54 } 55 56 callback_.Run(make_scoped_ptr( 57 static_cast<base::DictionaryValue*>(parsed_json.release()))); 58 } 59 60 void WebstoreSearchFetcher::OnJsonParseError(const std::string& error) { 61 callback_.Run(scoped_ptr<base::DictionaryValue>()); 62 } 63 64 void WebstoreSearchFetcher::OnURLFetchComplete(const net::URLFetcher* source) { 65 CHECK_EQ(fetcher_.get(), source); 66 67 scoped_ptr<net::URLFetcher> fetcher(fetcher_.Pass()); 68 69 if (!fetcher->GetStatus().is_success() || 70 fetcher->GetResponseCode() != 200) { 71 OnJsonParseError(kBadResponse); 72 return; 73 } 74 75 std::string webstore_json_data; 76 fetcher->GetResponseAsString(&webstore_json_data); 77 78 scoped_refptr<SafeJsonParser> parser = 79 new SafeJsonParser(webstore_json_data, 80 base::Bind(&WebstoreSearchFetcher::OnJsonParseSuccess, 81 weak_factory_.GetWeakPtr()), 82 base::Bind(&WebstoreSearchFetcher::OnJsonParseError, 83 weak_factory_.GetWeakPtr())); 84 // The parser will call us back via one of the callbacks. 85 parser->Start(); 86 } 87 88 } // namespace app_list 89