folder.rb 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. require_dependency 'mixin/rails_logger'
  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(&method(:request_children))
  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(e) && return
  45. end
  46. end
  47. end
  48. end