Project

General

Profile

Feature #4882 » mapi_mail_handler.rb

in app/models - Francois-Xavier CAUVIN, 2010-02-19 16:31

 
1
# redMine - project management software
2
# Copyright (C) 2006-2007  Jean-Philippe Lang
3
#
4
# This program is free software; you can redistribute it and/or
5
# modify it under the terms of the GNU General Public License
6
# as published by the Free Software Foundation; either version 2
7
# of the License, or (at your option) any later version.
8
# 
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
# 
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17

    
18
class MAPIMailHandler
19
  include ActionView::Helpers::SanitizeHelper
20

    
21
  class UnauthorizedAction < StandardError; end
22
  class MissingInformation < StandardError; end
23
  
24
  attr_reader :email, :user
25
  
26
  def self.receive(email, options={})
27
    @@handler_options = options.dup
28
    @@handler_options[:issue] ||= {}
29
  
30
    @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip) if @@handler_options[:allow_override].is_a?(String)
31
    @@handler_options[:allow_override] ||= []
32

    
33
    # Project needs to be overridable if not specified
34
    @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
35
    # Status overridable by default
36
    @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)    
37

    
38
    #super email
39
	new.receive(email)
40
  end
41
  
42
  # Processes incoming emails
43
  def receive(email)
44
    @email = email
45
    @user = User.active.find(:first, :conditions => ["LOWER(mail) = ?", email.sender.address.strip.downcase])
46
    unless @user
47
      # Unknown user => the email is ignored
48
      # TODO: ability to create the user's account
49
	  puts "email submitted by unknown user #{email.sender.address}"
50
      logger.info "MailHandler: email submitted by unknown user [#{email.sender.address}]" if logger && logger.info
51
      return false
52
    end
53
	puts "user identified #{@user}"
54
    User.current = @user
55
    dispatch
56
  end
57
  
58
  private
59
  
60
  def logger
61
        RAILS_DEFAULT_LOGGER
62
  end
63

    
64
  ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]+#(\d+)\]}
65
  
66
  def dispatch
67
    if m = email.subject.match(ISSUE_REPLY_SUBJECT_RE)
68
      receive_issue_update(m[1].to_i)
69
    else
70
      receive_issue
71
    end
72
  rescue ActiveRecord::RecordInvalid => e
73
    # TODO: send a email to the user
74
    logger.error e.message if logger
75
    false
76
  rescue MissingInformation => e
77
    logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
78
    false
79
  rescue UnauthorizedAction => e
80
    logger.error "MailHandler: unauthorized attempt from #{user}" if logger
81
    false
82
  end
83
  
84
  # Creates a new issue
85
  def receive_issue
86
    project = target_project
87
    tracker = (get_keyword(:tracker) && project.trackers.find_by_name(get_keyword(:tracker))) || project.trackers.find(:first)
88
    category = (get_keyword(:category) && project.issue_categories.find_by_name(get_keyword(:category)))
89
    priority = (get_keyword(:priority) && Enumeration.find_by_opt_and_name('IPRI', get_keyword(:priority)))
90
    status =  (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status)))
91

    
92
	puts "receive_issue [#{target_project}]"
93
    # check permission
94
    raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
95
    issue = Issue.new(:author => user, :project => project, :tracker => tracker, :category => category, :priority => priority)
96
    # check workflow
97
    if status && issue.new_statuses_allowed_to(user).include?(status)
98
      issue.status = status
99
    end
100
    issue.subject = email.subject.chomp.toutf8
101
    issue.description = plain_text_body
102
    # custom fields
103
    issue.custom_field_values = issue.available_custom_fields.inject({}) do |h, c|
104
      if value = get_keyword(c.name, :override => true)
105
        h[c.id] = value
106
      end
107
      h
108
    end
109
    issue.save!
110
    add_attachments(issue)
111
    logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger && logger.info
112
    # add To and Cc as watchers
113
    add_watchers(issue)
114
    # send notification after adding watchers so that they can reply to Redmine
115
    Mailer.deliver_issue_add(issue) if Setting.notified_events.include?('issue_added')
116
    issue
117
  end
118
  
119
  def target_project
120
    # TODO: other ways to specify project:
121
    # * parse the email To field
122
    # * specific project (eg. Setting.mail_handler_target_project)
