Created
January 8, 2014 12:09
-
-
Save StephanieSunshine/8315920 to your computer and use it in GitHub Desktop.
Sinatra, Websockets, Redis publish / subscribe ( publish is missing atm )
This file contains hidden or 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
| !/usr/bin/env ruby | |
| # ruby examples/echochat.rb | |
| require 'ostruct' | |
| require 'json' | |
| require 'base32' | |
| require 'sinatra' | |
| require 'sinatra-websocket' | |
| require 'sinatra/respond_to' | |
| require 'redis' | |
| set :server, 'puma' | |
| set :sockets, [] | |
| def digest_and_validate( base32 ) | |
| #This needs to validate the user if authenticated as well. | |
| payload = OpenStruct.new(JSON.parse(Base32.decode( base32 ),{ :symbolize_names => true })) | |
| if(payload.from.nil?)then payload.valid = false; payload.error = 'bad from'; return payload; end | |
| ( payload.valid = false; payload.error = 'bad to'; return payload ) if(payload.to.nil?) | |
| ( payload.valid = false; payload.error = 'bad ver'; return payload ) if(payload.ver.nil?) | |
| ( payload.valid = false; payload.error = 'bad pay'; return payload ) if(payload.pay.nil?) | |
| payload.valid = true | |
| payload.error = 'none' | |
| return payload | |
| end | |
| get '/api/publish/:payload' do | |
| end | |
| get '/api/link/:payload' do | |
| if !request.websocket? | |
| redirect "/" | |
| else | |
| payload = digest_and_validate(params[:payload]) | |
| return(payload.error) if !payload.valid | |
| request.websocket do |ws| | |
| redis = Redis.new | |
| ws.onopen do | |
| ws.send("Hello World!") | |
| settings.sockets << ws | |
| redis.subscribe(:main) do |on| | |
| on.subscribe do |channel, subscriptions| | |
| # puts "Subscribed to ##{channel} (#{subscriptions} subscriptions)" | |
| ws.send "Subscribed to ##{channel} (#{subscriptions} subscriptions)" | |
| end | |
| on.message do |channel, message| | |
| ws.send "##{channel}: #{message}" | |
| end | |
| end | |
| end | |
| ws.onmessage do |msg| | |
| EM.next_tick { settings.sockets.each{|s| s.send(msg) } } | |
| end | |
| ws.onclose do | |
| warn("wetbsocket closed") | |
| settings.sockets.delete(ws) | |
| end | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment