# Technical Documentation: google/libphonenumber

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/google/libphonenumber)

### Overview (`README.md`)

<p align="right">
<img src="https://travis-ci.org/google/libphonenumber.svg?branch=master">
</p>

# What is it?

Google's common Java, C++ and JavaScript library for parsing, formatting, and
validating international phone numbers. The Java version is optimized for
running on smartphones, and is used by the Android framework since 4.0 (Ice
Cream Sandwich).

# Quick links

*   **Reporting an issue?** Want to send a pull request? See the [contribution
    guidelines](CONTRIBUTING.md)
*   Check the [frequently asked questions](FAQ.md)
*   Fun! [Falsehoods Programmers Believe About Phone Numbers](FALSEHOODS.md)
*   Look for
    [`README`s](https://github.com/google/libphonenumber/find/master) in
    directories relevant to the code you're interested in.
*   For contributors and porters: [How to run the Java demo](run-java-demo.md)
*   For porters: [How to make metadata changes](making-metadata-changes.md)

# Highlights of functionality

*   Parsing, formatting, and validating phone numbers for all countries/regions
    of the world.
*   `getNumberType` - gets the type of the number based on the number itself;
    able to distinguish Fixed-line, Mobile, Toll-free, Premium Rate, Shared
    Cost, VoIP, Personal Numbers, UAN, Pager, and Voicemail (whenever feasible).
*   `isNumberMatch` - gets a confidence level on whether two numbers could be
    the same.
*   `getExampleNumber` and `getExampleNumberForType` - provide valid example
    numbers for all countries/regions, with the option of specifying which type
    of example phone number is needed.
*   `isPossibleNumber` - quickly guesses whether a number is a possible
    phone number by using only the length information, much faster than a full
    validation.
*   `isValidNumber` - full validation of a phone number for a region using
    length and prefix information.
*   `AsYouTypeFormatter` - formats phone numbers on-the-fly when users enter
    each digit.
*   `findNumbers` - finds numbers in text.
*   `PhoneNumberOfflineGeocoder` - provides geographical information related to
    a phone number.
*   `PhoneNumberToCarrierMapper` - provides carrier information related to a
    phone number.
*   `PhoneNumberToTimeZonesMapper` - provides timezone information related to a
    phone number.

# Demo

## Java

The [Java demo](https://libphonenumber.appspot.com/) is updated with a slight
delay after the GitHub release.

Last demo update: v9.0.41.

Note: Even though the library (main branch/[maven release](https://repo1.maven.org/maven2/com/googlecode/libphonenumber/libphonenumber/8.12.56/))
is at v8.12.57, because of some deployment issues, we were unable to update the
Java demo with the new binary version. We will soon fix this. Meantime, please
use JS demo.

If this number is lower than the [latest release's version
number](https://github.com/google/libphonenumber/releases), we are between
releases and the demo may be at either version.

### Demo App

There is a demo Android App called [E.164 Formatter](java/demoapp) in this
repository. The purpose of this App is to show an example of how the library can
be used in a real-life situation, in this case specifically in an Android App
using Java.

## JavaScript

The [JavaScript
demo](https://htmlpreview.github.io/?https://github.com/google/libphonenumber/blob/master/javascript/i18n/phonenumbers/demo-compiled.html)
may be run at various tags; this link will take you to `master`.

# Java code

To include the Java code in your application, either integrate with Maven (see
[wiki](https://github.com/google/libphonenumber/wiki)) or download the latest
jars from the [Maven
repository](https://repo1.maven.org/maven2/com/googlecode/libphonenumber/libphonenumber/).

# Javadoc

Javadoc is automatically updated to reflect the latest release at
https://javadoc.io/doc/com.googlecode.libphonenumber/libphonenumber/.

# Versioning and Announcements

We generally choose the release number following these guidelines.

If any of the changes pushed to master since the last release are incompatible
with the intent / specification of an existing libphonenumber API or may cause
libphonenumber (Java, C++, or JS) clients to have to change their code to keep
building, we publish a major release. For example, if the last release were
7.7.3, the new one would be 8.0.0.

If any of those changes *enable* clients to update their code to take advantage
of new functionality, and if clients would have to roll-back these changes in
the event that the release was marked as "bad", we publish a minor release. For
example, we'd go from 7.7.3 to 7.8.0.

Otherwise, including when a release contains only
[metadata](FAQ.md#metadata_definition) changes, we publish a sub-minor release,
e.g. 7.7.3 to 7.7.4.

Sometimes we make internal changes to the code or metadata that, while not
affecting compatibility for clients, could affect compatibility for **porters**
of the library. For such changes we make announcements to
[libphonenumber-discuss](
https://groups.google.com/forum/#!forum/libphonenumber-discuss). Such changes
are not reflected in the version number, and we would publish a sub-minor
release if there were no other changes.

Want to get notified of new releases? During most of the year, excepting
holidays and extenuating circumstances, we release fortnightly. We update
[release tags](https://github.com/google/libphonenumber/releases) and
document detailed [release notes](
https://github.com/google/libphonenumber/blob/master/release_notes.txt).
We also send an announcement to [libphonenumber-discuss](
https://groups.google.com/forum/#!forum/libphonenumber-discuss) for every
release.

# Quick Examples

Let's say you have a string representing a phone number from Switzerland. This
is how you parse/normalize it into a `PhoneNumber` object:

```java
String swissNumberStr = "044 668 18 00";
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
  PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
} catch (NumberParseException e) {
  System.err.println("NumberParseException was thrown: " + e.toString());
}
```

At this point, `swissNumberProto` contains:

```json
{
  "country_code": 41,
  "national_number": 446681800
}
```

`PhoneNumber` is a class that was originally auto-generated from
`phonenumber.proto` with necessary modifications for efficiency. For details on
the meaning of each field, refer to `resources/phonenumber.proto`.

Now let us validate whether the number is valid:

```java
boolean isValid = phoneUtil.isValidNumber(swissNumberProto); // returns true
```

There are a few formats supported by the formatting method, as illustrated
below:

```java
// Produces "+41 44 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.INTERNATIONAL));
// Produces "044 668 18 00"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.NATIONAL));
// Produces "+41446681800"
System.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.E164));
```

You could also choose to format the number in the way it is dialed from another
country:

```java
// Produces "011 41 44 668 1800", the number when it is dialed in the United States.
System.out.println(phoneUtil.formatOutOfCountryCallingNumber(swissNumberProto, "US"));
```

## Formatting Phone Numbers 'as you type'

```java
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
AsYouTypeFormatter formatter = phoneUtil.getAsYouTypeFormatter("US");
System.out.println(formatter.inputDigit('6'));  // Outputs "6"
...  // Input more digits
System.out.println(formatter.inputDigit('3'));  // Now outputs "650 253"
```

## Geocoding Phone Numbers

```java
PhoneNumberOfflineGeocoder geocoder = PhoneNumberOfflineGeocoder.getInstance();
// Outputs "Zurich"
System.out.println(geocoder.getDescriptionForNumber(swissNumberProto, Locale.ENGLISH));
// Outputs "Zürich"
System.out.println(geocoder.getDescriptionForNumber(swissNumberProto, Locale.GERMAN));
// Outputs "Zurigo"
System.out.println(geocoder.getDescriptionForNumber(swissNumberProto, Locale.ITALIAN));
```

## Mapping Phone Numbers to original carriers

Caveat: We do not provide data about the current carrier of a phone number, only
the original carrier who is assigned the corresponding range. Read about [number
portability](FAQ.md#what-is-mobile-number-portability).

```java
PhoneNumber swissMobileNumber =
    new PhoneNumber().setCountryCode(41).setNationalNumber(798765432L);
PhoneNumberToCarrierMapper carrierMapper = PhoneNumberToCarrierMapper.getInstance();
// Outputs "Swisscom"
System.out.println(carrierMapper.getNameForNumber(swissMobileNumber, Locale.ENGLISH));
```

More examples on how to use the library can be found in the [unit
tests](https://github.com/google/libphonenumber/tree/master/java/libphonenumber/test/com/google/i18n/phonenumbers).

# Third-party Ports

Several third-party ports of the phone number library are known to us. We share
them here in case they're useful for developers.

However, we emphasize that these ports are by developers outside the
libphonenumber project. We do not evaluate their quality or influence their
maintenance processes.

*   C#: https://github.com/twcclegg/libphonenumber-csharp
*   Gleam: https://github.com/massivefermion/phony
*   Go: https://github.com/nyaruka/phonenumbers
*   Objective-c: https://github.com/iziz/libPhoneNumber-iOS
*   Swift: https://github.com/marmelroy/PhoneNumberKit
*   PHP: https://github.com/giggsey/libphonenumber-for-php
*   PostgreSQL in-database types: https://github.com/blm768/pg-libphonenumber
*   Python: https://github.com/daviddrysdale/python-phonenumbers
*   Ruby: https://github.com/ianks/mini_phone
*   Ruby: https://github.com/daddyz/phonelib
*   Ruby: https://github.com/mobi/telephone_number
*   Rust: https://github.com/vloldik/rlibphonenumber
*   Rust: https://github.com/1aim/rust-phonenumber
*   Erlang: https://github.com/marinakr/libphonenumber_erlang
*   Clojure: https://github.com/randomseed-io/phone-number
*   R: https://github.com/socialresearchcentre/dialr/
*   Elixir: https://github.com/socialpaymentsbv/ex_phone_number
*   Salesforce: https://appexchange.salesforce.com/appxListingDetail?listingId=a0N3A00000G12oJUAR
*   Dart: https://github.com/superakabo/dlibphonenumber
*   Delphi / FreePascal: https://github.com/landrix/libphonenumber-pascal
  
Alternatives to our own versions:

*   Android-optimized: Our Java version loads the metadata from
    `Class#getResourcesAsStream` and asks that Android apps follow the Android
    loading best practices of repackaging the metadata and loading from
    `AssetManager#open()` themselves
    ([FAQ](https://github.com/google/libphonenumber/blob/master/FAQ.md#optimize-loads)).
    If you don't want to do this, check out the port at
    https://github.com/MichaelRocks/libphonenumber-android, which does repackage
    the metadata and use `AssetManager#open()`, and may be depended on without
    needing those specific loading optimizations from clients. You should also check
    out the port at https://github.com/lionscribe/libphonenumber-android which also
    supports geocoding, and only requires a one line code change.
*   Javascript: If you don't want to use our version, which depends on Closure,
    there are several other options, including
    https://github.com/catamphetamine/libphonenumber-js - a stripped-down
    rewrite, about 110 KB in size - and
    https://github.com/seegno/google-libphonenumber - a browserify-compatible
    wrapper around the original unmodified library installable via npm, which
    packs the Google Closure library, about 420 KB in size.

Tools based on libphonenumber metadata:

*   Scala: https://github.com/mr-tolmach/raf - library for generating valid phone numbers in the E.164 format

---

### Overview (`javascript/README.md`)

Info:
=====
Google's JavaScript library for parsing, formatting, and validating
international phone numbers.


How to setup:
=============
1.  Checkout closure-library, closure-compiler, closure-linter and python-gflags next to libphonenumber:

* `git clone https://github.com/google/libphonenumber/`

* `git clone https://github.com/google/closure-library/`

* `git clone https://github.com/google/closure-compiler.git`

* `git clone https://github.com/google/closure-linter.git`

* `git clone https://github.com/google/python-gflags.git`

1.  We officially support only these versions of these dependencies:

* Closure library: v20201006

* Closure compiler: v20210302

* Closure linter: v2.3.19

* Python gflags: 3.1.2

Note: We were to build at latest versions of these dependencies, however, we cannot promise that
we continue to support newer version of these dependencies. We learned that newer Closure binaries
deprecate older apis earlier, leading to build breakages.

If you don't checkout the dependencies next to libphonenumber:

1. Change the path of the `<script src="">` in the html pages to point to wherever base.js is located
2. Update `javascript/build.xml` with the correct paths

3. Run the unit tests to make sure everything is working. Open the following pages with your web browser:
  `javascript/i18n/phonenumbers/phonenumberutil_test.html`
  `javascript/i18n/phonenumbers/asyoutypeformatter_test.html`

4. Run the demo: `javascript/i18n/phonenumbers/demo.html`


How to compile:
===============
1. Build the Closure Compiler JAR file by following the directions on the
   [Closure Compiler README](https://github.com/google/closure-compiler/tree/master/README.md).
   If this step doesn't work, try updating your local copy of each of the
   repositories listed above before filing an issue.

2. Compile the demo.js and all its dependencies to one file: `demo-compiled.js`:
  `ant -f javascript/build.xml compile-demo`

3. Run the compiled demo: `javascript/i18n/phonenumbers/demo-compiled.html`


How to use:
===========
To use and compile the library in your own project, use the `javascript/i18n/phonenumbers/demo.js` as an example. You will need to goog.exportSymbol all the methods you use in your html so that the compiler won't rename them. You can then invoke the compiler similarly to how the compile-demo ant target in `javascript/build.xml` invokes it.


How to update:
==============
The JavaScript library is ported from the Java implementation.
When the Java project gets updated follow these steps to update the JavaScript
project:

1. If the protocol buffers (phonemetadata.proto and phonenumber.proto) have changed:
  * Manually update the .pb.js files with the changes of the .proto files.
  * Manually update the toJsArray() Java methods in tools/java/java-build/src/com/google/i18n/phonenumbers/BuildMetadataJsonFromXml.java
  * Build `tools/java/java-build/target/java-build-1.0-SNAPSHOT-jar-with-dependencies.jar` by running: `mvn -f tools/java/java-build/pom.xml package`

2. If the phone number metadata in the XML format has changed `resources/PhoneNumberMetadata.xml` run the following commands to regenerate `metadata.js` and `metadatafortesting.js`:

  `ant -f java/build.xml build-js-metadata`

3. Manually port any changes of the Java code to the JavaScript code:
  * PhoneNumberUtil.java => phonenumberutil.js
  * AsYouTypeFormatter.java => asyoutypeformatter.js
  * PhoneNumberUtilTest.java => phonenumberutil_test.js
  * AsYouTypeFormatterTest.java => asyoutypeformatter_test.js

4. Run the Closure Compiler to get your changes syntax and type checked. This will also generate `demo-compiled.js` used by `demo-compiler.html`

  `ant -f javascript/build.xml compile`

5. Run the Closure Linter to lint the JavaScript files:

  `ant -f javascript/build.xml lint`


Missing functionality:
=====
1. JS port does not support extracting phone-numbers from text (findNumbers).
2. JS port does not have an offline phone number geocoder.
3. JS port of PhoneNumberUtil does not handle all digits, only a subset (JavaScript has no equivalent to the Java Character.digit).

---

### Overview (`metadata/README.md`)

## Libphonenumber Metadata Tools

This directory contains auxiliary libraries to support reading and manipulating
the CSV packaged metadata for libphonenumber client library. The initial release
of these libraries is purely concerned with processing the CSV files, and does
not yet contain the classes needed to convert the CSV data in the XML and other
text files used by libphonenumber.

Eventually it is expected that all the tooling for manipulating CSV metadata and
generating the XML files will be released here, at which time the CSV files will
become the source of truth for libphonenumber and the XML-based metadata and
other mapping files will be automatically derived from it.

## About metadata.zip

It contains canonical metadata for the libphonenumber project, intended for use
by libphonenumber tools. CSV schemas are not promised to be stable.

### Support and Api Stability

**These libraries are not currently supported and do not provide a stable API;
use at your own risk.**

There are no guarantees of stability for the APIs in this library, and while
they are not expected to change dramatically, API tweaks and bug fixes are
inevitable.

### Issues and Contributions

Patches and pull requests cannot be accepted directly on this codebase, so if
you find an issue with these libraries, please open a new issue for it. However
we do not accept feature requests, or provide answers or technical support for
anything in this directory at this time.

---

### Overview (`migrator/README.md`)

# Migrator Library

The library takes in E.164 phone numbers with their corresponding [BCP-47 country code](https://countrycode.org/). If inputted numbers match any of the supported internal renumbering ‘recipes’, which are created from official country documentation, said numbers will undergo a process of migration to convert them into the most up to date, dialable format. A given “recipe” is an internal record which holds data needed to migrate a stale number into one that is valid and dialable. 

## Capabilities

The migrator library can be used as either a [command line tool](#command-line-usage) or a [web application](#web-application). Both applications have the following capabilities:

```Single Number Migration``` - input a single E.164 phone number with its corresponding BCP-47 country code. If there is an available migration recipe, the number will be converted to the new format based on the given recipe. The resulting string of the migration will be outputted to the console.

```File Migration``` - input a text file location with one E.164 number per line along with the BCP-47 country code that corresponds to the numbers in the text file. All numbers in the text file that match available recipes will be migrated and a copy of the text file will be created with the updated numbers. The file path to the newly created text file will be outputted to the console.

```Custom Recipe Migration``` - specify a [custom recipe](#custom-recipe-migrations) file to use for a migration instead of the internal maintained file. Custom recipe migrations will not check if converted numbers are valid based on country formats. 

```Migration Report``` - find all phone numbers in a given input that were migrated with given migration recipes. The report will also show the phone numbers that were already seen as valid before migrations as well as identify any numbers that were migrated into invalid formats based on known valid phone number ranges for the specified country code.

## Command Line Usage

### Required Parameters

```(-n, --number | -f, --file)``` - either the phone number input or file input for a given migration. The number argument must be a single E.164 phone number. This number can be in strict E.164 format (“+841200000000”) or contain hyphens, spaces and curved brackets (“84 (120) 5555-555”). The file argument must be a path to a text file containing one E.164 phone number per line. For file migrations, the original text file will not be overwritten or stored and instead a new text file will be created containing the migrated version of each phone number or the original phone number when a migration did not take place. Original phone numbers will also be written to file when a given migration on a number is seen as invalid, producing a number not dialable for the given country, unless the --exportInvalidMigrations (see [Optional Parameters](#optional-parameters)) flag is specified. Note: all phone numbers entered for migration will be sanitized by removing any whitespace, hyphens or curved brackets. If the number after this process is still not in E.164 format, a migration will not be able to be performed on it.

```-c, --countryCode``` - the BCP-47 country code that corresponds to the given phone number input. Only recipes from this country will be queried to find matching recipes for inputted numbers. (E.g. 44 for United Kingdom, 1 for US, 84 for Vietnam)

### Optional Parameters

```-r, --customRecipe``` - the path to a csv file containing custom migration recipes which follow the standard recipes file format. When using custom recipes, validity checks on migrated numbers will not be performed.

```-e, --exportInvalidMigrations``` - the boolean command line flag specifying that text files created after the migration process for standard file migration job should contain the migrated version of a phone number when a migration has taken place on it, regardless of whether the migration resulted in an invalid phone number. By default, when a migrated number is seen as invalid, its original inputted representation is written to file. Note: this flag has no effect on a --number migration or a migration using a --customRecipe. 

```-h, --help``` - usage help


### Installation and Setup

Start off by using git to download the latest version of the libphonenumber repository:

```bash
git clone https://github.com/google/libphonenumber.git
cd libphonenumber
ls
```

The project must then be built with its dependencies using maven so that an executable jar can be created and run:

```bash
# clean install metadata dependency to run migrator tool
cd metadata
mvn clean install

cd ../migrator
# clean install migrator to run migrator-servlet locally (optional)
mvn clean install

mvn clean compile assembly:single
cd target
ls
```

### Single Number Migration

To perform a single number migration, the “countryCode” and “number” arguments must be specified. The tool will clean the number string to remove spaces, hyphens and curved brackets. Note that when a number contains spaces, the whole string must be enclosed with quotation marks.

An example of a valid migration of a Vietnam phone number is as shown below:

```bash
java -jar migrator-1.0.0-jar-with-dependencies.jar --countryCode=84 --number=+841201234567

# Output:
# Migration of country code +84 phone number(s):
# Successful migration into: +84701234567
```

If the given number is already in a valid format for the given country code, a migration will not occur and instead a message explaining this will be printed:

```bash
java -jar migrator-1.0.0-jar-with-dependencies.jar --countryCode=84 --number=+84(70)123-4567

# Output:
# Migration of country code +84 phone number(s):
# This number was seen to already be valid and dialable based on our data for the given country
```

The migrator tool will not migrate or validate a number that belongs to a different country from the specified country code. In such situations the tool will take no action:

```bash
java -jar migrator-1.0.0-jar-with-dependencies.jar --countryCode=84 --number=”+44 77 12345 678”

# Output:
# Migration of country code +84 phone number(s):
# This number could not be migrated using any of the recipes from the given recipes file
```

### File Migration

To perform a file migration, the “countryCode” and “file” arguments must be specified. The tool will generate a new text file with the outputted numbers once the migration is completed. For the following examples, “VietnamNumbers.txt” is a text file containing the phone numbers:

```bash
VietnamNumbers.txt

84-1201234567
+84(121)7654321
+841225555555
84 120 1424534
+84709000000
+123829734972
373203934781
```
##### Migration using the country code +84:
```bash
java -jar migrator-1.0.0-jar-with-dependencies.jar --countryCode=84 --file=../VietnamNumbers.txt

# Output: 
# Migration of country code +84 phone number(s):
# New numbers file created at: ./+84_Migration_VietnamNumbers.txt
```
```bash
+84_Migration_VietnamNumbers.txt

+84701234567
+84797654321
+84775555555
+84701424534
+84709000000
+123829734972
373203934781
```
##### Migration using the country code +1:
```bash
java -jar migrator-1.0.0-jar-with-dependencies.jar --countryCode=1 --file=../VietnamNumbers.txt 

# Output:
# Migration of country code +1 phone number(s):
# New numbers file created at: ./+1_Migration_VietnamNumbers.txt
```
```bash
+1_Migration_VietnamNumbers.txt

84-1201234567
+84(121)7654321
+841225555555
84 120 1424534
+84709000000
+123829734972
373203934781
```
The above migration run created a text file with the same phone numbers as the original file because there are no +1 phone numbers in the file that could have been migrated.

#### Exporting Invalid Migrations

When performing standard migrations (migrations that do not use custom recipe files), there is a possibility that a migrated phone number is seen as being invalid for the given country code based on internal checks. This will occur when either an internal recipe is erroneous or the internal phone number ranges for a given country code do not properly reflect all valid numbers. In such cases, migrations will be rolled back and the original number will be written to file when running a “file” migration. To allow for invalid migrations to still be written to file, the “exportInvalidMigrations” flag must be specified.

The recipes table below shows a recipe with an error which will cause +84120 phone numbers to be converted invalidly to +8460 instead of +8470 which is the actual valid representation for the given Vietnamese numbers:

```bash
Erroneous Internal Recipe File

Old Prefix   ;   Old Length  ;  Country Code   ;    Old Format     ;    New Format     ;  Description
84120        ;   12          ;  84             ;    xx120xxxxxxx   ;    xx60xxxxxxx    ;  Redial 84120 with 8470
84121        ;   12          ;  84             ;    xx121xxxxxx    ;    xx79xxxxxxx    ;  Redial 84121 with 8479
```

Below is the file input for the example migration runs:

```bash
VietnamNums.txt

84-1201234567
+84(121)7654321
```

##### Example 1 - export original numbers (default):

```bash
java -jar migrator-1.0.0-jar-with-dependencies.jar --countryCode=84 --file=../VietnamNums.txt 

# Output:
# Migration of country code +84 phone number(s):
# New numbers file created at: ./+84_Migration_VietnamNums.txt
```

The created text file will use the original number for the +84120 migration due to the migration being invalid.

```bash
+84_Migration_VietnamNums.txt

84-1201234567
+84797654321
```

##### Example 2 - export invalid migrations:

```bash
java -jar migrator-1.0.0-jar-with-dependencies.jar --countryCode=84 --file=../VietnamNums.txt --exportInvalidMigrations

# Output:
# Migration of country code +84 phone number(s):
# New numbers file created at: ./+84_Migration_VietnamNums.txt
```

Even though the migration was invalid, the newly created text file will use the migrated number for the +84120 migration because the file is set to be exported with invalid migrations.

```bash
+84_Migration_VietnamNums.txt

+84601234567
+84797654321
```

### Custom Recipe Migrations
Custom recipe migrations can be performed on both “number” and “file” type migrations. The additional requirement is that there is a “customRecipe” argument which points to a csv file containing a recipes table in the standard table format. The following is an example of a valid custom recipe file to be used.

```bash
CustomRecipes.csv

Old Prefix ; Old Length ; Country Code ;  Old Format    ;  New Format   ; Description
123        ; 7          ; 1            ;  xx3xxxx       ;  xx99xxxx     ; Custom recipe, replace 3 with 99
001234     ; 7          ; 00           ;  xxxxxxx       ;  xx5xxxxx     ; Custom recipe, add 5 to third index
```

The above recipes file can be used in place of internal recipes by specifying in the following way:

```bash
java -jar migrator-1.0.0-jar-with-dependencies.jar --countryCode=00 --number=0012345 --customRecipe=./CustomRecipes.csv

# Output:
# Migration of country code +00 phone number(s):
# Successful migration into: +00512345
```
### Creating Custom Recipes.csv Files

A Recipes.csv file holds a table containing migration information for all known recipes. A given “recipe” is a row within the table which holds data needed to migrate a stale number into one that is valid and dialable. 

When creating custom recipe files to use, there should never be a case where two recipes can be used to renumber one stale number so as a result, a given stale number can only ever match with one row in a Recipes table. Each column in the file must be separated using ```;``` and the table must have the following columns: 

```Prefix (key)``` - the prefix of the possible stale numbers that can be represented by the row. For example, the prefix of the number “12345” could be “12”. Please note that the prefix cannot be the actual number so for the example case, the prefix could not be “12345”.

```Length (key)``` - the length of all numbers that can be represented in the row. For example a length of 5 for a prefix of “1234” could represent numbers: “12340”, “12341”, “12342”, “12343”, ...

```Old Format``` - represents what digits in the old format need to change where every digit that needs to stay the same is represented as an ‘x’
E.g. the number 7 at the 3rd index of a 4 digit number needs to be removed/replaced. This number is always 7 → xx7x
E.g. an addition needs to happen for a 4 digit number and no digits from the original format need to be changed, so none of the original digits need to be altered → xxxx

```New Format``` - represents what the new number format should be. ‘x’ values represent digits from the original number that will stay the same.
E.g. digits ‘98’ need to be added at the start of an originally 4 digit number → 98xxxx
E.g. no digits need to be added because a removal took place. A 5 digit number has now become a 4 digit number → xxxx

```Description``` - text specifying what the change is in words. This column is used purely for debugging purposes and will help easily diagnose issues with recipes quickly when the strings in the ‘Old Format’ or ‘New Format’ columns are incorrect.

## Web Application

Please [click here](https://phone-number-migrator.uc.r.appspot.com/) to view the web application version of the migrator tool.

## About validation of phone numbers:

APIs and data in [libphonenumber/metadata/](https://github.com/google/libphonenumber/tree/master/metadata/) are used for validating phone numbers. More details in [metadata/README](https://github.com/google/libphonenumber/tree/master/metadata/README).

## Privacy

Both web application and command line versions of the migrator tool require an input of either a single string E.164 phone number or a text file containing one E.164 phone number per line. After the tool has completed the migration process, this data, along with any resulting data, is never written to any records or stored for later use.

## Disclaimer

The migration library is designed to only migrate E.164 phone numbers using internally maintained migration “recipes”. The library will not attempt to migrate national phone numbers or format non-E.164 phone numbers prior to migrations in order for said numbers to be in E.164 format. Only recipes from the specified country code will be used to perform migrations on a given number(s) input. This means that even if a stale E.164 phone number from country A has a recipe that can be used to migrate it successfully but ```--countryCode=B``` is inputted as the command line argument, the phone number will not be migrated.

For standard migrations using internal recipes, it is possible for E.164 phone numbers to be migrated to a format which the library deems as being invalid. The validity of phone numbers is checked using metadata containing valid number ranges for all countries. As a result, a phone number migration will be seen as invalid if either the metadata of valid number ranges does not reflect the given format correctly or if there is an error with the used recipe internally. In either case, please [file a new issue](https://b.corp.google.com/issues/new?component=192347&template=829703) following the guidance of how to create one [here](https://github.com/google/libphonenumber/blob/master/CONTRIBUTING.md#filing-a-code-issue) in order to resolve the issue. For ```--file``` number inputs, invalid migrations by default will not be written to the created text file containing the updated phone numbers and instead, the original number which correlates to the migration will be used. If you would like to include invalid migration results in the newly created text file, specify this by using the ```--exportInvalidMigrations``` command line flag.

When using the ```--customRecipe``` argument, all numbers that match a given recipe from the number input will be migrated. These migrations will not be checked for validity based on internal metadata of valid phone number ranges. This means that for custom recipe migrations, there is no perception of invalid migrations. 

## License
See [LICENSE file](https://github.com/google/libphonenumber/blob/master/LICENSE) for Terms and Conditions.

---

### Overview (`java/demo/README.md`)

# Running the demo

## 1. Install Google Cloud SDK

### Linux

#### Install the Appengine SDK.

`$ sudo apt-get install google-cloud-sdk-app-engine-java`

### Mac

#### Install the Google Cloud SDK.

`$ brew install google-cloud-sdk`

#### Use GCloud CLI to install the Java Appengine

`$ gcloud components install app-engine-java`

## 2. Add IDE Plugin

### Intellij

Install [Cloud Code Plugin for Intellij](https://plugins.jetbrains.com/plugin/8079-cloud-code)

_If you have worked with the App Engine Plugin before,
please [migrate](https://cloud.google.com/code/docs/intellij/migrate)._

### Eclipse

Install [Cloud Code Plugin for Eclipse](https://marketplace.eclipse.org/content/google-cloud-tools-eclipse)

### Visual Studio Code

Install [Cloud Code Plugin for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=GoogleCloudTools.cloudcode&ssr=false#overview)

## 3. Run

Most IDEs should autodetect your configuration after installing the plugin (and
restart)



## (Optional) Run Natively

This is _not recommended_ with an IDE as you have to manage updating your
artifacts yourself, it does not support live reload

`$ mvn appengine:run`

---

### Overview (`java/demoapp/README.md`)

# Demo App: E.164 Formatter

## What is this?

The E.164 Formatter is an Android App that reads all the phone numbers stored in
the device's contacts and processes them using the
[LibPhoneNumber](https://github.com/google/libphonenumber) Library.

The purpose of this App is to show an example of how LPN can be used in a
real-life situation, in this case specifically in an Android App using Java.

## How can I install the app?

You can use the source code to build the app yourself.

## Where is the LPN code located?

The code using LPN is located in
[`PhoneNumberFormatting#formatPhoneNumberInApp(PhoneNumberInApp, String,
boolean)`](app/src/main/java/com/google/phonenumbers/demoapp/phonenumbers/PhoneNumberFormatting.java#L31)
.

## How does the app work?

On the start screen, the app asks the user for a country to later use when
trying to convert the phone numbers to E.164. After the user starts the process
and grants permission to read and write contacts, the app shows the user two
lists in the UI.

**List 1: Formattable**

Contains all the phone number that are parsable by LPN, are not short numbers,
and are valid numbers and can be reformatted to E.164 using the country selected
on the start screen. In other words, valid locally formatted phone numbers of
the selected country (e.g. `044 668 18 00` if the selected country is
Switzerland).

Each list item (= one phone number in the device's contacts) has a checkbox.
With the click of the button "Update selected" under the list, the app replaces
the phone numbers of the checked list elements in the contacts with the
suggested E.164 replacements.

**List 2: Not formattable**

Shows all the phone number that do not fit the criteria of List 1, each tagged
with one of the following errors:

*   Parsing error
*   Short number (e.g. `112`)
*   Invalid number (e.g. `+41446681800123`)
*   Already E.164 (e.g. `+41446681800`)

---

### Overview (`resources/timezones/README.md`)

# Timezone Mapper

The timezone mapper allows a likely timezone to be obtained for a given phone
number. The timezone returned is the canonical ID from [CLDR](
http://www.unicode.org/cldr/charts/latest/supplemental/zone_tzid.html), not a
localised name (or any other identifier). For mobile phones which are associated
with particular area codes, it returns the timezone of the area code; it does
not track the user's current location in any way. This could be used to work out
whether it is likely to be a good time to ring a user based on their provided
number.

Code Location:
[java/geocoder/src/com/google/i18n/phonenumbers/PhoneNumberToTimeZonesMapper.java](https://github.com/google/libphonenumber/blob/master/java/geocoder/src/com/google/i18n/phonenumbers/PhoneNumberToTimeZonesMapper.java)

Example usage:

```
PhoneNumberToTimeZonesMapper timeZonesMapper = PhoneNumberToTimeZonesMapper.getInstance();

List<String> timezones = timeZonesMapper.getTimeZonesForNumber(phoneNumber);
```

## Contributing to the timezone metadata

The timezone metadata is auto-generated with few exceptions, so we cannot accept
pull requests. If we have an error please file an issue and we'll see if we can
make a generic fix.

If making fixes in your own fork while you wait for this, build the metadata by
running this command from the root of the repository (assuming you have `ant`
installed):

```
ant -f java/build.xml build-timezones-data
```

Note that, due to our using stable CLDR timezone IDs, we do not change the ID
for an existing timezone when the name of a region or subdivision changes. The
library returns the *ID*, which you may use to get the localised name from CLDR.

See CLDR's [documentation for timezone
translations](http://cldr.unicode.org/translation/timezones). You can also
browse [different languages'
names](http://www.unicode.org/cldr/charts/latest/verify/zones/index.html); for
example, the `Asia/Calcutta` timezone identifier has English names
`Kolkata Time` and `India Standard Time`, and the [English
file](http://www.unicode.org/cldr/charts/latest/verify/zones/en.html) links to
a [view](http://st.unicode.org/cldr-apps/v#/en/SAsia/2dac3ef061238996) with
other regions having the same timezone (including those with different IDs).

Other relevant CLDR data:
*   http://www.unicode.org/cldr/charts/latest/supplemental/zone_tzid.html
*   http://unicode.org/repos/cldr/trunk/common/bcp47/timezone.xml
*   http://unicode.org/repos/cldr/trunk/common/supplemental/metaZones.xml
*   http://unicode.org/repos/cldr/trunk/common/supplemental/windowsZones.xml

---

--- METRICS ---
- Files Extracted: 7
- Estimated Token Budget: ~9884 tokens
- Canonical Reference: https://codewiki.google/github.com/google/libphonenumber
