add irc-line type, switch to (match) for handle-line
[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 q)
28              (ice-9 match))
29
30 \f
31 ;;; Network stuff
32 ;;; =============
33
34 (define default-irc-port 6665)
35
36 (define* (irc-socket-setup hostname #:optional (inet-port default-irc-port))
37   (let ((s (socket PF_INET SOCK_STREAM 0))
38         (ip-address (inet-ntoa (car (hostent:addr-list (gethost hostname))))))
39     (connect s AF_INET
40              (inet-pton AF_INET ip-address)
41              inet-port)
42     s))
43
44 (define (install-socket socket handler)
45   (display "Installing socket...\n")   ; debugging :)
46   (make-port-request socket #:read handler))
47
48 (define irc-eol "\r\n")
49
50 (define (irc-line line)
51   (string-concatenate (list line irc-eol)))
52
53 (define-syntax-rule (irc-format dest format-string rest ...)
54   (let ((line (string-concatenate
55                (list (format #f format-string rest ...)
56                      irc-eol))))
57     (match dest
58       (#f line)
59       (#t (display line))
60       (else
61        (display line dest)))))
62
63 (define* (irc-display line #:optional dest)
64   (if dest
65       (display (irc-line line) dest)
66       (display (irc-line dest))))
67
68 (define* (handle-login socket username
69                        #:key
70                        (hostname "*")
71                        (servername "*")
72                        (realname username)
73                        (channels '()))
74   (irc-format socket "USER ~a ~a ~a :~a"
75               username hostname servername realname)
76   (irc-format socket "NICK ~a" username)
77   (for-each
78    (lambda (channel)
79      (irc-format socket "JOIN ~a" channel))
80    channels))
81
82 (define (startswith-colon? str)
83   (and (> (string-length str) 0)
84        (eq? (string-ref str 0)
85             #\:)))
86
87 (define-record-type <irc-line>
88   (make-irc-line prefix command params)
89   irc-line?
90   (prefix irc-line-prefix)
91   (command irc-line-command)
92   (params irc-line-params))
93
94
95 (define (parse-line line)
96   (define (parse-params pre-params)
97     ;; This is stupid and imperative but I can't wrap my brain around
98     ;; the right way to do it in a functional way :\
99     (let ((param-list '())
100           (currently-building '()))
101       (for-each
102        (lambda (param-item)
103          (cond
104           ((startswith-colon? param-item)
105            (if (not (eq? currently-building '()))
106                (set! param-list
107                      (cons
108                       (reverse currently-building)
109                       param-list)))
110            (set! currently-building (list param-item)))
111           (else
112            (set! currently-building (cons param-item currently-building)))))
113        pre-params)
114       ;; We're still building something, so tack that on there
115       (if (not (eq? currently-building '()))
116           (set! param-list
117                 (cons (reverse currently-building) param-list)))
118       ;; return the reverse of the param list
119       (reverse param-list)))
120
121   (match (string-split line #\space)
122     (((? startswith-colon? prefix)
123       command
124       pre-params ...)
125      (make-irc-line prefix command
126                     (parse-params pre-params)))
127     ((command pre-params ...)
128      (make-irc-line #f command
129                     (parse-params pre-params)))))
130
131
132 (define (handle-line socket line my-username)
133   (let ((parsed-line (parse-line line)))
134     (match (irc-line-command parsed-line)
135       ("PING"
136        (irc-display "PONG" socket))
137       ("PRIVMSG"
138        (display "hey we got a PRIVMSG up in here!\n")
139        (display parsed-line)
140        (newline)
141        (display line)
142        (newline))
143       (_
144        (display line)
145        (newline)))))
146
147 (define (make-simple-irc-handler handle-line username)
148   (let ((buffer '()))
149     (define (reset-buffer)
150       (set! buffer '()))
151     (define (should-read-char socket)
152       (and (char-ready? socket) (not (eof-object? (peek-char socket)))))
153     (define (irc-handler socket)
154       (while (should-read-char socket)
155         (set! buffer (cons (read-char socket) buffer))
156         (match buffer
157           ((#\newline #\return (? char? line-chars) ...)
158            (%sync (%run (handle-line
159                          socket
160                          (list->string (reverse line-chars))
161                          username)))
162            ;; reset buffer
163            (set! buffer '()))
164           (_ #f))))
165     irc-handler))
166
167 (define* (queue-and-start-irc-agenda! agenda socket #:key
168                                       (username "syncbot")
169                                       (inet-port default-irc-port)
170                                       (handler (make-simple-irc-handler
171                                                 (lambda args
172                                                   (apply handle-line args))
173                                                 username))
174                                       (channels '()))
175   (dynamic-wind
176     (lambda () #f)
177     (lambda ()
178       (enq! (agenda-queue agenda) (wrap (install-socket socket handler)))
179       (enq! (agenda-queue agenda) (wrap (handle-login socket username
180                                                       #:channels channels)))
181       (start-agenda agenda))
182     (lambda ()
183       (display "Cleaning up...\n")
184       (close socket))))
185
186
187 \f
188 ;;; CLI
189 ;;; ===
190
191 (define option-spec
192   `((server (single-char #\s) (required? #t) (value #t))
193     (port (single-char #\p)
194           (value #t)
195           (predicate
196            ,(lambda (s)
197               (if (string->number s) #t #f))))
198     (username (single-char #\u) (required? #t) (value #t))
199     (channels (value #t))
200     (listen)))
201
202 (define (main args)
203   (let* ((options (getopt-long args option-spec))
204          (hostname (option-ref options 'server #f))
205          (port (or (option-ref options 'port #f)
206                    default-irc-port))
207          (username (option-ref options 'username #f))
208          (listen (option-ref options 'listen #f))
209          (channels (option-ref options 'channels ""))
210          (agenda (make-agenda)))
211     (display `((server ,hostname) (port ,port) (username ,username)
212                (listen ,listen) (channels-split ,(string-split channels #\space))))
213     (newline)
214     (if listen
215         (spawn-and-queue-repl-server! agenda))
216     (queue-and-start-irc-agenda!
217      agenda
218      (irc-socket-setup hostname port)
219      #:inet-port port
220      #:username username
221      #:channels (string-split channels #\space))))