Created
          March 25, 2010 10:31 
        
      - 
      
- 
        Save justincaldwell/343408 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | require 'mms2r' | |
| class IncomingMailHandler < ActionMailer::Base | |
| # Receive and process emails | |
| def receive(email) | |
| mms = MMS2R::Media.new(email) | |
| photos = get_images_from_email(mms) | |
| pemail = PhotoEmail.create_from_mail_handler(email, mms) | |
| logit "Processing email from #{pemail.sender} with subject #{pemail.subject} " | |
| pemail.determine_and_save_kase_and_doc | |
| logit(pemail.matched_by ? "Subject was matched via #{matched_by}" : "Subject could not be matched.") | |
| if photos.length > 0 | |
| logit "Photos are attached to this email. Beginning to process." | |
| if attachments = Photo.save_from_email(photos, pemail) | |
| logit "Email has #{attachments} valid photos attached. Successfully saved." | |
| status = pemail.doctor_id ? 2 : 1 | |
| pemail.update_attributes(:attachments => attachments, | |
| :photo_email_status_id => status) | |
| else | |
| logit "Email has failed while processing. Returned as bad photo format." | |
| pemail.update_attributes(:photo_email_status_id => 3) | |
| end | |
| else | |
| logit "Email has no photos attached. Email sent to sender to notify." | |
| pemail.update_attributes(:photo_email_status_id => 4) | |
| end | |
| logit "Email has been processed." | |
| send_mail_notification(pemail) | |
| mms.purge | |
| end | |
| protected | |
| # Extracts images (photos and pdfs) from an email (mms2r object) | |
| def get_images_from_email mms | |
| images = mms.media.select{|k,v| k[0..4] == "image" || k.include?('pdf')} | |
| images.collect{|a|a[1]}.flatten | |
| end | |
| # Invokes the correct notifier according to pemail status | |
| def send_mail_notification pemail | |
| case pemail.photo_email_status_id | |
| when 1 : Notifier.deliver_photos_via_email(pemail.doctor, pemail.kase_id, pemail) | |
| when 2 : Notifier.deliver_unknown_photos_via_email(pemail) | |
| when 3 : Notifier.deliver_wrong_photo_format(pemail.sender) | |
| when 4 : Notifier.deliver_no_photos_attached(pemail.sender) | |
| end | |
| end | |
| # Simple logger | |
| def logit message | |
| puts "#{Time.now.strftime('%x %X')}: " + message | |
| end | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment