handler_retry.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class SecureMailing::Backend::HandlerRetry < SecureMailing::Backend::Handler
  3. attr_reader :article
  4. def initialize(article)
  5. super()
  6. @article = article
  7. end
  8. def process
  9. return existing_result if already_processed?
  10. save_result if retry_succeeded?
  11. retry_result
  12. end
  13. def signature_checked?
  14. @signature_checked ||= existing_result&.dig('sign', 'success') || false
  15. end
  16. def decrypted?
  17. @decrypted ||= existing_result&.dig('encryption', 'success') || false
  18. end
  19. def already_processed?
  20. signature_checked? && decrypted?
  21. end
  22. def existing_result
  23. article.preferences['security']
  24. end
  25. def mail
  26. @mail ||= begin
  27. raw_mail = article.as_raw.store_file.content
  28. Channel::EmailParser.new.parse(raw_mail).tap do |parsed|
  29. SecureMailing.incoming(parsed)
  30. end
  31. end
  32. end
  33. def retry_result
  34. @retry_result ||= mail['x-zammad-article-preferences']['security']
  35. end
  36. def signature_found?
  37. return false if signature_checked?
  38. retry_result['sign']['success']
  39. end
  40. def decryption_succeeded?
  41. return false if decrypted?
  42. retry_result['encryption']['success']
  43. end
  44. def retry_succeeded?
  45. return true if signature_found?
  46. decryption_succeeded?
  47. end
  48. def save_result
  49. save_decrypted if decryption_succeeded?
  50. article.preferences['security'] = retry_result
  51. article.save!
  52. end
  53. def save_decrypted
  54. article.content_type = mail['content_type']
  55. article.body = mail['body']
  56. store_cleanup
  57. store_attachments
  58. end
  59. private
  60. def store_cleanup
  61. Store.remove(
  62. object: 'Ticket::Article',
  63. o_id: article.id,
  64. )
  65. end
  66. def store_attachments
  67. mail[:attachments]&.each do |attachment|
  68. filename = attachment[:filename].force_encoding('utf-8')
  69. if !filename.force_encoding('UTF-8').valid_encoding?
  70. filename = filename.utf8_encode(fallback: :read_as_sanitized_binary)
  71. end
  72. Store.create!(
  73. object: 'Ticket::Article',
  74. o_id: article.id,
  75. data: attachment[:data],
  76. filename: filename,
  77. preferences: attachment[:preferences],
  78. created_by_id: article.created_by_id,
  79. )
  80. end
  81. end
  82. end