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

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



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

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

.cleanse_source(source) ⇒ Object



95
96
97
98
99
100
101
102
103
104
# File 'app/models/mail_manager/mailing.rb', line 95

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



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

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)


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

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

#can_edit?Boolean

Returns:

  • (Boolean)


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

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

#can_run?Boolean

Returns:

  • (Boolean)


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

def can_run?
   # processing is allowed for failed job reset and is OK since we lock around whole job
   ['scheduled','processing'].include?(status.to_s)
end

#can_schedule?Boolean

Returns:

  • (Boolean)


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

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

#cancelObject



242
243
244
245
246
# File 'app/models/mail_manager/mailing.rb', line 242

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

#deleteObject



173
174
175
176
177
178
# File 'app/models/mail_manager/mailing.rb', line 173

def delete
  transaction do
    super
    job.try(:destroy)
  end
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
85
86
87
# 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.limit(MailManager.deliveries_per_run).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
        # should use the cached mailing parts as mailing object for message should be the same as its caller
        message.deliver(raw_parts)
     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
    if messages.pending.count == 0
      change_status(:completed) 
    else
      self.delay(run_at: [scheduled_at,Time.now.utc].max).deliver
    end
  end
end

#initialize_messagesObject

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



156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'app/models/mail_manager/mailing.rb', line 156

def initialize_messages
  emails_hash = MailManager::Message.email_address_hash_for_mailing_id(self.id)
  # NOTE: the following over-protective line has been removed as per Ken's request 2017-12-21
  # emails_hash.merge!(MailManager::Subscription.unsubscribed_emails_hash)
  ids = self.mailing_lists.select('id').map(&:id)
  active_subscriptions_hash = MailManager::MailingList.
    active_email_addresses_contact_ids_subscription_ids_for_mailing_list_ids(ids)
  active_subscriptions_hash.each_pair do | email, data |
    next if emails_hash[email.to_s.strip.downcase].present?
    message = MailManager::Message.create({
      :subscription_id => data[:subscription_id],
      :contact_id => data[:contact_id],
      :mailing_id => self.id
    })
  end 
end

#jobObject



234
235
236
# File 'app/models/mail_manager/mailing.rb', line 234

def job
  mailing_jobs.first
end

#mailableObject



89
90
91
92
93
# File 'app/models/mail_manager/mailing.rb', line 89

def mailable
  return @mailable if @mailable
  return (@mailable=nil) if mailable_type.nil? or mailable_id.nil?
  @mailable = mailable_type.constantize.find(mailable_id)
end

#mailable=(value) ⇒ Object



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

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

#mailable_class_and_id=(value) ⇒ Object



143
144
145
146
147
148
# File 'app/models/mail_manager/mailing.rb', line 143

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



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

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

#mailing_jobsObject



238
239
240
# File 'app/models/mail_manager/mailing.rb', line 238

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

#mailing_list_ids=(mailing_list_ids) ⇒ Object



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

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 = {}, cached_parts = nil) ⇒ Object



127
128
129
130
131
132
133
134
# File 'app/models/mail_manager/mailing.rb', line 127

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

#pending?Boolean

Returns:

  • (Boolean)


248
249
250
# File 'app/models/mail_manager/mailing.rb', line 248

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

#raw_partsObject



123
124
125
# File 'app/models/mail_manager/mailing.rb', line 123

def raw_parts
  @raw_parts ||= mailable.mailable_parts
end

#scheduleObject



224
225
226
227
228
# File 'app/models/mail_manager/mailing.rb', line 224

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

#scheduled?Boolean

Returns:

  • (Boolean)


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

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



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

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