aboutsummaryrefslogtreecommitdiff
path: root/src/modules/blog/module.rs
blob: af204883efb950abdf3f652164aeabdefe89b8bd (plain) (blame)
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
use {
  super::{
    config::{BlogCategory, BlogPost},
    post::Post,
  },
  crate::{
    notion,
    response::success,
    route::track_mount,
    url::ROOT_GEMINI_URL,
    xml::{Item as XmlItem, Writer as XmlWriter},
  },
  std::sync::{LazyLock, Mutex, RwLock},
};

pub static POSTS: LazyLock<Mutex<Vec<Post>>> =
  LazyLock::new(|| Mutex::new(Vec::new()));
static BLOG_CATEGORIES: LazyLock<RwLock<Vec<BlogCategory>>> =
  LazyLock::new(|| RwLock::new(Vec::new()));
static BLOG_POSTS: LazyLock<RwLock<Vec<BlogPost>>> =
  LazyLock::new(|| RwLock::new(Vec::new()));

#[allow(clippy::too_many_lines)]
pub fn module(router: &mut windmark::router::Router) {
  std::thread::spawn(fetch_from_notion)
    .join()
    .expect("initial Notion fetch failed");
  track_mount(router, "/blog", "Fuwn's blogs", |context| {
    let categories = BLOG_CATEGORIES.read().unwrap();
    let listing = categories
      .iter()
      .map(|category| {
        let slug = slugify(&category.title);

        format!(
          "=> /blog/{} {}{}",
          slug,
          category.title,
          category
            .description
            .as_ref()
            .map_or_else(String::new, |description_text| format!(
              " ― {description_text}"
            ))
        )
      })
      .collect::<Vec<_>>()
      .join("\n");

    success(&format!("# Blogs ({})\n\n{}", categories.len(), listing), &context)
  });
  track_mount(
    router,
    "/blog/:blog_name",
    "-A blog on Fuwn's capsule",
    |context| {
      let raw_blog_name =
        context.parameters.get("blog_name").cloned().unwrap_or_default();

      if let Some(blog_slug) = raw_blog_name.strip_suffix(".xml") {
        return build_rss_feed(blog_slug);
      }

      let blog_slug = raw_blog_name;
      let categories = BLOG_CATEGORIES.read().unwrap();
      let posts = BLOG_POSTS.read().unwrap();
      let matched_category = categories
        .iter()
        .find(|category| slugify(&category.title) == blog_slug);
      let Some(category) = matched_category else {
        return windmark::response::Response::not_found(
          "This blog could not be found.",
        );
      };
      let category_posts = visible_posts_for_blog(&posts, &category.notion_id);
      let post_listing = category_posts
        .iter()
        .map(|post| {
          let post_slug = slugify(&post.title);

          format!(
            "=> /blog/{}/{} {}{}",
            blog_slug,
            post_slug,
            post.title,
            post
              .description
              .as_ref()
              .filter(|description_text| !description_text.is_empty())
              .map_or_else(String::new, |description_text| format!(
                " ― {description_text}"
              ))
          )
        })
        .collect::<Vec<_>>()
        .join("\n");

      success(
        &format!(
          "# {} ({})\n\n{}\n\n{}\n\n## Really Simple Syndication\n\nAccess \
           {0}'s RSS feed\n\n=> /blog/{}.xml here!",
          category.title,
          category_posts.len(),
          category.description.as_deref().unwrap_or(""),
          post_listing,
          blog_slug,
        ),
        &context,
      )
    },
  );
  track_mount(
    router,
    "/blog/:blog_name/:post_title",
    "-An entry to one of Fuwn's blogs",
    |context| {
      let blog_slug =
        context.parameters.get("blog_name").cloned().unwrap_or_default();
      let post_slug =
        context.parameters.get("post_title").cloned().unwrap_or_default();
      let categories = BLOG_CATEGORIES.read().unwrap();
      let posts = BLOG_POSTS.read().unwrap();
      let matched_category = categories
        .iter()
        .find(|category| slugify(&category.title) == blog_slug);
      let Some(category) = matched_category else {
        return windmark::response::Response::not_found(
          "This blog could not be found.",
        );
      };
      let matched_post =
        find_visible_post_by_slug(&posts, &category.notion_id, &post_slug);
      let Some(post) = matched_post else {
        return windmark::response::Response::not_found(
          "This post could not be found.",
        );
      };
      let header = construct_header(post);

      success(&format!("{}\n{}", header, post.content), &context)
    },
  );
}

