Search in sources :

Example 16 with PhoneNumberUtil

use of com.google.i18n.phonenumbers.PhoneNumberUtil in project Signal-Android by WhisperSystems.

the class ShortCodeUtil method isShortCode.

public static boolean isShortCode(@NonNull String localNumber, @NonNull String number) {
    try {
        PhoneNumberUtil util = PhoneNumberUtil.getInstance();
        Phonenumber.PhoneNumber localNumberObject = util.parse(localNumber, null);
        String localCountryCode = util.getRegionCodeForNumber(localNumberObject);
        String bareNumber = number.replaceAll("[^0-9+]", "");
        // libphonenumber seems incorrect for Russia and a few other countries with 4 digit short codes.
        if (bareNumber.length() <= 4 && !SHORT_COUNTRIES.contains(localCountryCode)) {
            return true;
        }
        Phonenumber.PhoneNumber shortCode = util.parse(number, localCountryCode);
        return ShortNumberInfo.getInstance().isPossibleShortNumberForRegion(shortCode, localCountryCode);
    } catch (NumberParseException e) {
        Log.w(TAG, e);
        return false;
    }
}
Also used : PhoneNumberUtil(com.google.i18n.phonenumbers.PhoneNumberUtil) NumberParseException(com.google.i18n.phonenumbers.NumberParseException) Phonenumber(com.google.i18n.phonenumbers.Phonenumber)

Example 17 with PhoneNumberUtil

use of com.google.i18n.phonenumbers.PhoneNumberUtil in project Signal-Android by WhisperSystems.

the class NumberViewState method getCountryDisplayName.

public String getCountryDisplayName() {
    if (selectedCountryName != null) {
        return selectedCountryName;
    }
    PhoneNumberUtil util = PhoneNumberUtil.getInstance();
    if (isValid()) {
        String actualCountry = getActualCountry(util, getE164Number());
        if (actualCountry != null) {
            return actualCountry;
        }
    }
    String regionCode = util.getRegionCodeForCountryCode(countryCode);
    return PhoneNumberFormatter.getRegionDisplayNameLegacy(regionCode);
}
Also used : PhoneNumberUtil(com.google.i18n.phonenumbers.PhoneNumberUtil)

Example 18 with PhoneNumberUtil

use of com.google.i18n.phonenumbers.PhoneNumberUtil in project wire-android by wireapp.

the class CountryController method populateCountries.

@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
private void populateCountries(Context context) {
    List<Country> countries = new ArrayList<>();
    String deviceLanguage;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        // noinspection deprecation
        deviceLanguage = context.getResources().getConfiguration().locale.getLanguage();
    } else {
        deviceLanguage = context.getResources().getConfiguration().getLocales().get(0).getLanguage();
    }
    PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
    for (String region : phoneNumberUtil.getSupportedRegions()) {
        Locale locale = new Locale(deviceLanguage, region);
        Country country = new Country();
        country.setAbbreviation(locale.getCountry());
        country.setCountryCode(Integer.toString(phoneNumberUtil.getCountryCodeForRegion(region)));
        country.setName(locale.getDisplayCountry());
        countries.add(country);
    }
    for (Country country : countries) {
        codeToCountryMap.put(country.getCountryCode(), country);
        abbreviationToCountryMap.put(country.getAbbreviation(), country);
    }
}
Also used : Locale(java.util.Locale) PhoneNumberUtil(com.google.i18n.phonenumbers.PhoneNumberUtil) ArrayList(java.util.ArrayList)

Example 19 with PhoneNumberUtil

use of com.google.i18n.phonenumbers.PhoneNumberUtil in project mxisd by kamax-io.

the class AuthManager method proxyLogin.

