Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update deps, generate files.upload method #108

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ serde_json = "1.0"

[dependencies.reqwest_]
package = "reqwest"
version = "0.10"
version = "0.11"
optional = true
default-features = false
features = ["gzip"]
Expand All @@ -28,7 +28,7 @@ optional = true

[dev-dependencies.tokio]
package = "tokio"
version = "0.2"
version = "1"
features = ["macros"]

[features]
Expand Down
8 changes: 4 additions & 4 deletions codegen/src/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ use crate::json_schema::*;

pub static AUTOGEN_HEADER: &str = "
//=============================================================================
//
//
// WARNING: This file is AUTO-GENERATED
//
//
// Do not make changes directly to this file.
//
// If you would like to make a change to the library, please update the schema
// definitions at https://github.com/slack-rs/slack-api-schemas
//
// If you would like to make a change how the library was generated,
// please edit https://github.com/slack-rs/slack-rs-api/tree/master/codegen
//
//
//=============================================================================

";
Expand Down Expand Up @@ -122,7 +122,7 @@ pub struct Method {
impl Method {
pub fn generate(&self, gen_mode: GenMode) -> String {
// HACK: these methods requires multipart support, which is not yet supported by this library
if self.name == "files.upload" || self.name == "users.setPhoto" {
if self.name == "users.setPhoto" {
return String::new();
}

Expand Down
37 changes: 37 additions & 0 deletions src/async_impl/mods/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,40 @@ where
})
.and_then(|o| o.into())
}

/// Uploads or creates a file.
///
/// Wraps https://api.slack.com/methods/files.upload

pub async fn upload<R>(
client: &R,
token: &str,
request: &UploadRequest<'_>,
) -> Result<UploadResponse, UploadError<R::Error>>
where
R: SlackWebRequestSender,
{
let params = vec![
Some(("token", token)),
request.file.map(|file| ("file", file)),
request.content.map(|content| ("content", content)),
request.filetype.map(|filetype| ("filetype", filetype)),
Some(("filename", request.filename)),
request.title.map(|title| ("title", title)),
request
.initial_comment
.map(|initial_comment| ("initial_comment", initial_comment)),
request.channels.map(|channels| ("channels", channels)),
];
let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
let url = crate::get_slack_url_for_method("files.upload");
client
.send(&url, &params[..])
.await
.map_err(UploadError::Client)
.and_then(|result| {
serde_json::from_str::<UploadResponse>(&result)
.map_err(|e| UploadError::MalformedResponse(result, e))
})
.and_then(|o| o.into())
}
32 changes: 16 additions & 16 deletions src/async_impl/mods/mod.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
pub mod api;
pub mod auth;
pub mod bots;
pub mod channels;
pub mod chat;
pub mod dnd;
pub mod emoji;
pub mod files_comments;
pub mod files;
pub mod groups;
pub mod im;
pub mod mpim;
pub mod oauth;
pub mod users;
pub mod pins;
pub mod reactions;
pub mod reminders;
pub mod dnd;
pub mod groups;
pub mod im;
pub mod rtm;
pub mod bots;
pub mod users_profile;
pub mod reactions;
pub mod search;
pub mod stars;
pub mod team;
pub mod team_profile;
pub mod usergroups;
pub mod api;
pub mod chat;
pub mod usergroups_users;
pub mod users;
pub mod users_profile;
pub mod team;
pub mod stars;
pub mod auth;
pub mod channels;
pub mod team_profile;
pub mod mpim;
pub mod files;
126 changes: 126 additions & 0 deletions src/mod_types/files_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -643,3 +643,129 @@ impl<E: Error + 'static> Error for SharedPublicURLError<E> {
}
}
}

#[derive(Clone, Default, Debug)]
pub struct UploadRequest<'a> {
/// File contents via multipart/form-data. If omitting this parameter, you must submit content.
pub file: Option<&'a str>,
/// File contents via a POST variable. If omitting this parameter, you must provide a file.
pub content: Option<&'a str>,
/// A file type identifier.
pub filetype: Option<&'a str>,
/// Filename of file.
pub filename: &'a str,
/// Title of file.
pub title: Option<&'a str>,
/// Initial comment to add to file.
pub initial_comment: Option<&'a str>,
/// Comma-separated list of channel names or IDs where the file will be shared.
pub channels: Option<&'a str>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct UploadResponse {
error: Option<String>,
pub file: Option<crate::File>,
#[serde(default)]
ok: bool,
}

