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

refactor: structure the project better #87

Merged
merged 6 commits into from
Aug 13, 2024
Merged
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
106 changes: 0 additions & 106 deletions rm-main/src/cli.rs

This file was deleted.

46 changes: 46 additions & 0 deletions rm-main/src/cli/add_torrent.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use std::{fs::File, io::Read};

use anyhow::Result;
use base64::Engine;
use transmission_rpc::types::TorrentAddArgs;

use crate::transmission;

pub(super) async fn add_torrent(torrent: String) -> Result<()> {
let mut transclient = transmission::utils::new_client();
let args = {
if torrent.starts_with("magnet:")
|| torrent.starts_with("http:")
|| torrent.starts_with("https:")
{
TorrentAddArgs {
filename: Some(torrent),
..Default::default()
}
} else if torrent.starts_with("www") {
TorrentAddArgs {
filename: Some(format!("https://{torrent}")),
..Default::default()
}
} else {
let mut torrent_file = File::open(torrent)?;
let mut buf = vec![];
torrent_file.read_to_end(&mut buf).unwrap();
let metainfo = base64::engine::general_purpose::STANDARD.encode(buf);
TorrentAddArgs {
metainfo: Some(metainfo),
..Default::default()
}
}
};

if let Err(e) = transclient.torrent_add(args).await {
eprintln!("error while adding a torrent: {e}");
if e.to_string().contains("expected value at line") {
eprintln!("Check whether your arguments are valid.");
}

std::process::exit(1);
};
Ok(())
}
42 changes: 42 additions & 0 deletions rm-main/src/cli/fetch_rss.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use anyhow::{bail, Result};
use regex::Regex;
use transmission_rpc::types::TorrentAddArgs;

use crate::transmission;

pub async fn fetch_rss(url: &str, filter: Option<&str>) -> Result<()> {
let mut transclient = transmission::utils::new_client();
let content = reqwest::get(url).await?.bytes().await?;
let channel = rss::Channel::read_from(&content[..])?;
let re: Option<Regex> = {
if let Some(filter_str) = filter {
let res = Regex::new(filter_str)?;
Some(res)
} else {
None
}
};
let items = channel.items().iter().filter_map(|item| {
if let (Some(title), Some(url)) = (item.title(), item.link()) {
if let Some(re) = &re {
if re.is_match(title) {
return Some((title, url));
}
} else {
return Some((title, url));
}
}
None
});
for (title, url) in items {
println!("downloading {title}");
let args = TorrentAddArgs {
filename: Some(url.to_string()),
..Default::default()
};
if let Err(e) = transclient.torrent_add(args).await {
bail!("error while adding a torrent: {e}")
}
}
Ok(())
}
29 changes: 29 additions & 0 deletions rm-main/src/cli/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
mod add_torrent;
mod fetch_rss;

use anyhow::Result;
use clap::{Parser, Subcommand};

use add_torrent::add_torrent;
use fetch_rss::fetch_rss;

#[derive(Parser)]
#[command(version, about)]
pub struct Args {
#[command(subcommand)]
pub command: Option<Commands>,
}

#[derive(Subcommand)]
pub enum Commands {
AddTorrent { torrent: String },
FetchRss { url: String, filter: Option<String> },
}

pub async fn handle_command(command: Commands) -> Result<()> {
match command {
Commands::AddTorrent { torrent } => add_torrent(torrent).await?,
Commands::FetchRss { url, filter } => fetch_rss(&url, filter.as_deref()).await?,
}
Ok(())
}
7 changes: 2 additions & 5 deletions rm-main/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
pub mod app;
mod cli;
pub mod transmission;
pub mod tui;
mod ui;

use app::App;
mod tui;

use anyhow::Result;
use clap::Parser;
use tui::app::App;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
Expand Down
3 changes: 2 additions & 1 deletion rm-main/src/transmission/fetchers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ use rm_config::CONFIG;
use tokio::sync::oneshot;
use transmission_rpc::types::TorrentGetField;

use crate::app;
use rm_shared::action::UpdateAction;

use crate::tui::app;

use super::TorrentAction;

pub async fn stats(ctx: app::Ctx) {
Expand Down
16 changes: 7 additions & 9 deletions rm-main/src/app.rs → rm-main/src/tui/app.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
use crossterm::event::Event;
use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;
use rm_config::CONFIG;
use rm_shared::action::Action;
use rm_shared::action::UpdateAction;
use std::sync::Arc;

use crate::ui::components::tabs::CurrentTab;
use crate::{
transmission::{self, TorrentAction},
tui::Tui,
ui::{components::Component, MainWindow},
tui::components::Component,
};

use rm_config::CONFIG;
use rm_shared::action::{Action, UpdateAction};

use anyhow::{Error, Result};
use crossterm::event::{Event, KeyCode, KeyModifiers};
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use transmission_rpc::{types::SessionGet, TransClient};

use super::{components::CurrentTab, main_window::MainWindow, terminal::Tui};

#[derive(Clone)]
pub struct Ctx {
pub session_info: Arc<SessionGet>,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use crossterm::event::{Event, KeyEvent};
use ratatui::{
prelude::*,
widgets::{Clear, Paragraph},
};
use rm_config::CONFIG;
use tui_input::{Input, InputRequest};
use tui_input::{backend::crossterm::to_input_request, Input, InputResponse};

use crate::ui::components::Component;
use crate::tui::components::Component;

pub struct InputManager {
input: Input,
Expand All @@ -31,8 +32,14 @@ impl InputManager {
self.input.to_string()
}

pub fn handle(&mut self, req: InputRequest) {
self.input.handle(req);
pub fn handle_key(&mut self, key: KeyEvent) -> InputResponse {
let event = Event::Key(key);

if let Some(req) = to_input_request(&event) {
self.input.handle(req)
} else {
None
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
pub mod table;
pub mod tabs;
mod input_manager;
mod table;
mod tabs;

pub use input_manager::InputManager;
pub use table::GenericTable;
pub use tabs::{CurrentTab, TabComponent};

use ratatui::prelude::*;
use ratatui::Frame;

use rm_shared::action::Action;
use rm_shared::action::UpdateAction;
pub use tabs::TabComponent;

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ComponentAction {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use crate::app;
use rm_config::CONFIG;
use rm_shared::action::Action;

use crate::tui::app;

use super::{Component, ComponentAction};
use ratatui::{layout::Flex, prelude::*, widgets::Tabs};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ use ratatui::{
widgets::{Block, Clear, Paragraph, Wrap},
};

use crate::ui::{
centered_rect,
use rm_shared::action::Action;

use crate::tui::{
components::{Component, ComponentAction},
main_window::centered_rect,
};
use rm_shared::action::Action;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorPopup {
Expand Down
Loading
Loading