Class: MailManager::Mailing

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
StatusHistory
Defined in:
app/models/mail_manager/mailing.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from StatusHistory

#change_status, included, #set_default_status, #status, #status=, #status_changed_at=

Instance Attribute Details

#bounce_countObject

Returns the value of attribute bounce_count.



29
30
31
# File 'app/models/mail_manager/mailing.rb', line 29

def bounce_count
  @bounce_count
end

Class Method Details

.clean_email_address(email_address) ⇒ Object

clean up an email address for sending FIXME - maybe do a bit more



189
190
191
# File 'app/models/mail_manager/mailing.rb', line 189

def self.clean_email_address(email_address)
  email_address.downcase.strip
end

.cleanse_source(source) ⇒ Object



101
102
103
104
105
106
107
108
109
110
# File 'app/models/mail_manager/mailing.rb', line 101

def self.cleanse_source(source)
  require 'iconv' unless String.method_defined?(:encode)
  if String.method_defined?(:encode)
    source.encode!('UTF-16', 'UTF-8', :invalid => :replace, :replace => '')
    source.encode!('UTF-8', 'UTF-16')
  else
    ic = Iconv.new('UTF-8', 'UTF-8//IGNORE')
    source = ic.iconv(source)
  end
end

.substitute_values(source, substitutions) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'app/models/mail_manager/mailing.rb', line 112

