how do i get message list with Gmail Api? - ruby-on-rails

i want to access list of messages
Object:
2.0.0-p481 :008 > g.gmail_api.users.messages.list
=> # < Google::APIClient::Method:0x41c948c ID:gmail.users.messages.list >
i'm new in this API and unable to get how do i use Gmail API.
Thanks

# Google
gem "omniauth-google-oauth2"
gem "google-api-client"
in my model
def query_google( email )
self.refresh_token_from_google if self.expires_at.to_i < Time.now.to_i
#google_api_client = Google::APIClient.new(
application_name: 'Joggle',
application_version: '1.0.0'
)
#google_api_client.authorization.access_token = self.access_key
#gmail = #google_api_client.discovered_api('gmail', "v1")
# https://developers.google.com/gmail/api/v1/reference/users/messages/list
# Now that we instantiated gmail, we can take the category (messages) and the method
# You can also add parameters if you wish to do so:
# #calendar_events = google_api_client.execute(
# :api_method => #calendar.events.list,
# :parameters => {
# "calendarId" => current_user.email,
# 'timeMin' => date.to_s,
# 'timeMax' => max_date.to_s
# # 'items' => [{'id' => current_user.email}]
# },
# :headers => {'Content-Type' => 'application/json'}
# )
#emails = #google_api_client.execute(
api_method: #gmail.users.messages.list,
parameters: {
userId: "me",
# searching messages based on number of queries:
# https://developers.google.com/gmail/api/guides/filtering
q: "from:" + email.to_s
},
headers: {'Content-Type' => 'application/json'}
)
count = #emails.data.messages.count
Rails.logger.error count
{count: count, last_emails: get_three_emails} if count > 0
end
for reference : https://github.com/google/google-api-ruby-client/issues/135

Not a ruby expert but that looks like a method, can you call () it? I imagine you've gone through steps to setup authentication, etc? the messages.list() function should be able to be called without any parameters generally (well, you may need to specify a userId, which you can just use "me" for to get the authenticated user).

Related

How to speed up sitemap_generator with parallel gem

I am trying to speed up sitemap_generator by adding parallelization via the parallel gem. I have the following code but my groups aren't getting written to the public/sitemaps directory. I am thinking it's due to lambdas getting executed in a different space in parallel. Any feedback would be helpful. Thanks!
#!/usr/bin/env ruby
require 'rubygems'
require 'sitemap_generator'
require 'benchmark'
require 'parallel'
require 'random-word'
SitemapGenerator::Sitemap.default_host = "http://localhost"
a = lambda {
SitemapGenerator::Sitemap.group(:filename => :biz, :sitemaps_path => 'sitemaps/biz/') do
(1..1000).each do |index|
url = "/#{RandomWord.adjs.next}/#{RandomWord.nouns.next}"
add url, :priority => 0.8
end
end
}
b = lambda {
SitemapGenerator::Sitemap.group(:filename => :wedding_ugc, :sitemaps_path => 'sitemaps/ugc') do
(1..1000).each do |index|
url = "/#{RandomWord.adjs.next}/#{RandomWord.nouns.next}"
add url, :priority => 0.8
end
end
}
#working example
# SitemapGenerator::Sitemap.default_host = "http://localhost"
# SitemapGenerator::Sitemap.create(:compress => false) do
# group(:filename => :biz, :sitemaps_path => 'sitemaps/biz/') do
# (1..1000).each do |index|
# url = "/#{RandomWord.adjs.next}/#{RandomWord.nouns.next}"
# add url, :priority => 0.8
# end
# end
# end
puts Time.now
Parallel.each([a,b]){|job| job.call()}
puts Time.now
I got this working and posted the solution on github here
Here is the code incase the url gets broken.
SitemapGenerator::Sitemap.create(:compress => false, :create_index => false) do
group1 = lambda {
group = sitemap.group(:filename => :group1, :sitemaps_path => 'sitemaps/group1') do
Record.find_each do |record|
add '/record/path'
end
end
group.sitemap.write unless group.sitemap.written? #write if not full
}
# group2 like above...
Parallel.each([group1, group2], :in_processes => 8) do |group|
group.call
end
end
#regenerate the index sitemap xml file because I couldn't figure out how to track it with multiple processes
SitemapGenerator::Sitemap.create(:compress => false) do
Dir.chdir(sitemap.public_path.to_s)
xml_files = File.join("**", "sitemaps", "**", "*.xml")
xml_file_paths = Dir.glob(xml_files)
xml_file_paths.each do |file|
add file
end
end

Using Ruby Webrick HTTPAuth with LDAP

The app I am writing has the ability to have a login popup appear and it authenticates against a hard coded username/password constant pair. I would like to authenticate against our central LDAP server. the we dont have a base however we do have a bind_dn string of "cn=USERFOO,ou=it,o=corporate". The variables user/pass are passed in through the basic login box.
I am trying to do this through ActiveLdap however I dont mind using any other library as long as I can validate the credentials through a single sign on against our LDAP server using the HTTPAuth since is written completely in Webrick Ruby. Below is a sample of the function I am calling.
Does anyone have any idea how to do this?
Thanks in advance.
def authenticate_ldap(req,res)
authlabel = "LDAP Authentication"
HTTPAuth.basic_auth(req, res, authlabel) { |user, pass|
ActiveLdap::Base.setup_connection(
:host => 'ldap.internalserver.com',
:port => 389,
:bind_dn => "cn=#{user},ou=it,o=corporate",
:password_block => Proc.new { pass },
)
}
return
end
I figured out a solution. The person who manages our LDAP server provided the incorrect ldap connection string, but even with that it still didn't work.
The solution I discovered that did indeed make a connection with very basic validation is something to this effect for anyone else interested in a very simple ldap authentication popup in pure Ruby.
def authenticate(req,res)
authlabel = 'LDAP Authentication'
HTTPAuth.basic_auth(req, res, authlabel) { |user, pass|
if pass.to_s != ''
ldap = Net::LDAP.new
ldap.host = "ldap.serverfoo.com"
ldap.port = 389
result = ldap.bind_as(
:base => "t=basetreefoo",
:filter => "uid=#{user}",
:password => pass
)
if result
ldap = Net::LDAP.new :host => "ldap.serverfoo.com",
:port => "389",
:auth => {
:method => :simple,
:username => "",
:password => ""
}
group_name = Net::LDAP::Filter.eq("cn", "#{user}")
group_type = Net::LDAP::Filter.eq("groupmembership", "cn=infra,ou=IT,o=Corporate")
filter = group_name & group_type
treebase = "t=basetreefoo"
ldap.search(:base => treebase, :filter => filter) do |entry|
if entry.dn.to_s != ""
puts 'success'
return
end
end
end
end
puts 'fail'
}
end

ActiveMerchant's support for determining the account status (verified/unverified) of a PayPal Express Checkout customer/buyer

