]> code.delx.au - offlineimap/blob - src/Network/IMAP/Parser.hs
1158c070321d30cf4e11aad322b69d31a8f15b63
[offlineimap] / src / Network / IMAP / Parser.hs
1 {- offlineimap component
2 Copyright (C) 2008 John Goerzen <jgoerzen@complete.org>
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 -}
18
19 module Network.IMAP.Parser where
20 import Text.ParserCombinators.Parsec
21 import Network.IMAP.Types
22 import Text.Regex.Posix
23 import Data.Int
24 import Data.List
25
26 {- | Read a full response from the server. -}
27 readFullResponse :: Monad m =>
28 IMAPConnection m -> -- ^ The connection to the server
29 m IMAPString
30 readFullResponse conn =
31 accumLines []
32 where accumLines accum =
33 do line <- getFullLine [] conn
34 if "* " `isPrefixOf` line
35 then accumLines (accum ++ line ++ "\r\n")
36 else return (accum ++ line ++ "\r\n")
37
38 {- | Read a full line from the server, handling any continuation stuff.
39
40 If a {x}\r\n occurs, then that string (including the \r\n) will occur
41 literally in the result, followed by the literal read, and the rest of the
42 data.
43 -}
44
45 getFullLine :: Monad m =>
46 IMAPString -> -- ^ The accumulator (empty for first call)
47 IMAPConnection m -> -- ^ IMAP connection
48 m IMAPString -- ^ Result
49
50 getFullLine accum conn =
51 do input <- readLine conn
52 case checkContinuation input of
53 Nothing -> return (accum ++ input)
54 Just (size) ->
55 do literal <- readBytes conn size
56 getFullLine (accum ++ input ++ "\r\n" ++ literal) conn
57 where checkContinuation :: String -> Maybe Int64
58 checkContinuation i =
59 case i =~ "\\{([0-9]+)\\}$" :: (String, String, String, [String]) of
60 (_, _, _, [x]) -> Just (read x)
61 _ -> Nothing