-
-
Notifications
You must be signed in to change notification settings - Fork 900
/
Copy pathfeeds.rs
561 lines (500 loc) Β· 14.7 KB
/
feeds.rs
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
use actix_web::{error::ErrorBadRequest, web, Error, HttpRequest, HttpResponse, Result};
use anyhow::anyhow;
use chrono::{DateTime, Utc};
use lemmy_api_common::{
context::LemmyContext,
utils::{check_private_instance, local_user_view_from_jwt},
};
use lemmy_db_schema::{
source::{community::Community, person::Person},
traits::ApubActor,
CommunityVisibility,
ListingType,
PostSortType,
};
use lemmy_db_views::{
combined::inbox_combined_view::InboxCombinedQuery,
post::post_view::PostQuery,
structs::{InboxCombinedView, PostView, SiteView},
};
use lemmy_utils::{
cache_header::cache_1hour,
error::{LemmyError, LemmyErrorType, LemmyResult},
utils::markdown::markdown_to_html,
};
use rss::{
extension::{dublincore::DublinCoreExtension, ExtensionBuilder, ExtensionMap},
Category,
Channel,
EnclosureBuilder,
Guid,
Item,
};
use serde::Deserialize;
use std::{collections::BTreeMap, str::FromStr, sync::LazyLock};
const RSS_FETCH_LIMIT: i64 = 20;
#[derive(Deserialize)]
struct Params {
sort: Option<String>,
limit: Option<i64>,
page: Option<i64>,
}
impl Params {
fn sort_type(&self) -> Result<PostSortType, Error> {
let sort_query = self
.sort
.clone()
.unwrap_or_else(|| PostSortType::Hot.to_string());
PostSortType::from_str(&sort_query).map_err(ErrorBadRequest)
}
fn get_limit(&self) -> i64 {
self.limit.unwrap_or(RSS_FETCH_LIMIT)
}
fn get_page(&self) -> i64 {
self.page.unwrap_or(1)
}
}
enum RequestType {
Community,
User,
Front,
Inbox,
}
pub fn config(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/feeds")
.route("/{type}/{name}.xml", web::get().to(get_feed))
.route("/all.xml", web::get().to(get_all_feed).wrap(cache_1hour()))
.route(
"/local.xml",
web::get().to(get_local_feed).wrap(cache_1hour()),
),
);
}
static RSS_NAMESPACE: LazyLock<BTreeMap<String, String>> = LazyLock::new(|| {
let mut h = BTreeMap::new();
h.insert(
"dc".to_string(),
rss::extension::dublincore::NAMESPACE.to_string(),
);
h.insert(
"media".to_string(),
"http://search.yahoo.com/mrss/".to_string(),
);
h
});
#[tracing::instrument(skip_all)]
async fn get_all_feed(
info: web::Query<Params>,
context: web::Data<LemmyContext>,
) -> Result<HttpResponse, Error> {
Ok(
get_feed_data(
&context,
ListingType::All,
info.sort_type()?,
info.get_limit(),
info.get_page(),
)
.await?,
)
}
#[tracing::instrument(skip_all)]
async fn get_local_feed(
info: web::Query<Params>,
context: web::Data<LemmyContext>,
) -> Result<HttpResponse, Error> {
Ok(
get_feed_data(
&context,
ListingType::Local,
info.sort_type()?,
info.get_limit(),
info.get_page(),
)
.await?,
)
}
#[tracing::instrument(skip_all)]
async fn get_feed_data(
context: &LemmyContext,
listing_type: ListingType,
sort_type: PostSortType,
limit: i64,
page: i64,
) -> LemmyResult<HttpResponse> {
let site_view = SiteView::read_local(&mut context.pool()).await?;
check_private_instance(&None, &site_view.local_site)?;
let posts = PostQuery {
listing_type: (Some(listing_type)),
sort: (Some(sort_type)),
limit: (Some(limit)),
page: (Some(page)),
..Default::default()
}
.list(&site_view.site, &mut context.pool())
.await?;
let items = create_post_items(posts, &context.settings().get_protocol_and_hostname())?;
let mut channel = Channel {
namespaces: RSS_NAMESPACE.clone(),
title: format!("{} - {}", site_view.site.name, listing_type),
link: context.settings().get_protocol_and_hostname(),
items,
..Default::default()
};
if let Some(site_desc) = site_view.site.description {
channel.set_description(&site_desc);
}
let rss = channel.to_string();
Ok(
HttpResponse::Ok()
.content_type("application/rss+xml")
.body(rss),
)
}
#[tracing::instrument(skip_all)]
async fn get_feed(
req: HttpRequest,
info: web::Query<Params>,
context: web::Data<LemmyContext>,
) -> Result<HttpResponse, Error> {
let req_type: String = req.match_info().get("type").unwrap_or("none").parse()?;
let param: String = req.match_info().get("name").unwrap_or("none").parse()?;
let request_type = match req_type.as_str() {
"u" => RequestType::User,
"c" => RequestType::Community,
"front" => RequestType::Front,
"inbox" => RequestType::Inbox,
_ => return Err(ErrorBadRequest(LemmyError::from(anyhow!("wrong_type")))),
};
let builder = match request_type {
RequestType::User => {
get_feed_user(
&context,
&info.sort_type()?,
&info.get_limit(),
&info.get_page(),
¶m,
)
.await
}
RequestType::Community => {
get_feed_community(
&context,
&info.sort_type()?,
&info.get_limit(),
&info.get_page(),
¶m,
)
.await
}
RequestType::Front => {
get_feed_front(
&context,
&info.sort_type()?,
&info.get_limit(),
&info.get_page(),
¶m,
)
.await
}
RequestType::Inbox => get_feed_inbox(&context, ¶m).await,
}
.map_err(ErrorBadRequest)?;
let rss = builder.to_string();
Ok(
HttpResponse::Ok()
.content_type("application/rss+xml")
.body(rss),
)
}
#[tracing::instrument(skip_all)]
async fn get_feed_user(
context: &LemmyContext,
sort_type: &PostSortType,
limit: &i64,
page: &i64,
user_name: &str,
) -> LemmyResult<Channel> {
let site_view = SiteView::read_local(&mut context.pool()).await?;
let person = Person::read_from_name(&mut context.pool(), user_name, false)
.await?
.ok_or(LemmyErrorType::NotFound)?;
check_private_instance(&None, &site_view.local_site)?;
let posts = PostQuery {
listing_type: (Some(ListingType::All)),
sort: (Some(*sort_type)),
creator_id: (Some(person.id)),
limit: (Some(*limit)),
page: (Some(*page)),
..Default::default()
}
.list(&site_view.site, &mut context.pool())
.await?;
let items = create_post_items(posts, &context.settings().get_protocol_and_hostname())?;
let channel = Channel {
namespaces: RSS_NAMESPACE.clone(),
title: format!("{} - {}", site_view.site.name, person.name),
link: person.actor_id.to_string(),
items,
..Default::default()
};
Ok(channel)
}
#[tracing::instrument(skip_all)]
async fn get_feed_community(
context: &LemmyContext,
sort_type: &PostSortType,
limit: &i64,
page: &i64,
community_name: &str,
) -> LemmyResult<Channel> {
let site_view = SiteView::read_local(&mut context.pool()).await?;
let community = Community::read_from_name(&mut context.pool(), community_name, false)
.await?
.ok_or(LemmyErrorType::NotFound)?;
if community.visibility != CommunityVisibility::Public {
return Err(LemmyErrorType::NotFound.into());
}
check_private_instance(&None, &site_view.local_site)?;
let posts = PostQuery {
sort: (Some(*sort_type)),
community_id: (Some(community.id)),
limit: (Some(*limit)),
page: (Some(*page)),
..Default::default()
}
.list(&site_view.site, &mut context.pool())
.await?;
let items = create_post_items(posts, &context.settings().get_protocol_and_hostname())?;
let mut channel = Channel {
namespaces: RSS_NAMESPACE.clone(),
title: format!("{} - {}", site_view.site.name, community.name),
link: community.actor_id.to_string(),
items,
..Default::default()
};
if let Some(community_desc) = community.description {
channel.set_description(markdown_to_html(&community_desc));
}
Ok(channel)
}
#[tracing::instrument(skip_all)]
async fn get_feed_front(
context: &LemmyContext,
sort_type: &PostSortType,
limit: &i64,
page: &i64,
jwt: &str,
) -> LemmyResult<Channel> {
let site_view = SiteView::read_local(&mut context.pool()).await?;
let local_user = local_user_view_from_jwt(jwt, context).await?;
check_private_instance(&Some(local_user.clone()), &site_view.local_site)?;
let posts = PostQuery {
listing_type: (Some(ListingType::Subscribed)),
local_user: (Some(&local_user.local_user)),
sort: (Some(*sort_type)),
limit: (Some(*limit)),
page: (Some(*page)),
..Default::default()
}
.list(&site_view.site, &mut context.pool())
.await?;
let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let items = create_post_items(posts, &protocol_and_hostname)?;
let mut channel = Channel {
namespaces: RSS_NAMESPACE.clone(),
title: format!("{} - Subscribed", site_view.site.name),
link: protocol_and_hostname,
items,
..Default::default()
};
if let Some(site_desc) = site_view.site.description {
channel.set_description(markdown_to_html(&site_desc));
}
Ok(channel)
}
#[tracing::instrument(skip_all)]
async fn get_feed_inbox(context: &LemmyContext, jwt: &str) -> LemmyResult<Channel> {
let site_view = SiteView::read_local(&mut context.pool()).await?;
let local_user = local_user_view_from_jwt(jwt, context).await?;
let my_person_id = local_user.person.id;
let show_bot_accounts = Some(local_user.local_user.show_bot_accounts);
check_private_instance(&Some(local_user.clone()), &site_view.local_site)?;
let inbox = InboxCombinedQuery {
show_bot_accounts,
..Default::default()
}
.list(&mut context.pool(), my_person_id)
.await?;
let protocol_and_hostname = context.settings().get_protocol_and_hostname();
let items = create_reply_and_mention_items(inbox, &protocol_and_hostname)?;
let mut channel = Channel {
namespaces: RSS_NAMESPACE.clone(),
title: format!("{} - Inbox", site_view.site.name),
link: format!("{protocol_and_hostname}/inbox"),
items,
..Default::default()
};
if let Some(site_desc) = site_view.site.description {
channel.set_description(&site_desc);
}
Ok(channel)
}
#[tracing::instrument(skip_all)]
fn create_reply_and_mention_items(
inbox: Vec<InboxCombinedView>,
protocol_and_hostname: &str,
) -> LemmyResult<Vec<Item>> {
let reply_items: Vec<Item> = inbox
.iter()
.map(|r| match r {
InboxCombinedView::CommentReply(v) => {
let reply_url = format!("{}/comment/{}", protocol_and_hostname, v.comment.id);
build_item(
&v.creator.name,
&v.comment.published,
&reply_url,
&v.comment.content,
protocol_and_hostname,
)
}
InboxCombinedView::CommentMention(v) => {
let mention_url = format!("{}/comment/{}", protocol_and_hostname, v.comment.id);
build_item(
&v.creator.name,
&v.comment.published,
&mention_url,
&v.comment.content,
protocol_and_hostname,
)
}
InboxCombinedView::PostMention(v) => {
let mention_url = format!("{}/post/{}", protocol_and_hostname, v.post.id);
build_item(
&v.creator.name,
&v.post.published,
&mention_url,
&v.post.body.clone().unwrap_or_default(),
protocol_and_hostname,
)
}
InboxCombinedView::PrivateMessage(v) => {
let inbox_url = format!("{}/inbox", protocol_and_hostname);
build_item(
&v.creator.name,
&v.private_message.published,
&inbox_url,
&v.private_message.content,
protocol_and_hostname,
)
}
})
.collect::<LemmyResult<Vec<Item>>>()?;
Ok(reply_items)
}
#[tracing::instrument(skip_all)]
fn build_item(
creator_name: &str,
published: &DateTime<Utc>,
url: &str,
content: &str,
protocol_and_hostname: &str,
) -> LemmyResult<Item> {
// TODO add images
let guid = Some(Guid {
permalink: true,
value: url.to_owned(),
});
let description = Some(markdown_to_html(content));
Ok(Item {
title: Some(format!("Reply from {creator_name}")),
author: Some(format!(
"/u/{creator_name} <a href=\"{}\">(link)</a>",
format_args!("{protocol_and_hostname}/u/{creator_name}")
)),
pub_date: Some(published.to_rfc2822()),
comments: Some(url.to_owned()),
link: Some(url.to_owned()),
guid,
description,
..Default::default()
})
}
#[tracing::instrument(skip_all)]
fn create_post_items(posts: Vec<PostView>, protocol_and_hostname: &str) -> LemmyResult<Vec<Item>> {
let mut items: Vec<Item> = Vec::new();
for p in posts {
let post_url = format!("{}/post/{}", protocol_and_hostname, p.post.id);
let community_url = format!("{}/c/{}", protocol_and_hostname, &p.community.name);
let dublin_core_ext = Some(DublinCoreExtension {
creators: vec![p.creator.actor_id.to_string()],
..DublinCoreExtension::default()
});
let guid = Some(Guid {
permalink: true,
value: post_url.clone(),
});
let mut description = format!("submitted by <a href=\"{}\">{}</a> to <a href=\"{}\">{}</a><br>{} points | <a href=\"{}\">{} comments</a>",
p.creator.actor_id,
&p.creator.name,
community_url,
&p.community.name,
p.counts.score,
post_url,
p.counts.comments);
// If its a url post, add it to the description
// and see if we can parse it as a media enclosure.
let enclosure_opt = p.post.url.map(|url| {
let link_html = format!("<br><a href=\"{url}\">{url}</a>");
description.push_str(&link_html);
let mime_type = p
.post
.url_content_type
.unwrap_or_else(|| "application/octet-stream".to_string());
let mut enclosure_bld = EnclosureBuilder::default();
enclosure_bld.url(url.as_str().to_string());
enclosure_bld.mime_type(mime_type);
enclosure_bld.length("0".to_string());
enclosure_bld.build()
});
if let Some(body) = p.post.body {
let html = markdown_to_html(&body);
description.push_str(&html);
}
let mut extensions = ExtensionMap::new();
// If there's a thumbnail URL, add a media:content tag to display it.
// See https://www.rssboard.org/media-rss#media-content for details.
if let Some(url) = p.post.thumbnail_url {
let mut thumbnail_ext = ExtensionBuilder::default();
thumbnail_ext.name("media:content".to_string());
thumbnail_ext.attrs(BTreeMap::from([
("url".to_string(), url.to_string()),
("medium".to_string(), "image".to_string()),
]));
extensions.insert(
"media".to_string(),
BTreeMap::from([("content".to_string(), vec![thumbnail_ext.build()])]),
);
}
let category = Category {
name: p.community.title,
domain: Some(p.community.actor_id.to_string()),
};
let i = Item {
title: Some(p.post.name),
pub_date: Some(p.post.published.to_rfc2822()),
comments: Some(post_url.clone()),
guid,
description: Some(description),
dublin_core_ext,
link: Some(post_url.clone()),
extensions,
enclosure: enclosure_opt,
categories: vec![category],
..Default::default()
};
items.push(i);
}
Ok(items)
}