fn construct_header(post: &BlogPost) -> String {
  let title_line = format!("# {}", post.title);
  let has_metadata = post.author.is_some()
    || post.created.is_some()
    || post.last_modified.is_some()
    || post.description.is_some();

  if !has_metadata {
    return title_line;
  }

  let author_fragment =
    post.author.as_ref().map_or_else(String::new, |author_name| {
      format!("Written by {author_name}")
    });
  let created_fragment = post
    .created
    .as_ref()
    .map_or_else(String::new, |created_date| format!(" on {created_date}"));
  let modified_fragment =
    post.last_modified.as_ref().map_or_else(String::new, |modified_date| {
      format!(" (last modified on {modified_date})\n")
    });
  let description_fragment = post
    .description
    .as_ref()
    .filter(|description_text| !description_text.is_empty())
    .map_or_else(String::new, |description_text| {
      format!("\n{description_text}\n")
    });

  format!(
    "{title_line}\n\n{author_fragment}{created_fragment}{modified_fragment}{description_fragment}"
  )
}

fn slugify(text: &str) -> String { text.replace(' ', "_").to_lowercase() }

fn visible_posts_for_blog<'a>(
  posts: &'a [BlogPost],
  blog_identifier: &str,
) -> Vec<&'a BlogPost> {
  posts
    .iter()
    .filter(|post| post.blog_id == blog_identifier && !post.hidden)
    .collect()
}

fn find_visible_post_by_slug<'a>(
  posts: &'a [BlogPost],
  blog_identifier: &str,
  post_slug: &str,
) -> Option<&'a BlogPost> {
  visible_posts_for_blog(posts, blog_identifier)
    .into_iter()
    .find(|post| slugify(&post.title) == post_slug)
}

fn build_rss_feed(blog_slug: &str) -> windmark::response::Response {
  let categories = BLOG_CATEGORIES.read().unwrap();
  let posts = BLOG_POSTS.read().unwrap();
  let matched_category =
    categories.iter().find(|category| slugify(&category.title) == blog_slug);
  let Some(category) = matched_category else {
    return windmark::response::Response::not_found(
      "This blog could not be found.",
    );
  };
  let mut xml = XmlWriter::builder();

  xml.add_field("title", &category.title);
  xml.add_field("link", &format!("{ROOT_GEMINI_URL}/blog/{blog_slug}"));

  if let Some(ref description_text) = category.description {
    xml.add_field("description", description_text);
  }

  xml.add_field("generator", "locus");
  xml.add_field("lastBuildDate", &chrono::Local::now().to_rfc2822());
  xml.add_link(&format!("{ROOT_GEMINI_URL}/blog/{blog_slug}.xml"));

  for post in visible_posts_for_blog(&posts, &category.notion_id) {
    let post_slug = slugify(&post.title);

    xml.add_item(&{
      let mut builder = XmlItem::builder();

      builder.add_field(
        "link",
        &format!("{ROOT_GEMINI_URL}/blog/{blog_slug}/{post_slug}"),
      );
      builder.add_field("description", &post.content);
      builder.add_field(
        "guid",
        &format!("{ROOT_GEMINI_URL}/blog/{blog_slug}/{post_slug}"),
      );
      builder.add_field("title", &post.title);

      if let Some(ref created_date) = post.created {
        builder.add_field("pubDate", created_date);
      }

      builder
    });
  }

  windmark::response::Response::success(xml.to_string())
    .with_mime("text/rss+xml")
    .clone()
}

fn fetch_from_notion() {
  let api_key = std::env::var("NOTION_API_KEY")
    .expect("NOTION_API_KEY environment variable is required");
  let blogs_database_identifier = std::env::var("NOTION_BLOGS_DATABASE_ID")
    .expect("NOTION_BLOGS_DATABASE_ID environment variable is required");
  let posts_database_identifier = std::env::var("NOTION_POSTS_DATABASE_ID")
    .expect("NOTION_POSTS_DATABASE_ID environment variable is required");
  let http_client = reqwest::blocking::Client::new();
  let blog_pages =
    notion::query_database(&http_client, &api_key, &blogs_database_identifier)
      .expect("failed to query Notion blogs database");
  let mut categories: Vec<BlogCategory> = blog_pages
    .iter()
    .map(|page| {
      let description_text =
        notion::extract_rich_text(&page.properties, "Description");

      BlogCategory {
        title:       notion::extract_title(&page.properties, "Title"),
        description: if description_text.is_empty() {
          None
        } else {
          Some(description_text)
        },
        priority:    notion::extract_number(&page.properties, "Priority")
          .unwrap_or(0),
        notion_id:   page.id.clone(),
      }
    })
    .collect();

  categories.sort_by(|first, second| second.priority.cmp(&first.priority));

  let post_pages =
    notion::query_database(&http_client, &api_key, &posts_database_identifier)
      .expect("failed to query Notion posts database");
  let fetched_posts: Vec<BlogPost> = post_pages
    .iter()
    .map(|page| {
      let page_content =
        notion::fetch_page_content(&http_client, &api_key, &page.id)
          .unwrap_or_default();
      let blog_relation_ids =
        notion::extract_relation_ids(&page.properties, "Blog");
      let blog_identifier =
        blog_relation_ids.first().cloned().unwrap_or_default();
      let created_raw = notion::extract_date(&page.properties, "Created");
      let last_modified_raw =
        notion::extract_date(&page.properties, "Last Modified");
      let description_text =
        notion::extract_rich_text(&page.properties, "Description");
      let author_text = notion::extract_rich_text(&page.properties, "Author");

      BlogPost {
        title:         notion::extract_title(&page.properties, "Title"),
        description:   if description_text.is_empty() {
          None
        } else {
          Some(description_text)
        },
        author:        if author_text.is_empty() {
          None
        } else {
          Some(author_text)
        },
        created:       if created_raw.is_empty() {
          None
        } else {
          Some(notion::format_notion_date(&created_raw))
        },
        last_modified: if last_modified_raw.is_empty() {
          None
        } else {
          Some(notion::format_notion_date(&last_modified_raw))
        },
        content:       page_content,
        blog_id:       blog_identifier,
        hidden:        notion::extract_checkbox(&page.properties, "Hidden"),
      }
    })
    .collect();

  {
    let mut global_posts = POSTS.lock().unwrap();

    global_posts.clear();

    for post in fetched_posts.iter().filter(|post| !post.hidden) {
      let blog_title = categories
        .iter()
        .find(|category| category.notion_id == post.blog_id)
        .map(|category| category.title.clone())
        .unwrap_or_default();

      global_posts.push(Post::new(
        format!("{}, {}", blog_title, post.title),
        format!("/blog/{}/{}", slugify(&blog_title), slugify(&post.title)),
        post.created.clone().unwrap_or_default(),
      ));
    }
  }

  *BLOG_CATEGORIES.write().unwrap() = categories;
  *BLOG_POSTS.write().unwrap() = fetched_posts;

  info!("fetched blog data from Notion");
}

pub fn refresh_loop() {
  let refresh_interval_seconds = std::env::var("NOTION_REFRESH_INTERVAL")
    .ok()
    .and_then(|value| value.parse::<u64>().ok())
    .unwrap_or(300);

  info!("spawned Notion blog refresh loop ({refresh_interval_seconds}s interval)");

  loop {
    std::thread::sleep(std::time::Duration::from_secs(refresh_interval_seconds));

    match std::panic::catch_unwind(fetch_from_notion) {
      Ok(()) => info!("refreshed blog data from Notion"),
      Err(_) => warn!("failed to refresh blog data from Notion"),
    }
  }
}

#[cfg(test)]
mod tests {
  use super::{
    build_rss_feed, find_visible_post_by_slug, slugify, visible_posts_for_blog,
    BLOG_CATEGORIES, BLOG_POSTS,
  };
  use crate::modules::blog::config::{BlogCategory, BlogPost};

  #[test]
  fn hidden_posts_are_excluded_from_rss_feed() {
    let original_categories = BLOG_CATEGORIES.read().unwrap().clone();
    let original_posts = BLOG_POSTS.read().unwrap().clone();
    let category = BlogCategory {
      title:       "Test Blog".to_string(),
      description: None,
      priority:    1,
      notion_id:   "blog-id".to_string(),
    };
    let visible_post = BlogPost {
      title:         "Visible".to_string(),
      description:   None,
      author:        None,
      created:       None,
      last_modified: None,
      content:       "visible content".to_string(),
      blog_id:       "blog-id".to_string(),
      hidden:        false,
    };
    let hidden_post = BlogPost {
      title:         "Hidden".to_string(),
      description:   None,
      author:        None,
      created:       None,
      last_modified: None,
      content:       "hidden content".to_string(),
      blog_id:       "blog-id".to_string(),
      hidden:        true,
    };

    *BLOG_CATEGORIES.write().unwrap() = vec![category];
    *BLOG_POSTS.write().unwrap() = vec![visible_post, hidden_post];

    let feed = build_rss_feed(&slugify("Test Blog"));
    let feed_xml = feed.content;

    assert!(feed_xml.contains("<title>Visible</title>"));
    assert!(!feed_xml.contains("<title>Hidden</title>"));

    *BLOG_CATEGORIES.write().unwrap() = original_categories;
    *BLOG_POSTS.write().unwrap() = original_posts;
  }

  #[test]
  fn visible_posts_for_blog_excludes_hidden_posts() {
    let visible_post = BlogPost {
      title:         "Visible".to_string(),
      description:   None,
      author:        None,
      created:       None,
      last_modified: None,
      content:       "visible content".to_string(),
      blog_id:       "blog-id".to_string(),
      hidden:        false,
    };
    let hidden_post = BlogPost {
      title:         "Hidden".to_string(),
      description:   None,
      author:        None,
      created:       None,
      last_modified: None,
      content:       "hidden content".to_string(),
      blog_id:       "blog-id".to_string(),
      hidden:        true,
    };

    let posts = vec![visible_post, hidden_post];
    let visible_titles = visible_posts_for_blog(&posts, "blog-id")
      .into_iter()
      .map(|post| post.title.clone())
      .collect::<Vec<_>>();

    assert_eq!(visible_titles, vec!["Visible".to_string()]);
  }

  #[test]
  fn find_visible_post_by_slug_skips_hidden_posts() {
    let visible_post = BlogPost {
      title:         "Visible Post".to_string(),
      description:   None,
      author:        None,
      created:       None,
      last_modified: None,
      content:       "visible content".to_string(),
      blog_id:       "blog-id".to_string(),
      hidden:        false,
    };
    let hidden_post = BlogPost {
      title:         "Hidden Post".to_string(),
      description:   None,
      author:        None,
      created:       None,
      last_modified: None,
      content:       "hidden content".to_string(),
      blog_id:       "blog-id".to_string(),
      hidden:        true,
    };
    let posts = vec![visible_post, hidden_post];

    assert!(
      find_visible_post_by_slug(&posts, "blog-id", "visible_post").is_some()
    );
    assert!(
      find_visible_post_by_slug(&posts, "blog-id", "hidden_post").is_none()
    );
  }
}