Class: MailManager::Mailing

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
Deleteable, 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=

Methods included from Deleteable

#delete, included, #is_deleted?, #undelete

Instance Attribute Details

#bounce_countObject

Returns the value of attribute bounce_count.



31
32
33
# File 'app/models/mail_manager/mailing.rb', line 31

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



180
181
182
# File 'app/models/mail_manager/mailing.rb', line 180

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

.cleanse_source(source) ⇒ Object



92
93
94
95
96
97
98
99
100
101
# File 'app/models/mail_manager/mailing.rb', line 92

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



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'app/models/mail_manager/mailing.rb', line 103

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

Instance Method Details

#can_cancel?Boolean

Returns:

  • (Boolean)


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

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

#can_edit?Boolean

Returns:

  • (Boolean)


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

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

#can_run?Boolean

Returns:

  • (Boolean)


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

def can_run?
   ['scheduled','processing'].include?(status.to_s)
end

#can_schedule?Boolean

Returns:

  • (Boolean)


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

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

#cancelObject



240
241
242
243
244
# File 'app/models/mail_manager/mailing.rb', line 240

def cancel
  raise "Unable to cancel" unless can_cancel?
  change_status('pending')
  mailing_jobs.delete_all
end

#deliverObject



53
54
55
56
57
58
59
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
# File 'app/models/mail_manager/mailing.rb', line 53

def deliver
  Rails.logger.info "Starting to Process Mailing '#{subject}' ID:#{id}"
  Lock.with_lock("mail_mgr_mailing_send[#{id}]") do |lock|
    unless can_run?
      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.deliver
     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



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'app/models/mail_manager/mailing.rb', line 151

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

#jobObject



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

def job
  mailing_jobs.first
end

#mailableObject



86
87
88
89
90
# File 'app/models/mail_manager/mailing.rb', line 86

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



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

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



138
139
140
141
142
143
# File 'app/models/mail_manager/mailing.rb', line 138

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



196
197
198
199
# File 'app/models/mail_manager/mailing.rb', line 196

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

#mailing_jobsObject



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

def mailing_jobs
  Delayed::Job.where("handler like ?","%MailManager::Mailing% id: #{self.id}\n%")
end

#mailing_list_ids=(mailing_list_ids) ⇒ Object



201
202
203
204
# File 'app/models/mail_manager/mailing.rb', line 201

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



124
125
126
127
128
129
130
# File 'app/models/mail_manager/mailing.rb', line 124

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

#pending?Boolean

Returns:

  • (Boolean)


246
247
248
# File 'app/models/mail_manager/mailing.rb', line 246

def pending?
  status.to_s.eql?('pending')
end

#raw_partsObject



120
121
122
# File 'app/models/mail_manager/mailing.rb', line 120

def raw_parts
  @raw_parts ||= mailable.mailable_parts
end

#scheduleObject



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

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

#scheduled?Boolean

Returns:

  • (Boolean)


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

def scheduled?
  status.to_s.eql?('scheduled')
end

#send_one_off_message(contact) ⇒ Object



45
46
47
48
49
50
51
# File 'app/models/mail_manager/mailing.rb', line 45

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



185
186
187
188
189
190
191
192
193
# File 'app/models/mail_manager/mailing.rb', line 185

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