Last active
April 17, 2019 17:53
-
-
Save Struki84/4a83d5a5bf22b068f8178573e92a1e4b to your computer and use it in GitHub Desktop.
Sinatra web socket gem integration, taken out of Sinatra modular application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra-websocket' | |
class ChatController < Sinatra::Base | |
enable :method_override | |
set :channels, [] | |
# set :views, '/var/www/app/views' | |
set :root, File.dirname(File.dirname(__FILE__)) | |
register Sinatra::Reloader | |
helpers do | |
def subscribe(ws) | |
channel = {id: @channel_id, account: @account, socket: ws} | |
settings.channels << channel | |
user_status | |
end | |
def unsubscribe(ws) | |
settings.channels.each do |channel| | |
if channel[:socket] == ws | |
settings.channels.delete(channel) | |
end | |
end | |
user_status | |
end | |
def send_message(msg) | |
msg = JSON.parse(msg) | |
message = {'type' => msg['type'], 'content' => msg['content']} | |
if msg['type'] == 'media' | |
message['media_type'] = msg['media_type'] | |
end | |
message = message.to_json | |
settings.channels.each do |channel| | |
if channel[:id] == @channel_id | |
puts "sending to account #{channel[:account]} on channel #{@channel_id}" | |
channel[:socket].send message unless channel[:account] == @account | |
end | |
end | |
end | |
def user_status | |
#puts "user status for account #{@account}" | |
if settings.channels.count > 1 | |
status = {'type' => 'status', 'online' => true}.to_json | |
else | |
status = {'type' => 'status', 'online' => false}.to_json | |
end | |
settings.channels.each do |channel| | |
channel[:socket].send status unless channel[:id] != @channel_id | |
end | |
end | |
end | |
get '/:id/:account' do | |
@channel_id = params[:id] | |
@account = params[:account] | |
if !request.websocket? | |
haml :bad_request | |
else | |
content_type :json | |
puts "user #{@account} connected" | |
request.websocket do |socket| | |
socket.onopen do | |
subscribe socket | |
end | |
socket.onmessage do |content| | |
puts "sending message...#{content}" | |
send_message content | |
end | |
socket.onclose do |msg| | |
unsubscribe socket | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment