e6ad361ae322cfa7bc8308629c24840f8f3b173d
[8sync.git] / 8sync / systems / irc.scm
1 #!/usr/bin/guile \
2 -e main -s
3 !#
4
5 ;;; 8sync --- Asynchronous programming for Guile
6 ;;; Copyright (C) 2015 Christopher Allan Webber <cwebber@dustycloud.org>
7 ;;;
8 ;;; This file is part of 8sync.
9 ;;;
10 ;;; 8sync is free software: you can redistribute it and/or modify it
11 ;;; under the terms of the GNU Lesser General Public License as
12 ;;; published by the Free Software Foundation, either version 3 of the
13 ;;; License, or (at your option) any later version.
14 ;;;
15 ;;; 8sync is distributed in the hope that it will be useful,
16 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;;; GNU Lesser General Public License for more details.
19 ;;;
20 ;;; You should have received a copy of the GNU Lesser General Public
21 ;;; License along with 8sync.  If not, see <http://www.gnu.org/licenses/>.
22
23 (define-module (8sync systems irc)
24   #:use-module (8sync repl)
25   #:use-module (8sync agenda)
26   #:use-module (8sync actors)
27   #:use-module (srfi srfi-9)
28   #:use-module (ice-9 getopt-long)
29   #:use-module (ice-9 format)
30   #:use-module (ice-9 receive)
31   #:use-module (ice-9 rdelim)
32   #:use-module (ice-9 q)
33   #:use-module (ice-9 match)
34   #:use-module (oop goops)
35   #:export (<irc-bot>
36             irc-bot-username irc-bot-server irc-bot-channels irc-bot-port
37
38             irc-bot-send-line
39
40             handle-line handle-misc-input
41             handle-user-join handle-user-quit
42
43             default-irc-port))
44
45 \f
46 ;;; Network stuff
47 ;;; =============
48
49 (define default-irc-port 6665)
50
51 (define* (irc-socket-setup hostname #:optional (inet-port default-irc-port))
52   (let* ((s (socket PF_INET SOCK_STREAM 0))
53          (flags (fcntl s F_GETFL))
54          (ip-address (inet-ntop AF_INET (car (hostent:addr-list (gethost hostname))))))
55     (fcntl s F_SETFL (logior O_NONBLOCK flags))
56     (connect s AF_INET
57              (inet-pton AF_INET ip-address)
58              inet-port)
59     s))
60
61 (define irc-eol "\r\n")
62
63 (define (startswith-colon? str)
64   (and (> (string-length str) 0)
65        (eq? (string-ref str 0)
66             #\:)))
67
68 ;; TODO: This needs a cleanup.  Maybe even just using a regex is fine.
69 (define (parse-line line)
70   (define (parse-params pre-params)
71     ;; This is stupid and imperative but I can't wrap my brain around
72     ;; the right way to do it in a functional way :\
73     (let ((param-list '())
74           (currently-building '()))
75       (for-each
76        (lambda (param-item)
77          (cond
78           ((startswith-colon? param-item)
79            (if (not (eq? currently-building '()))
80                (set! param-list
81                      (cons
82                       (reverse currently-building)
83                       param-list)))
84            (set! currently-building (list param-item)))
85           (else
86            (set! currently-building (cons param-item currently-building)))))
87        pre-params)
88       ;; We're still building something, so tack that on there
89       (if (not (eq? currently-building '()))
90           (set! param-list
91                 (cons (reverse currently-building) param-list)))
92       ;; return the reverse of the param list
93       (reverse param-list)))
94
95   (match (string-split line #\space)
96     (((? startswith-colon? prefix)
97       command
98       pre-params ...)
99      (values prefix command
100              (parse-params pre-params)))
101     ((command pre-params ...)
102      (values #f command
103              (parse-params pre-params)))))
104
105 (define (strip-colon-if-necessary string)
106   (if (and (> (string-length string) 0)
107            (string-ref string 0))
108       (substring/copy string 1)
109       string))
110
111 ;; @@: Not sure if this works in all cases, like what about in a non-privmsg one?
112 (define (irc-line-username irc-line-prefix)
113   (let* ((prefix-name (strip-colon-if-necessary irc-line-prefix))
114          (exclaim-index (string-index prefix-name #\!)))
115     (if exclaim-index
116         (substring/copy prefix-name 0 exclaim-index)
117         prefix-name)))
118
119 (define (condense-privmsg-line line)
120   "Condense message line and do multiple value return of
121   (channel message emote?)"
122   (define (strip-last-char string)
123     (substring/copy string 0 (- (string-length string) 1)))
124   (let* ((channel-name (caar line))
125          (rest-params (apply append (cdr line))))
126     (match rest-params
127       (((or "\x01ACTION" ":\x01ACTION") middle-words ... (= strip-last-char last-word))
128        (values channel-name
129                (string-join
130                 (append middle-words (list last-word))
131                 " ")
132                #t))
133       (((= strip-colon-if-necessary first-word) rest-message ...)
134        (values channel-name
135                (string-join (cons first-word rest-message) " ")
136                #f)))))
137
138 ;;; A goofy default
139 (define (echo-message irc-bot speaker channel-name
140                       line-text emote?)
141   "Simply echoes the message to the current-output-port."
142   (if emote?
143       (format #t "~a emoted ~s in channel ~a\n"
144               speaker line-text channel-name)
145       (format #t "~a said ~s in channel ~a\n"
146               speaker line-text channel-name)))
147
148 \f
149 ;;; Bot
150 ;;; ===
151
152 (define-class <irc-bot> (<actor>)
153   (username #:init-keyword #:username
154             #:getter irc-bot-username)
155   (realname #:init-keyword #:realname
156             #:init-value #f)
157   (server #:init-keyword #:server
158           #:getter irc-bot-server)
159   (channels #:init-keyword #:channels
160             #:getter irc-bot-channels)
161   (port #:init-keyword #:port
162         #:init-value default-irc-port
163         #:getter irc-bot-port)
164   (socket #:accessor irc-bot-socket)
165   (actions #:allocation #:each-subclass
166            #:init-value (build-actions
167                          (*init* irc-bot-init)
168                          (*cleanup* irc-bot-cleanup)
169                          (main-loop irc-bot-main-loop)
170                          (send-line irc-bot-send-line-action))))
171
172 (define (irc-bot-realname irc-bot)
173   (or (slot-ref irc-bot 'realname)
174       (irc-bot-username irc-bot)))
175
176 (define (irc-bot-init irc-bot message)
177   "Initialize the IRC bot"
178   (define socket
179     (irc-socket-setup (irc-bot-server irc-bot)
180                       (irc-bot-port irc-bot)))
181   (set! (irc-bot-socket irc-bot) socket)
182   (format socket "USER ~a ~a ~a :~a~a"
183           (irc-bot-username irc-bot)
184           "*" "*"  ; hostname and servername
185           (irc-bot-realname irc-bot) irc-eol)
186   (format socket "NICK ~a~a" (irc-bot-username irc-bot) irc-eol)
187
188   (for-each
189    (lambda (channel)
190      (format socket "JOIN ~a~a" channel irc-eol))
191    (irc-bot-channels irc-bot))
192
193   (<- (actor-id irc-bot) 'main-loop))
194
195 (define (irc-bot-cleanup irc-bot message)
196   (close (irc-bot-socket irc-bot)))
197
198 (define (irc-bot-main-loop irc-bot message)
199   (define socket (irc-bot-socket irc-bot))
200   (define line (string-trim-right (read-line socket) #\return))
201   (dispatch-raw-line irc-bot line)
202   (cond
203    ;; The port's been closed for some reason, so stop looping
204    ((port-closed? socket)
205     'done)
206    ;; We've reached the EOF object, which means we should close
207    ;; the port ourselves and stop looping
208    ((eof-object? (peek-char socket))
209     (close socket)
210     'done)
211    ;; ;; Looks like we've been killed somehow... well, stop running
212    ;; ;; then!
213    ;; ((actor-am-i-dead? irc-bot)
214    ;;  (if (not (port-closed? socket))
215    ;;      (close socket))
216    ;;  'done)
217    ;; Otherwise, let's read till the next line!
218    (else
219     (<- (actor-id irc-bot) 'main-loop))))
220
221 (define* (irc-bot-send-line-action irc-bot message
222                                    channel line #:key emote?)
223   "Action handler for sending lines.  Real behavior happens in
224 irc-bot-send-line."
225   (irc-bot-send-line irc-bot channel line #:emote? emote?))
226
227 (define* (irc-bot-send-line irc-bot channel line #:key emote?)
228   ;; TODO: emote? handling
229   (format (irc-bot-socket irc-bot) "PRIVMSG ~a :~a~a"
230           channel line irc-eol))
231
232
233 ;;; Likely-to-be-overridden generic methods
234
235 (define-method (dispatch-raw-line (irc-bot <irc-bot>) raw-line)
236   "Dispatch a raw line of input"
237   (receive (line-prefix line-command line-params)
238       (parse-line raw-line)
239     (match line-command
240       ("PING"
241        (display (string-append "PONG" irc-eol)
242                 (irc-bot-socket irc-bot)))
243       ("PRIVMSG"
244        (receive (channel-name line-text emote?)
245            (condense-privmsg-line line-params)
246          (let ((username (irc-line-username line-prefix)))
247            (handle-line irc-bot username channel-name
248                         line-text emote?))))
249       (_ (handle-misc-input irc-bot raw-line)))))
250
251 (define-method (handle-line (irc-bot <irc-bot>) username channel-name
252                                     line-text emote?)
253   (echo-message irc-bot username channel-name line-text emote?))
254
255 (define-method (handle-misc-input (irc-bot <irc-bot>) raw-line)
256   (display raw-line)
257   (newline))
258
259 (define-method (handle-user-join (irc-bot <irc-bot>) user channel)
260   'TODO)
261
262 (define-method (handle-user-quit (irc-bot <irc-bot>) user channel)
263   'TODO)
264