-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
276 lines (266 loc) · 11.6 KB
/
main.rs
File metadata and controls
276 lines (266 loc) · 11.6 KB
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
mod api;
mod config;
use anyhow::Result;
use librqbit::{
AddTorrent, AddTorrentOptions, AddTorrentResponse, ConnectionOptions, Session, SessionOptions,
};
use std::{collections::HashSet, num::NonZero, time::Duration};
use url::Url;
#[tokio::main]
async fn main() -> Result<()> {
use btracker_fs::crawler::Storage;
use chrono::Local;
use clap::Parser;
use config::Config;
use tokio::time;
// debug
if std::env::var("RUST_LOG").is_ok() {
use tracing_subscriber::{EnvFilter, fmt::*};
struct T;
impl time::FormatTime for T {
fn format_time(&self, w: &mut format::Writer<'_>) -> std::fmt::Result {
write!(w, "{}", Local::now())
}
}
fmt()
.with_env_filter(EnvFilter::from_default_env())
.with_timer(T)
.init()
}
// init components
let time_init = Local::now();
let config = Config::parse();
let preload = Storage::init(
config.preload,
config.preload_regex,
config.preload_max_filecount,
config.preload_max_filesize,
)
.unwrap();
let mut ban = HashSet::with_capacity(config.index_capacity);
log::info!("crawler started at {time_init}");
loop {
let time_queue = Local::now();
log::debug!("queue crawl begin at {time_queue}...");
// Please, note:
// * it's important to start new `Session` inside the crawler loop:
// https://github.com/ikatson/rqbit/issues/481
// * when fix and after starting it once (outside the loop),
// remove also each torrent after resolve it with `session.delete`, to prevent impl panic (see `single-session` branch)
let session = Session::new_with_opts(
preload.root().clone(),
SessionOptions {
bind_device_name: config.bind.clone(),
blocklist_url: config.blocklist.as_ref().map(|b| b.to_string()),
listen: None,
connect: Some(ConnectionOptions {
enable_tcp: !config.disable_tcp,
proxy_url: config.proxy_url.as_ref().map(|u| u.to_string()),
..ConnectionOptions::default()
}),
disable_dht_persistence: true,
disable_dht: !config.enable_dht,
disable_local_service_discovery: !config.enable_lsd,
disable_upload: true,
fastresume: false,
persistence: None,
ratelimits: librqbit::limits::LimitsConfig {
download_bps: config.download_limit.and_then(NonZero::new),
..librqbit::limits::LimitsConfig::default()
},
trackers: config.tracker.iter().cloned().collect(),
..SessionOptions::default()
},
)
.await?;
// build unique ID index from the multiple info-hash sources
let mut queue = HashSet::with_capacity(config.index_capacity);
for source in &config.infohash {
log::debug!("index source `{source}`...");
// grab latest info-hashes from this source
// * aquatic server may update the stats at this moment, handle result manually
for i in match api::get(source, config.index_capacity) {
Some(i) => {
log::debug!("fetch `{}` hashes from `{source}`...", i.len());
i
}
None => {
log::warn!(
"the feed `{source}` has an incomplete format (or is still updating); skip."
);
continue; // skip without panic
}
} {
queue.insert(i);
}
}
// clean up nonexistent ban entries from the memory pool
ban.retain(|i| {
let is_retain = queue.contains(i);
if !is_retain {
log::debug!(
"remove `{}` from the ban list, as it is no longer available in the source.",
i.as_string()
)
}
is_retain
});
// handle
log::debug!(
"fetched {} unique hashes from {} source, banned: {}.",
queue.len(),
config.infohash.len(),
ban.len()
);
for i in queue {
// convert to string once
let h = i.as_string();
if preload.contains_torrent(&h)? {
log::debug!("torrent `{h}` exists, skip.");
continue;
}
// skip banned entry, remove it from the ban list to retry on the next iteration
if ban.remove(&i) {
log::debug!("torrent `{h}` is banned, skip for this queue.");
continue;
}
log::info!("resolve `{h}`...");
// run the crawler in single thread for performance reasons,
// use `timeout` argument option to skip the dead connections.
match time::timeout(
Duration::from_secs(config.timeout),
session.add_torrent(
AddTorrent::from_url(magnet(
&h,
if config.tracker.is_empty() {
None
} else {
Some(config.tracker.as_ref())
},
)),
Some(AddTorrentOptions {
paused: true, // continue after `only_files` update
overwrite: true,
disable_trackers: config.tracker.is_empty(),
initial_peers: config.initial_peer.clone(),
list_only: false,
// the destination folder to preload files match `preload_regex`
// * e.g. images for audio albums
output_folder: preload.tmp_dir(&h, true)?.to_str().map(|s| s.to_string()),
..Default::default()
}),
),
)
.await
{
Ok(r) => match r {
Ok(AddTorrentResponse::Added(_, mt)) => {
assert!(mt.is_paused());
let mut keep_files = HashSet::with_capacity(
config.preload_max_filecount.unwrap_or_default(),
);
let mut only_files = HashSet::with_capacity(
config.preload_max_filecount.unwrap_or_default(),
);
mt.wait_until_initialized().await?;
let bytes = mt.with_metadata(|m| {
for (id, info) in m.file_infos.iter().enumerate() {
if preload
.max_filecount
.is_some_and(|limit| only_files.len() + 1 > limit)
{
log::debug!(
"file count limit ({}) reached, skip file `{id}` for `{h}` at `{}` (and other files after it)",
only_files.len(),
info.relative_filename.to_string_lossy()
);
break;
}
if preload.max_filesize.is_some_and(|limit| info.len > limit) {
log::debug!(
"file size ({}) limit reached, skip file `{id}` for `{h}` at `{}`",
info.len,
info.relative_filename.to_string_lossy()
);
continue;
}
if preload.regex.as_ref().is_some_and(|r| {
!r.is_match(&info.relative_filename.to_string_lossy())
}) {
log::debug!("regex filter, skip file `{id}` for `{h}` at `{}`",
info.relative_filename.to_string_lossy());
continue;
}
log::debug!(
"keep file `{id}` for `{h}` as `{}`",
info.relative_filename.to_string_lossy()
);
assert!(keep_files.insert(info.relative_filename.clone()));
assert!(only_files.insert(id))
}
m.torrent_bytes.to_vec()
})?;
session.update_only_files(&mt, &only_files).await?;
session.unpause(&mt).await?;
log::debug!("begin torrent `{h}` preload...");
if let Err(e) = time::timeout(
Duration::from_secs(config.timeout),
mt.wait_until_completed(),
)
.await
{
log::info!(
"skip awaiting the completion of preload torrent data for `{h}` (`{e}`), ban for the next queue.",
);
assert!(ban.insert(i));
continue;
}
log::debug!("torrent `{h}` preload completed.");
// persist torrent bytes and preloaded content,
// cleanup tmp (see rqbit#408)
log::debug!("persist torrent `{h}` with `{}` files...", keep_files.len());
preload.commit(&h, bytes, Some(keep_files))?;
log::info!("torrent `{h}` resolved.")
}
Ok(_) => panic!(),
Err(e) => {
log::warn!(
"failed to resolve torrent `{h}`: `{e}`, ban for the next queue."
);
assert!(ban.insert(i))
}
},
Err(e) => {
log::info!(
"skip awaiting the completion of adding torrent `{h}` (`{e}`), ban for the next queue."
);
assert!(ban.insert(i))
}
}
}
session.stop().await;
log::info!(
"queue completed at {time_queue} (time: {} / uptime: {} / banned: {}) await {} seconds to continue...",
Local::now()
.signed_duration_since(time_queue)
.as_seconds_f32(),
Local::now()
.signed_duration_since(time_init)
.as_seconds_f32(),
ban.len(),
config.sleep
);
std::thread::sleep(Duration::from_secs(config.sleep))
}
}
/// Build magnet URI (`librqbit` impl dependency)
fn magnet(info_hash: &str, trackers: Option<&Vec<Url>>) -> String {
let mut m = format!("magnet:?xt=urn:btih:{info_hash}");
if let Some(t) = trackers {
for tracker in t {
m.push_str("&tr=");
m.push_str(&urlencoding::encode(tracker.as_str()))
}
}
m
}