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
extern crate serde;
extern crate serde_json;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::Debug;
use std::fs;
use std::io::Write;
use std::io::{BufRead, BufReader};
use std::sync::{Arc, Mutex};
use crate::utils;
#[derive(Deserialize, Debug, Clone, Serialize)]
#[serde(bound = "T: Serialize + for<'a> Deserialize<'a> + Debug + Clone")]
pub struct Task<T>
where
T: Serialize + for<'a> Deserialize<'a> + Debug + Clone,
{
pub uri: String,
pub method: String,
pub headers: HashMap<String, String>,
pub body: Option<HashMap<String, String>>,
pub able: f64,
pub trys: u8,
pub parser: String,
pub targs: Option<T>,
}
impl<T> Task<T>
where
T: Serialize + for<'a> Deserialize<'a> + Debug + Clone,
{
pub fn new() -> Self {
let now = utils::now();
Task::<T> {
uri: "".to_string(),
method: "GET".to_string(),
headers: HashMap::new(),
body: None,
able: now,
trys: 0,
parser: "".to_string(),
targs: None,
}
}
pub fn stored(path: &str, task: &mut Arc<Mutex<Vec<Task<T>>>>) {
let mut file = fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.open(path)
.unwrap();
let mut buf = Vec::new();
while let Some(r) = task.lock().unwrap().pop() {
let s = serde_json::to_string(&r).unwrap();
buf.push(s);
}
file.write(buf.join("\n").as_bytes()).unwrap();
}
pub fn load(path: &str) -> Vec<Task<T>> {
let file = fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(path)
.unwrap();
let data = BufReader::new(&file)
.lines()
.map(|line| {
let s = line.unwrap().to_string();
let task: Task<T> = serde_json::from_str(&s).unwrap();
task
})
.collect::<Vec<Task<T>>>();
return data;
}
}