@onxdev/silentium 0.1.0 → 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 +76 -4
- package/Cargo.toml +2 -1
- package/README.md +280 -20
- package/package.json +1 -1
- package/src/cli.rs +6 -0
- package/src/main.rs +2 -0
- package/src/ui.rs +44 -3
- package/src/update.rs +385 -0
package/Cargo.lock
CHANGED
|
@@ -76,6 +76,15 @@ version = "2.13.2"
|
|
|
76
76
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
77
77
|
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
|
78
78
|
|
|
79
|
+
[[package]]
|
|
80
|
+
name = "block-buffer"
|
|
81
|
+
version = "0.10.4"
|
|
82
|
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
83
|
+
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
|
84
|
+
dependencies = [
|
|
85
|
+
"generic-array",
|
|
86
|
+
]
|
|
87
|
+
|
|
79
88
|
[[package]]
|
|
80
89
|
name = "block2"
|
|
81
90
|
version = "0.6.2"
|
|
@@ -169,6 +178,15 @@ version = "0.8.7"
|
|
|
169
178
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
170
179
|
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
|
171
180
|
|
|
181
|
+
[[package]]
|
|
182
|
+
name = "cpufeatures"
|
|
183
|
+
version = "0.2.17"
|
|
184
|
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
185
|
+
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
|
186
|
+
dependencies = [
|
|
187
|
+
"libc",
|
|
188
|
+
]
|
|
189
|
+
|
|
172
190
|
[[package]]
|
|
173
191
|
name = "crc32fast"
|
|
174
192
|
version = "1.5.5"
|
|
@@ -178,6 +196,16 @@ dependencies = [
|
|
|
178
196
|
"cfg-if",
|
|
179
197
|
]
|
|
180
198
|
|
|
199
|
+
[[package]]
|
|
200
|
+
name = "crypto-common"
|
|
201
|
+
version = "0.1.7"
|
|
202
|
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
203
|
+
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
|
204
|
+
dependencies = [
|
|
205
|
+
"generic-array",
|
|
206
|
+
"typenum",
|
|
207
|
+
]
|
|
208
|
+
|
|
181
209
|
[[package]]
|
|
182
210
|
name = "ctrlc"
|
|
183
211
|
version = "3.5.3"
|
|
@@ -189,6 +217,16 @@ dependencies = [
|
|
|
189
217
|
"windows-sys 0.61.2",
|
|
190
218
|
]
|
|
191
219
|
|
|
220
|
+
[[package]]
|
|
221
|
+
name = "digest"
|
|
222
|
+
version = "0.10.7"
|
|
223
|
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
224
|
+
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
|
225
|
+
dependencies = [
|
|
226
|
+
"block-buffer",
|
|
227
|
+
"crypto-common",
|
|
228
|
+
]
|
|
229
|
+
|
|
192
230
|
[[package]]
|
|
193
231
|
name = "dispatch2"
|
|
194
232
|
version = "0.3.1"
|
|
@@ -219,7 +257,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
|
219
257
|
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
|
|
220
258
|
dependencies = [
|
|
221
259
|
"libc",
|
|
222
|
-
"windows-sys 0.
|
|
260
|
+
"windows-sys 0.61.2",
|
|
223
261
|
]
|
|
224
262
|
|
|
225
263
|
[[package]]
|
|
@@ -269,6 +307,16 @@ dependencies = [
|
|
|
269
307
|
"percent-encoding",
|
|
270
308
|
]
|
|
271
309
|
|
|
310
|
+
[[package]]
|
|
311
|
+
name = "generic-array"
|
|
312
|
+
version = "0.14.7"
|
|
313
|
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
314
|
+
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
|
315
|
+
dependencies = [
|
|
316
|
+
"typenum",
|
|
317
|
+
"version_check",
|
|
318
|
+
]
|
|
319
|
+
|
|
272
320
|
[[package]]
|
|
273
321
|
name = "getrandom"
|
|
274
322
|
version = "0.2.17"
|
|
@@ -621,7 +669,7 @@ dependencies = [
|
|
|
621
669
|
"errno",
|
|
622
670
|
"libc",
|
|
623
671
|
"linux-raw-sys",
|
|
624
|
-
"windows-sys 0.
|
|
672
|
+
"windows-sys 0.61.2",
|
|
625
673
|
]
|
|
626
674
|
|
|
627
675
|
[[package]]
|
|
@@ -734,6 +782,17 @@ dependencies = [
|
|
|
734
782
|
"zmij",
|
|
735
783
|
]
|
|
736
784
|
|
|
785
|
+
[[package]]
|
|
786
|
+
name = "sha2"
|
|
787
|
+
version = "0.10.9"
|
|
788
|
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
789
|
+
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
|
790
|
+
dependencies = [
|
|
791
|
+
"cfg-if",
|
|
792
|
+
"cpufeatures",
|
|
793
|
+
"digest",
|
|
794
|
+
]
|
|
795
|
+
|
|
737
796
|
[[package]]
|
|
738
797
|
name = "shlex"
|
|
739
798
|
version = "2.0.1"
|
|
@@ -742,13 +801,14 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
|
|
742
801
|
|
|
743
802
|
[[package]]
|
|
744
803
|
name = "silentium"
|
|
745
|
-
version = "0.
|
|
804
|
+
version = "0.2.0"
|
|
746
805
|
dependencies = [
|
|
747
806
|
"anyhow",
|
|
748
807
|
"clap",
|
|
749
808
|
"ctrlc",
|
|
750
809
|
"serde",
|
|
751
810
|
"serde_json",
|
|
811
|
+
"sha2",
|
|
752
812
|
"ureq",
|
|
753
813
|
]
|
|
754
814
|
|
|
@@ -825,7 +885,7 @@ dependencies = [
|
|
|
825
885
|
"getrandom 0.4.3",
|
|
826
886
|
"once_cell",
|
|
827
887
|
"rustix",
|
|
828
|
-
"windows-sys 0.
|
|
888
|
+
"windows-sys 0.61.2",
|
|
829
889
|
]
|
|
830
890
|
|
|
831
891
|
[[package]]
|
|
@@ -838,6 +898,12 @@ dependencies = [
|
|
|
838
898
|
"zerovec",
|
|
839
899
|
]
|
|
840
900
|
|
|
901
|
+
[[package]]
|
|
902
|
+
name = "typenum"
|
|
903
|
+
version = "1.20.1"
|
|
904
|
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
905
|
+
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
|
906
|
+
|
|
841
907
|
[[package]]
|
|
842
908
|
name = "unicode-ident"
|
|
843
909
|
version = "1.0.27"
|
|
@@ -908,6 +974,12 @@ version = "0.2.15"
|
|
|
908
974
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
909
975
|
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
|
910
976
|
|
|
977
|
+
[[package]]
|
|
978
|
+
name = "version_check"
|
|
979
|
+
version = "0.9.5"
|
|
980
|
+
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
981
|
+
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
|
982
|
+
|
|
911
983
|
[[package]]
|
|
912
984
|
name = "wasi"
|
|
913
985
|
version = "0.11.1+wasi-snapshot-preview1"
|
package/Cargo.toml
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[package]
|
|
2
2
|
name = "silentium"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.2.0"
|
|
4
4
|
edition = "2021"
|
|
5
5
|
rust-version = "1.75"
|
|
6
6
|
description = "Discord voice kill switch: drop/mute/deafen every call participant, plus local voice-traffic shaping"
|
|
@@ -22,6 +22,7 @@ clap = { version = "4", features = ["derive", "env"] }
|
|
|
22
22
|
ctrlc = "3"
|
|
23
23
|
serde = { version = "1", features = ["derive"] }
|
|
24
24
|
serde_json = "1"
|
|
25
|
+
sha2 = "0.10"
|
|
25
26
|
|
|
26
27
|
[target.'cfg(windows)'.dependencies]
|
|
27
28
|
ureq = { version = "2.12", default-features = false, features = ["json", "native-tls", "gzip"] }
|
package/README.md
CHANGED
|
@@ -7,49 +7,309 @@
|
|
|
7
7
|
╚═══██║ ██║ ██║ ██╔══╝ ██║╚██╗██║ ██║ ██║ ██║ ██║ ██║╚██╔╝██║
|
|
8
8
|
██████║ ██║ ██████╗ ██████╗ ██║ ╚████║ ██║ ██║ ╚██████╔╝ ██║ ╚═╝ ██║
|
|
9
9
|
╚═════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝
|
|
10
|
-
```
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
**Kill switch de voz para Discord.** Detecta a call ativa pelos sockets locais do cliente e corta, limita, muta ou derruba — sem plugin, sem injeção, sem tocar no aplicativo.
|
|
11
13
|
|
|
12
14
|
[](https://github.com/onx90s/silentium/releases)
|
|
13
15
|
[](https://www.npmjs.com/package/@onxdev/silentium)
|
|
14
16
|
[](https://github.com/onx90s/silentium/actions)
|
|
15
17
|
[](#licença)
|
|
18
|
+

|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## O que é
|
|
23
|
+
|
|
24
|
+
Silentium é uma CLI em Rust que trata a voz do Discord como infraestrutura: você escolhe o escopo — todos na call, um canal, um usuário — e aplica uma ação.
|
|
25
|
+
|
|
26
|
+
| camada | o que faz | precisa de |
|
|
27
|
+
|---|---|---|
|
|
28
|
+
| **detecção local** | descobre se existe call ativa e onde, lendo os sockets UDP do processo Discord | nada |
|
|
29
|
+
| **controle de voz** | derruba, muta, ensurdece, restaura e vigia entrada de participantes via REST | token com permissões de moderação |
|
|
30
|
+
| **shaping de rede** | corta ou limita só o tráfego do Discord, o resto da máquina segue intacto | root (Linux) / Administrador (Windows) |
|
|
31
|
+
|
|
32
|
+
O binário é pequeno, sem runtime, sem dependência de Node ou Python. `npm install -g @onxdev/silentium` existe só como transporte do binário.
|
|
33
|
+
|
|
34
|
+
## Como funciona
|
|
35
|
+
|
|
36
|
+
**1. Detecção sem API.** O Discord negocia mídia em UDP na faixa **50000–65535**. Silentium lê a tabela de sockets do sistema, filtra o que pertence ao processo Discord e separa tráfego de mídia (faixa de voz) de tráfego de gateway/QUIC (443). Nenhum token é usado nesse caminho — `silentium detect` funciona offline.
|
|
37
|
+
|
|
38
|
+
**2. Controle via REST v10.** Com token de bot (`Authorization: Bot <token>`) ou token de usuário (`--user-token`), o comando faz `PATCH /guilds/{guild}/members/{user}` com um destes corpos:
|
|
39
|
+
|
|
40
|
+
```json
|
|
41
|
+
{ "channel_id": null } // derruba da call
|
|
42
|
+
{ "mute": true } // muta no servidor
|
|
43
|
+
{ "deaf": true } // ensurdece no servidor
|
|
44
|
+
{ "mute": false, "deaf": false } // restaura
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Permissões exigidas no servidor: `MOVE_MEMBERS`, `MUTE_MEMBERS`, `DEAFEN_MEMBERS`.
|
|
48
|
+
|
|
49
|
+
**3. Shaping no sistema.** No Linux, `iptables` com match por dono do socket e `tc`/`netem` para banda, perda e latência. No Windows, regras de firewall por caminho do `Discord.exe` e política `New-NetQosPolicy` na faixa de voz. Sempre restrito ao tráfego do Discord.
|
|
50
|
+
|
|
51
|
+
## Instalação
|
|
16
52
|
|
|
17
|
-
|
|
53
|
+
### npm (recomendado)
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
npm install -g @onxdev/silentium
|
|
57
|
+
silentium
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
O `postinstall` baixa o binário pré-compilado para a sua plataforma direto dos releases, confere o SHA-256 e coloca em `node_modules/@onxdev/silentium/vendor/`. Sem Rust instalado, sem compilação. Se o download falhar e houver Rust na máquina, ele compila na hora.
|
|
61
|
+
|
|
62
|
+
Linux, macOS e Windows usam exatamente o mesmo comando. Precisa de Node 18+ apenas para instalar; o binário em si não tem runtime.
|
|
63
|
+
|
|
64
|
+
Sem instalar nada globalmente:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
npx @onxdev/silentium
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
> O nome `silentium` no npm pertence a outro projeto (uma solução de mensageria). Este CLI é publicado sob o escopo `@onx90s`, e o comando continua sendo `silentium`.
|
|
71
|
+
|
|
72
|
+
### Cargo
|
|
18
73
|
|
|
19
74
|
```bash
|
|
20
|
-
npm install -g @onxdev/silentium # baixa o binário do release
|
|
21
75
|
cargo install --git https://github.com/onx90s/silentium --locked
|
|
22
76
|
```
|
|
23
77
|
|
|
24
|
-
Binário direto
|
|
78
|
+
### Binário direto
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
# Linux x86_64
|
|
82
|
+
curl -fsSL https://github.com/onx90s/silentium/releases/latest/download/silentium-linux-x64.tar.gz \
|
|
83
|
+
| tar -xz -C ~/.local/bin
|
|
84
|
+
chmod +x ~/.local/bin/silentium
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Assets disponíveis: `silentium-linux-x64`, `silentium-linux-arm64`, `silentium-darwin-x64`, `silentium-darwin-arm64`, `silentium-windows-x64.zip`, sempre com `SHASUMS256.txt` ao lado.
|
|
25
88
|
|
|
26
|
-
##
|
|
89
|
+
## Primeiro uso
|
|
90
|
+
|
|
91
|
+
Rodar sem argumento abre a tela inicial: banner, diagnóstico do sistema e menu.
|
|
27
92
|
|
|
28
93
|
```bash
|
|
29
|
-
silentium
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
94
|
+
silentium
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
```
|
|
98
|
+
sistema linux-x86_64 · uid 1000
|
|
99
|
+
discord ● rodando — pid 4213
|
|
100
|
+
call ● ativa — 2 socket(s) de mídia (50002, 50004)
|
|
101
|
+
token ● definido (MTQ3…)
|
|
102
|
+
guild ● 123456789012345678
|
|
103
|
+
firewall ○ sem privilégio — net só com sudo
|
|
33
104
|
```
|
|
34
105
|
|
|
35
|
-
|
|
106
|
+
Depois, dois caminhos:
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
# só detecção, zero credencial
|
|
110
|
+
silentium detect
|
|
111
|
+
|
|
112
|
+
# controle de voz: aponte o convite da call, sem precisar de IDs
|
|
113
|
+
export DISCORD_TOKEN="seu_token_de_bot"
|
|
114
|
+
silentium voice list --invite discord.gg/abc123
|
|
115
|
+
silentium voice drop --invite discord.gg/abc123
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
`--invite` resolve o convite em guild + canal automaticamente. IDs explícitos também valem:
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
silentium voice mute --guild 123456789012345678 --channel 987654321098765432
|
|
122
|
+
```
|
|
36
123
|
|
|
37
124
|
## Comandos
|
|
38
125
|
|
|
39
|
-
|
|
126
|
+
### Globais
|
|
127
|
+
|
|
128
|
+
| flag | padrão | função |
|
|
129
|
+
|---|---|---|
|
|
130
|
+
| `--token` | `$DISCORD_TOKEN` | token de bot, ou de usuário com `--user-token` |
|
|
131
|
+
| `--user-token` | — | trata o token como de usuário (sem prefixo `Bot `) |
|
|
132
|
+
| `--guild` | `$GUILD_ID` | ID do servidor |
|
|
133
|
+
| `--delay-ms` | `150` | intervalo entre chamadas REST |
|
|
134
|
+
| `--dry-run` | — | mostra o que faria, sem executar |
|
|
135
|
+
|
|
136
|
+
### `silentium detect`
|
|
137
|
+
|
|
138
|
+
Lista sockets do Discord. Sem token. Marca o que cai na faixa de voz.
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
silentium detect
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### `silentium whoami` / `silentium resolve`
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
silentium whoami # valida o token
|
|
148
|
+
silentium resolve discord.gg/abc123 # convite -> guild + canal
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### `silentium voice <ação>`
|
|
152
|
+
|
|
153
|
+
Ações: `list`, `drop`, `mute`, `unmute`, `deafen`, `undeafen`, `restore`.
|
|
154
|
+
|
|
155
|
+
```bash
|
|
156
|
+
silentium voice list # quem está em voz
|
|
157
|
+
silentium voice drop # derruba todos
|
|
158
|
+
silentium voice mute --channel 987654321098765432 # muta um canal
|
|
159
|
+
silentium voice restore # desfaz mute e deafen
|
|
160
|
+
silentium voice drop --user 111111111111111111 # alvo único
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
Filtros comuns a todas as ações:
|
|
164
|
+
|
|
165
|
+
| flag | efeito |
|
|
40
166
|
|---|---|
|
|
41
|
-
|
|
|
42
|
-
|
|
|
43
|
-
|
|
|
44
|
-
|
|
|
167
|
+
| `--guild <id>` | servidor |
|
|
168
|
+
| `--channel <id>` | restringe a um canal de voz |
|
|
169
|
+
| `--user <id>` | alvo específico, repetível |
|
|
170
|
+
| `--invite <link>` | extrai guild e canal do convite |
|
|
45
171
|
|
|
46
|
-
|
|
172
|
+
### `silentium voice guard`
|
|
47
173
|
|
|
48
|
-
|
|
174
|
+
Vigia o canal e aplica a ação em quem entrar.
|
|
49
175
|
|
|
50
176
|
```bash
|
|
51
|
-
|
|
52
|
-
./build.ps1 -Install # Windows: copia para %LOCALAPPDATA%\Silentium e põe no PATH
|
|
177
|
+
silentium voice guard --invite discord.gg/abc123 --action drop --interval 2
|
|
53
178
|
```
|
|
54
179
|
|
|
55
|
-
|
|
180
|
+
### `silentium net <subcomando>`
|
|
181
|
+
|
|
182
|
+
| comando | efeito |
|
|
183
|
+
|---|---|
|
|
184
|
+
| `throttle --kbps 8` | limita a banda do áudio (8 degrada, 2 mata) |
|
|
185
|
+
| `throttle --loss 30 --latency 400` | perda e latência no UDP de voz (Linux) |
|
|
186
|
+
| `clear` | remove todo o shaping |
|
|
187
|
+
| `block` | corta a internet **só do Discord**, por processo |
|
|
188
|
+
| `unblock` | desfaz o bloqueio |
|
|
189
|
+
| `auto` | detecta call ativa e corta; restaura no `Enter`/`Ctrl-C` |
|
|
190
|
+
|
|
191
|
+
```bash
|
|
192
|
+
sudo silentium net auto --seconds 30
|
|
193
|
+
sudo silentium net throttle --kbps 4 --loss 40
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
## Receitas
|
|
197
|
+
|
|
198
|
+
Cortar a call por 30 segundos, sem pensar em IDs:
|
|
199
|
+
|
|
200
|
+
```bash
|
|
201
|
+
sudo silentium net auto --seconds 30
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Silenciar um participante específico, sem sair do servidor:
|
|
205
|
+
|
|
206
|
+
```bash
|
|
207
|
+
silentium voice mute --invite discord.gg/abc123 --user 987654321098765432
|
|
208
|
+
silentium voice unmute --invite discord.gg/abc123 --user 987654321098765432
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
Receber ninguém: vigia o canal e derruba quem entrar.
|
|
212
|
+
|
|
213
|
+
```bash
|
|
214
|
+
silentium voice guard --invite discord.gg/abc123 --action drop
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
Silêncio total numa máquina compartilhada: corta o Discord, resto navega normal.
|
|
218
|
+
|
|
219
|
+
```bash
|
|
220
|
+
sudo silentium net block # até Enter/Ctrl-C
|
|
221
|
+
sudo silentium net block --seconds 120
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
## Atualização
|
|
225
|
+
|
|
226
|
+
O CLI consulta a última release do GitHub uma vez a cada 6 horas (cache em `~/.cache/silentium/update.json`) e avisa na tela inicial:
|
|
227
|
+
|
|
228
|
+
```
|
|
229
|
+
atualização disponível: v0.2.0 (você tem v0.1.0)
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Aí é só escolher `u` no menu, ou rodar direto:
|
|
233
|
+
|
|
234
|
+
```bash
|
|
235
|
+
silentium update --check # só informa
|
|
236
|
+
silentium update # baixa, confere o SHA-256 e troca o binário
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
Como ele se atualiza depende de como foi instalado: pacote npm → `npm install -g @onxdev/silentium@<versão>`; binário solto → baixa o asset da release, valida o checksum e substitui o executável no lugar (no Windows via renomear, já que o arquivo em uso não pode ser sobrescrito).
|
|
240
|
+
|
|
241
|
+
## Permissões
|
|
242
|
+
|
|
243
|
+
| operação | Linux | Windows |
|
|
244
|
+
|---|---|---|
|
|
245
|
+
| `detect` | `iproute2` (`ss`) | PowerShell (`netstat`) |
|
|
246
|
+
| `voice *` | token + permissões no servidor | idem |
|
|
247
|
+
| `net block` | root, `iptables` | Administrador, firewall |
|
|
248
|
+
| `net throttle` | root, `iptables` + `tc`/`netem` | Administrador, `New-NetQosPolicy` (só banda) |
|
|
249
|
+
| `net throttle --loss/--latency` | Linux apenas | ignorado com aviso |
|
|
250
|
+
|
|
251
|
+
No Windows a pilha nativa de QoS só limita banda; perda e latência são exclusivas do Linux.
|
|
252
|
+
|
|
253
|
+
## Plataformas
|
|
254
|
+
|
|
255
|
+
| | detect | voice | net block | net throttle |
|
|
256
|
+
|---|---|---|---|---|
|
|
257
|
+
| Linux x86_64 / arm64 | ✅ | ✅ | ✅ | ✅ |
|
|
258
|
+
| Windows x86_64 | ✅ | ✅ | ✅ | banda |
|
|
259
|
+
| macOS x86_64 / arm64 | ⚠️ `detect` usa `ss`, indisponível | ✅ | — | — |
|
|
260
|
+
|
|
261
|
+
O controle de voz é independente de plataforma: é REST.
|
|
262
|
+
|
|
263
|
+
## Construindo do código
|
|
264
|
+
|
|
265
|
+
```bash
|
|
266
|
+
git clone https://github.com/onx90s/silentium
|
|
267
|
+
cd silentium
|
|
268
|
+
cargo build --release # target/release/silentium
|
|
269
|
+
cargo test
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
Toolchain: stable, edição 2021, MSRV 1.75. Sem dependência nativa: `clap`, `serde`, `ureq`, `anyhow`, `ctrlc`.
|
|
273
|
+
|
|
274
|
+
## Estrutura do repositório
|
|
275
|
+
|
|
276
|
+
```
|
|
277
|
+
src/
|
|
278
|
+
main.rs dispatch, guard, janela de restauração
|
|
279
|
+
cli.rs superfície de argumentos (clap)
|
|
280
|
+
ui.rs tela inicial: banner, diagnóstico, menu
|
|
281
|
+
detect.rs sockets do Discord (ss / netstat)
|
|
282
|
+
discord.rs REST v10: membros, voice states, convites
|
|
283
|
+
net.rs iptables + tc (Linux) / firewall + QoS (Windows)
|
|
284
|
+
npm/
|
|
285
|
+
lib.js resolução de plataforma, download, verificação
|
|
286
|
+
install.js postinstall com fallback para cargo
|
|
287
|
+
bin/ shim que executa o binário nativo
|
|
288
|
+
```
|
|
289
|
+
|
|
290
|
+
## Limites
|
|
291
|
+
|
|
292
|
+
- Ações de moderação são registradas no audit log do servidor: `drop`, `mute` e `deafen` ficam atribuídos ao token que as executou.
|
|
293
|
+
- `net block` depende de privilégio elevado. Sem ele, o comando informa e sai sem aplicar nada.
|
|
294
|
+
- A detecção lê sockets do próprio sistema: com Discord rodando em Flatpak ou sandbox, `ss` pode não expor o dono do socket.
|
|
295
|
+
- Token de usuário viola os termos do Discord. Use token de bot em servidor que você administra.
|
|
296
|
+
|
|
297
|
+
## Licença
|
|
298
|
+
|
|
299
|
+
MIT. Veja [LICENSE](LICENSE).
|
|
300
|
+
|
|
301
|
+
---
|
|
302
|
+
|
|
303
|
+
## English
|
|
304
|
+
|
|
305
|
+
**Silentium** is a voice kill switch for Discord, written in Rust. It detects an active call by inspecting the client's local UDP sockets (50000–65535), then drops, mutes, deafens or restores participants through the REST v10 API, or shapes the machine's network so only Discord traffic is cut.
|
|
306
|
+
|
|
307
|
+
```bash
|
|
308
|
+
npm install -g @onxdev/silentium
|
|
309
|
+
silentium # banner, local diagnosis, interactive menu
|
|
310
|
+
silentium detect # no credentials needed
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
Requires Node 18+ only for installation; the CLI itself is a native binary. Voice actions need a bot token with `MOVE_MEMBERS`, `MUTE_MEMBERS`, `DEAFEN_MEMBERS`. Network shaping needs root on Linux (iptables/tc) or Administrator on Windows (firewall/QoS).
|
|
314
|
+
|
|
315
|
+
Star the repo if it saved a call.
|
package/package.json
CHANGED
package/src/cli.rs
CHANGED
|
@@ -45,6 +45,12 @@ pub enum Cmd {
|
|
|
45
45
|
Resolve { invite: String },
|
|
46
46
|
/// Detecta a call ativa olhando os sockets locais do Discord. Não usa API.
|
|
47
47
|
Detect,
|
|
48
|
+
/// Verifica e instala a atualização mais recente publicada no GitHub.
|
|
49
|
+
Update {
|
|
50
|
+
/// Só informa se existe versão nova, sem instalar.
|
|
51
|
+
#[arg(long)]
|
|
52
|
+
check: bool,
|
|
53
|
+
},
|
|
48
54
|
/// Operações na sessão de voz.
|
|
49
55
|
#[command(subcommand)]
|
|
50
56
|
Voice(VoiceCmd),
|
package/src/main.rs
CHANGED
|
@@ -3,6 +3,7 @@ mod detect;
|
|
|
3
3
|
mod discord;
|
|
4
4
|
mod net;
|
|
5
5
|
mod ui;
|
|
6
|
+
mod update;
|
|
6
7
|
|
|
7
8
|
use anyhow::{bail, Context, Result};
|
|
8
9
|
use clap::Parser;
|
|
@@ -54,6 +55,7 @@ fn run() -> Result<()> {
|
|
|
54
55
|
}
|
|
55
56
|
Ok(())
|
|
56
57
|
}
|
|
58
|
+
Some(Cmd::Update { check }) => update::run(check),
|
|
57
59
|
Some(Cmd::Voice(cmd)) => voice_dispatch(&cli, &cmd),
|
|
58
60
|
}
|
|
59
61
|
}
|
package/src/ui.rs
CHANGED
|
@@ -46,7 +46,23 @@ pub fn interactive(cli: &Cli) -> Result<()> {
|
|
|
46
46
|
return Ok(());
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
|
|
49
|
+
let pending = if io::stdout().is_terminal() {
|
|
50
|
+
crate::update::check(false)
|
|
51
|
+
} else {
|
|
52
|
+
None
|
|
53
|
+
};
|
|
54
|
+
if let Some(tag) = &pending {
|
|
55
|
+
println!(
|
|
56
|
+
"\n {}atualização disponível:{} {} {}(você tem v{}){}",
|
|
57
|
+
warn(color),
|
|
58
|
+
reset(color),
|
|
59
|
+
bold(color),
|
|
60
|
+
tag,
|
|
61
|
+
env!("CARGO_PKG_VERSION"),
|
|
62
|
+
reset(color)
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
menu(color, pending.is_some());
|
|
50
66
|
loop {
|
|
51
67
|
print!("\n{}silentium ›{} ", accent(color), reset(color));
|
|
52
68
|
io::stdout().flush()?;
|
|
@@ -74,6 +90,20 @@ pub fn interactive(cli: &Cli) -> Result<()> {
|
|
|
74
90
|
"5" => voice(cli, VoiceCmd::Deafen(TargetArgs::default()))?,
|
|
75
91
|
"6" => voice(cli, VoiceCmd::Restore(TargetArgs::default()))?,
|
|
76
92
|
"7" => cut_discord(color)?,
|
|
93
|
+
"u" | "atualizar" | "update" => {
|
|
94
|
+
if pending.is_some() {
|
|
95
|
+
if let Err(err) = crate::update::run(false) {
|
|
96
|
+
println!("{}falha ao atualizar: {err:#}{}", bad(color), reset(color));
|
|
97
|
+
}
|
|
98
|
+
} else {
|
|
99
|
+
println!(
|
|
100
|
+
"{}nada para atualizar — v{} é a última{}",
|
|
101
|
+
dim(color),
|
|
102
|
+
env!("CARGO_PKG_VERSION"),
|
|
103
|
+
reset(color)
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
77
107
|
"?" | "h" | "help" => help_hint(color),
|
|
78
108
|
other => println!(
|
|
79
109
|
"{}opção desconhecida: {}{}",
|
|
@@ -82,7 +112,7 @@ pub fn interactive(cli: &Cli) -> Result<()> {
|
|
|
82
112
|
reset(color)
|
|
83
113
|
),
|
|
84
114
|
}
|
|
85
|
-
menu(color);
|
|
115
|
+
menu(color, pending.is_some());
|
|
86
116
|
}
|
|
87
117
|
Ok(())
|
|
88
118
|
}
|
|
@@ -218,8 +248,19 @@ fn is_root() -> bool {
|
|
|
218
248
|
}
|
|
219
249
|
}
|
|
220
250
|
|
|
221
|
-
fn menu(color: bool) {
|
|
251
|
+
fn menu(color: bool, update_available: bool) {
|
|
222
252
|
println!("\n {}menu{}", bold(color), reset(color));
|
|
253
|
+
if update_available {
|
|
254
|
+
println!(
|
|
255
|
+
" {}{:>2}{} {:<28} {}baixa e troca o binário{}",
|
|
256
|
+
accent(color),
|
|
257
|
+
"u",
|
|
258
|
+
reset(color),
|
|
259
|
+
"atualizar agora",
|
|
260
|
+
dim(color),
|
|
261
|
+
reset(color)
|
|
262
|
+
);
|
|
263
|
+
}
|
|
223
264
|
for (key, label, hint) in MENU {
|
|
224
265
|
println!(
|
|
225
266
|
" {}{:>2}{} {:<28} {}{}{}",
|
package/src/update.rs
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
// rust — src/update.rs — detecta versão nova no GitHub e troca o próprio binário
|
|
2
|
+
use anyhow::{bail, Context, Result};
|
|
3
|
+
use serde::{Deserialize, Serialize};
|
|
4
|
+
use sha2::{Digest, Sha256};
|
|
5
|
+
use std::fs;
|
|
6
|
+
use std::io::Read;
|
|
7
|
+
use std::path::{Path, PathBuf};
|
|
8
|
+
use std::process::Command;
|
|
9
|
+
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
|
10
|
+
|
|
11
|
+
pub const REPO: &str = "onx90s/silentium";
|
|
12
|
+
pub const NPM_PACKAGE: &str = "@onxdev/silentium";
|
|
13
|
+
pub const CURRENT: &str = env!("CARGO_PKG_VERSION");
|
|
14
|
+
|
|
15
|
+
/// Duas checagens por dia, no máximo, para não bater no rate limit da API.
|
|
16
|
+
const CHECK_INTERVAL_SECS: u64 = 6 * 60 * 60;
|
|
17
|
+
|
|
18
|
+
#[derive(Debug, Serialize, Deserialize, Default)]
|
|
19
|
+
struct Cache {
|
|
20
|
+
checked_at: u64,
|
|
21
|
+
#[serde(default)]
|
|
22
|
+
tag: Option<String>,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/// Entra na tela inicial: devolve a tag nova, se houver.
|
|
26
|
+
pub fn check(force: bool) -> Option<String> {
|
|
27
|
+
let cache = read_cache();
|
|
28
|
+
let fresh = now().saturating_sub(cache.checked_at) < CHECK_INTERVAL_SECS;
|
|
29
|
+
if !force && fresh {
|
|
30
|
+
return cache.tag.filter(|tag| is_newer(tag, CURRENT));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
match fetch_latest_tag() {
|
|
34
|
+
Ok(tag) => {
|
|
35
|
+
write_cache(&Cache {
|
|
36
|
+
checked_at: now(),
|
|
37
|
+
tag: Some(tag.clone()),
|
|
38
|
+
});
|
|
39
|
+
if is_newer(&tag, CURRENT) {
|
|
40
|
+
Some(tag)
|
|
41
|
+
} else {
|
|
42
|
+
None
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
// Sem rede, offline ou rate limit: silêncio, o CLI segue funcionando.
|
|
46
|
+
Err(_) => None,
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/// `silentium update` / `silentium update --check`.
|
|
51
|
+
pub fn run(check_only: bool) -> Result<()> {
|
|
52
|
+
let latest = fetch_latest_tag().context("consultando a última release no GitHub")?;
|
|
53
|
+
if !is_newer(&latest, CURRENT) {
|
|
54
|
+
println!("já na última versão ({CURRENT})");
|
|
55
|
+
return Ok(());
|
|
56
|
+
}
|
|
57
|
+
if check_only {
|
|
58
|
+
println!("atualização disponível: {latest} (você tem {CURRENT})");
|
|
59
|
+
return Ok(());
|
|
60
|
+
}
|
|
61
|
+
println!("atualizando {CURRENT} → {latest}");
|
|
62
|
+
apply(&latest)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
fn apply(tag: &str) -> Result<()> {
|
|
66
|
+
if via_npm() {
|
|
67
|
+
return update_via_npm(tag);
|
|
68
|
+
}
|
|
69
|
+
update_binary(tag)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/// Instalado como pacote npm: deixa o npm trocar o binário.
|
|
73
|
+
fn update_via_npm(tag: &str) -> Result<()> {
|
|
74
|
+
let version = tag.trim_start_matches('v');
|
|
75
|
+
let spec = format!("{NPM_PACKAGE}@{version}");
|
|
76
|
+
println!("instalando {spec} via npm");
|
|
77
|
+
let status = Command::new("npm")
|
|
78
|
+
.args(["install", "-g", &spec])
|
|
79
|
+
.status()
|
|
80
|
+
.context("npm não encontrado no PATH")?;
|
|
81
|
+
if !status.success() {
|
|
82
|
+
bail!("npm install falhou ({status}); tente manualmente: npm i -g {spec}");
|
|
83
|
+
}
|
|
84
|
+
println!("pronto — a próxima execução já usa {tag}");
|
|
85
|
+
Ok(())
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
fn update_binary(tag: &str) -> Result<()> {
|
|
89
|
+
let asset = asset_name().context("plataforma sem binário publicado")?;
|
|
90
|
+
let base = format!("https://github.com/{REPO}/releases/download/{tag}");
|
|
91
|
+
let agent = agent();
|
|
92
|
+
|
|
93
|
+
let dir = std::env::temp_dir().join(format!("silentium-update-{}", std::process::id()));
|
|
94
|
+
let _ = fs::remove_dir_all(&dir);
|
|
95
|
+
fs::create_dir_all(&dir).context("criando diretório temporário")?;
|
|
96
|
+
let archive = dir.join(&asset);
|
|
97
|
+
|
|
98
|
+
let mut reader = agent
|
|
99
|
+
.get(&format!("{base}/{asset}"))
|
|
100
|
+
.call()
|
|
101
|
+
.with_context(|| format!("baixando {asset}"))?
|
|
102
|
+
.into_reader();
|
|
103
|
+
let mut file = fs::File::create(&archive).context("criando arquivo temporário")?;
|
|
104
|
+
let mut hasher = Sha256::new();
|
|
105
|
+
let mut buf = [0u8; 64 * 1024];
|
|
106
|
+
loop {
|
|
107
|
+
let read = reader.read(&mut buf)?;
|
|
108
|
+
if read == 0 {
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
hasher.update(&buf[..read]);
|
|
112
|
+
std::io::Write::write_all(&mut file, &buf[..read])?;
|
|
113
|
+
}
|
|
114
|
+
drop(file);
|
|
115
|
+
|
|
116
|
+
if let Some(expected) = expected_sha(&agent, &base, &asset) {
|
|
117
|
+
let actual = format!("{:x}", hasher.finalize());
|
|
118
|
+
if expected != actual {
|
|
119
|
+
bail!("checksum não bate: esperado {expected}, obtido {actual}");
|
|
120
|
+
}
|
|
121
|
+
} else {
|
|
122
|
+
eprintln!("[!] SHASUMS256.txt indisponível, seguindo sem verificação");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
extract(&archive, &dir)?;
|
|
126
|
+
let new_bin = find_binary(&dir).context("binário não encontrado dentro do pacote")?;
|
|
127
|
+
let replaced = replace_self(&new_bin);
|
|
128
|
+
let _ = fs::remove_dir_all(&dir);
|
|
129
|
+
replaced?;
|
|
130
|
+
println!("pronto — {tag} instalado em {}", self_path()?.display());
|
|
131
|
+
Ok(())
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
fn expected_sha(agent: &ureq::Agent, base: &str, asset: &str) -> Option<String> {
|
|
135
|
+
let text = agent
|
|
136
|
+
.get(&format!("{base}/SHASUMS256.txt"))
|
|
137
|
+
.call()
|
|
138
|
+
.ok()?
|
|
139
|
+
.into_string()
|
|
140
|
+
.ok()?;
|
|
141
|
+
text.lines()
|
|
142
|
+
.find(|line| line.trim_end().ends_with(asset))
|
|
143
|
+
.and_then(|line| line.split_whitespace().next())
|
|
144
|
+
.map(|hash| hash.to_ascii_lowercase())
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
fn extract(archive: &Path, into: &Path) -> Result<()> {
|
|
148
|
+
#[cfg(windows)]
|
|
149
|
+
{
|
|
150
|
+
let status = Command::new("powershell")
|
|
151
|
+
.args([
|
|
152
|
+
"-NoProfile",
|
|
153
|
+
"-NonInteractive",
|
|
154
|
+
"-Command",
|
|
155
|
+
&format!(
|
|
156
|
+
"Expand-Archive -Path '{}' -DestinationPath '{}' -Force",
|
|
157
|
+
archive.display(),
|
|
158
|
+
into.display()
|
|
159
|
+
),
|
|
160
|
+
])
|
|
161
|
+
.status()
|
|
162
|
+
.context("executando powershell")?;
|
|
163
|
+
if !status.success() {
|
|
164
|
+
bail!("Expand-Archive falhou");
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
#[cfg(not(windows))]
|
|
168
|
+
{
|
|
169
|
+
let status = Command::new("tar")
|
|
170
|
+
.arg("-xzf")
|
|
171
|
+
.arg(archive)
|
|
172
|
+
.arg("-C")
|
|
173
|
+
.arg(into)
|
|
174
|
+
.status()
|
|
175
|
+
.context("tar não encontrado")?;
|
|
176
|
+
if !status.success() {
|
|
177
|
+
bail!("tar falhou ao extrair {archive:?}");
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
Ok(())
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
fn find_binary(dir: &Path) -> Option<PathBuf> {
|
|
184
|
+
let name = binary_name();
|
|
185
|
+
let direct = dir.join(name);
|
|
186
|
+
if direct.exists() {
|
|
187
|
+
return Some(direct);
|
|
188
|
+
}
|
|
189
|
+
fs::read_dir(dir)
|
|
190
|
+
.ok()?
|
|
191
|
+
.flatten()
|
|
192
|
+
.map(|entry| entry.path())
|
|
193
|
+
.find(|path| path.file_name().map(|n| n == name).unwrap_or(false))
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
fn replace_self(new_bin: &Path) -> Result<()> {
|
|
197
|
+
let current = self_path()?;
|
|
198
|
+
let staged = current.with_file_name(format!(".{}.new", binary_name()));
|
|
199
|
+
fs::copy(new_bin, &staged).context("copiando binário novo")?;
|
|
200
|
+
#[cfg(unix)]
|
|
201
|
+
{
|
|
202
|
+
use std::os::unix::fs::PermissionsExt;
|
|
203
|
+
fs::set_permissions(&staged, fs::Permissions::from_mode(0o755))?;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
#[cfg(windows)]
|
|
207
|
+
{
|
|
208
|
+
let old = current.with_file_name(format!(".{}.old", binary_name()));
|
|
209
|
+
let _ = fs::remove_file(&old);
|
|
210
|
+
fs::rename(¤t, &old).context("movendo binário em uso")?;
|
|
211
|
+
if let Err(err) = fs::rename(&staged, ¤t) {
|
|
212
|
+
let _ = fs::rename(&old, ¤t);
|
|
213
|
+
return Err(err.into());
|
|
214
|
+
}
|
|
215
|
+
let _ = fs::remove_file(&old);
|
|
216
|
+
return Ok(());
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
#[cfg(unix)]
|
|
220
|
+
{
|
|
221
|
+
fs::rename(&staged, ¤t)
|
|
222
|
+
.with_context(|| format!("substituindo {}", current.display()))?;
|
|
223
|
+
Ok(())
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
fn self_path() -> Result<PathBuf> {
|
|
228
|
+
std::env::current_exe().context("descobrindo o próprio executável")
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
fn binary_name() -> &'static str {
|
|
232
|
+
if cfg!(windows) {
|
|
233
|
+
"silentium.exe"
|
|
234
|
+
} else {
|
|
235
|
+
"silentium"
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
fn asset_name() -> Option<String> {
|
|
240
|
+
let os = match std::env::consts::OS {
|
|
241
|
+
"linux" => "linux",
|
|
242
|
+
"macos" => "darwin",
|
|
243
|
+
"windows" => "windows",
|
|
244
|
+
_ => return None,
|
|
245
|
+
};
|
|
246
|
+
let arch = match std::env::consts::ARCH {
|
|
247
|
+
"x86_64" => "x64",
|
|
248
|
+
"aarch64" => "arm64",
|
|
249
|
+
_ => return None,
|
|
250
|
+
};
|
|
251
|
+
let ext = if os == "windows" { "zip" } else { "tar.gz" };
|
|
252
|
+
Some(format!("silentium-{os}-{arch}.{ext}"))
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
fn agent() -> ureq::Agent {
|
|
256
|
+
ureq::AgentBuilder::new()
|
|
257
|
+
.timeout(Duration::from_secs(20))
|
|
258
|
+
.build()
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
fn fetch_latest_tag() -> Result<String> {
|
|
262
|
+
let url = format!("https://api.github.com/repos/{REPO}/releases/latest");
|
|
263
|
+
let json: serde_json::Value = agent()
|
|
264
|
+
.get(&url)
|
|
265
|
+
.set("user-agent", &format!("silentium/{CURRENT}"))
|
|
266
|
+
.call()
|
|
267
|
+
.context("GitHub API")?
|
|
268
|
+
.into_json()
|
|
269
|
+
.context("resposta da API não é JSON")?;
|
|
270
|
+
json.get("tag_name")
|
|
271
|
+
.and_then(|value| value.as_str())
|
|
272
|
+
.map(|tag| tag.to_string())
|
|
273
|
+
.context("release sem tag_name")
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
fn via_npm() -> bool {
|
|
277
|
+
self_path()
|
|
278
|
+
.map(|path| path.to_string_lossy().contains("node_modules"))
|
|
279
|
+
.unwrap_or(false)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
fn now() -> u64 {
|
|
283
|
+
SystemTime::now()
|
|
284
|
+
.duration_since(UNIX_EPOCH)
|
|
285
|
+
.map(|elapsed| elapsed.as_secs())
|
|
286
|
+
.unwrap_or(0)
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
fn cache_path() -> Option<PathBuf> {
|
|
290
|
+
let base = cache_base()?;
|
|
291
|
+
Some(base.join("silentium").join("update.json"))
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
fn cache_base() -> Option<PathBuf> {
|
|
295
|
+
if let Some(dir) = std::env::var_os("XDG_CACHE_HOME") {
|
|
296
|
+
return Some(PathBuf::from(dir));
|
|
297
|
+
}
|
|
298
|
+
#[cfg(windows)]
|
|
299
|
+
{
|
|
300
|
+
std::env::var_os("LOCALAPPDATA").map(PathBuf::from)
|
|
301
|
+
}
|
|
302
|
+
#[cfg(not(windows))]
|
|
303
|
+
{
|
|
304
|
+
std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache"))
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
fn read_cache() -> Cache {
|
|
309
|
+
cache_path()
|
|
310
|
+
.and_then(|path| fs::read_to_string(path).ok())
|
|
311
|
+
.and_then(|text| serde_json::from_str(&text).ok())
|
|
312
|
+
.unwrap_or_default()
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
fn write_cache(cache: &Cache) {
|
|
316
|
+
let Some(path) = cache_path() else { return };
|
|
317
|
+
if let Some(dir) = path.parent() {
|
|
318
|
+
let _ = fs::create_dir_all(dir);
|
|
319
|
+
}
|
|
320
|
+
if let Ok(text) = serde_json::to_string(cache) {
|
|
321
|
+
let _ = fs::write(path, text);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/// Compara tags tipo `v0.2.0`. Pré-release (`v0.2.0-rc.1`) conta como menor.
|
|
326
|
+
pub fn is_newer(latest: &str, current: &str) -> bool {
|
|
327
|
+
let (latest_version, latest_pre) = parse_version(latest);
|
|
328
|
+
let (current_version, current_pre) = parse_version(current);
|
|
329
|
+
match latest_version.cmp(¤t_version) {
|
|
330
|
+
std::cmp::Ordering::Greater => true,
|
|
331
|
+
std::cmp::Ordering::Less => false,
|
|
332
|
+
std::cmp::Ordering::Equal => current_pre && !latest_pre,
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
fn parse_version(raw: &str) -> (Vec<u64>, bool) {
|
|
337
|
+
let trimmed = raw.trim().trim_start_matches('v');
|
|
338
|
+
let (core, pre) = match trimmed.split_once('-') {
|
|
339
|
+
Some((core, _)) => (core, true),
|
|
340
|
+
None => (trimmed, false),
|
|
341
|
+
};
|
|
342
|
+
let parts = core
|
|
343
|
+
.split('.')
|
|
344
|
+
.map(|part| {
|
|
345
|
+
part.chars()
|
|
346
|
+
.take_while(|c| c.is_ascii_digit())
|
|
347
|
+
.collect::<String>()
|
|
348
|
+
.parse::<u64>()
|
|
349
|
+
.unwrap_or(0)
|
|
350
|
+
})
|
|
351
|
+
.collect();
|
|
352
|
+
(parts, pre)
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
#[cfg(test)]
|
|
356
|
+
mod tests {
|
|
357
|
+
use super::{is_newer, parse_version};
|
|
358
|
+
|
|
359
|
+
#[test]
|
|
360
|
+
fn reconhece_versao_maior() {
|
|
361
|
+
assert!(is_newer("v0.2.0", "0.1.0"));
|
|
362
|
+
assert!(is_newer("v1.0.0", "0.9.9"));
|
|
363
|
+
assert!(is_newer("v0.1.10", "0.1.9"));
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
#[test]
|
|
367
|
+
fn ignora_mesma_versao_e_menor() {
|
|
368
|
+
assert!(!is_newer("v0.1.0", "0.1.0"));
|
|
369
|
+
assert!(!is_newer("0.1.0", "v0.1.0"));
|
|
370
|
+
assert!(!is_newer("v0.0.9", "0.1.0"));
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
#[test]
|
|
374
|
+
fn pre_release_e_tratada() {
|
|
375
|
+
assert!(is_newer("v0.2.0", "0.2.0-rc.1"));
|
|
376
|
+
assert!(!is_newer("v0.2.0-rc.1", "0.2.0"));
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
#[test]
|
|
380
|
+
fn versao_estavel_a_partir_de_pre() {
|
|
381
|
+
let (atual, pre) = parse_version("v1.2.3-beta.2");
|
|
382
|
+
assert_eq!(atual, vec![1, 2, 3]);
|
|
383
|
+
assert!(pre);
|
|
384
|
+
}
|
|
385
|
+
}
|