I am currently working on a Ruby-on-Rails web-application that accepts PayPal payments through PayPal's Express Checkout and ActiveMerchant. I have done several research on ActiveMerchant's support for determining if a customer/buyer has paid using either a verified or unverified PayPal account but I got no luck on finding a helpful guide.
I find it also that ActiveMerchant is currently not well-documented so it's not that helpful at all.
Below are the relevant codes that my project is currently using. On PaymentsController#purchase, I temporarily used the #params['protection_eligibility'] and the #params['protection_eligibility_type'] methods of the ActiveMerchant::Billing::PaypalExpressResponse object that is returned by the EXPRESS_GATEWAY.purchase method call, to assess if a PayPal customer/buyer has a verified/unverified PayPal account. Later I found out that this is not a reliable basis for knowing the customer's account status.
I hope somebody can give me a wisdom on knowing whether a PayPal customer/buyer has a verified/unverified account using Ruby-on-Rails' ActiveMerchant or using other alternatives on Rails.
# config/environments/development.rb
config.after_initialize do
ActiveMerchant::Billing::Base.mode = :test
paypal_options = {
# credentials removed for this StackOverflow question
:login => "",
:password => "",
:signature => ""
}
::EXPRESS_GATEWAY = ActiveMerchant::Billing::PaypalExpressGateway.new(paypal_options)
end
# app/models/payment.rb
class Payment < ActiveRecord::Base
# ...
PAYPAL_CREDIT_TO_PRICE = {
# prices in cents(US)
1 => 75_00,
4 => 200_00,
12 => 550_00
}
STATUSES = ["pending", "complete", "failed"]
TYPES = ["paypal", "paypal-verified", "paypal-unverified", "wiretransfer", "creditcard"]
# ...
end
# app/controllers/payments_controller.rb
class PaymentsController < ApplicationController
# ...
def checkout
session[:credits_qty] = params[:credit_qty].to_i
total_as_cents = Payment::PAYPAL_CREDIT_TO_PRICE[session[:credits_qty]]
setup_purchase_params = {
:allow_guest_checkout => true,
:ip => request.remote_ip,
:return_url => url_for(:action => 'purchase', :only_path => false),
:cancel_return_url => url_for(:controller => 'payments', :action => 'new', :only_path => false),
:items => [{
:name => pluralize(session[:credits_qty], "Credit"),
:number => 1,
:quantity => 1,
:amount => Payment::PAYPAL_CREDIT_TO_PRICE[session[:credits_qty]]
}]
}
setup_response = EXPRESS_GATEWAY.setup_purchase(total_as_cents, setup_purchase_params)
redirect_to EXPRESS_GATEWAY.redirect_url_for(setup_response.token)
end
def purchase
if params[:token].nil? or params[:PayerID].nil?
redirect_to new_payment_url, :notice => I18n.t('flash.payment.paypal.error')
return
end
total_as_cents = Payment::PAYPAL_CREDIT_TO_PRICE[session[:credits_qty]]
purchase_params = {
:ip => request.remote_ip,
:token => params[:token],
:payer_id => params[:PayerID],
:items => [{
:name => pluralize(session[:credits_qty], "Credit"),
:number => 1,
:quantity => 1,
:amount => Payment::PAYPAL_CREDIT_TO_PRICE[session[:credits_qty]]
}]
}
purchase = EXPRESS_GATEWAY.purchase total_as_cents, purchase_params
if purchase.success?
payment = current_user.payments.new
payment.paypal_params = params
payment.credits = session[:credits_qty]
payment.amount = Payment::PAYPAL_CREDIT_TO_PRICE[session[:credits_qty]]
payment.currency = "USD"
payment.status = "complete"
if(purchase.params["receipt_id"] && (purchase.params["success_page_redirect_requested"] == "true"))
payment.payment_type = "creditcard"
else
if purchase.params['protection_eligibility'] == 'Eligible' && purchase.params['protection_eligibility_type'] == 'ItemNotReceivedEligible,UnauthorizedPaymentEligible'
payment.payment_type = 'paypal-verified'
else
payment.payment_type = 'paypal-unverified'
end
end
payment.ip_address = request.remote_ip.to_s
payment.save!
SiteMailer.paypal_payment(payment).deliver
SiteMailer.notice_payment(payment).deliver
notice = I18n.t('flash.payment.status.thanks')
redirect_to profile_url, :notice => notice
else
notice = I18n.t('flash.payment.status.failed', :message => purchase.message)
redirect_to new_payment_url, :notice => notice
end
end
# ...
end
I used PayPal's paypal-sdk-merchant gem to do the job ActiveMerchant wasn't able to help me with (getting the status of a payer's account: verified/unverified PayPal account. I followed the installation of paypal-sdk-merchant on https://github.com/paypal/merchant-sdk-ruby
gem 'paypal-sdk-merchant'
bundle install
rails generate paypal:sdk:install
Then I set-up their samples https://github.com/paypal/merchant-sdk-ruby#samples. After setting-up the samples, go to /samples of your Rails app and you will find a lot of code generator for what ever function you need from PayPal's API. Don't forget to configure your config/paypal.yml. I configured the username, password and signature (can be obtained from your PayPal sandbox specifically your test seller account) and removed the app_id in my case.
I obtained the following code for getting a PayPal payer's account status (verified/unverified) using PayPal's samples (/samples) and placed it on a class method of a model in my app:
def self.get_paypal_payer_status(transaction_id)
require 'paypal-sdk-merchant'
api = PayPal::SDK::Merchant::API.new
get_transaction_details = api.build_get_transaction_details({
:Version => "94.0",
:TransactionID => transaction_id
})
get_transaction_details_response = api.get_transaction_details(get_transaction_details)
get_transaction_details_response.payment_transaction_details.payer_info.payer_status
end
I'm not familiar with ActiveMerchant so I can't tell you specific to that, but with any Express Checkout implementation you can use GetExpressCheckoutDetails to obtain the payers information which will include a PAYERSTATUS parameter with a value of "verified" or "unverified".
It's an optional call, but I would assume ActiveMerchant is probably including it so you just need to track that down and pull that parameter accordingly.
Alternatively, you can use Instant Payment Notification (IPN) to receive transaction information and you will get back a payer_status parameter here as well.

Pre-filling first and last name in Paypal setExpressCheckout using ActiveMerchant

I'm trying to get Paypal SetExpressCheckout operation to add first and last name for billing. I'm using ActiveMerchant. I'm seeing the address field pre-populated (street, state, city,zip-code) but nothing else.
#### gateway ######
gateway = ActiveMerchant::Billing::PaypalExpressGateway.new(:login => 'login',:password => 'pass',:signature => 'sig')
### options ######
#options = Hash.new
#options.merge!(:ip => '127.0.0.1')
#options.merge!(:return_url => '127.0.0.1')
#options.merge!(:return_url => 'http://www.google.com')
#options.merge!(:cancel_return_url => 'http://www.google.com')
#options.merge!(:name => 'name')
#options.merge!(:description => 'description')
#options.merge!(:max_amount => 5000)
#options.merge!(:solution_type => 'Sole')
#options.merge!(:no_shipping => 1)
#options.merge!(:address_override => 1)
### build address
#address = Hash.new
#address.merge!(:name => "Joe User")
#address.merge!(:address1 => "111 ABCD EFG")
#address.merge!(:address2 => nil)
#address.merge!(:city => "Fremont")
#address.merge!(:state => "CA")
#address.merge!(:country => "US")
#address.merge!(:phone => "408-111-2222")
#options.merge!(:address => #address)
setup_response = gateway.setup_purchase(5000, #options)
redirect_to gateway.redirect_url_for(setup_response.token)
On the resultant page, I'm not seeing the name pre-filled for billing.
What am I doing wrong?
Thanks
I had the same issue as you did. After some research I came to the conclusion that this is a bug in ActiveMerchant. Please see the issue that I filed. It includes an explanation of how I patched my code to make phone number and names work:
https://github.com/Shopify/active_merchant/issues/161

Rails LDAP login using net/ldap

I am trying to get LDAP authentication to work under Rails.
I have chosen net/ldap since it's a native Ruby LDAP library.
I have tried all possible stuff, specially examples from http://net-ldap.rubyforge.org/classes/Net/LDAP.html but still unable to get it work.
Any ideas?
The best solution I managed to reach is a Model with the following:
require 'net/ldap'
class User < ActiveRecord::Base
def after_initialize
#config = YAML.load(ERB.new(File.read("#{Rails.root}/config/ldap.yml")).result)[Rails.env]
end
def ldap_auth(user, pass)
ldap = initialize_ldap_con
result = ldap.bind_as(
:base => #config['base_dn'],
:filter => "(#{#config['attributes']['id']}=#{user})",
:password => pass
)
if result
# fetch user DN
get_user_dn user
sync_ldap_with_db user
end
nil
end
private
def initialize_ldap_con
options = { :host => #config['host'],
:port => #config['port'],
:encryption => (#config['tls'] ? :simple_tls : nil),
:auth => {
:method => :simple,
:username => #config['ldap_user'],
:password => #config['ldap_password']
}
}
Net::LDAP.new options
end
def get_user_dn(user)
ldap = initialize_ldap_con
login_filter = Net::LDAP::Filter.eq #config['attributes']['id'], "#{user}"
object_filter = Net::LDAP::Filter.eq "objectClass", "*"
ldap.search :base => #config['base_dn'],
:filter => object_filter & login_filter,
:attributes => ['dn', #config['attributes']['first_name'], #config['attributes']['last_name'], #config['attributes']['mail']] do |entry|
logger.debug "DN: #{entry.dn}"
entry.each do |attr, values|
values.each do |value|
logger.debug "#{attr} = #{value}"
end
end
end
end
end
I work on a Devise plugin for Rails 3 that uses LDAP for authentication, you can look at the source to get some ideas, it currently uses net-ldap 0.1.1:
http://github.com/cschiewek/devise_ldap_authenticatable
The actual connecting and authenticating to the LDAP sever is done at:
http://github.com/cschiewek/devise_ldap_authenticatable/blob/master/lib/devise_ldap_authenticatable/ldap_adapter.rb
Lastly, you can look at the sample LDAP server config and Rails 3 app I use to run the tests against:
App: http://github.com/cschiewek/devise_ldap_authenticatable/tree/master/test/rails_app/
Server: http://github.com/cschiewek/devise_ldap_authenticatable/tree/master/test/ldap/

Resources