Skip to content

Commit

Permalink
Merge branch 'release/v0.1.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
genaromadrid committed Mar 26, 2018
2 parents 890df7d + 66b3727 commit e627808
Show file tree
Hide file tree
Showing 14 changed files with 543 additions and 19 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,4 @@ Gemfile.lock

# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
.rvmrc
*.sublime-workspace
14 changes: 12 additions & 2 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ AllCops:
Style/Documentation:
Enabled: false

Metrics/BlockLength:
Exclude:
- Guardfile
- 'spec/**/*'
- 'examples/**/*'
- '*.gemspec'

Style/HashSyntax:
EnforcedStyle: ruby19

Expand Down Expand Up @@ -36,5 +43,8 @@ Metrics/ModuleLength:
Style/Documentation:
Enabled: false

Style/HashSyntax:
EnforcedStyle: ruby19
RSpec/ExampleLength:
Max: 10

Style/SafeNavigation:
Enabled: false
14 changes: 14 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
language: ruby
sudo: false
rvm:
- 2.1
- 2.2
- 2.3.0
- 2.5.0
notifications:
email:
on_success: change
on_failure: always
script:
- bundle exec rubocop
- bundle exec rspec
64 changes: 60 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
# Em::Pusher::Client

Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/em/pusher/client`. To experiment with that code, run `bin/console` for an interactive prompt.
[![Gem Version][rubygems-image]][rubygems-url]
[![Build Status][travis-image]][travis-url]
[![Coverage Status][coverage-image]][coverage-url]

TODO: Delete this and the text above, and describe your gem
EventMachine client library for Pusher

## Installation

Expand All @@ -22,14 +24,68 @@ Or install it yourself as:

## Usage

TODO: Write usage instructions here
```ruby
EM.run do
opts = {
key: 'my-key',
cluster: 'us2',
port: 80,
scheme: 'ws',
}
EM::Pusher::Client.connect(opts) do |conn|
conn.connected do
puts 'connected'
end

conn.callback do
puts 'callback'
msg = {
event: 'pusher:subscribe',
data: {
channel: 'my-channel',
},
}
conn.send_msg(msg)
end

conn.errback do |e|
puts "Got error: #{e}"
end

conn.stream do |msg|
puts "stream: <#{msg}>"
case msg.event
when 'pusher:connection_established'
puts 'Connection Established'
when 'pusher_internal:subscription_succeeded'
puts "Subscribed to #{msg.json['channel']}"
when 'someevent'
puts "someevent: #{msg.data}"
end
end

conn.disconnect do
puts 'gone'
EM.stop_event_loop
end
end
end
```

## Development

After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
After checking out the repo, run `bin/setup` to install dependencies. You can also run `rake console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/em-pusher-client.


[rubygems-image]: https://badge.fury.io/rb/em-pusher-client.svg
[rubygems-url]: https://badge.fury.io/rb/em-pusher-client
[travis-image]: https://travis-ci.org/genaromadrid/em-pusher-client.svg?branch=master
[travis-url]: https://travis-ci.org/genaromadrid/em-pusher-client
[coverage-image]: https://coveralls.io/repos/github/genaromadrid/em-pusher-client/badge.svg?branch=master
[coverage-url]: https://coveralls.io/github/genaromadrid/em-pusher-client?branch=master
4 changes: 4 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,7 @@

require 'bundler/gem_tasks'
task default: :spec

task :console do
exec 'pry -r em/pusher/client -I ./lib'
end
6 changes: 1 addition & 5 deletions bump
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ __INITIAL__ = ['0', '0', '1']
if __name__ == "__main__":
v = []
try:
version_file = glob.glob("lib/*/version.rb")[0]
version_file = glob.glob("lib/em/pusher/client/version.rb")[0]
raw_v = re.search(r'VERSION = \'(.*)\'', open(version_file).read(), re.M|re.I|re.S).group(1)
v = re.split(re.compile("\.|-"), raw_v)
v = v[0:3]
Expand All @@ -29,10 +29,6 @@ if __name__ == "__main__":
print("failed to parse the existing VERSION file, assuming v 0.0.1")
v = ['0', '0', '1']

except FileNotFoundError:
print("failed to find a VERSION file, assuming v 0.0.0")
v = ['0', '0', '0']

op = ''
try:
op = sys.argv[1]
Expand Down
17 changes: 12 additions & 5 deletions em-pusher-client.gemspec
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

# frozen_string_literal: true

lib = File.expand_path('lib', __dir__)
Expand All @@ -11,9 +10,9 @@ Gem::Specification.new do |spec|
spec.authors = ['Genaro Madrid']
spec.email = ['genmadrid@gmail.com']

spec.summary = 'Write a short summary, because RubyGems requires one.'
spec.description = 'Write a longer description or delete this line.'
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.summary = 'Eventmachine pusher.com client'
spec.description = 'Subscribe to channels with eventmachine'
spec.homepage = 'https://github.com/genaromadrid/em-pusher-client'

# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
Expand All @@ -31,7 +30,15 @@ Gem::Specification.new do |spec|
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']

