|
| 1 | +(ns dirac.automation.transcript-streamer |
| 2 | + (:require-macros [cljs.core.async.macros :refer [go go-loop]]) |
| 3 | + (:require [cljs.core.async :refer [<! chan sliding-buffer put! timeout]] |
| 4 | + [chromex.logging :refer-macros [log warn error info]] |
| 5 | + [dirac.lib.ws-client :as ws-client])) |
| 6 | + |
| 7 | +(defonce current-client (atom nil)) |
| 8 | +(defonce transcript-stream (chan (sliding-buffer 1024))) |
| 9 | + |
| 10 | +(defn publish! [text style] |
| 11 | + (put! transcript-stream {:op :publish |
| 12 | + :text text |
| 13 | + :style style})) |
| 14 | + |
| 15 | +; -- message sending -------------------------------------------------------------------------------------------------------- |
| 16 | + |
| 17 | +(defn send! [msg] |
| 18 | + (if-let [client @current-client] |
| 19 | + (ws-client/send! client msg) |
| 20 | + (throw (ex-info "No client!" msg)))) |
| 21 | + |
| 22 | +; -- message processing ----------------------------------------------------------------------------------------------------- |
| 23 | + |
| 24 | +(defmulti process-message :op) |
| 25 | + |
| 26 | +(defmethod process-message :error [message] |
| 27 | + (throw (ex-info "Received error message" message)) |
| 28 | + (go |
| 29 | + {:op :error |
| 30 | + :message (:type message)})) |
| 31 | + |
| 32 | +; -- connection ------------------------------------------------------------------------------------------------------------- |
| 33 | + |
| 34 | +(defn run-streaming-loop! [] |
| 35 | + (log "transcript-streamer: entering streaming loop...") |
| 36 | + (go-loop [] |
| 37 | + (when-let [msg (<! transcript-stream)] |
| 38 | + (send! msg) |
| 39 | + (recur)) |
| 40 | + (log "transcript-streamer: leaving streaming loop..."))) |
| 41 | + |
| 42 | +(defn on-message-handler [_client message] |
| 43 | + (go |
| 44 | + (if-let [result (<! (process-message message))] |
| 45 | + (send! result)))) |
| 46 | + |
| 47 | +(defn on-open-handler [client] |
| 48 | + (run-streaming-loop!)) |
| 49 | + |
| 50 | +(defn connect! [server-url opts] |
| 51 | + (log (str "transcript-streamer: connecting " server-url)) |
| 52 | + (let [default-opts {:name "Transcript Streamer (client)" |
| 53 | + :on-message on-message-handler |
| 54 | + :on-open on-open-handler} |
| 55 | + effective-opts (merge default-opts opts) |
| 56 | + client (ws-client/connect! server-url effective-opts)] |
| 57 | + (reset! current-client client))) |
| 58 | + |
| 59 | +(defn disconnect! [] |
| 60 | + (when-let [client @current-client] |
| 61 | + (ws-client/close! client) |
| 62 | + true)) |
| 63 | + |
| 64 | +(defn init! [server-url & [opts]] |
| 65 | + (if (some? server-url) |
| 66 | + (connect! server-url opts))) |
0 commit comments