80d4ce182f4fe2a7ba65aa729f56c63f0de3252c
[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 (srfi srfi-9)
27   #:use-module (ice-9 getopt-long)
28   #:use-module (ice-9 format)
29   #:use-module (ice-9 receive)
30   #:use-module (ice-9 q)
31   #:use-module (ice-9 match)
32   #:export (;; The only things you definitely need if writing a bot
33             make-irc-bot-cli            
34             irc-format irc-display irc-send-message irc-send-formatted
35             
36             ;; Useful things if you're making something more complicated
37             irc-line
38             irc-eol
39
40             default-irc-port
41
42             startswith-colon?
43
44             <irc-line>
45             make-irc-line irc-line?
46             irc-line-prefix irc-line-command irc-line-params
47
48             parse-line
49             irc-line-username
50
51             condense-privmsg-line
52             echo-back-message
53
54             make-handle-line make-basic-irc-handler
55             queue-and-start-irc-agenda!))
56
57 \f
58 ;;; Network stuff
59 ;;; =============
60
61 (define default-irc-port 6665)
62
63 (define* (irc-socket-setup hostname #:optional (inet-port default-irc-port))
64   (let ((s (socket PF_INET SOCK_STREAM 0))
65         (ip-address (inet-ntoa (car (hostent:addr-list (gethost hostname))))))
66     (connect s AF_INET
67              (inet-pton AF_INET ip-address)
68              inet-port)
69     s))
70
71 (define (install-socket socket handler)
72   (display "Installing socket...\n")   ; debugging :)
73   (make-port-request socket #:read handler))
74
75 (define irc-eol "\r\n")
76
77 (define (irc-line line)
78   (string-concatenate (list line irc-eol)))
79
80 (define-syntax-rule (irc-format dest format-string rest ...)
81   (let ((line (string-concatenate
82                (list (format #f format-string rest ...)
83                      irc-eol))))
84     (match dest
85       (#f line)
86       (#t (display line))
87       (else
88        (display line dest)))))
89
90 (define* (irc-display line #:optional dest)
91   (if dest
92       (display (irc-line line) dest)
93       (display (irc-line dest))))
94
95 (define (irc-send-message socket channel message)
96   (irc-format socket "PRIVMSG ~a :~a" channel message))
97
98 (define-syntax-rule (irc-send-formatted socket channel format-string
99                                         args ...)
100   (irc-format socket "PRIVMSG ~a :~a" channel
101               (format #f format-string args ...)))
102
103 (define* (handle-login socket username
104                        #:key
105                        (hostname "*")
106                        (servername "*")
107                        (realname username)
108                        (channels '()))
109   (irc-format socket "USER ~a ~a ~a :~a"
110               username hostname servername realname)
111   (irc-format socket "NICK ~a" username)
112   (for-each
113    (lambda (channel)
114      (irc-format socket "JOIN ~a" channel))
115    channels))
116
117 (define (startswith-colon? str)
118   (and (> (string-length str) 0)
119        (eq? (string-ref str 0)
120             #\:)))
121
122 (define-record-type <irc-line>
123   (make-irc-line prefix command params)
124   irc-line?
125   (prefix irc-line-prefix)
126   (command irc-line-command)
127   (params irc-line-params))
128
129
130 (define (parse-line line)
131   (define (parse-params pre-params)
132     ;; This is stupid and imperative but I can't wrap my brain around
133     ;; the right way to do it in a functional way :\
134     (let ((param-list '())
135           (currently-building '()))
136       (for-each
137        (lambda (param-item)
138          (cond
139           ((startswith-colon? param-item)
140            (if (not (eq? currently-building '()))
141                (set! param-list
142                      (cons
143                       (reverse currently-building)
144                       param-list)))
145            (set! currently-building (list param-item)))
146           (else
147            (set! currently-building (cons param-item currently-building)))))
148        pre-params)
149       ;; We're still building something, so tack that on there
150       (if (not (eq? currently-building '()))
151           (set! param-list
152                 (cons (reverse currently-building) param-list)))
153       ;; return the reverse of the param list
154       (reverse param-list)))
155
156   (match (string-split line #\space)
157     (((? startswith-colon? prefix)
158       command
159       pre-params ...)
160      (make-irc-line prefix command
161                     (parse-params pre-params)))
162     ((command pre-params ...)
163      (make-irc-line #f command
164                     (parse-params pre-params)))))
165
166 (define (strip-colon-if-necessary string)
167   (if (and (> (string-length string) 0)
168            (string-ref string 0))
169       (substring/copy string 1)
170       string))
171
172 ;; @@: Not sure if this works in all cases, like what about in a non-privmsg one?
173 (define (irc-line-username irc-line)
174   (let* ((prefix-name (strip-colon-if-necessary (irc-line-prefix irc-line)))
175          (exclaim-index (string-index prefix-name #\!)))
176     (if exclaim-index
177         (substring/copy prefix-name 0 exclaim-index)
178         prefix-name)))
179
180 (define (condense-privmsg-line line)
181   "Condense message line and do multiple value return of
182   (channel message is-action)"
183   (define (strip-last-char string)
184     (substring/copy string 0 (- (string-length string) 1)))
185   (let* ((channel-name (caar line))
186          (rest-params (apply append (cdr line))))
187     (match rest-params
188       (((or "\x01ACTION" ":\x01ACTION") middle-words ... (= strip-last-char last-word))
189        (values channel-name
190                (string-join
191                 (append middle-words (list last-word))
192                 " ")
193                #t))
194       (((= strip-colon-if-necessary first-word) rest-message ...)
195        (values channel-name
196                (string-join (cons first-word rest-message) " ")
197                #f)))))
198
199 (define (echo-back-message socket my-name speaker
200                            channel-name message is-action)
201   (if is-action
202       (format #t "~a emoted ~s in channel ~a\n"
203               speaker message channel-name)
204       (format #t "~a said ~s in channel ~a\n"
205               speaker message channel-name)))
206
207 (define default-handle-privmsg echo-back-message)
208
209 (define* (make-handle-line #:key
210                            (handle-privmsg default-handle-privmsg))
211   (define (handle-line socket line my-username)
212     (let ((parsed-line (parse-line line)))
213       (match (irc-line-command parsed-line)
214         ("PING"
215          (irc-display "PONG" socket))
216         ("PRIVMSG"
217          (receive (channel-name message is-action)
218              (condense-privmsg-line (irc-line-params parsed-line))
219            (let ((username (irc-line-username parsed-line)))
220              (handle-privmsg socket my-username username
221                              channel-name message is-action))))
222         (_
223          (display line)
224          (newline)))))
225   handle-line)
226
227 (define (make-basic-irc-handler handle-line username)
228   (let ((buffer '()))
229     (define (reset-buffer)
230       (set! buffer '()))
231     (define (should-read-char socket)
232       (and (not (port-closed? socket))
233            (char-ready? socket)
234            (not (eof-object? (peek-char socket)))))
235     (define (irc-handler socket)
236       (while (should-read-char socket)
237         (set! buffer (cons (read-char socket) buffer))
238         (match buffer
239           ((#\newline #\return (? char? line-chars) ...)
240            (let ((ready-line (list->string (reverse line-chars))))
241              ;; reset buffer
242              (set! buffer '())
243              ;; run it
244              (%8sync-run (handle-line
245                           socket
246                           ready-line
247                           username))))
248           (_ #f)))
249       ;; I need to shut things down on EOF object
250       (cond
251        ((port-closed? socket)
252         (display "port closed time\n")
253         (port-remove-request socket))
254        ((and (char-ready? socket)
255              (eof-object? (peek-char socket)))
256         (display "port eof time\n")
257         (close socket)
258         (port-remove-request socket))))
259     irc-handler))
260
261 (define default-line-handler (make-handle-line))
262
263 (define* (queue-and-start-irc-agenda! agenda socket #:key
264                                       (username "syncbot")
265                                       (inet-port default-irc-port)
266                                       (line-handler default-line-handler)
267                                       (channels '()))
268   (dynamic-wind
269     (lambda () #f)
270     (lambda ()
271       (enq! (agenda-queue agenda)
272             (wrap (install-socket
273                    socket
274                    (make-basic-irc-handler
275                     line-handler
276                     username))))
277       (enq! (agenda-queue agenda) (wrap (handle-login socket username
278                                                       #:channels channels)))
279       (start-agenda agenda))
280     (lambda ()
281       (display "Cleaning up...\n")
282       (close socket))))
283
284
285 \f
286 ;;; CLI
287 ;;; ===
288
289 (define option-spec
290   `((server (single-char #\s) (required? #t) (value #t))
291     (port (single-char #\p)
292           (value #t)
293           (predicate
294            ,(lambda (s)
295               (if (string->number s) #t #f))))
296     (username (single-char #\u) (required? #t) (value #t))
297     (channels (value #t))
298     (listen)))
299
300 (define* (make-irc-bot-cli #:optional
301                            (line-handler default-line-handler)
302                            (print-and-continue-on-error #t))
303   (define (main args)
304     (let* ((options (getopt-long args option-spec))
305            (hostname (option-ref options 'server #f))
306            (port (or (option-ref options 'port #f)
307                      default-irc-port))
308            (username (option-ref options 'username #f))
309            (listen (option-ref options 'listen #f))
310            (channels (option-ref options 'channels ""))
311            (agenda (if print-and-continue-on-error
312                        (make-agenda #:pre-unwind-handler print-error-and-continue)
313                        (make-agenda))))
314       (display `((server ,hostname) (port ,port) (username ,username)
315                  (listen ,listen) (channels-split ,(string-split channels #\space))))
316       (newline)
317       (if listen
318           (spawn-and-queue-repl-server! agenda))
319       (queue-and-start-irc-agenda!
320        agenda
321        (irc-socket-setup hostname port)
322        #:inet-port port
323        #:username username
324        #:channels (string-split channels #\space)
325        #:line-handler line-handler)))
326   main)
327
328 (define main (make-irc-bot-cli))