-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathMessage.hs
86 lines (73 loc) · 1.9 KB
/
Message.hs
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
module Message (ServerMessage(..),
ClientMessage(..),
parseMsg) where
import Debug.Trace
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Error
-- Messages from the client to the server
data ServerMessage =
Login String |
SPrivateMessage String String |
SRoomMessage String String |
Join String |
Part String |
Logout |
Invalid String |
StopThread deriving (Read, Show, Eq)
-- Messages from the server to the client
data ClientMessage =
Ok |
Error String |
CPrivateMessage String String |
CRoomMessage String String String deriving (Read, Eq)
instance Show ClientMessage where
show Message.Ok = "OK"
show (CPrivateMessage from msg) = "GOTUSERMSG " ++ from ++ " " ++ msg
show (CRoomMessage from room msg) = "GOTROOMMSG " ++ from ++ " #" ++ room ++ " " ++ msg
show (Message.Error msg) = "ERROR " ++ msg
parseMsg :: String -> ServerMessage
parseMsg msg = case parse messageParser "Network" msg of
Left err -> Invalid ("Error parsing: " ++ (show err))
Right msg -> trace ("Got message: " ++ (show msg)) $ msg
messageParser :: Parser ServerMessage
messageParser =
try parseLogin
<|> try parseJoin
<|> try parsePrivateMessage
<|> try parseRoomMessage
<|> try parsePart
<|> try parseLogout
<|> return (Invalid "Couldn't parse")
parseLogin = do
s <- string "LOGIN "
name <- many (noneOf " ")
eof
return (Login name)
parseJoin = do
string "JOIN #"
room <- many (noneOf " ")
eof
return (Join room)
parsePrivateMessage = do
string "MSG "
to <- many (noneOf " #")
char ' '
msg <- many anyChar
eof
return (SPrivateMessage to msg)
parseRoomMessage = do
string "MSG #"
to <- many (noneOf " ")
char ' '
msg <- many anyChar
eof
return (SRoomMessage to msg)
parsePart = do
string "PART #"
room <- many (noneOf " ")
eof
return (Part room)
parseLogout = do
string "LOGOUT"
eof
return Logout