Guest User

Untitled

a guest
Jul 22nd, 2018
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. require File.expand_path('../../config/environment.rb', __FILE__)
  2. require 'net/sftp'
  3. require 'fileutils'
  4.  
  5. module MailParser
  6. def self.sftp_retrieve opts={}
  7. Net::SFTP.start opts[:server], opts[:username], :password => opts[:password] do |sftp|
  8. p 'connected'
  9.  
  10. i = 0
  11.  
  12. sftp.dir.glob opts[:source], "**/*" do |entry|
  13. server_path = "#{opts[:source]}/#{entry.name}"
  14. local_path = "#{opts[:target]}/#{entry.name}"
  15.  
  16. p server_path
  17. p local_path
  18.  
  19. p "Copying #{entry.name}"
  20. sftp.download! server_path, local_path
  21.  
  22. # p "Deleting #{name}"
  23. # sftp.remove(server_path)
  24.  
  25. yield local_path
  26.  
  27. # debug
  28. break if limit = opts[:limit] and (i += 1) >= limit
  29. end
  30. end
  31. end
  32.  
  33. def self.parse file
  34. result = {}
  35. mail = Mail.read file
  36.  
  37. if mail && mail.multipart?
  38. result[:bounced_at] = mail.date
  39.  
  40. if msg = mail.parts.find { |part| part.content_type =~ /message\/rfc822/i }
  41. mail2 = Mail.new msg.body
  42. slug = mail2.reply_to.to_s[/notification\+(.*)@/,1]
  43.  
  44. result[:sent_email] = SentEmail[:slug => slug] if slug
  45.  
  46. raise SlugNotMatchedError unless result[:sent_email]
  47.  
  48. yield result
  49. end
  50. end
  51. end
  52.  
  53. class ParseError < StandardError; self; end
  54. class SlugNotMatchedError < ParseError; self; end
  55. end
  56.  
  57. WORKING_DIR = [:new, :processed, :failed].inject({}) { |hash,dir| hash.merge({dir => "/Users/jeshuaborges/Desktop/test/#{dir}"}) }
  58.  
  59. # ensure all working dirs have been created
  60. WORKING_DIR.values.each { |dir| FileUtils.mkdir dir rescue nil }
  61.  
  62. MailParser.sftp_retrieve(
  63. :server => 'homerunmail.com',
  64. :username => 'fbl',
  65. :password => 'h0merun1sc00l',
  66. :source => "Maildir/new",
  67. :target => WORKING_DIR[:new],
  68. :limit => 1
  69. ) do |local_path|
  70. begin
  71. MailParser.parse local_path do |result|
  72. se = result[:sent_email]
  73. bounced_at = result[:bounced_at]
  74.  
  75. se.feed_back_loop! bounced_at
  76. FileUtils.mv local_path, WORKING_DIR[:processed]
  77. end
  78. rescue MailParser::ParseError
  79. FileUtils.mv local_path, WORKING_DIR[:failed]
  80. end
  81. end
Add Comment
Please, Sign In to add comment