Skip to content

Commit

Permalink
feat(activate on all rooms): virus protection can now be activated on…
Browse files Browse the repository at this point in the history
… all rooms.
  • Loading branch information
semtisem committed Sep 19, 2024
1 parent 2c7b8f1 commit d8b6ee0
Show file tree
Hide file tree
Showing 7 changed files with 175 additions and 51 deletions.
38 changes: 23 additions & 15 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ lazy_static = "1.4.0"
process_path = "0.1.4"
serde = { version = "1.0.197", features = ["derive"] }
tokio = { version = "1.36.0", features = ["full"] }
dco3 = "0.10.2"
dco3 = "0.16"

# logging and tracing
tracing = "0.1.40"
Expand Down
6 changes: 5 additions & 1 deletion config.example.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
dracoon:
base_url: https://dracoon.team
client_id: YOUR_CLIENT_ID
client_secret: YOUR_CLIENT_SECRET
logging:
log_level: info
log_file:
log_file_path: dracoon.log
activate_virus_protection: [] # data room ids to activate virus scan in including all sub rooms
activate_virus_protection:
activate_on_all_rooms: false # activate virus scan in all rooms - !!! be careful with this setting !!! files are blocked until scanned
room_ids: [] # data room ids to activate virus scan in including all sub rooms. Will be ignored when activate_on_all_rooms is set to true
28 changes: 20 additions & 8 deletions src/client/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ pub struct Client {}

