1 // Copyright 2018 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 #ifndef COMPONENTS_FEED_CORE_FEED_NETWORKING_HOST_H_ 6 #define COMPONENTS_FEED_CORE_FEED_NETWORKING_HOST_H_ 7 8 #include <stdint.h> 9 10 #include <memory> 11 #include <string> 12 #include <vector> 13 14 #include "base/callback.h" 15 #include "base/containers/flat_set.h" 16 #include "base/containers/unique_ptr_adapters.h" 17 #include "base/macros.h" 18 #include "base/memory/scoped_refptr.h" 19 #include "url/gurl.h" 20 21 class PrefService; 22 23 namespace base { 24 class TickClock; 25 } 26 27 namespace signin { 28 class IdentityManager; 29 } 30 31 namespace network { 32 class SharedURLLoaderFactory; 33 } 34 35 namespace feed { 36 37 class NetworkFetch; 38 39 // Implementation of the Feed Networking Host API. The networking host handles 40 // the process of sending http requests to remote endpoints, including the 41 // fetching of access tokens for the primary user. 42 class FeedNetworkingHost { 43 public: 44 // status_code is a union of net::Error (if the request failed) and the http 45 // status code(if the request succeeded in reaching the server). 46 using ResponseCallback = 47 base::OnceCallback<void(int32_t status_code, 48 std::vector<uint8_t> response_bytes)>; 49 50 FeedNetworkingHost( 51 signin::IdentityManager* identity_manager, 52 const std::string& api_key, 53 scoped_refptr<network::SharedURLLoaderFactory> loader_factory, 54 const base::TickClock* tick_clock, 55 PrefService* pref_service); 56 57 ~FeedNetworkingHost(); 58 59 // Cancels all pending requests immediately. This could be used, for example, 60 // if there are pending requests for a user who just signed out. 61 void CancelRequests(); 62 63 // Start a request to |url| of type |request_type| with body |request_body|. 64 // |callback| will be called when the response is received or if there is 65 // an error, including non-protocol errors. The contents of |request_body| 66 // will be gzipped. 67 void Send( 68 const GURL& url, 69 const std::string& request_type, 70 std::vector<uint8_t> request_body, 71 ResponseCallback callback); 72 73 private: 74 void NetworkFetchFinished(NetworkFetch* fetch, 75 ResponseCallback callback, 76 int32_t http_code, 77 std::vector<uint8_t> response_body); 78 79 base::flat_set<std::unique_ptr<NetworkFetch>, base::UniquePtrComparator> 80 pending_requests_; 81 signin::IdentityManager* identity_manager_; 82 const std::string api_key_; 83 scoped_refptr<network::SharedURLLoaderFactory> loader_factory_; 84 const base::TickClock* tick_clock_; 85 PrefService* pref_service_; 86 87 DISALLOW_COPY_AND_ASSIGN(FeedNetworkingHost); 88 }; 89 90 } // namespace feed 91 92 #endif // COMPONENTS_FEED_CORE_FEED_NETWORKING_HOST_H_ 93