1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Common where
import Web.Twitter.Conduit
import Control.Applicative
import Control.Lens
import qualified Data.ByteString.Char8 as S8
import qualified Data.CaseInsensitive as CI
import qualified Data.Map as M
import Network.HTTP.Conduit
import qualified Network.URI as URI
import System.Environment
getOAuthTokens :: IO (OAuth, Credential)
getOAuthTokens = do
consumerKey <- getEnv' "OAUTH_CONSUMER_KEY"
consumerSecret <- getEnv' "OAUTH_CONSUMER_SECRET"
accessToken <- getEnv' "OAUTH_ACCESS_TOKEN"
accessSecret <- getEnv' "OAUTH_ACCESS_SECRET"
let oauth =
twitterOAuth
{ oauthConsumerKey = consumerKey
, oauthConsumerSecret = consumerSecret
}
cred =
Credential
[ ("oauth_token", accessToken)
, ("oauth_token_secret", accessSecret)
]
return (oauth, cred)
where
getEnv' = (S8.pack <$>) . getEnv
getProxyEnv :: IO (Maybe Proxy)
getProxyEnv = do
env <- M.fromList . over (mapped . _1) CI.mk <$> getEnvironment
let u =
M.lookup "https_proxy" env
<|> M.lookup "http_proxy" env
<|> M.lookup "proxy" env >>= URI.parseURI >>= URI.uriAuthority
return $ Proxy <$> (S8.pack . URI.uriRegName <$> u) <*> (parsePort . URI.uriPort <$> u)
where
parsePort :: String -> Int
parsePort [] = 8080
parsePort (':' : xs) = read xs
parsePort xs = error $ "port number parse failed " ++ xs
getTWInfoFromEnv :: IO TWInfo
getTWInfoFromEnv = do
pr <- getProxyEnv
(oa, cred) <- getOAuthTokens
return $ (setCredential oa cred def) {twProxy = pr}
|