impl<E: Error> Into<Result<UploadResponse, UploadError<E>>> for UploadResponse {
fn into(self) -> Result<UploadResponse, UploadError<E>> {
if self.ok {
Ok(self)
} else {
Err(self.error.as_ref().map(String::as_ref).unwrap_or("").into())
}
}
}
#[derive(Debug)]
pub enum UploadError<E: Error> {
/// An admin has restricted posting to the #general channel.
PostingToGeneralChannelDenied,
/// One or more channels supplied are invalid
InvalidChannel,
/// No authentication token provided.
NotAuthed,
/// Invalid authentication token.
InvalidAuth,
/// Authentication token is for a deleted user or team.
AccountInactive,
/// The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.
InvalidArgName,
/// The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.
InvalidArrayArg,
/// The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.
InvalidCharset,
/// The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.
InvalidFormData,
/// The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.
InvalidPostType,
/// The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.
MissingPostType,
/// The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.
TeamAddedToOrg,
/// The method was called via a POST request, but the POST data was either missing or truncated.
RequestTimeout,
/// The response was not parseable as the expected object
MalformedResponse(String, serde_json::error::Error),
/// The response returned an error that was unknown to the library
Unknown(String),
/// The client had an error sending the request to Slack
Client(E),
}

impl<'a, E: Error> From<&'a str> for UploadError<E> {
fn from(s: &'a str) -> Self {
match s {
"posting_to_general_channel_denied" => UploadError::PostingToGeneralChannelDenied,
"invalid_channel" => UploadError::InvalidChannel,
"not_authed" => UploadError::NotAuthed,
"invalid_auth" => UploadError::InvalidAuth,
"account_inactive" => UploadError::AccountInactive,
"invalid_arg_name" => UploadError::InvalidArgName,
"invalid_array_arg" => UploadError::InvalidArrayArg,
"invalid_charset" => UploadError::InvalidCharset,
"invalid_form_data" => UploadError::InvalidFormData,
"invalid_post_type" => UploadError::InvalidPostType,
"missing_post_type" => UploadError::MissingPostType,
"team_added_to_org" => UploadError::TeamAddedToOrg,
"request_timeout" => UploadError::RequestTimeout,
_ => UploadError::Unknown(s.to_owned()),
}
}
}

impl<E: Error> fmt::Display for UploadError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let d = match *self {
UploadError::PostingToGeneralChannelDenied => "posting_to_general_channel_denied: An admin has restricted posting to the #general channel.",
UploadError::InvalidChannel => "invalid_channel: One or more channels supplied are invalid",
UploadError::NotAuthed => "not_authed: No authentication token provided.",
UploadError::InvalidAuth => "invalid_auth: Invalid authentication token.",
UploadError::AccountInactive => "account_inactive: Authentication token is for a deleted user or team.",
UploadError::InvalidArgName => "invalid_arg_name: The method was passed an argument whose name falls outside the bounds of common decency. This includes very long names and names with non-alphanumeric characters other than _. If you get this error, it is typically an indication that you have made a very malformed API call.",
UploadError::InvalidArrayArg => "invalid_array_arg: The method was passed a PHP-style array argument (e.g. with a name like foo[7]). These are never valid with the Slack API.",
UploadError::InvalidCharset => "invalid_charset: The method was called via a POST request, but the charset specified in the Content-Type header was invalid. Valid charset names are: utf-8 iso-8859-1.",
UploadError::InvalidFormData => "invalid_form_data: The method was called via a POST request with Content-Type application/x-www-form-urlencoded or multipart/form-data, but the form data was either missing or syntactically invalid.",
UploadError::InvalidPostType => "invalid_post_type: The method was called via a POST request, but the specified Content-Type was invalid. Valid types are: application/x-www-form-urlencoded multipart/form-data text/plain.",
UploadError::MissingPostType => "missing_post_type: The method was called via a POST request and included a data payload, but the request did not include a Content-Type header.",
UploadError::TeamAddedToOrg => "team_added_to_org: The team associated with your request is currently undergoing migration to an Enterprise Organization. Web API and other platform operations will be intermittently unavailable until the transition is complete.",
UploadError::RequestTimeout => "request_timeout: The method was called via a POST request, but the POST data was either missing or truncated.",
UploadError::MalformedResponse(_, ref e) => return write!(f, "{}", e),
UploadError::Unknown(ref s) => return write!(f, "{}", s),
UploadError::Client(ref inner) => return write!(f, "{}", inner),
};
write!(f, "{}", d)
}
}

