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



168
169
170
# File 'app/models/mail_manager/mailing.rb', line 168

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)


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

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

#can_edit?Boolean

Returns:

  • (Boolean)


194
195
196
# File 'app/models/mail_manager/mailing.rb', line 194

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

#can_run?Boolean

Returns:

  • (Boolean)


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

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

#can_schedule?Boolean

Returns:

  • (Boolean)


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

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

#cancelObject



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

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
# File 'app/models/mail_manager/mailing.rb', line 151

def initialize_messages
  emails_hash = MailManager::Message.email_address_hash_for_mailing_id(self.id)
  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



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

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



184
185
186
187
# File 'app/models/mail_manager/mailing.rb', line 184

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

#mailing_jobsObject



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

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

#mailing_list_ids=(mailing_list_ids) ⇒ Object



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

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)


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

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



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

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

#scheduled?Boolean

Returns:

  • (Boolean)


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

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



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

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