irc: Split irc-bot-send-line into main functionality and action handler.
[8sync.git] / 8sync / systems / irc.scm
1 #!/usr/bin/guile \
2 -e main -s
3 !#
4
5 ;;; 8sync --- Asynchronous programming for Guile
6 ;;; Copyright (C) 2015 Christopher Allan Webber <cwebber@dustycloud.org>
7 ;;;
8 ;;; This file is part of 8sync.
9 ;;;
10 ;;; 8sync is free software: you can redistribute it and/or modify it
11 ;;; under the terms of the GNU Lesser General Public License as
12 ;;; published by the Free Software Foundation, either version 3 of the
13 ;;; License, or (at your option) any later version.
14 ;;;
15 ;;; 8sync is distributed in the hope that it will be useful,
16 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;;; GNU Lesser General Public License for more details.
19 ;;;
20 ;;; You should have received a copy of the GNU Lesser General Public
21 ;;; License along with 8sync.  If not, see <http://www.gnu.org/licenses/>.
22
23 (define-module (8sync systems irc)
24   #:use-module (8sync repl)
25   #:use-module (8sync agenda)
26   #:use-module (8sync actors)
27   #:use-module (srfi srfi-9)
28   #:use-module (ice-9 getopt-long)
29   #:use-module (ice-9 format)
30   #:use-module (ice-9 receive)
31   #:use-module (ice-9 rdelim)
32   #:use-module (ice-9 q)
33   #:use-module (ice-9 match)
34   #:use-module (oop goops)
35   #:export (<irc-bot>
36             irc-bot-username irc-bot-server irc-bot-channels irc-bot-port
37
38             irc-bot-send-line
39
40             handle-line handle-misc-input
41             handle-user-join handle-user-quit
42
43             default-irc-port))
44
45 \f
46 ;;; Network stuff
47 ;;; =============
48
49 (define default-irc-port 6665)
50
51 (define* (irc-socket-setup hostname #:optional (inet-port default-irc-port))
52   (let* ((s (socket PF_INET SOCK_STREAM 0))
53          (flags (fcntl s F_GETFL))
54          (ip-address (inet-ntop AF_INET (car (hostent:addr-list (gethost hostname))))))
55     (fcntl s F_SETFL (logior O_NONBLOCK flags))
56     (connect s AF_INET
57              (inet-pton AF_INET ip-address)
58              inet-port)
59     s))
60
61 (define irc-eol "\r\n")
62
63 (define (startswith-colon? str)
64   (and (> (string-length str) 0)
65        (eq? (string-ref str 0)
66             #\:)))
67
68 ;; TODO: This needs a cleanup.  Maybe even just using a regex is fine.
69 (define (parse-line line)
70   (define (parse-params pre-params)
71     ;; This is stupid and imperative but I can't wrap my brain around
72     ;; the right way to do it in a functional way :\
73     (let ((param-list '())
74           (currently-building '()))
75       (for-each
76        (lambda (param-item)
77          (cond
78           ((startswith-colon? param-item)
79            (if (not (eq? currently-building '()))
80                (set! param-list
81                      (cons
82                       (reverse currently-building)
83                       param-list)))
84            (set! currently-building (list param-item)))
85           (else
86            (set! currently-building (cons param-item currently-building)))))
87        pre-params)
88       ;; We're still building something, so tack that on there
89       (if (not (eq? currently-building '()))
90           (set! param-list
91                 (cons (reverse currently-building) param-list)))
92       ;; return the reverse of the param list
93       (reverse param-list)))
94
95   (match (string-split line #\space)
96     (((? startswith-colon? prefix)
97       command
98       pre-params ...)
99      (values prefix command
100              (parse-params pre-params)))
101     ((command pre-params ...)
102      (values #f command
103              (parse-params pre-params)))))
104
105 (define (strip-colon-if-necessary string)
106   (if (and (> (string-length string) 0)
107            (string-ref string 0))
108       (substring/copy string 1)
109       string))
110
111 ;; @@: Not sure if this works in all cases, like what about in a non-privmsg one?
112 (define (irc-line-username irc-line-prefix)
113   (let* ((prefix-name (strip-colon-if-necessary irc-line-prefix))
114          (exclaim-index (string-index prefix-name #\!)))
115     (if exclaim-index
116         (substring/copy prefix-name 0 exclaim-index)
117         prefix-name)))
118
119 (define (condense-privmsg-line line)
120   "Condense message line and do multiple value return of
121   (channel message emote?)"
122   (define (strip-last-char string)
123     (substring/copy string 0 (- (string-length string) 1)))
124   (let* ((channel-name (caar line))
125          (rest-params (apply append (cdr line))))
126     (match rest-params
127       (((or "\x01ACTION" ":\x01ACTION") middle-words ... (= strip-last-char last-word))
128        (values channel-name
129                (string-join
130                 (append middle-words (list last-word))
131                 " ")
132                #t))
133       (((= strip-colon-if-necessary first-word) rest-message ...)
134        (values channel-name
135                (string-join (cons first-word rest-message) " ")
136                #f)))))
137
138 ;;; A goofy default
139 (define (echo-message irc-bot speaker channel-name
140                       line-text emote?)
141   "Simply echoes the message to the current-output-port."
142   (if emote?
143       (format #t "~a emoted ~s in channel ~a\n"
144               speaker line-text channel-name)
145       (format #t "~a said ~s in channel ~a\n"
146               speaker line-text channel-name)))
147
148 \f
149 ;;; Bot
150 ;;; ===
151
152 (define-class <irc-bot> (<actor>)
153   (username #:init-keyword #:username
154             #:getter irc-bot-username)
155   (realname #:init-keyword #:realname
156             #:init-value #f)
157   (server #:init-keyword #:server
158           #:getter irc-bot-server)
159   (channels #:init-keyword #:channels
160             #:getter irc-bot-channels)
161   (port #:init-keyword #:port
162         #:init-value default-irc-port
163         #:getter irc-bot-port)
164   (socket #:accessor irc-bot-socket)
165   (actions #:allocation #:each-subclass
166            #:init-value (build-actions
167                          (init irc-bot-init)
168                          (main-loop irc-bot-main-loop)
169                          (send-line irc-bot-send-line-action))))
170
171 (define (irc-bot-realname irc-bot)
172   (or (slot-ref irc-bot 'realname)
173       (irc-bot-username irc-bot)))
174
175 (define (irc-bot-init irc-bot message)
176   "Initialize the IRC bot"
177   (define socket
178     (irc-socket-setup (irc-bot-server irc-bot)
179                       (irc-bot-port irc-bot)))
180   (set! (irc-bot-socket irc-bot) socket)
181   (format socket "USER ~a ~a ~a :~a~a"
182           (irc-bot-username irc-bot)
183           "*" "*"  ; hostname and servername
184           (irc-bot-realname irc-bot) irc-eol)
185   (format socket "NICK ~a~a" (irc-bot-username irc-bot) irc-eol)
186
187   (for-each
188    (lambda (channel)
189      (format socket "JOIN ~a~a" channel irc-eol))
190    (irc-bot-channels irc-bot))
191
192   (<- irc-bot (actor-id irc-bot) 'main-loop))
193
194 (define (irc-bot-main-loop irc-bot message)
195   (define socket (irc-bot-socket irc-bot))
196   (define line (string-trim-right (read-line socket) #\return))
197   (dispatch-raw-line irc-bot line)
198   (cond
199    ;; The port's been closed for some reason, so stop looping
200    ((port-closed? socket)
201     'done)
202    ;; We've reached the EOF object, which means we should close
203    ;; the port ourselves and stop looping
204    ((eof-object? (peek-char socket))
205     (close socket)
206     'done)
207    ;; ;; Looks like we've been killed somehow... well, stop running
208    ;; ;; then!
209    ;; ((actor-am-i-dead? irc-bot)
210    ;;  (if (not (port-closed? socket))
211    ;;      (close socket))
212    ;;  'done)
213    ;; Otherwise, let's read till the next line!
214    (else
215     (<- irc-bot (actor-id irc-bot) 'main-loop))))
216
217 (define* (irc-bot-send-line-action irc-bot message
218                                    channel line #:key emote?)
219   "Action handler for sending lines.  Real behavior happens in
220 irc-bot-send-line."
221   (irc-bot-send-line irc-bot channel line #:emote? emote?))
222
223 (define* (irc-bot-send-line irc-bot channel line #:key emote?)
224   ;; TODO: emote? handling
225   (format (irc-bot-socket irc-bot) "PRIVMSG ~a :~a~a"
226           channel line irc-eol))
227
228
229 ;;; Likely-to-be-overridden generic methods
230
231 (define-method (dispatch-raw-line (irc-bot <irc-bot>) raw-line)
232   "Dispatch a raw line of input"
233   (receive (line-prefix line-command line-params)
234       (parse-line raw-line)
235     (match line-command
236       ("PING"
237        (display (string-append "PONG" irc-eol)
238                 (irc-bot-socket irc-bot)))
239       ("PRIVMSG"
240        (receive (channel-name line-text emote?)
241            (condense-privmsg-line line-params)
242          (let ((username (irc-line-username line-prefix)))
243            (handle-line irc-bot username channel-name
244                         line-text emote?))))
245       (_ (handle-misc-input irc-bot raw-line)))))
246
247 (define-method (handle-line (irc-bot <irc-bot>) username channel-name
248                                     line-text emote?)
249   (echo-message irc-bot username channel-name line-text emote?))
250
251 (define-method (handle-misc-input (irc-bot <irc-bot>) raw-line)
252   (display raw-line)
253   (newline))
254
255 (define-method (handle-user-join (irc-bot <irc-bot>) user channel)
256   'TODO)
257
258 (define-method (handle-user-quit (irc-bot <irc-bot>) user channel)
259   'TODO)
260