Skip to content

Commit

Permalink
Remove obsolete form encoded upload. Update docs for 2.0. (#238)
Browse files Browse the repository at this point in the history
* Fixed content type for file upload

* AsRef instead of ToString

* Multipart upload separate module

* Remove URL encoded uploader

* Docs update
  • Loading branch information
abdolence authored Jan 27, 2024
1 parent 96cda99 commit 3bd8d3f
Show file tree
Hide file tree
Showing 18 changed files with 150 additions and 281 deletions.
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ hyper-rustls = { version="0.26", features = ["rustls-native-certs", "http2"], op
tokio-tungstenite = { version = "0.21.0", features = ["rustls-tls-native-roots"], optional = true }
axum = { version = "0.7", optional = true }
tower = { version = "0.4", optional = true }
serde_urlencoded = "0.7.1"

[target.'cfg(not(windows))'.dependencies]
signal-hook = { version = "0.3", default-features = false, features = ["extended-siginfo"], optional = true}
Expand Down
2 changes: 1 addition & 1 deletion docs/src/events-api-axum.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ fn test_error_handler(
async fn test_server() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let client: Arc<SlackHyperClient> =
Arc::new(SlackClient::new(SlackClientHyperConnector::new()));
Arc::new(SlackClient::new(SlackClientHyperConnector::new()?));
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 8080));
info!("Loading server: {}", addr);
Expand Down
2 changes: 1 addition & 1 deletion docs/src/events-api-hyper.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ async fn create_slack_events_listener_server() -> Result<(), Box<dyn std::error:
// We need also a client instance. `Arc` used here because we would like
// to share the the same client for all of the requests and all hyper threads
let client = Arc::new(SlackClient::new(SlackClientHyperConnector::new()));
let client = Arc::new(SlackClient::new(SlackClientHyperConnector::new()?));
// In this example we're going to use all of the events handlers, but
Expand Down
2 changes: 1 addition & 1 deletion docs/src/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Cargo.toml dependencies example:

```toml
[dependencies]
slack-morphism = { version = "1.17", features = ["hyper", "axum"] }
slack-morphism = { version = "2.0", features = ["hyper", "axum"] }
```

All imports you need:
Expand Down
2 changes: 1 addition & 1 deletion docs/src/hyper-connections-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ For example for proxy server config it might be used as:
let proxy = {
let https_connector = hyper_rustls::HttpsConnectorBuilder::new()
.with_native_roots()
.with_native_roots()?
.https_only()
.enable_http1()
.build();
Expand Down
2 changes: 1 addition & 1 deletion docs/src/pagination-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use std::time::Duration;
async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let hyper_connector = SlackClientHyperConnector::new();
let hyper_connector = SlackClientHyperConnector::new()?;
let client = SlackClient::new(hyper_connector);
let token_value: SlackApiTokenValue = "xoxb-89.....".into();
Expand Down
4 changes: 2 additions & 2 deletions docs/src/rate-control-and-retries.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ By default, throttler *isn't* enabled, so you should enable it explicitly:
use slack_morphism::prelude::*;
let client = SlackClient::new(
SlackClientHyperConnector::new()
SlackClientHyperConnector::new()?
.with_rate_control(
SlackApiRateControlConfig::new()
)
Expand Down Expand Up @@ -44,7 +44,7 @@ you need to specify `max_retries` in rate control params (default value is `0`):
```rust,noplaypen
let client = SlackClient::new(
SlackClientHyperConnector::new()
SlackClientHyperConnector::new()?
.with_rate_control(
SlackApiRateControlConfig::new().with_max_retries(5)
),
Expand Down
2 changes: 1 addition & 1 deletion docs/src/send-webhooks-messages.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ You can use `client..post_webhook_message` to post [Slack Incoming Webhook](http
use slack_morphism::prelude::*;
use url::Url;
let client = SlackClient::new(SlackClientHyperConnector::new());
let client = SlackClient::new(SlackClientHyperConnector::new()?);
// Your incoming webhook url from config or OAuth/events (ResponseURL)
let webhook_url: Url = Url::parse("https://hooks.slack.com/services/...")?;
Expand Down
2 changes: 1 addition & 1 deletion docs/src/socket-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ async fn test_push_events_sm_function(
Ok(())
}
let client = Arc::new(SlackClient::new(SlackClientHyperConnector::new()));
let client = Arc::new(SlackClient::new(SlackClientHyperConnector::new()?));
let socket_mode_callbacks = SlackSocketModeListenerCallbacks::new()
.with_command_events(test_command_events_function)
Expand Down
4 changes: 2 additions & 2 deletions docs/src/web-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
```rust,noplaypen
use slack_morphism::prelude::*;
let client = SlackClient::new( SlackClientHyperConnector::new() );
let client = SlackClient::new( SlackClientHyperConnector::new()? );
```

Expand All @@ -25,7 +25,7 @@ use slack_morphism::prelude::*;
async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let client = SlackClient::new(SlackClientHyperConnector::new());
let client = SlackClient::new(SlackClientHyperConnector::new()?);
// Create our Slack API token
let token_value: SlackApiTokenValue = "xoxb-89.....".into();
Expand Down
8 changes: 4 additions & 4 deletions examples/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ async fn test_post_message() -> Result<(), Box<dyn std::error::Error + Send + Sy
let message = WelcomeMessageTemplateParams::new("".into());

let post_chat_req =
SlackApiChatPostMessageRequest::new("#general".into(), message.render_template());
SlackApiChatPostMessageRequest::new("#random".into(), message.render_template());

let post_chat_resp = session.chat_post_message(&post_chat_req).await?;
println!("post chat resp: {:#?}", &post_chat_resp);
Expand Down Expand Up @@ -89,9 +89,9 @@ async fn test_file_upload() -> Result<(), Box<dyn std::error::Error + Send + Syn
let session = client.open_session(&token);

let file_upload_req = SlackApiFilesUploadRequest::new()
.with_channels(vec!["#general".into()])
.with_filename("test.txt".into())
.with_file("test".into());
.with_channels(vec!["#random".into()])
.with_binary_content("test-content".into())
.with_filename("test.txt".into());

let file_upload_resp = session.files_upload(&file_upload_req).await?;
println!("file upload resp: {:#?}", &file_upload_resp);
Expand Down
70 changes: 36 additions & 34 deletions src/api/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use serde::{Deserialize, Serialize, Serializer};
use serde_with::skip_serializing_none;

use crate::models::*;
use crate::multipart_form::FileMultipartData;
use crate::ratectl::*;
use crate::SlackClientSession;
use crate::{ClientResult, SlackClientHttpConnector};
Expand All @@ -23,44 +24,45 @@ where
&self,
req: &SlackApiFilesUploadRequest,
) -> ClientResult<SlackApiFilesUploadResponse> {
if let Some(file) = &req.file {
let maybe_file = req.binary_content.as_ref().map(|file_data| {
let filename = req.filename.clone().unwrap_or("file".to_string());
let file_content_type = req.file_content_type.clone().unwrap_or_else(|| {
let file_mime = mime_guess::MimeGuess::from_path(&filename).first_or_octet_stream();
file_mime.to_string()
});
self.http_session_api
.http_post_multipart_form(
"files.upload",
filename,
file_content_type,
file,
&vec![
(
"channels",
req.channels
.as_ref()
.map(|xs| {
xs.iter()
.map(|x| x.to_string())
.collect::<Vec<String>>()
.join(",")
})
.as_ref(),
),
("filetype", req.filetype.as_ref().map(|x| x.value())),
("initial_comment", req.initial_comment.as_ref()),
("thread_ts", req.thread_ts.as_ref().map(|x| x.value())),
("title", req.title.as_ref()),
],
Some(&SLACK_TIER2_METHOD_CONFIG),
)
.await
} else {
self.http_session_api
.http_post_form_urlencoded("files.upload", req, Some(&SLACK_TIER2_METHOD_CONFIG))
.await
}
FileMultipartData {
name: filename,
content_type: file_content_type,
data: file_data.as_slice(),
}
});
self.http_session_api
.http_post_multipart_form(
"files.upload",
maybe_file,
&vec![
(
"channels",
req.channels
.as_ref()
.map(|xs| {
xs.iter()
.map(|x| x.to_string())
.collect::<Vec<String>>()
.join(",")
})
.as_ref(),
),
("content", req.content.as_ref()),
("filename", req.filename.as_ref()),
("filetype", req.filetype.as_ref().map(|x| x.value())),
("initial_comment", req.initial_comment.as_ref()),
("thread_ts", req.thread_ts.as_ref().map(|x| x.value())),
("title", req.title.as_ref()),
],
Some(&SLACK_TIER2_METHOD_CONFIG),
)
.await
}
}

Expand All @@ -70,12 +72,12 @@ pub struct SlackApiFilesUploadRequest {
#[serde(serialize_with = "to_csv")]
pub channels: Option<Vec<SlackChannelId>>,
pub content: Option<String>,
pub binary_content: Option<Vec<u8>>,
pub filename: Option<String>,
pub filetype: Option<SlackFileType>,
pub initial_comment: Option<String>,
pub thread_ts: Option<SlackTs>,
pub title: Option<String>,
pub file: Option<Vec<u8>>,
pub file_content_type: Option<String>,
}

Expand Down
Loading

0 comments on commit 3bd8d3f

Please sign in to comment.