aboutsummaryrefslogtreecommitdiff
path: root/src/wialt_listener.cr
diff options
context:
space:
mode:
authorIndrajith K L2023-11-06 06:12:28 +0530
committerIndrajith K L2023-11-06 06:12:28 +0530
commitbf91c7ef4f374a78bff46a42a85c0426b0abf7d0 (patch)
treea38e002b64c3dd5fb6f9dca7791eba4f99a68760 /src/wialt_listener.cr
downloadwialt_listener-bf91c7ef4f374a78bff46a42a85c0426b0abf7d0.tar.gz
wialt_listener-bf91c7ef4f374a78bff46a42a85c0426b0abf7d0.tar.bz2
wialt_listener-bf91c7ef4f374a78bff46a42a85c0426b0abf7d0.zip
Initial CommitHEADmaster
* Listener Implementation - In-Progress * Initial API Endpoints and Websocket implementation * API End Points Implemented -> /music_changed, /state_change * Websocket End Points implemented -> /i_am_listening_to * Socket Implementation - In-Progress
Diffstat (limited to 'src/wialt_listener.cr')
-rw-r--r--src/wialt_listener.cr52
1 files changed, 52 insertions, 0 deletions
diff --git a/src/wialt_listener.cr b/src/wialt_listener.cr
new file mode 100644
index 0000000..7c4d01e
--- /dev/null
+++ b/src/wialt_listener.cr
@@ -0,0 +1,52 @@
+# TODO: Write documentation for `WialtListener`
+require "kemal"
+
+class MusicChange
+ include JSON::Serializable
+
+ property title : String
+end
+
+
+module WialtListener
+ VERSION = "0.1.0"
+ sockets = [] of HTTP::WebSocket
+
+ static_headers do |response|
+ response.headers.add("Access-Control-Allow-Origin", "")
+ end
+
+ post "/music_changed" do |env|
+ response = MusicChange.from_json env.request.body.not_nil!
+ puts "#{response.title}"
+ send_message_to_clients(sockets, response.title)
+ {status: "OK"}
+ end
+
+ post "/state_change" do |env|
+ puts "#{env.request.body}"
+ {status: "OK"}
+ end
+
+ ws "/i_am_listening_to" do |socket|
+ sockets.push socket
+
+ socket.on_message do |message|
+ send_message_to_clients(sockets, message)
+ end
+
+ socket.on_close do |_|
+ sockets.delete(socket)
+ puts "Closing Socket: #{socket}"
+ end
+
+ end
+
+ def self.send_message_to_clients(sockets, title)
+ sockets.each do |a_socket|
+ a_socket.send title
+ end
+ end
+
+ Kemal.run
+end