侧边栏壁纸

Typecho博客调用FreshRss订阅源

  • bosir 原创作品 3个月前
  • 博文 RSS
  • 1.2k阅读30评论
  • 近日,基于RSS订阅的“朋友圈”比较火,赶个时髦,我也参与了一把。具体页面请移步友人页面,Bosir调用了关注博友的十条最新博文。功能实现起来还是比较快的,就是美化后期慢慢来吧。

    FreshRSS安装

    因为我使用的是 阿里云ECS服务器宝塔面板 ,所以就以这个配置环境做例子了。
    宝塔面板的安装环境里面有一个Docker项目模块,支持常用项目快速部署、自定义、容器监控、终端管理。直接点击安装这个模块即可。
    安装完模块后,使用阿里云ECS的远程链接进入后台,输入以下代码:

     docker run -d --restart unless-stopped --log-opt max-size=10m \
      -p 8080:80 \
      -e TZ=Europe/Paris \
      -e 'CRON_MIN=1,31' \
      -v freshrss_data:/var/www/FreshRSS/data \
      -v freshrss_extensions:/var/www/FreshRSS/extensions \
      --name freshrss \
      freshrss/freshrss

    安装结束以后,在阿里云的安全组和宝塔面板的端口同时开放 8080 默认的服务器端口就是这个。

    配置网站

    宝塔面板添加网站,纯静态网站,不需要添加数据库和选择php版本。域名随意,我是使用的二级域名rss.bosir.cn,和常规添加站点一样设置好SSL,可以直接宝塔申请,支持免费续签服务,还是特别方便的。
    这里重点,要添加反向代理。目标就写 http://127.0.0.1:8080 即可,本地服务器。当然如果你不是装在本地的就填写相应的地址加上端口号。
    然后你就访问这个网址,一通设置就可以了。只要记住 设置-账户-API管理 里面的密码就可以。

    博客调用

    网站根目录添加rss.php文件,命名随意,我这里为了方便所以如此命名。然后在里面添加如下代码:

    <?php
    /**
     * 获取最新订阅文章并生成JSON文件
     */
    function getAllSubscribedArticlesAndSaveToJson($user, $password)
    {
        $apiUrl = 'https://你部署FreshRSS的域名/api/greader.php';
        $loginUrl = $apiUrl . '/accounts/ClientLogin?Email=' . urlencode($user) . '&Passwd=' . urlencode($password);
        $loginResponse = curlRequest($loginUrl);
        if (strpos($loginResponse, 'Auth=') !== false) {
            $authToken = substr($loginResponse, strpos($loginResponse, 'Auth=') + 5);
            $articlesUrl = $apiUrl . '/reader/api/0/stream/contents/reading-list?&n=1000';
            $articlesResponse = curlRequest($articlesUrl, $authToken);
            $articles = json_decode($articlesResponse, true);
            if (isset($articles['items'])) {
                usort($articles['items'], function ($a, $b) {
                    return $b['published'] - $a['published'];
                });
                $subscriptionsUrl = $apiUrl . '/reader/api/0/subscription/list?output=json';
                $subscriptionsResponse = curlRequest($subscriptionsUrl, $authToken);
                $subscriptions = json_decode($subscriptionsResponse, true);
                if (isset($subscriptions['subscriptions'])) {
                    $subscriptionMap = array();
                    foreach ($subscriptions['subscriptions'] as $subscription) {
                        $subscriptionMap[$subscription['id']] = $subscription;
                    }
                    $formattedArticles = array();
                    foreach ($articles['items'] as $article) {
                        $desc_length = mb_strlen(strip_tags(html_entity_decode($article['summary']['content'], ENT_QUOTES, 'UTF-8')), 'UTF-8');
                        if ($desc_length > 20) {
                            $short_desc = mb_substr(strip_tags(html_entity_decode($article['summary']['content'], ENT_QUOTES, 'UTF-8')), 0, 99, 'UTF-8') . '...';
                        } else {
                            $short_desc = strip_tags(html_entity_decode($article['summary']['content'], ENT_QUOTES, 'UTF-8'));
                        }
    
                        $formattedArticle = array(
                            'site_name' => $article['origin']['title'],
                            'title' => $article['title'],
                            'link' => $article['alternate'][0]['href'],
                            'time' => date('Y-m-d H:i', $article['published']),
                            'description' => $short_desc,
                        );
                        $subscriptionId = $article['origin']['streamId'];
                        if (isset($subscriptionMap[$subscriptionId])) {
                            $subscription = $subscriptionMap[$subscriptionId];
                            $iconUrl = $subscription['iconUrl'];
                            $filename = 'https://你部署FreshRSS的域名/'.substr($iconUrl, strrpos($iconUrl, '/') + 1);
                            $formattedArticle['icon'] = $filename;
                        }
                        $formattedArticles[] = $formattedArticle;
                    }
                    saveToJsonFile($formattedArticles);
                    return $formattedArticles;
                } else {
                    echo 'Error retrieving articles.';
                }
            } else {
                echo 'Error retrieving articles.';
            }
        } else {
            echo 'Login failed.';
        }
        return null;
    }
    function curlRequest($url, $authToken = null)
    {
        $ch = curl_init($url);
        if ($authToken) {
            $headers = array(
                'Authorization: GoogleLogin auth=' . $authToken,
            );
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    /**
     * 将数据保存到JSON文件中
     */
    function saveToJsonFile($data)
    {
        $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        file_put_contents('output.json', $json);
        echo '数据已保存到JSON文件中';
    }
    // 调用函数并提供用户名和密码
    getAllSubscribedArticlesAndSaveToJson('这里是FreshRSS的用户名', '这里是第3步设置的api密码');

    把这里面需要更改成自己的内容更改以后即可。刚才设置的api密码和rss用户名也别忘了填写。
    接下来就是在博客页面添加调用数据了。找到想要添加的页面,输入以下代码:

    <?php
                // 获取JSON数据
                $jsonData = file_get_contents('./output.json');
                // 将JSON数据解析为PHP数组
                $articles = json_decode($jsonData, true);
                // 对文章按时间排序(最新的排在前面)
                usort($articles, function ($a, $b) {
                    return strtotime($b['time']) - strtotime($a['time']);
                });
                // 设置每页显示的文章数量
                $itemsPerPage = 30;
                // 生成文章列表
                foreach (array_slice($articles, 0, $itemsPerPage) as $article) {
                    $articles_list ='
                    图标:' . htmlspecialchars($article['icon']) . '
                    站点标题:' . htmlspecialchars($article['site_name']) . '
                    文章标题:' . htmlspecialchars($article['title']) . '
                    文章内容摘要:' . htmlspecialchars($article['description']) . '
                    文章链接:' . htmlspecialchars($article['link']) . '
                    文章发布时间:' . htmlspecialchars($article['time']) . '
                    ';
                    echo $articles_list;
                }
            ?>

    这是纯代码,没有啥美化,比较丑,可以结合自己的页面模版进行更改,我的是这样的。

    <?php
              // 获取JSON数据
              $jsonData = file_get_contents('./output.json');
              // 将JSON数据解析为PHP数组
              $articles = json_decode($jsonData, true);
              // 对文章按时间排序(最新的排在前面)
              usort($articles, function ($a, $b) {
                  return strtotime($b['time']) - strtotime($a['time']);
              });
              // 设置每页显示的文章数量
              $itemsPerPage = 10;
              // 生成文章列表
              foreach (array_slice($articles, 0, $itemsPerPage) as $article) {
              ?>
              <article class="flex comment-body my-2" style="margin-top: 10px;margin-bottom:40px">
                        <div class="flex-initial w-full text-sm">
                            <div class="comment-author mb-1">
                                <div class="flex items-center">
                                    <!--输出文章链接和站名-->
                                    <a href="<?php echo htmlspecialchars($article['link']); ?>" target="_blank" rel="external nofollow" class="" data-ajax="false" style="text-decoration: none;font-size:18px;color:var(--main)"><?php echo htmlspecialchars($article['title']); ?></a><span class="mx-1"></span> 
                                </div>
                            </div>
                            <div class="comment-content card mb-2">
                                <!--输出文章摘要-->
                                <a><?php echo htmlspecialchars($article['description']); ?> </a>
                            </div>
                            <div class="flex items-center comment-meta text-xs text-gray-500 mt-1" data-no-instant="">
                            </div>
                                <!--输出站名和时间-->
                               <a> <span  class="flex items-center comment-reply text-muted comment-reply-link hover:text-blue-500" ><span><?php echo htmlspecialchars($article['site_name']); ?></span>・<time class="mr-1"><?php echo htmlspecialchars($article['time']); ?></time>  </span> </a>
                                <div>
                        </div>
                    </div>
                </article>            
             <?php } ?>

    添加定时任务

    宝塔面板添加定时任务,具体更新时间,依据个人喜好来定。不过第一次肯定要先执行,不然博客调用不了数据。

    最后,奉劝大家折腾的时候做好备份!备份!备份!不然.....

    昵称
    邮箱
    网址
    取消
    1. 头像
      王光卫博客
      Mac OS X 10.15.7   Google Chrome
      回复

      我在想有人用rss订阅没,用户量大的话,真的有必要把rss功能完善

      1. 头像
        bosir 博主
        Windows Server 2003   Quark浏览器
        回复
        @王光卫博客

        现在用 rss 的人还是挺多的

    2. 头像
      老陳网志
      Mac OS X 10.15.7   Microsoft Edge
      回复

       你博客的配色越看越喜欢。QQ

      1. 头像
        bosir 博主
        Windows 10   Google Chrome
        回复
        @老陳网志

        瞎折腾,现在不断在调整

    3. 头像
      林羽凡
      Windows 10   Firefox
      回复

      这个看着就专业啊。

      1. 头像
        bosir 博主
        Windows 10   Google Chrome
        回复
        @林羽凡

        这是从大佬那边扒过来改的。@阿呆 @网友小宋 @若志 他们都有出教程

        1. 头像
          林羽凡
          Windows 10   Firefox
          回复
          @bosir

          这都是老朋友了。

    4. 头像
      子痕
      Windows 10   Microsoft Edge
      回复

      大概扫了一下rss的输出页面,林羽凡就占了8个,他真的是更博狂人。

      1. 头像
        林羽凡
        Windows 10   Firefox
        回复
        @子痕

        我隐约看到你@我了,QQ,其实我就是随手就记录了,生活琐事,实在不想发朋友圈,但又想记录。

    5. 头像
      子痕
      Windows 10   Microsoft Edge
      回复

      交叉阅读,应该可以指定哪些或者分类博客展示出来,不然还不如直接公开订阅rss来的方便。

      1. 头像
        bosir 博主
        Windows 10   Google Chrome
        回复
        @子痕

        自用倒是不讲究那么多,一个页面承载太多也不好搞。访客点进来,看看标题,感兴趣的就直接过去了~哈哈。