diff options
| author | Christine Dodrill <me@christine.website> | 2020-07-16 15:32:30 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-07-16 15:32:30 -0400 |
| commit | 385d25c9f96c0acd5d932488e3bd0ed36ceb4dd7 (patch) | |
| tree | af789f7250519b23038a7e5ea0ae7f4f4c1ffdfc /lib | |
| parent | 449e934246c82d90dd0aac2644d67f928befeeb4 (diff) | |
| download | xesite-385d25c9f96c0acd5d932488e3bd0ed36ceb4dd7.tar.xz xesite-385d25c9f96c0acd5d932488e3bd0ed36ceb4dd7.zip | |
Rewrite site backend in Rust (#178)
* add shell.nix changes for Rust #176
* set up base crate layout
* add first set of dependencies
* start adding basic app modules
* start html templates
* serve index page
* add contact and feeds pages
* add resume rendering support
* resume cleanups
* get signalboost page working
* rewrite config to be in dhall
* more work
* basic generic post loading
* more tests
* initial blog index support
* fix routing?
* render blogposts
* X-Clacks-Overhead
* split blog handlers into blog.rs
* gallery index
* gallery posts
* fix hashtags
* remove instantpage (it messes up the metrics)
* talk support + prometheus
* Create rust.yml
* Update rust.yml
* Update codeql-analysis.yml
* add jsonfeed library
* jsonfeed support
* rss/atom
* go mod tidy
* atom: add posted date
* rss: add publishing date
* nix: build rust program
* rip out go code
* rip out go templates
* prepare for serving in docker
* create kubernetes deployment
* create automagic deployment
* build docker images on non-master
* more fixes
* fix timestamps
* fix RSS/Atom/JSONFeed validation errors
* add go vanity import redirecting
* templates/header: remove this
* atom feed: fixes
* fix?
* fix??
* fix rust tests
* Update rust.yml
* automatically show snow during the winter
* fix dates
* show commit link in footer
* sitemap support
* fix compiler warning
* start basic patreon client
* integrate kankyo
* fix patreon client
* add patrons page
* remove this
* handle patron errors better
* fix build
* clean up deploy
* sort envvars for deploy
* remove deps.nix
* shell.nix: remove go
* update README
* fix envvars for tests
* nice
* blog: add rewrite in rust post
* blog/site-update: more words
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/go_vanity/Cargo.toml | 15 | ||||
| -rw-r--r-- | lib/go_vanity/src/build.rs | 5 | ||||
| -rw-r--r-- | lib/go_vanity/src/lib.rs | 12 | ||||
| -rw-r--r-- | lib/go_vanity/templates/gitea.rs.html | 14 | ||||
| -rw-r--r-- | lib/go_vanity/templates/github.rs.html | 14 | ||||
| -rw-r--r-- | lib/jsonfeed/.gitignore | 4 | ||||
| -rw-r--r-- | lib/jsonfeed/Cargo.toml | 15 | ||||
| -rw-r--r-- | lib/jsonfeed/LICENSE-APACHE | 201 | ||||
| -rw-r--r-- | lib/jsonfeed/LICENSE-MIT | 25 | ||||
| -rw-r--r-- | lib/jsonfeed/README.adoc | 27 | ||||
| -rw-r--r-- | lib/jsonfeed/src/builder.rs | 204 | ||||
| -rw-r--r-- | lib/jsonfeed/src/errors.rs | 7 | ||||
| -rw-r--r-- | lib/jsonfeed/src/feed.rs | 296 | ||||
| -rw-r--r-- | lib/jsonfeed/src/item.rs | 493 | ||||
| -rw-r--r-- | lib/jsonfeed/src/lib.rs | 252 | ||||
| -rw-r--r-- | lib/patreon/.gitignore | 1 | ||||
| -rw-r--r-- | lib/patreon/Cargo.toml | 20 | ||||
| -rw-r--r-- | lib/patreon/examples/campaign.rs | 17 | ||||
| -rw-r--r-- | lib/patreon/src/lib.rs | 158 |
19 files changed, 1780 insertions, 0 deletions
diff --git a/lib/go_vanity/Cargo.toml b/lib/go_vanity/Cargo.toml new file mode 100644 index 0000000..ae10f24 --- /dev/null +++ b/lib/go_vanity/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "go_vanity" +version = "0.1.0" +authors = ["Christine Dodrill <me@christine.website>"] +edition = "2018" +build = "src/build.rs" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +mime = "0.3.0" +warp = "0.2" + +[build-dependencies] +ructe = { version = "0.11", features = ["warp02"] } diff --git a/lib/go_vanity/src/build.rs b/lib/go_vanity/src/build.rs new file mode 100644 index 0000000..f36737c --- /dev/null +++ b/lib/go_vanity/src/build.rs @@ -0,0 +1,5 @@ +use ructe::{Result, Ructe}; + +fn main() -> Result<()> { + Ructe::from_env()?.compile_templates("templates") +} diff --git a/lib/go_vanity/src/lib.rs b/lib/go_vanity/src/lib.rs new file mode 100644 index 0000000..e4a11e2 --- /dev/null +++ b/lib/go_vanity/src/lib.rs @@ -0,0 +1,12 @@ +use warp::{http::Response, Rejection, Reply}; +use crate::templates::{RenderRucte}; + +include!(concat!(env!("OUT_DIR"), "/templates.rs")); + +pub async fn gitea(pkg_name: &str, git_repo: &str) -> Result<impl Reply, Rejection> { + Response::builder().html(|o| templates::gitea_html(o, pkg_name, git_repo)) +} + +pub async fn github(pkg_name: &str, git_repo: &str) -> Result<impl Reply, Rejection> { + Response::builder().html(|o| templates::github_html(o, pkg_name, git_repo)) +} diff --git a/lib/go_vanity/templates/gitea.rs.html b/lib/go_vanity/templates/gitea.rs.html new file mode 100644 index 0000000..b20985b --- /dev/null +++ b/lib/go_vanity/templates/gitea.rs.html @@ -0,0 +1,14 @@ +@(pkg_name: &str, git_repo: &str) + +<!DOCTYPE html> +<html> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> + <meta name="go-import" content="@pkg_name git @git_repo"> + <meta name="go-source" content="@pkg_name @git_repo @git_repo/src/master@{/dir@} @git_repo/src/master@{/dir@}/@{file@}#L@{line@}"> + <meta http-equiv="refresh" content="0; url=https://godoc.org/@pkg_name"> + </head> + <body> + Please see <a href="https://godoc.org/@pkg_name">here</a> for documentation on this package. + </body> +</html> diff --git a/lib/go_vanity/templates/github.rs.html b/lib/go_vanity/templates/github.rs.html new file mode 100644 index 0000000..61f42e5 --- /dev/null +++ b/lib/go_vanity/templates/github.rs.html @@ -0,0 +1,14 @@ +@(pkg_name: &str, git_repo: &str) + +<!DOCTYPE html> +<html> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> + <meta name="go-import" content="@pkg_name git @git_repo"> + <meta name="go-source" content="@pkg_name @git_repo @git_repo/tree/master@{/dir@} @git_repo/blob/master@{/dir@}/@{file@}#L@{line@}"> + <meta http-equiv="refresh" content="0; url=https://godoc.org/@pkg_name"> + </head> + <body> + Please see <a href="https://godoc.org/@pkg_name">here</a> for documentation on this package. + </body> +</html> diff --git a/lib/jsonfeed/.gitignore b/lib/jsonfeed/.gitignore new file mode 100644 index 0000000..f382b9f --- /dev/null +++ b/lib/jsonfeed/.gitignore @@ -0,0 +1,4 @@ +target/ +**/*.rs.bk +Cargo.lock +*.html diff --git a/lib/jsonfeed/Cargo.toml b/lib/jsonfeed/Cargo.toml new file mode 100644 index 0000000..e85ee46 --- /dev/null +++ b/lib/jsonfeed/Cargo.toml @@ -0,0 +1,15 @@ +[package] +authors = ["Paul Woolcock <paul@woolcock.us>", "Christine Dodrill <me@christine.website>"] +description = "Parser for the JSONFeed (http://jsonfeed.org) specification\n" +documentation = "https://docs.rs/jsonfeed" +homepage = "https://github.com/pwoolcoc/jsonfeed" +license = "MIT/Apache-2.0" +name = "jsonfeed" +readme = "README.adoc" +version = "0.3.0" + +[dependencies] +error-chain = "0.12" +serde = "1" +serde_derive = "1" +serde_json = "1" diff --git a/lib/jsonfeed/LICENSE-APACHE b/lib/jsonfeed/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/lib/jsonfeed/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/lib/jsonfeed/LICENSE-MIT b/lib/jsonfeed/LICENSE-MIT new file mode 100644 index 0000000..39d4bdb --- /dev/null +++ b/lib/jsonfeed/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/lib/jsonfeed/README.adoc b/lib/jsonfeed/README.adoc new file mode 100644 index 0000000..581bf3d --- /dev/null +++ b/lib/jsonfeed/README.adoc @@ -0,0 +1,27 @@ += JSON Feed Parser + +[link=https://github.com/pwoolcoc/jsonfeed] +image::https://img.shields.io/crates/v/jsonfeed.svg[JSON Feed crate version] + +This is a http://jsonfeed.org[JSON Feed] parser in Rust. Just a thin layer on top of `serde`, but it +provides serialization & deserialization, along with a Builder API for constructing feeds. + +Note that this is alpha, I still need to add a lot of tests and a couple more features. + +== Example + +---- +extern crate jsonfeed; +extern crate reqwest; + +fn main() { + let resp = reqwest::get("https://example.com/feed.json").unwrap(); + let feed = jsonfeed::from_reader(resp).unwrap(); + println!("Feed title is: {}", feed.title); +} +---- + +TODO: + +* Tests. Lots and lots of tests +* Implement ability to add, serialize, and deserialize custom attributes from the json feed spec diff --git a/lib/jsonfeed/src/builder.rs b/lib/jsonfeed/src/builder.rs new file mode 100644 index 0000000..f17740f --- /dev/null +++ b/lib/jsonfeed/src/builder.rs @@ -0,0 +1,204 @@ +use std::default::Default; + +use errors::*; +use feed::{Feed, Author, Attachment}; +use item::{Content, Item}; + +/// Feed Builder +/// +/// This is used to programmatically build up a Feed object, +/// which can be serialized later into a JSON string +pub struct Builder(Feed); + +impl Builder { + pub fn new() -> Builder { + Builder(Feed::default()) + } + + pub fn title<I: Into<String>>(mut self, t: I) -> Builder { + self.0.title = t.into(); + self + } + + pub fn home_page_url<I: Into<String>>(mut self, url: I) -> Builder { + self.0.home_page_url = Some(url.into()); + self + } + + pub fn feed_url<I: Into<String>>(mut self, url: I) -> Builder { + self.0.feed_url = Some(url.into()); + self + } + + pub fn description<I: Into<String>>(mut self, desc: I) -> Builder { + self.0.description = Some(desc.into()); + self + } + + pub fn user_comment<I: Into<String>>(mut self, cmt: I) -> Builder { + self.0.user_comment = Some(cmt.into()); + self + } + + pub fn next_url<I: Into<String>>(mut self, url: I) -> Builder { + self.0.next_url = Some(url.into()); + self + } + + pub fn icon<I: Into<String>>(mut self, url: I) -> Builder { + self.0.icon = Some(url.into()); + self + } + + pub fn favicon<I: Into<String>>(mut self, url: I) -> Builder { + self.0.favicon = Some(url.into()); + self + } + + pub fn author(mut self, author: Author) -> Builder { + self.0.author = Some(author); + self + } + + pub fn expired(mut self) -> Builder { + self.0.expired = Some(true); + self + } + + pub fn item(mut self, item: Item) -> Builder { + self.0.items.push(item); + self + } + + pub fn build(self) -> Feed { + self.0 + } +} + +/// Builder object for an item in a feed +pub struct ItemBuilder { + pub id: Option<String>, + pub url: Option<String>, + pub external_url: Option<String>, + pub title: Option<String>, + pub content: Option<Content>, + pub summary: Option<String>, + pub image: Option<String>, + pub banner_image: Option<String>, + pub date_published: Option<String>, + pub date_modified: Option<String>, + pub author: Option<Author>, + pub tags: Option<Vec<String>>, + pub attachments: Option<Vec<Attachment>>, +} + +impl ItemBuilder { + pub fn new() -> ItemBuilder { + ItemBuilder { + id: None, + url: None, + external_url: None, + title: None, + content: None, + summary: None, + image: None, + banner_image: None, + date_published: None, + date_modified: None, + author: None, + tags: None, + attachments: None, + } + } + + pub fn title<I: Into<String>>(mut self, i: I) -> ItemBuilder { + self.title = Some(i.into()); + self + } + + pub fn image<I: Into<String>>(mut self, i: I) -> ItemBuilder { + self.image = Some(i.into()); + self + } + + pub fn id<I: Into<String>>(mut self, i: I) -> ItemBuilder { + self.id = Some(i.into()); + self + } + + pub fn url<I: Into<String>>(mut self, i: I) -> ItemBuilder { + self.url = Some(i.into()); + self + } + + pub fn external_url<I: Into<String>>(mut self, i: I) -> ItemBuilder { + self.external_url = Some(i.into()); + self + } + + pub fn date_modified<I: Into<String>>(mut self, i: I) -> ItemBuilder { + self.date_modified = Some(i.into()); + self + } + + pub fn date_published<I: Into<String>>(mut self, i: I) -> ItemBuilder { + self.date_published = Some(i.into()); + self + } + + pub fn tags(mut self, tags: Vec<String>) -> ItemBuilder { + self.tags = Some(tags); + self + } + + pub fn author(mut self, who: Author) -> ItemBuilder { + self.author = Some(who); + self + } + + pub fn content_html<I: Into<String>>(mut self, i: I) -> ItemBuilder { + match self.content { + Some(Content::Text(t)) => { + self.content = Some(Content::Both(i.into(), t)); + }, + _ => { + self.content = Some(Content::Html(i.into())); + } + } + self + } + + pub fn content_text<I: Into<String>>(mut self, i: I) -> ItemBuilder { + match self.content { + Some(Content::Html(s)) => { + self.content = Some(Content::Both(s, i.into())); + }, + _ => { + self.content = Some(Content::Text(i.into())); + }, + } + self + } + + pub fn build(self) -> Result<Item> { + if self.id.is_none() || self.content.is_none() { + return Err("missing field 'id' or 'content_*'".into()); + } + Ok(Item { + id: self.id.unwrap(), + url: self.url, + external_url: self.external_url, + title: self.title, + content: self.content.unwrap(), + summary: self.summary, + image: self.image, + banner_image: self.banner_image, + date_published: self.date_published, + date_modified: self.date_modified, + author: self.author, + tags: self.tags, + attachments: self.attachments + }) + } +} + diff --git a/lib/jsonfeed/src/errors.rs b/lib/jsonfeed/src/errors.rs new file mode 100644 index 0000000..936b7ec --- /dev/null +++ b/lib/jsonfeed/src/errors.rs @@ -0,0 +1,7 @@ +use serde_json; +error_chain!{ + foreign_links { + Serde(serde_json::Error); + } +} + diff --git a/lib/jsonfeed/src/feed.rs b/lib/jsonfeed/src/feed.rs new file mode 100644 index 0000000..8b5b5ce --- /dev/null +++ b/lib/jsonfeed/src/feed.rs @@ -0,0 +1,296 @@ +use std::default::Default; + +use item::Item; +use builder::Builder; + +const VERSION_1: &'static str = "https://jsonfeed.org/version/1"; + +/// Represents a single feed +/// +/// # Examples +/// +/// ```rust +/// // Serialize a feed object to a JSON string +/// +/// # extern crate jsonfeed; +/// # use std::default::Default; +/// # use jsonfeed::Feed; +/// # fn main() { +/// let feed: Feed = Feed::default(); +/// assert_eq!( +/// jsonfeed::to_string(&feed).unwrap(), +/// "{\"version\":\"https://jsonfeed.org/version/1\",\"title\":\"\",\"items\":[]}" +/// ); +/// # } +/// ``` +/// +/// ```rust +/// // Deserialize a feed objects from a JSON String +/// +/// # extern crate jsonfeed; +/// # use jsonfeed::Feed; +/// # fn main() { +/// let json = "{\"version\":\"https://jsonfeed.org/version/1\",\"title\":\"\",\"items\":[]}"; +/// let feed: Feed = jsonfeed::from_str(&json).unwrap(); +/// assert_eq!( +/// feed, +/// Feed::default() +/// ); +/// # } +/// ``` +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Feed { + pub version: String, + pub title: String, + pub items: Vec<Item>, + #[serde(skip_serializing_if = "Option::is_none")] + pub home_page_url: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub feed_url: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub user_comment: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub next_url: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub icon: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub favicon: Option<String>, + #[serde(skip_serializing_if = "Option::is_none")] + pub author: Option<Author>, + #[serde(skip_serializing_if = "Option::is_none")] + pub expired: Option<bool>, + #[serde(skip_serializing_if = "Option::is_none")] + pub hubs: Option<Vec<Hub>>, +} + +impl Feed { + /// Used to construct a Feed object + pub fn builder() -> Builder { + Builder::new() + } +} + +impl Default for Feed { + fn default() -> Feed { + Feed { + version: VERSION_1.to_string(), + title: "".to_string(), + items: vec![], + home_page_url: None, + feed_url: None, + description: None, + user_comment: None, + next_url: None, + icon: None, + favicon: None, + author: None, + expired: None, + hubs: None, + } + } +} + +/// Represents an `attachment` for an item +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Attachment { + url: String, + mime_type: String, + title: Option<String>, + size_in_bytes: Option<u64>, + duration_in_seconds: Option<u64>, +} + +/// Represents an `author` in both a feed and a feed item +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Author { + name: Option<String>, + url: Option<String>, + avatar: Option<String>, +} + +impl Author { + pub fn new() -> Author { + Author { + name: None, + url: None, + avatar: None, + } + } + + pub fn name<I: Into<String>>(mut self, name: I) -> Self { + self.name = Some(name.into()); + self + } + + pub fn url<I: Into<String>>(mut self, url: I) -> Self { + self.url = Some(url.into()); + self + } + + pub fn avatar<I: Into<String>>(mut self, avatar: I) -> Self { + self.avatar = Some(avatar.into()); + self + } +} + +/// Represents a `hub` for a feed +#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] +pub struct Hub { + #[serde(rename = "type")] + type_: String, + url: String, +} + +#[cfg(test)] +mod tests { + use serde_json; + use std::default::Default; + use super::*; + + #[test] + fn serialize_feed() { + let feed = Feed { + version: "https://jsonfeed.org/version/1".to_string(), + title: "some title".to_string(), + items: vec![], + home_page_url: None, + description: None, + expired: Some(true), + ..Default::default() + }; + assert_eq!( + serde_json::to_string(&feed).unwrap(), + r#"{"version":"https://jsonfeed.org/version/1","title":"some title","items":[],"expired":true}"# + ); + } + + #[test] + fn deserialize_feed() { + let json = r#"{"version":"https://jsonfeed.org/version/1","title":"some title","items":[]}"#; + let feed: Feed = serde_json::from_str(&json).unwrap(); + let expected = Feed { + version: "https://jsonfeed.org/version/1".to_string(), + title: "some title".to_string(), + items: vec![], + ..Default::default() + }; + assert_eq!( + feed, + expected + ); + } |
