Skip to content

Commit

Permalink
Add files upload to rooms (#46)
Browse files Browse the repository at this point in the history
* Add form data to request helper
* Add upload_file method to rooms
* Add file upload to docs
  • Loading branch information
MrRTi committed Aug 22, 2023
1 parent 8c3c061 commit bac8079
Show file tree
Hide file tree
Showing 14 changed files with 414 additions and 3 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ This gem supports the following Rocket.Chat APIs (Tested against Rocket.Chat v0.
* [/api/v1/channels.online](docs/channels.md#channelsonline)
* [/api/v1/channels.members](docs/channels.md#channelsmembers)
* /api/v1/channels.unarchive
* [/api/v1/rooms.upload](docs/channels.md#channelsupload_file)

#### Groups
* /api/v1/groups.archive
Expand All @@ -92,6 +93,7 @@ This gem supports the following Rocket.Chat APIs (Tested against Rocket.Chat v0.
* /api/v1/groups.setType
* [/api/v1/groups.members](docs/groups.md#groupsmembers)
* /api/v1/groups.unarchive
* [/api/v1/rooms.upload](docs/groups.md#groupsupload_file)

#### Users
* [/api/v1/users.create](docs/users.md#userscreate)
Expand Down
14 changes: 14 additions & 0 deletions docs/channels.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,3 +182,17 @@ session = rocket_server.login('username', 'password')
session.channels.members(name: 'some_channel_name')

```


### channels.upload_file

Upload file to the room

```ruby
require 'rocketchat'

rocket_server = RocketChat::Server.new('http://your.server.address/')
session = rocket_server.login('username', 'password')
session.channels.upload_file(room_id: 'GENERAL', file: File, msg: "Optional Message", description: "Optional Description", tmid: "Optional thread message id")

```
16 changes: 15 additions & 1 deletion docs/groups.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,18 @@ rocket_server = RocketChat::Server.new('http://your.server.address/')
session = rocket_server.login('username', 'password')
session.groups.members(name: 'some_channel_name')

```
```


### channels.upload_file

Upload file to the room

```ruby
require 'rocketchat'

rocket_server = RocketChat::Server.new('http://your.server.address/')
session = rocket_server.login('username', 'password')
session.groups.upload_file(room_id: 'GENERAL', file: File, msg: "Optional Message", description: "Optional Description", tmid: "Optional thread message id")

```
28 changes: 27 additions & 1 deletion lib/rocket_chat/messages/room.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ class Room # rubocop:disable Metrics/ClassLength
include RoomSupport
include UserSupport

API_PREFIX = '/api/v1'

def self.inherited(subclass)
field = subclass.name.split('::')[-1].downcase
collection = "#{field}s"
Expand All @@ -27,7 +29,7 @@ def initialize(session)

# Full API path to call
def self.api_path(method)
"/api/v1/#{collection}.#{method}"
"#{API_PREFIX}/#{collection}.#{method}"
end

#
Expand Down Expand Up @@ -304,6 +306,25 @@ def members(room_id: nil, name: nil, offset: nil, count: nil, sort: nil)
response['members'].map { |hash| RocketChat::User.new hash } if response['success']
end

#
# *.upload* REST API
# @param [String] room_id Rocket.Chat room id
# @param [File] file that should be uploaded to Rocket.Chat room
# @param [Hash] rest_params Optional params (msg, description, tmid)
# @return [RocketChat::Message]
# @raise [HTTPError, StatusError]
#
# https://developer.rocket.chat/reference/api/rest-api/endpoints/rooms-endpoints/upload-file-to-a-room
def upload_file(room_id:, file:, **rest_params)
response = session.request_json(
"#{API_PREFIX}/rooms.upload/#{room_id}",
method: :post,
form_data: file_upload_hash(file: file, **rest_params)
)

RocketChat::Message.new response['message'] if response['success']
end

private

attr_reader :session
Expand All @@ -323,6 +344,11 @@ def validate_attribute(attribute)
raise ArgumentError, "Unsettable attribute: #{attribute || 'nil'}" unless \
self.class.settable_attributes.include?(attribute)
end

def file_upload_hash(**params)
permited_keys_for_file_upload = %i[file msg description tmid]
Util.slice_hash(params, *permited_keys_for_file_upload)
end
end
end
end
14 changes: 13 additions & 1 deletion lib/rocket_chat/request_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,14 @@ def create_http(options)

def create_request(path, options)
headers = get_headers(options)
body = options[:body]&.reject { |_key, value| value.nil? }
body = reject_nils(options[:body])

if options[:method] == :post
req = Net::HTTP::Post.new(path, headers)
add_body(req, body) if body

form_data = reject_nils(options[:form_data])
add_form_data(req, form_data) if form_data
else
uri = path
uri += "?#{URI.encode_www_form(body)}" if body
Expand All @@ -126,5 +129,14 @@ def add_body(request, body)
request.body = body.to_s
end
end

def add_form_data(request, form_data)
form_data = form_data.transform_keys(&:to_s) if form_data.is_a? Hash
request.set_form(form_data, 'multipart/form-data')
end

def reject_nils(data)
data&.reject { |_key, value| value.nil? }
end
end
end
Binary file added spec/fixtures/files/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions spec/fixtures/files/iterm-theme.itermcolors
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
</dict>
</plist>
4 changes: 4 additions & 0 deletions spec/fixtures/files/not_accepted.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
62 changes: 62 additions & 0 deletions spec/fixtures/messages/room/upload/file_upload_success.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"message": {
"_id": "%{message_id}",
"rid": "%{room_id}",
"ts": "2023-07-06T12:05:07.127Z",
"file": {
"_id": "%{file_id}",
"name": "%{file_name}",
"type": "application/octet-stream"
},
"files": [
{
"_id": "%{file_id}",
"name": "%{file_name}",
"type": "application/octet-stream"
}
],
"attachments": [
{
"ts": "1970-01-01T00:00:00.000Z",
"title": "%{file_name}",
"title_link": "/file-upload/%{file_id}/%{file_name}",
"title_link_download": true,
"type": "file",
"description": "%{description}",
"format": "%{format}",
"size": 8347,
"descriptionMd": [
{
"type": "PARAGRAPH",
"value": [
{
"type": "PLAIN_TEXT",
"value": "%{description}"
}
]
}
]
}
],
"msg": "%{msg}",
"u": {
"_id": "%{user_id}",
"username": "admin",
"name": "Admin"
},
"_updatedAt": "2023-07-06T12:05:07.264Z",
"urls": [],
"md": [
{
"type": "PARAGRAPH",
"value": [
{
"type": "PLAIN_TEXT",
"value": "%{msg}"
}
]
}
]
},
"success": true
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@

{
"message": {
"_id": "%{message_id}",
"rid": "%{room_id}",
"ts": "2023-07-07T10:03:44.048Z",
"file": {
"_id": "%{file_id}",
"name": "%{file_name}",
"type": "application/octet-stream"
},
"files": [
{
"_id": "%{file_id}",
"name": "%{file_name}",
"type": "application/octet-stream"
}
],
"attachments": [
{
"ts": "1970-01-01T00:00:00.000Z",
"title": "%{file_name}",
"title_link": "/file-upload/%{file_id}/%{file_name}",
"title_link_download": true,
"type": "file",
"format": "%{format}",
"size": 8347
}
],
"msg": "",
"u": {
"_id": "%{user_id}",
"username": "rocket_admin",
"name": "Admin"
},
"_updatedAt": "2023-07-07T10:03:44.097Z",
"urls": []
},
"success": true
}
5 changes: 5 additions & 0 deletions spec/fixtures/messages/room/upload/no_accepted_error.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"success": false,
"error": "File type is not accepted. [error-invalid-file-type]",
"errorType": "error-invalid-file-type"
}
5 changes: 5 additions & 0 deletions spec/fixtures/messages/room/upload/no_file_error.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"success": false,
"error": "[No file uploaded]",
"errorType": "No file uploaded"
}
73 changes: 73 additions & 0 deletions spec/fixtures/messages/room/upload/png_upload_success.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
{
"message": {
"_id": "%{message_id}",
"rid": "%{room_id}",
"ts": "2023-07-07T08:05:32.625Z",
"file": {
"_id": "%{file_id}",
"name": "%{file_name}",
"type": "image/png"
},
"files": [
{
"_id": "%{file_id}",
"name": "%{file_name}",
"type": "image/png"
},
{
"_id": "%{preview_file_id}",
"name": "%{file_name}",
"type": "image/png"
}
],
"attachments": [
{
"ts": "1970-01-01T00:00:00.000Z",
"title": "%{file_name}",
"title_link": "/file-upload/%{file_id}/%{file_name}",
"title_link_download": true,
"image_dimensions": {
"width": 480,
"height": 300
},
"image_preview": "/9j/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAAUACADASIAAhEBAxEB/8QAGQAAAwADAAAAAAAAAAAAAAAAAAIDAQQH/8QAHxABAAICAgIDAAAAAAAAAAAAAQACAxESIRMxBEFS/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAUC/8QAFREBAQAAAAAAAAAAAAAAAAAAAAH/2gAMAwEAAhEDEQA/AOFx8PEuche4FtG+PUal26V0SgiFza8jr1JsrZCzyO4rY/MALutfUxRS4kIQK4jy5kv2Tcr8XE1XXo3CEzSP/9k=",
"image_url": "/file-upload/%{preview_file_id}/%{file_name}",
"image_type": "image/png",
"image_size": 103724,
"type": "file",
"description": "%{description}",
"descriptionMd": [
{
"type": "PARAGRAPH",
"value": [
{
"type": "PLAIN_TEXT",
"value": "%{description}"
}
]
}
]
}
],
"msg": "%{msg}",
"u": {
"_id": "%{user_id}",
"username": "admin",
"name": "Admin"
},
"_updatedAt": "2023-07-07T08:05:32.669Z",
"urls": [],
"md": [
{
"type": "PARAGRAPH",
"value": [
{
"type": "PLAIN_TEXT",
"value": "%{msg}"
}
]
}
]
},
"success": true
}
Loading

0 comments on commit bac8079

Please sign in to comment.