From 60e62ee05f75d0b76a4d5668b3b21b9f33fd4cf9 Mon Sep 17 00:00:00 2001 From: Ben Sima Date: Wed, 31 Jan 2018 09:27:39 -0800 Subject: Parse phone numbers into E164 format --- main.hs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) (limited to 'main.hs') diff --git a/main.hs b/main.hs index 04acafc..8845d3f 100755 --- a/main.hs +++ b/main.hs @@ -44,11 +44,23 @@ import Control.Monad import Control.Monad.Reader (ask) import Control.Monad.State (get, put) import Data.Maybe (isJust) -import Data.Text (Text, pack, unpack) +import Data.Text (Text, pack, unpack, isPrefixOf) import Yesod hiding (Number, Update, update, get) import Network.HTTP.Types.Status (status400, status200) import Data.Aeson hiding (Number) +---------------------------------------------------------------------- +-- | Parser for standardizing phone number format + +-- To properly implement this, I would use libphonenumber +parsePhoneNumber :: Text -> Text +parsePhoneNumber = countryCode . pack . stripInvalidChars . unpack + where + stripInvalidChars :: String -> String + countryCode :: Text -> Text + stripInvalidChars cs = [ c | c <- cs, not $ elem c (".()- " :: String) ] + countryCode t = if (isPrefixOf "+" t) then t else ("+1" <> t) + -------------------------------------------------------------------- -- | Here be the state and data model stuff. @@ -90,7 +102,7 @@ $(deriveSafeCopy 0 'base ''Context) instance Indexable Caller where empty = ixSet [ ixFun $ (:[]) . callerId , ixFun $ \c -> [ Name $ name c ] - , ixFun $ \c -> [ PhoneNumber $ number c ] + , ixFun $ \c -> [ PhoneNumber $ parsePhoneNumber $ number c ] , ixFun $ \c -> [ Context $ context c ] ] @@ -122,7 +134,7 @@ addCaller name number context = do db@Database{..} <- get let caller = Caller { callerId = nextCallerId , name = name - , number = number + , number = parsePhoneNumber number , context = context } put $ db { nextCallerId = succ nextCallerId , callers = IxSet.insert caller callers -- cgit v1.2.3