-
Notifications
You must be signed in to change notification settings - Fork 69
/
main.rs
422 lines (378 loc) · 12.4 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod config;
use std::{
fs::{File, OpenOptions},
io::{BufReader, BufWriter},
path::Path,
sync::Arc,
};
use anyhow::Context;
use config::RqbitDesktopConfig;
use http::StatusCode;
use librqbit::{
api::{
ApiAddTorrentResponse, EmptyJsonResponse, TorrentDetailsResponse, TorrentIdOrHash,
TorrentListResponse, TorrentStats,
},
dht::PersistentDhtConfig,
session_stats::snapshot::SessionStatsSnapshot,
tracing_subscriber_config_utils::{init_logging, InitLoggingOptions, InitLoggingResult},
AddTorrent, AddTorrentOptions, Api, ApiError, PeerConnectionOptions, Session, SessionOptions,
SessionPersistenceConfig,
};
use parking_lot::RwLock;
use serde::Serialize;
use tracing::{error, error_span, info, warn};
const ERR_NOT_CONFIGURED: ApiError =
ApiError::new_from_text(StatusCode::FAILED_DEPENDENCY, "not configured");
struct StateShared {
config: config::RqbitDesktopConfig,
api: Option<Api>,
}
struct State {
config_filename: String,
shared: Arc<RwLock<Option<StateShared>>>,
init_logging: InitLoggingResult,
}
fn read_config(path: &str) -> anyhow::Result<RqbitDesktopConfig> {
let rdr = BufReader::new(File::open(path)?);
let mut config: RqbitDesktopConfig = serde_json::from_reader(rdr)?;
config.persistence.fix_backwards_compat();
Ok(config)
}
fn write_config(path: &str, config: &RqbitDesktopConfig) -> anyhow::Result<()> {
std::fs::create_dir_all(Path::new(path).parent().context("no parent")?)
.context("error creating dirs")?;
let tmp = format!("{}.tmp", path);
let mut tmp_file = BufWriter::new(
OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(&tmp)?,
);
serde_json::to_writer(&mut tmp_file, config)?;
std::fs::rename(tmp, path)?;
Ok(())
}
async fn api_from_config(
init_logging: &InitLoggingResult,
config: &RqbitDesktopConfig,
) -> anyhow::Result<Api> {
config
.validate()
.context("error validating configuration")?;
let persistence = if config.persistence.disable {
None
} else {
Some(SessionPersistenceConfig::Json {
folder: if config.persistence.folder == Path::new("") {
None
} else {
Some(config.persistence.folder.clone())
},
})
};
let session = Session::new_with_opts(
config.default_download_location.clone(),
SessionOptions {
disable_dht: config.dht.disable,
disable_dht_persistence: config.dht.disable_persistence,
dht_config: Some(PersistentDhtConfig {
config_filename: Some(config.dht.persistence_filename.clone()),
..Default::default()
}),
persistence,
peer_opts: Some(PeerConnectionOptions {
connect_timeout: Some(config.peer_opts.connect_timeout),
read_write_timeout: Some(config.peer_opts.read_write_timeout),
..Default::default()
}),
listen_port_range: if !config.tcp_listen.disable {
Some(config.tcp_listen.min_port..config.tcp_listen.max_port)
} else {
None
},
enable_upnp_port_forwarding: !config.upnp.disable_tcp_port_forward,
fastresume: config.persistence.fastresume,
disable_upload: config.disable_upload,
..Default::default()
},
)
.await
.context("couldn't set up librqbit session")?;
let api = Api::new(
session.clone(),
Some(init_logging.rust_log_reload_tx.clone()),
Some(init_logging.line_broadcast.clone()),
);
if !config.http_api.disable {
let listen_addr = config.http_api.listen_addr;
let api = api.clone();
let read_only = config.http_api.read_only;
let upnp_router = if config.upnp.enable_server {
let friendly_name = config
.upnp
.server_friendly_name
.as_ref()
.map(|f| f.trim())
.filter(|s| !s.is_empty())
.map(|s| s.to_owned())
.unwrap_or_else(|| {
format!(
"rqbit-desktop@{}",
gethostname::gethostname().to_string_lossy()
)
});
let mut upnp_adapter = session
.make_upnp_adapter(friendly_name, config.http_api.listen_addr.port())
.await
.context("error starting UPnP server")?;
let router = upnp_adapter.take_router()?;
session.spawn(error_span!("ssdp"), async move {
upnp_adapter.run_ssdp_forever().await
});
Some(router)
} else {
None
};
let http_api_task = async move {
let listener = tokio::net::TcpListener::bind(listen_addr)
.await
.with_context(|| format!("error listening on {}", listen_addr))?;
librqbit::http_api::HttpApi::new(
api.clone(),
Some(librqbit::http_api::HttpApiOptions { read_only }),
)
.make_http_api_and_run(listener, upnp_router)
.await
};
session.spawn(error_span!("http_api"), http_api_task);
}
Ok(api)
}
impl State {
async fn new(init_logging: InitLoggingResult) -> Self {
let config_filename = directories::ProjectDirs::from("com", "rqbit", "desktop")
.expect("directories::ProjectDirs::from")
.config_dir()
.join("config.json")
.to_str()
.expect("to_str()")
.to_owned();
if let Ok(config) = read_config(&config_filename) {
let api = api_from_config(&init_logging, &config)
.await
.map_err(|e| {
warn!(error=?e, "error reading configuration");
e
})
.ok();
let shared = Arc::new(RwLock::new(Some(StateShared { config, api })));
return Self {
config_filename,
shared,
init_logging,
};
}
Self {
config_filename,
init_logging,
shared: Arc::new(RwLock::new(None)),
}
}
fn api(&self) -> Result<Api, ApiError> {
let g = self.shared.read();
match g.as_ref().and_then(|s| s.api.as_ref()) {
Some(api) => Ok(api.clone()),
None => Err(ERR_NOT_CONFIGURED),
}
}
async fn configure(&self, config: RqbitDesktopConfig) -> Result<(), ApiError> {
{
let g = self.shared.read();
if let Some(shared) = g.as_ref() {
if shared.api.is_some() && shared.config == config {
// The config didn't change, and the API is running, nothing to do.
return Ok(());
}
}
}
let existing = self.shared.write().as_mut().and_then(|s| s.api.take());
if let Some(api) = existing {
api.session().stop().await;
}
let api = api_from_config(&self.init_logging, &config).await?;
if let Err(e) = write_config(&self.config_filename, &config) {
error!("error writing config: {:#}", e);
}
let mut g = self.shared.write();
*g = Some(StateShared {
config,
api: Some(api),
});
Ok(())
}
}
#[derive(Default, Serialize)]
struct CurrentState {
config: Option<RqbitDesktopConfig>,
configured: bool,
}
#[tauri::command]
fn config_default() -> config::RqbitDesktopConfig {
config::RqbitDesktopConfig::default()
}
#[tauri::command]
fn config_current(state: tauri::State<'_, State>) -> CurrentState {
let g = state.shared.read();
match &*g {
Some(s) => CurrentState {
config: Some(s.config.clone()),
configured: s.api.is_some(),
},
None => Default::default(),
}
}
#[tauri::command]
async fn config_change(
state: tauri::State<'_, State>,
config: RqbitDesktopConfig,
) -> Result<EmptyJsonResponse, ApiError> {
state.configure(config).await.map(|_| EmptyJsonResponse {})
}
#[tauri::command]
fn torrents_list(state: tauri::State<State>) -> Result<TorrentListResponse, ApiError> {
Ok(state.api()?.api_torrent_list())
}
#[tauri::command]
async fn torrent_create_from_url(
state: tauri::State<'_, State>,
url: String,
opts: Option<AddTorrentOptions>,
) -> Result<ApiAddTorrentResponse, ApiError> {
state
.api()?
.api_add_torrent(AddTorrent::Url(url.into()), opts)
.await
}
#[tauri::command]
async fn torrent_create_from_base64_file(
state: tauri::State<'_, State>,
contents: String,
opts: Option<AddTorrentOptions>,
) -> Result<ApiAddTorrentResponse, ApiError> {
use base64::{engine::general_purpose, Engine as _};
let bytes = general_purpose::STANDARD
.decode(&contents)
.context("invalid base64")
.map_err(|e| ApiError::new_from_anyhow(StatusCode::BAD_REQUEST, e))?;
state
.api()?
.api_add_torrent(AddTorrent::TorrentFileBytes(bytes.into()), opts)
.await
}
#[tauri::command]
async fn torrent_details(
state: tauri::State<'_, State>,
id: TorrentIdOrHash,
) -> Result<TorrentDetailsResponse, ApiError> {
state.api()?.api_torrent_details(id)
}
#[tauri::command]
async fn torrent_stats(
state: tauri::State<'_, State>,
id: TorrentIdOrHash,
) -> Result<TorrentStats, ApiError> {
state.api()?.api_stats_v1(id)
}
#[tauri::command]
async fn torrent_action_delete(
state: tauri::State<'_, State>,
id: TorrentIdOrHash,
) -> Result<EmptyJsonResponse, ApiError> {
state.api()?.api_torrent_action_delete(id).await
}
#[tauri::command]
async fn torrent_action_pause(
state: tauri::State<'_, State>,
id: TorrentIdOrHash,
) -> Result<EmptyJsonResponse, ApiError> {
state.api()?.api_torrent_action_pause(id).await
}
#[tauri::command]
async fn torrent_action_forget(
state: tauri::State<'_, State>,
id: TorrentIdOrHash,
) -> Result<EmptyJsonResponse, ApiError> {
state.api()?.api_torrent_action_forget(id).await
}
#[tauri::command]
async fn torrent_action_start(
state: tauri::State<'_, State>,
id: TorrentIdOrHash,
) -> Result<EmptyJsonResponse, ApiError> {
state.api()?.api_torrent_action_start(id).await
}
#[tauri::command]
async fn torrent_action_configure(
state: tauri::State<'_, State>,
id: TorrentIdOrHash,
only_files: Vec<usize>,
) -> Result<EmptyJsonResponse, ApiError> {
state
.api()?
.api_torrent_action_update_only_files(id, &only_files.into_iter().collect())
.await
}
#[tauri::command]
async fn stats(state: tauri::State<'_, State>) -> Result<SessionStatsSnapshot, ApiError> {
Ok(state.api()?.api_session_stats())
}
#[tauri::command]
fn get_version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
async fn start() {
tauri::async_runtime::set(tokio::runtime::Handle::current());
let init_logging_result = init_logging(InitLoggingOptions {
default_rust_log_value: Some("info"),
log_file: None,
log_file_rust_log: None,
})
.unwrap();
match librqbit::try_increase_nofile_limit() {
Ok(limit) => info!(limit = limit, "inreased open file limit"),
Err(e) => warn!("failed increasing open file limit: {:#}", e),
};
let state = State::new(init_logging_result).await;
tauri::Builder::default()
.manage(state)
.invoke_handler(tauri::generate_handler![
torrents_list,
torrent_details,
torrent_stats,
torrent_create_from_url,
torrent_action_delete,
torrent_action_pause,
torrent_action_forget,
torrent_action_start,
torrent_action_configure,
torrent_create_from_base64_file,
stats,
get_version,
config_default,
config_current,
config_change,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
fn main() {
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("couldn't set up tokio runtime")
.block_on(start())
}