refactoring args to default-handle-privmsg
[8sync.git] / demos / irc.scm
1 #!/usr/bin/guile \
2 -e main -s
3 !#
4
5 ;; Copyright (C) 2015 Christopher Allan Webber <cwebber@dustycloud.org>
6
7 ;; This library is free software; you can redistribute it and/or
8 ;; modify it under the terms of the GNU Lesser General Public
9 ;; License as published by the Free Software Foundation; either
10 ;; version 3 of the License, or (at your option) any later version.
11 ;;
12 ;; This library is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 ;; Lesser General Public License for more details.
16 ;;
17 ;; You should have received a copy of the GNU Lesser General Public
18 ;; License along with this library; if not, write to the Free Software
19 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 ;; 02110-1301 USA
21
22 (use-modules (eightsync repl)
23              (eightsync agenda)
24              (srfi srfi-9)
25              (ice-9 getopt-long)
26              (ice-9 format)
27              (ice-9 receive)
28              (ice-9 q)
29              (ice-9 match))
30
31 \f
32 ;;; Network stuff
33 ;;; =============
34
35 (define default-irc-port 6665)
36
37 (define* (irc-socket-setup hostname #:optional (inet-port default-irc-port))
38   (let ((s (socket PF_INET SOCK_STREAM 0))
39         (ip-address (inet-ntoa (car (hostent:addr-list (gethost hostname))))))
40     (connect s AF_INET
41              (inet-pton AF_INET ip-address)
42              inet-port)
43     s))
44
45 (define (install-socket socket handler)
46   (display "Installing socket...\n")   ; debugging :)
47   (make-port-request socket #:read handler))
48
49 (define irc-eol "\r\n")
50
51 (define (irc-line line)
52   (string-concatenate (list line irc-eol)))
53
54 (define-syntax-rule (irc-format dest format-string rest ...)
55   (let ((line (string-concatenate
56                (list (format #f format-string rest ...)
57                      irc-eol))))
58     (match dest
59       (#f line)
60       (#t (display line))
61       (else
62        (display line dest)))))
63
64 (define* (irc-display line #:optional dest)
65   (if dest
66       (display (irc-line line) dest)
67       (display (irc-line dest))))
68
69 (define* (handle-login socket username
70                        #:key
71                        (hostname "*")
72                        (servername "*")
73                        (realname username)
74                        (channels '()))
75   (irc-format socket "USER ~a ~a ~a :~a"
76               username hostname servername realname)
77   (irc-format socket "NICK ~a" username)
78   (for-each
79    (lambda (channel)
80      (irc-format socket "JOIN ~a" channel))
81    channels))
82
83 (define (startswith-colon? str)
84   (and (> (string-length str) 0)
85        (eq? (string-ref str 0)
86             #\:)))
87
88 (define-record-type <irc-line>
89   (make-irc-line prefix command params)
90   irc-line?
91   (prefix irc-line-prefix)
92   (command irc-line-command)
93   (params irc-line-params))
94
95
96 (define (parse-line line)
97   (define (parse-params pre-params)
98     ;; This is stupid and imperative but I can't wrap my brain around
99     ;; the right way to do it in a functional way :\
100     (let ((param-list '())
101           (currently-building '()))
102       (for-each
103        (lambda (param-item)
104          (cond
105           ((startswith-colon? param-item)
106            (if (not (eq? currently-building '()))
107                (set! param-list
108                      (cons
109                       (reverse currently-building)
110                       param-list)))
111            (set! currently-building (list param-item)))
112           (else
113            (set! currently-building (cons param-item currently-building)))))
114        pre-params)
115       ;; We're still building something, so tack that on there
116       (if (not (eq? currently-building '()))
117           (set! param-list
118                 (cons (reverse currently-building) param-list)))
119       ;; return the reverse of the param list
120       (reverse param-list)))
121
122   (match (string-split line #\space)
123     (((? startswith-colon? prefix)
124       command
125       pre-params ...)
126      (make-irc-line prefix command
127                     (parse-params pre-params)))
128     ((command pre-params ...)
129      (make-irc-line #f command
130                     (parse-params pre-params)))))
131
132 (define (strip-colon-if-necessary string)
133   (if (and (> (string-length string) 0)
134            (string-ref string 0))
135       (substring/copy string 1)
136       string))
137
138 ;; @@: Not sure if this works in all cases, like what about in a non-privmsg one?
139 (define (irc-line-username irc-line)
140   (let* ((prefix-name (strip-colon-if-necessary (irc-line-prefix irc-line)))
141          (exclaim-index (string-index prefix-name #\!)))
142     (if exclaim-index
143         (substring/copy prefix-name 0 exclaim-index)
144         prefix-name)))
145
146 (define (condense-privmsg-line line)
147   "Condense message line and do multiple value return of
148   (channel message is-action)"
149   (define (strip-last-char string)
150     (substring/copy string 0 (- (string-length string) 1)))
151   (let* ((channel-name (caar line))
152          (rest-params (apply append (cdr line))))
153     (match rest-params
154       (((or "\x01ACTION" ":\x01ACTION") middle-words ... (= strip-last-char last-word))
155        (values channel-name
156                (string-join
157                 (append middle-words (list last-word))
158                 " ")
159                #t))
160       (((= strip-colon-if-necessary first-word) rest-message ...)
161        (values channel-name
162                (string-join (cons first-word rest-message) " ")
163                #f)))))
164
165 (define (default-handle-privmsg my-name speaker
166                                 channel-name message is-action)
167   (if is-action
168       (format #t "~a emoted ~s in channel ~a\n"
169               speaker message channel-name)
170       (format #t "~a said ~s in channel ~a\n"
171               speaker message channel-name)))
172
173 (define* (make-handle-line #:key
174                            (handle-privmsg default-handle-privmsg))
175   (define (handle-line socket line my-username)
176     (let ((parsed-line (parse-line line)))
177       (match (irc-line-command parsed-line)
178         ("PING"
179          (irc-display "PONG" socket))
180         ("PRIVMSG"
181          (receive (channel-name message is-action)
182              (condense-privmsg-line (irc-line-params parsed-line))
183            (let ((username (irc-line-username parsed-line)))
184              (handle-privmsg my-username username channel-name message is-action))))
185         (_
186          (display line)
187          (newline)))))
188   handle-line)
189
190 (define (make-simple-irc-handler handle-line username)
191   (let ((buffer '()))
192     (define (reset-buffer)
193       (set! buffer '()))
194     (define (should-read-char socket)
195       (and (char-ready? socket) (not (eof-object? (peek-char socket)))))
196     (define (irc-handler socket)
197       (while (should-read-char socket)
198         (set! buffer (cons (read-char socket) buffer))
199         (match buffer
200           ((#\newline #\return (? char? line-chars) ...)
201            (%sync (%run (handle-line
202                          socket
203                          (list->string (reverse line-chars))
204                          username)))
205            ;; reset buffer
206            (set! buffer '()))
207           (_ #f))))
208     irc-handler))
209
210 (define* (queue-and-start-irc-agenda! agenda socket #:key
211                                       (username "syncbot")
212                                       (inet-port default-irc-port)
213                                       (handler (make-simple-irc-handler
214                                                 (lambda args
215                                                   (apply (make-handle-line) args))
216                                                 username))
217                                       (channels '()))
218   (dynamic-wind
219     (lambda () #f)
220     (lambda ()
221       (enq! (agenda-queue agenda) (wrap (install-socket socket handler)))
222       (enq! (agenda-queue agenda) (wrap (handle-login socket username
223                                                       #:channels channels)))
224       (start-agenda agenda))
225     (lambda ()
226       (display "Cleaning up...\n")
227       (close socket))))
228
229
230 \f
231 ;;; CLI
232 ;;; ===
233
234 (define option-spec
235   `((server (single-char #\s) (required? #t) (value #t))
236     (port (single-char #\p)
237           (value #t)
238           (predicate
239            ,(lambda (s)
240               (if (string->number s) #t #f))))
241     (username (single-char #\u) (required? #t) (value #t))
242     (channels (value #t))
243     (listen)))
244
245 (define (main args)
246   (let* ((options (getopt-long args option-spec))
247          (hostname (option-ref options 'server #f))
248          (port (or (option-ref options 'port #f)
249                    default-irc-port))
250          (username (option-ref options 'username #f))
251          (listen (option-ref options 'listen #f))
252          (channels (option-ref options 'channels ""))
253          (agenda (make-agenda)))
254     (display `((server ,hostname) (port ,port) (username ,username)
255                (listen ,listen) (channels-split ,(string-split channels #\space))))
256     (newline)
257     (if listen
258         (spawn-and-queue-repl-server! agenda))
259     (queue-and-start-irc-agenda!
260      agenda
261      (irc-socket-setup hostname port)
262      #:inet-port port
263      #:username username
264      #:channels (string-split channels #\space))))