article_customer.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module Import
  3. module OTRS
  4. class ArticleCustomer
  5. include Import::Helper
  6. def initialize(article)
  7. import(article)
  8. rescue Exceptions::UnprocessableEntity
  9. log "ERROR: Can't extract customer from Article #{article[:id]}"
  10. end
  11. def self.mutex
  12. @mutex ||= Mutex.new
  13. end
  14. class << self
  15. def find(article)
  16. email = local_email(article['From'])
  17. return if !email
  18. user = ::User.find_by(email: email)
  19. user ||= ::User.find_by(login: email)
  20. user
  21. end
  22. def local_email(from)
  23. # TODO: should get unified with User#check_email
  24. email = extract_email(from)
  25. return if !email
  26. email.downcase
  27. end
  28. private
  29. def extract_email(from)
  30. Mail::Address.new(from).address
  31. rescue
  32. return from if from !~ %r{<\s*([^>]+)}
  33. $1.strip
  34. end
  35. end
  36. private
  37. def import(article)
  38. find_or_create(article)
  39. end
  40. def find_or_create(article)
  41. self.class.mutex.synchronize do
  42. return if self.class.find(article)
  43. create(article)
  44. end
  45. end
  46. def create(article)
  47. email = self.class.local_email(article['From'])
  48. ::User.create(
  49. login: email,
  50. firstname: extract_display_name(article['From']),
  51. lastname: '',
  52. email: email,
  53. password: '',
  54. active: true,
  55. role_ids: roles,
  56. updated_by_id: 1,
  57. created_by_id: 1,
  58. )
  59. end
  60. def roles
  61. [
  62. Role.find_by(name: 'Customer').id
  63. ]
  64. end
  65. def extract_display_name(from)
  66. # do extra decoding because we needed to use field.value
  67. Mail::Field.new('X-From', parsed_display_name(from)).to_s
  68. end
  69. def parsed_display_name(from)
  70. parsed_address = Mail::Address.new(from)
  71. return parsed_address.display_name if parsed_address.display_name
  72. return from if parsed_address.comments.blank?
  73. parsed_address.comments[0]
  74. rescue
  75. from
  76. end
  77. end
  78. end
  79. end