Yue Zhang | 32468b8 | 2023-10-31 18:09:19 | [diff] [blame] | 1 | // Copyright 2023 The Chromium Authors |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #import "components/commerce/ios/browser/web_extractor_impl.h" |
| 6 | |
| 7 | #import "base/strings/utf_string_conversions.h" |
| 8 | #import "components/grit/components_resources.h" |
| 9 | #import "ui/base/resource/resource_bundle.h" |
| 10 | |
| 11 | namespace commerce { |
| 12 | |
| 13 | WebExtractorImpl::WebExtractorImpl() = default; |
| 14 | WebExtractorImpl::~WebExtractorImpl() = default; |
| 15 | |
| 16 | void WebExtractorImpl::ExtractMetaInfo( |
| 17 | WebWrapper* web_wrapper, |
Yue Zhang | c7360ec | 2023-11-07 19:33:42 | [diff] [blame] | 18 | base::OnceCallback<void(base::Value)> callback) { |
Yue Zhang | 32468b8 | 2023-10-31 18:09:19 | [diff] [blame] | 19 | std::string script = |
| 20 | ui::ResourceBundle::GetSharedInstance().LoadDataResourceString( |
| 21 | IDR_QUERY_SHOPPING_META_JS); |
| 22 | |
Yue Zhang | c7360ec | 2023-11-07 19:33:42 | [diff] [blame] | 23 | web_wrapper->RunJavascript( |
| 24 | base::UTF8ToUTF16(script), |
| 25 | base::BindOnce(&WebExtractorImpl::OnExtractionMetaInfo, |
| 26 | weak_ptr_factory_.GetWeakPtr(), std::move(callback))); |
| 27 | } |
| 28 | |
| 29 | void WebExtractorImpl::OnExtractionMetaInfo( |
| 30 | base::OnceCallback<void(base::Value)> callback, |
| 31 | base::Value result) { |
| 32 | if (!result.is_string()) { |
| 33 | std::move(callback).Run(base::Value()); |
| 34 | return; |
| 35 | } |
| 36 | |
| 37 | data_decoder::DataDecoder::ParseJsonIsolated( |
| 38 | result.GetString(), |
| 39 | base::BindOnce(&WebExtractorImpl::OnProductInfoJsonSanitizationCompleted, |
| 40 | weak_ptr_factory_.GetWeakPtr(), std::move(callback))); |
| 41 | } |
| 42 | |
| 43 | void WebExtractorImpl::OnProductInfoJsonSanitizationCompleted( |
| 44 | base::OnceCallback<void(base::Value)> callback, |
| 45 | data_decoder::DataDecoder::ValueOrError result) { |
| 46 | if (!result.has_value() || !result.value().is_dict()) { |
| 47 | std::move(callback).Run(base::Value()); |
| 48 | return; |
| 49 | } |
| 50 | |
| 51 | std::move(callback).Run(std::move(result.value())); |
Yue Zhang | 32468b8 | 2023-10-31 18:09:19 | [diff] [blame] | 52 | } |
| 53 | |
| 54 | } // namespace commerce |