impl<E: Error + 'static> Error for UploadError<E> {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match *self {
UploadError::MalformedResponse(_, ref e) => Some(e),
UploadError::Client(ref inner) => Some(inner),
_ => None,
}
}
}
32 changes: 16 additions & 16 deletions src/mod_types/mod.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
pub mod api_types;
pub mod auth_types;
pub mod bots_types;
pub mod channels_types;
pub mod chat_types;
pub mod dnd_types;
pub mod emoji_types;
pub mod files_comments_types;
pub mod files_types;
pub mod groups_types;
pub mod im_types;
pub mod mpim_types;
pub mod oauth_types;
pub mod users_types;
pub mod pins_types;
pub mod reactions_types;
pub mod reminders_types;
pub mod dnd_types;
pub mod groups_types;
pub mod im_types;
pub mod rtm_types;
pub mod bots_types;
pub mod users_profile_types;
pub mod reactions_types;
pub mod search_types;
pub mod stars_types;
pub mod team_types;
pub mod team_profile_types;
pub mod usergroups_types;
pub mod api_types;
pub mod chat_types;
pub mod usergroups_users_types;
pub mod users_types;
pub mod users_profile_types;
pub mod team_types;
pub mod stars_types;
pub mod auth_types;
pub mod channels_types;
pub mod team_profile_types;
pub mod mpim_types;
pub mod files_types;
36 changes: 36 additions & 0 deletions src/sync/mods/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,39 @@ where
})
.and_then(|o| o.into())
}

/// Uploads or creates a file.
///
/// Wraps https://api.slack.com/methods/files.upload

pub fn upload<R>(
client: &R,
token: &str,
request: &UploadRequest<'_>,
) -> Result<UploadResponse, UploadError<R::Error>>
where
R: SlackWebRequestSender,
{
let params = vec![
Some(("token", token)),
request.file.map(|file| ("file", file)),
request.content.map(|content| ("content", content)),
request.filetype.map(|filetype| ("filetype", filetype)),
Some(("filename", request.filename)),
request.title.map(|title| ("title", title)),
request
.initial_comment
.map(|initial_comment| ("initial_comment", initial_comment)),
request.channels.map(|channels| ("channels", channels)),
];
let params = params.into_iter().filter_map(|x| x).collect::<Vec<_>>();
let url = crate::get_slack_url_for_method("files.upload");
client
.send(&url, &params[..])
.map_err(UploadError::Client)
.and_then(|result| {
serde_json::from_str::<UploadResponse>(&result)
.map_err(|e| UploadError::MalformedResponse(result, e))
})
.and_then(|o| o.into())
}
32 changes: 16 additions & 16 deletions src/sync/mods/mod.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
pub mod api;
pub mod auth;
pub mod bots;
pub mod channels;
pub mod chat;
pub mod dnd;
pub mod emoji;
pub mod files_comments;
pub mod files;
pub mod groups;
pub mod im;
pub mod mpim;
pub mod oauth;
pub mod users;
pub mod pins;
pub mod reactions;
pub mod reminders;
pub mod dnd;
pub mod groups;
pub mod im;
pub mod rtm;
pub mod bots;
pub mod users_profile;
pub mod reactions;
pub mod search;
pub mod stars;
pub mod team;
pub mod team_profile;
pub mod usergroups;
pub mod api;
pub mod chat;
pub mod usergroups_users;
pub mod users;
pub mod users_profile;
pub mod team;
pub mod stars;
pub mod auth;
pub mod channels;
pub mod team_profile;
pub mod mpim;
pub mod files;
Loading