folder.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. module Import
  3. class Exchange
  4. class Folder
  5. include ::Mixin::RailsLogger
  6. DEFAULT_ROOTS = %i[root msgfolderroot publicfoldersroot].freeze
  7. def initialize(connection)
  8. @connection = connection
  9. @lookup_map = {}
  10. end
  11. def id_folder_map
  12. @id_folder_map ||= all.index_by(&:id)
  13. # duplicate object to avoid errors where keys get
  14. # added via #get_folder while iterating over
  15. # the result of this method
  16. @lookup_map = @id_folder_map.dup
  17. @id_folder_map
  18. end
  19. def find(id)
  20. @lookup_map[id] ||= @connection.get_folder(id)
  21. end
  22. def all
  23. @all ||= children(*DEFAULT_ROOTS)
  24. end
  25. def children(*parents)
  26. return [] if parents.empty?
  27. direct_descendants = parents.map { |parent| request_children(parent) }
  28. .flatten.uniq.compact
  29. direct_descendants | children(*direct_descendants)
  30. end
  31. def display_path(folder)
  32. display_name = folder.display_name.utf8_encode(fallback: :read_as_sanitized_binary)
  33. parent_folder = id_folder_map[folder.parent_folder_id]
  34. return display_name if parent_folder.blank?
  35. "#{display_path(parent_folder)} -> #{display_name}"
  36. rescue Viewpoint::EWS::EwsError
  37. display_name
  38. end
  39. private
  40. def request_children(parent)
  41. parent = parent.id if parent.respond_to?(:id) # type coercion
  42. @connection.folders(root: parent)
  43. rescue Viewpoint::EWS::EwsFolderNotFound => e
  44. logger.warn("Try to get children folders of: #{parent.inspect}")
  45. logger.warn(e)
  46. nil
  47. end
  48. end
  49. end
  50. end