123
    target = Project.find_by_identifier(get_keyword(:project))
124
    raise MissingInformation.new('Unable to determine target project') if target.nil?
125
    target
126
  end
127
  
128
  # Adds a note to an existing issue
129
  def receive_issue_update(issue_id)
130
    status =  (get_keyword(:status) && IssueStatus.find_by_name(get_keyword(:status)))
131
    
132
    issue = Issue.find_by_id(issue_id)
133
    return unless issue
134
    # check permission
135
    raise UnauthorizedAction unless user.allowed_to?(:add_issue_notes, issue.project) || user.allowed_to?(:edit_issues, issue.project)
136
    raise UnauthorizedAction unless status.nil? || user.allowed_to?(:edit_issues, issue.project)
137

    
138
    # add the note
139
    journal = issue.init_journal(user, plain_text_body)
140
    add_attachments(issue)
141
    # check workflow
142
    if status && issue.new_statuses_allowed_to(user).include?(status)
143
      issue.status = status
144
    end
145
    issue.save!
146
    logger.info "MailHandler: issue ##{issue.id} updated by #{user}" if logger && logger.info
147
    Mailer.deliver_issue_edit(journal) if Setting.notified_events.include?('issue_updated')
148
    journal
149
  end
150
  
151
  def add_attachments(obj)
152
    #if email.has_attachments?
153
      email.attachments.each do |attachment|
154
		puts "attachment :#{attachment.name}"
155
		attachment.fields.each do |field|
156
			puts "Field: name=#{field.name} type=#{field.type} value=#{field.value} index=#{field.index} id=#{field.id}"
157
		end
158
		attachment.ole_methods.each do |method|
159
			puts "Method: name=#{method.name}"
160
		end
161
		
162
		if attachment.Type == 1 #|| attachment.Type == 3
163
			filename = "c:\\tmp\\#{attachment.name}"
164
			puts "#{filename} source #{attachment.source.size}"
165
			attachment.WriteToFile( filename );
166
			Attachment.create(:container => obj,
167
                          :file => File.new(filename),
168
                          :author => user,
169
                          :content_type => attachment.fields.item(15))
170
			File.delete(filename)
171
		end
172
	  end
173
    #end
174
  end
175
  
176
  # Adds To and Cc as watchers of the given object if the sender has the
177
  # appropriate permission
178
  def add_watchers(obj)
179
    if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
180
		addresses = []
181
		email.recepients.each do |recipient|
182
			if reciepient.type < 3
183
				addresses += recipient.address
184
			end
185
		end
186
      #addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
187
      unless addresses.empty?
188
        watchers = User.active.find(:all, :conditions => ['LOWER(mail) IN (?)', addresses])
189
        watchers.each {|w| obj.add_watcher(w)}
190
      end
191
    end
192
  end
193
  
194
  def get_keyword(attr, options={})
195
    @keywords ||= {}
196
    if @keywords.has_key?(attr)
197
      @keywords[attr]
198
    else
199
      @keywords[attr] = begin
200
        if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) && plain_text_body.gsub!(/^#{attr}[ \t]*:[ \t]*(.+)\s*$/i, '')
201
          $1.strip
202
        elsif !@@handler_options[:issue][attr].blank?
203
          @@handler_options[:issue][attr]
204
        end
205
      end
206
    end
207
  end
208
  
209
  # Returns the text/plain part of the email
210
  # If not found (eg. HTML-only email), returns the body with tags removed
211
  def plain_text_body
212
    return @plain_text_body unless @plain_text_body.nil?
213
	
214
    #parts = @email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten
215
    #if parts.empty?
216
    #  parts << @email
217
    #end
218
    #plain_text_part = parts.detect {|p| p.content_type == 'text/plain'}
219
	plain_text_part = email.text
220
    if plain_text_part.nil?
221
      # no text/plain part found, assuming html-only email
222
      # strip html tags and remove doctype directive
223
      @plain_text_body = strip_tags(@email.text)
224
      @plain_text_body.gsub! %r{^<!DOCTYPE .*$}, ''
225
    else
226
      @plain_text_body = plain_text_part
227
    end
228
    @plain_text_body.strip!
229
    @plain_text_body
230
  end
231
end
(3-3/3)