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