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
3 // found in the LICENSE file.
5 #include "content/renderer/android/phone_number_detector.h"
9 #include "base/string_util.h"
10 #include "base/utf_string_conversions.h"
11 #include "content/public/renderer/android_content_detection_prefixes.h"
12 #include "net/base/escape.h"
13 #include "third_party/libphonenumber/src/phonenumber_api.h"
14 #include "third_party/libphonenumber/src/phonenumbers/phonenumbermatch.h"
15 #include "third_party/libphonenumber/src/phonenumbers/phonenumbermatcher.h"
16 #include "third_party/libphonenumber/src/phonenumbers/region_code.h"
18 using i18n::phonenumbers::PhoneNumberMatch
;
19 using i18n::phonenumbers::PhoneNumberMatcher
;
20 using i18n::phonenumbers::PhoneNumberUtil
;
21 using i18n::phonenumbers::RegionCode
;
25 // Maximum number of characters to look around for phone number detection.
26 const size_t kMaximumTelephoneLength
= 20;
28 } // anonymous namespace
32 PhoneNumberDetector::PhoneNumberDetector()
33 : region_code_(RegionCode::GetUnknown()) {
36 // Region should be empty or an ISO 3166-1 alpha-2 country code.
37 PhoneNumberDetector::PhoneNumberDetector(const std::string
& region
)
38 : region_code_(region
.empty() ? RegionCode::GetUnknown()
39 : StringToUpperASCII(region
)) {
42 PhoneNumberDetector::~PhoneNumberDetector() {
45 size_t PhoneNumberDetector::GetMaximumContentLength() {
46 return kMaximumTelephoneLength
;
49 GURL
PhoneNumberDetector::GetIntentURL(const std::string
& content_text
) {
50 if (content_text
.empty())
53 return GURL(kPhoneNumberPrefix
+
54 net::EscapeQueryParamValue(content_text
, true));
57 bool PhoneNumberDetector::FindContent(const string16::const_iterator
& begin
,
58 const string16::const_iterator
& end
,
61 std::string
* content_text
) {
62 string16 utf16_input
= string16(begin
, end
);
63 std::string utf8_input
= UTF16ToUTF8(utf16_input
);
65 PhoneNumberMatcher
matcher(utf8_input
, region_code_
);
66 if (matcher
.HasNext()) {
67 PhoneNumberMatch match
;
70 PhoneNumberUtil
* phone_util
= PhoneNumberUtil::GetInstance();
71 phone_util
->FormatNumberForMobileDialing(match
.number(), region_code_
,
72 false, /* with_formatting */
74 // If the number can't be dialed from the current region, the formatted
75 // string will be empty.
76 if (content_text
->empty())
79 // Need to return start_pos and end_pos relative to a UTF16 encoding.
80 *start_pos
= UTF8ToUTF16(utf8_input
.substr(0, match
.start())).length();
81 *end_pos
= *start_pos
+ UTF8ToUTF16(match
.raw_string()).length();
89 } // namespace content