@@ -1,5 +1,5 @@
11{-# LANGUAGE OverloadedStrings #-}
2−module Web.Connexpay.Init where
2+module Web.Connexpay.Init (initConnexpay) where
33
44import Web.Connexpay.Auth
55import Web.Connexpay.Data
@@ -26,7 +26,7 @@ initConnexpay :: (Text -> IO ()) -- ^ Logging function
2626 -> Text -- ^ Password.
2727 -> IO (Either ConnexpayError Connexpay)
2828initConnexpay logf mgr devguid url tls login password =
29− do v <- newEmptyMVar
29+ do v <- newMVar Nothing
3030 let env = Connexpay { logAction = logf
3131 , manager = mgr
3232 , bearerToken = v
@@ -38,19 +38,30 @@ initConnexpay logf mgr devguid url tls login password =
3838 , password = password
3939 }
4040 runConnexpay env $ do
41− (tok, ts) <- authenticate
42− a <- liftIO $ do logf "Connexpay authentication success"
43− putMVar v tok
44− async (runConnexpay_ env $ updateToken ts)
41+ ts <- initialAuth v logf
42+ a <- liftIO (async (runConnexpay_ env $ updateToken ts))
4543 pure (env { refreshAsync = Just a })
4644
45+initialAuth :: MVar (Maybe BearerToken) -> (Text -> IO ()) -> ConnexpayM Natural
46+initialAuth v logf =
47+ do (tok, ts) <- authenticate
48+ liftIO $ do logf "Connexpay authentication success"
49+ void (swapMVar v (Just tok))
50+ return ts
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.
55+ return 1
56+
57+
4758updateToken :: Natural -> ConnexpayM ()
4859updateToken w = liftIO (threadDelay w') >> upd
4960 where w' = fromIntegral w * 1000000
5061 upd = do (tok, ts) <- authenticate
5162 logf <- asks (.logAction)
5263 tokVar <- asks (.bearerToken)
53− liftIO (void $ swapMVar tokVar tok)
64+ liftIO (void $ swapMVar tokVar (Just tok))
5465 liftIO (logf "Connexpay token update success")
5566 updateToken (ts - 5)
5667 `catchError` \err -> do