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
use std::error::Error;
use std::fmt;
use std::hash::Hasher;
use std::io::{BufRead, BufReader, Read};
use siphasher::sip128::{Hasher128, SipHasher};
use crate::model;
use crate::xml;
use crate::xml::NS;
mod atom;
mod json;
mod rss0;
mod rss1;
mod rss2;
pub(crate) mod itunes;
pub(crate) mod mediarss;
pub(crate) mod util;
pub type ParseFeedResult<T> = std::result::Result<T, ParseFeedError>;
#[derive(Debug)]
pub enum ParseFeedError {
ParseError(ParseErrorKind),
IoError(std::io::Error),
JsonSerde(serde_json::error::Error),
JsonUnsupportedVersion(String),
XmlReader(xml::XmlError),
}
impl From<serde_json::error::Error> for ParseFeedError {
fn from(err: serde_json::error::Error) -> Self {
ParseFeedError::JsonSerde(err)
}
}
impl From<std::io::Error> for ParseFeedError {
fn from(err: std::io::Error) -> Self {
ParseFeedError::IoError(err)
}
}
impl From<xml::XmlError> for ParseFeedError {
fn from(err: xml::XmlError) -> Self {
ParseFeedError::XmlReader(err)
}
}
impl fmt::Display for ParseFeedError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseFeedError::ParseError(pe) => write!(f, "unable to parse feed: {}", pe),
ParseFeedError::IoError(ie) => write!(f, "unable to read feed: {}", ie),
ParseFeedError::JsonSerde(je) => write!(f, "unable to parse JSON: {}", je),
ParseFeedError::JsonUnsupportedVersion(version) => write!(f, "unsupported version: {}", version),
ParseFeedError::XmlReader(xe) => write!(f, "unable to parse XML: {}", xe),
}
}
}
impl Error for ParseFeedError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ParseFeedError::IoError(ie) => Some(ie),
ParseFeedError::JsonSerde(je) => Some(je),
ParseFeedError::XmlReader(xe) => Some(xe),
_ => None,
}
}
}
#[derive(Debug)]
pub enum ParseErrorKind {
NoFeedRoot,
UnknownMimeType(String),
MissingContent(&'static str),
}
impl fmt::Display for ParseErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseErrorKind::NoFeedRoot => f.write_str("no root element"),
ParseErrorKind::UnknownMimeType(mime) => write!(f, "unsupported content type {}", mime),
ParseErrorKind::MissingContent(elem) => write!(f, "missing content element {}", elem),
}
}
}
pub fn parse<R: Read>(source: R) -> ParseFeedResult<model::Feed> {
parse_with_uri(source, None)
}
pub fn parse_with_uri<R: Read>(source: R, uri: Option<&str>) -> ParseFeedResult<model::Feed> {
let mut input = BufReader::new(source);
input.fill_buf()?;
let first_char = input.buffer().iter().find(|b| **b == b'<' || **b == b'{').map(|b| *b as char);
let result = match first_char {
Some('<') => parse_xml(input, uri),
Some('{') => parse_json(input),
_ => Err(ParseFeedError::ParseError(ParseErrorKind::NoFeedRoot)),
};
if let Ok(mut feed) = result {
assign_missing_ids(&mut feed, uri);
Ok(feed)
} else {
result
}
}
fn assign_missing_ids(feed: &mut model::Feed, uri: Option<&str>) {
if feed.id.is_empty() {
feed.id = create_id(&feed.links, &feed.title, uri);
}
for entry in feed.entries.iter_mut() {
if entry.id.is_empty() {
entry.id = create_id(&entry.links, &entry.title, uri);
}
}
}
const LINK_HASH_KEY1: u64 = 0x5d78_4074_2887_2d60;
const LINK_HASH_KEY2: u64 = 0x90ee_ca4c_90a5_e228;
fn create_id(links: &[model::Link], title: &Option<model::Text>, uri: Option<&str>) -> String {
if let Some(link) = links.iter().next() {
let mut hasher = SipHasher::new_with_keys(LINK_HASH_KEY1, LINK_HASH_KEY2);
hasher.write(link.href.as_bytes());
if let Some(title) = title {
hasher.write(title.content.as_bytes());
}
let hash = hasher.finish128();
format!("{:x}{:x}", hash.h1, hash.h2)
} else if let (Some(uri), Some(title)) = (uri, title) {
let mut hasher = SipHasher::new_with_keys(LINK_HASH_KEY1, LINK_HASH_KEY2);
hasher.write(uri.as_bytes());
hasher.write(title.content.as_bytes());
let hash = hasher.finish128();
format!("{:x}{:x}", hash.h1, hash.h2)
} else {
util::uuid_gen()
}
}
fn parse_json<R: BufRead>(source: R) -> ParseFeedResult<model::Feed> {
json::parse(source)
}
fn parse_xml<R: BufRead>(source: R, uri: Option<&str>) -> ParseFeedResult<model::Feed> {
let element_source = xml::ElementSource::new(source, uri)?;
if let Ok(Some(root)) = element_source.root() {
let version = root.attr_value("version");
match (root.name.as_str(), version.as_deref()) {
("feed", _) => {
element_source.set_default_default_namespace(NS::Atom);
return atom::parse_feed(root);
}
("entry", _) => {
element_source.set_default_default_namespace(NS::Atom);
return atom::parse_entry(root);
}
("rss", Some("2.0")) => {
element_source.set_default_default_namespace(NS::RSS);
return rss2::parse(root);
}
("rss", Some("0.91")) | ("rss", Some("0.92")) => {
element_source.set_default_default_namespace(NS::RSS);
return rss0::parse(root);
}
("RDF", _) => {
element_source.set_default_default_namespace(NS::RSS);
return rss1::parse(root);
}
_ => {}
};
}
Err(ParseFeedError::ParseError(ParseErrorKind::NoFeedRoot))
}
#[cfg(test)]
mod fuzz;