@@ -1,5 +1,5 @@
1{-# LANGUAGE OverloadedStrings #-}
1{-# LANGUAGE OverloadedStrings #-}
2−module Web.Connexpay.Init where
2+module Web.Connexpay.Init (initConnexpay) where
4import Web.Connexpay.Auth
4import Web.Connexpay.Auth
5import Web.Connexpay.Data
5import Web.Connexpay.Data
@@ -26,7 +26,7 @@ initConnexpay :: (Text -> IO ()) -- ^ Logging function
26 -> Text -- ^ Password.
26 -> Text -- ^ Password.
27 -> IO (Either ConnexpayError Connexpay)
27 -> IO (Either ConnexpayError Connexpay)
28initConnexpay logf mgr devguid url tls login password =
28initConnexpay logf mgr devguid url tls login password =
29− do v <- newEmptyMVar
29+ do v <- newMVar Nothing
30 let env = Connexpay { logAction = logf
30 let env = Connexpay { logAction = logf
31 , manager = mgr
31 , manager = mgr
32 , bearerToken = v
32 , bearerToken = v
@@ -38,19 +38,30 @@ initConnexpay logf mgr devguid url tls login password =
38 , password = password
38 , password = password
40 runConnexpay env $ do
40 runConnexpay env $ do
41− (tok, ts) <- authenticate
41+ ts <- initialAuth v logf
42− a <- liftIO $ do logf "Connexpay authentication success"
44− async (runConnexpay_ env $ updateToken ts)
42+ a <- liftIO (async (runConnexpay_ env $ updateToken ts))
45 pure (env { refreshAsync = Just a })
43 pure (env { refreshAsync = Just a })
45+initialAuth :: MVar (Maybe BearerToken) -> (Text -> IO ()) -> ConnexpayM Natural
47+ do (tok, ts) <- authenticate
48+ liftIO $ do logf "Connexpay authentication success"
49+ void (swapMVar v (Just tok))
51+ `catchError` \err -> do
52+ liftIO (logf ("Initial connexpay authentication failed: " <> tshow err))
53+ -- if initial authentication failed, wait 1 second?
54+ -- there isn't much else to do, really.
47updateToken :: Natural -> ConnexpayM ()
58updateToken :: Natural -> ConnexpayM ()
48updateToken w = liftIO (threadDelay w') >> upd
59updateToken w = liftIO (threadDelay w') >> upd
49 where w' = fromIntegral w * 1000000
60 where w' = fromIntegral w * 1000000
50 upd = do (tok, ts) <- authenticate
61 upd = do (tok, ts) <- authenticate
51 logf <- asks (.logAction)
62 logf <- asks (.logAction)
52 tokVar <- asks (.bearerToken)
63 tokVar <- asks (.bearerToken)
53− liftIO (void $ swapMVar tokVar tok)
64+ liftIO (void $ swapMVar tokVar (Just tok))
54 liftIO (logf "Connexpay token update success")
65 liftIO (logf "Connexpay token update success")
55 updateToken (ts - 5)
66 updateToken (ts - 5)
56 `catchError` \err -> do
67 `catchError` \err -> do