module Receive ( receiveMails ) where import Text.Estraier.EstDB import QDBM.Curia (Curia) import QDBM.Depot as D import Graphics.UI.WX hiding (when) import Graphics.UI.WXCore hiding (when) import Control.Exception import Control.Monad import qualified Network.POP3 as POP3 import SingleMail import Maildir import Config import Prelude hiding (catch) dialogStyle = 0x1 -- can_abort + 0x4 -- auto_hide + 0x40 -- remaining_time receivePOP3 :: Window a -> POP3.Connection -> Depot -> (EstDB, Curia) -> [String] -> IO () receivePOP3 w conn uidldb db tags = do uidls <- POP3.allUIDLs conn dialog <- progressDialogCreate ("receive from POP server") "" (length uidls) w dialogStyle zipWithM_ (retrieve dialog) uidls [1..] `catch` (\_ -> return ()) progressDialogUpdate dialog (length uidls) return () where retrieve dialog (mid, uidl) n = do hasKey uidldb uidl >>= \flag -> unless flag $ do mail <- POP3.retr conn mid addSingleMail mail tags db insert uidldb uidl (show mid) canceled <- progressDialogUpdateWithMessage dialog n (show mid) when (canceled == 0) $ fail "canceled" receivePOP3Del :: Window a -> POP3.Connection -> (EstDB, Curia) -> [String] -> IO () receivePOP3Del w conn db tags = do msgs <- POP3.allList conn dialog <- progressDialogCreate ("receive from POP server") "" (length msgs) w dialogStyle zipWithM_ (retrieve dialog) msgs [1..] `catch` (\_ -> return ()) progressDialogUpdate dialog (length msgs) return () where retrieve dialog (mid, _) n = do mail <- POP3.retr conn mid addSingleMail mail tags db POP3.dele conn mid progressDialogUpdateWithMessage dialog n (show mid) receiveMaildir :: Window a -> FilePath -> (EstDB, Curia) -> [String] -> Bool -> IO () receiveMaildir w path db tags isRecur = (maildirDo w db tags path "new" True) `catch` (\_ -> return ()) receiveMails :: Window a -> Config -> (EstDB, Curia) -> IO () receiveMails w config db = mapM_ (\(r, t) -> receiver r t `catch` errorProc) $ receive config where errorProc exn = errorDialog w "receive error" (show exn) receiver (Maildir mdir) tags = receiveMaildir w mdir db tags True receiver (POP3Server hostname pnum auth isDel) tags = POP3.doPop3Port hostname pnum $ \conn -> do authenticate conn auth if isDel then receivePOP3Del w conn db tags else do uidls <- open "_uidl" [DpReader, DpWriter, DpCreat] receivePOP3 w conn uidls db tags D.close uidls authenticate conn (POP3.PlainAuth user pass) = do (u, p) <- getPass user pass unless (any null [u, p]) $ POP3.auth conn u p authenticate conn (POP3.ApopAuth user pass) = do (u, p) <- getPass user pass unless (any null [u, p]) $ POP3.apop conn u p getPass "" pass = do u <- textDialog w "input name" "your account" "" if (null u) then return ("", pass) else getPass u pass getPass user "" = do p <- passwordDialog w "input password" "password" "" return (user, p) getPass user pass = return (user, pass)