1 // Copyright 2014 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_SAFE_SEARCH_API_URL_CHECKER_H_ 6 #define COMPONENTS_SAFE_SEARCH_API_URL_CHECKER_H_ 7 8 #include <list> 9 #include <memory> 10 11 #include "base/callback_forward.h" 12 #include "base/containers/mru_cache.h" 13 #include "base/time/time.h" 14 #include "components/safe_search_api/url_checker_client.h" 15 #include "url/gurl.h" 16 17 namespace base { 18 struct Feature; 19 } 20 21 namespace safe_search_api { 22 23 // The SafeSearch API classification of a URL. 24 enum class Classification { SAFE, UNSAFE }; 25 26 // Visible for testing. 27 extern const base::Feature kAllowAllGoogleUrls; 28 29 // This class uses one implementation of URLCheckerClient to check the 30 // classification of the content on a given URL and returns the result 31 // asynchronously via a callback. It is also responsible for the synchronous 32 // logic such as caching, the injected URLCheckerClient is who makes the 33 // async request. 34 class URLChecker { 35 public: 36 // Used to report whether |url| should be blocked. Called from CheckURL. 37 using CheckCallback = base::OnceCallback< 38 void(const GURL&, Classification classification, bool /* uncertain */)>; 39 40 explicit URLChecker(std::unique_ptr<URLCheckerClient> async_checker); 41 42 URLChecker(std::unique_ptr<URLCheckerClient> async_checker, 43 size_t cache_size); 44 45 ~URLChecker(); 46 47 // Returns whether |callback| was run synchronously. 48 bool CheckURL(const GURL& url, CheckCallback callback); 49 SetCacheTimeoutForTesting(const base::TimeDelta & timeout)50 void SetCacheTimeoutForTesting(const base::TimeDelta& timeout) { 51 cache_timeout_ = timeout; 52 } 53 54 private: 55 struct Check; 56 struct CheckResult { 57 CheckResult(Classification classification, bool uncertain); 58 Classification classification; 59 bool uncertain; 60 base::TimeTicks timestamp; 61 }; 62 using CheckList = std::list<std::unique_ptr<Check>>; 63 64 void OnAsyncCheckComplete(CheckList::iterator it, 65 const GURL& url, 66 ClientClassification classification); 67 68 std::unique_ptr<URLCheckerClient> async_checker_; 69 CheckList checks_in_progress_; 70 71 base::MRUCache<GURL, CheckResult> cache_; 72 base::TimeDelta cache_timeout_; 73 74 DISALLOW_COPY_AND_ASSIGN(URLChecker); 75 }; 76 77 } // namespace safe_search_api 78 79 #endif // COMPONENTS_SAFE_SEARCH_API_URL_CHECKER_H_ 80