upload_cache.rb 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. # A wrapper class around Store that handles temporary attachment uploads
  3. # and provides an interface for those.
  4. class UploadCache
  5. attr_reader :id
  6. # Initializes a UploadCache for a given form_id.
  7. #
  8. # @example
  9. # cache = UploadCache.new(form_id)
  10. #
  11. # @return [UploadCache]
  12. def initialize(id)
  13. # conversion to Integer is required for proper Store#o_id comparsion
  14. @id = id.to_i
  15. end
  16. # Adds a Store item with the given attributes for the form_id.
  17. #
  18. # @see Store#create!
  19. #
  20. # @example
  21. # cache = UploadCache.new(form_id)
  22. # store = cache.add(
  23. # filename: file.original_filename,
  24. # data: file.read,
  25. # preferences: {
  26. # 'Content-Type' => 'application/octet-stream'
  27. # }
  28. # )
  29. #
  30. # @return [Store] the created Store item
  31. def add(args)
  32. Store.create!(
  33. args.merge(
  34. object: store_object,
  35. o_id: id,
  36. )
  37. )
  38. end
  39. # Provides all Store items associated to the form_id.
  40. #
  41. # @see Store#list
  42. #
  43. # @example
  44. # attachments = UploadCache.new(form_id).attachments
  45. #
  46. # @return [Array<Store>] an enumerator of Store items
  47. def attachments
  48. Store.list(
  49. object: store_object,
  50. o_id: id,
  51. )
  52. end
  53. # Removes all Store items associated to the form_id.
  54. #
  55. # @see Store#remove
  56. #
  57. # @example
  58. # UploadCache.new(form_id).destroy
  59. #
  60. def destroy
  61. Store.remove(
  62. object: store_object,
  63. o_id: id,
  64. )
  65. end
  66. # Removes all Store items associated to the form_id.
  67. #
  68. # @see Store#remove
  69. #
  70. # @example
  71. # UploadCache.new(form_id).remove_item(store_id)
  72. #
  73. # @raise [Exceptions::UnprocessableEntity] in cases where a Store item should get deleted that is not an UploadCache item
  74. #
  75. def remove_item(store_id = nil)
  76. store = Store.find(store_id)
  77. if store.o_id != id || store.store_object_id != store_object_id
  78. raise Exceptions::UnprocessableEntity, "Attempt to delete Store item #{store_id} that is not bound to UploadCache object"
  79. end
  80. Store.remove_item(store_id)
  81. end
  82. private
  83. def store_object
  84. self.class.name
  85. end
  86. def store_object_id
  87. Store::Object.lookup(name: store_object).id
  88. end
  89. end