public String proxyLogin(URI target, String body) {
    JsonObject reqJsonObject = io.kamax.matrix.json.GsonUtil.parseObj(body);
    GsonUtil.findObj(reqJsonObject, IdentifierKey).ifPresent(obj -> {
        GsonUtil.findString(obj, TypeKey).ifPresent(type -> {
            if (StringUtils.equals(type, UserIdTypeValue)) {
                log.info("Login request is User ID type");
                if (cfg.getRewrite().getUser().getRules().isEmpty()) {
                    log.info("No User ID rewrite rules to apply");
                } else {
                    log.info("User ID rewrite rules: checking for a match");
                    String userId = GsonUtil.getStringOrThrow(obj, UserKey);
                    for (AuthenticationConfig.Rule m : cfg.getRewrite().getUser().getRules()) {
                        if (m.getPattern().matcher(userId).matches()) {
                            log.info("Found matching pattern, resolving to 3PID with medium {}", m.getMedium());
                            // Remove deprecated login info on the top object if exists to avoid duplication
                            reqJsonObject.remove(UserKey);
                            obj.addProperty(TypeKey, ThreepidTypeValue);
                            obj.addProperty(ThreepidMediumKey, m.getMedium());
                            obj.addProperty(ThreepidAddressKey, userId);
                            log.info("Rewrite to 3PID done");
                        }
                    }
                    log.info("User ID rewrite rules: done checking rules");
                }
            }
        });
    });
    GsonUtil.findObj(reqJsonObject, IdentifierKey).ifPresent(obj -> {
        GsonUtil.findString(obj, TypeKey).ifPresent(type -> {
            if (StringUtils.equals(type, ThreepidTypeValue)) {
                // Remove deprecated login info if exists to avoid duplication
                reqJsonObject.remove(ThreepidMediumKey);
                reqJsonObject.remove(ThreepidAddressKey);
                GsonUtil.findPrimitive(obj, ThreepidMediumKey).ifPresent(medium -> {
                    GsonUtil.findPrimitive(obj, ThreepidAddressKey).ifPresent(address -> {
                        log.info("Login request with medium '{}' and address '{}'", medium.getAsString(), address.getAsString());
                        strategy.findLocal(medium.getAsString(), address.getAsString()).ifPresent(lookupDataOpt -> {
                            obj.remove(ThreepidMediumKey);
                            obj.remove(ThreepidAddressKey);
                            obj.addProperty(TypeKey, UserIdTypeValue);
                            obj.addProperty(UserKey, lookupDataOpt.getMxid().getLocalPart());
                        });
                    });
                });
            }
            if (StringUtils.equals(type, "m.id.phone")) {
                // Remove deprecated login info if exists to avoid duplication
                reqJsonObject.remove(ThreepidMediumKey);
                reqJsonObject.remove(ThreepidAddressKey);
                GsonUtil.findPrimitive(obj, "number").ifPresent(number -> {
                    GsonUtil.findPrimitive(obj, "country").ifPresent(country -> {
                        log.info("Login request with phone '{}'-'{}'", country.getAsString(), number.getAsString());
                        try {
                            PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
                            Phonenumber.PhoneNumber phoneNumber = phoneUtil.parse(number.getAsString(), country.getAsString());
                            String msisdn = phoneUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164).replace("+", "");
                            String medium = "msisdn";
                            strategy.findLocal(medium, msisdn).ifPresent(lookupDataOpt -> {
                                obj.remove("country");
                                obj.remove("number");
                                obj.addProperty(TypeKey, UserIdTypeValue);
                                obj.addProperty(UserKey, lookupDataOpt.getMxid().getLocalPart());
                            });
                        } catch (NumberParseException e) {
                            log.error("Not a valid phone number");
                            throw new RuntimeException(e);
                        }
                    });
                });
            }
        });
    });
    // invoke 'login' on homeserver
    HttpPost httpPost = RestClientUtils.post(resolveProxyUrl(target), gson, reqJsonObject);
    try (CloseableHttpResponse httpResponse = client.execute(httpPost)) {
        // check http status
        int status = httpResponse.getStatusLine().getStatusCode();
        log.info("http status = {}", status);
        if (status != 200) {
            // try to get possible json error message from response
            // otherwise just get returned plain error message
            String errcode = String.valueOf(httpResponse.getStatusLine().getStatusCode());
            String error = EntityUtils.toString(httpResponse.getEntity());
            if (httpResponse.getEntity() != null) {
                try {
                    JsonObject bodyJson = new JsonParser().parse(error).getAsJsonObject();
                    if (bodyJson.has("errcode")) {
                        errcode = bodyJson.get("errcode").getAsString();
                    }
                    if (bodyJson.has("error")) {
                        error = bodyJson.get("error").getAsString();
                    }
                    throw new RemoteLoginException(status, errcode, error, bodyJson);
                } catch (JsonSyntaxException e) {
                    log.warn("Response body is not JSON");
                }
            }
            throw new RemoteLoginException(status, errcode, error);
        }
        // return response
        HttpEntity entity = httpResponse.getEntity();
        if (Objects.isNull(entity)) {
            log.warn("Expected HS to return data but got nothing");
            return "";
        } else {
            return IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) PhoneNumberUtil(com.google.i18n.phonenumbers.PhoneNumberUtil) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) RemoteLoginException(io.kamax.mxisd.exception.RemoteLoginException) AuthenticationConfig(io.kamax.mxisd.config.AuthenticationConfig) JsonSyntaxException(com.google.gson.JsonSyntaxException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) NumberParseException(com.google.i18n.phonenumbers.NumberParseException) Phonenumber(com.google.i18n.phonenumbers.Phonenumber) JsonParser(com.google.gson.JsonParser)

