mirror of
https://gitlab.com/xmpp-rs/xmpp-rs.git
synced 2024-06-09 09:44:03 +02:00
58 lines
1.9 KiB
Rust
58 lines
1.9 KiB
Rust
// Copyright (c) 2023 xmpp-rs contributors.
|
|
//
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
|
|
use std::path::Path;
|
|
use tokio::fs::File;
|
|
use tokio_xmpp::connect::ServerConnector;
|
|
use tokio_xmpp::{
|
|
parsers::{http_upload::SlotRequest, iq::Iq},
|
|
Jid,
|
|
};
|
|
|
|
use crate::Agent;
|
|
|
|
/// Upload a file to the HTTP server associated with a given Jid.
|
|
///
|
|
/// # Arguments
|
|
/// - `agent`: The XMPP agent through which to negociate the request.
|
|
/// - `service`: The Jid of the HTTP server to upload the file to.
|
|
/// - `path`: The path to the file to upload.
|
|
pub async fn upload_file_with<C: ServerConnector>(agent: &mut Agent<C>, service: Jid, path: &Path) {
|
|
// Create the IQ request to upload the file.
|
|
let request =
|
|
Iq::from_get("upload1", slotslot_request_for_file(path).await).with_to(service.clone());
|
|
|
|
// Record the upload request so we can handle the response later.
|
|
agent
|
|
.uploads
|
|
.push((String::from("upload1"), service, path.to_path_buf()));
|
|
|
|
// Send the request to the server.
|
|
agent.client.send_stanza(request.into()).await.unwrap();
|
|
}
|
|
|
|
/// Create a SlotRequest for a file, representing a request for a URL to upload the file to.
|
|
///
|
|
/// Note: this function is async because it accesses the file system to read the file's metadata.
|
|
///
|
|
/// # Arguments
|
|
/// - `path`: The path to the file to upload.
|
|
async fn slotslot_request_for_file(path: &Path) -> SlotRequest {
|
|
// Extract the file's name.
|
|
let name = path.file_name().unwrap().to_str().unwrap().to_string();
|
|
|
|
// Open the file and read its size.
|
|
let file = File::open(path).await.unwrap();
|
|
let size = file.metadata().await.unwrap().len();
|
|
|
|
// Create a SlotRequest for the file.
|
|
SlotRequest {
|
|
filename: name,
|
|
size: size,
|
|
content_type: None,
|
|
}
|
|
}
|