attachments_controller.rb 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class AttachmentsController < ApplicationController
  3. include CalendarPreview
  4. prepend_before_action :authorize!, only: %i[show destroy]
  5. prepend_before_action :authentication_check, except: %i[show destroy]
  6. prepend_before_action :authentication_check_only, only: %i[show destroy]
  7. def show
  8. return render_calendar_preview if params[:preview].present? && params[:type] == 'calendar'
  9. view_type = params[:preview] ? 'preview' : nil
  10. send_data(
  11. download_file.content(view_type),
  12. filename: download_file.filename,
  13. type: download_file.content_type,
  14. disposition: download_file.disposition
  15. )
  16. end
  17. def create
  18. file = params[:File]
  19. content_type = file.content_type
  20. if !content_type || content_type == 'application/octet-stream'
  21. content_type = if MIME::Types.type_for(file.original_filename).first
  22. MIME::Types.type_for(file.original_filename).first.content_type
  23. else
  24. 'application/octet-stream'
  25. end
  26. end
  27. headers_store = {
  28. 'Content-Type' => content_type
  29. }
  30. store = Store.create!(
  31. object: 'UploadCache',
  32. o_id: params[:form_id],
  33. data: file.read,
  34. filename: file.original_filename,
  35. preferences: headers_store
  36. )
  37. render json: {
  38. success: true,
  39. data: {
  40. id: store.id,
  41. filename: file.original_filename,
  42. size: store.size,
  43. contentType: store.preferences['Content-Type']
  44. }
  45. }
  46. end
  47. def destroy
  48. Store.remove_item(download_file.id)
  49. render json: {
  50. success: true,
  51. }
  52. end
  53. def destroy_form
  54. Store.remove(
  55. object: 'UploadCache',
  56. o_id: params[:form_id],
  57. )
  58. render json: {
  59. success: true,
  60. }
  61. end
  62. private
  63. def render_calendar_preview
  64. data = parse_calendar(download_file)
  65. render json: data, status: :ok
  66. rescue => e
  67. logger.error e
  68. render json: { error: e.message }, status: :unprocessable_entity
  69. end
  70. def user_not_authorized(e)
  71. not_found(e)
  72. end
  73. end