ios 5 push notification and rhomobile - rhomobile

I can get push working except for messages that come in while app is closed.
Messages do show up on Notification Center, but only passed to app when user clicks on the actual msg 1 by 1.
Does anyone know if there is a way to fetch all the messages from the Notification Center with Rhomobile?

For anyone interested,
Could not find a way to retrieve notifications from iOS Notifications Center so I did the following:
added in application.rb
def on_activate_app
# Had to do this for iOS not getting all the messages from Notification Center
Rho::Timer.start(100, "/app/Settings/check_for_pending_friends", "nil")
super
end
Then in controller.rb inside the Settings folder
def check_for_pending_friends
person = Person.find(:first)
url = "http://my_app.com/users/#{person.remote_id}/pending_msgs
# which looks for any msgs sent to that person with read_at = nil from server
Rho::AsyncHttp.get(
:url => url,
:headers => {'User-Agent' => Rho::RhoConfig.user_agent},
:callback => url_for(:action => :see_if_pending_messages_callback)
) if person
end
def see_if_pending_messages_callback
# Check to see if msg does not already exist in device, if not then add it
end

Related

Unable to get facebook Open Graph action approved using rails and the Koala gem

I keep getting this message after submitting my application
Your Open Graph action failed to publish on any of the Platforms you submitted. Make sure the action is working properly by publishing the action with a test user before resubmitting.
I have testers with test users, my own account, testers and it works all the time..
background.
users has_many :authorization_providers, e.g. facebook, twitter, gplus e.t.c
in the facebook action I'm fetching the oauth_token
def facebook
begin provider = authorization_providers.where(provider: 'facebook').first
#facebook ||= Koala::Facebook::API.new(provider.oauth_token)
block_given? ? yield(#facebook) : #facebook
rescue Koala::Facebook::APIError => e #Koala::Facebook::APIError
return nil
end
#facebook
end
In this action I'm getting permission
def facebook_publish_actions
if facebook
begin
permissions = facebook.get_connection("me", "permissions")
publish_actions_permission = permissions.find { |permission| permission["permission"] == "publish_actions" }
publish_actions_permission_granted = publish_actions_permission && publish_actions_permission["status"] == "granted"
return publish_actions_permission_granted
rescue
return false
end
else
return false
end
end
The actual posting is done from a sidekiq worker where 'share_on_facebook' and 'recording' is records from the db
user.facebook.put_wall_post(share_on_facebook.message,
{
"name" => "#{recording.title}",
"link" => "http://www.digiramp.com/users/#{recording.user.slug}/recordings/#{recording.id}",
"caption" => "#{user.name} recomended a recording",
"description" => "#{recording.comment}",
"picture" => "#{recording.get_artwork}"
})
On the facebook developer page I have created one story for the app 'Recommend a Song'
All the above works.
Anyone willing to help me I will grant all the required permissions.
Right now you can go to http://digiramp.com and sign up with facebook.
I will add you as a tester to my project and you should be able to post.
Edit:
I Do pass the id: FbRecordingCommentWorker.perform_async(#share_on_facebook.id)
Can you post the line of the code, where you initiate sidekiq job? Using objects in sidekiq call may not work as expected as objects are stored in hash representation in Redis. So better idea is replacing the object parameters to values.
Replacing some thing like this
User.delay.do_some_stuff(current_user, 20)
with
User.delay.do_some_stuff(current_user.id, 20)
and finding user object in the actual method may fix the issue.

How do I take this method I defined in the model and have it executed automatically once per day?

This is only the second rails app I've ever created so I new at doing this. If there is a better way of doing things then I'm open to hearing your suggestions but keep in mind that I'm learning right now.
I have a method in my model called twilio_api_call. It uses an api to send a text message to a specified phone number pulled out of the database. I would like this method to be executed once per day at 12pm without any user interaction. I am working off my localhost and plan to deploy this app to Heroku. How can I achieve this goal? Maybe pull out this code and place it in some external file that can be called automatically somehow?
require 'twilio-ruby'
class User < ActiveRecord::Base
has_many :selections
has_many :movies, through: :selection
has_secure_password
def self.get_notifications
Movie.find_by_sql("SELECT u.phone, m.title FROM users AS u INNER JOIN movies AS m ON u.id = m.user_id WHERE m.release_date::date = current_date")
end
def self.twilio_api_call
# get user data to parse and send to Twilio api
data = get_notifications
# put your own credentials here
account_sid = 'insert sid here'
auth_token = 'token goes here'
# data is array of hashes. Parse data.
# loop through data hash, build Twilio code
data.each { | key |
phone_number = key["phone"]
message = "Message from MovieTextAlert - the movie: '" + key["title"] + "' has been released today in theaters."
# set up a client to talk to the Twilio REST API
#client = Twilio::REST::Client.new account_sid, auth_token
#client.account.messages.create({
:from => '+18563176098',
:to => phone_number,
:body => message,
})
}
end
end
You can use whenever gem for such periodic actions
every 1.day, :at => '12:00 pm' do
runner "User.twilio_api_call"
end
This code will execute your method everyday at 12:00 pm.

