This repository was archived by the owner on Apr 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatroom_channel.rb
74 lines (66 loc) · 1.89 KB
/
chatroom_channel.rb
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class ChatroomChannel < ApplicationCable::Channel
def subscribed
room = params[:room]
if room == "Waiting Room"
stream_from get_stream_name
elsif room.starts_with?("pixel:")
id = room[6..-1]
canvas = PixelCanvas.find_by(id: id)
if canvas
stream_from get_stream_name
else
puts "[ERROR] ChatroomChannel.subscribed - could not find pixel canvas with id #{id}"
end
else
canvas = Canvas.find_by(id: room)
if canvas
stream_from get_stream_name
else
puts "[ERROR] ChatroomChannel.subscribed - could not find canvas with id #{params[:room]}"
end
end
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def message(data)
room = params[:room]
chatroom = nil
canvas = nil
if room == "Waiting Room"
chatroom = Chatroom.find_by(name: room)
elsif room.starts_with?("pixel:")
id = room[6..-1]
canvas = PixelCanvas.find(id)
if canvas
chatroom = canvas.chatroom
else
puts "[ERROR] ChatroomChannel.message - could not find pixel canvas with id #{params[:room]}"
return
end
else
canvas = Canvas.find(params[:room])
if canvas
chatroom = canvas.chatroom
else
puts "[ERROR] ChatroomChannel.message - could not find canvas with id #{params[:room]}"
return
end
end
message = Message.new(content: data["content"])
message.user = User.find_by(id: current_user)
message.chatroom = chatroom
if message.save
ActionCable.server.broadcast get_stream_name,
message: message.content,
user: message.user.name,
time: message.created_at
else
puts "[ERROR] ChatroomChannel.message - error: #{message.errors.full_messages}"
end
end
private
def get_stream_name
"chatroom_channel:#{params[:room]}"
end
end