feat: add RSS and Atom feeds with caching and nice links

This commit is contained in:
David Bailey 2023-12-25 20:13:00 +01:00
parent c6297fd81b
commit 596cc0e1a3
7 changed files with 120 additions and 1 deletions

View file

@ -57,6 +57,11 @@ class PostHandler extends MySQLAdapter {
parent::make_post_directory($directory);
}
function update_or_create_post(...$args) {
$this->_exec("TRUNCATE feed_cache");
parent::update_or_create_post(...$args);
}
function save_file($post_path, $file_path) {
$this->bump_post($post_path);
move_uploaded_file($file_path, $this->data_directory . $post_path);
@ -101,6 +106,86 @@ class PostHandler extends MySQLAdapter {
$this->save_file($post_path, $file_path);
}
}
function try_get_cached_feed($path, $export_opt) {
$post_cache = $this->_exec("SELECT feed_content, feed_created_on
FROM feed_cache
WHERE search_path=? AND export_type=?", "ss", $path, $export_opt)->fetch_assoc();
if(!isset($post_cache)) {
return null;
}
return ['feed' => $post_cache['feed_content'], 'feed_ts' => $post_cache['feed_created_on']];
}
function construct_feed($path) {
$path = $this->_sanitize_path($path);
$feed = @new Feed;
$feed->setTitle("DergFeed");
$feed->setLink("https://lucidragons.de" . $path);
$feed->setFeedLink("https://lucidragons.de/feeds/atom" . $path, "atom");
$feed->setDateModified(time());
$feed->setDescription("DergenFeed for all your " . $path . " needs <3");
$feed_posts = $this->_exec("SELECT
post_path,
post_create_time, post_update_time,
post_content,
post_metadata
FROM posts
WHERE (post_path = ?) OR (post_path LIKE ?)
ORDER BY post_create_time DESC LIMIT 200",
"ss", $path, $path . '/%');
while($row = $feed_posts->fetch_array(MYSQLI_ASSOC)) {
$row = $this->_normalize_post_data($row);
$pmeta = $row['post_metadata'];
if($pmeta['type'] == 'directory') {
continue;
}
$entry = $feed->createEntry();
$entry->setTitle($row['post_path'] . '> ' . $pmeta['title']);
$entry->setLink('https://lucidragons.de' . $row['post_path']);
$entry->setDateModified(strtotime($row['post_update_time']));
$entry->setDateCreated(strtotime($row['post_create_time']));
$entry->setDescription($pmeta['brief'] ?? $pmeta['title']);
$feed->addEntry($entry);
}
return $feed;
}
function get_laminas_feed($path, $export_opt) {
$path = $this->_sanitize_path($path);
$feed_cache = $this->try_get_cached_feed($path, $export_opt);
if(isset($feed_cache)) {
return $feed_cache;
}
$feed = $this->construct_feed($path);
$this->_exec("INSERT INTO feed_cache
(search_path, export_type, feed_content)
VALUES
(?, 'atom', ?),
(?, 'rss', ?)",
"ssss", $path, $feed->export('atom'),
$path, $feed->export('rss'));
return $this->try_get_cached_feed($path, $export_opt);
}
}
?>