spec.add_dependency 'eventmachine', '~> 1.2.5'
spec.add_dependency 'websocket', '~> 1.2.5'

spec.add_development_dependency 'bundler', '~> 1.16'
spec.add_development_dependency 'coveralls', '0.8.21'
spec.add_development_dependency 'pry', '~> 0.11'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'rubocop-rspec'
spec.add_development_dependency 'rspec', '~> 3.7'
spec.add_development_dependency 'rubocop', '~> 0.54'
spec.add_development_dependency 'rubocop-rspec', '~> 1.24'
spec.add_development_dependency 'simplecov', '~> 0.14'
end
50 changes: 50 additions & 0 deletions examples/normal.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# frozen_string_literal: true

require './lib/em/pusher/client'

EM.run do
opts = {
key: 'my-key',
cluster: 'us2',
port: 80,
scheme: 'ws',
}
EM::Pusher::Client.connect(opts) do |conn|
conn.connected do
puts 'connected'
end

conn.callback do
puts 'callback'
msg = {
event: 'pusher:subscribe',
data: {
channel: 'my-channel',
},
}
conn.send_msg(msg)
end

conn.errback do |e|
puts "Got error: #{e}"
end

conn.stream do |msg|
puts "stream: <#{msg}>"
case msg.event
when 'pusher:connection_established'
puts 'Connection Established'
when 'pusher_internal:subscription_succeeded'
puts "Subscribed to #{msg.json['channel']}"
when 'someevent'
puts "someevent: #{msg.data}"
end
# conn.close_connection if closed?
end

conn.disconnect do
puts 'gone'
EM.stop_event_loop
end
end
end
35 changes: 32 additions & 3 deletions lib/em/pusher/client.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,40 @@
# frozen_string_literal: true

require 'em/pusher/client/version'
require_relative 'client/version'
require_relative 'client/connection'
require_relative 'client/msg_parser'

module Em
module EM
module Pusher
module Client
# Your code goes here...
DEFAULT_OPTIONS = {
app_id: nil,
app_secret: nil,
scheme: 'ws',
port: 80,
encrypted: 'on',
protocol: 4,
version: '4.2',
client_name: 'em-pusher-client',
}.freeze

REQUIRED_OPTIONS = %i[key cluster].freeze

def self.connect(options)
uri = url(options)
Connection.connect(uri).tap do |conn|
yield conn if block_given?
end
end

def self.url(options)
opts = DEFAULT_OPTIONS.merge(options)
REQUIRED_OPTIONS.each { |opt| fail ArgumentError, "option #{opt} is required" unless opts[opt] }
"#{opts[:scheme]}://ws-#{opts[:cluster]}.pusher.com:#{opts[:port]}/app/#{opts[:key]}" \
"?protocol=#{opts[:protocol]}" \
"&client=#{opts[:client_name]}" \
"&version=#{opts[:version]}"
end
end
end
end
107 changes: 107 additions & 0 deletions lib/em/pusher/client/connection.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# frozen_string_literal: true

require 'eventmachine'
require 'uri'
require 'json'
require 'websocket'

module EM
module Pusher
module Client
class Connection < EM::Connection
include EM::Deferrable

attr_accessor :url
attr_accessor :protocol_version
attr_accessor :origin

def self.connect(uri, opts = {})
p_uri = URI.parse(uri)
conn = EM.connect(p_uri.host, p_uri.port || 80, self) do |c|
c.url = uri
c.protocol_version = opts[:version]
c.origin = opts[:origin]
end
yield conn if block_given?
conn
end

def post_init
@handshaked = false
@frame = ::WebSocket::Frame::Incoming::Client.new
end

def connection_completed
@connect.yield if @connect
@hs = ::WebSocket::Handshake::Client.new(
url: @url,
origin: @origin,
version: @protocol_version,
)
send_data(@hs.to_s)
end

def stream(&cback)
@stream = cback
end

def connected(&cback)
@connect = cback
end

def disconnect(&cback)
@disconnect = cback
end

# https://pusher.com/docs/pusher_protocol#subscription-events
def subscribe(channel, auth = nil, channel_data = nil)
msg = {
event: 'pusher:subscribe',
data: {
channel: channel,
auth: auth,
channel_data: channel_data,
},
}
conn.send_msg(msg)
end

def receive_data(data)
return handle_received_data(data) if @handshaked
@hs << data
if @hs.finished?
@handshaked = true
succeed
end

receive_data(@hs.leftovers) if @hs.leftovers
end

def send_msg(data, args = {})
type = args[:type] || :text
data = data.to_json if data.is_a?(Hash)
frame = ::WebSocket::Frame::Outgoing::Client.new(
data: data,
type: type,
version: @hs.version,
)
send_data(frame.to_s)
end

def unbind
super
@disconnect.call if @disconnect
end

private

def handle_received_data(data)
@frame << data
while (msg = @frame.next)
@stream.call(EM::Pusher::Client::MsgParser.new(msg)) if @stream
end
end
end
end
end
end
Loading

0 comments on commit e627808

Please sign in to comment.