Class: WcoEmail::MessageStub

Inherits:
Object
  • Object
show all
Includes:
Mongoid::Document, Mongoid::Paranoia, Mongoid::Timestamps
Defined in:
app/models/wco_email/message_stub.rb

Overview

Only object_key, no validations. 2023-12-28 vp Continue. 2024-01-05 LFG

Constant Summary collapse

PAGE_PARAM_NAME =
'stubs_page'
STATUS_PENDING =
'status_pending'
STATUS_PROCESSED =
'status_processed'
STATUS_FAILED =
'status_failed'
STATUSES =
[ STATUS_PENDING, STATUS_PROCESSED, STATUS_FAILED ]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.mbox2stubs(mbox_path, tagname:, skip:) ⇒ Object



284
285
286
287
# File 'app/models/wco_email/message_stub.rb', line 284

def self.mbox2stubs mbox_path, tagname:, skip:
  skip ||= 0
  self.new.mbox2stubs mbox_path, tagname: tagname, skip: skip
end

Instance Method Details

#configObject

skip_notification process_images



43
44
45
# File 'app/models/wco_email/message_stub.rb', line 43

field :config, type: Object, default: "{}\n"

#do_processObject



47
48
49
50
51
52
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'app/models/wco_email/message_stub.rb', line 47

def do_process
  if Rails.env.production?
    @client ||= Aws::S3::Client.new({
      region:            ::S3_CREDENTIALS[:region_ses],
      access_key_id:     ::S3_CREDENTIALS[:access_key_id_ses],
      secret_access_key: ::S3_CREDENTIALS[:secret_access_key_ses],
    })
  else
    @client ||= Aws::S3::Client.new(::SES_S3_CREDENTIALS)
  end

  stub = self

  raw      = @client.get_object( bucket: stub.bucket, key: stub.object_key ).body.read
  raw      = raw.encode('utf-8', invalid: :replace, undef: :replace, replace: '_' )
  the_mail = Mail.new( raw )
  # puts! the_mail, 'the_mail'

  message_id         = the_mail.header['message-id']&.decoded
  message_id       ||= "#{the_mail.date&.iso8601}::#{the_mail.from}"
  # puts! message_id, 'message_id'

  in_reply_to_id     = the_mail.header['in-reply-to']&.to_s
  # puts! in_reply_to_id, 'in_reply_to_id'

  the_mail.to        = [ 'NO-RECIPIENT' ] if !the_mail.to
  subject            = WcoEmail::Message.strip_emoji( the_mail.subject || '(wco-no-subject)' )
  # puts! subject, 'subject'

  ## Conversation
  if in_reply_to_id
    in_reply_to_msg = WcoEmail::Message.where({ message_id: in_reply_to_id }).first
    if !in_reply_to_msg
      conv = WcoEmail::Conversation.find_or_create_by({
        subject: subject,
      })
      in_reply_to_msg = WcoEmail::Message.find_or_create_by({
        message_id: in_reply_to_id,
        conversation: conv,
      })
    end
    conv = in_reply_to_msg.conversation
  else
    conv = WcoEmail::Conversation.unscoped.find_or_create_by({
      subject: subject,
    })
    conv.deleted_at = nil
  end


  ## Leadset, Lead
  from      = the_mail.from ? the_mail.from[0] : "[email protected]"
  lead      = Wco::Lead.find_or_create_by_email( from )
  conv.leads.push lead
  leadset   = Wco::Leadset.from_email from
  conv.leadsets.push leadset
  # conv.save

  message   = WcoEmail::Message.unscoped.where( message_id: message_id ).first
  if message
    message.message_id = "#{Time.now.strftime('%Y%m%d')}-trash-#{message.message_id}"
    message.object_key = "#{Time.now.strftime('%Y%m%d')}-trash-#{message.object_key}"
    message.save( validate: false )
    message.delete
  end

  @message = WcoEmail::Message.create!({
    stub:         stub,
    conversation: conv,
    lead:         lead,

    message_id:     message_id,
    in_reply_to_id: in_reply_to_id,
    object_key:     stub.object_key,

    subject: subject,
    date:    the_mail.date,

    from:  from,
    froms: the_mail.from,

    to:  the_mail.to ? the_mail.to[0] : nil,
    tos: the_mail.to,

    cc:  the_mail.cc ? the_mail.cc[0] : nil,
    ccs: the_mail.cc,
  })
  # puts! @message, '@message'

  ## Parts
  the_mail.parts.each do |part|
    @message.churn_subpart( part )
  end
  @message.save

  if the_mail.parts.length == 0
    body = the_mail.body.decoded.encode('UTF-8', invalid: :replace, undef: :replace, replace: '?')
    if the_mail.content_type&.include?('text/html')
      @message.part_html = body
    elsif the_mail.content_type&.include?('text/plain')
      @message.part_html = "<pre>#{body}</pre>"
    elsif the_mail.content_type.blank?
      @message.part_html = "<pre>#{body}</pre>"
    else
      @message.logs.push "mail body of unknown type: #{the_mail.content_type}"
      @message.part_html = "<pre>#{body}</pre>"
    end
    @message.save
  end

  ## Attachments, which are parts (omit!)
  # the_mail.attachments.each do |att|
  #   @message.save_attachment( att )
  # end

  if !@message.save
    puts! @message.errors.full_messages.join(", "), "Could not save @message"
  end

  the_mail.cc&.each do |cc|
    Wco::Lead.find_or_create_by_email( cc )
  end

  conv.update_attributes({
    status:      WcoEmail::Conversation::STATUS_UNREAD,
    latest_at:   the_mail.date || Time.now.to_datetime,
    from_emails: ( conv.from_emails + the_mail.from ).uniq,
    preview:     @message.preview_str,
  })

  ##
  ## Tags
  ##
  conv.tags.push Wco::Tag.inbox
  conv.tags.push stub.tags
  conv.save


  ## Actions & Filters
  email_filters = WcoEmail::EmailFilter.all
  email_filters.each do |filter|
    reason = nil
    if filter.from_regex.present? && @message.from.downcase.match( filter.from_regex )
      reason = 'from_regex'
    end
    if filter.from_exact.present? && @message.from.downcase.include?( filter.from_exact.downcase )
      reason = 'from_exact'
    end
    if filter.body_exact.present? && @message.part_html&.include?( filter.body_exact )
      reason = 'body_exact'
    end
    if filter.subject_regex.present? && @message.subject.match( filter.subject_regex )
      reason = 'subject_regex'
    end
    if filter.subject_exact.present? && @message.subject.downcase.include?( filter.subject_exact.downcase )
      reason = 'subject_exact'
    end

    filter.conditions.each do |scond|
      reason ||= scond.apply(leadset: leadset, message: @message )
    end

    if reason
      puts! "Applying filter #{filter} to conv #{@message.conversation} for matching #{reason}" if DEBUG

      ## skip
      skip_reason = nil
      if filter.skip_to_exact.present? && @message.to&.downcase.include?( filter.skip_to_exact.downcase )
        skip_reason = 'skip_to_exact'
      end
      if filter.skip_from_regex.present? && @message.from.downcase.match( filter.skip_from_regex )
        skip_reason = 'skip_from_regex'
      end

      filter.skip_conditions.each do |scond|
        skip_reason ||= scond.apply(leadset: leadset, message: @message )
      end

      if skip_reason
        puts! "NOT Applying filter #{filter} to conv #{@message.conversation} for matching #{skip_reason}" if DEBUG
      else
        @message.apply_filter( filter )
      end
    end
  end

  stub.update_attributes({ status: WcoEmail::MessageStub::STATUS_PROCESSED })

  ## Notification
  config = JSON.parse(stub.config)
  if config['skip_notification']
    ;
  else
    ## 2024-07-30 I'm no longer sending these to google.
    ## 2024-11-03 restarted sending.
    ## 2025-01-23 no longer sending to google.
    conv = WcoEmail::Conversation.find( conv.id )
    if conv.tags.include? Wco::Tag.inbox
      if defined?(::NOTIFY_TO_GOOGLE) && ::NOTIFY_TO_GOOGLE
        out = WcoEmail::ApplicationMailer.forwarder_notify( @message.id.to_s )
        Rails.env.production? ? out.deliver_later : out.deliver_now
      end
    end
  end

  puts 'ok'
