@onxdev/silentium 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Cargo.lock +1194 -0
- package/Cargo.toml +37 -0
- package/LICENSE +21 -0
- package/README.md +314 -2
- package/npm/bin/silentium.js +45 -0
- package/npm/install.js +31 -0
- package/npm/lib.js +220 -0
- package/package.json +44 -4
- package/rust-toolchain.toml +2 -0
- package/src/cli.rs +146 -0
- package/src/detect.rs +248 -0
- package/src/discord.rs +273 -0
- package/src/main.rs +347 -0
- package/src/net.rs +371 -0
- package/src/ui.rs +414 -0
- package/src/update.rs +385 -0
package/src/discord.rs
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
use anyhow::{anyhow, bail, Context, Result};
|
|
2
|
+
use serde::Deserialize;
|
|
3
|
+
use serde_json::{json, Value};
|
|
4
|
+
use std::thread::sleep;
|
|
5
|
+
use std::time::Duration;
|
|
6
|
+
|
|
7
|
+
const API: &str = "https://discord.com/api/v10";
|
|
8
|
+
|
|
9
|
+
#[derive(Debug, Deserialize)]
|
|
10
|
+
pub struct Me {
|
|
11
|
+
pub id: String,
|
|
12
|
+
pub username: String,
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
#[derive(Debug, Deserialize)]
|
|
16
|
+
pub struct User {
|
|
17
|
+
pub id: String,
|
|
18
|
+
pub username: String,
|
|
19
|
+
#[serde(default)]
|
|
20
|
+
pub bot: bool,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
#[derive(Debug, Deserialize)]
|
|
24
|
+
pub struct Member {
|
|
25
|
+
pub user: User,
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
#[derive(Debug, Deserialize)]
|
|
29
|
+
pub struct VoiceState {
|
|
30
|
+
#[allow(dead_code)]
|
|
31
|
+
pub user_id: String,
|
|
32
|
+
pub channel_id: Option<String>,
|
|
33
|
+
#[serde(default)]
|
|
34
|
+
pub mute: bool,
|
|
35
|
+
#[serde(default)]
|
|
36
|
+
pub deaf: bool,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
#[derive(Debug, Deserialize)]
|
|
40
|
+
pub struct InviteTarget {
|
|
41
|
+
pub guild: Option<InviteGuild>,
|
|
42
|
+
pub channel: Option<InviteChannel>,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
#[derive(Debug, Deserialize)]
|
|
46
|
+
pub struct InviteGuild {
|
|
47
|
+
pub id: String,
|
|
48
|
+
pub name: String,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
#[derive(Debug, Deserialize)]
|
|
52
|
+
pub struct InviteChannel {
|
|
53
|
+
pub id: String,
|
|
54
|
+
pub name: String,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
pub struct Api {
|
|
58
|
+
agent: ureq::Agent,
|
|
59
|
+
header: String,
|
|
60
|
+
pub dry_run: bool,
|
|
61
|
+
pub delay_ms: u64,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
impl Api {
|
|
65
|
+
pub fn new(token: String, dry_run: bool, delay_ms: u64, user_token: bool) -> Self {
|
|
66
|
+
let agent = ureq::AgentBuilder::new()
|
|
67
|
+
.timeout_connect(Duration::from_secs(10))
|
|
68
|
+
.timeout(Duration::from_secs(30))
|
|
69
|
+
.build();
|
|
70
|
+
let header = if user_token {
|
|
71
|
+
token
|
|
72
|
+
} else {
|
|
73
|
+
format!("Bot {token}")
|
|
74
|
+
};
|
|
75
|
+
Self {
|
|
76
|
+
agent,
|
|
77
|
+
header,
|
|
78
|
+
dry_run,
|
|
79
|
+
delay_ms,
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
fn auth(&self, req: ureq::Request) -> ureq::Request {
|
|
84
|
+
req.set("Authorization", &self.header)
|
|
85
|
+
.set("User-Agent", "Silentium/0.1 (local)")
|
|
86
|
+
.set("Content-Type", "application/json")
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
fn raw(&self, method: &str, path: &str, body: Option<Value>) -> Result<Value> {
|
|
90
|
+
let url = format!("{API}{path}");
|
|
91
|
+
loop {
|
|
92
|
+
let req = self.auth(self.agent.request(method, &url));
|
|
93
|
+
let sent = match &body {
|
|
94
|
+
Some(payload) => req.send_json(payload.clone()),
|
|
95
|
+
None => req.call(),
|
|
96
|
+
};
|
|
97
|
+
match sent {
|
|
98
|
+
Ok(resp) => {
|
|
99
|
+
if resp.status() == 204 {
|
|
100
|
+
return Ok(Value::Null);
|
|
101
|
+
}
|
|
102
|
+
return resp.into_json::<Value>().context("resposta não-JSON");
|
|
103
|
+
}
|
|
104
|
+
Err(ureq::Error::Status(code, resp)) => {
|
|
105
|
+
let payload = resp.into_json::<Value>().unwrap_or(Value::Null);
|
|
106
|
+
if code == 429 {
|
|
107
|
+
let wait = payload
|
|
108
|
+
.get("retry_after")
|
|
109
|
+
.and_then(Value::as_f64)
|
|
110
|
+
.unwrap_or(1.5);
|
|
111
|
+
sleep(Duration::from_millis((wait * 1000.0) as u64 + 120));
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
let msg = payload
|
|
115
|
+
.get("message")
|
|
116
|
+
.and_then(Value::as_str)
|
|
117
|
+
.unwrap_or("sem mensagem");
|
|
118
|
+
bail!("{method} {path} -> HTTP {code}: {msg}");
|
|
119
|
+
}
|
|
120
|
+
Err(err) => bail!("{method} {path} falhou: {err}"),
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
fn pause(&self) {
|
|
126
|
+
if self.delay_ms > 0 {
|
|
127
|
+
sleep(Duration::from_millis(self.delay_ms));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
pub fn me(&self) -> Result<Me> {
|
|
132
|
+
let raw = self.raw("GET", "/users/@me", None)?;
|
|
133
|
+
serde_json::from_value(raw).context("payload de /users/@me inesperado")
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
pub fn resolve_invite(&self, invite: &str) -> Result<InviteTarget> {
|
|
137
|
+
let code = invite_code(invite)?;
|
|
138
|
+
let raw = self.raw("GET", &format!("/invites/{code}?with_counts=true"), None)?;
|
|
139
|
+
serde_json::from_value(raw).context("payload de /invites inesperado")
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
pub fn members(&self, guild: &str) -> Result<Vec<Member>> {
|
|
143
|
+
let mut out: Vec<Member> = Vec::new();
|
|
144
|
+
let mut after = String::from("0");
|
|
145
|
+
loop {
|
|
146
|
+
let page = self.raw(
|
|
147
|
+
"GET",
|
|
148
|
+
&format!("/guilds/{guild}/members?limit=1000&after={after}"),
|
|
149
|
+
None,
|
|
150
|
+
)?;
|
|
151
|
+
let batch: Vec<Member> =
|
|
152
|
+
serde_json::from_value(page).context("payload de /members inesperado")?;
|
|
153
|
+
let len = batch.len();
|
|
154
|
+
if let Some(last) = batch.last() {
|
|
155
|
+
after.clone_from(&last.user.id);
|
|
156
|
+
}
|
|
157
|
+
out.extend(batch);
|
|
158
|
+
if len < 1000 {
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
self.pause();
|
|
162
|
+
}
|
|
163
|
+
Ok(out)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
pub fn voice_state(&self, guild: &str, user: &str) -> Result<Option<VoiceState>> {
|
|
167
|
+
let url = format!("{API}/guilds/{guild}/voice-states/{user}");
|
|
168
|
+
let req = self
|
|
169
|
+
.agent
|
|
170
|
+
.get(&url)
|
|
171
|
+
.set("Authorization", &self.header)
|
|
172
|
+
.set("User-Agent", "Silentium/0.1 (local)");
|
|
173
|
+
match req.call() {
|
|
174
|
+
Ok(resp) => {
|
|
175
|
+
let payload = resp.into_json::<Value>().unwrap_or(Value::Null);
|
|
176
|
+
Ok(serde_json::from_value::<VoiceState>(payload).ok())
|
|
177
|
+
}
|
|
178
|
+
Err(ureq::Error::Status(404, _)) => Ok(None),
|
|
179
|
+
Err(ureq::Error::Status(code, resp)) => {
|
|
180
|
+
let payload = resp.into_json::<Value>().unwrap_or(Value::Null);
|
|
181
|
+
let msg = payload
|
|
182
|
+
.get("message")
|
|
183
|
+
.and_then(Value::as_str)
|
|
184
|
+
.unwrap_or("sem mensagem");
|
|
185
|
+
bail!("GET voice-states -> HTTP {code}: {msg}");
|
|
186
|
+
}
|
|
187
|
+
Err(err) => Err(anyhow!("GET voice-states falhou: {err}")),
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
pub fn patch_member(&self, guild: &str, user: &str, body: &Value) -> Result<()> {
|
|
192
|
+
if self.dry_run {
|
|
193
|
+
println!(" [dry-run] PATCH /guilds/{guild}/members/{user} {body}");
|
|
194
|
+
return Ok(());
|
|
195
|
+
}
|
|
196
|
+
self.raw(
|
|
197
|
+
"PATCH",
|
|
198
|
+
&format!("/guilds/{guild}/members/{user}"),
|
|
199
|
+
Some(body.clone()),
|
|
200
|
+
)?;
|
|
201
|
+
Ok(())
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
pub fn body_for(action: &str) -> Result<Value> {
|
|
205
|
+
Ok(match action {
|
|
206
|
+
"drop" => json!({ "channel_id": null }),
|
|
207
|
+
"mute" => json!({ "mute": true }),
|
|
208
|
+
"unmute" => json!({ "mute": false }),
|
|
209
|
+
"deafen" => json!({ "deaf": true }),
|
|
210
|
+
"undeafen" => json!({ "deaf": false }),
|
|
211
|
+
"restore" => json!({ "mute": false, "deaf": false }),
|
|
212
|
+
other => bail!("ação desconhecida: {other}"),
|
|
213
|
+
})
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
pub fn invite_code(raw: &str) -> Result<String> {
|
|
218
|
+
let trimmed = raw.trim().trim_end_matches('/');
|
|
219
|
+
let tail = trimmed.rsplit('/').next().unwrap_or(trimmed);
|
|
220
|
+
let code = tail.split(['?', '#']).next().unwrap_or(tail);
|
|
221
|
+
let valido = !code.is_empty() && code.len() <= 64 && !code.contains('.') && !code.contains(':');
|
|
222
|
+
if !valido {
|
|
223
|
+
bail!("convite inválido: {raw}");
|
|
224
|
+
}
|
|
225
|
+
Ok(code.to_string())
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
#[cfg(test)]
|
|
229
|
+
mod tests {
|
|
230
|
+
use super::{invite_code, Api};
|
|
231
|
+
use serde_json::json;
|
|
232
|
+
|
|
233
|
+
#[test]
|
|
234
|
+
fn extrai_codigo_de_varias_formas() {
|
|
235
|
+
for raw in [
|
|
236
|
+
"discord.gg/abc123",
|
|
237
|
+
"https://discord.gg/abc123",
|
|
238
|
+
"https://discord.gg/abc123/",
|
|
239
|
+
"https://discord.com/invite/abc123?event=1",
|
|
240
|
+
"abc123",
|
|
241
|
+
] {
|
|
242
|
+
assert_eq!(invite_code(raw).unwrap(), "abc123", "entrada: {raw}");
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
#[test]
|
|
247
|
+
fn rejeita_convite_vazio() {
|
|
248
|
+
assert!(invite_code("https://discord.gg/").is_err());
|
|
249
|
+
assert!(invite_code("").is_err());
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
#[test]
|
|
253
|
+
fn corpo_do_drop_zera_canal() {
|
|
254
|
+
assert_eq!(
|
|
255
|
+
Api::body_for("drop").unwrap(),
|
|
256
|
+
json!({ "channel_id": null })
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
#[test]
|
|
261
|
+
fn corpo_do_restore_limpa_estado() {
|
|
262
|
+
assert_eq!(
|
|
263
|
+
Api::body_for("restore").unwrap(),
|
|
264
|
+
json!({ "mute": false, "deaf": false })
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
#[test]
|
|
269
|
+
fn acao_invalida_falha() {
|
|
270
|
+
assert!(Api::body_for("explodir").is_err());
|
|
271
|
+
assert!(Api::body_for("drop").is_ok());
|
|
272
|
+
}
|
|
273
|
+
}
|
package/src/main.rs
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
mod cli;
|
|
2
|
+
mod detect;
|
|
3
|
+
mod discord;
|
|
4
|
+
mod net;
|
|
5
|
+
mod ui;
|
|
6
|
+
mod update;
|
|
7
|
+
|
|
8
|
+
use anyhow::{bail, Context, Result};
|
|
9
|
+
use clap::Parser;
|
|
10
|
+
use cli::{Cli, Cmd, NetCmd, TargetArgs, VoiceCmd};
|
|
11
|
+
use discord::Api;
|
|
12
|
+
use std::collections::HashSet;
|
|
13
|
+
use std::sync::atomic::{AtomicBool, Ordering};
|
|
14
|
+
use std::sync::Arc;
|
|
15
|
+
use std::thread::sleep;
|
|
16
|
+
use std::time::Duration;
|
|
17
|
+
|
|
18
|
+
struct Target {
|
|
19
|
+
user_id: String,
|
|
20
|
+
name: String,
|
|
21
|
+
channel_id: String,
|
|
22
|
+
mute: bool,
|
|
23
|
+
deaf: bool,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
fn main() {
|
|
27
|
+
if let Err(err) = run() {
|
|
28
|
+
eprintln!("error: {err:#}");
|
|
29
|
+
std::process::exit(1);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
fn run() -> Result<()> {
|
|
34
|
+
let cli = Cli::parse();
|
|
35
|
+
match cli.cmd.clone() {
|
|
36
|
+
None => ui::interactive(&cli),
|
|
37
|
+
Some(Cmd::Net(cmd)) => net_dispatch(&cmd),
|
|
38
|
+
Some(Cmd::Whoami) => {
|
|
39
|
+
let api = build_api(&cli)?;
|
|
40
|
+
let me = api.me()?;
|
|
41
|
+
println!("bot: {} ({})", me.username, me.id);
|
|
42
|
+
Ok(())
|
|
43
|
+
}
|
|
44
|
+
Some(Cmd::Detect) => print_detect(),
|
|
45
|
+
Some(Cmd::Resolve { invite }) => {
|
|
46
|
+
let api = build_api(&cli)?;
|
|
47
|
+
let resolved = api.resolve_invite(&invite)?;
|
|
48
|
+
match (resolved.guild, resolved.channel) {
|
|
49
|
+
(Some(guild), Some(channel)) => println!(
|
|
50
|
+
"guild={} nome={:?}\ncanal={} nome={:?}",
|
|
51
|
+
guild.id, guild.name, channel.id, channel.name
|
|
52
|
+
),
|
|
53
|
+
(Some(guild), None) => println!("guild={} nome={:?}", guild.id, guild.name),
|
|
54
|
+
_ => println!("convite não aponta para servidor (DM ou inválido)"),
|
|
55
|
+
}
|
|
56
|
+
Ok(())
|
|
57
|
+
}
|
|
58
|
+
Some(Cmd::Update { check }) => update::run(check),
|
|
59
|
+
Some(Cmd::Voice(cmd)) => voice_dispatch(&cli, &cmd),
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/// Imprime o estado da call olhando só os sockets locais do Discord.
|
|
64
|
+
pub(crate) fn print_detect() -> Result<()> {
|
|
65
|
+
let peers = detect::voice_peers()?;
|
|
66
|
+
let voice: Vec<_> = peers.iter().filter(|p| p.is_voice()).collect();
|
|
67
|
+
if voice.is_empty() {
|
|
68
|
+
println!("nenhuma call ativa");
|
|
69
|
+
if !peers.is_empty() {
|
|
70
|
+
println!("sockets do Discord fora da faixa de voz (gateway/QUIC):");
|
|
71
|
+
for peer in &peers {
|
|
72
|
+
println!(" {} pid={} ({})", peer.endpoint(), peer.pid, peer.process);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
} else {
|
|
76
|
+
println!("call ativa, {} socket(s) de mídia:", voice.len());
|
|
77
|
+
for peer in voice {
|
|
78
|
+
println!(" {} pid={} ({})", peer.endpoint(), peer.pid, peer.process);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
Ok(())
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
fn build_api(cli: &Cli) -> Result<Api> {
|
|
85
|
+
let token = cli
|
|
86
|
+
.token
|
|
87
|
+
.clone()
|
|
88
|
+
.context("faltou --token ou DISCORD_TOKEN")?;
|
|
89
|
+
Ok(Api::new(token, cli.dry_run, cli.delay_ms, cli.user_token))
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
fn resolve_scope(api: &Api, cli: &Cli, target: &TargetArgs) -> Result<(String, Option<String>)> {
|
|
93
|
+
if let Some(invite) = &target.invite {
|
|
94
|
+
let resolved = api.resolve_invite(invite)?;
|
|
95
|
+
let guild = resolved
|
|
96
|
+
.guild
|
|
97
|
+
.context("convite não aponta para um servidor")?;
|
|
98
|
+
let channel = target
|
|
99
|
+
.channel
|
|
100
|
+
.clone()
|
|
101
|
+
.or_else(|| resolved.channel.map(|c| c.id));
|
|
102
|
+
return Ok((guild.id, channel));
|
|
103
|
+
}
|
|
104
|
+
let guild = cli.guild.clone().context("faltou --guild ou um --invite")?;
|
|
105
|
+
Ok((guild, target.channel.clone()))
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
fn collect_targets(
|
|
109
|
+
api: &Api,
|
|
110
|
+
guild: &str,
|
|
111
|
+
channel: Option<&str>,
|
|
112
|
+
explicit: &[String],
|
|
113
|
+
) -> Result<Vec<Target>> {
|
|
114
|
+
if !explicit.is_empty() {
|
|
115
|
+
let mut out = Vec::new();
|
|
116
|
+
for uid in explicit {
|
|
117
|
+
match api.voice_state(guild, uid)? {
|
|
118
|
+
Some(state) => out.push(Target {
|
|
119
|
+
user_id: uid.clone(),
|
|
120
|
+
name: uid.clone(),
|
|
121
|
+
channel_id: state.channel_id.unwrap_or_default(),
|
|
122
|
+
mute: state.mute,
|
|
123
|
+
deaf: state.deaf,
|
|
124
|
+
}),
|
|
125
|
+
None => eprintln!("[!] {uid} não está em voz"),
|
|
126
|
+
}
|
|
127
|
+
pause(api);
|
|
128
|
+
}
|
|
129
|
+
return Ok(out);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
let mut out = Vec::new();
|
|
133
|
+
for member in api.members(guild)? {
|
|
134
|
+
if member.user.bot {
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if let Some(state) = api.voice_state(guild, &member.user.id)? {
|
|
138
|
+
let channel_id = state.channel_id.clone().unwrap_or_default();
|
|
139
|
+
if let Some(want) = channel {
|
|
140
|
+
if channel_id != want {
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
out.push(Target {
|
|
145
|
+
user_id: member.user.id,
|
|
146
|
+
name: member.user.username,
|
|
147
|
+
channel_id,
|
|
148
|
+
mute: state.mute,
|
|
149
|
+
deaf: state.deaf,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
pause(api);
|
|
153
|
+
}
|
|
154
|
+
Ok(out)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
fn pause(api: &Api) {
|
|
158
|
+
if api.delay_ms > 0 {
|
|
159
|
+
sleep(Duration::from_millis(api.delay_ms));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
pub(crate) fn voice_dispatch(cli: &Cli, cmd: &VoiceCmd) -> Result<()> {
|
|
164
|
+
let api = build_api(cli)?;
|
|
165
|
+
|
|
166
|
+
if let VoiceCmd::Guard {
|
|
167
|
+
target,
|
|
168
|
+
action,
|
|
169
|
+
interval,
|
|
170
|
+
} = cmd
|
|
171
|
+
{
|
|
172
|
+
return run_guard(&api, cli, target, action, *interval);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
let (target, action) = match cmd {
|
|
176
|
+
VoiceCmd::List(t) => (t, "list"),
|
|
177
|
+
VoiceCmd::Drop(t) => (t, "drop"),
|
|
178
|
+
VoiceCmd::Mute(t) => (t, "mute"),
|
|
179
|
+
VoiceCmd::Unmute(t) => (t, "unmute"),
|
|
180
|
+
VoiceCmd::Deafen(t) => (t, "deafen"),
|
|
181
|
+
VoiceCmd::Undeafen(t) => (t, "undeafen"),
|
|
182
|
+
VoiceCmd::Restore(t) => (t, "restore"),
|
|
183
|
+
VoiceCmd::Guard { .. } => unreachable!(),
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
let (guild, channel) = resolve_scope(&api, cli, target)?;
|
|
187
|
+
let targets = collect_targets(&api, &guild, channel.as_deref(), &target.user)?;
|
|
188
|
+
|
|
189
|
+
if targets.is_empty() {
|
|
190
|
+
println!("ninguém em voz no escopo");
|
|
191
|
+
return Ok(());
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if action == "list" {
|
|
195
|
+
println!(
|
|
196
|
+
"{:<20} {:<22} {:<20} mute deaf",
|
|
197
|
+
"user_id", "nome", "canal"
|
|
198
|
+
);
|
|
199
|
+
for t in &targets {
|
|
200
|
+
println!(
|
|
201
|
+
"{:<20} {:<22} {:<20} {:<5} {}",
|
|
202
|
+
t.user_id, t.name, t.channel_id, t.mute, t.deaf
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
println!("total: {}", targets.len());
|
|
206
|
+
return Ok(());
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
let body = Api::body_for(action)?;
|
|
210
|
+
println!("ação={action} alvos={}", targets.len());
|
|
211
|
+
let mut ok = 0usize;
|
|
212
|
+
for t in &targets {
|
|
213
|
+
match api.patch_member(&guild, &t.user_id, &body) {
|
|
214
|
+
Ok(()) => {
|
|
215
|
+
ok += 1;
|
|
216
|
+
println!(" ok {} ({})", t.user_id, t.name);
|
|
217
|
+
}
|
|
218
|
+
Err(err) => println!(" falha {} ({}): {err}", t.user_id, t.name),
|
|
219
|
+
}
|
|
220
|
+
pause(&api);
|
|
221
|
+
}
|
|
222
|
+
println!("{ok}/{} aplicados", targets.len());
|
|
223
|
+
Ok(())
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
fn run_guard(api: &Api, cli: &Cli, target: &TargetArgs, action: &str, interval: u64) -> Result<()> {
|
|
227
|
+
let (guild, channel) = resolve_scope(api, cli, target)?;
|
|
228
|
+
let body = Api::body_for(action)?;
|
|
229
|
+
let mut seen: HashSet<String> = HashSet::new();
|
|
230
|
+
|
|
231
|
+
let running = Arc::new(AtomicBool::new(true));
|
|
232
|
+
let flag = running.clone();
|
|
233
|
+
ctrlc::set_handler(move || flag.store(false, Ordering::SeqCst))
|
|
234
|
+
.context("não consegui instalar handler de Ctrl-C")?;
|
|
235
|
+
|
|
236
|
+
println!("[+] vigiando guild {guild} (ação: {action}, a cada {interval}s)");
|
|
237
|
+
|
|
238
|
+
while running.load(Ordering::SeqCst) {
|
|
239
|
+
match collect_targets(api, &guild, channel.as_deref(), &target.user) {
|
|
240
|
+
Ok(current) => {
|
|
241
|
+
for t in current {
|
|
242
|
+
if seen.insert(t.user_id.clone()) {
|
|
243
|
+
match api.patch_member(&guild, &t.user_id, &body) {
|
|
244
|
+
Ok(()) => println!(" {action} -> {} ({})", t.user_id, t.name),
|
|
245
|
+
Err(err) => println!(" falha em {}: {err}", t.user_id),
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
Err(err) => eprintln!("[!] tick falhou: {err}"),
|
|
251
|
+
}
|
|
252
|
+
for _ in 0..interval {
|
|
253
|
+
if !running.load(Ordering::SeqCst) {
|
|
254
|
+
break;
|
|
255
|
+
}
|
|
256
|
+
sleep(Duration::from_secs(1));
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
println!("[+] guard encerrado");
|
|
261
|
+
Ok(())
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
fn wait_window(seconds: Option<u64>, hint: &str) -> Result<()> {
|
|
265
|
+
let running = Arc::new(AtomicBool::new(true));
|
|
266
|
+
let flag = running.clone();
|
|
267
|
+
ctrlc::set_handler(move || flag.store(false, Ordering::SeqCst))
|
|
268
|
+
.context("não consegui instalar handler de Ctrl-C")?;
|
|
269
|
+
|
|
270
|
+
match seconds {
|
|
271
|
+
Some(secs) => {
|
|
272
|
+
println!("[+] ativo por {secs}s ({hint})");
|
|
273
|
+
let mut left = secs;
|
|
274
|
+
while left > 0 && running.load(Ordering::SeqCst) {
|
|
275
|
+
sleep(Duration::from_secs(1));
|
|
276
|
+
left -= 1;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
None => {
|
|
280
|
+
println!("[+] ativo — {hint}");
|
|
281
|
+
while running.load(Ordering::SeqCst) {
|
|
282
|
+
sleep(Duration::from_millis(250));
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
Ok(())
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
fn net_dispatch(cmd: &NetCmd) -> Result<()> {
|
|
290
|
+
match cmd {
|
|
291
|
+
NetCmd::Clear { iface } => net::clear(iface.clone()),
|
|
292
|
+
NetCmd::Unblock => net::unblock(),
|
|
293
|
+
NetCmd::Auto { seconds, force } => {
|
|
294
|
+
let peers: Vec<_> = detect::voice_peers()?
|
|
295
|
+
.into_iter()
|
|
296
|
+
.filter(|p| p.is_voice())
|
|
297
|
+
.collect();
|
|
298
|
+
if peers.is_empty() {
|
|
299
|
+
if !force {
|
|
300
|
+
println!(
|
|
301
|
+
"[-] nenhuma call de voz detectada (use --force para cortar assim mesmo)"
|
|
302
|
+
);
|
|
303
|
+
return Ok(());
|
|
304
|
+
}
|
|
305
|
+
println!("[!] sem call de voz, cortando por --force");
|
|
306
|
+
} else {
|
|
307
|
+
let list: Vec<String> = peers.iter().map(|p| p.endpoint()).collect();
|
|
308
|
+
println!("[+] call ativa: {}", list.join(", "));
|
|
309
|
+
}
|
|
310
|
+
net::block()?;
|
|
311
|
+
let waited = wait_window(*seconds, "Enter ou Ctrl-C para restaurar");
|
|
312
|
+
net::unblock().and(waited)
|
|
313
|
+
}
|
|
314
|
+
NetCmd::Block { seconds } => {
|
|
315
|
+
net::block()?;
|
|
316
|
+
let result = wait_window(*seconds, "Enter ou Ctrl-C para restaurar");
|
|
317
|
+
let restored = net::unblock();
|
|
318
|
+
result.and(restored)
|
|
319
|
+
}
|
|
320
|
+
NetCmd::Throttle {
|
|
321
|
+
kbps,
|
|
322
|
+
loss,
|
|
323
|
+
delay,
|
|
324
|
+
seconds,
|
|
325
|
+
iface,
|
|
326
|
+
} => {
|
|
327
|
+
if *kbps == 0 {
|
|
328
|
+
bail!("--kbps precisa ser maior que zero");
|
|
329
|
+
}
|
|
330
|
+
if let Some(loss) = loss {
|
|
331
|
+
if *loss > 100 {
|
|
332
|
+
bail!("--loss vai de 0 a 100");
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
let spec = net::ShapeSpec {
|
|
336
|
+
rate_kbps: *kbps,
|
|
337
|
+
loss_percent: *loss,
|
|
338
|
+
delay_ms: *delay,
|
|
339
|
+
iface: iface.clone(),
|
|
340
|
+
};
|
|
341
|
+
net::apply(&spec)?;
|
|
342
|
+
|
|
343
|
+
let waited = wait_window(*seconds, "Ctrl-C restaura agora");
|
|
344
|
+
net::clear(iface.clone()).and(waited)
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
}
|