How do I get clientId who published the message using faye - ruby-on-rails

I have implemented faye for chatting services. But I want to know how can I find the clientId of that person who published the msg. I tried this:
faye_server = Faye::RackAdapter.new(:mount => '/faye', :timeout => 45)
faye_server.bind(:publish) do |clientId, channel, data|
puts "client_id is #{clientId}"
end
But it gives me a blank ID. How can I fetch the clientID?

Related

How to subscribe a Pubnub channel asynchronous?

I want my rails app to subscribe a global channel, so everything happens on client, then client will publish into that channel. I want it to be asynchronous because there will be a lot of messages via that channels, and I want it to run along with Rails process. Currently, I can't get it to work, I put it initializers/pubnub.rb:
$pubnub.subscribe(channel: 'global', callback: ->(envelop) { do_something })
I don't get any incoming messages.
Just an usage example in my test app:
$pubnub = Pubnub.new(
:subscribe_key => "demo",
:publish_key => "demo",
:heartbeat => 10,
:logger => Rails.logger
)
ActiveRecord::Base.establish_connection
$pubnub.subscribe(:channel => :demo){|e| Message.create(:content => e.msg)}
It works just fine. What code You are trying to run in the callback?

How to integrate SoundCloud in Ruby on Rails?

I am new to RubyOnRails and SoundCloud.
I want to integrate SoundCloud API in my ruby on rails application.
For this I have registered on SoundCloud And I got the ClientID and ClientSecret. Also I have downloaded the SDK.
Now I have copied the files and folders from lib and spec directory to my applications lib and spec directory. Also I have added gem 'soundcloud' in the Gemfile.
After this I made simple code (copied from doc) in My Interactor:
# register a client with YOUR_CLIENT_ID as client_id_
client = SoundCloud.new(:client_id => YOUR_CLIENT_ID)
# get 10 hottest tracks
tracks = client.get('/tracks', :limit => 10, :order => 'hotness')
# print each link
tracks.each do |track|
puts track.permalink_url
end
But here I'm getting the error -
uninitialized constant MyApp::Interactors::MyInteractor::MyAction::SoundCloud
I followed the steps from APIDoc. Is there any step by step example for integrating SoundCloud in Ruby on Rails so that I can follow?
How can I resolve this error?
MyInteracor.rb
module MyApp
module Interactors
module MyInteractor
class MyAction < Struct.new(:user, :params)
def run
# SoundCloud
# register a client with YOUR_CLIENT_ID as client_id_
client = SoundCloud.new(:client_id => 'my-client-id')
# get 10 hottest tracks
tracks = client.get('/tracks', :limit => 10, :order => 'hotness')
# print each link
tracks.each do |track|
puts track.permalink_url
end
end
end
end
end
end
There's a typo in the soundcloud github page change the line:
client = SoundCloud.new(:client_id => 'my-client-id')
to
client = Soundcloud.new(:client_id => 'my-client-id')
[notice the lowercase c in Soundcloud]
Also you are going to need your client secret for SoundCloud's API to verify you.
Perhaps put client method and in it have client = SoundCloud.new(your-client-id,your-secret-key-your-redirect-uri) in a controller or helper with your client_id, client_secret, and redirect uri values protected in a .env file.
I think by leaving out your redirect_uri and client secret you might be getting this error in MyInteractor.rb
Hope this helps

Faye: big delay in http post request

