注意!!!修改前一定先备份,放置操作失误;并且在修改文件时,将原文件复制一份到相同目录下

1.使用前准备

  • 关闭所有评论插件
  • 进入hao主题评论配置页面开启Artalk
  • 配置Artalk(配置部分详看Artalk-1panel配置)

2.文件修改

  • new_comments.html文件修改:此部分为newest页面

    • 打开1panel系统进入文件-打开hao主题templates下的new_comments.html文件(记得操作前复制一份),由于官网的api有所变化,所以需要进行一些修改,仅修改以下部分

                   <script>
                        var config = {
                            mailMd5: GLOBAL_CONFIG.source.comments.mailMd5,
                            twikooUrl: GLOBAL_CONFIG.source.twikoo.twikooUrl,
                            artalkUrl: GLOBAL_CONFIG.source.artalk.artalkUrl,
                            walineUrl: GLOBAL_CONFIG.source.waline.serverURL,
                            use: GLOBAL_CONFIG.source.comments.use
                        };
                        var isTwikoo = config.use == 'Twikoo';
                        var isArtalk = config.use == 'Artalk';
                        var isWaline = config.use == 'Waline';
                        comments();
                        async function comments() {
                            if (isTwikoo) {
                                fetch(GLOBAL_CONFIG.source.twikoo.twikooUrl, {
                                    method: "POST",
                                    body: JSON.stringify({
                                        event: "GET_RECENT_COMMENTS",
                                        accessToken: GLOBAL_CONFIG.source.twikoo.accessToken,
                                        includeReply: !0,
                                        pageSize: 100
                                    }),
                                    headers: {
                                        "Content-Type": "application/json"
                                    }
                                }).then(res => res.json()).then(async ({data}) => {
                                    const twikooArray = data.map(e => {
                                        return {
                                            'comment': changeContents(e.comment),
                                            'avatar': 'https://weavatar.com/avatar/' + e.mailMd5 + "?d=https://api.vvhan.com/api/avatar/rand",
                                            'nick': e.nick,
                                            'url': e.url,
                                            'barrageBlogger': e.mailMd5 === config.mailMd5,
                                            'id': e.id,
                                            'created': e.created
                                        }
                                    }
                                    )
                                    renderer(twikooArray)
                                }
                                ).catch( (err) => {
                                    console.log(err);
                                }
                                )
                            }
                            if (isArtalk) {

                                const statheaderList = {
                                    method: 'GET',
                                    headers: {
                                        'Content-Type': 'application/x-www-form-urlencoded',
                                        'Origin': window.location.origin
                                    }
                                }
                                var params = {
                                    'site_name': GLOBAL_CONFIG.source.artalk.siteName,
                                    'limit': '100',
                                };

                                //兼容2.8以后版本的artalk接口
                                fetch(GLOBAL_CONFIG.source.artalk.artalkUrl + 'api/v2/stats/latest_comments?' + new URLSearchParams(params).toString(), statheaderList).then(res => res.json()).then(d => {
                                    const artalk = d.data.map(function(e) {
                                        return {
                                            'comment': changeContents(e.content_marked),
                                            'avatar': 'https://weavatar.com/avatar/' + e.email_encrypted + '?d=https://api.vvhan.com/api/avatar/rand&s=240',
                                            'nick': e.nick,
                                            'url': e.page_key,
                                            'barrageBlogger': e.email_encrypted === config.mailMd5,
                                            'id': 'atk-comment-' + e.id,
                                            'created': e.date,
                                        }
                                    })
                                    renderer(artalk)
                                }
                                ).catch( (err) => {
                                    console.log(err);
                                }
                                )
                            }
                            if (isWaline) {
                                const loadWaline = () => {
                                    Waline.RecentComments({
                                        serverURL: GLOBAL_CONFIG.source.waline.serverURL,
                                        count: 50
                                    }).then( ({comments}) => {
                                        const walineArray = comments.map(e => {
                                            return {
                                                'comment': changeContents(e.comment),
                                                'avatar': e.avatar,
                                                'nick': e.nick,
                                                'url': e.url,
                                                'barrageBlogger': e.type === 'administrator',
                                                'id': e.objectId,
                                                'created': e.insertedAt,
                                            }
                                        }
                                        )
                                        renderer(walineArray);
                                    }
                                    ).catch( (err) => {
                                        console.log(err);
                                    }
                                    )
                                }
                                if (typeof Waline === 'object')
                                    loadWaline()
                                else
                                    getScript(GLOBAL_CONFIG.source.waline.js).then(loadWaline)
                            }

                        }

                        function getTitle(url) {
                            let a = articles.find(a => a.path == url)
                            if (a)
                                return a.title
                            return '该文章/页面不存在'
                        }

                        function renderer(data) {
                            let html = "";
                            data.forEach(item => {
                                const a = new Date(item.created)
                                  , c = `${a.getFullYear().toString().slice(-2)}-${a.getMonth() + 1}-${a.getDate()} ${a.getHours()}:${a.getMinutes()}:${a.getSeconds()}`;
                                html += `<div class="comment-card" title="${item.comment}" onclick="pjax.loadUrl('${item.url}#${item.id}')">
                                    <div class="comment-info no-lightbox">
                                        <img src="${item.avatar}" alt='${item.nick}'/>
                                        <div class="comment-information">
                                                <span class="comment-user">${item.nick} ${item.barrageBlogger ? '<span class="isBlogger">博主</span>' : ''}</span>
                                                <span class="comment-time">${c}</span>
                                        </div>
                                    </div>
                                    <div class="comment-content">${item.comment}</div>
                                    <div class="comment-article">"${getTitle(item.url)}"</div>
                                </div>`
                            }
                            )
                            document.getElementById('comments-page').innerHTML = html
                        }
                        function changeContents(content) {
                            if (content === '')
                                return content

                            content = content.replace(/<img.*?src="(.*?)"?[^\>]+>/ig, '[图片]')
                            // replace image link
                            content = content.replace(/<a[^>]+?href=["']?([^"']+)["']?[^>]*>([^<]+)<\/a>/gi, '[链接]')
                            // replace url
                            content = content.replace(/<pre><code>.*?<\/pre>/gi, '[代码]')
                            // replace code
                            content = content.replace(/<[^>]+>/g, "")
                            // remove html tag

                            if (content.length > 150) {
                                content = content.substring(0, 150) + '...'
                            }
                            return content
                        }
                    </script>
  • Artalk.html文件修改:此部分为卡片和中控台显示

    • 打开1panel系统进入文件-打开hao主题templates/modules/comment下的Artalk.html文件(记得操作前复制一份),仅修改一下部分

            <!-- 最近评论 -->
            <script>
                window.addEventListener('load', () => {
                    const generateHtml = array => {
                        let result = ''

                        if (array.length) {
                            for (let i = 0; i < array.length; i++) {
                                if (i == 6) {
                                    break;
                                }
                                result += '<div class=\'aside-list-item\'>'

                                if (true) {
                                    let name = 'src'
                                    if (true) {
                                        name = 'data-lazy-src'
                                    }
                                    result += `<a href='${array[i].url}' class='thumbnail'><img ${name}='${array[i].avatar}' alt='${array[i].nick}'><div class='name'><span>${array[i].nick}</span></div></a>`
                                }

                                result += `<div class='content'>
                                <a class='comment' href='${array[i].url}' title='${array[i].content}'>${array[i].content}</a>
                                <time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time></div>
                                </div>`
                            }
                        } else {
                            result += '没有评论'
                        }

                        let $dom = document.querySelector('#card-newest-comments .aside-list')
                        $dom.innerHTML = result
                        window.lazyLoadInstance && window.lazyLoadInstance.update()
                        window.pjax && window.pjax.refresh($dom)
                    }

                    const necommHtml = array => {
                        let result = ''

                        const pagesize = 4;
                        const defaultpagesize = 5;
                        const finalpagesize = pagesize <= 0 ? defaultpagesize : pagesize;

                        if (array.length) {
                            for (let i = 0; i < array.length; i++) {

                                if (i == finalpagesize) {
                                    break;
                                }
                                result += '<div class="aside-list-item">'

                                if (true) {
                                    let name = 'src'
                                    if (true) {
                                        name = 'data-lazy-src'
                                    }
                                    result += `
                            <a class="thumbnail" href="${array[i].url}">
                                <img alt="dasda" ${name}="${array[i].avatar}">
                            </a>
                        `
                                }

                                result += `
                        <div class="content">
                            <a class="comment" style="display: -webkit-box;-webkit-line-clamp: 2;-webkit-box-orient: vertical;overflow: hidden;"
                            href="${array[i].url}" title="${array[i].content}">
                            ${array[i].content}
                            </a>
                            <div class="name">
                                <span>${array[i].nick} / </span>
                                <time datetime="${array[i].date}">${btf.diffDate(array[i].date, true)}</time>
                            </div>
                        </div>
                    </div>
                  `
                            }
                        } else {
                            result += '没有评论'
                        }

                        let $dom = document.querySelector('#newcomm')
                        $dom.innerHTML = result
                        window.lazyLoadInstance && window.lazyLoadInstance.update()
                        window.pjax && window.pjax.refresh($dom)
                    }

                    const getComment = () => {
                        const statheaderList = {
                            method: 'GET',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded',
                                'Origin': window.location.origin
                            }
                        }
                        var params = {
                            'site_name': GLOBAL_CONFIG.source.artalk.siteName,
                            'limit': '20',
                        };

                        //兼容2.8以后版本的artalk接口
                        fetch(GLOBAL_CONFIG.source.artalk.artalkUrl + 'api/v2/stats/latest_comments?' + new URLSearchParams(params).toString(), statheaderList).then(response => response.json()).then(d => {
                            const artalk = d.data.map(function(e) {
                                return {
                                    'avatar': 'https://weavatar.com/avatar/' + e.email_encrypted + '?d=https://api.vvhan.com/api/avatar/rand&s=240',
                                    'content': btf.changeContent(e.content_marked, 150),
                                    'nick': e.nick,
                                    'url': e.page_url + '#atk-comment-' + e.id,
                                    'date': e.date,
                                }
                            })
                            saveToLocal.set('artalk-newest-comments', JSON.stringify(artalk), 10 / (60 * 24))
                            generateHtml(artalk)
                            document.querySelector('#newcomm') && necommHtml(artalk)
                        }
                        ).catch(e => {
                            const $dom = document.querySelector('#card-newest-comments .aside-list')
                            $dom.innerHTML = "无法获取评论,请确认相关配置是否正确"
                        }
                        )
                    }
                    const newestCommentInit = () => {
                        if (document.querySelector('#card-newest-comments .aside-list')) {
                            const data = saveToLocal.get('artalk-newest-comments')
                            if (data) {
                                generateHtml(JSON.parse(data))
                                document.querySelector('#newcomm') && necommHtml(JSON.parse(data))
                            } else {
                                getComment()
                            }
                        }
                    }

                    newestCommentInit()
                    document.addEventListener('pjax:complete', newestCommentInit)
                }
                )
            </script>

修改完文件即可使用newest页面以及最新评论卡片与中控台最新评论显示。

常见问题

  • newest页面卡主-new_comments.html文件修改有问题,仔细检查一下,因为本页面复制到1panel会出现格式问题。

  • 最新评论卡片以及中控台没有最新评论-可以将saveToLocal.set('artalk-newest-comments', JSON.stringify(artalk), 10 / (60 * 24)) 重新设置一下,我这里设置的是10分钟发起一次请求。