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