tambur-client 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/.gitignore ADDED
@@ -0,0 +1,4 @@
1
+ *.gem
2
+ .bundle
3
+ Gemfile.lock
4
+ pkg/*
data/.travis.yml ADDED
@@ -0,0 +1,8 @@
1
+ language: ruby
2
+ rvm:
3
+ - 1.8.7
4
+ - 1.9.2
5
+ - 1.9.3
6
+ - jruby-18mode # JRuby in 1.8 mode
7
+ - jruby-19mode # JRuby in 1.9 mode
8
+ - rbx-18mode
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "http://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in ruby-tambur.gemspec
4
+ gemspec
data/README.md ADDED
@@ -0,0 +1,58 @@
1
+ ## Ruby Tambur.io REST API Client [![Build Status](https://secure.travis-ci.org/tamburio/ruby-tambur.png?branch=master)](http://travis-ci.org/tamburio/ruby-tambur)
2
+ Tambur.io provides a pain-free websocket experience.
3
+ ###Preliminary
4
+ Install this library preferably using [bundler][1]:
5
+
6
+ gem "ruby-tambur", :git => "git://github.com/tamburio/ruby-tambur.git", :branch => "master"
7
+
8
+ Please register on [Tambur.io][2] and create at least one app. This will give you the unique API\_KEY, an APP\_ID and a SECRET, which you need to initialize the client.
9
+
10
+ ###Example
11
+ ```ruby
12
+ require 'ruby-tambur'
13
+ tambur = Tambur::Connector.new(API_KEY, APP_ID, SECRET)
14
+ tambur.publish('mystream', 'some message')
15
+ ```
16
+ The example above publishes the given message to all subscribed clients. Clients can set different modes for streams they have subscribed. Currently the Tambur.io supports a 'auth', 'presence', and 'direct' mode. But you must grant permission by issueing a specific mode token. For generating such tokens you typically need the StreamName, the SubscriberId, and for direct- and presence-modes the UserId. The SubscriberId is the only parameter your clients must send you e.g. through some AJAX request which you can answer with the generated mode token.
17
+
18
+ ####Auth Mode
19
+ If you issue an auth mode token, the client can authenticate himself for a particular stream. If you use the <code>auth:</code> stream prefix you can control how we deliver your message.
20
+ ```ruby
21
+ tambur.publish('auth:mystream', 'some auth message')
22
+ ```
23
+ The example above publishes the given message to all subscribed clients that have the auth mode enabled.
24
+ Issuing an auth mode token is straight forward:
25
+ ```ruby
26
+ tambur.generate_auth_token('mystream', subscriber_id)
27
+ ```
28
+
29
+ ####Presence Mode
30
+ If you issue a presence mode token, the client can switch on and off presence mode. If presence mode is switched on the client will receive join- and leave-events of all the other presence clients in that particular stream. Issuing a presence mode token needs an extra 'User-Id' parameter, which enables you to connect a tambur.io subscriber-id to a User-Id used in your application:
31
+ ```ruby
32
+ tambur.generate_presence_token('mystream', 'Alice', subscriber_id)
33
+ ```
34
+
35
+ ####Direct Mode
36
+ If you issue a direct mode token, the client can switch on and off direct mode. If direct mode is switched on the client can send and receive messages from other clients in that particular stream. Issuing a direct mode token needs an extra 'User-Id' parameter, which enables you to connect a tambur.io subscriber-id to a User-Id used in your application:
37
+ ```ruby
38
+ tambur.generate_direct_token('mystream', 'Alice', subscriber_id)
39
+ ```
40
+
41
+ ####Private Messages
42
+ If you want to further limit your receivers to one specific subscriber you can do this using the 'private' stream.
43
+ ```ruby
44
+ tambur.publish('private:' + subscriber_id, 'some private message')
45
+ ```
46
+
47
+ ##License (MIT)
48
+ Copyright (c) \<2012\> \<Tambur.io\>
49
+
50
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
51
+
52
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
53
+
54
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
55
+
56
+
57
+ [1]: http://gembundler.com//
58
+ [2]: http://tambur.io
data/Rakefile ADDED
@@ -0,0 +1,32 @@
1
+ require "bundler/gem_tasks"
2
+ require 'rake/testtask'
3
+
4
+ task :default => ['test:units']
5
+
6
+ def rubies
7
+ require 'yaml'
8
+ rubies = YAML.load_file('.travis.yml')['rvm']
9
+ end
10
+
11
+ namespace :test do
12
+ Rake::TestTask.new(:units) do |t|
13
+ t.libs << "test"
14
+ t.test_files = FileList['test/*_test.rb']
15
+
16
+ t.verbose = true
17
+ end
18
+
19
+ desc 'run bundle install for all rubies'
20
+ task :prepare_rubies do
21
+ rubies.each do |ruby_version|
22
+ puts `rvm use #{ruby_version} && gem install bundler && bundle`
23
+ end
24
+ end
25
+
26
+ desc 'run test suite with all ruby versions'
27
+ task :multi_ruby do
28
+ rubies.each do |ruby_version|
29
+ puts `rvm use #{ruby_version} && bundle exec rake`
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,102 @@
1
+ module Tambur
2
+ begin
3
+ require 'uri'
4
+ require 'cgi'
5
+ require 'openssl'
6
+ require 'base64'
7
+ rescue LoadError
8
+ end
9
+
10
+ module Util
11
+ # A utility for signing an url using OAuth in a way that's convenient for debugging
12
+ # Note: the standard Ruby OAuth lib is here http://github.com/mojodna/oauth
13
+ # License: http://gist.github.com/375593
14
+ # Usage: see example.rb below
15
+ class OAuth
16
+
17
+ attr_accessor :consumer_key, :consumer_secret, :token, :token_secret, :req_method,
18
+ :sig_method, :oauth_version, :callback_url, :params, :req_url, :base_str
19
+
20
+ def initialize
21
+ @consumer_key = ''
22
+ @consumer_secret = ''
23
+ @token = ''
24
+ @token_secret = ''
25
+ @req_method = 'GET'
26
+ @sig_method = 'HMAC-SHA1'
27
+ @oauth_version = '1.0'
28
+ @callback_url = ''
29
+ end
30
+
31
+ # openssl::random_bytes returns non-word chars, which need to be removed. using alt method to get length
32
+ # ref http://snippets.dzone.com/posts/show/491
33
+ def nonce
34
+ Array.new( 5 ) { rand(256) }.pack('C*').unpack('H*').first
35
+ end
36
+
37
+ def percent_encode( string )
38
+ return URI.escape( string, /[^a-zA-Z0-9\-\.\_\~]/)
39
+ end
40
+
41
+ # @ref http://oauth.net/core/1.0/#rfc.section.9.2
42
+ def signature
43
+ key = percent_encode( @consumer_secret ) + '&' + percent_encode( @token_secret )
44
+
45
+ # ref: http://blog.nathanielbibler.com/post/63031273/openssl-hmac-vs-ruby-hmac-benchmarks
46
+ digest = OpenSSL::Digest::Digest.new( 'sha1' )
47
+ hmac = OpenSSL::HMAC.digest( digest, key, @base_str )
48
+
49
+ # ref http://groups.google.com/group/oauth-ruby/browse_thread/thread/9110ed8c8f3cae81
50
+ Base64.encode64( hmac ).chomp.gsub( /\n/, '' )
51
+ end
52
+
53
+ # sort (very important as it affects the signature), concat, and percent encode
54
+ # @ref http://oauth.net/core/1.0/#rfc.section.9.1.1
55
+ # @ref http://oauth.net/core/1.0/#9.2.1
56
+ # @ref http://oauth.net/core/1.0/#rfc.section.A.5.1
57
+ def query_string
58
+ pairs = []
59
+ @params.sort.each { | key, val |
60
+ pairs.push( "#{ percent_encode( key ) }=#{ percent_encode( val.to_s ) }" )
61
+ }
62
+ pairs.join '&'
63
+ end
64
+
65
+ # organize params & create signature
66
+ def sign( parsed_url )
67
+
68
+ @params = {
69
+ 'oauth_consumer_key' => @consumer_key,
70
+ 'oauth_nonce' => nonce,
71
+ 'oauth_signature_method' => @sig_method,
72
+ 'oauth_timestamp' => Time.now.to_i.to_s,
73
+ 'oauth_version' => @oauth_version
74
+ }
75
+
76
+ # if url has query, merge key/values into params obj overwriting defaults
77
+ if parsed_url.query
78
+ @params.merge! CGI.parse( parsed_url.query ).inject({}){|h, (k, v)|h[k.to_s] = v[0];h}
79
+ end
80
+
81
+ # @ref http://oauth.net/core/1.0/#rfc.section.9.1.2
82
+ @req_url = parsed_url.scheme + '://' + parsed_url.host + parsed_url.path
83
+
84
+ # create base str. make it an object attr for ez debugging
85
+ # ref http://oauth.net/core/1.0/#anchor14
86
+ @base_str = [
87
+ @req_method,
88
+ percent_encode( req_url ),
89
+
90
+ # normalization is just x-www-form-urlencoded
91
+ percent_encode( query_string )
92
+
93
+ ].join( '&' )
94
+
95
+ # add signature
96
+ @params[ 'oauth_signature' ] = signature
97
+
98
+ return self
99
+ end
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,3 @@
1
+ module Tambur
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,53 @@
1
+ require "ruby-tambur/version"
2
+ require "ruby-tambur/vendor/oauth_util.rb"
3
+ require 'net/http'
4
+ require 'openssl'
5
+
6
+ module Tambur
7
+ class Connector
8
+ def initialize(api_key, app_id, secret, options = {})
9
+ @app_id = app_id
10
+ @api_host = options[:api_host] || 'api.tambur.io'
11
+ @oauth = Tambur::Util::OAuth.new()
12
+ @oauth.consumer_key=api_key
13
+ @oauth.consumer_secret=secret
14
+ @oauth.req_method='POST'
15
+ end
16
+
17
+ def publish(stream, message)
18
+ path = '/app/' + @app_id + '/stream/' + stream.to_str+'?api_version=1.0&message='+ CGI::escape(message)
19
+ url = URI.parse('http://' + @api_host + path)
20
+ Net::HTTP.start(url.host) do | http |
21
+ request = Net::HTTP::Post.new(url.path)
22
+ request.body = @oauth.sign(url).query_string()
23
+ request['Content-Type'] = 'application/x-www-form-urlencoded'
24
+ response = http.request(request)
25
+ if response.code == '204'
26
+ return true
27
+ else
28
+ raise 'publish error: '+response.read_body
29
+ end
30
+ end
31
+ end
32
+
33
+ def generate_auth_token(stream, subscriber_id)
34
+ return generate_mode_token('auth', stream, subscriber_id)
35
+ end
36
+
37
+ def generate_presence_token(stream, user_id, subscriber_id)
38
+ return generate_mode_token('presence', stream + ':' + user_id, subscriber_id)
39
+ end
40
+
41
+ def generate_direct_token(stream, user_id, subscriber_id)
42
+ return generate_mode_token('direct', stream + ':' + user_id, subscriber_id)
43
+ end
44
+
45
+ private
46
+ def generate_mode_token(mode, property, subscriber_id)
47
+ mode_string = @oauth.consumer_key + ':' + @app_id + ':' + mode + ':' + property + ':' + subscriber_id
48
+ digest = OpenSSL::Digest::Digest.new( 'sha1' )
49
+ return OpenSSL::HMAC.hexdigest( digest, @oauth.consumer_secret, mode_string)
50
+ end
51
+
52
+ end
53
+ end
@@ -0,0 +1,24 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "ruby-tambur/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "tambur-client"
7
+ s.version = Tambur::VERSION
8
+ s.authors = ["Andre Graf"]
9
+ s.email = ["graf@tambur.io"]
10
+ s.homepage = "https://github.com/tamburio/ruby-tambur"
11
+ s.summary = %q{Simple Client for the Tambur.io REST API}
12
+ s.description = %q{Simple Client for the Tambur.io REST API}
13
+
14
+ s.rubyforge_project = "ruby-tambur"
15
+
16
+ s.files = `git ls-files`.split("\n")
17
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
18
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
19
+ s.require_paths = ["lib"]
20
+
21
+ # specify any dependencies here; for example:
22
+ s.add_development_dependency "rake"
23
+ s.add_runtime_dependency "json"
24
+ end
@@ -0,0 +1,84 @@
1
+ require 'test_helper'
2
+
3
+ class TamburPublishTest < Test::Unit::TestCase
4
+
5
+ def setup
6
+ url = URI.parse('http://wsbot.tambur.io')
7
+ Net::HTTP::start(url.host, url.port) {|http|
8
+ credentials = JSON.parse(http.get('/credentials').read_body)
9
+ @api_key = credentials['api_key']
10
+ @app_id = credentials['app_id']
11
+ @secret = credentials['secret']
12
+ @subscriber_id = http.get('/subscriber_id').read_body
13
+ }
14
+ @tambur = Tambur::Connector.new(@api_key, @app_id, @secret)
15
+ end
16
+
17
+ def test_publish
18
+ publish('test', 'test message')
19
+ end
20
+
21
+ def test_auth_publish
22
+ publish('auth:test', 'test message')
23
+ end
24
+
25
+ def test_private_publish
26
+ publish('private:'+@subscriber_id, 'test message')
27
+ end
28
+
29
+ def publish(stream, msg)
30
+ handle = generate_handle()
31
+ msg = {'handle' => handle, 'msg' => msg}
32
+ json_msg = msg.to_json()
33
+ assert_equal(true, @tambur.publish(stream, json_msg))
34
+ sleep(0.5)
35
+ url = URI.parse('http://wsbot.tambur.io')
36
+ Net::HTTP.start(url.host) { | http |
37
+ request = Net::HTTP::Get.new('/results?handle='+handle)
38
+ results = JSON.parse(http.request(request).read_body)
39
+ assert_equal(1, results.length)
40
+ if stream.start_with? 'private'
41
+ assert_equal(results[0][handle], {'private' => msg})
42
+ else
43
+ assert_equal(results[0][handle], {stream => msg})
44
+ end
45
+ }
46
+
47
+ end
48
+ end
49
+
50
+ class TamburAuthTokenTest < Test::Unit::TestCase
51
+
52
+ def setup
53
+ @tambur = Tambur::Connector.new('30af96de47e3c58329045ff136a4a3ea', 'ws-bot-1', 'wsbot')
54
+ end
55
+
56
+ def test_generate_auth_token
57
+ stream = 'test'
58
+ subscriber_id = 'a0629978-28d8-4fd4-b862-f67e9b6dfd8f'
59
+ token = @tambur.generate_auth_token(stream, subscriber_id)
60
+ assert_equal('2f25ad1ce5afab906cc582b6254a912590c60f73', token)
61
+ end
62
+
63
+ def test_generate_presence_token
64
+ stream = 'test'
65
+ user_id = 'test_user'
66
+ subscriber_id = 'a0629978-28d8-4fd4-b862-f67e9b6dfd8f'
67
+ token = @tambur.generate_presence_token(stream, user_id, subscriber_id)
68
+ assert_equal('dcadf9659116ebbe024a4cd5ae12bde48d95408e', token)
69
+ end
70
+
71
+ def test_generate_direct_token
72
+ stream = 'test'
73
+ user_id = 'test_user'
74
+ subscriber_id = 'a0629978-28d8-4fd4-b862-f67e9b6dfd8f'
75
+ token = @tambur.generate_direct_token(stream, user_id, subscriber_id)
76
+ assert_equal('2403374744295f5d22e3f999d4eb85b3f689c6b2', token)
77
+ end
78
+ end
79
+
80
+ def generate_handle
81
+ s = ""
82
+ 6.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
83
+ return s
84
+ end
@@ -0,0 +1,7 @@
1
+ $LOAD_PATH.unshift( File.join( File.dirname(__FILE__), "..", "lib") )
2
+
3
+ require 'rubygems'
4
+ require 'test/unit'
5
+ require 'net/http'
6
+ require 'json'
7
+ require 'ruby-tambur'
metadata ADDED
@@ -0,0 +1,90 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: tambur-client
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Andre Graf
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-10-08 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rake
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ! '>='
28
+ - !ruby/object:Gem::Version
29
+ version: '0'
30
+ - !ruby/object:Gem::Dependency
31
+ name: json
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - ! '>='
36
+ - !ruby/object:Gem::Version
37
+ version: '0'
38
+ type: :runtime
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ! '>='
44
+ - !ruby/object:Gem::Version
45
+ version: '0'
46
+ description: Simple Client for the Tambur.io REST API
47
+ email:
48
+ - graf@tambur.io
49
+ executables: []
50
+ extensions: []
51
+ extra_rdoc_files: []
52
+ files:
53
+ - .gitignore
54
+ - .travis.yml
55
+ - Gemfile
56
+ - README.md
57
+ - Rakefile
58
+ - lib/ruby-tambur.rb
59
+ - lib/ruby-tambur/vendor/oauth_util.rb
60
+ - lib/ruby-tambur/version.rb
61
+ - ruby-tambur.gemspec
62
+ - test/tambur_test.rb
63
+ - test/test_helper.rb
64
+ homepage: https://github.com/tamburio/ruby-tambur
65
+ licenses: []
66
+ post_install_message:
67
+ rdoc_options: []
68
+ require_paths:
69
+ - lib
70
+ required_ruby_version: !ruby/object:Gem::Requirement
71
+ none: false
72
+ requirements:
73
+ - - ! '>='
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ required_rubygems_version: !ruby/object:Gem::Requirement
77
+ none: false
78
+ requirements:
79
+ - - ! '>='
80
+ - !ruby/object:Gem::Version
81
+ version: '0'
82
+ requirements: []
83
+ rubyforge_project: ruby-tambur
84
+ rubygems_version: 1.8.24
85
+ signing_key:
86
+ specification_version: 3
87
+ summary: Simple Client for the Tambur.io REST API
88
+ test_files:
89
+ - test/tambur_test.rb
90
+ - test/test_helper.rb