msisdn.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # Copyright 2017 Vector Creations Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import phonenumbers
  15. from synapse.api.errors import SynapseError
  16. def phone_number_to_msisdn(country: str, number: str) -> str:
  17. """
  18. Takes an ISO-3166-1 2 letter country code and phone number and
  19. returns an msisdn representing the canonical version of that
  20. phone number.
  21. Args:
  22. country: ISO-3166-1 2 letter country code
  23. number: Phone number in a national or international format
  24. Returns:
  25. The canonical form of the phone number, as an msisdn
  26. Raises:
  27. SynapseError if the number could not be parsed.
  28. """
  29. try:
  30. phoneNumber = phonenumbers.parse(number, country)
  31. except phonenumbers.NumberParseException:
  32. raise SynapseError(400, "Unable to parse phone number")
  33. return phonenumbers.format_number(phoneNumber, phonenumbers.PhoneNumberFormat.E164)[
  34. 1:
  35. ]