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