add stdout logging
[cloogle-irc.git] / cloogleirc.icl
1 module cloogleirc
2
3 import Cloogle
4 import GenPrint
5 import StdEnv
6
7 import Data.Functor
8 import Data.Maybe
9 import Data.Either
10 from Data.Func import $, mapSt
11 from Text import class Text(..), instance Text String, instance + String
12
13 import Internet.HTTP
14
15 import Text.JSON
16
17 import Text.URI
18 import System.Time
19
20 import Control.Applicative
21 import qualified Control.Monad as CM
22 import qualified Data.Map as DM
23 from Control.Monad import class Monad, instance Monad Maybe, >>=
24 from Text.Encodings.UrlEncoding import urlEncode
25 import System.CommandLine
26 import Internet.HTTP
27 import Data.Error
28 import Data.List
29 import Data.Functor
30 import Data.Tuple
31
32 import TCPIP
33 import IRC
34 import IRCBot
35
36 import StdMisc, StdDebug
37
38 shorten :: String *World -> (String, *World)
39 shorten s w
40 # s = if (startsWith "http://" s) s (if (startsWith "https://" s) s ("http://" + s))
41 # data = "type=regular&url="+urlEncode s+"&token=a"
42 # (mer, w) = doHTTPRequest
43 { newHTTPRequest
44 & req_method = HTTP_POST
45 , req_path = "/"
46 , server_name = "cloo.gl"
47 , server_port = 80
48 , req_headers = 'DM'.fromList
49 [("Content-Type", "application/x-www-form-urlencoded")
50 ,("Content-Length", toString $ size data)
51 ,("Accept", "*/*")]
52 , req_data = data} 10000 w
53 | isError mer = ("request failed: " + fromError mer, w)
54 # resp = fromOk mer
55 = (resp.rsp_data, w)
56
57 cloogle :: String *World -> (String, *World)
58 cloogle data w
59 # (mer, w) = doHTTPRequestL
60 { newHTTPRequest
61 & req_path = "/api.php"
62 , req_query = "?str=" + urlEncode data
63 , req_headers = 'DM'.fromList [("User-Agent", "cloogle-irc")]
64 , server_name = "cloogle.org"
65 , server_port = 80} 10000 10 w
66 | isError mer = ("request failed: " + fromError mer, w)
67 # resp = fromOk mer
68 = case fromJSON $ fromString resp.HTTPResponse.rsp_data of
69 Nothing = ("couldn't parse json", w)
70 Just clr = ("Results for " + data + " -- https://cloogle.org/#" +
71 replaceSubString "+" "%20" (urlEncode data) + "\n" +
72 processResults clr, w)
73 where
74 processResults :: Response -> String
75 processResults resp
76 | resp.return > 127 = "Failed: return code: " + toString resp.return + ", " + resp.msg
77 = join "\n" $ map processResult $ take 3 resp.data
78
79 processResult :: Result -> String
80 processResult (FunctionResult (br, {func}))
81 = "Function in " +++ br.library +++ ": " +++ br.modul +++ "\n" +++ func
82 processResult (TypeResult (br, {type}))
83 = "Type in " +++ br.library +++ ": " +++ br.modul +++ "\n" +++ limitResults type
84 processResult (ClassResult (br, {class_name,class_funs}))
85 = "Class in " +++ br.library +++ ": " +++ br.modul +++ "\n" +++ class_name +++ " with "
86 +++ toString (length class_funs) +++ " class functions"
87 processResult (ModuleResult (br, _))
88 = "Module in " +++ br.library +++ ": " +++ br.modul
89
90 limitResults :: String -> String
91 limitResults s
92 # lines = split "\n" s
93 | length lines > 4 = limitResults (join "\n" (take 3 lines) + "\n...")
94 = join "\n" (map maxWidth lines)
95
96 maxWidth :: String -> String
97 maxWidth s = if (size s > 80) (subString 0 77 s + "...") s
98
99 :: BotSettings =
100 { bs_nick :: String
101 , bs_nickserv :: Maybe String
102 , bs_autojoin :: [String]
103 , bs_port :: Int
104 , bs_server :: String
105 , bs_strftime :: String
106 }
107
108 Start :: *World -> (Maybe String, *World)
109 Start w
110 # ([arg0:args], w) = getCommandLine w
111 # (io, w) = stdio w
112 # io = io <<< "\n"
113 # bs = parseCLI args
114 //| isError bs = (Just $ "\n" +++ fromError bs +++ "\n", snd $ fclose io w)
115 # (Ok bs) = bs
116 # (merr, io, w) = bot (bs.bs_server, bs.bs_port) (startup bs) shutdown io (process bs.bs_strftime) w
117 = (Nothing, w)//= (merr, snd $ fclose io w)
118 where
119 parseCLI :: [String] -> MaybeErrorString BotSettings
120 parseCLI [] = Ok
121 { bs_nick = "clooglebot"
122 , bs_nickserv = Nothing
123 , bs_autojoin = []
124 , bs_port = 6667
125 , bs_server = "irc.freenode.net"
126 , bs_strftime = "%s"
127 }
128 parseCLI [a:as]
129 | a == "-f" || a == "--strftime"
130 = arg1 "--strftime" as \a c->{c & bs_strftime=a}
131 | a == "-n" || a == "--nick"
132 = arg1 "--nick" as \a c->{c & bs_nick=a}
133 | a == "-ns" || a == "--nickserv"
134 = arg1 "--nickserv" as \a c->{c & bs_nickserv=Just a}
135 | a == "-a" || a == "--autojoin"
136 = arg1 "--autojoin" as \a c->{c & bs_autojoin=c.bs_autojoin ++ [a]}
137 | a == "-p" || a == "--port"
138 = arg1 "--port" as \a c->{c & bs_port=toInt a}
139 | a == "-s" || a == "--server"
140 = arg1 "--server" as \a c->{c & bs_server=a}
141 | a == "-h" || a == "--help" = Error $ join "\n" $
142 [ "Usage: cloogle [OPTS]"
143 , "Options:"
144 , "\t--strftime/-f FORMAT strftime format used in the output. default: %s\n"
145 , "\t--nick/-n NICKNAME Use the given nickname instead of clooglebot"
146 , "\t--nickserv/-ns PW Identify via the given password with NickServ"
147 , "\t--port/-p PORT Use the given port instead of port 6667"
148 , "\t--server/-s SERVER Use the given server instead of irc.freenode.net"
149 , "\t--autojoin/-a CHANNEL Add CHANNEL to the autojoin list. This command "
150 , "\t can be called multiple times. Beware that #"
151 , "\t has to be escaped in most shells"
152 ]
153 = Error $ "Unknown option: " +++ a
154
155 arg1 name [] _ = Error $ name +++ " requires an argument"
156 arg1 name [a:as] f = parseCLI as >>= Ok o f a
157
158 nickserv pw = PRIVMSG (CSepList ["NickServ"]) $ "IDENTIFY " +++ pw
159
160 toPrefix c = {irc_prefix=Nothing,irc_command=Right c}
161
162 startup bs = map toPrefix $
163 [ NICK bs.bs_nick Nothing
164 , USER "cloogle" "cloogle" "cloogle" "Cloogle bot"
165 ]++ maybe [] (pure o nickserv) bs.bs_nickserv
166 ++ if (isEmpty bs.bs_autojoin) []
167 [JOIN (CSepList bs.bs_autojoin) Nothing]
168 shutdown = map toPrefix [QUIT $ Just "Bye"]
169
170 process :: String !IRCMessage *File !*World -> (Maybe [IRCMessage], *File, !*World)
171 process strf im io w
172 #! (io, w) = log strf " (r): " im (io, w)
173 = case im.irc_command of
174 Left numr = (Just [], io, w)
175 Right cmd = case process` im.irc_prefix cmd w of
176 (Nothing, w) = (Nothing, io, w)
177 (Just cs, w)
178 # msgs = map toPrefix cs
179 #! (io, w) = foldr (log strf " (s): ") (io, w) msgs
180 = (Just msgs, io, w)
181
182 log :: String String IRCMessage (!*File, !*World) -> (!*File, !*World)
183 log strf pref m (io, w)
184 #! (t, w) = localTime w
185 = (io <<< strfTime strf t <<< pref <<< toString m, w)
186
187 process` :: (Maybe (Either IRCUser String)) IRCCommand *World -> (Maybe [IRCCommand], *World)
188 process` (Just (Left user)) (PRIVMSG t m) w
189 | m == "!restart" = (Nothing, w)
190 | m.[0] == '!'
191 # (msgs, w) = realProcess (split " " $ m % (1, size m)) w
192 = (Just $ map reply msgs, w)
193 = (Just [], w)
194 where
195 reply = case (\(CSepList [t:_]) -> t.[0]) t of
196 '#' -> PRIVMSG t
197 _ -> NOTICE user.irc_nick
198 process` _ (PING t mt) w = (Just [PONG t mt], w)
199 process` _ _ w = (Just [], w)
200
201 realProcess :: [String] *World -> ([String], *World)
202 realProcess ["help",x:xs] w = ((case x of
203 "help" =
204 [ "Usage: !help [ARG]"
205 , "Show this help, or the specific help of the argument"]
206 "ping" =
207 [ "Usage: !ping [ARG [ARG ...]]"
208 , "Ping the bot, it will pong the arguments back"]
209 "shorten" =
210 [ "Usage: !shorten URL [URL [URL ...]]"
211 , "Shorten the given urls with the cloo.gl url shortener"]
212 "query" =
213 [ "Usage: !query QUERY"
214 , "Query QUERY in cloogle and return the results"]
215 "restart" =
216 [ "Usage: !restart"
217 , "Restart the bot"]
218 x = ["Unknown command: " +++ x]
219 ), w)
220 realProcess ["help"] w = (
221 ["Type !help cmd for command specific help"
222 ,"available commands: help, ping, shorten, query, restart"], w)
223 realProcess ["ping":xs] w = (["pong " +++ join " " xs], w)
224 realProcess ["shorten":xs] w = case xs of
225 [] = (["shorten requires at least one argument"], w)
226 xs = mapSt shorten xs w
227 realProcess ["query":xs] w = case xs of
228 [] = (["query requires one or more arguments"], w)
229 xs = appFst (split "\n") $ cloogle (join " " xs) w
230 realProcess ["restart":_] w = (["restart takes no arguments"], w)
231 realProcess [c:_] w = ([join " " [
232 "Unknown cmd: ", c, ", type !help to get help"]], w)