How to create a multipart ical email? [Rails]

What I want to achieve is the following:
Send an email with delayed_job containing:
plain-text
html (will be displayed by regular clients which don't understand the inline ical)
"inline" ical which is recognized by Outlook and Thunderbird (with Lightning).
a "regular" ical attachment (for #2)
What works so far/what does'nt:
I am able to send the email via delayed_job with all parts, however:
in Apple's Mail 2 attachments show up (instead of one):
(the html is displayed fine)
in Thunderbird (Lightning) I do get an invitation, just like I want. But the Alarm does not show up.
I have to do some REALLY disgusting gsubs on the rendered iCal in order for the ATTENDEES to show up. (see code snippet)
My thinking:
The first thing to keep in mind is: in order to send an email with attachments from delayed_job
To fix this, remember to add this line to your mailer: content_type "multipart/mixed"
As far as I understand the correct MIME-Type hierarchy would therefore be:
multipart/mixed
multipart/alternative
text/plain
text/html
text/calendar (with: method=REQUEST)
application/ics
Warning! code incoming.
I currently construct this email in the following manner:
Edit: I updated the mailer for Rails 4.2 (attachments must be placed before mail)
in my mailer.rb
def invitation_email(...)
subject = "I suck at email..."
attachments["invite.ics"] = { mime_type: "application/ics",
content: ical_attachment }
email = mail(from: me, to: you, subject: subject)
add_ical_part_to(email)
email
end
def add_ical_part_to(mail)
outlook_body = ical_attachment
mail.add_part(Mail::Part.new do
content_type "text/calendar; method=REQUEST"
body outlook_body
end)
end
and this is how I construct the ical attachments:
def ical_attachment
params_participant = {
"ROLE" => "REQ-PARTICIPANT",
"RSVP" => "FALSE",
"PARTSTAT" => "ACCEPTED"
}
params_invite = {
"CUTYPE" => 'INDIVIDUAL',
"ROLE" => "REQ-PARTICIPANT",
"PARTSTAT" => "NEEDS-ACTION",
"RSVP" => "TRUE"
}
cal = Icalendar::Calendar.new
event = Icalendar::Event.new
event.dtstart #party.from.to_datetime, { "VALUE" => "DATE" }
event.dtend #party.to.to_datetime, { "VALUE" => "DATE" }
event.summary #party.title
event.description #party.description
event.klass "PRIVATE"
event.organizer "cn=#{#user.name} #{#user.surname}:mailto:#{#user.email}"
# THIS DOES NOT WORK
event.alarm.trigger = "-PT5M" # 5 Minutes before...
#party.participations.each do |participation|
str = "cn=#{participation.user.name} #{participation.user.surname}:mailto:#{participation.user.email}"
event.add_attendee(str, params_participant)
end
#party.invitations.each do |invitee|
event.add_attendee("mailto:#{invitee.email}", params_invite)
end
cal.add_event(event)
cal.publish
# I KNOW THIS IS HORRIBLE AND I HATE IT, BUT OTHERWISE THE ATTENDEES DO NOT SHOW UP
cal.to_ical.gsub("ORGANIZER:", "ORGANIZER;").gsub("ACCEPTED:", "ACCEPTED;").gsub("TRUE:", "TRUE;").gsub("PUBLISH", "REQUEST")
end
Any help would be really appreciated!
The email that is being generated: http://pastebin.com/patf05zd
Oh and I'm on:
Rails 3.2.13
The Icalendar gem I'm using
In case someone else happens to come across this, here is what I did:
Instead of the icalendar gem I now use ri_cal. Although I was skeptical because the last commit to that repo was 3 years ago, the google group was a very helpful resource.
Here is how I generate the ical attachment (both inline and normal), which seems to be working fine (although it obviously needs some refactoring :))
def to_ical
# this is horrible
klass = self
cal = RiCal.Calendar do
event = event do
organizer "CN=#{klass.user.name} #{klass.user.surname}:mailto:#{klass.user.email}"
summary klass.party.title
description klass.ical_description
dtstart klass.party.from.utc.to_datetime
dtend klass.party.to.utc.to_datetime
location "See url in description"
security_class klass.security_class
# this is horrible
h = self
klass.party.participations.each do |participation|
h.add_attendee klass.prepare_participant(participation)
end
klass.party.invitations.each do |invitee|
h.add_attendee klass.prepare_invitee(invitee.email)
end
unless klass.party.reminder == 0
alarm do
description "Alarm description"
trigger klass.convert_trigger # -PT1H
action "DISPLAY"
end
end
end
end
# THE HORROR
cal.to_s.gsub("ATTENDEE:", "ATTENDEE")
.gsub("ORGANIZER:", "ORGANIZER;")
.gsub("CALSCALE:GREGORIAN", "CALSCALE:GREGORIAN\nMETHOD:REQUEST\n")
end
The 2 Attachments in Apples Mail still show up, I don't think that can be fixed.
Your second B64 encoded attachment contains a lot of garbage towards the end (attendee field).
That would explain the Thunderbird issue.
Please note that some clients will ignore any alarm you may set on a REQUEST: As an organizer, you should not dictate when each attendee should be reminded of the meeting. That would be a rather rude thing to do.
Regarding the Apple iCal issue, there is not much you can do I'm afraid: Some clients want the ics within, some as an attachment so you have to provide both. Does it show the accept/decline panel on iCal ?

Action Controller Live for different user

Im experementing with the new Rails 4 feature ActionControllerLive.
I try to build up a system with many users who are notified when somebody clicks a specific link for example enters messages#index controller.
My problem is that at the time all users are notified when somebody uses messages#index controller even the user who entered the controller!
Im searching for a solution so that i can only inform specific users!
In all my controlles i have #current_user but i dont really know how i should avoid that he also gets a notifcation about what he is actually doing!
One possible solution would be that i sort the notifications with jquery at the frontend but this also would mean that you can spyout notifications that are privat.
Another solution is that every user has its on channel but i dont know i this really makes sens and how i should transpose it!
Here is my actual code: Thanks!
def events
response.headers["Content-Type"] = "text/event-stream"
redis = Redis.new
redis.subscribe('gaga') do |on|
on.message do |event, data|
response.stream.write("data: #{data }\n\n")
end
end
rescue IOError
logger.info "Stream closed"
ensure
response.stream.close
end
def index
#message = Message.new
#departments = Department.all.where.not(id: #current_department.id).last(4)
$redis = Redis.new
data = {"user" => #current_user.name}
$redis.publish "gaga", data.merge('msg' => "#{#current_user.name} entered messages index").to_json
end
And forntend:
source = new EventSource('/formular')
source.addEventListener 'gaga', (e) ->
alert e
Had this problem :)
We solved it by using a private channel
The ActionController::Live component doesn't know who is listening to whatever it sends, so the best way to keep your code efficient is to send to private channels which are dependent on the user
Here's an example from our live code. It uses Pusher, which is websockets, but is the same principle:
#app/controllers/controller.rb
Pusher['private-user-' + current_user.id.to_s].trigger('my_event', {
message: "Removed"
})
#app/assets/javascripts/javascript.js
channel = pusher.subscribe("private-user-#{gon.user_id}")
channel.bind "my_event", (data) ->
alert data.message

confused and disoriented with paypal ipn

I am using this gem for payments in paypal https://github.com/tc/paypal_adaptive
I am very confused and disoriented with this gem. It has a poorly documented and is difficult for me to understand how to get the data from paypal on ipn response.
I hope this question will help more people having the same problem.
My steps are:
1º I send request to paypal from my orders_controller.rb with method preaproval_payment.
def preapproval_payment
preapproval_request = PaypalAdaptive::Request.new
data = {
"returnUrl" => response_paypal_user_orders_url(current_user),
"cancelUrl"=> cancel_payment_gift_url(#gift),
"requestEnvelope" => {"errorLanguage" => "en_US"},
"senderEmail" => "gift_1342711309_per#gmail.com",
"startingDate" => Time.now,
"endingDate" => Time.now + (60*60*24) * 30,
"currencyCode"=>"USD",
"maxAmountPerPayment" => "#gift.price",
"ipnNotificationUrl" => ipn_notification_url,
"ip" => request.remote_ip
}
preapproval_response = preapproval_request.preapproval(data)
puts data
if preapproval_response.success?
redirect_to preapproval_response.preapproval_paypal_payment_url
else
redirect_to gift_url(#gift), alert: t(".something_was_wrong")
end
end
2º These are the data of my request in my log console from command puts data :
{"returnUrl"=>"http://localhost:3000/en/u/maserranocaceres/orders/response_paypal", "cancelUrl"=>"http://localhost:3000/en/gifts/gift-1/cancel_payment", "requestEnvelope"=>{"errorLanguage"=>"en_US"}, "senderEmail"=>"gift_1342711309_per#gmail.com", "startingDate"=>2012-07-29 13:05:49 +0200, "endingDate"=>2012-08-28 13:05:49 +0200, "currencyCode"=>"USD", "maxAmountPerPayment"=>9, "ipnNotificationUrl"=>"http://localhost:3000/ipn_notification?locale=en", "ip"=>"127.0.0.1"}
3º I redirect to paypal page, and I make the payment on paypal successfully :D.
4º When payment is completed successfully, I am directed to:
http://localhost:3000/en/u/maserranocaceres/orders/response_paypal
I have response_paypal action in orders_controller.rb. It is GET action and my code for this action is:
def response_paypal
respond_to do |format|
format.html { redirect_to user_orders_url(current_user), :alert => "works fine return url"}
end
end
Up to this point everything works fine.
Now what I need is to get the data I received from paypal and save my database a new order if payment is successfully processed.
5º For this purpose I make a file in lib/paypal_ipn.rb and I add to this file the content from https://github.com/tc/paypal_adaptive/blob/master/templates/paypal_ipn.rb
# Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
class PaypalIpn
def self.call(env)
if env["PATH_INFO"] =~ /^\/paypal_ipn/
request = Rack::Request.new(env)
params = request.params
ipn = PaypalAdaptive::IpnNotification.new
ipn.send_back(env['rack.request.form_vars'])
if ipn.verified?
#mark transaction as completed in your DB
output = "Verified."
else
output = "Not Verified."
end
[200, {"Content-Type" => "text/html"}, [output]]
else
[404, {"Content-Type" => "text/html"}, ["Not Found"]]
end
end
end
In my routes.rb I add:
match "/ipn_notification" => PaypalIpn
My 2 problems are:
a) I do not see that after making the payment this file to be fired and I can not see in my console data I get from paypal.
b) I want to send to paypal in my request, the id of object #gift for being able to recover later in paypal_ipn.rb and to save my database.
What am I doing wrong and how I can solve these problems?
Thank you
I haven't used that gem, but I've used PayPal IPN before. Here are some things you should check:
Do you have your PayPal account set up to use IPN? You must enable this setting on the account for this to work.
Have you verified that when you pass ipn_notification_url during the payment process, that it matches your "/ipn_notification" route?
For this to work, PayPal must be able to communicate directly with the server that is running this app. This means that typically, unless you have a custom setup on your local machine with dynamic DNS or something, that you will need to actually deploy this code to a server in order for PayPal to be able to communicate with your app. In other words, if this is running on http://localhost:3000, this will not work.
To answer your second question, how to recover #gift in order to record the fact it was paid in your database, I'm not entirely sure how to do it with this gem, but I'll tell you how I do it using ActiveMerchant - it is probably quite similar.
In your payment request to PayPal, you can pass in an invoice number. I believe the field is just called "invoice". Here you would pass the ID of the gift.
When PayPal notifies your app via IPN that the order was paid for, it will pass the invoice number back to you. Retrieve the #gift using this invoice number and then you can do what you need with it.
Here are the relevant parts of my working PayPal code, using the ActiveMerchant gem: https://gist.github.com/3198178
Good luck!

Resources