def self.substitute_values(source,substitutions)
  substitutions.each_pair do |substitution,value| 
    if value.blank?
      source.gsub!(/##{substitution}#([^#]*)#/,'\1') rescue source = self.cleanse_source(source).gsub(/##{substitution}#([^#]*)#/,'\1')
    else
      source.gsub!(/##{substitution}#[^#]*#/,value.to_s) rescue source = self.cleanse_source(source).gsub(/##{substitution}#[^#]*#/,value.to_s)
    end
  end
  if defined? MailManager::ContactableRegistry.respond_to?(:valid_contactable_substitutions)
    MailManager::ContactableRegistry.valid_contactable_substitutions.
      reject{|key| substitutions.keys.include?(key)}.each do |substitution|
      source.gsub!(/##{substitution}#([^#]*)#/,'\1') rescue source = self.cleanse_source(source).gsub(/##{substitution}#([^#]*)#/,'\1')
    end
  end
  source
end

.with_bounces(bounce_status = nil) ⇒ Object



37
38
39
40
41
42
43
44
# File 'app/models/mail_manager/mailing.rb', line 37

def self.with_bounces(bounce_status=nil)
  bounce_status_condition = bounce_status.present? ? ActiveRecord::Base.send(:sanitize_sql_array,[" WHERE status=?", bounce_status]) : ''
  bounce_query = "SELECT mailing_id, COUNT(id) AS count from #{MailManager.table_prefix}bounces #{bounce_status_condition} group by mailing_id"
  bounce_data = Bounce.connection.execute(bounce_query).inject({}){|hash,(mailing_id,count)| hash.merge(mailing_id => count)}
  mailings = scoped
  mailings = mailings.where("id in (#{bounce_data.keys.select(&:present?).join(',')})") if bounce_data.keys.select(&:present?).present?
  mailings.order("created_at desc").map{|mailing| mailing.bounce_count = bounce_data[mailing.id]; mailing}
end

Instance Method Details

#can_cancel?Boolean

Returns:

  • (Boolean)


223
224
225
# File 'app/models/mail_manager/mailing.rb', line 223

def can_cancel?
   ['pending','scheduled','processing','paused','resumed'].include?(status.to_s)
end

#can_edit?Boolean

Returns:

  • (Boolean)


219
220
221
# File 'app/models/mail_manager/mailing.rb', line 219

def can_edit?
  ['pending','scheduled','paused'].include?(status.to_s)
end

#can_pause?Boolean

Returns:

  • (Boolean)


215
216
217
# File 'app/models/mail_manager/mailing.rb', line 215

def can_pause?
  ['processing'].include?(status.to_s)
end

#can_resume?Boolean

Returns:

  • (Boolean)


227
228
229
# File 'app/models/mail_manager/mailing.rb', line 227

def can_resume?
  ['paused'].include?(status.to_s)
end

#can_schedule?Boolean

Returns:

  • (Boolean)


231
232
233
# File 'app/models/mail_manager/mailing.rb', line 231

def can_schedule?
  ['pending'].include?(status.to_s)
end

#cancelObject



241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'app/models/mail_manager/mailing.rb', line 241

def cancel
  raise "Unable to cancel" unless can_cancel?
  change_status('pending')
  # Delayed::Job.active.find(:all, :conditions => ["handler like ?","MailMgr::Mailing"])

  #Changing this to return only the jobs that match the id so I don't have to parse with YAML ... seems logical
  mailing_jobs = Delayed::Job.find(:all, :conditions => ["handler like ?","%MailMgr::Mailing%"] || ["handler like ?", "%id: {job_mailing_id.to_i}\n%"])
  #mailing_jobs = Delayed::Job.active.find(:all, :conditions => ["handler like ?","%MailMgr::Mailing%"])
  mailing_jobs.each do |job|
    #job_mailing_id = YAML::load(job.handler).object.split(':').last
    #logger.debug "Job mailing id: #{job_mailing_id} - This mailing id: #{self.id} - do they match: #{job_mailing_id.to_i == self.id.to_i}"
    job.destroy #if job_mailing_id.to_i == self.id.to_i
  end
end

#deliverObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'app/models/mail_manager/mailing.rb', line 60

def deliver
  Rails.logger.info "Starting to Process Mailing '#{subject}' ID:#{id}"
  Lock.with_lock("mail_mgr_mailing_send[#{id}]") do |lock|
    unless status.to_s.eql?('scheduled')
      raise Exception.new("Mailing was not scheduled when job tried to run!")
    end
    unless scheduled_at <= Time.now
      Rails.logger.info "Mailing is not scheduled to run until #{scheduled_at} rescheduling job!"
      self.delay(run_at: scheduled_at).deliver
      return true
    end     
    change_status(:processing)
    initialize_messages
    messages.pending.each do |message|
      if reload.status.to_s != 'processing'
        Rails.logger.warn "Mailing #{id} is no longer in processing status it was changed to #{status} while running"
        return false
      end
     begin
        # use the cached mailing parts, set messages mailing to self
        message.mailing=self
       message.change_status(:processing)
        message.deliver
       message.change_status(:sent)
     rescue => e
       message.result = "Error: #{e.message} - #{e.backtrace.join("\n")}"
       message.change_status(:failed)
     end
      Rails.logger.debug "Sleeping #{MailManager.sleep_time_between_messages} before next message"
      sleep MailManager.sleep_time_between_messages
    end
    change_status(:completed) if status.to_s.eql?('processing')
  end
end

#initialize_messagesObject

creates all of the Messages that will be sent for this mailing



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'app/models/mail_manager/mailing.rb', line 160

def initialize_messages
  unless messages.length > 0
    Rails.logger.info "Building mailing messages for mailing(#{id})"
    transaction do 
      emails_hash = messages.select{|m| m.type.eql?('MailManager::Message')}.inject(Hash.new){|emails_hash,message| emails_hash.merge(Mailing.clean_email_address(message.email_address)=>1)}
      mailing_lists.each do |mailing_list|
        mailing_list.subscriptions.active.each do |subscription|
          contact = subscription.contact
          next if contact.nil? or contact.deleted?
          email_address = Mailing.clean_email_address(contact.email_address)
          if emails_hash.has_key?(email_address)
            Rails.logger.info "Skipping duplicate address: #{email_address}"
          else
            Rails.logger.info "Adding #{email_address} to mailing #{subject}"
            emails_hash[email_address] = 1
            message = Message.new
            message.subscription = subscription
            message.contact = contact
            message.mailing = self
            message.save
          end
        end
      end
    end
    save
  end
end

#mailableObject



95
96
97
98
99
# File 'app/models/mail_manager/mailing.rb', line 95

def mailable
  return @mailable if @mailable
  return self unless mailable_type and mailable_id
  @mailable = mailable_type.constantize.find(mailable_id)
end

#mailable=(value) ⇒ Object



141
142
143
144
145
# File 'app/models/mail_manager/mailing.rb', line 141

def mailable=(value)
  return if value.nil?
  self[:mailable_type] = value.class.name
  self[:mailable_id] = value.id
end

#mailable_class_and_id=(value) ⇒ Object



147
148
149
150
151
152
# File 'app/models/mail_manager/mailing.rb', line 147

def mailable_class_and_id=(value)
  return if value.nil?
  parts = value.split(/_/)
  self[:mailable_id] = parts.pop
  self[:mailable_type] = parts.join('_')
end

#mailable_thing_and_idObject

used in select helpers to identify this Mailing’s Mailable



205
206
207
208
# File 'app/models/mail_manager/mailing.rb', line 205

def mailable_thing_and_id
  return '' if mailable.nil?
  return "#{mailable.class.name}_#{mailable.id}"
end

#mailing_list_ids=(mailing_list_ids) ⇒ Object



210
211
212
213
# File 'app/models/mail_manager/mailing.rb', line 210

def mailing_list_ids=(mailing_list_ids)
  mailing_list_ids.delete('')
  self.mailing_lists = mailing_list_ids.collect{|mailing_list_id| MailingList.find_by_id(mailing_list_id)}
end

#parts(substitutions = {}) ⇒ Object



133
134
135
136
137
138
139
# File 'app/models/mail_manager/mailing.rb', line 133

def parts(substitutions={})
  parts = []
  raw_parts.each do |type,source|
    parts << [type, Mailing.substitute_values(source.dup,substitutions)]
  end
  parts
end

#pauseObject



261
262
263
264
# File 'app/models/mail_manager/mailing.rb', line 261

def pause
  raise "Unable to pause" unless can_pause?
  change_status('paused')
end

#raw_partsObject



129
130
131
# File 'app/models/mail_manager/mailing.rb', line 129

def raw_parts
  @raw_parts ||= mailable.mailable_parts
end

#resumeObject



256
257
258
259
# File 'app/models/mail_manager/mailing.rb', line 256

def resume
  raise "Unable to resume" unless can_resume?
  change_status('resumed')
end

#scheduleObject



235
236
237
238
239
# File 'app/models/mail_manager/mailing.rb', line 235

def schedule
  raise "Unable to schedule" unless can_schedule?
  change_status('scheduled')
  delay(run_at: scheduled_at).deliver
end

#send_one_off_message(contact) ⇒ Object



52
53
54
55
56
57
58
# File 'app/models/mail_manager/mailing.rb', line 52

def send_one_off_message(contact)
  message = Message.new
  message.contact_id = contact.id
  message.mailing_id = self.id
  message.change_status(:ready)
  message.delay.deliver
end

#send_test_message(test_email_addresses) ⇒ Object

sends a test message for this mailing to the given address



194
195
196
197
198
199
200
201
202
# File 'app/models/mail_manager/mailing.rb', line 194

def send_test_message(test_email_addresses)
  test_email_addresses.split(/,/).each do |test_email_address|
    puts "Creating test message for #{test_email_address}"
    test_message = TestMessage.new(:test_email_address => test_email_address.strip)
    test_message.mailing_id = self.id
    test_message.save
    test_message.delay.deliver
  end
end