Skip to content

Commit

Permalink
Added delete button
Browse files Browse the repository at this point in the history
  • Loading branch information
obvMellow committed Oct 13, 2024
1 parent 209e1fd commit 7b4f84d
Show file tree
Hide file tree
Showing 2 changed files with 176 additions and 16 deletions.
77 changes: 62 additions & 15 deletions libdistore/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,10 @@ pub fn get_config(global: bool, dir: Option<PathBuf>) -> Result<()> {
Ok(())
}

pub(crate) fn get_config_internal(global: bool, dir: Option<PathBuf>) -> Result<(ConfigValue, ConfigValue)> {
pub(crate) fn get_config_internal(
global: bool,
dir: Option<PathBuf>,
) -> Result<(ConfigValue, ConfigValue)> {
let mut path = dir
.unwrap_or(dirs::config_dir().ok_or(ConfigError::NoConfigDir)?)
.join("distore");
Expand All @@ -104,7 +107,11 @@ pub fn disassemble(path: PathBuf, output: PathBuf) -> Result<()> {
Ok(())
}

pub(crate) fn disassemble_internal<F: Fn(String, f64)>(path: PathBuf, output: PathBuf, callback: F) -> Result<(Vec<PathBuf>, String, usize)> {
pub(crate) fn disassemble_internal<F: Fn(String, f64)>(
path: PathBuf,
output: PathBuf,
callback: F,
) -> Result<(Vec<PathBuf>, String, usize)> {
let mut file =
File::open(&path).with_context(|| format!("Cannot open file: {}", path.display()))?;
let filename = path.file_name().unwrap().to_str().unwrap().to_owned();
Expand Down Expand Up @@ -132,7 +139,7 @@ pub(crate) fn disassemble_internal<F: Fn(String, f64)>(path: PathBuf, output: Pa
let fraction = if total > 0 {
progress as f64 / total as f64
} else {
1.0
1.0
};

let fraction = fraction.clamp(0.0, 1.0);
Expand Down Expand Up @@ -272,10 +279,16 @@ pub async fn upload(
Ok(())
}

pub(crate) async fn upload_internal<F: Fn(String, f64)>(http: &Http, file: PathBuf, channel: u64, callback: F) -> Result<Vec<Message>> {
pub(crate) async fn upload_internal<F: Fn(String, f64)>(
http: &Http,
file: PathBuf,
channel: u64,
callback: F,
) -> Result<Vec<Message>> {
let cache_dir = dirs::cache_dir().unwrap().join("distore");
fs::create_dir_all(&cache_dir)?;
let (part_paths, filename, _) = disassemble_internal(file.clone(), cache_dir.clone(), &callback)?;
let (part_paths, filename, _) =
disassemble_internal(file.clone(), cache_dir.clone(), &callback)?;

let msg = format!(
"### This message is generated by Distore. Do not edit this message.\nname={}\nsize={}",
Expand Down Expand Up @@ -311,7 +324,7 @@ pub(crate) async fn upload_internal<F: Fn(String, f64)>(http: &Http, file: PathB
let fraction = if total > 0 {
progress as f64 / total as f64
} else {
1.0
1.0
};

let fraction = fraction.clamp(0.0, 1.0);
Expand Down Expand Up @@ -361,7 +374,7 @@ pub(crate) async fn upload_internal<F: Fn(String, f64)>(http: &Http, file: PathB
let fraction = if total > 0 {
progress as f64 / total as f64
} else {
1.0
1.0
};

callback("Editing".to_string(), fraction);
Expand Down Expand Up @@ -431,7 +444,10 @@ pub async fn download(
pb.set_message("Assembling");

let pb_clone = pb.clone();
download_internal(&http, message_id, channel, output.clone(), move |_| pb_clone.inc(1)).await?;
download_internal(&http, message_id, channel, output.clone(), move |_| {
pb_clone.inc(1)
})
.await?;

pb.finish();

Expand All @@ -444,7 +460,11 @@ pub async fn download(
Ok(())
}

pub(crate) async fn _get_download_variables(http: &Http, message_id: u64, channel: u64) -> Result<(Message, FileEntry, String, usize)> {
pub(crate) async fn _get_download_variables(
http: &Http,
message_id: u64,
channel: u64,
) -> Result<(Message, FileEntry, String, usize)> {
let msg = http.get_message(channel.into(), message_id.into()).await?;
let entry = FileEntry::from_str(&msg.content)?;
let name = entry.name.clone().ok_or(anyhow!("Invalid Message"))?;
Expand All @@ -453,7 +473,13 @@ pub(crate) async fn _get_download_variables(http: &Http, message_id: u64, channe
Ok((msg, entry, name, len))
}

pub(crate) async fn download_internal<F: Fn(f64)>(http: &Http, message_id: u64, channel: u64, output: Option<PathBuf>, callback: F) -> Result<PathBuf> {
pub(crate) async fn download_internal<F: Fn(f64)>(
http: &Http,
message_id: u64,
channel: u64,
output: Option<PathBuf>,
callback: F,
) -> Result<PathBuf> {
let (msg, mut entry, name, len) = _get_download_variables(http, message_id, channel).await?;

let size = entry.size.unwrap();
Expand All @@ -473,7 +499,7 @@ pub(crate) async fn download_internal<F: Fn(f64)>(http: &Http, message_id: u64,
let fraction = if size > 0 {
progress as f64 / size as f64
} else {
1.0
1.0
};

let fraction = fraction.clamp(0.0, 1.0);
Expand Down Expand Up @@ -527,7 +553,7 @@ pub async fn list(token: Option<String>, channel: Option<u64>, dir: Option<PathB
let channel = http.get_channel(channel.into()).await?.id();

info!("Retrieving messages...");

let list = list_internal(channel.into(), &http).await?;

for entry in list {
Expand Down Expand Up @@ -566,7 +592,15 @@ pub(crate) async fn list_internal(channel: u64, http: &Http) -> Result<Vec<(File
let name = entry.name.ok_or(anyhow!("Invalid Message"))?;
let size = entry.size.ok_or(anyhow!("Invalid Message"))?;

out.push((FileEntry { name: Some(name), size: Some(size), len: entry.len, next: entry.next }, msg.id.into()))
out.push((
FileEntry {
name: Some(name),
size: Some(size),
len: entry.len,
next: entry.next,
},
msg.id.into(),
))
}
return Ok(out);
}
Expand Down Expand Up @@ -641,7 +675,18 @@ pub async fn delete(

let http = Http::new(&token);

let msg = http.get_message(channel.into(), message_id.into()).await?;
delete_internal(&http, message_id, channel, || {}).await
}

pub(crate) async fn delete_internal<F: Fn()>(
http: &Http,
message_id: u64,
channel_id: u64,
callback: F,
) -> Result<()> {
let msg = http
.get_message(channel_id.into(), message_id.into())
.await?;

let mut entry = FileEntry::from_str(&msg.content)?;

Expand All @@ -652,10 +697,12 @@ pub async fn delete(

while entry.next.is_some() {
let msg = http
.get_message(channel.into(), entry.next.unwrap().into())
.get_message(channel_id.into(), entry.next.unwrap().into())
.await?;
entry = FileEntry::from_str(&msg.content)?;
msg.delete(&http).await?;

callback();
}

Ok(())
Expand Down
115 changes: 114 additions & 1 deletion libdistore/src/gui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use gtk::{AlertDialog, Application, Button, ProgressBar};
use indicatif::HumanBytes;
use serenity::all::{ChannelId, Http};

use crate::commands::{self, download_internal, upload_internal};
use crate::commands::{self, delete_internal, download_internal, upload_internal};
use crate::parser::FileEntry;

const APP_ID: &str = "org.distore.Distore";
Expand Down Expand Up @@ -105,6 +105,119 @@ fn build_ui(app: &Application) {
button_box.append(&upload_btn);
button_box.append(&delete_btn);

let list_box_clone = list_box.clone();
let progress_box_clone = progress_box.clone();
let window_clone = window.clone();
let channel_ = channel.clone();
let token_ = token.clone();
delete_btn.connect_clicked(move |_| {
if let Some(selected_row) = list_box_clone.selected_row() {
if let Some(box_) = selected_row.child().and_then(|w| w.downcast::<Box>().ok()) {
let mut labels: Vec<Label> = Vec::new();

let first_child: Label = box_.first_child().unwrap().downcast().unwrap();
labels.push(first_child.clone());

let mut current: Option<Label> = Some(first_child);

while let Some(curr) = current {
current = match curr.next_sibling() {
Some(v) => v.downcast().ok(),
None => None,
};

if current.is_some() {
labels.push(current.clone().unwrap());
}
}

for (i, label) in labels.iter().enumerate() {
println!("Label {}: {}", i, label.label());
}

let mut iter = labels.iter();
let name = iter.next().unwrap().to_owned();
let _size = iter.next().unwrap().label().replace("Size: ", "");
let id = iter
.next()
.unwrap()
.label()
.replace("ID: ", "")
.parse::<u64>()
.unwrap();

let progressbar = Rc::new(
ProgressBar::builder()
.visible(true)
.show_text(true)
.valign(Align::Fill)
.pulse_step(0.0)
.build(),
);
progressbar.set_text(Some(format!("Deleting {}", name.label()).as_str()));
progressbar.set_fraction(0.0);

progress_box_clone.append(&*progressbar);

let (sender, receiver) = mpsc::channel();

let http = Http::new(token_.inner());
let channel_ = channel_.clone();
tokio::spawn(async move {
let res = delete_internal(&http, id, channel_.inner().parse().unwrap(), || {
sender.send((Some(()), None)).unwrap();
})
.await;

sender.send((None, Some(res))).unwrap();
});

let progressbar = progressbar.clone();
let progress_box_clone = progress_box_clone.clone();
let window_clone = window_clone.clone();
let list_box_clone = list_box_clone.clone();
progressbar.pulse();
glib::timeout_add_local(Duration::from_millis(100), move || {
match receiver.try_recv() {
Ok((p, r)) => {
if let Some(_) = p {
progressbar.pulse();
}

if let Some(r) = r {
match r {
Ok(_) => {
list_box_clone.remove(&selected_row);

AlertDialog::builder()
.message("Delete Complete")
.detail(format!("Succesfully deleted {}", name.label()))
.build()
.show(Some(&*window_clone));
}
Err(e) => {
AlertDialog::builder()
.message("Delete Failed")
.detail(format!("An error occured: {}", e))
.build()
.show(Some(&*window_clone));
}
}
}
}
Err(e) => {
if let TryRecvError::Disconnected = e {
progress_box_clone.remove(&*progressbar);
return glib::ControlFlow::Break;
}
}
}
glib::ControlFlow::Continue
});
}
}
});

let window_clone = window.clone();
let channel_ = channel.clone();
let progress_box_ = progress_box.clone();
Expand Down

0 comments on commit 7b4f84d

Please sign in to comment.