1 use actix_web::{error::ErrorBadRequest, *};
3 use chrono::{DateTime, NaiveDateTime, Utc};
4 use diesel::PgConnection;
5 use lemmy_api::claims::Claims;
6 use lemmy_db_queries::{
7 source::{community::Community_, user::User},
11 use lemmy_db_schema::source::{community::Community, user::User_};
13 comment_view::{CommentQueryBuilder, CommentView},
14 post_view::{PostQueryBuilder, PostView},
17 use lemmy_db_views_actor::user_mention_view::{UserMentionQueryBuilder, UserMentionView};
18 use lemmy_structs::blocking;
19 use lemmy_utils::{settings::Settings, utils::markdown_to_html, LemmyError};
20 use lemmy_websocket::LemmyContext;
22 extension::dublincore::DublinCoreExtensionBuilder,
28 use serde::Deserialize;
29 use std::{collections::HashMap, str::FromStr};
30 use strum::ParseError;
32 #[derive(Deserialize)]
44 pub fn config(cfg: &mut web::ServiceConfig) {
46 .route("/feeds/{type}/{name}.xml", web::get().to(get_feed))
47 .route("/feeds/all.xml", web::get().to(get_all_feed))
48 .route("/feeds/local.xml", web::get().to(get_local_feed));
52 static ref RSS_NAMESPACE: HashMap<String, String> = {
53 let mut h = HashMap::new();
56 rss::extension::dublincore::NAMESPACE.to_string(),
62 async fn get_all_feed(
63 info: web::Query<Params>,
64 context: web::Data<LemmyContext>,
65 ) -> Result<HttpResponse, Error> {
66 let sort_type = get_sort_type(info).map_err(ErrorBadRequest)?;
67 Ok(get_feed_data(&context, ListingType::All, sort_type).await?)
70 async fn get_local_feed(
71 info: web::Query<Params>,
72 context: web::Data<LemmyContext>,
73 ) -> Result<HttpResponse, Error> {
74 let sort_type = get_sort_type(info).map_err(ErrorBadRequest)?;
75 Ok(get_feed_data(&context, ListingType::Local, sort_type).await?)
78 async fn get_feed_data(
79 context: &LemmyContext,
80 listing_type: ListingType,
82 ) -> Result<HttpResponse, LemmyError> {
83 let site_view = blocking(context.pool(), move |conn| SiteView::read(&conn)).await??;
85 let listing_type_ = listing_type.clone();
86 let posts = blocking(context.pool(), move |conn| {
87 PostQueryBuilder::create(&conn)
88 .listing_type(&listing_type_)
94 let items = create_post_items(posts)?;
96 let mut channel_builder = ChannelBuilder::default();
98 .namespaces(RSS_NAMESPACE.to_owned())
102 listing_type.to_string()
104 .link(Settings::get().get_protocol_and_hostname())
107 if let Some(site_desc) = site_view.site.description {
108 channel_builder.description(&site_desc);
111 let rss = channel_builder.build().map_err(|e| anyhow!(e))?.to_string();
114 .content_type("application/rss+xml")
120 web::Path((req_type, param)): web::Path<(String, String)>,
121 info: web::Query<Params>,
122 context: web::Data<LemmyContext>,
123 ) -> Result<HttpResponse, Error> {
124 let sort_type = get_sort_type(info).map_err(ErrorBadRequest)?;
126 let request_type = match req_type.as_str() {
127 "u" => RequestType::User,
128 "c" => RequestType::Community,
129 "front" => RequestType::Front,
130 "inbox" => RequestType::Inbox,
131 _ => return Err(ErrorBadRequest(LemmyError::from(anyhow!("wrong_type")))),
134 let builder = blocking(context.pool(), move |conn| match request_type {
135 RequestType::User => get_feed_user(conn, &sort_type, param),
136 RequestType::Community => get_feed_community(conn, &sort_type, param),
137 RequestType::Front => get_feed_front(conn, &sort_type, param),
138 RequestType::Inbox => get_feed_inbox(conn, param),
141 .map_err(ErrorBadRequest)?;
143 let rss = builder.build().map_err(ErrorBadRequest)?.to_string();
147 .content_type("application/rss+xml")
152 fn get_sort_type(info: web::Query<Params>) -> Result<SortType, ParseError> {
153 let sort_query = info
156 .unwrap_or_else(|| SortType::Hot.to_string());
157 SortType::from_str(&sort_query)
162 sort_type: &SortType,
164 ) -> Result<ChannelBuilder, LemmyError> {
165 let site_view = SiteView::read(&conn)?;
166 let user = User_::find_by_username(&conn, &user_name)?;
167 let user_url = user.get_profile_url(&Settings::get().hostname);
169 let posts = PostQueryBuilder::create(&conn)
170 .listing_type(&ListingType::All)
175 let items = create_post_items(posts)?;
177 let mut channel_builder = ChannelBuilder::default();
179 .namespaces(RSS_NAMESPACE.to_owned())
180 .title(&format!("{} - {}", site_view.site.name, user.name))
187 fn get_feed_community(
189 sort_type: &SortType,
190 community_name: String,
191 ) -> Result<ChannelBuilder, LemmyError> {
192 let site_view = SiteView::read(&conn)?;
193 let community = Community::read_from_name(&conn, &community_name)?;
195 let posts = PostQueryBuilder::create(&conn)
196 .listing_type(&ListingType::All)
198 .community_id(community.id)
201 let items = create_post_items(posts)?;
203 let mut channel_builder = ChannelBuilder::default();
205 .namespaces(RSS_NAMESPACE.to_owned())
206 .title(&format!("{} - {}", site_view.site.name, community.name))
207 .link(community.actor_id.to_string())
210 if let Some(community_desc) = community.description {
211 channel_builder.description(&community_desc);
219 sort_type: &SortType,
221 ) -> Result<ChannelBuilder, LemmyError> {
222 let site_view = SiteView::read(&conn)?;
223 let user_id = Claims::decode(&jwt)?.claims.id;
225 let posts = PostQueryBuilder::create(&conn)
226 .listing_type(&ListingType::Subscribed)
231 let items = create_post_items(posts)?;
233 let mut channel_builder = ChannelBuilder::default();
235 .namespaces(RSS_NAMESPACE.to_owned())
236 .title(&format!("{} - Subscribed", site_view.site.name))
237 .link(Settings::get().get_protocol_and_hostname())
240 if let Some(site_desc) = site_view.site.description {
241 channel_builder.description(&site_desc);
247 fn get_feed_inbox(conn: &PgConnection, jwt: String) -> Result<ChannelBuilder, LemmyError> {
248 let site_view = SiteView::read(&conn)?;
249 let user_id = Claims::decode(&jwt)?.claims.id;
251 let sort = SortType::New;
253 let replies = CommentQueryBuilder::create(&conn)
254 .recipient_id(user_id)
259 let mentions = UserMentionQueryBuilder::create(&conn)
260 .recipient_id(user_id)
265 let items = create_reply_and_mention_items(replies, mentions)?;
267 let mut channel_builder = ChannelBuilder::default();
269 .namespaces(RSS_NAMESPACE.to_owned())
270 .title(&format!("{} - Inbox", site_view.site.name))
273 Settings::get().get_protocol_and_hostname()
277 if let Some(site_desc) = site_view.site.description {
278 channel_builder.description(&site_desc);
284 fn create_reply_and_mention_items(
285 replies: Vec<CommentView>,
286 mentions: Vec<UserMentionView>,
287 ) -> Result<Vec<Item>, LemmyError> {
288 let mut reply_items: Vec<Item> = replies
291 let reply_url = format!(
292 "{}/post/{}/comment/{}",
293 Settings::get().get_protocol_and_hostname(),
299 &r.comment.published,
304 .collect::<Result<Vec<Item>, LemmyError>>()?;
306 let mut mention_items: Vec<Item> = mentions
309 let mention_url = format!(
310 "{}/post/{}/comment/{}",
311 Settings::get().get_protocol_and_hostname(),
317 &m.comment.published,
322 .collect::<Result<Vec<Item>, LemmyError>>()?;
324 reply_items.append(&mut mention_items);
330 published: &NaiveDateTime,
333 ) -> Result<Item, LemmyError> {
334 let mut i = ItemBuilder::default();
335 i.title(format!("Reply from {}", creator_name));
336 let author_url = format!(
338 Settings::get().get_protocol_and_hostname(),
342 "/u/{} <a href=\"{}\">(link)</a>",
343 creator_name, author_url
345 let dt = DateTime::<Utc>::from_utc(*published, Utc);
346 i.pub_date(dt.to_rfc2822());
347 i.comments(url.to_owned());
348 let guid = GuidBuilder::default()
352 .map_err(|e| anyhow!(e))?;
354 i.link(url.to_owned());
356 let html = markdown_to_html(&content.to_string());
358 Ok(i.build().map_err(|e| anyhow!(e))?)
361 fn create_post_items(posts: Vec<PostView>) -> Result<Vec<Item>, LemmyError> {
362 let mut items: Vec<Item> = Vec::new();
365 let mut i = ItemBuilder::default();
366 let mut dc_extension = DublinCoreExtensionBuilder::default();
368 i.title(p.post.name);
370 dc_extension.creators(vec![p.creator.actor_id.to_string()]);
372 let dt = DateTime::<Utc>::from_utc(p.post.published, Utc);
373 i.pub_date(dt.to_rfc2822());
375 let post_url = format!(
377 Settings::get().get_protocol_and_hostname(),
380 i.comments(post_url.to_owned());
381 let guid = GuidBuilder::default()
385 .map_err(|e| anyhow!(e))?;
388 let community_url = format!(
390 Settings::get().get_protocol_and_hostname(),
394 // TODO: for category we should just put the name of the category, but then we would have
395 // to read each community from the db
397 if let Some(url) = p.post.url {
402 let mut description = format!("submitted by <a href=\"{}\">{}</a> to <a href=\"{}\">{}</a><br>{} points | <a href=\"{}\">{} comments</a>",
411 if let Some(body) = p.post.body {
412 let html = markdown_to_html(&body);
413 description.push_str(&html);
416 i.description(description);
418 i.dublin_core_ext(dc_extension.build().map_err(|e| anyhow!(e))?);
419 items.push(i.build().map_err(|e| anyhow!(e))?);