end

#mbox2stubs(mbox_path, tagname:, skip:) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
# File 'app/models/wco_email/message_stub.rb', line 288

def mbox2stubs mbox_path, tagname:, skip:
  puts 'Starting...'
  skip ||= 0

  @count = 1
  @client ||= Aws::S3::Client.new({
    region:            ::S3_CREDENTIALS[:region_ses],
    access_key_id:     ::S3_CREDENTIALS[:access_key_id_ses],
    secret_access_key: ::S3_CREDENTIALS[:secret_access_key_ses],
  })
  @tag = Wco::Tag.find_or_create_by({ slug: tagname })

  message    = nil
  File.readlines(mbox_path, encoding: "ISO8859-1" ).each do |line|
    if (line.match(/\AFrom /))

      if message
        if skip < @count
          save_mbox_to_m3 message
          print "#{@count}."
        else
          print "s-#{@count}."
        end
        @count += 1
      end
      message = ''

    else
      message << line.sub(/^\>From/, 'From')
    end
  end

  if message
    if skip < @count
      save_mbox_to_m3 message
      print "#{@count}."
    else
      print "s-#{@count}."
    end
    @count += 1
  end
  message = ''
end

#save_mbox_to_m3(message) ⇒ Object

This only saves a local message from mbox to s3.



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'app/models/wco_email/message_stub.rb', line 256

def save_mbox_to_m3 message
  the_mail = Mail.new(message)
  key      = the_mail.message_id || "no-key-#{Time.now.to_i}.#{rand(1000)}"

  @stub = WcoEmail::MessageStub.create({
    bucket:      ::S3_CREDENTIALS[:bucket_ses],
    object_key:  key,
    status:      WcoEmail::MessageStub::STATUS_PENDING,
    tags:        [ @tag ],
  })
  if @stub.persisted?
    @client.put_object({
      body: message,
      bucket: ::S3_CREDENTIALS[:bucket_ses],
      key: key,
    })
  else
    msg = @stub.errors.full_messages.join(", ")
    puts! msg
    Wco::Log.create({
      message:    "Stub duplicate object_key: #{key}",
      class_name: 'WcoEmail::MessageStub',
      raw_json:   @stub.attributes.to_json,
      tags:       [ @tag ],
    })
  end
end