Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(230)

Side by Side Diff: chrome/browser/translate/translate_manager.cc

Issue 13508007: Translate: make URL handling logic more readable (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: rebase Created 7 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/translate/translate_manager.h" 5 #include "chrome/browser/translate/translate_manager.h"
6 6
7 #include "base/bind.h" 7 #include "base/bind.h"
8 #include "base/command_line.h" 8 #include "base/command_line.h"
9 #include "base/compiler_specific.h" 9 #include "base/compiler_specific.h"
10 #include "base/json/json_reader.h" 10 #include "base/json/json_reader.h"
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
43 #include "content/public/browser/notification_source.h" 43 #include "content/public/browser/notification_source.h"
44 #include "content/public/browser/notification_types.h" 44 #include "content/public/browser/notification_types.h"
45 #include "content/public/browser/render_process_host.h" 45 #include "content/public/browser/render_process_host.h"
46 #include "content/public/browser/render_view_host.h" 46 #include "content/public/browser/render_view_host.h"
47 #include "content/public/browser/web_contents.h" 47 #include "content/public/browser/web_contents.h"
48 #include "google_apis/google_api_keys.h" 48 #include "google_apis/google_api_keys.h"
49 #include "grit/browser_resources.h" 49 #include "grit/browser_resources.h"
50 #include "net/base/escape.h" 50 #include "net/base/escape.h"
51 #include "net/base/load_flags.h" 51 #include "net/base/load_flags.h"
52 #include "net/base/url_util.h" 52 #include "net/base/url_util.h"
53 #include "net/http/http_status_code.h"
53 #include "net/url_request/url_fetcher.h" 54 #include "net/url_request/url_fetcher.h"
54 #include "net/url_request/url_request_status.h" 55 #include "net/url_request/url_request_status.h"
55 #include "ui/base/resource/resource_bundle.h" 56 #include "ui/base/resource/resource_bundle.h"
56 57
57 #ifdef FILE_MANAGER_EXTENSION 58 #ifdef FILE_MANAGER_EXTENSION
58 #include "chrome/browser/chromeos/extensions/file_manager/file_manager_util.h" 59 #include "chrome/browser/chromeos/extensions/file_manager/file_manager_util.h"
59 #include "extensions/common/constants.h" 60 #include "extensions/common/constants.h"
60 #endif 61 #endif
61 62
62 using content::NavigationController; 63 using content::NavigationController;
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
129 "th", // Thai 130 "th", // Thai
130 "tr", // Turkish 131 "tr", // Turkish
131 "uk", // Ukrainian 132 "uk", // Ukrainian
132 "vi", // Vietnamese 133 "vi", // Vietnamese
133 "cy", // Welsh 134 "cy", // Welsh
134 "yi", // Yiddish 135 "yi", // Yiddish
135 }; 136 };
136 137
137 const char* const kTranslateScriptURL = 138 const char* const kTranslateScriptURL =
138 "https://translate.google.com/translate_a/element.js"; 139 "https://translate.google.com/translate_a/element.js";
139 const char* const kTranslateScriptQuery =
140 "?cb=cr.googleTranslate.onTranslateElementLoad&hl=%s";
141 const char* const kTranslateScriptHeader = 140 const char* const kTranslateScriptHeader =
142 "Google-Translate-Element-Mode: library"; 141 "Google-Translate-Element-Mode: library";
143 const char* const kReportLanguageDetectionErrorURL = 142 const char* const kReportLanguageDetectionErrorURL =
144 "https://translate.google.com/translate_error"; 143 "https://translate.google.com/translate_error?client=cr&action=langidc";
145 const char* const kLanguageListFetchURL = 144 const char* const kLanguageListFetchURL =
146 "https://translate.googleapis.com/translate_a/l?client=chrome&cb=sl"; 145 "https://translate.googleapis.com/translate_a/l?client=chrome&cb=sl";
147 146
148 const char* const kLanguageListFetchLocaleQueryName = "hl"; 147 // Used in kTranslateScriptURL to request supporting languages list including
149 const char* const kLanguageListFetchAlphaLanguageQueryName = "alpha"; 148 // "alpha languages".
150 const char* const kLanguageListFetchAlphaLanguageQueryValue = "1"; 149 const char* const kAlphaLanguageQueryName = "alpha";
150 const char* const kAlphaLanguageQueryValue = "1";
151
152 // Used in all translate URLs to specify API Key.
153 const char* const kApiKeyName = "key";
154
155 // Used in kTranslateScriptURL to specify a callback function name.
156 const char* const kCallbackQueryName = "cb";
157 const char* const kCallbackQueryValue =
158 "cr.googleTranslate.onTranslateElementLoad";
159
160 // Used in kTranslateScriptURL and kLanguageListFetchURL to specify the
161 // application locale.
162 const char* const kHostLocaleQueryName = "hl";
163
164 // Used in kReportLanguageDetectionErrorURL to specify the original page
165 // language.
166 const char* const kSourceLanguageQueryName = "sl";
167
168 // Used in kReportLanguageDetectionErrorURL to specify the page URL.
169 const char* const kUrlQueryName = "u";
151 170
152 const int kMaxRetryLanguageListFetch = 5; 171 const int kMaxRetryLanguageListFetch = 5;
153 const int kTranslateScriptExpirationDelayDays = 1; 172 const int kTranslateScriptExpirationDelayDays = 1;
154 173
155 void AddApiKeyToUrl(GURL* url) { 174 GURL AddApiKeyToUrl(const GURL& url) {
156 std::string api_key = google_apis::GetAPIKey(); 175 return net::AppendQueryParameter(url, kApiKeyName, google_apis::GetAPIKey());
157 std::string query(url->query()); 176 }
158 if (!query.empty()) 177
159 query += "&"; 178 GURL AddHostLocaleToUrl(const GURL& url) {
160 query += "key=" + net::EscapeQueryParamValue(api_key, true); 179 return net::AppendQueryParameter(
161 GURL::Replacements replacements; 180 url,
162 replacements.SetQueryStr(query); 181 kHostLocaleQueryName,
163 *url = url->ReplaceComponents(replacements); 182 TranslateManager::GetLanguageCode(
183 g_browser_process->GetApplicationLocale()));
164 } 184 }
165 185
166 } // namespace 186 } // namespace
167 187
168 // This must be kept in sync with the &cb= value in the kLanguageListFetchURL. 188 // This must be kept in sync with the &cb= value in the kLanguageListFetchURL.
169 const char* const TranslateManager::kLanguageListCallbackName = "sl("; 189 const char* const TranslateManager::kLanguageListCallbackName = "sl(";
170 const char* const TranslateManager::kTargetLanguagesKey = "tl"; 190 const char* const TranslateManager::kTargetLanguagesKey = "tl";
171 191
172 // static 192 // static
173 base::LazyInstance<std::set<std::string> > 193 base::LazyInstance<std::set<std::string> >
(...skipping 131 matching lines...) Expand 10 before | Expand all | Expand 10 after
305 } 325 }
306 326
307 TranslateTabHelper* translate_tab_helper = 327 TranslateTabHelper* translate_tab_helper =
308 TranslateTabHelper::FromWebContents(controller->GetWebContents()); 328 TranslateTabHelper::FromWebContents(controller->GetWebContents());
309 if (!translate_tab_helper) 329 if (!translate_tab_helper)
310 return; 330 return;
311 331
312 // If the navigation happened while offline don't show the translate 332 // If the navigation happened while offline don't show the translate
313 // bar since there will be nothing to translate. 333 // bar since there will be nothing to translate.
314 if (load_details->http_status_code == 0 || 334 if (load_details->http_status_code == 0 ||
315 load_details->http_status_code == 500) { 335 load_details->http_status_code == net::HTTP_INTERNAL_SERVER_ERROR) {
316 return; 336 return;
317 } 337 }
318 338
319 if (!load_details->is_main_frame && 339 if (!load_details->is_main_frame &&
320 translate_tab_helper->language_state().translation_declined()) { 340 translate_tab_helper->language_state().translation_declined()) {
321 // Some sites (such as Google map) may trigger sub-frame navigations 341 // Some sites (such as Google map) may trigger sub-frame navigations
322 // when the user interacts with the page. We don't want to show a new 342 // when the user interacts with the page. We don't want to show a new
323 // infobar if the user already dismissed one in that case. 343 // infobar if the user already dismissed one in that case.
324 return; 344 return;
325 } 345 }
(...skipping 74 matching lines...) Expand 10 before | Expand all | Expand 10 after
400 if (translate_script_request_pending_.get() != source && 420 if (translate_script_request_pending_.get() != source &&
401 language_list_request_pending_.get() != source) { 421 language_list_request_pending_.get() != source) {
402 // Looks like crash on Mac is possibly caused with callback entering here 422 // Looks like crash on Mac is possibly caused with callback entering here
403 // with unknown fetcher when network is refreshed. 423 // with unknown fetcher when network is refreshed.
404 scoped_ptr<const net::URLFetcher> delete_ptr(source); 424 scoped_ptr<const net::URLFetcher> delete_ptr(source);
405 return; 425 return;
406 } 426 }
407 427
408 bool error = 428 bool error =
409 (source->GetStatus().status() != net::URLRequestStatus::SUCCESS || 429 (source->GetStatus().status() != net::URLRequestStatus::SUCCESS ||
410 source->GetResponseCode() != 200); 430 source->GetResponseCode() != net::HTTP_OK);
411 if (translate_script_request_pending_.get() == source) { 431 if (translate_script_request_pending_.get() == source) {
412 scoped_ptr<const net::URLFetcher> delete_ptr( 432 scoped_ptr<const net::URLFetcher> delete_ptr(
413 translate_script_request_pending_.release()); 433 translate_script_request_pending_.release());
414 if (!error) { 434 if (!error) {
415 base::StringPiece str = ResourceBundle::GetSharedInstance(). 435 base::StringPiece str = ResourceBundle::GetSharedInstance().
416 GetRawDataResource(IDR_TRANSLATE_JS); 436 GetRawDataResource(IDR_TRANSLATE_JS);
417 DCHECK(translate_script_.empty()); 437 DCHECK(translate_script_.empty());
418 str.CopyToString(&translate_script_); 438 str.CopyToString(&translate_script_);
419 std::string argument = "('"; 439 std::string argument = "('";
420 std::string api_key = google_apis::GetAPIKey(); 440 std::string api_key = google_apis::GetAPIKey();
(...skipping 210 matching lines...) Expand 10 before | Expand all | Expand 10 after
631 651
632 void TranslateManager::ReportLanguageDetectionError(WebContents* web_contents) { 652 void TranslateManager::ReportLanguageDetectionError(WebContents* web_contents) {
633 UMA_HISTOGRAM_COUNTS("Translate.ReportLanguageDetectionError", 1); 653 UMA_HISTOGRAM_COUNTS("Translate.ReportLanguageDetectionError", 1);
634 // We'll open the URL in a new tab so that the user can tell us more. 654 // We'll open the URL in a new tab so that the user can tell us more.
635 Browser* browser = chrome::FindBrowserWithWebContents(web_contents); 655 Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
636 if (!browser) { 656 if (!browser) {
637 NOTREACHED(); 657 NOTREACHED();
638 return; 658 return;
639 } 659 }
640 660
661 GURL report_error_url = GURL(kReportLanguageDetectionErrorURL);
662
641 GURL page_url = web_contents->GetController().GetActiveEntry()->GetURL(); 663 GURL page_url = web_contents->GetController().GetActiveEntry()->GetURL();
642 // Report option should be disabled for secure URLs. 664 report_error_url = net::AppendQueryParameter(
643 DCHECK(!page_url.SchemeIsSecure()); 665 report_error_url,
644 std::string report_error_url_str(kReportLanguageDetectionErrorURL); 666 kUrlQueryName,
645 report_error_url_str += "?client=cr&action=langidc&u="; 667 page_url.spec());
646 report_error_url_str += net::EscapeUrlEncodedData(page_url.spec(), true);
647 report_error_url_str += "&sl=";
648 668
649 TranslateTabHelper* translate_tab_helper = 669 TranslateTabHelper* translate_tab_helper =
650 TranslateTabHelper::FromWebContents(web_contents); 670 TranslateTabHelper::FromWebContents(web_contents);
651 report_error_url_str += 671 report_error_url = net::AppendQueryParameter(
652 translate_tab_helper->language_state().original_language(); 672 report_error_url,
653 report_error_url_str += "&hl="; 673 kSourceLanguageQueryName,
654 report_error_url_str += 674 translate_tab_helper->language_state().original_language());
655 GetLanguageCode(g_browser_process->GetApplicationLocale());
656 675
657 GURL report_error_url(report_error_url_str); 676 report_error_url = AddHostLocaleToUrl(report_error_url);
658 AddApiKeyToUrl(&report_error_url); 677 report_error_url = AddApiKeyToUrl(report_error_url);
678
659 chrome::AddSelectedTabWithURL(browser, report_error_url, 679 chrome::AddSelectedTabWithURL(browser, report_error_url,
660 content::PAGE_TRANSITION_AUTO_BOOKMARK); 680 content::PAGE_TRANSITION_AUTO_BOOKMARK);
661 } 681 }
662 682
663 void TranslateManager::DoTranslatePage(WebContents* web_contents, 683 void TranslateManager::DoTranslatePage(WebContents* web_contents,
664 const std::string& translate_script, 684 const std::string& translate_script,
665 const std::string& source_lang, 685 const std::string& source_lang,
666 const std::string& target_lang) { 686 const std::string& target_lang) {
667 NavigationEntry* entry = web_contents->GetController().GetActiveEntry(); 687 NavigationEntry* entry = web_contents->GetController().GetActiveEntry();
668 if (!entry) { 688 if (!entry) {
(...skipping 104 matching lines...) Expand 10 before | Expand all | Expand 10 after
773 793
774 // We don't want to do this when translate is disabled. 794 // We don't want to do this when translate is disabled.
775 DCHECK(prefs != NULL); 795 DCHECK(prefs != NULL);
776 if (CommandLine::ForCurrentProcess()->HasSwitch( 796 if (CommandLine::ForCurrentProcess()->HasSwitch(
777 switches::kDisableTranslate) || 797 switches::kDisableTranslate) ||
778 (prefs != NULL && !prefs->GetBoolean(prefs::kEnableTranslate))) { 798 (prefs != NULL && !prefs->GetBoolean(prefs::kEnableTranslate))) {
779 return; 799 return;
780 } 800 }
781 801
782 GURL language_list_fetch_url = GURL(kLanguageListFetchURL); 802 GURL language_list_fetch_url = GURL(kLanguageListFetchURL);
783 language_list_fetch_url = net::AppendQueryParameter( 803 language_list_fetch_url = AddHostLocaleToUrl(language_list_fetch_url);
784 language_list_fetch_url, 804 language_list_fetch_url = AddApiKeyToUrl(language_list_fetch_url);
785 kLanguageListFetchLocaleQueryName,
786 GetLanguageCode(g_browser_process->GetApplicationLocale()).c_str());
787 805
788 const CommandLine& command_line = *CommandLine::ForCurrentProcess(); 806 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
789 if (command_line.HasSwitch(switches::kEnableTranslateAlphaLanguages)) { 807 if (command_line.HasSwitch(switches::kEnableTranslateAlphaLanguages)) {
790 language_list_fetch_url = net::AppendQueryParameter( 808 language_list_fetch_url = net::AppendQueryParameter(
791 language_list_fetch_url, 809 language_list_fetch_url,
792 kLanguageListFetchAlphaLanguageQueryName, 810 kAlphaLanguageQueryName,
793 kLanguageListFetchAlphaLanguageQueryValue); 811 kAlphaLanguageQueryValue);
794 } 812 }
795 AddApiKeyToUrl(&language_list_fetch_url); 813
796 VLOG(9) << "Fetch supporting language list from: " 814 VLOG(9) << "Fetch supporting language list from: "
797 << language_list_fetch_url.spec().c_str(); 815 << language_list_fetch_url.spec().c_str();
798 816
799 language_list_request_pending_.reset(net::URLFetcher::Create( 817 language_list_request_pending_.reset(net::URLFetcher::Create(
800 1, language_list_fetch_url, net::URLFetcher::GET, this)); 818 1, language_list_fetch_url, net::URLFetcher::GET, this));
801 language_list_request_pending_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | 819 language_list_request_pending_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
802 net::LOAD_DO_NOT_SAVE_COOKIES); 820 net::LOAD_DO_NOT_SAVE_COOKIES);
803 language_list_request_pending_->SetRequestContext( 821 language_list_request_pending_->SetRequestContext(
804 g_browser_process->system_request_context()); 822 g_browser_process->system_request_context());
805 language_list_request_pending_->SetMaxRetriesOn5xx( 823 language_list_request_pending_->SetMaxRetriesOn5xx(
806 kMaxRetryLanguageListFetch); 824 kMaxRetryLanguageListFetch);
807 language_list_request_pending_->Start(); 825 language_list_request_pending_->Start();
808 } 826 }
809 827
810 void TranslateManager::CleanupPendingUlrFetcher() { 828 void TranslateManager::CleanupPendingUlrFetcher() {
811 language_list_request_pending_.reset(); 829 language_list_request_pending_.reset();
812 translate_script_request_pending_.reset(); 830 translate_script_request_pending_.reset();
813 } 831 }
814 832
815 void TranslateManager::RequestTranslateScript() { 833 void TranslateManager::RequestTranslateScript() {
816 if (translate_script_request_pending_.get() != NULL) 834 if (translate_script_request_pending_.get() != NULL)
817 return; 835 return;
818 836
819 GURL translate_script_url; 837 GURL translate_script_url;
820 std::string translate_script;
821 // Check if command-line contains an alternative URL for translate service. 838 // Check if command-line contains an alternative URL for translate service.
822 const CommandLine& command_line = *CommandLine::ForCurrentProcess(); 839 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
823 if (command_line.HasSwitch(switches::kTranslateScriptURL)) { 840 if (command_line.HasSwitch(switches::kTranslateScriptURL)) {
824 translate_script = std::string( 841 translate_script_url = GURL(
825 command_line.GetSwitchValueASCII(switches::kTranslateScriptURL)); 842 command_line.GetSwitchValueASCII(switches::kTranslateScriptURL));
826 translate_script_url = GURL(translate_script.c_str());
827 if (!translate_script_url.is_valid() || 843 if (!translate_script_url.is_valid() ||
828 !translate_script_url.query().empty()) { 844 !translate_script_url.query().empty()) {
829 LOG(WARNING) << "The following translate URL specified at the " 845 LOG(WARNING) << "The following translate URL specified at the "
830 << "command-line is invalid: " << translate_script; 846 << "command-line is invalid: "
831 translate_script.clear(); 847 << translate_script_url.spec();
848 translate_script_url = GURL();
832 } 849 }
833 } 850 }
834 // Use default URL when command-line argument is not specified, or specified 851 // Use default URL when command-line argument is not specified, or specified
835 // URL is invalid. 852 // URL is invalid.
836 if (translate_script.empty()) 853 if (translate_script_url.is_empty())
837 translate_script = std::string(kTranslateScriptURL); 854 translate_script_url = GURL(kTranslateScriptURL);
838 855
839 translate_script += std::string(kTranslateScriptQuery); 856 translate_script_url = net::AppendQueryParameter(
840 translate_script_url = GURL(base::StringPrintf( 857 translate_script_url,
841 translate_script.c_str(), 858 kCallbackQueryName,
842 GetLanguageCode(g_browser_process->GetApplicationLocale()).c_str())); 859 kCallbackQueryValue);
843 AddApiKeyToUrl(&translate_script_url); 860 translate_script_url = AddHostLocaleToUrl(translate_script_url);
861 translate_script_url = AddApiKeyToUrl(translate_script_url);
862
844 translate_script_request_pending_.reset(net::URLFetcher::Create( 863 translate_script_request_pending_.reset(net::URLFetcher::Create(
845 0, translate_script_url, net::URLFetcher::GET, this)); 864 0, translate_script_url, net::URLFetcher::GET, this));
846 translate_script_request_pending_->SetLoadFlags( 865 translate_script_request_pending_->SetLoadFlags(
847 net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); 866 net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES);
848 translate_script_request_pending_->SetRequestContext( 867 translate_script_request_pending_->SetRequestContext(
849 g_browser_process->system_request_context()); 868 g_browser_process->system_request_context());
850 translate_script_request_pending_->SetExtraRequestHeaders( 869 translate_script_request_pending_->SetExtraRequestHeaders(
851 kTranslateScriptHeader); 870 kTranslateScriptHeader);
852 translate_script_request_pending_->Start(); 871 translate_script_request_pending_->Start();
853 } 872 }
(...skipping 15 matching lines...) Expand all
869 // list or not at all if no such candidate exists 888 // list or not at all if no such candidate exists
870 std::vector<std::string>::iterator iter; 889 std::vector<std::string>::iterator iter;
871 for (iter = accept_langs_list.begin(); 890 for (iter = accept_langs_list.begin();
872 iter != accept_langs_list.end(); ++iter) { 891 iter != accept_langs_list.end(); ++iter) {
873 std::string lang_code = GetLanguageCode(*iter); 892 std::string lang_code = GetLanguageCode(*iter);
874 if (IsSupportedLanguage(lang_code)) 893 if (IsSupportedLanguage(lang_code))
875 return lang_code; 894 return lang_code;
876 } 895 }
877 return std::string(); 896 return std::string();
878 } 897 }
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698