Merge pull request #15 from clean-cloogle/no-results-response
[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) = doHTTPRequestFollowRedirects
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 {return=127} = ("No results for " + data, w)
71 Just clr = ("Results for " + data + " -- https://cloogle.org/#" +
72 replaceSubString "+" "%20" (urlEncode data) + "\n" +
73 processResults clr, w)
74 where
75 processResults :: Response -> String
76 processResults resp
77 | resp.return > 127 = "Failed: return code: " + toString resp.return + ", " + resp.msg
78 = join "\n" $ map processResult $ take 3 resp.data
79
80 processResult :: Result -> String
81 processResult (FunctionResult (br, {func}))
82 = "Function in " +++ br.library +++ ": " +++ br.modul +++ "\n" +++ func
83 processResult (TypeResult (br, {type}))
84 = "Type in " +++ br.library +++ ": " +++ br.modul +++ "\n" +++ limitResults type
85 processResult (ClassResult (br, {class_name,class_funs}))
86 = "Class in " +++ br.library +++ ": " +++ br.modul +++ "\n" +++ class_name +++ " with "
87 +++ toString (length class_funs) +++ " class functions"
88 processResult (ModuleResult (br, _))
89 = "Module in " +++ br.library +++ ": " +++ br.modul
90
91 limitResults :: String -> String
92 limitResults s
93 # lines = split "\n" s
94 | length lines > 4 = limitResults (join "\n" (take 3 lines) + "\n...")
95 = join "\n" (map maxWidth lines)
96
97 maxWidth :: String -> String
98 maxWidth s = if (size s > 80) (subString 0 77 s + "...") s
99
100 :: BotSettings =
101 { bs_nick :: String
102 , bs_nickserv :: Maybe String
103 , bs_autojoin :: [String]
104 , bs_port :: Int
105 , bs_server :: String
106 , bs_strftime :: String
107 }
108
109 Start :: *World -> (Maybe String, *World)
110 Start w
111 # ([arg0:args], w) = getCommandLine w
112 # (io, w) = stdio w
113 # io = io <<< "\n"
114 # bs = parseCLI args
115 //| isError bs = (Just $ "\n" +++ fromError bs +++ "\n", snd $ fclose io w)
116 # (Ok bs) = bs
117 # (merr, io, w) = bot (bs.bs_server, bs.bs_port) (startup bs) shutdown io (process bs.bs_strftime) w
118 = (Nothing, w)//= (merr, snd $ fclose io w)
119 where
120 parseCLI :: [String] -> MaybeErrorString BotSettings
121 parseCLI [] = Ok
122 { bs_nick = "clooglebot"
123 , bs_nickserv = Nothing
124 , bs_autojoin = []
125 , bs_port = 6667
126 , bs_server = "irc.freenode.net"
127 , bs_strftime = "%s"
128 }
129 parseCLI [a:as]
130 | a == "-f" || a == "--strftime"
131 = arg1 "--strftime" as \a c->{c & bs_strftime=a}
132 | a == "-n" || a == "--nick"
133 = arg1 "--nick" as \a c->{c & bs_nick=a}
134 | a == "-ns" || a == "--nickserv"
135 = arg1 "--nickserv" as \a c->{c & bs_nickserv=Just a}
136 | a == "-a" || a == "--autojoin"
137 = arg1 "--autojoin" as \a c->{c & bs_autojoin=c.bs_autojoin ++ [a]}
138 | a == "-p" || a == "--port"
139 = arg1 "--port" as \a c->{c & bs_port=toInt a}
140 | a == "-s" || a == "--server"
141 = arg1 "--server" as \a c->{c & bs_server=a}
142 | a == "-h" || a == "--help" = Error $ join "\n" $
143 [ "Usage: cloogle [OPTS]"
144 , "Options:"
145 , "\t--strftime/-f FORMAT strftime format used in the output. default: %s\n"
146 , "\t--nick/-n NICKNAME Use the given nickname instead of clooglebot"
147 , "\t--nickserv/-ns PW Identify via the given password with NickServ"
148 , "\t--port/-p PORT Use the given port instead of port 6667"
149 , "\t--server/-s SERVER Use the given server instead of irc.freenode.net"
150 , "\t--autojoin/-a CHANNEL Add CHANNEL to the autojoin list. This command "
151 , "\t can be called multiple times. Beware that #"
152 , "\t has to be escaped in most shells"
153 ]
154 = Error $ "Unknown option: " +++ a
155
156 arg1 name [] _ = Error $ name +++ " requires an argument"
157 arg1 name [a:as] f = parseCLI as >>= Ok o f a
158
159 nickserv pw = PRIVMSG (CSepList ["NickServ"]) $ "IDENTIFY " +++ pw
160
161 toPrefix c = {irc_prefix=Nothing,irc_command=Right c}
162
163 startup bs = map toPrefix $
164 [ NICK bs.bs_nick Nothing
165 , USER "cloogle" "cloogle" "cloogle" "Cloogle bot"
166 ]++ maybe [] (pure o nickserv) bs.bs_nickserv
167 ++ if (isEmpty bs.bs_autojoin) []
168 [JOIN (CSepList bs.bs_autojoin) Nothing]
169 shutdown = map toPrefix [QUIT $ Just "Bye"]
170
171 process :: String !IRCMessage *File !*World -> (Maybe [IRCMessage], *File, !*World)
172 process strf im io w
173 #! (io, w) = log strf " (r): " im (io, w)
174 = case im.irc_command of
175 Left numr = (Just [], io, w)
176 Right cmd = case process` im.irc_prefix cmd w of
177 (Nothing, w) = (Nothing, io, w)
178 (Just cs, w)
179 # msgs = map toPrefix cs
180 #! (io, w) = foldr (log strf " (s): ") (io, w) msgs
181 = (Just msgs, io, w)
182
183 log :: String String IRCMessage (!*File, !*World) -> (!*File, !*World)
184 log strf pref m (io, w)
185 #! (t, w) = localTime w
186 = (io <<< strfTime strf t <<< pref <<< toString m, w)
187
188 process` :: (Maybe (Either IRCUser String)) IRCCommand *World -> (Maybe [IRCCommand], *World)
189 process` (Just (Left user)) (PRIVMSG t m) w
190 | m == "!restart" = (Nothing, w)
191 | m.[0] == '!'
192 # (msgs, w) = realProcess (split " " $ m % (1, size m)) w
193 = (Just $ map reply msgs, w)
194 | m % (0,4) == "\001PING" = (Just [reply m], w)
195 = (Just [], w)
196 where
197 reply = case (\(CSepList [t:_]) -> t.[0]) t of
198 '#' -> PRIVMSG t
199 _ -> NOTICE user.irc_nick
200 process` _ (PING t mt) w = (Just [PONG t mt], w)
201 process` _ _ w = (Just [], w)
202
203 realProcess :: [String] *World -> ([String], *World)
204 realProcess ["help",x:xs] w = ((case x of
205 "help" =
206 [ "Usage: !help [ARG]"
207 , "Show this help, or the specific help of the argument"]
208 "ping" =
209 [ "Usage: !ping [ARG [ARG ...]]"
210 , "Ping the bot, it will pong the arguments back"]
211 "shorten" =
212 [ "Usage: !shorten URL [URL [URL ...]]"
213 , "Shorten the given urls with the cloo.gl url shortener"]
214 "query" =
215 [ "Usage: !query QUERY"
216 , "Query QUERY in cloogle and return the results"]
217 "restart" =
218 [ "Usage: !restart"
219 , "Restart the bot"]
220 x = ["Unknown command: " +++ x]
221 ), w)
222 realProcess ["help"] w = (
223 ["Type !help cmd for command specific help"
224 ,"available commands: help, ping, shorten, query, restart"], w)
225 realProcess ["ping":xs] w = (["pong " +++ join " " xs], w)
226 realProcess ["shorten":xs] w = case xs of
227 [] = (["shorten requires at least one argument"], w)
228 xs = mapSt shorten xs w
229 realProcess ["query":xs] w = case xs of
230 [] = (["query requires one or more arguments"], w)
231 xs = appFst (split "\n") $ cloogle (join " " xs) w
232 realProcess ["restart":_] w = (["restart takes no arguments"], w)
233 realProcess [c:_] w = ([join " " [
234 "Unknown cmd: ", c, ", type !help to get help"]], w)