impl Client {
#[allow(unused)]
pub async fn connect_password_flow(base_url: &String, client_id: String, client_secret: String) -> Dracoon<Connected> {
pub async fn connect_password_flow(
base_url: &String,
client_id: String,
client_secret: String,
) -> Dracoon<Connected> {
let dracoon = Dracoon::builder()
.with_base_url(base_url)
.with_client_id(client_id)
Expand All @@ -16,19 +20,25 @@ impl Client {
let username = "test".to_string();
let password = "test".to_string();

dracoon.connect(OAuth2Flow::PasswordFlow(username, password))
.await.unwrap()
dracoon
.connect(OAuth2Flow::PasswordFlow(username, password))
.await
.unwrap()
}

#[allow(unused)]
pub async fn connect_auth_code_flow(base_url: &String, client_id: String, client_secret: String) -> Dracoon<Connected> {
pub async fn connect_auth_code_flow(
base_url: &String,
client_id: &String,
client_secret: &String,
) -> Dracoon<Connected> {
let dracoon = Dracoon::builder()
.with_base_url(base_url)
.with_client_id(client_id)
.with_client_secret(client_secret)
.with_redirect_uri(base_url.to_owned() + "/oauth/callback")
.build()
.unwrap();
.unwrap();

println!("Please log in via browser (open url): ");
println!("{}", dracoon.get_authorize_url());
Expand All @@ -38,7 +48,9 @@ impl Client {
.interact()
.unwrap();

dracoon.connect(OAuth2Flow::AuthCodeFlow(auth_code.trim_end().into()))
.await.unwrap()
dracoon
.connect(OAuth2Flow::AuthCodeFlow(auth_code.trim_end().into()))
.await
.unwrap()
}
}
}
38 changes: 35 additions & 3 deletions src/config/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::sync::OnceLock;
pub struct ScriptConfig {
dracoon: DracoonConfig,
logging: LoggingConfig,
activate_virus_protection: Vec<u64>,
activate_virus_protection: VirusProtectionConfig,
}

#[derive(Deserialize, Debug, Clone)]
Expand Down Expand Up @@ -46,12 +46,44 @@ impl LoggingConfig {
#[derive(Deserialize, Debug, Clone)]
pub struct DracoonConfig {
base_url: String,
client_id: String,
client_secret: String,
}

impl DracoonConfig {
pub fn get_base_url(&self) -> &String {
&self.base_url
}

pub fn get_client_id(&self) -> &String {
&self.client_id
}

pub fn get_client_secret(&self) -> &String {
&self.client_secret
}
}

#[derive(Deserialize, Debug, Clone)]
pub struct VirusProtectionConfig {
activate_on_all_rooms: bool,
room_ids: Vec<u64>,
}

impl VirusProtectionConfig {
pub fn activate_on_all_rooms(&self) -> bool {
self.activate_on_all_rooms
}

pub fn get_room_ids(&self) -> Vec<Option<u64>> {
if self.activate_on_all_rooms {
return vec![None];
} else {
let room_ids = self.room_ids.iter().map(|id| Some(*id)).collect();

return room_ids;
}
}
}

#[derive(Deserialize, Debug, Clone)]
Expand Down Expand Up @@ -105,8 +137,8 @@ impl ScriptConfig {
&self.logging
}

pub fn get_virus_protection_rooms(&self) -> &Vec<u64> {
&self.activate_virus_protection
pub fn get_virus_protection_rooms(&self) -> Vec<Option<u64>> {
self.activate_virus_protection.get_room_ids()
}

pub fn get_dracoon_config(&self) -> &DracoonConfig {
Expand Down
54 changes: 31 additions & 23 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use dco3::auth::Connected;
use dco3::nodes::{Node, NodesFilter, RoomPoliciesRequest};
use dco3::{Dracoon, DracoonClientError, ListAllParams, Nodes, Rooms};
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use models::{NodePermission, PermissionFilter};
use tracing::{error, info};

use crate::config::ScriptConfig;
Expand All @@ -15,20 +16,18 @@ use crate::logging::Logging;
mod client;
mod config;
mod logging;
mod models;

#[tokio::main]
async fn main() {
const CLIENT_ID: &str = "Q8dTruVvswW5Iyi0QWqiZFKP8gFgFjnZ";
const CLIENT_SECRET: &str = "nhh27DqlmFEjf5ijVAN0ZoBdhKMDu4lv";

let config = ScriptConfig::init(None);
Logging::setup(config.get_logging_config());
let term = Term::stdout();

let dracoon = Client::connect_auth_code_flow(
config.get_dracoon_config().get_base_url(),
CLIENT_ID.to_owned(),
CLIENT_SECRET.to_owned(),
config.get_dracoon_config().get_client_id(),
config.get_dracoon_config().get_client_secret(),
)
.await;
let mut collected_rooms = Vec::new();
Expand All @@ -46,17 +45,20 @@ async fn main() {
multibar.add(bar.clone());

for room_id in config.get_virus_protection_rooms() {
if *room_id == 0 {
error!("Room id is 0. Activating virus protection for every room is not allowed.");
continue;
}
bar.set_message(std::format!(
"Processing room with id: {}. Fetching all sub rooms",
"Processing room with id: {:?}. Fetching all sub rooms",
room_id
));

let current_room = dracoon.nodes.get_node(*room_id).await.unwrap();
collected_rooms.push(current_room);
if room_id.is_some() {
let current_room = dracoon
.nodes()
.get_node(room_id.expect("Must be some"))
.await
.unwrap();
collected_rooms.push(current_room);
}

let temp_vec = &mut Vec::new();

let bar_sub_rooms = ProgressBar::new_spinner();
Expand All @@ -68,15 +70,14 @@ async fn main() {
bar_sub_rooms.enable_steady_tick(Duration::from_millis(120));

multibar.add(bar_sub_rooms.clone());
let rooms =
get_all_room_children(&dracoon, *room_id, temp_vec, bar_sub_rooms.clone()).await;
let rooms = get_all_room_children(&dracoon, room_id, temp_vec, bar_sub_rooms.clone()).await;
match rooms {
Ok(rooms) => {
collected_rooms.extend(rooms.iter().cloned());
}
Err(e) => {
error!(
"Error while fetching rooms for room with id: {}. Error: {}",
"Error while fetching rooms for room with id: {:?}. Error: {}",
room_id, e
);
}
Expand Down Expand Up @@ -117,22 +118,25 @@ async fn main() {
#[async_recursion]
async fn get_all_room_children<'a>(
dracoon: &'a Dracoon<Connected>,
room_id: u64,
room_id: Option<u64>,
collected_room_ids: &'a mut Vec<Node>,
sub_bar: ProgressBar,
) -> Result<&'a mut Vec<Node>, DracoonClientError> {
let params = ListAllParams::builder()
.with_filter(NodesFilter::is_room())
.with_filter(PermissionFilter::has_permission(NodePermission::Manage))
.build();

info!("params {:?}", params);

sub_bar.set_message(std::format!(
"Fetching sub rooms for room with id: {}",
"Fetching sub rooms for room with id: {:?}",
room_id
));

let rooms_res = dracoon
.nodes
.get_nodes(Some(room_id), None, Some(params))
.nodes()
.get_nodes(room_id, None, Some(params))
.await
.unwrap();
let mut room_list = rooms_res.items.clone();
Expand All @@ -143,12 +147,13 @@ async fn get_all_room_children<'a>(
while offset < rooms_res.range.total {
let params_with_offset = ListAllParams::builder()
.with_filter(NodesFilter::is_room())
.with_filter(PermissionFilter::has_permission(NodePermission::Manage))
.with_offset(offset)
.build();

let rooms_res_offset = dracoon
.nodes
.get_nodes(Some(room_id), None, Some(params_with_offset))
.nodes()
.get_nodes(room_id, None, Some(params_with_offset))
.await;
if let Ok(rooms_res_offset) = rooms_res_offset {
room_list.extend(rooms_res_offset.items);
Expand All @@ -164,7 +169,7 @@ async fn get_all_room_children<'a>(
for room in room_list.iter() {
if let Some(cnt_rooms) = room.cnt_rooms {
if cnt_rooms > 0 {
get_all_room_children(dracoon, room.id, collected_room_ids, sub_bar.clone())
get_all_room_children(dracoon, Some(room.id), collected_room_ids, sub_bar.clone())
.await?;
}
}
Expand All @@ -183,7 +188,10 @@ async fn activate_virus_protection(
let policies = RoomPoliciesRequest::builder()
.with_virus_protection_enabled(true)
.build();
let response = dracoon.nodes.update_room_policies(room.id, policies).await;
let response = dracoon
.nodes()
.update_room_policies(room.id, policies)
.await;
match response {
Ok(_) => {
info!(
Expand Down
Loading

0 comments on commit d8b6ee0

Please sign in to comment.