Skip to content

Commit

Permalink
Add content-type and filename params for file upload
Browse files Browse the repository at this point in the history
  • Loading branch information
MrRTi committed Sep 20, 2023
1 parent 7441bde commit dbeae1b
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
13 changes: 11 additions & 2 deletions lib/rocket_chat/messages/room.rb
Original file line number Diff line number Diff line change
Expand Up @@ -316,10 +316,11 @@ def members(room_id: nil, name: nil, offset: nil, count: nil, sort: nil)
#
# https://developer.rocket.chat/reference/api/rest-api/endpoints/rooms-endpoints/upload-file-to-a-room
def upload_file(room_id:, file:, **rest_params)
form_data = file_upload_hash(file: file, **rest_params)
response = session.request_json(
"#{API_PREFIX}/rooms.upload/#{room_id}",
method: :post,
form_data: file_upload_hash(file: file, **rest_params)
form_data: form_data
)

RocketChat::Message.new response['message'] if response['success']
Expand Down Expand Up @@ -347,7 +348,15 @@ def validate_attribute(attribute)

def file_upload_hash(**params)
permited_keys_for_file_upload = %i[file msg description tmid]
Util.slice_hash(params, *permited_keys_for_file_upload)
hash = Util.slice_hash(params, *permited_keys_for_file_upload)

# NOTE: https://www.rubydoc.info/github/ruby/ruby/Net/HTTPHeader:set_form
file_options = params.slice(:filename, :content_type).reject { |_key, value| value.nil? }
hash.map do |key, value|
next [key, value] unless key == :file && file_options.keys.any?

[key, value, file_options]
end
end
end
end
Expand Down
16 changes: 16 additions & 0 deletions spec/shared/room_behaviors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,22 @@
it { expect(upload).to be_a(RocketChat::Message) }
end

context 'with content_type params' do
subject(:upload) { scope.upload_file(room_id: room_id, file: file, content_type: content_type, **rest_params) }

let(:content_type) { 'image/png' }
let(:file) { File.open('spec/fixtures/files/image.png') }
let(:response) { png_upload_response(room_id: room_id) }

before do
stub_authed_request(:post, path).to_return(body: response, status: 200)
end

it { expect { upload }.not_to raise_error }
it { expect(upload).to be_a(RocketChat::Message) }
end


context 'when not accepted error is raised' do
before do
stub_authed_request(:post, path).to_return(body: response, status: 400)
Expand Down

0 comments on commit dbeae1b

Please sign in to comment.