Debian Codegraph @

podcasts-data/src/opml.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // opml.rs
2 //
3 // Copyright 2017 Jordan Petridis <[email protected]>
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program. If not, see <http://www.gnu.org/licenses/>.
17 //
18 // SPDX-License-Identifier: GPL-3.0-or-later
19
20 //! FIXME: Docs
21
22 use crate::dbqueries;
23 use crate::errors::DataError;
24 use crate::models::Source;
25 use xml::{
26 common::XmlVersion,
27 reader,
28 writer::{EmitterConfig, events::XmlEvent},
29 };
30
31 use std::collections::HashSet;
32 use std::fs;
33 use std::io::{Read, Write};
34 use std::path::Path;
35
36 use std::fs::File;
37 // use std::io::BufReader;
38
39 use anyhow::Result;
40
41 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
42 // FIXME: Make it a Diesel model
43 /// Represents an `outline` xml element as per the `OPML` [specification][spec]
44 /// not `RSS` related sub-elements are omitted.
45 ///
46 /// [spec]: http://dev.opml.org/spec2.html
47 pub struct Opml {
48 title: String,
49 description: String,
50 url: String,
51 }
52
53 /// Import feed url's from a `R` into the `Source` table.
54 // TODO: Write test
55 pub fn import_to_db<R: Read>(reader: R) -> Result<Vec<Source>, reader::Error> {
56 let feeds = extract_sources(reader)?
57 .iter()
58 .map(|opml| Source::from_url(&opml.url))
59 .filter_map(|s| {
60 if let Err(ref err) = s {
61 let txt = "If you think this might be a bug please consider filling a report over \
62 at https://gitlab.gnome.org/World/podcasts/issues/new";
63
64 error!("Failed to import a Show: {}", err);
65 error!("{}", txt);
66 }
67
68 s.ok()
69 })
70 .collect();
71
72 Ok(feeds)
73 }
74
75 /// Open a File from `P`, try to parse the OPML then insert the Feeds in the database and
76 /// return the new `Source`s
77 // TODO: Write test
78 pub fn import_from_file<P: AsRef<Path>>(path: P) -> Result<Vec<Source>, DataError> {
79 let content = fs::read(path)?;
80 import_to_db(content.as_slice()).map_err(From::from)
81 }
82
83 /// Export a file to `P`, taking the feeds from the database and outputting
84 /// them in opml format.
85 pub fn export_from_db<P: AsRef<Path>>(path: P, export_title: &str) -> Result<()> {
86 let file = File::create(path)?;
87 export_to_file(&file, export_title)
88 }
89
90 /// Export from `Source`s and `Show`s into `F` in OPML format
91 pub fn export_to_file<F: Write>(file: F, export_title: &str) -> Result<()> {
92 let config = EmitterConfig::new().perform_indent(true);
93
94 let mut writer = config.create_writer(file);
95
96 let mut events: Vec<XmlEvent<'_>> = Vec::new();
97
98 // Set up headers
99 let doc = XmlEvent::StartDocument {
100 version: XmlVersion::Version10,
101 encoding: Some("UTF-8"),
102 standalone: Some(false),
103 };
104 events.push(doc);
105
106 let opml: XmlEvent<'_> = XmlEvent::start_element("opml")
107 .attr("version", "2.0")
108 .into();
109 events.push(opml);
110
111 let head: XmlEvent<'_> = XmlEvent::start_element("head").into();
112 events.push(head);
113
114 let title_ev: XmlEvent<'_> = XmlEvent::start_element("title").into();
115 events.push(title_ev);
116
117 let title_chars: XmlEvent<'_> = XmlEvent::characters(export_title);
118 events.push(title_chars);
119
120 // Close <title> & <head>
121 events.push(XmlEvent::end_element().into());
122 events.push(XmlEvent::end_element().into());
123
124 let body: XmlEvent<'_> = XmlEvent::start_element("body").into();
125 events.push(body);
126
127 for event in events {
128 writer.write(event)?;
129 }
130
131 // FIXME: Make this a model of a joined query (http://docs.diesel.rs/diesel/macro.joinable.html)
132 let shows = dbqueries::get_podcasts()?.into_iter().map(|show| {
133 let source = dbqueries::get_source_from_id(show.source_id()).unwrap();
134 (source, show)
135 });
136
137 for (ref source, ref show) in shows {
138 let title = show.title();
139 let link = show.link();
140 let xml_url = source.uri();
141
142 let s_ev: XmlEvent<'_> = XmlEvent::start_element("outline")
143 .attr("text", title)
144 .attr("title", title)
145 .attr("type", "rss")
146 .attr("xmlUrl", xml_url)
147 .attr("htmlUrl", link)
148 .into();
149
150 let end_ev: XmlEvent<'_> = XmlEvent::end_element().into();
151 writer.write(s_ev)?;
152 writer.write(end_ev)?;
153 }
154
155 // Close <body> and <opml>
156 let end_bod: XmlEvent<'_> = XmlEvent::end_element().into();
157 writer.write(end_bod)?;
158 let end_opml: XmlEvent<'_> = XmlEvent::end_element().into();
159 writer.write(end_opml)?;
160
161 Ok(())
162 }
163
164 /// Extracts the `outline` elements from a reader `R` and returns a `HashSet` of `Opml` structs.
165 pub fn extract_sources<R: Read>(reader: R) -> Result<HashSet<Opml>, reader::Error> {
166 let mut list = HashSet::new();
167 let parser = reader::EventReader::new(reader);
168
169 parser
170 .into_iter()
171 .map(|e| match e {
172 Ok(reader::XmlEvent::StartElement {
173 name, attributes, ..
174 }) => {
175 if name.local_name == "outline" {
176 let mut title = String::new();
177 let mut url = String::new();
178 let mut description = String::new();
179
180 attributes.into_iter().for_each(|attribute| {
181 match attribute.name.local_name.as_str() {
182 "title" => title = attribute.value,
183 "xmlUrl" => url = attribute.value,
184 "description" => description = attribute.value,
185 _ => {}
186 }
187 });
188
189 let feed = Opml {
190 title,
191 description,
192 url,
193 };
194 list.insert(feed);
195 }
196 Ok(())
197 }
198 Err(err) => Err(err),
199 _ => Ok(()),
200 })
201 .collect::<Result<Vec<_>, reader::Error>>()?;
202
203 Ok(list)
204 }
205
206 #[cfg(test)]
207 mod tests {
208 use super::*;
209 use anyhow::Result;
210 use chrono::Local;
211
212 use crate::database::{TEMPDIR, truncate_db};
213 use crate::utils::get_feed;
214
215 const URLS: &[(&str, &str)] = {
216 &[
217 (
218 "tests/feeds/2018-01-20-Intercepted.xml",
219 "https://web.archive.org/web/20180120083840if_/https://feeds.feedburner.\
220 com/InterceptedWithJeremyScahill",
221 ),
222 (
223 "tests/feeds/2018-01-20-LinuxUnplugged.xml",
224 "https://web.archive.org/web/20180120110314if_/https://feeds.feedburner.\
225 com/linuxunplugged",
226 ),
227 (
228 "tests/feeds/2018-01-20-TheTipOff.xml",
229 "https://web.archive.org/web/20180120110727if_/https://rss.acast.com/thetipoff",
230 ),
231 (
232 "tests/feeds/2018-01-20-StealTheStars.xml",
233 "https://web.archive.org/web/20180120104957if_/https://rss.art19.\
234 com/steal-the-stars",
235 ),
236 (
237 "tests/feeds/2018-01-20-GreaterThanCode.xml",
238 "https://web.archive.org/web/20180120104741if_/https://www.greaterthancode.\
239 com/feed/podcast",
240 ),
241 (
242 "tests/feeds/2019-01-27-ACC.xml",
243 "https://web.archive.org/web/20190127005213if_/https://anticapitalistchronicles.libsyn.com/rss",
244 ),
245 ]
246 };
247
248 #[test]
249 fn test_extract() -> Result<()> {
250 let int_title = String::from("Intercepted with Jeremy Scahill");
251 let int_url = String::from("https://feeds.feedburner.com/InterceptedWithJeremyScahill");
252 let int_desc = String::from(
253 "The people behind The Intercept’s fearless reporting and incisive \
254 commentary—Jeremy Scahill, Glenn Greenwald, Betsy Reed and others—discuss the \
255 crucial issues of our time: national security, civil liberties, foreign policy, \
256 and criminal justice. Plus interviews with artists, thinkers, and newsmakers \
257 who challenge our preconceptions about the world we live in.",
258 );
259
260 let dec_title = String::from("Deconstructed with Mehdi Hasan");
261 let dec_url = String::from("https://rss.prod.firstlook.media/deconstructed/podcast.rss");
262 let dec_desc = String::from(
263 "Journalist Mehdi Hasan is known around the world for his televised takedowns of \
264 presidents and prime ministers. In this new podcast from The Intercept, Mehdi \
265 unpacks a game-changing news event of the week while challenging the conventional \
266 wisdom. As a Brit, a Muslim and an immigrant based in Donald Trump's Washington \
267 D.C., Mehdi gives a refreshingly provocative perspective on the ups and downs of \
268 American—and global—politics.",
269 );
270
271 let sample1 = format!(
272 "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \
273 <opml version=\"2.0\"> \
274 <head> \
275 <title>Test OPML File</title> \
276 <dateCreated>{}</dateCreated> \
277 <docs>http://www.opml.org/spec2</docs> \
278 </head> \
279 <body> \
280 <outline type=\"rss\" title=\"{}\" description=\"{}\" xmlUrl=\"{}\"/> \
281 <outline type=\"rss\" title=\"{}\" description=\"{}\" xmlUrl=\"{}\"/> \
282 </body> \
283 </opml>",
284 Local::now().format("%a, %d %b %Y %T %Z"),
285 int_title,
286 int_desc,
287 int_url,
288 dec_title,
289 dec_desc,
290 dec_url,
291 );
292
293 let map = hashset![
294 Opml {
295 title: int_title,
296 description: int_desc,
297 url: int_url
298 },
299 Opml {
300 title: dec_title,
301 description: dec_desc,
302 url: dec_url
303 },
304 ];
305 assert_eq!(extract_sources(sample1.as_bytes())?, map);
306 Ok(())
307 }
308
•309 /* Disable tests that needs XML feed
310 #[test]
311 fn text_export() -> Result<()> {
312 truncate_db()?;
313
314 URLS.iter().for_each(|&(path, url)| {
315 // Create and insert a Source into db
316 let s = Source::from_url(url).unwrap();
317 let feed = get_feed(path, s.id());
318 feed.index().unwrap();
319 });
320
321 let mut map: HashSet<Opml> = HashSet::new();
322 let shows = dbqueries::get_podcasts()?.into_iter().map(|show| {
323 let source = dbqueries::get_source_from_id(show.source_id()).unwrap();
324 (source, show)
325 });
326
327 for (ref source, ref show) in shows {
328 let title = show.title().to_string();
329 // description is an optional field that we don't export
330 let description = String::new();
331 let url = source.uri().to_string();
332
333 map.insert(Opml {
334 title,
335 description,
336 url,
337 });
338 }
339
340 let opml_path = TEMPDIR.path().join("podcasts.opml");
341 export_from_db(opml_path.as_path(), "GNOME Podcasts Subscriptions")?;
342 let opml_file = File::open(opml_path.as_path())?;
343 assert_eq!(extract_sources(&opml_file)?, map);
344
345 // extract_sources drains the reader its passed
346 let mut opml_file = File::open(opml_path.as_path())?;
347 let mut opml_str = String::new();
348 opml_file.read_to_string(&mut opml_str)?;
349 assert_eq!(opml_str, include_str!("../tests/export_test.opml"));
350 Ok(())
351 }
•352 */
353 }