aboutsummaryrefslogtreecommitdiff
path: root/src/wialt_listener.cr
blob: 7c4d01e69084722fa01525acf25bfba30548952c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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