module Happstack.Server.I18N
( acceptLanguage
, bestLanguage
) where
import Control.Applicative ((<$>))
import Control.Arrow ((>>>), first, second)
import Data.Function (on)
import qualified Data.ByteString.Char8 as C
import Data.List (sortBy)
import Data.Maybe (fromMaybe)
import Data.Text as Text (Text, breakOnAll, pack, singleton)
import Happstack.Server.Monads (Happstack, getHeaderM)
import Happstack.Server.Internal.Compression (encodings)
import Text.ParserCombinators.Parsec (parse)
acceptLanguage :: (Happstack m) => m [(Text, Maybe Double)]
acceptLanguage =
do mAcceptLanguage <- (fmap C.unpack) <$> getHeaderM "Accept-Language"
case mAcceptLanguage of
Nothing -> return []
(Just al) ->
case parse encodings al al of
(Left _) -> return []
(Right encs) -> return (map (first Text.pack) encs)
bestLanguage :: [(Text, Maybe Double)] -> [Text]
bestLanguage range =
map (second $ fromMaybe 1) >>>
sortBy (flip compare `on` snd) >>>
filter (\(lang, q) -> lang /= (Text.singleton '*') && q > 0) >>>
concatMap (explode . fst) $
range
where
explode :: Text -> [Text]
explode lang = lang : (reverse $ map fst $ breakOnAll (singleton '-') lang)