1(import mpd socketserver
2 [mpd.exceptions [*]]
3 [mpd.parser [parse-command]])
4(require [hy.contrib.walk [let]])
5
6(defclass Handler [socketserver.BaseRequestHandler]
7 (defn send-resp [self resp]
8 (self.request.sendall (.encode (+ (str resp) mpd.DELIMITER))))
9
10 (defn dispatch-single [self cmd]
11 (let [resp (self.server.callable cmd)]
12 (if resp (self.send-resp resp))))
13
14 (defn dispatch-list [self list]
15 (setv ok-list? (= list.name "command_list_ok_begin"))
16 (for [cmd list.args]
17 (self.dispatch-single cmd)
18 (if ok-list? (self.send-resp "list_OK"))))
19
20 (defn dispatch [self input]
21 (try
22 (setv cmd (parse-command input))
23 (except [ValueError]
24 (self.send-resp (MPDException ACKError.UNKNOWN "syntax error"))
25 (return)))
26 (try
27 (if (cmd.list?)
28 (self.dispatch-list cmd)
29 (self.dispatch-single cmd))
30 (except [e MPDException]
31 (self.send-resp e))
32 (else (self.send-resp "OK"))))
33
34 (defn handle [self]
35 (self.send-resp (% "OK MPD %s" mpd.VERSION))
36 (with [file (self.request.makefile)]
37 (for [input (iter (mpd.util.Reader file) "")]
38 (self.dispatch input)))))
39
40(defclass Server [socketserver.ThreadingTCPServer]
41 (defn --init-- [self addr callable]
42 (.--init-- socketserver.ThreadingTCPServer self addr Handler)
43 (setv self.daemon_threads True)
44 (setv self.callable callable)))