Example 20 with PhoneNumberUtil

use of com.google.i18n.phonenumbers.PhoneNumberUtil in project libsignal-service-java by signalapp.

the class PhoneNumberFormatter method formatE164.

public static String formatE164(String countryCode, String number) {
    try {
        PhoneNumberUtil util = PhoneNumberUtil.getInstance();
        int parsedCountryCode = Integer.parseInt(countryCode);
        PhoneNumber parsedNumber = util.parse(number, util.getRegionCodeForCountryCode(parsedCountryCode));
        return util.format(parsedNumber, PhoneNumberUtil.PhoneNumberFormat.E164);
    } catch (NumberParseException | NumberFormatException npe) {
        Log.w(TAG, npe);
    }
    return "+" + countryCode.replaceAll("[^0-9]", "").replaceAll("^0*", "") + number.replaceAll("[^0-9]", "");
}
Also used : PhoneNumberUtil(com.google.i18n.phonenumbers.PhoneNumberUtil) PhoneNumber(com.google.i18n.phonenumbers.Phonenumber.PhoneNumber) NumberParseException(com.google.i18n.phonenumbers.NumberParseException)

Aggregations

PhoneNumberUtil (com.google.i18n.phonenumbers.PhoneNumberUtil)47 NumberParseException (com.google.i18n.phonenumbers.NumberParseException)34 PhoneNumber (com.google.i18n.phonenumbers.Phonenumber.PhoneNumber)23 Phonenumber (com.google.i18n.phonenumbers.Phonenumber)13 IndicatorParameters (org.talend.dataquality.indicators.IndicatorParameters)6 TextParameters (org.talend.dataquality.indicators.TextParameters)6 Locale (java.util.Locale)5 SuppressLint (android.annotation.SuppressLint)4 Nullable (androidx.annotation.Nullable)2 PhoneNumberOfflineGeocoder (com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder)2 RemoteLoginException (io.kamax.mxisd.exception.RemoteLoginException)2 IOException (java.io.IOException)2 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)2 HttpPost (org.apache.http.client.methods.HttpPost)2 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)2 GenericValue (org.apache.ofbiz.entity.GenericValue)2 SpannableString (android.text.SpannableString)1 JsonObject (com.google.gson.JsonObject)1 JsonParser (com.google.gson.JsonParser)1 JsonSyntaxException (com.google.gson.JsonSyntaxException)1