##// END OF EJS Templates
Ignore email keywords after truncation line (#8758)....
Jean-Philippe Lang -
r13050:8ae41b4846fc
parent child
Show More
@@ -0,0 +1,25
1 Return-Path: <JSmith@somenet.foo>
2 Received: from osiris ([127.0.0.1])
3 by OSIRIS
4 with hMailServer ; Sun, 22 Jun 2008 12:28:07 +0200
5 Message-ID: <000501c8d452$a95cd7e0$0a00a8c0@osiris>
6 From: "John Smith" <JSmith@somenet.foo>
7 To: <redmine@somenet.foo>
8 Subject: New ticket on a given project
9 Date: Sun, 22 Jun 2008 12:28:07 +0200
10 MIME-Version: 1.0
11 Content-Type: text/plain;
12 format=flowed;
13 charset="iso-8859-1";
14 reply-type=original
15 Content-Transfer-Encoding: 7bit
16 X-Priority: 3
17 X-MSMail-Priority: Normal
18 X-Mailer: Microsoft Outlook Express 6.00.2900.2869
19 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2869
20
21 Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
22
23 Project: ecookbook
24 Priority: High
25 Priority: Low
@@ -0,0 +1,27
1 Return-Path: <JSmith@somenet.foo>
2 Received: from osiris ([127.0.0.1])
3 by OSIRIS
4 with hMailServer ; Sun, 22 Jun 2008 12:28:07 +0200
5 Message-ID: <000501c8d452$a95cd7e0$0a00a8c0@osiris>
6 From: "John Smith" <JSmith@somenet.foo>
7 To: <redmine@somenet.foo>
8 Subject: New ticket on a given project
9 Date: Sun, 22 Jun 2008 12:28:07 +0200
10 MIME-Version: 1.0
11 Content-Type: text/plain;
12 format=flowed;
13 charset="iso-8859-1";
14 reply-type=original
15 Content-Transfer-Encoding: 7bit
16 X-Priority: 3
17 X-MSMail-Priority: Normal
18 X-Mailer: Microsoft Outlook Express 6.00.2900.2869
19 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2869
20
21 Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
22
23 Project: ecookbook
24
25 == DELIMITER ==
26
27 Priority: High
@@ -1,550 +1,550
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2014 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class MailHandler < ActionMailer::Base
19 19 include ActionView::Helpers::SanitizeHelper
20 20 include Redmine::I18n
21 21
22 22 class UnauthorizedAction < StandardError; end
23 23 class MissingInformation < StandardError; end
24 24
25 25 attr_reader :email, :user
26 26
27 27 def self.receive(email, options={})
28 28 @@handler_options = options.dup
29 29
30 30 @@handler_options[:issue] ||= {}
31 31
32 32 if @@handler_options[:allow_override].is_a?(String)
33 33 @@handler_options[:allow_override] = @@handler_options[:allow_override].split(',').collect(&:strip)
34 34 end
35 35 @@handler_options[:allow_override] ||= []
36 36 # Project needs to be overridable if not specified
37 37 @@handler_options[:allow_override] << 'project' unless @@handler_options[:issue].has_key?(:project)
38 38 # Status overridable by default
39 39 @@handler_options[:allow_override] << 'status' unless @@handler_options[:issue].has_key?(:status)
40 40
41 41 @@handler_options[:no_account_notice] = (@@handler_options[:no_account_notice].to_s == '1')
42 42 @@handler_options[:no_notification] = (@@handler_options[:no_notification].to_s == '1')
43 43 @@handler_options[:no_permission_check] = (@@handler_options[:no_permission_check].to_s == '1')
44 44
45 45 email.force_encoding('ASCII-8BIT') if email.respond_to?(:force_encoding)
46 46 super(email)
47 47 end
48 48
49 49 # Receives an email and rescues any exception
50 50 def self.safe_receive(*args)
51 51 receive(*args)
52 52 rescue => e
53 53 logger.error "An unexpected error occurred when receiving email: #{e.message}" if logger
54 54 return false
55 55 end
56 56
57 57 # Extracts MailHandler options from environment variables
58 58 # Use when receiving emails with rake tasks
59 59 def self.extract_options_from_env(env)
60 60 options = {:issue => {}}
61 61 %w(project status tracker category priority).each do |option|
62 62 options[:issue][option.to_sym] = env[option] if env[option]
63 63 end
64 64 %w(allow_override unknown_user no_permission_check no_account_notice default_group).each do |option|
65 65 options[option.to_sym] = env[option] if env[option]
66 66 end
67 67 options
68 68 end
69 69
70 70 def logger
71 71 Rails.logger
72 72 end
73 73
74 74 cattr_accessor :ignored_emails_headers
75 75 @@ignored_emails_headers = {
76 76 'X-Auto-Response-Suppress' => 'oof',
77 77 'Auto-Submitted' => /\Aauto-(replied|generated)/
78 78 }
79 79
80 80 # Processes incoming emails
81 81 # Returns the created object (eg. an issue, a message) or false
82 82 def receive(email)
83 83 @email = email
84 84 sender_email = email.from.to_a.first.to_s.strip
85 85 # Ignore emails received from the application emission address to avoid hell cycles
86 86 if sender_email.downcase == Setting.mail_from.to_s.strip.downcase
87 87 if logger
88 88 logger.info "MailHandler: ignoring email from Redmine emission address [#{sender_email}]"
89 89 end
90 90 return false
91 91 end
92 92 # Ignore auto generated emails
93 93 self.class.ignored_emails_headers.each do |key, ignored_value|
94 94 value = email.header[key]
95 95 if value
96 96 value = value.to_s.downcase
97 97 if (ignored_value.is_a?(Regexp) && value.match(ignored_value)) || value == ignored_value
98 98 if logger
99 99 logger.info "MailHandler: ignoring email with #{key}:#{value} header"
100 100 end
101 101 return false
102 102 end
103 103 end
104 104 end
105 105 @user = User.find_by_mail(sender_email) if sender_email.present?
106 106 if @user && !@user.active?
107 107 if logger
108 108 logger.info "MailHandler: ignoring email from non-active user [#{@user.login}]"
109 109 end
110 110 return false
111 111 end
112 112 if @user.nil?
113 113 # Email was submitted by an unknown user
114 114 case @@handler_options[:unknown_user]
115 115 when 'accept'
116 116 @user = User.anonymous
117 117 when 'create'
118 118 @user = create_user_from_email
119 119 if @user
120 120 if logger
121 121 logger.info "MailHandler: [#{@user.login}] account created"
122 122 end
123 123 add_user_to_group(@@handler_options[:default_group])
124 124 unless @@handler_options[:no_account_notice]
125 125 Mailer.account_information(@user, @user.password).deliver
126 126 end
127 127 else
128 128 if logger
129 129 logger.error "MailHandler: could not create account for [#{sender_email}]"
130 130 end
131 131 return false
132 132 end
133 133 else
134 134 # Default behaviour, emails from unknown users are ignored
135 135 if logger
136 136 logger.info "MailHandler: ignoring email from unknown user [#{sender_email}]"
137 137 end
138 138 return false
139 139 end
140 140 end
141 141 User.current = @user
142 142 dispatch
143 143 end
144 144
145 145 private
146 146
147 147 MESSAGE_ID_RE = %r{^<?redmine\.([a-z0-9_]+)\-(\d+)\.\d+(\.[a-f0-9]+)?@}
148 148 ISSUE_REPLY_SUBJECT_RE = %r{\[[^\]]*#(\d+)\]}
149 149 MESSAGE_REPLY_SUBJECT_RE = %r{\[[^\]]*msg(\d+)\]}
150 150
151 151 def dispatch
152 152 headers = [email.in_reply_to, email.references].flatten.compact
153 153 subject = email.subject.to_s
154 154 if headers.detect {|h| h.to_s =~ MESSAGE_ID_RE}
155 155 klass, object_id = $1, $2.to_i
156 156 method_name = "receive_#{klass}_reply"
157 157 if self.class.private_instance_methods.collect(&:to_s).include?(method_name)
158 158 send method_name, object_id
159 159 else
160 160 # ignoring it
161 161 end
162 162 elsif m = subject.match(ISSUE_REPLY_SUBJECT_RE)
163 163 receive_issue_reply(m[1].to_i)
164 164 elsif m = subject.match(MESSAGE_REPLY_SUBJECT_RE)
165 165 receive_message_reply(m[1].to_i)
166 166 else
167 167 dispatch_to_default
168 168 end
169 169 rescue ActiveRecord::RecordInvalid => e
170 170 # TODO: send a email to the user
171 171 logger.error e.message if logger
172 172 false
173 173 rescue MissingInformation => e
174 174 logger.error "MailHandler: missing information from #{user}: #{e.message}" if logger
175 175 false
176 176 rescue UnauthorizedAction => e
177 177 logger.error "MailHandler: unauthorized attempt from #{user}" if logger
178 178 false
179 179 end
180 180
181 181 def dispatch_to_default
182 182 receive_issue
183 183 end
184 184
185 185 # Creates a new issue
186 186 def receive_issue
187 187 project = target_project
188 188 # check permission
189 189 unless @@handler_options[:no_permission_check]
190 190 raise UnauthorizedAction unless user.allowed_to?(:add_issues, project)
191 191 end
192 192
193 193 issue = Issue.new(:author => user, :project => project)
194 194 issue.safe_attributes = issue_attributes_from_keywords(issue)
195 195 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
196 196 issue.subject = cleaned_up_subject
197 197 if issue.subject.blank?
198 198 issue.subject = '(no subject)'
199 199 end
200 200 issue.description = cleaned_up_text_body
201 201 issue.start_date ||= Date.today if Setting.default_issue_start_date_to_creation_date?
202 202
203 203 # add To and Cc as watchers before saving so the watchers can reply to Redmine
204 204 add_watchers(issue)
205 205 issue.save!
206 206 add_attachments(issue)
207 207 logger.info "MailHandler: issue ##{issue.id} created by #{user}" if logger
208 208 issue
209 209 end
210 210
211 211 # Adds a note to an existing issue
212 212 def receive_issue_reply(issue_id, from_journal=nil)
213 213 issue = Issue.find_by_id(issue_id)
214 214 return unless issue
215 215 # check permission
216 216 unless @@handler_options[:no_permission_check]
217 217 unless user.allowed_to?(:add_issue_notes, issue.project) ||
218 218 user.allowed_to?(:edit_issues, issue.project)
219 219 raise UnauthorizedAction
220 220 end
221 221 end
222 222
223 223 # ignore CLI-supplied defaults for new issues
224 224 @@handler_options[:issue].clear
225 225
226 226 journal = issue.init_journal(user)
227 227 if from_journal && from_journal.private_notes?
228 228 # If the received email was a reply to a private note, make the added note private
229 229 issue.private_notes = true
230 230 end
231 231 issue.safe_attributes = issue_attributes_from_keywords(issue)
232 232 issue.safe_attributes = {'custom_field_values' => custom_field_values_from_keywords(issue)}
233 233 journal.notes = cleaned_up_text_body
234 234 add_attachments(issue)
235 235 issue.save!
236 236 if logger
237 237 logger.info "MailHandler: issue ##{issue.id} updated by #{user}"
238 238 end
239 239 journal
240 240 end
241 241
242 242 # Reply will be added to the issue
243 243 def receive_journal_reply(journal_id)
244 244 journal = Journal.find_by_id(journal_id)
245 245 if journal && journal.journalized_type == 'Issue'
246 246 receive_issue_reply(journal.journalized_id, journal)
247 247 end
248 248 end
249 249
250 250 # Receives a reply to a forum message
251 251 def receive_message_reply(message_id)
252 252 message = Message.find_by_id(message_id)
253 253 if message
254 254 message = message.root
255 255
256 256 unless @@handler_options[:no_permission_check]
257 257 raise UnauthorizedAction unless user.allowed_to?(:add_messages, message.project)
258 258 end
259 259
260 260 if !message.locked?
261 261 reply = Message.new(:subject => cleaned_up_subject.gsub(%r{^.*msg\d+\]}, '').strip,
262 262 :content => cleaned_up_text_body)
263 263 reply.author = user
264 264 reply.board = message.board
265 265 message.children << reply
266 266 add_attachments(reply)
267 267 reply
268 268 else
269 269 if logger
270 270 logger.info "MailHandler: ignoring reply from [#{sender_email}] to a locked topic"
271 271 end
272 272 end
273 273 end
274 274 end
275 275
276 276 def add_attachments(obj)
277 277 if email.attachments && email.attachments.any?
278 278 email.attachments.each do |attachment|
279 279 next unless accept_attachment?(attachment)
280 280 obj.attachments << Attachment.create(:container => obj,
281 281 :file => attachment.decoded,
282 282 :filename => attachment.filename,
283 283 :author => user,
284 284 :content_type => attachment.mime_type)
285 285 end
286 286 end
287 287 end
288 288
289 289 # Returns false if the +attachment+ of the incoming email should be ignored
290 290 def accept_attachment?(attachment)
291 291 @excluded ||= Setting.mail_handler_excluded_filenames.to_s.split(',').map(&:strip).reject(&:blank?)
292 292 @excluded.each do |pattern|
293 293 regexp = %r{\A#{Regexp.escape(pattern).gsub("\\*", ".*")}\z}i
294 294 if attachment.filename.to_s =~ regexp
295 295 logger.info "MailHandler: ignoring attachment #{attachment.filename} matching #{pattern}"
296 296 return false
297 297 end
298 298 end
299 299 true
300 300 end
301 301
302 302 # Adds To and Cc as watchers of the given object if the sender has the
303 303 # appropriate permission
304 304 def add_watchers(obj)
305 305 if user.allowed_to?("add_#{obj.class.name.underscore}_watchers".to_sym, obj.project)
306 306 addresses = [email.to, email.cc].flatten.compact.uniq.collect {|a| a.strip.downcase}
307 307 unless addresses.empty?
308 308 User.active.where('LOWER(mail) IN (?)', addresses).each do |w|
309 309 obj.add_watcher(w)
310 310 end
311 311 end
312 312 end
313 313 end
314 314
315 315 def get_keyword(attr, options={})
316 316 @keywords ||= {}
317 317 if @keywords.has_key?(attr)
318 318 @keywords[attr]
319 319 else
320 320 @keywords[attr] = begin
321 321 if (options[:override] || @@handler_options[:allow_override].include?(attr.to_s)) &&
322 (v = extract_keyword!(plain_text_body, attr, options[:format]))
322 (v = extract_keyword!(cleaned_up_text_body, attr, options[:format]))
323 323 v
324 324 elsif !@@handler_options[:issue][attr].blank?
325 325 @@handler_options[:issue][attr]
326 326 end
327 327 end
328 328 end
329 329 end
330 330
331 331 # Destructively extracts the value for +attr+ in +text+
332 332 # Returns nil if no matching keyword found
333 333 def extract_keyword!(text, attr, format=nil)
334 334 keys = [attr.to_s.humanize]
335 335 if attr.is_a?(Symbol)
336 336 if user && user.language.present?
337 337 keys << l("field_#{attr}", :default => '', :locale => user.language)
338 338 end
339 339 if Setting.default_language.present?
340 340 keys << l("field_#{attr}", :default => '', :locale => Setting.default_language)
341 341 end
342 342 end
343 343 keys.reject! {|k| k.blank?}
344 344 keys.collect! {|k| Regexp.escape(k)}
345 345 format ||= '.+'
346 346 keyword = nil
347 347 regexp = /^(#{keys.join('|')})[ \t]*:[ \t]*(#{format})\s*$/i
348 348 if m = text.match(regexp)
349 349 keyword = m[2].strip
350 text.gsub!(regexp, '')
350 text.sub!(regexp, '')
351 351 end
352 352 keyword
353 353 end
354 354
355 355 def target_project
356 356 # TODO: other ways to specify project:
357 357 # * parse the email To field
358 358 # * specific project (eg. Setting.mail_handler_target_project)
359 359 target = Project.find_by_identifier(get_keyword(:project))
360 360 if target.nil?
361 361 # Invalid project keyword, use the project specified as the default one
362 362 default_project = @@handler_options[:issue][:project]
363 363 if default_project.present?
364 364 target = Project.find_by_identifier(default_project)
365 365 end
366 366 end
367 367 raise MissingInformation.new('Unable to determine target project') if target.nil?
368 368 target
369 369 end
370 370
371 371 # Returns a Hash of issue attributes extracted from keywords in the email body
372 372 def issue_attributes_from_keywords(issue)
373 373 assigned_to = (k = get_keyword(:assigned_to, :override => true)) && find_assignee_from_keyword(k, issue)
374 374
375 375 attrs = {
376 376 'tracker_id' => (k = get_keyword(:tracker)) && issue.project.trackers.named(k).first.try(:id),
377 377 'status_id' => (k = get_keyword(:status)) && IssueStatus.named(k).first.try(:id),
378 378 'priority_id' => (k = get_keyword(:priority)) && IssuePriority.named(k).first.try(:id),
379 379 'category_id' => (k = get_keyword(:category)) && issue.project.issue_categories.named(k).first.try(:id),
380 380 'assigned_to_id' => assigned_to.try(:id),
381 381 'fixed_version_id' => (k = get_keyword(:fixed_version, :override => true)) &&
382 382 issue.project.shared_versions.named(k).first.try(:id),
383 383 'start_date' => get_keyword(:start_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
384 384 'due_date' => get_keyword(:due_date, :override => true, :format => '\d{4}-\d{2}-\d{2}'),
385 385 'estimated_hours' => get_keyword(:estimated_hours, :override => true),
386 386 'done_ratio' => get_keyword(:done_ratio, :override => true, :format => '(\d|10)?0')
387 387 }.delete_if {|k, v| v.blank? }
388 388
389 389 if issue.new_record? && attrs['tracker_id'].nil?
390 390 attrs['tracker_id'] = issue.project.trackers.first.try(:id)
391 391 end
392 392
393 393 attrs
394 394 end
395 395
396 396 # Returns a Hash of issue custom field values extracted from keywords in the email body
397 397 def custom_field_values_from_keywords(customized)
398 398 customized.custom_field_values.inject({}) do |h, v|
399 399 if keyword = get_keyword(v.custom_field.name, :override => true)
400 400 h[v.custom_field.id.to_s] = v.custom_field.value_from_keyword(keyword, customized)
401 401 end
402 402 h
403 403 end
404 404 end
405 405
406 406 # Returns the text/plain part of the email
407 407 # If not found (eg. HTML-only email), returns the body with tags removed
408 408 def plain_text_body
409 409 return @plain_text_body unless @plain_text_body.nil?
410 410
411 411 parts = if (text_parts = email.all_parts.select {|p| p.mime_type == 'text/plain'}).present?
412 412 text_parts
413 413 elsif (html_parts = email.all_parts.select {|p| p.mime_type == 'text/html'}).present?
414 414 html_parts
415 415 else
416 416 [email]
417 417 end
418 418
419 419 parts.reject! do |part|
420 420 part.header[:content_disposition].try(:disposition_type) == 'attachment'
421 421 end
422 422
423 423 @plain_text_body = parts.map do |p|
424 424 body_charset = p.charset.respond_to?(:force_encoding) ?
425 425 Mail::RubyVer.pick_encoding(p.charset).to_s : p.charset
426 426 Redmine::CodesetUtil.to_utf8(p.body.decoded, body_charset)
427 427 end.join("\r\n")
428 428
429 429 # strip html tags and remove doctype directive
430 430 if parts.any? {|p| p.mime_type == 'text/html'}
431 431 @plain_text_body = strip_tags(@plain_text_body.strip)
432 432 @plain_text_body.sub! %r{^<!DOCTYPE .*$}, ''
433 433 end
434 434
435 435 @plain_text_body
436 436 end
437 437
438 438 def cleaned_up_text_body
439 cleanup_body(plain_text_body)
439 @cleaned_up_text_body ||= cleanup_body(plain_text_body)
440 440 end
441 441
442 442 def cleaned_up_subject
443 443 subject = email.subject.to_s
444 444 subject.strip[0,255]
445 445 end
446 446
447 447 def self.full_sanitizer
448 448 @full_sanitizer ||= HTML::FullSanitizer.new
449 449 end
450 450
451 451 def self.assign_string_attribute_with_limit(object, attribute, value, limit=nil)
452 452 limit ||= object.class.columns_hash[attribute.to_s].limit || 255
453 453 value = value.to_s.slice(0, limit)
454 454 object.send("#{attribute}=", value)
455 455 end
456 456
457 457 # Returns a User from an email address and a full name
458 458 def self.new_user_from_attributes(email_address, fullname=nil)
459 459 user = User.new
460 460
461 461 # Truncating the email address would result in an invalid format
462 462 user.mail = email_address
463 463 assign_string_attribute_with_limit(user, 'login', email_address, User::LOGIN_LENGTH_LIMIT)
464 464
465 465 names = fullname.blank? ? email_address.gsub(/@.*$/, '').split('.') : fullname.split
466 466 assign_string_attribute_with_limit(user, 'firstname', names.shift, 30)
467 467 assign_string_attribute_with_limit(user, 'lastname', names.join(' '), 30)
468 468 user.lastname = '-' if user.lastname.blank?
469 469 user.language = Setting.default_language
470 470 user.generate_password = true
471 471 user.mail_notification = 'only_my_events'
472 472
473 473 unless user.valid?
474 474 user.login = "user#{Redmine::Utils.random_hex(6)}" unless user.errors[:login].blank?
475 475 user.firstname = "-" unless user.errors[:firstname].blank?
476 476 (puts user.errors[:lastname];user.lastname = "-") unless user.errors[:lastname].blank?
477 477 end
478 478
479 479 user
480 480 end
481 481
482 482 # Creates a User for the +email+ sender
483 483 # Returns the user or nil if it could not be created
484 484 def create_user_from_email
485 485 from = email.header['from'].to_s
486 486 addr, name = from, nil
487 487 if m = from.match(/^"?(.+?)"?\s+<(.+@.+)>$/)
488 488 addr, name = m[2], m[1]
489 489 end
490 490 if addr.present?
491 491 user = self.class.new_user_from_attributes(addr, name)
492 492 if @@handler_options[:no_notification]
493 493 user.mail_notification = 'none'
494 494 end
495 495 if user.save
496 496 user
497 497 else
498 498 logger.error "MailHandler: failed to create User: #{user.errors.full_messages}" if logger
499 499 nil
500 500 end
501 501 else
502 502 logger.error "MailHandler: failed to create User: no FROM address found" if logger
503 503 nil
504 504 end
505 505 end
506 506
507 507 # Adds the newly created user to default group
508 508 def add_user_to_group(default_group)
509 509 if default_group.present?
510 510 default_group.split(',').each do |group_name|
511 511 if group = Group.named(group_name).first
512 512 group.users << @user
513 513 elsif logger
514 514 logger.warn "MailHandler: could not add user to [#{group_name}], group not found"
515 515 end
516 516 end
517 517 end
518 518 end
519 519
520 520 # Removes the email body of text after the truncation configurations.
521 521 def cleanup_body(body)
522 522 delimiters = Setting.mail_handler_body_delimiters.to_s.split(/[\r\n]+/).reject(&:blank?).map {|s| Regexp.escape(s)}
523 523 unless delimiters.empty?
524 524 regex = Regexp.new("^[> ]*(#{ delimiters.join('|') })\s*[\r\n].*", Regexp::MULTILINE)
525 525 body = body.gsub(regex, '')
526 526 end
527 527 body.strip
528 528 end
529 529
530 530 def find_assignee_from_keyword(keyword, issue)
531 531 keyword = keyword.to_s.downcase
532 532 assignable = issue.assignable_users
533 533 assignee = nil
534 534 assignee ||= assignable.detect {|a|
535 535 a.mail.to_s.downcase == keyword ||
536 536 a.login.to_s.downcase == keyword
537 537 }
538 538 if assignee.nil? && keyword.match(/ /)
539 539 firstname, lastname = *(keyword.split) # "First Last Throwaway"
540 540 assignee ||= assignable.detect {|a|
541 541 a.is_a?(User) && a.firstname.to_s.downcase == firstname &&
542 542 a.lastname.to_s.downcase == lastname
543 543 }
544 544 end
545 545 if assignee.nil?
546 546 assignee ||= assignable.detect {|a| a.name.downcase == keyword}
547 547 end
548 548 assignee
549 549 end
550 550 end
@@ -1,60 +1,60
1 1 Return-Path: <JSmith@somenet.foo>
2 2 Received: from osiris ([127.0.0.1])
3 3 by OSIRIS
4 4 with hMailServer ; Sun, 22 Jun 2008 12:28:07 +0200
5 5 Message-ID: <000501c8d452$a95cd7e0$0a00a8c0@osiris>
6 6 From: "John Smith" <JSmith@somenet.foo>
7 7 To: <redmine@somenet.foo>
8 8 Subject: New ticket on a given project
9 9 Date: Sun, 22 Jun 2008 12:28:07 +0200
10 10 MIME-Version: 1.0
11 11 Content-Type: text/plain;
12 12 format=flowed;
13 13 charset="iso-8859-1";
14 14 reply-type=original
15 15 Content-Transfer-Encoding: 7bit
16 16 X-Priority: 3
17 17 X-MSMail-Priority: Normal
18 18 X-Mailer: Microsoft Outlook Express 6.00.2900.2869
19 19 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.2869
20 20
21 21 Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas imperdiet
22 22 turpis et odio. Integer eget pede vel dolor euismod varius. Phasellus
23 23 blandit eleifend augue. Nulla facilisi. Duis id diam. Class aptent taciti
24 24 sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In
25 25 in urna sed tellus aliquet lobortis. Morbi scelerisque tortor in dolor. Cras
26 26 sagittis odio eu lacus. Aliquam sem tortor, consequat sit amet, vestibulum
27 27 id, iaculis at, lectus. Fusce tortor libero, congue ut, euismod nec, luctus
28 28 eget, eros. Pellentesque tortor enim, feugiat in, dignissim eget, tristique
29 29 sed, mauris --- Pellentesque habitant morbi tristique senectus et netus et
30 30 malesuada fames ac turpis egestas. Quisque sit amet libero. In hac habitasse
31 31 platea dictumst.
32 32
33 Project: onlinestore
34 Status: Resolved
35 due date: 2010-12-31
36 Start Date:2010-01-01
37 Assigned to: John Smith
38 fixed version: alpha
39 estimated hours: 2.5
40 done ratio: 30
41
33 42 --- This line starts with a delimiter and should not be stripped
34 43
35 44 This paragraph is before delimiters.
36 45
37 46 BREAK
38 47
39 48 This paragraph is between delimiters.
40 49
41 50 ---
42 51
43 52 This paragraph is after the delimiter so it shouldn't appear.
44 53
45 54 Nulla et nunc. Duis pede. Donec et ipsum. Nam ut dui tincidunt neque
46 55 sollicitudin iaculis. Duis vitae dolor. Vestibulum eget massa. Sed lorem.
47 56 Nullam volutpat cursus erat. Cras felis dolor, lacinia quis, rutrum et,
48 57 dictum et, ligula. Sed erat nibh, gravida in, accumsan non, placerat sed,
49 58 massa. Sed sodales, ante fermentum ultricies sollicitudin, massa leo
50 59 pulvinar dui, a gravida orci mi eget odio. Nunc a lacus.
51 60
52 Project: onlinestore
53 Status: Resolved
54 due date: 2010-12-31
55 Start Date:2010-01-01
56 Assigned to: John Smith
57 fixed version: alpha
58 estimated hours: 2.5
59 done ratio: 30
60
@@ -1,933 +1,947
1 1 # encoding: utf-8
2 2 #
3 3 # Redmine - project management software
4 4 # Copyright (C) 2006-2014 Jean-Philippe Lang
5 5 #
6 6 # This program is free software; you can redistribute it and/or
7 7 # modify it under the terms of the GNU General Public License
8 8 # as published by the Free Software Foundation; either version 2
9 9 # of the License, or (at your option) any later version.
10 10 #
11 11 # This program is distributed in the hope that it will be useful,
12 12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 14 # GNU General Public License for more details.
15 15 #
16 16 # You should have received a copy of the GNU General Public License
17 17 # along with this program; if not, write to the Free Software
18 18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 19
20 20 require File.expand_path('../../test_helper', __FILE__)
21 21
22 22 class MailHandlerTest < ActiveSupport::TestCase
23 23 fixtures :users, :projects, :enabled_modules, :roles,
24 24 :members, :member_roles, :users,
25 25 :issues, :issue_statuses,
26 26 :workflows, :trackers, :projects_trackers,
27 27 :versions, :enumerations, :issue_categories,
28 28 :custom_fields, :custom_fields_trackers, :custom_fields_projects,
29 29 :boards, :messages
30 30
31 31 FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures/mail_handler'
32 32
33 33 def setup
34 34 ActionMailer::Base.deliveries.clear
35 35 Setting.notified_events = Redmine::Notifiable.all.collect(&:name)
36 36 end
37 37
38 38 def teardown
39 39 Setting.clear_cache
40 40 end
41 41
42 42 def test_add_issue
43 43 ActionMailer::Base.deliveries.clear
44 44 lft1 = new_issue_lft
45 45 # This email contains: 'Project: onlinestore'
46 46 issue = submit_email('ticket_on_given_project.eml')
47 47 assert issue.is_a?(Issue)
48 48 assert !issue.new_record?
49 49 issue.reload
50 50 assert_equal Project.find(2), issue.project
51 51 assert_equal issue.project.trackers.first, issue.tracker
52 52 assert_equal 'New ticket on a given project', issue.subject
53 53 assert_equal User.find_by_login('jsmith'), issue.author
54 54 assert_equal IssueStatus.find_by_name('Resolved'), issue.status
55 55 assert issue.description.include?('Lorem ipsum dolor sit amet, consectetuer adipiscing elit.')
56 56 assert_equal '2010-01-01', issue.start_date.to_s
57 57 assert_equal '2010-12-31', issue.due_date.to_s
58 58 assert_equal User.find_by_login('jsmith'), issue.assigned_to
59 59 assert_equal Version.find_by_name('Alpha'), issue.fixed_version
60 60 assert_equal 2.5, issue.estimated_hours
61 61 assert_equal 30, issue.done_ratio
62 62 assert_equal [issue.id, lft1, lft1 + 1], [issue.root_id, issue.lft, issue.rgt]
63 63 # keywords should be removed from the email body
64 64 assert !issue.description.match(/^Project:/i)
65 65 assert !issue.description.match(/^Status:/i)
66 66 assert !issue.description.match(/^Start Date:/i)
67 67 # Email notification should be sent
68 68 mail = ActionMailer::Base.deliveries.last
69 69 assert_not_nil mail
70 70 assert mail.subject.include?("##{issue.id}")
71 71 assert mail.subject.include?('New ticket on a given project')
72 72 end
73 73
74 74 def test_add_issue_with_default_tracker
75 75 # This email contains: 'Project: onlinestore'
76 76 issue = submit_email(
77 77 'ticket_on_given_project.eml',
78 78 :issue => {:tracker => 'Support request'}
79 79 )
80 80 assert issue.is_a?(Issue)
81 81 assert !issue.new_record?
82 82 issue.reload
83 83 assert_equal 'Support request', issue.tracker.name
84 84 end
85 85
86 86 def test_add_issue_with_status
87 87 # This email contains: 'Project: onlinestore' and 'Status: Resolved'
88 88 issue = submit_email('ticket_on_given_project.eml')
89 89 assert issue.is_a?(Issue)
90 90 assert !issue.new_record?
91 91 issue.reload
92 92 assert_equal Project.find(2), issue.project
93 93 assert_equal IssueStatus.find_by_name("Resolved"), issue.status
94 94 end
95 95
96 96 def test_add_issue_with_attributes_override
97 97 issue = submit_email(
98 98 'ticket_with_attributes.eml',
99 99 :allow_override => 'tracker,category,priority'
100 100 )
101 101 assert issue.is_a?(Issue)
102 102 assert !issue.new_record?
103 103 issue.reload
104 104 assert_equal 'New ticket on a given project', issue.subject
105 105 assert_equal User.find_by_login('jsmith'), issue.author
106 106 assert_equal Project.find(2), issue.project
107 107 assert_equal 'Feature request', issue.tracker.to_s
108 108 assert_equal 'Stock management', issue.category.to_s
109 109 assert_equal 'Urgent', issue.priority.to_s
110 110 assert issue.description.include?('Lorem ipsum dolor sit amet, consectetuer adipiscing elit.')
111 111 end
112 112
113 113 def test_add_issue_with_group_assignment
114 114 with_settings :issue_group_assignment => '1' do
115 115 issue = submit_email('ticket_on_given_project.eml') do |email|
116 116 email.gsub!('Assigned to: John Smith', 'Assigned to: B Team')
117 117 end
118 118 assert issue.is_a?(Issue)
119 119 assert !issue.new_record?
120 120 issue.reload
121 121 assert_equal Group.find(11), issue.assigned_to
122 122 end
123 123 end
124 124
125 125 def test_add_issue_with_partial_attributes_override
126 126 issue = submit_email(
127 127 'ticket_with_attributes.eml',
128 128 :issue => {:priority => 'High'},
129 129 :allow_override => ['tracker']
130 130 )
131 131 assert issue.is_a?(Issue)
132 132 assert !issue.new_record?
133 133 issue.reload
134 134 assert_equal 'New ticket on a given project', issue.subject
135 135 assert_equal User.find_by_login('jsmith'), issue.author
136 136 assert_equal Project.find(2), issue.project
137 137 assert_equal 'Feature request', issue.tracker.to_s
138 138 assert_nil issue.category
139 139 assert_equal 'High', issue.priority.to_s
140 140 assert issue.description.include?('Lorem ipsum dolor sit amet, consectetuer adipiscing elit.')
141 141 end
142 142
143 143 def test_add_issue_with_spaces_between_attribute_and_separator
144 144 issue = submit_email(
145 145 'ticket_with_spaces_between_attribute_and_separator.eml',
146 146 :allow_override => 'tracker,category,priority'
147 147 )
148 148 assert issue.is_a?(Issue)
149 149 assert !issue.new_record?
150 150 issue.reload
151 151 assert_equal 'New ticket on a given project', issue.subject
152 152 assert_equal User.find_by_login('jsmith'), issue.author
153 153 assert_equal Project.find(2), issue.project
154 154 assert_equal 'Feature request', issue.tracker.to_s
155 155 assert_equal 'Stock management', issue.category.to_s
156 156 assert_equal 'Urgent', issue.priority.to_s
157 157 assert issue.description.include?('Lorem ipsum dolor sit amet, consectetuer adipiscing elit.')
158 158 end
159 159
160 160 def test_add_issue_with_attachment_to_specific_project
161 161 issue = submit_email('ticket_with_attachment.eml', :issue => {:project => 'onlinestore'})
162 162 assert issue.is_a?(Issue)
163 163 assert !issue.new_record?
164 164 issue.reload
165 165 assert_equal 'Ticket created by email with attachment', issue.subject
166 166 assert_equal User.find_by_login('jsmith'), issue.author
167 167 assert_equal Project.find(2), issue.project
168 168 assert_equal 'This is a new ticket with attachments', issue.description
169 169 # Attachment properties
170 170 assert_equal 1, issue.attachments.size
171 171 assert_equal 'Paella.jpg', issue.attachments.first.filename
172 172 assert_equal 'image/jpeg', issue.attachments.first.content_type
173 173 assert_equal 10790, issue.attachments.first.filesize
174 174 end
175 175
176 176 def test_add_issue_with_custom_fields
177 177 issue = submit_email('ticket_with_custom_fields.eml', :issue => {:project => 'onlinestore'})
178 178 assert issue.is_a?(Issue)
179 179 assert !issue.new_record?
180 180 issue.reload
181 181 assert_equal 'New ticket with custom field values', issue.subject
182 182 assert_equal 'PostgreSQL', issue.custom_field_value(1)
183 183 assert_equal 'Value for a custom field', issue.custom_field_value(2)
184 184 assert !issue.description.match(/^searchable field:/i)
185 185 end
186 186
187 187 def test_add_issue_with_version_custom_fields
188 188 field = IssueCustomField.create!(:name => 'Affected version', :field_format => 'version', :is_for_all => true, :tracker_ids => [1,2,3])
189 189
190 190 issue = submit_email('ticket_with_custom_fields.eml', :issue => {:project => 'ecookbook'}) do |email|
191 191 email << "Affected version: 1.0\n"
192 192 end
193 193 assert issue.is_a?(Issue)
194 194 assert !issue.new_record?
195 195 issue.reload
196 196 assert_equal '2', issue.custom_field_value(field)
197 197 end
198 198
199 199 def test_add_issue_should_match_assignee_on_display_name
200 200 user = User.generate!(:firstname => 'Foo Bar', :lastname => 'Foo Baz')
201 201 User.add_to_project(user, Project.find(2))
202 202 issue = submit_email('ticket_on_given_project.eml') do |email|
203 203 email.sub!(/^Assigned to.*$/, 'Assigned to: Foo Bar Foo baz')
204 204 end
205 205 assert issue.is_a?(Issue)
206 206 assert_equal user, issue.assigned_to
207 207 end
208 208
209 209 def test_add_issue_should_set_default_start_date
210 210 with_settings :default_issue_start_date_to_creation_date => '1' do
211 211 issue = submit_email('ticket_with_cc.eml', :issue => {:project => 'ecookbook'})
212 212 assert issue.is_a?(Issue)
213 213 assert_equal Date.today, issue.start_date
214 214 end
215 215 end
216 216
217 217 def test_add_issue_with_cc
218 218 issue = submit_email('ticket_with_cc.eml', :issue => {:project => 'ecookbook'})
219 219 assert issue.is_a?(Issue)
220 220 assert !issue.new_record?
221 221 issue.reload
222 222 assert issue.watched_by?(User.find_by_mail('dlopper@somenet.foo'))
223 223 assert_equal 1, issue.watcher_user_ids.size
224 224 end
225 225
226 226 def test_add_issue_by_unknown_user
227 227 assert_no_difference 'User.count' do
228 228 assert_equal false,
229 229 submit_email(
230 230 'ticket_by_unknown_user.eml',
231 231 :issue => {:project => 'ecookbook'}
232 232 )
233 233 end
234 234 end
235 235
236 236 def test_add_issue_by_anonymous_user
237 237 Role.anonymous.add_permission!(:add_issues)
238 238 assert_no_difference 'User.count' do
239 239 issue = submit_email(
240 240 'ticket_by_unknown_user.eml',
241 241 :issue => {:project => 'ecookbook'},
242 242 :unknown_user => 'accept'
243 243 )
244 244 assert issue.is_a?(Issue)
245 245 assert issue.author.anonymous?
246 246 end
247 247 end
248 248
249 249 def test_add_issue_by_anonymous_user_with_no_from_address
250 250 Role.anonymous.add_permission!(:add_issues)
251 251 assert_no_difference 'User.count' do
252 252 issue = submit_email(
253 253 'ticket_by_empty_user.eml',
254 254 :issue => {:project => 'ecookbook'},
255 255 :unknown_user => 'accept'
256 256 )
257 257 assert issue.is_a?(Issue)
258 258 assert issue.author.anonymous?
259 259 end
260 260 end
261 261
262 262 def test_add_issue_by_anonymous_user_on_private_project
263 263 Role.anonymous.add_permission!(:add_issues)
264 264 assert_no_difference 'User.count' do
265 265 assert_no_difference 'Issue.count' do
266 266 assert_equal false,
267 267 submit_email(
268 268 'ticket_by_unknown_user.eml',
269 269 :issue => {:project => 'onlinestore'},
270 270 :unknown_user => 'accept'
271 271 )
272 272 end
273 273 end
274 274 end
275 275
276 276 def test_add_issue_by_anonymous_user_on_private_project_without_permission_check
277 277 lft1 = new_issue_lft
278 278 assert_no_difference 'User.count' do
279 279 assert_difference 'Issue.count' do
280 280 issue = submit_email(
281 281 'ticket_by_unknown_user.eml',
282 282 :issue => {:project => 'onlinestore'},
283 283 :no_permission_check => '1',
284 284 :unknown_user => 'accept'
285 285 )
286 286 assert issue.is_a?(Issue)
287 287 assert issue.author.anonymous?
288 288 assert !issue.project.is_public?
289 289 assert_equal [issue.id, lft1, lft1 + 1], [issue.root_id, issue.lft, issue.rgt]
290 290 end
291 291 end
292 292 end
293 293
294 294 def test_add_issue_by_created_user
295 295 Setting.default_language = 'en'
296 296 assert_difference 'User.count' do
297 297 issue = submit_email(
298 298 'ticket_by_unknown_user.eml',
299 299 :issue => {:project => 'ecookbook'},
300 300 :unknown_user => 'create'
301 301 )
302 302 assert issue.is_a?(Issue)
303 303 assert issue.author.active?
304 304 assert_equal 'john.doe@somenet.foo', issue.author.mail
305 305 assert_equal 'John', issue.author.firstname
306 306 assert_equal 'Doe', issue.author.lastname
307 307
308 308 # account information
309 309 email = ActionMailer::Base.deliveries.first
310 310 assert_not_nil email
311 311 assert email.subject.include?('account activation')
312 312 login = mail_body(email).match(/\* Login: (.*)$/)[1].strip
313 313 password = mail_body(email).match(/\* Password: (.*)$/)[1].strip
314 314 assert_equal issue.author, User.try_to_login(login, password)
315 315 end
316 316 end
317 317
318 318 def test_created_user_should_be_added_to_groups
319 319 group1 = Group.generate!
320 320 group2 = Group.generate!
321 321
322 322 assert_difference 'User.count' do
323 323 submit_email(
324 324 'ticket_by_unknown_user.eml',
325 325 :issue => {:project => 'ecookbook'},
326 326 :unknown_user => 'create',
327 327 :default_group => "#{group1.name},#{group2.name}"
328 328 )
329 329 end
330 330 user = User.order('id DESC').first
331 331 assert_same_elements [group1, group2], user.groups
332 332 end
333 333
334 334 def test_created_user_should_not_receive_account_information_with_no_account_info_option
335 335 assert_difference 'User.count' do
336 336 submit_email(
337 337 'ticket_by_unknown_user.eml',
338 338 :issue => {:project => 'ecookbook'},
339 339 :unknown_user => 'create',
340 340 :no_account_notice => '1'
341 341 )
342 342 end
343 343
344 344 # only 1 email for the new issue notification
345 345 assert_equal 1, ActionMailer::Base.deliveries.size
346 346 email = ActionMailer::Base.deliveries.first
347 347 assert_include 'Ticket by unknown user', email.subject
348 348 end
349 349
350 350 def test_created_user_should_have_mail_notification_to_none_with_no_notification_option
351 351 assert_difference 'User.count' do
352 352 submit_email(
353 353 'ticket_by_unknown_user.eml',
354 354 :issue => {:project => 'ecookbook'},
355 355 :unknown_user => 'create',
356 356 :no_notification => '1'
357 357 )
358 358 end
359 359 user = User.order('id DESC').first
360 360 assert_equal 'none', user.mail_notification
361 361 end
362 362
363 363 def test_add_issue_without_from_header
364 364 Role.anonymous.add_permission!(:add_issues)
365 365 assert_equal false, submit_email('ticket_without_from_header.eml')
366 366 end
367 367
368 368 def test_add_issue_with_invalid_attributes
369 369 with_settings :default_issue_start_date_to_creation_date => '0' do
370 370 issue = submit_email(
371 371 'ticket_with_invalid_attributes.eml',
372 372 :allow_override => 'tracker,category,priority'
373 373 )
374 374 assert issue.is_a?(Issue)
375 375 assert !issue.new_record?
376 376 issue.reload
377 377 assert_nil issue.assigned_to
378 378 assert_nil issue.start_date
379 379 assert_nil issue.due_date
380 380 assert_equal 0, issue.done_ratio
381 381 assert_equal 'Normal', issue.priority.to_s
382 382 assert issue.description.include?('Lorem ipsum dolor sit amet, consectetuer adipiscing elit.')
383 383 end
384 384 end
385 385
386 386 def test_add_issue_with_invalid_project_should_be_assigned_to_default_project
387 387 issue = submit_email('ticket_on_given_project.eml', :issue => {:project => 'ecookbook'}, :allow_override => 'project') do |email|
388 388 email.gsub!(/^Project:.+$/, 'Project: invalid')
389 389 end
390 390 assert issue.is_a?(Issue)
391 391 assert !issue.new_record?
392 392 assert_equal 'ecookbook', issue.project.identifier
393 393 end
394 394
395 395 def test_add_issue_with_localized_attributes
396 396 User.find_by_mail('jsmith@somenet.foo').update_attribute 'language', 'fr'
397 397 issue = submit_email(
398 398 'ticket_with_localized_attributes.eml',
399 399 :allow_override => 'tracker,category,priority'
400 400 )
401 401 assert issue.is_a?(Issue)
402 402 assert !issue.new_record?
403 403 issue.reload
404 404 assert_equal 'New ticket on a given project', issue.subject
405 405 assert_equal User.find_by_login('jsmith'), issue.author
406 406 assert_equal Project.find(2), issue.project
407 407 assert_equal 'Feature request', issue.tracker.to_s
408 408 assert_equal 'Stock management', issue.category.to_s
409 409 assert_equal 'Urgent', issue.priority.to_s
410 410 assert issue.description.include?('Lorem ipsum dolor sit amet, consectetuer adipiscing elit.')
411 411 end
412 412
413 413 def test_add_issue_with_japanese_keywords
414 414 ja_dev = "\xe9\x96\x8b\xe7\x99\xba"
415 415 ja_dev.force_encoding('UTF-8') if ja_dev.respond_to?(:force_encoding)
416 416 tracker = Tracker.create!(:name => ja_dev)
417 417 Project.find(1).trackers << tracker
418 418 issue = submit_email(
419 419 'japanese_keywords_iso_2022_jp.eml',
420 420 :issue => {:project => 'ecookbook'},
421 421 :allow_override => 'tracker'
422 422 )
423 423 assert_kind_of Issue, issue
424 424 assert_equal tracker, issue.tracker
425 425 end
426 426
427 427 def test_add_issue_from_apple_mail
428 428 issue = submit_email(
429 429 'apple_mail_with_attachment.eml',
430 430 :issue => {:project => 'ecookbook'}
431 431 )
432 432 assert_kind_of Issue, issue
433 433 assert_equal 1, issue.attachments.size
434 434
435 435 attachment = issue.attachments.first
436 436 assert_equal 'paella.jpg', attachment.filename
437 437 assert_equal 10790, attachment.filesize
438 438 assert File.exist?(attachment.diskfile)
439 439 assert_equal 10790, File.size(attachment.diskfile)
440 440 assert_equal 'caaf384198bcbc9563ab5c058acd73cd', attachment.digest
441 441 end
442 442
443 443 def test_thunderbird_with_attachment_ja
444 444 issue = submit_email(
445 445 'thunderbird_with_attachment_ja.eml',
446 446 :issue => {:project => 'ecookbook'}
447 447 )
448 448 assert_kind_of Issue, issue
449 449 assert_equal 1, issue.attachments.size
450 450 ja = "\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88.txt"
451 451 ja.force_encoding('UTF-8') if ja.respond_to?(:force_encoding)
452 452 attachment = issue.attachments.first
453 453 assert_equal ja, attachment.filename
454 454 assert_equal 5, attachment.filesize
455 455 assert File.exist?(attachment.diskfile)
456 456 assert_equal 5, File.size(attachment.diskfile)
457 457 assert_equal 'd8e8fca2dc0f896fd7cb4cb0031ba249', attachment.digest
458 458 end
459 459
460 460 def test_gmail_with_attachment_ja
461 461 issue = submit_email(
462 462 'gmail_with_attachment_ja.eml',
463 463 :issue => {:project => 'ecookbook'}
464 464 )
465 465 assert_kind_of Issue, issue
466 466 assert_equal 1, issue.attachments.size
467 467 ja = "\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88.txt"
468 468 ja.force_encoding('UTF-8') if ja.respond_to?(:force_encoding)
469 469 attachment = issue.attachments.first
470 470 assert_equal ja, attachment.filename
471 471 assert_equal 5, attachment.filesize
472 472 assert File.exist?(attachment.diskfile)
473 473 assert_equal 5, File.size(attachment.diskfile)
474 474 assert_equal 'd8e8fca2dc0f896fd7cb4cb0031ba249', attachment.digest
475 475 end
476 476
477 477 def test_thunderbird_with_attachment_latin1
478 478 issue = submit_email(
479 479 'thunderbird_with_attachment_iso-8859-1.eml',
480 480 :issue => {:project => 'ecookbook'}
481 481 )
482 482 assert_kind_of Issue, issue
483 483 assert_equal 1, issue.attachments.size
484 484 u = ""
485 485 u.force_encoding('UTF-8') if u.respond_to?(:force_encoding)
486 486 u1 = "\xc3\x84\xc3\xa4\xc3\x96\xc3\xb6\xc3\x9c\xc3\xbc"
487 487 u1.force_encoding('UTF-8') if u1.respond_to?(:force_encoding)
488 488 11.times { u << u1 }
489 489 attachment = issue.attachments.first
490 490 assert_equal "#{u}.png", attachment.filename
491 491 assert_equal 130, attachment.filesize
492 492 assert File.exist?(attachment.diskfile)
493 493 assert_equal 130, File.size(attachment.diskfile)
494 494 assert_equal '4d80e667ac37dddfe05502530f152abb', attachment.digest
495 495 end
496 496
497 497 def test_gmail_with_attachment_latin1
498 498 issue = submit_email(
499 499 'gmail_with_attachment_iso-8859-1.eml',
500 500 :issue => {:project => 'ecookbook'}
501 501 )
502 502 assert_kind_of Issue, issue
503 503 assert_equal 1, issue.attachments.size
504 504 u = ""
505 505 u.force_encoding('UTF-8') if u.respond_to?(:force_encoding)
506 506 u1 = "\xc3\x84\xc3\xa4\xc3\x96\xc3\xb6\xc3\x9c\xc3\xbc"
507 507 u1.force_encoding('UTF-8') if u1.respond_to?(:force_encoding)
508 508 11.times { u << u1 }
509 509 attachment = issue.attachments.first
510 510 assert_equal "#{u}.txt", attachment.filename
511 511 assert_equal 5, attachment.filesize
512 512 assert File.exist?(attachment.diskfile)
513 513 assert_equal 5, File.size(attachment.diskfile)
514 514 assert_equal 'd8e8fca2dc0f896fd7cb4cb0031ba249', attachment.digest
515 515 end
516 516
517 517 def test_multiple_inline_text_parts_should_be_appended_to_issue_description
518 518 issue = submit_email('multiple_text_parts.eml', :issue => {:project => 'ecookbook'})
519 519 assert_include 'first', issue.description
520 520 assert_include 'second', issue.description
521 521 assert_include 'third', issue.description
522 522 end
523 523
524 524 def test_attachment_text_part_should_be_added_as_issue_attachment
525 525 issue = submit_email('multiple_text_parts.eml', :issue => {:project => 'ecookbook'})
526 526 assert_not_include 'Plain text attachment', issue.description
527 527 attachment = issue.attachments.detect {|a| a.filename == 'textfile.txt'}
528 528 assert_not_nil attachment
529 529 assert_include 'Plain text attachment', File.read(attachment.diskfile)
530 530 end
531 531
532 532 def test_add_issue_with_iso_8859_1_subject
533 533 issue = submit_email(
534 534 'subject_as_iso-8859-1.eml',
535 535 :issue => {:project => 'ecookbook'}
536 536 )
537 537 str = "Testmail from Webmail: \xc3\xa4 \xc3\xb6 \xc3\xbc..."
538 538 str.force_encoding('UTF-8') if str.respond_to?(:force_encoding)
539 539 assert_kind_of Issue, issue
540 540 assert_equal str, issue.subject
541 541 end
542 542
543 543 def test_quoted_printable_utf8
544 544 issue = submit_email(
545 545 'quoted_printable_utf8.eml',
546 546 :issue => {:project => 'ecookbook'}
547 547 )
548 548 assert_kind_of Issue, issue
549 549 str = "Freundliche Gr\xc3\xbcsse"
550 550 str.force_encoding('UTF-8') if str.respond_to?(:force_encoding)
551 551 assert_equal str, issue.description
552 552 end
553 553
554 554 def test_gmail_iso8859_2
555 555 issue = submit_email(
556 556 'gmail-iso8859-2.eml',
557 557 :issue => {:project => 'ecookbook'}
558 558 )
559 559 assert_kind_of Issue, issue
560 560 str = "Na \xc5\xa1triku se su\xc5\xa1i \xc5\xa1osi\xc4\x87."
561 561 str.force_encoding('UTF-8') if str.respond_to?(:force_encoding)
562 562 assert issue.description.include?(str)
563 563 end
564 564
565 565 def test_add_issue_with_japanese_subject
566 566 issue = submit_email(
567 567 'subject_japanese_1.eml',
568 568 :issue => {:project => 'ecookbook'}
569 569 )
570 570 assert_kind_of Issue, issue
571 571 ja = "\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88"
572 572 ja.force_encoding('UTF-8') if ja.respond_to?(:force_encoding)
573 573 assert_equal ja, issue.subject
574 574 end
575 575
576 576 def test_add_issue_with_korean_body
577 577 # Make sure mail bodies with a charset unknown to Ruby
578 578 # but known to the Mail gem 2.5.4 are handled correctly
579 579 kr = "\xEA\xB3\xA0\xEB\xA7\x99\xEC\x8A\xB5\xEB\x8B\x88\xEB\x8B\xA4."
580 580 if !kr.respond_to?(:force_encoding)
581 581 puts "\nOn Ruby 1.8, skip Korean encoding mail body test"
582 582 else
583 583 kr.force_encoding('UTF-8')
584 584 issue = submit_email(
585 585 'body_ks_c_5601-1987.eml',
586 586 :issue => {:project => 'ecookbook'}
587 587 )
588 588 assert_kind_of Issue, issue
589 589 assert_equal kr, issue.description
590 590 end
591 591 end
592 592
593 593 def test_add_issue_with_no_subject_header
594 594 issue = submit_email(
595 595 'no_subject_header.eml',
596 596 :issue => {:project => 'ecookbook'}
597 597 )
598 598 assert_kind_of Issue, issue
599 599 assert_equal '(no subject)', issue.subject
600 600 end
601 601
602 602 def test_add_issue_with_mixed_japanese_subject
603 603 issue = submit_email(
604 604 'subject_japanese_2.eml',
605 605 :issue => {:project => 'ecookbook'}
606 606 )
607 607 assert_kind_of Issue, issue
608 608 ja = "Re: \xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88"
609 609 ja.force_encoding('UTF-8') if ja.respond_to?(:force_encoding)
610 610 assert_equal ja, issue.subject
611 611 end
612 612
613 613 def test_should_ignore_emails_from_locked_users
614 614 User.find(2).lock!
615 615
616 616 MailHandler.any_instance.expects(:dispatch).never
617 617 assert_no_difference 'Issue.count' do
618 618 assert_equal false, submit_email('ticket_on_given_project.eml')
619 619 end
620 620 end
621 621
622 622 def test_should_ignore_emails_from_emission_address
623 623 Role.anonymous.add_permission!(:add_issues)
624 624 assert_no_difference 'User.count' do
625 625 assert_equal false,
626 626 submit_email(
627 627 'ticket_from_emission_address.eml',
628 628 :issue => {:project => 'ecookbook'},
629 629 :unknown_user => 'create'
630 630 )
631 631 end
632 632 end
633 633
634 634 def test_should_ignore_auto_replied_emails
635 635 MailHandler.any_instance.expects(:dispatch).never
636 636 [
637 637 "X-Auto-Response-Suppress: OOF",
638 638 "Auto-Submitted: auto-replied",
639 639 "Auto-Submitted: Auto-Replied",
640 640 "Auto-Submitted: auto-generated"
641 641 ].each do |header|
642 642 raw = IO.read(File.join(FIXTURES_PATH, 'ticket_on_given_project.eml'))
643 643 raw = header + "\n" + raw
644 644
645 645 assert_no_difference 'Issue.count' do
646 646 assert_equal false, MailHandler.receive(raw), "email with #{header} header was not ignored"
647 647 end
648 648 end
649 649 end
650 650
651 651 test "should not ignore Auto-Submitted headers not defined in RFC3834" do
652 652 [
653 653 "Auto-Submitted: auto-forwarded"
654 654 ].each do |header|
655 655 raw = IO.read(File.join(FIXTURES_PATH, 'ticket_on_given_project.eml'))
656 656 raw = header + "\n" + raw
657 657
658 658 assert_difference 'Issue.count', 1 do
659 659 assert_not_nil MailHandler.receive(raw), "email with #{header} header was ignored"
660 660 end
661 661 end
662 662 end
663 663
664 664 def test_add_issue_should_send_email_notification
665 665 Setting.notified_events = ['issue_added']
666 666 ActionMailer::Base.deliveries.clear
667 667 # This email contains: 'Project: onlinestore'
668 668 issue = submit_email('ticket_on_given_project.eml')
669 669 assert issue.is_a?(Issue)
670 670 assert_equal 1, ActionMailer::Base.deliveries.size
671 671 end
672 672
673 673 def test_update_issue
674 674 journal = submit_email('ticket_reply.eml')
675 675 assert journal.is_a?(Journal)
676 676 assert_equal User.find_by_login('jsmith'), journal.user
677 677 assert_equal Issue.find(2), journal.journalized
678 678 assert_match /This is reply/, journal.notes
679 679 assert_equal false, journal.private_notes
680 680 assert_equal 'Feature request', journal.issue.tracker.name
681 681 end
682 682
683 683 def test_update_issue_with_attribute_changes
684 684 # This email contains: 'Status: Resolved'
685 685 journal = submit_email('ticket_reply_with_status.eml')
686 686 assert journal.is_a?(Journal)
687 687 issue = Issue.find(journal.issue.id)
688 688 assert_equal User.find_by_login('jsmith'), journal.user
689 689 assert_equal Issue.find(2), journal.journalized
690 690 assert_match /This is reply/, journal.notes
691 691 assert_equal 'Feature request', journal.issue.tracker.name
692 692 assert_equal IssueStatus.find_by_name("Resolved"), issue.status
693 693 assert_equal '2010-01-01', issue.start_date.to_s
694 694 assert_equal '2010-12-31', issue.due_date.to_s
695 695 assert_equal User.find_by_login('jsmith'), issue.assigned_to
696 696 assert_equal "52.6", issue.custom_value_for(CustomField.find_by_name('Float field')).value
697 697 # keywords should be removed from the email body
698 698 assert !journal.notes.match(/^Status:/i)
699 699 assert !journal.notes.match(/^Start Date:/i)
700 700 end
701 701
702 702 def test_update_issue_with_attachment
703 703 assert_difference 'Journal.count' do
704 704 assert_difference 'JournalDetail.count' do
705 705 assert_difference 'Attachment.count' do
706 706 assert_no_difference 'Issue.count' do
707 707 journal = submit_email('ticket_with_attachment.eml') do |raw|
708 708 raw.gsub! /^Subject: .*$/, 'Subject: Re: [Cookbook - Feature #2] (New) Add ingredients categories'
709 709 end
710 710 end
711 711 end
712 712 end
713 713 end
714 714 journal = Journal.order('id DESC').first
715 715 assert_equal Issue.find(2), journal.journalized
716 716 assert_equal 1, journal.details.size
717 717
718 718 detail = journal.details.first
719 719 assert_equal 'attachment', detail.property
720 720 assert_equal 'Paella.jpg', detail.value
721 721 end
722 722
723 723 def test_update_issue_should_send_email_notification
724 724 ActionMailer::Base.deliveries.clear
725 725 journal = submit_email('ticket_reply.eml')
726 726 assert journal.is_a?(Journal)
727 727 assert_equal 1, ActionMailer::Base.deliveries.size
728 728 end
729 729
730 730 def test_update_issue_should_not_set_defaults
731 731 journal = submit_email(
732 732 'ticket_reply.eml',
733 733 :issue => {:tracker => 'Support request', :priority => 'High'}
734 734 )
735 735 assert journal.is_a?(Journal)
736 736 assert_match /This is reply/, journal.notes
737 737 assert_equal 'Feature request', journal.issue.tracker.name
738 738 assert_equal 'Normal', journal.issue.priority.name
739 739 end
740 740
741 741 def test_replying_to_a_private_note_should_add_reply_as_private
742 742 private_journal = Journal.create!(:notes => 'Private notes', :journalized => Issue.find(1), :private_notes => true, :user_id => 2)
743 743
744 744 assert_difference 'Journal.count' do
745 745 journal = submit_email('ticket_reply.eml') do |email|
746 746 email.sub! %r{^In-Reply-To:.*$}, "In-Reply-To: <redmine.journal-#{private_journal.id}.20060719210421@osiris>"
747 747 end
748 748
749 749 assert_kind_of Journal, journal
750 750 assert_match /This is reply/, journal.notes
751 751 assert_equal true, journal.private_notes
752 752 end
753 753 end
754 754
755 755 def test_reply_to_a_message
756 756 m = submit_email('message_reply.eml')
757 757 assert m.is_a?(Message)
758 758 assert !m.new_record?
759 759 m.reload
760 760 assert_equal 'Reply via email', m.subject
761 761 # The email replies to message #2 which is part of the thread of message #1
762 762 assert_equal Message.find(1), m.parent
763 763 end
764 764
765 765 def test_reply_to_a_message_by_subject
766 766 m = submit_email('message_reply_by_subject.eml')
767 767 assert m.is_a?(Message)
768 768 assert !m.new_record?
769 769 m.reload
770 770 assert_equal 'Reply to the first post', m.subject
771 771 assert_equal Message.find(1), m.parent
772 772 end
773 773
774 774 def test_should_strip_tags_of_html_only_emails
775 775 issue = submit_email('ticket_html_only.eml', :issue => {:project => 'ecookbook'})
776 776 assert issue.is_a?(Issue)
777 777 assert !issue.new_record?
778 778 issue.reload
779 779 assert_equal 'HTML email', issue.subject
780 780 assert_equal 'This is a html-only email.', issue.description
781 781 end
782 782
783 783 test "truncate emails with no setting should add the entire email into the issue" do
784 784 with_settings :mail_handler_body_delimiters => '' do
785 785 issue = submit_email('ticket_on_given_project.eml')
786 786 assert_issue_created(issue)
787 787 assert issue.description.include?('---')
788 788 assert issue.description.include?('This paragraph is after the delimiter')
789 789 end
790 790 end
791 791
792 792 test "truncate emails with a single string should truncate the email at the delimiter for the issue" do
793 793 with_settings :mail_handler_body_delimiters => '---' do
794 794 issue = submit_email('ticket_on_given_project.eml')
795 795 assert_issue_created(issue)
796 796 assert issue.description.include?('This paragraph is before delimiters')
797 797 assert issue.description.include?('--- This line starts with a delimiter')
798 798 assert !issue.description.match(/^---$/)
799 799 assert !issue.description.include?('This paragraph is after the delimiter')
800 800 end
801 801 end
802 802
803 803 test "truncate emails with a single quoted reply should truncate the email at the delimiter with the quoted reply symbols (>)" do
804 804 with_settings :mail_handler_body_delimiters => '--- Reply above. Do not remove this line. ---' do
805 805 journal = submit_email('issue_update_with_quoted_reply_above.eml')
806 806 assert journal.is_a?(Journal)
807 807 assert journal.notes.include?('An update to the issue by the sender.')
808 808 assert !journal.notes.match(Regexp.escape("--- Reply above. Do not remove this line. ---"))
809 809 assert !journal.notes.include?('Looks like the JSON api for projects was missed.')
810 810 end
811 811 end
812 812
813 813 test "truncate emails with multiple quoted replies should truncate the email at the delimiter with the quoted reply symbols (>)" do
814 814 with_settings :mail_handler_body_delimiters => '--- Reply above. Do not remove this line. ---' do
815 815 journal = submit_email('issue_update_with_multiple_quoted_reply_above.eml')
816 816 assert journal.is_a?(Journal)
817 817 assert journal.notes.include?('An update to the issue by the sender.')
818 818 assert !journal.notes.match(Regexp.escape("--- Reply above. Do not remove this line. ---"))
819 819 assert !journal.notes.include?('Looks like the JSON api for projects was missed.')
820 820 end
821 821 end
822 822
823 823 test "truncate emails with multiple strings should truncate the email at the first delimiter found (BREAK)" do
824 824 with_settings :mail_handler_body_delimiters => "---\nBREAK" do
825 825 issue = submit_email('ticket_on_given_project.eml')
826 826 assert_issue_created(issue)
827 827 assert issue.description.include?('This paragraph is before delimiters')
828 828 assert !issue.description.include?('BREAK')
829 829 assert !issue.description.include?('This paragraph is between delimiters')
830 830 assert !issue.description.match(/^---$/)
831 831 assert !issue.description.include?('This paragraph is after the delimiter')
832 832 end
833 833 end
834 834
835 835 def test_attachments_that_match_mail_handler_excluded_filenames_should_be_ignored
836 836 with_settings :mail_handler_excluded_filenames => '*.vcf, *.jpg' do
837 837 issue = submit_email('ticket_with_attachment.eml', :issue => {:project => 'onlinestore'})
838 838 assert issue.is_a?(Issue)
839 839 assert !issue.new_record?
840 840 assert_equal 0, issue.reload.attachments.size
841 841 end
842 842 end
843 843
844 844 def test_attachments_that_do_not_match_mail_handler_excluded_filenames_should_be_attached
845 845 with_settings :mail_handler_excluded_filenames => '*.vcf, *.gif' do
846 846 issue = submit_email('ticket_with_attachment.eml', :issue => {:project => 'onlinestore'})
847 847 assert issue.is_a?(Issue)
848 848 assert !issue.new_record?
849 849 assert_equal 1, issue.reload.attachments.size
850 850 end
851 851 end
852 852
853 853 def test_email_with_long_subject_line
854 854 issue = submit_email('ticket_with_long_subject.eml')
855 855 assert issue.is_a?(Issue)
856 856 assert_equal issue.subject, 'New ticket on a given project with a very long subject line which exceeds 255 chars and should not be ignored but chopped off. And if the subject line is still not long enough, we just add more text. And more text. Wow, this is really annoying. Especially, if you have nothing to say...'[0,255]
857 857 end
858 858
859 def test_first_keyword_should_be_matched
860 issue = submit_email('ticket_with_duplicate_keyword.eml', :allow_override => 'priority')
861 assert issue.is_a?(Issue)
862 assert_equal 'High', issue.priority.name
863 end
864
865 def test_keyword_after_delimiter_should_be_ignored
866 with_settings :mail_handler_body_delimiters => "== DELIMITER ==" do
867 issue = submit_email('ticket_with_keyword_after_delimiter.eml', :allow_override => 'priority')
868 assert issue.is_a?(Issue)
869 assert_equal 'Normal', issue.priority.name
870 end
871 end
872
859 873 def test_new_user_from_attributes_should_return_valid_user
860 874 to_test = {
861 875 # [address, name] => [login, firstname, lastname]
862 876 ['jsmith@example.net', nil] => ['jsmith@example.net', 'jsmith', '-'],
863 877 ['jsmith@example.net', 'John'] => ['jsmith@example.net', 'John', '-'],
864 878 ['jsmith@example.net', 'John Smith'] => ['jsmith@example.net', 'John', 'Smith'],
865 879 ['jsmith@example.net', 'John Paul Smith'] => ['jsmith@example.net', 'John', 'Paul Smith'],
866 880 ['jsmith@example.net', 'AVeryLongFirstnameThatExceedsTheMaximumLength Smith'] => ['jsmith@example.net', 'AVeryLongFirstnameThatExceedsT', 'Smith'],
867 881 ['jsmith@example.net', 'John AVeryLongLastnameThatExceedsTheMaximumLength'] => ['jsmith@example.net', 'John', 'AVeryLongLastnameThatExceedsTh']
868 882 }
869 883
870 884 to_test.each do |attrs, expected|
871 885 user = MailHandler.new_user_from_attributes(attrs.first, attrs.last)
872 886
873 887 assert user.valid?, user.errors.full_messages.to_s
874 888 assert_equal attrs.first, user.mail
875 889 assert_equal expected[0], user.login
876 890 assert_equal expected[1], user.firstname
877 891 assert_equal expected[2], user.lastname
878 892 assert_equal 'only_my_events', user.mail_notification
879 893 end
880 894 end
881 895
882 896 def test_new_user_from_attributes_should_use_default_login_if_invalid
883 897 user = MailHandler.new_user_from_attributes('foo+bar@example.net')
884 898 assert user.valid?
885 899 assert user.login =~ /^user[a-f0-9]+$/
886 900 assert_equal 'foo+bar@example.net', user.mail
887 901 end
888 902
889 903 def test_new_user_with_utf8_encoded_fullname_should_be_decoded
890 904 assert_difference 'User.count' do
891 905 issue = submit_email(
892 906 'fullname_of_sender_as_utf8_encoded.eml',
893 907 :issue => {:project => 'ecookbook'},
894 908 :unknown_user => 'create'
895 909 )
896 910 end
897 911 user = User.order('id DESC').first
898 912 assert_equal "foo@example.org", user.mail
899 913 str1 = "\xc3\x84\xc3\xa4"
900 914 str2 = "\xc3\x96\xc3\xb6"
901 915 str1.force_encoding('UTF-8') if str1.respond_to?(:force_encoding)
902 916 str2.force_encoding('UTF-8') if str2.respond_to?(:force_encoding)
903 917 assert_equal str1, user.firstname
904 918 assert_equal str2, user.lastname
905 919 end
906 920
907 921 def test_extract_options_from_env_should_return_options
908 922 options = MailHandler.extract_options_from_env({
909 923 'tracker' => 'defect',
910 924 'project' => 'foo',
911 925 'unknown_user' => 'create'
912 926 })
913 927
914 928 assert_equal({
915 929 :issue => {:tracker => 'defect', :project => 'foo'},
916 930 :unknown_user => 'create'
917 931 }, options)
918 932 end
919 933
920 934 private
921 935
922 936 def submit_email(filename, options={})
923 937 raw = IO.read(File.join(FIXTURES_PATH, filename))
924 938 yield raw if block_given?
925 939 MailHandler.receive(raw, options)
926 940 end
927 941
928 942 def assert_issue_created(issue)
929 943 assert issue.is_a?(Issue)
930 944 assert !issue.new_record?
931 945 issue.reload
932 946 end
933 947 end
General Comments 0
You need to be logged in to leave comments. Login now