I have this code in Faye rackup script:
faye_server = Faye::RackAdapter.new(:mount => '/faye', :timeout => 45)
faye_server.add_extension(ServerAuth.new)
server_uri = URI.parse(BacklinkHealth::FAYE_SERVER)
faye_server.on(:subscribe) do |client_id, channel|
puts "subscribed #{channel}"
if channel.starts_with?('/pagination')
website_id = channel.split('/')[2]
page = channel.split('/')[3]
app = ActionDispatch::Integration::Session.new(Rails.application)
app.get app.pagination_website_backlinks_path(website_id, :page => page)
message = {:channel => channel, :data => app.response.body, :ext => {:auth_token => BacklinkHealth::FAYE_TOKEN}}
puts 'started HTTP post'
Net::HTTP.post_form(server_uri, :message => message.to_json)
puts 'finished HTTP post'
end
end
The problem is that the execution comes to "started HTTP post" and then it takes more than a minute for the message to be registered at the client-side javascript. The messge "finished HTTP post" is never printed :( I don't understand what is going on.
If I try to execute an identical HTTP post from Rails console, it goes through in an instant although it did happen once or twice that it took a minute.
Any ideas?
It's much better to use this:
require 'eventmachine'
EM.run {
client = Faye::Client.new(BacklinkHealth::FAYE_SERVER)
client.publish(channel, 'pagination' => pagination)
}
than Http requests... I couldn't get this to work with authentication (yet) but I will.

Pubnub and Rails 4

I'm following a twitter tutorial for a class project and I'm stuck at the part where the tutorial is using PUBNUB. I'm getting the following error:
Showing C:/RubyProjects/twitter/app/views/layouts/application.html.erb where line #93 raised:
**wrong number of arguments(1 for 0)**
Extracted source (around line #93):
PUBNUB.subscribe({
channel : "<%= Digest::SHA1.hexdigest(current_user.username, current_user.created_at) %>",
callback : function(message) { updateTimeline(message) }
I found on stackoverflow and found that EventMachine helped some folks and I tried that but still nada :(
I checked the PUBNUB page on Github and saw that it has changed the way channel and callback was written so I tried doing that but it did not help either. Im still getting the same error about wrong number of arguments(1 for 0).
Notify.rb
class Notify
def self.deliver_message_to_user(params)
post = Post.find(params[:post_id])
user = User.find(params[:user_id])
user.channel ||= Channel.new(
:channel_ident =>
Digest::SHA1.hexdigest(user.username, user.created_at.to_s))
Pubnub.publish({
:channel => user.channel.channel_ident,
:message => post.to_json(:include => :user)
})
end
end
application.html.erb
<script>
function updateTimeline(message) {
var html = JST['post'](jQuery.parseJSON(message));
$('#timeline').prepend(html);
}
Pubnub.subscribe({
:channel => "<%= Digest::SHA1.hexdigest(current_user.username, current_user.created_at) %>",
:callback => function(message) { updateTimeline(message) }
})
</script>
I put require 'digest' in my application.rb file and it still din't help. Could it be the syntax? If it is, i'm not sure what the correct syntax would be.
Publishing PubNub Messages in Ruby on Rails 4.0+
I'm pulling the following details from the PubNub Ruby README.md file - https://github.com/pubnub/ruby/blob/master/README.md
First you need to require PubNub lib from the PubNub Gem in Ruby.
## Require PubNub Gem
require 'pubnub'
## Instantiate a new PubNub instance.
pubnub = Pubnub.new(
:publish_key => 'demo', # publish_key only required if publishing.
:subscribe_key => 'demo', # required
:secret_key => nil, # optional, if used, message signing is enabled
:cipher_key => nil, # optional, if used, encryption is enabled
:ssl => nil # true or default is false
)
## Create a callback for checking response of Publish
#my_callback = lambda { |message| puts(message) }
## Execute Publish
pubnub.publish(
:channel => :hello_world,
:message => "hi",
:callback => #my_callback
)
## Sometimes you need a sleep depending on your server type
sleep(1)

How to pull Google Analytics stats?

Is Google API Ruby client the best option?
I have a site example.com with users and I want them to see their google analytics stats on example.com, how can I do it ?
I can see the example but I'm not able to figure out how to begin.
I also use the google-api-ruby-client gem and set it up about the same way that is outlined in the link you provided (https://gist.github.com/joost/5344705).
Just follow the steps outlined in the link to set up a Google Analytics client:
# you need to set this according to your situation/needs
SERVICE_ACCOUNT_EMAIL_ADDRESS = '...' # looks like 12345#developer.gserviceaccount.com
PATH_TO_KEY_FILE = '...' # the path to the downloaded .p12 key file
PROFILE = '...' # your GA profile id, looks like 'ga:12345'
require 'google/api_client'
# set up a client instance
client = Google::APIClient.new
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:issuer => SERVICE_ACCOUNT_EMAIL_ADDRESS,
:signing_key => Google::APIClient::PKCS12.load_key(PATH_TO_KEY_FILE, 'notasecret')
).tap { |auth| auth.fetch_access_token! }
api_method = client.discovered_api('analytics','v3').data.ga.get
# make queries
result = client.execute(:api_method => api_method, :parameters => {
'ids' => PROFILE,
'start-date' => Date.new(1970,1,1).to_s,
'end-date' => Date.today.to_s,
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'filters' => 'ga:pagePath==/url/to/user'
})
puts result.data.rows.inspect
To display statistics for a user's page in your app, you have to adjust the metrics and filters parameters when making the query. The query above for example will return a result object containing all pageviews for the page with url example.com/url/to/user.
Caveat: this answer was written a long time ago and Google released a new, incompatible version of the gem. Please consult https://github.com/google/google-api-ruby-client/blob/master/MIGRATING.md

Resources