From e01b45659d72d613f9510772e1c17628324d1e9b Mon Sep 17 00:00:00 2001 From: ChishFoxcat <76027184+ChishFoxcat@users.noreply.github.com> Date: Fri, 7 Jun 2024 15:55:58 +0800 Subject: [PATCH] add MOD: one-saying --- app/mod/one-saying/mod.js | 94 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 app/mod/one-saying/mod.js diff --git a/app/mod/one-saying/mod.js b/app/mod/one-saying/mod.js new file mode 100644 index 0000000..1d53bb5 --- /dev/null +++ b/app/mod/one-saying/mod.js @@ -0,0 +1,94 @@ +(function () { + const observedAnchors = '.ps-container'; + async function moduleFunction() { + const container = document.querySelector('.ps-container'); + const newElement = document.createElement('div'); + newElement.setAttribute('widget-id', 'saying'); + + userImage = "/v1/users/avatar?token=" + localStorage.getItem('access_token'); + userName = JSON.parse(localStorage.getItem('user')).username; + saying = "你好!一言加载中..." + + newElement.innerHTML = ` +
+
+
+
+
+
+
+ +
+
+

`+ userName + `

+

+

${saying}

+

+
+
+
+
+
+
+`; + container.insertBefore(newElement, container.firstChild); + + async function getSaying() { + try { + if (localStorage.getItem('lang') === "zh_cn") { + const response = await fetch('https://v1.hitokoto.cn/'); + const data = await response.json(); + return data.hitokoto; + } else { + const response = await fetch('https://api.quotable.io/quotes/random'); + const data = await response.json(); + return data[0].content; + } + } catch (error) { + console.error('Failed to get Saying', error); + return false; + } + } + + async function cacheSaying(force = false) { + const cacheKey = 'saying'; + const cacheExpiry = 60 * 60 * 1000; + const cacheData = localStorage.getItem(cacheKey); + if (cacheData && force == false) { + const { saying, timestamp } = JSON.parse(cacheData); + if (Date.now() - timestamp < cacheExpiry) { + return saying; + } + } + const newSaying = await getSaying(); + localStorage.setItem(cacheKey, JSON.stringify({ + saying: newSaying, + timestamp: Date.now(), + })); + return newSaying; + } + + document.querySelector('#saying').innerHTML = await cacheSaying(); + document.querySelector('#saying').addEventListener('click', async function() { + document.querySelector('#saying').innerHTML = await cacheSaying(true); + }); + } + + const observer = new MutationObserver(mutations => { + mutations.forEach(mutation => { + if (mutation.target.querySelector(observedAnchors)) { + observer.disconnect(); + debounced(); + } + }); + }); + observer.observe(document.body, { childList: true, subtree: true, once: true }); + function debounce(func, wait) { + let timeout; + return (...args) => { + clearTimeout(timeout); + timeout = setTimeout(() => func.apply(this, args), wait); + }; + } + const debounced = debounce(moduleFunction, 1); +})(); \ No newline at end of file