jam-cloud/ruby/lib/jam_ruby/models/email_error.rb

85 lines
2.6 KiB
Ruby

module JamRuby
class EmailError < ActiveRecord::Base
self.table_name = "email_errors"
belongs_to :email_batch, :class_name => 'JamRuby::EmailBatch'
belongs_to :user, :class_name => 'JamRuby::User'
default_scope :order => 'email_date DESC'
ERR_BOUNCE = :bounce
ERR_INVALID = :invalid
SENDGRID_UNAME = 'jamkazam'
SENDGRID_PASSWD = 'jamjamblueberryjam'
def self.sendgrid_url(resource, action='get', params='')
"https://api.sendgrid.com/api/#{resource}.#{action}.json?api_user=#{EmailError::SENDGRID_UNAME}&api_key=#{EmailError::SENDGRID_PASSWD}&date=1&#{params}"
end
def self.bounce_url(batch)
uu = sendgrid_url('bounces')
uu += "&start_date=#{batch.started_at.strftime('%Y-%m-%d')}&end_date=#{batch.completed_at.strftime('%Y-%m-%d')}" if batch.batched?
uu
end
def self.bounce_errors(batch)
uu = self.bounce_url(batch)
response = RestClient.get(uu)
if 200 == response.code
return JSON.parse(response.body).collect do |jj|
ee = EmailError.new
ee.error_type = 'bounces'
ee.email_batch_id = batch.id
ee.email_address = jj['email']
ee.user_id = User.where(:email => ee.email_address).pluck(:id).first
ee.status = jj['status']
ee.email_date = jj['created']
ee.reason = jj['reason']
ee.save!
RestClient.delete(self.sendgrid_url('bounces', 'delete', "email=#{ee.email_address}"))
ee
end
end
end
def self.invalid_url(batch)
uu = sendgrid_url('invalidemails')
uu += "&start_date=#{batch.started_at.strftime('%Y-%m-%d')}&end_date=#{batch.completed_at.strftime('%Y-%m-%d')}" if batch.batched?
uu
end
def self.invalid_errors(batch)
uu = self.invalid_url(batch)
response = RestClient.get(uu)
if 200 == response.code
return JSON.parse(response.body).collect do |jj|
ee = EmailError.new
ee.error_type = 'invalidemails'
ee.email_batch_id = batch.id
ee.email_address = jj['email']
ee.user_id = User.where(:email => ee.email_address).pluck(:id).first
ee.email_date = jj['created']
ee.reason = jj['reason']
ee.save!
uu =
RestClient.delete(self.sendgrid_url('invalidemails', 'delete', "email=#{ee.email_address}"))
ee
end
end
end
def self.collect_errors(batch)
if batch.batched?
EmailError.bounce_errors(batch)
EmailError.invalid_errors(batch)
end
end
def batch_subject
self.email_batch.try(:subject)
end
end
end