37e4e0195ecbbe4a5b449aa19b39d8521a3e94f1
[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 (echo-back-message 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 default-handle-privmsg echo-back-message)
174
175 (define* (make-handle-line #:key
176                            (handle-privmsg default-handle-privmsg))
177   (define (handle-line socket line my-username)
178     (let ((parsed-line (parse-line line)))
179       (match (irc-line-command parsed-line)
180         ("PING"
181          (irc-display "PONG" socket))
182         ("PRIVMSG"
183          (receive (channel-name message is-action)
184              (condense-privmsg-line (irc-line-params parsed-line))
185            (let ((username (irc-line-username parsed-line)))
186              (handle-privmsg my-username username channel-name message is-action))))
187         (_
188          (display line)
189          (newline)))))
190   handle-line)
191
192 (define (make-simple-irc-handler handle-line username)
193   (let ((buffer '()))
194     (define (reset-buffer)
195       (set! buffer '()))
196     (define (should-read-char socket)
197       (and (char-ready? socket) (not (eof-object? (peek-char socket)))))
198     (define (irc-handler socket)
199       (while (should-read-char socket)
200         (set! buffer (cons (read-char socket) buffer))
201         (match buffer
202           ((#\newline #\return (? char? line-chars) ...)
203            (%sync (%run (handle-line
204                          socket
205                          (list->string (reverse line-chars))
206                          username)))
207            ;; reset buffer
208            (set! buffer '()))
209           (_ #f))))
210     irc-handler))
211
212 (define* (queue-and-start-irc-agenda! agenda socket #:key
213                                       (username "syncbot")
214                                       (inet-port default-irc-port)
215                                       (handler (make-simple-irc-handler
216                                                 (lambda args
217                                                   (apply (make-handle-line) args))
218                                                 username))
219                                       (channels '()))
220   (dynamic-wind
221     (lambda () #f)
222     (lambda ()
223       (enq! (agenda-queue agenda) (wrap (install-socket socket handler)))
224       (enq! (agenda-queue agenda) (wrap (handle-login socket username
225                                                       #:channels channels)))
226       (start-agenda agenda))
227     (lambda ()
228       (display "Cleaning up...\n")
229       (close socket))))
230
231
232 \f
233 ;;; CLI
234 ;;; ===
235
236 (define option-spec
237   `((server (single-char #\s) (required? #t) (value #t))
238     (port (single-char #\p)
239           (value #t)
240           (predicate
241            ,(lambda (s)
242               (if (string->number s) #t #f))))
243     (username (single-char #\u) (required? #t) (value #t))
244     (channels (value #t))
245     (listen)))
246
247 (define (main args)
248   (let* ((options (getopt-long args option-spec))
249          (hostname (option-ref options 'server #f))
250          (port (or (option-ref options 'port #f)
251                    default-irc-port))
252          (username (option-ref options 'username #f))
253          (listen (option-ref options 'listen #f))
254          (channels (option-ref options 'channels ""))
255          (agenda (make-agenda)))
256     (display `((server ,hostname) (port ,port) (username ,username)
257                (listen ,listen) (channels-split ,(string-split channels #\space))))
258     (newline)
259     (if listen
260         (spawn-and-queue-repl-server! agenda))
261     (queue-and-start-irc-agenda!
262      agenda
263      (irc-socket-setup hostname port)
264      #:inet-port port
265      #:username username
266      #:channels (string-split channels #\space))))