2024-10-12 19:53:34 -04:00
|
|
|
(in-package #:live-chat-ws)
|
|
|
|
|
|
|
|
(defvar *connections* (make-hash-table))
|
|
|
|
|
|
|
|
(defun handle-post-message (message)
|
|
|
|
"Handle a new message being posted to the chat."
|
2024-10-14 05:34:03 -04:00
|
|
|
(let* ((message (gethash "message" (com.inuoe.jzon:parse message)))
|
|
|
|
(message (string-trim '(#\Newline #\Return)
|
|
|
|
(cl-who:escape-string message))))
|
|
|
|
(when (and message
|
|
|
|
(> (length message) 0)
|
|
|
|
(not (string= "" message)))
|
|
|
|
(format *standard-output* "Message received: ~a~%" message)
|
|
|
|
(live-chat-db:insert-message message))))
|
2024-10-12 19:53:34 -04:00
|
|
|
|
|
|
|
(defun handle-new-connection (con)
|
|
|
|
(setf (gethash con *connections*)
|
|
|
|
(princ-to-string (gensym "USER-"))))
|
|
|
|
|
|
|
|
(defun broadcast-to-room (connection message)
|
2024-10-14 05:34:03 -04:00
|
|
|
(let* ((message (handle-post-message message))
|
|
|
|
(message (live-chat-ui:generate-html-message
|
|
|
|
(format nil "~a: ~a"
|
|
|
|
(gethash connection *connections*)
|
|
|
|
message))))
|
|
|
|
(loop for con being the hash-key of *connections* do
|
2024-10-12 19:53:34 -04:00
|
|
|
(send con message))))
|
|
|
|
|
|
|
|
(defun handle-close-connection (connection)
|
|
|
|
(let ((message
|
2024-10-14 05:34:03 -04:00
|
|
|
(live-chat-ui:generate-html-message
|
2024-10-13 01:26:33 -04:00
|
|
|
(format nil "... ~a disconnected."
|
|
|
|
(gethash connection *connections*)))))
|
2024-10-14 05:34:03 -04:00
|
|
|
(loop for con being the hash-key of *connections* do
|
2024-10-12 19:53:34 -04:00
|
|
|
(send con message))))
|
|
|
|
|
|
|
|
(defun make-websocket-server (env)
|
|
|
|
(handler-case
|
|
|
|
(let ((ws (make-server env)))
|
|
|
|
(on :open ws
|
|
|
|
(lambda ()
|
|
|
|
(handle-new-connection ws)))
|
|
|
|
(on :message ws
|
|
|
|
(lambda (msg)
|
|
|
|
(broadcast-to-room ws msg)))
|
|
|
|
(on :close ws
|
|
|
|
(lambda (&key code reason)
|
|
|
|
(declare (ignore code reason))
|
|
|
|
(handle-close-connection ws)))
|
|
|
|
(lambda (responder)
|
|
|
|
(declare (ignore responder))
|
|
|
|
(start-connection ws)))
|
|
|
|
(error (e)
|
|
|
|
(declare (ignore e))
|
|
|
|
(format nil "Something went wrong. Try again?"))))
|