-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHircIO.hs
212 lines (184 loc) · 7.14 KB
/
HircIO.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
module HircIO
(CliFlag(..), parseCliArgs, handleCliArgs,
LogLevel(..), logLine,
loadConfig,
Message(..), MOrigin, MCommand, MCommandArgs, Numeric, toNumeric,
ircNetInit, ircConnect, ircSend, ircRecvLoop, readMsg) where
-- Haskell modules
import Data.Char
import Data.List
import Data.Text (pack, strip, unpack)
import Data.Time
import GHC.IO.Handle
import Network
import System.Directory
import System.IO
import System.Locale
import System.Posix.Signals
import HircState
instance Show Message where
show (Message "" c a) = c ++ (showArgs a)
show (Message p c a) = ":" ++ p ++ " " ++ c ++ (showArgs a)
showArgs :: MCommandArgs -> String
showArgs (a:arest) | contains ' ' a = " :" ++ a
| otherwise = " " ++ a ++ (showArgs arest)
showArgs [] = ""
contains :: Eq a => a -> [a] -> Bool
contains item (h:t) | h == item = True
| otherwise = contains item t
contains item [] = False
readMsg :: String -> Message
readMsg s = Message p c a where
(p:rest) = splitIRCLn s
(c:a) = if rest == []
then [""]
else rest
-- split something of format [:prefix] <command> [arg0 arg1 ... argn] [:argrest]
-- into [prefix, command, arg0, arg1, ... argn, argrest]
splitIRCLn :: String -> [String]
splitIRCLn "" = [""]
splitIRCLn line =
-- does the line start with : (if so prefix is present)
let chr1:_ = line
in if chr1 == ':'
then let (prefix, command) = break (== ' ') line
in
-- use prefix and parse rest of list
(drop 1 prefix) : (drop 1 . splitIRCLn . drop 1 $ command)
else let (command, args) = break (== ' ') line
in if length args <= 1
then "" : [command]
else if (head . drop 1 $ args) == ':'
then let rest = drop 2 args
in "" : [command, rest]
else "" : (command : (drop 1 . splitIRCLn . drop 1 $ args))
type MOrigin = String
type MCommand = String
type MCommandArgs = [String]
-- Message: represents a raw message sent over the network
-- MSource is the prefix or source used/to use, where "" means no source was given (nearest IRC node)
data Message = Message {
msgOrigin :: MOrigin,
msgCommand :: MCommand,
msgCommandArgs :: MCommandArgs }
-- an IRC Numeric (3 digit number)
type Numeric = Int
-- converting from string
toNumeric :: String -> Numeric
toNumeric s = foldl ((+) . (* 10)) 0 $ map digitToInt s
-- LogLevel: levels logging can occur at
data LogLevel = LogError | LogWarning | LogInfo | LogDebug | LogVerbose deriving Enum
instance Show LogLevel where
show LogError = " ERROR"
show LogWarning = " WARNING"
show LogInfo = " INFO"
show LogDebug = " DEBUG"
show _ = " VERBOSE"
-- TODO: no CLI arguments actually handled at this time
-- CliFlags: possible options in CL arguments
data CliFlag = CliVerbose | CliServer | CliPort | CliNick deriving Enum
-- parses CLI args and returns a map of flag -> value (can be "")
parseCliArgs :: [String] -> [(CliFlag, String)]
parseCliArgs args = []
handleCliArgs :: [(CliFlag, String)] -> HircState -> IO HircState
handleCliArgs ((key, val):rest) state =
handleCliArgs rest state -- TODO: currently ignores CLI args
handleCliArgs [] state = return state
cfgFolder :: IO FilePath
cfgFolder =
do
homeDir <- getHomeDirectory
let cfgDir = homeDir ++ "/.hircbot"
in do
createDirectoryIfMissing False cfgDir
return cfgDir
-- loads configuration from the given file name and creates a HircState
loadConfig :: IO HircState
loadConfig =
do
cfgDir <- cfgFolder
fileExist <- doesFileExist $ cfgDir ++ "/cfg"
lines <- if fileExist
then do
h <- openFile (cfgDir ++ "/cfg") ReadMode
loadConfigLn h
else return []
let server = byKey "Server" lines "irc.freenode.net"
port = byKey "Port" lines "6667"
nick = byKey "Nick" lines ""
username = byKey "Username" lines ""
pass = byKey "Pass" lines ""
rname = byKey "RealName" lines "HircBot v0.2 -- nmbook"
chans = byKey "Channels" lines "#hircbot"
in do
return $ HircState (HircConfig server (toEnum (read port :: Int)) nick username pass rname chans) HircCStateDisc
where
byKey :: String -> [(String, String)] -> String -> String
byKey key [] def = def
byKey key ((isKey, val):list) def =
if isKey == key
then val
else byKey key list def
loadConfigLn :: Handle -> IO [(String, String)]
loadConfigLn handle = loadConfigLn' handle []
loadConfigLn' :: Handle -> [(String, String)] -> IO [(String, String)]
loadConfigLn' handle part =
do
isEof <- hIsEOF handle
if isEof
then do
hClose handle
return part
else do
line <- hGetLine handle
if any (== '=') line
then let (key, val) = break (== '=') line
in loadConfigLn' handle
((unpack . strip . pack $ key,
unpack . strip . pack . drop 1 $ val) : part)
else loadConfigLn' handle part
ircNetInit :: IO ()
ircNetInit =
withSocketsDo $ do
installHandler sigPIPE Ignore Nothing
return ()
-- connects to IRC
ircConnect :: HircState -> IO HircState
ircConnect state =
do
sock <- connectTo (cfgHost . stateCfg $ state) (PortNumber . cfgPort . stateCfg $ state)--(stateCfgGetServerPort state))
hSetBuffering sock LineBuffering
return $ HircState (stateCfg state) (HircCState sock (cfgNick . stateCfg $ state) [])
-- receive loop for IRC
ircRecvLoop :: HircState -> (HircState -> Message -> IO HircState) -> IO ()
ircRecvLoop state handleFn =
do
line <- hGetLine $ curSocket . stateCur $ state
state <- if last line == '\r'
then handleFn state . readMsg . init $ line
else handleFn state . readMsg $ line
ircRecvLoop state handleFn
return ()
-- send for IRC
ircSend :: HircState -> Message -> IO ()
ircSend state msg = hPutStr (curSocket . stateCur $ state) ((show msg) ++ "\r\n")
-- logs a line to the log file
logLine :: HircState -> LogLevel -> String -> IO ()
logLine state lv ln =
do
now <- getZonedTime
fp <- getCurrentLogFile now
let output = "[" ++ (getCurrentTimeStamp now) ++ "]" ++ (show lv) ++ ": " ++ ln ++ "\n"
in do
appendFile fp output
putStr output
getCurrentTimeStamp :: ZonedTime -> String
getCurrentTimeStamp = formatTime defaultTimeLocale "%I:%M:%S %p"
getCurrentLogFile :: ZonedTime -> IO FilePath
getCurrentLogFile now =
do
cfgDir <- cfgFolder
let logDir = cfgDir ++ "/logs"
in do
createDirectoryIfMissing False logDir
return $ logDir ++ "/" ++ (formatTime defaultTimeLocale "%Y-%m-%d" now) ++ ".txt"