Linux do Level Enhanced

Enhanced script to track progress towards next trust level on linux.do with added search functionality, adjusted posts read limit, and a breathing icon animation.

当前为 2024-03-25 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Linux do Level Enhanced
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0.3
  5. // @description Enhanced script to track progress towards next trust level on linux.do with added search functionality, adjusted posts read limit, and a breathing icon animation.
  6. // @author Hua, Reno, NullUser
  7. // @match https://linux.do/*
  8. // @icon https://www.google.com/s2/favicons?domain=linux.do
  9. // @grant none
  10. // @license MIT
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. 'use strict';
  15.  
  16. const StyleManager = {
  17. styles: `
  18. @keyframes breathAnimation {
  19. 0%, 100% { transform: scale(1); box-shadow: 0 0 5px rgba(0,0,0,0.5); }
  20. 50% { transform: scale(1.1); box-shadow: 0 0 10px rgba(0,0,0,0.7); }
  21. }
  22. .breath-animation { animation: breathAnimation 4s ease-in-out infinite; }
  23. .minimized { border-radius: 50%; cursor: pointer; }
  24. .linuxDoLevelPopup { position: fixed; width: 250px; height: 150px; background: var(--d-sidebar-background); box-shadow: 0 0 10px rgba(0,0,0,0.5); padding: 15px; z-index: 10000; font-size: 14px; border-radius: 5px; cursor: move; }
  25. .linuxDoLevelPopup input, .linuxDoLevelPopup button { width: 100%; margin-top: 10px; }
  26. .linuxDoLevelPopup button { cursor: pointer; }
  27. .minimizeButton { position: absolute; top: 5px; right: 5px; background: transparent; border: none; cursor: pointer; width: 30px; height: 30px; font-size: 16px; }
  28. .searchButton { width: 100%; marginTop: 10px }
  29. .searchBox { width: 100%; marginTop: 10px }
  30. `,
  31.  
  32. injectStyles: function() {
  33. const styleSheet = document.createElement('style');
  34. styleSheet.type = 'text/css';
  35. styleSheet.innerText = this.styles;
  36. document.head.appendChild(styleSheet);
  37. }
  38. };
  39.  
  40. const DataManager = {
  41. Config: {
  42. BASE_URL: 'https://linux.do',
  43. PATHS: {
  44. ABOUT: '/about.json',
  45. USER_SUMMARY: '/u/{username}/summary.json',
  46. USER_DETAIL: '/u/{username}.json',
  47. },
  48. },
  49.  
  50. levelRequirements: {
  51. 0: { 'topics_entered': 5, 'posts_read_count': 30, 'time_read': 600 },
  52. 1: { 'days_visited': 15, 'likes_given': 1, 'likes_received': 1, 'post_count': 3, 'topics_entered': 20, 'posts_read_count': 100, 'time_read': 3600 },
  53. 2: { 'days_visited': 50, 'likes_given': 30, 'likes_received': 20, 'post_count': 10 },
  54. },
  55.  
  56. levelDescriptions: {
  57. 0: "游客",
  58. 1: "基本用户",
  59. 2: "成员",
  60. 3: "活跃用户",
  61. 4: "领导者"
  62. },
  63.  
  64. fetch: async function(url, options = {}) {
  65. try {
  66. const response = await fetch(url, {
  67. ...options,
  68. headers: { "Accept": "application/json", "User-Agent": "Mozilla/5.0" },
  69. method: options.method || "GET",
  70. });
  71. if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  72. return await response.json();
  73. } catch (error) {
  74. console.error(`Error fetching data from ${url}:`, error);
  75. throw error;
  76. }
  77. },
  78.  
  79. fetchAboutData: function() {
  80. const url = this.buildUrl(this.Config.PATHS.ABOUT);
  81. return this.fetch(url);
  82. },
  83.  
  84. fetchSummaryData: function(username) {
  85. const url = this.buildUrl(this.Config.PATHS.USER_SUMMARY, { username });
  86. return this.fetch(url);
  87. },
  88.  
  89. fetchUserData: function(username) {
  90. const url = this.buildUrl(this.Config.PATHS.USER_DETAIL, { username });
  91. return this.fetch(url);
  92. },
  93.  
  94. buildUrl: function(path, params = {}) {
  95. let url = this.Config.BASE_URL + path;
  96. Object.keys(params).forEach(key => {
  97. url = url.replace(`{${key}}`, encodeURIComponent(params[key]));
  98. });
  99. return url;
  100. },
  101. };
  102.  
  103. const UIManager = {
  104. initPopup: function() {
  105. this.popup = this.createElement('div', { id: 'linuxDoLevelPopup', class: 'linuxDoLevelPopup' });
  106. this.content = this.createElement('div', { id: 'linuxDoLevelPopupContent' }, '欢迎使用 Linux do 等级增强插件');
  107. this.searchBox = this.createElement('input', { placeholder: '请输入用户名...', type: 'text', class: 'searchBox' });
  108. this.searchButton = this.createElement('button', { class: 'searchButton' }, '搜索');
  109. this.minimizeButton = this.createElement('button', { }, '隐藏');
  110. this.popup.style.bottom = '20px'; // 示例:距离顶部20px
  111. this.popup.style.right = '20px'; // 示例:距离左侧20px
  112. this.popup.style.width = '250px'; // 初始化宽度
  113. this.popup.style.height = 'auto'; // 高度自适应内容
  114. this.searchButton.classList.add('btn', 'btn-icon-text', 'btn-default')
  115. this.minimizeButton.classList.add('btn', 'btn-icon-text', 'btn-default')
  116.  
  117. this.popup.append(this.content, this.searchBox, this.searchButton, this.minimizeButton);
  118. document.body.appendChild(this.popup);
  119.  
  120. this.minimizeButton.addEventListener('click', () => this.togglePopupSize());
  121. this.searchButton.addEventListener('click', () => EventHandler.handleSearch());
  122. // 添加输入框的回车键事件监听器
  123. this.searchBox.addEventListener('keypress', (event) => {
  124. // 检查是否按下了回车键并且弹窗不处于最小化状态
  125. if (event.key === 'Enter' && !this.popup.classList.contains('minimized')) {
  126. EventHandler.handleSearch();
  127. }
  128. });
  129.  
  130. var checkInterval = setInterval(function() {
  131. // 查找id为current-user的li元素
  132. var currentUserLi = document.querySelector('#current-user');
  133.  
  134. // 如果找到了元素
  135. if(currentUserLi) {
  136. // 查找该元素下的button
  137. var button = currentUserLi.querySelector('button');
  138.  
  139. // 如果找到了button元素
  140. if(button) {
  141. // 获取button的href属性值
  142. var href = button.getAttribute('href');
  143. UIManager.searchBox.value = href.replace('/u/', '');
  144. clearInterval(checkInterval); // 停止检查
  145. // 这里你可以根据需要对href进行进一步操作
  146. }
  147. }
  148. }, 1000); // 每隔1秒检查一次
  149. },
  150.  
  151. createElement: function(tag, attributes, text) {
  152. const element = document.createElement(tag);
  153. for (const attr in attributes) {
  154. if (attr === 'class') {
  155. element.classList.add(attributes[attr]);
  156. } else {
  157. element.setAttribute(attr, attributes[attr]);
  158. }
  159. }
  160. if (text) element.textContent = text;
  161. return element;
  162. },
  163.  
  164. updatePopupContent: function(userSummary, user, userDetail, status) {
  165. if (!userSummary || !user || !userDetail) return;
  166.  
  167. let content = `<strong>信任等级:</strong>${DataManager.levelDescriptions[user.trust_level]}<br>`;
  168. const requirements = DataManager.levelRequirements[user.trust_level] || {};
  169.  
  170. if (userDetail.gamification_score) {
  171. content += `<strong>你的点数:</strong>${userDetail.gamification_score}<br>`;
  172. } else {
  173. content += `<strong>你还没有获得点数,继续加油!</strong>无<br>`;
  174. }
  175.  
  176. content += `<strong>最近活跃:</strong>${formatTimestamp(userDetail.last_seen_at)}<br> <strong>升级进度:</strong><br>`;
  177.  
  178. if (user.trust_level === 2) {
  179. requirements['posts_read_count'] = Math.min(parseInt(parseInt(status.posts_30_days) / 4), 20000);
  180. requirements['topics_entered'] = Math.min(parseInt(parseInt(status.topics_30_days) / 4), 500);
  181. }
  182.  
  183. if (user.trust_level === 3) {
  184. content += '联系管理员进行py交易以升级到领导者<br>';
  185. } else if (user.trust_level === 4) {
  186. content += '您已是最高信任等级<br>';
  187. } else {
  188. let summary = summaryRequired(requirements, userSummary, this.translateStat.bind(this));
  189. content += summary;
  190. }
  191. this.content.innerHTML = content;
  192. },
  193.  
  194. togglePopupSize: function() {
  195. if (this.popup.classList.contains('minimized')) {
  196. this.popup.classList.remove('minimized');
  197. this.popup.style.width = '250px';
  198. this.popup.style.height = 'auto';
  199. this.content.style.display = 'block';
  200. this.searchBox.style.display = 'block';
  201. this.searchButton.style.display = 'block';
  202. this.minimizeButton.textContent = '隐藏';
  203. this.popup.classList.remove('breath-animation');
  204. } else {
  205. this.popup.classList.add('minimized');
  206. this.popup.style.width = '50px';
  207. this.popup.style.height = '50px';
  208. this.content.style.display = 'none';
  209. this.searchBox.style.display = 'none';
  210. this.searchButton.style.display = 'none';
  211. this.popup.classList.add('breath-animation');
  212.  
  213. // 调用 updatePercentage 函数并更新按钮文本
  214. updatePercentage().then(percentage => {
  215. this.minimizeButton.textContent = `${percentage.toFixed(2)}%`;
  216. }).catch(error => {
  217. console.error('Error calculating percentage:', error);
  218. // 出错时保持原有文本
  219. this.minimizeButton.textContent = '展开';
  220. });
  221. }
  222.  
  223. // 自动校正窗口位置
  224. addDraggableFeature(this.popup);
  225. const windowWidth = window.innerWidth;
  226. const windowHeight = window.innerHeight;
  227. const popupWidth = this.popup.offsetWidth;
  228. const popupHeight = this.popup.offsetHeight;
  229. const popupTop = parseInt(this.popup.style.top);
  230. const popupLeft = parseInt(this.popup.style.left);
  231.  
  232. // 初始化新的位置
  233. let newTop = popupTop;
  234. let newLeft = popupLeft;
  235.  
  236. // 上下边界同时检查
  237. newTop = Math.min(Math.max(70, popupTop), windowHeight - popupHeight);
  238.  
  239. // 左右边界同时检查
  240. newLeft = Math.min(Math.max(5, popupLeft), windowWidth - popupWidth - 20);
  241.  
  242. this.popup.style.top = newTop + 'px';
  243. this.popup.style.left = newLeft + 'px';
  244. },
  245.  
  246. displayError: function(message) {
  247. this.content.innerHTML = `<strong>错误:</strong>${message}`;
  248. },
  249.  
  250. translateStat: function(stat) {
  251. const translations = {
  252. 'days_visited': '访问天数',
  253. 'likes_given': '给出的赞',
  254. 'likes_received': '收到的赞',
  255. 'post_count': '帖子数量',
  256. 'posts_read_count': '已读帖子',
  257. 'topics_entered': '已读主题',
  258. 'time_read': '阅读时间(秒)'
  259. };
  260. return translations[stat] || stat;
  261. }
  262. };
  263.  
  264. const EventHandler = {
  265. handleSearch: async function() {
  266. const username = UIManager.searchBox.value.trim();
  267. if (!username) return;
  268.  
  269. try {
  270. const aboutData = await DataManager.fetchAboutData();
  271. const summaryData = await DataManager.fetchSummaryData(username);
  272. const userData = await DataManager.fetchUserData(username);
  273. if (summaryData && userData && aboutData) {
  274. UIManager.updatePopupContent(summaryData.user_summary, summaryData.users ? summaryData.users[0] : { 'trust_level': 0 }, userData.user, aboutData.about.stats);
  275. }
  276. } catch (error) {
  277. console.error(error);
  278. }
  279. },
  280. // 更新拖动状态
  281. handleDragEnd: function() {
  282. UIManager.updateDragStatus(true);
  283. }
  284. };
  285.  
  286. // 添加含水率
  287. function updatePercentage() {
  288. return new Promise((resolve, reject) => {
  289. let badIds = [11, 16, 34, 17, 18, 19, 29, 36, 35, 22, 26, 25];
  290. const badScore = [];
  291. const goodScore = [];
  292. const urls = [
  293. 'https://linux.do/latest.json?order=created',
  294. 'https://linux.do/new.json',
  295. 'https://linux.do/top.json?period=daily'
  296. ];
  297.  
  298. Promise.all(urls.map(url => fetch(url).then(resp => resp.json())))
  299. .then(data => {
  300. data.forEach(({ topic_list: { topics } }) => {
  301. topics.forEach(topic => {
  302. const score = topic.posts_count + topic.like_count + topic.reply_count;
  303. (badIds.includes(topic.category_id) ? badScore : goodScore).push(score);
  304. });
  305. });
  306.  
  307. const badTotal = badScore.reduce((acc, curr) => acc + curr, 0);
  308. const goodTotal = goodScore.reduce((acc, curr) => acc + curr, 0);
  309. const percentage = (badTotal / (badTotal + goodTotal)) * 100;
  310.  
  311. resolve(percentage);
  312. })
  313. .catch(reject);
  314. });
  315. };
  316.  
  317. // 添加时间格式化
  318. function formatTimestamp(lastSeenAt) {
  319. // 解析时间戳并去除毫秒
  320. let timestamp = new Date(lastSeenAt);
  321.  
  322. // 使用Intl.DateTimeFormat格式化时间为上海时区
  323. let formatter = new Intl.DateTimeFormat('zh-CN', {
  324. timeZone: 'Asia/Shanghai',
  325. year: 'numeric',
  326. month: 'numeric',
  327. day: 'numeric',
  328. hour: 'numeric',
  329. minute: 'numeric',
  330. second: 'numeric',
  331. });
  332.  
  333. // 获取格式化后的字符串
  334. let formattedTimestamp = formatter.format(timestamp);
  335.  
  336. return formattedTimestamp;
  337. }
  338.  
  339. // 添加用户升级进度总结
  340. function summaryRequired(required, current, translateStat) {
  341. let summary = '';
  342. let allMet = true;
  343.  
  344. for (const stat in required) {
  345. if (required.hasOwnProperty(stat) && current.hasOwnProperty(stat)) {
  346. const reqValue = required[stat];
  347. const curValue = current[stat] || 0; // 使用 || 0 确保未定义的情况下使用0
  348. if (curValue < reqValue) {
  349. allMet = false;
  350. const diff = reqValue - curValue;
  351. summary += `${translateStat(stat)}: <span style="color: red;"> ${curValue} < ${reqValue},还差 ${diff}</span><br>`;
  352. } else {
  353. // 如果当前值满足或超过了要求值,也打印出来,但使用不同的颜色或提示信息
  354. summary += `${translateStat(stat)}: <span style="color: green;"> ${curValue} ${reqValue},已合格</span><br>`;
  355. }
  356. }
  357. }
  358.  
  359. if (allMet) {
  360. return "恭喜您!所有项次都已达到合格标准。<br>" + summary;
  361. } else {
  362. return summary;
  363. }
  364. }
  365.  
  366. // 添加拖动功能
  367. function addDraggableFeature(element) {
  368. let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  369.  
  370. const dragMouseDown = function(e) {
  371. // 检查事件的目标是否是输入框,按钮或其他可以忽略拖动逻辑的元素
  372. if (e.target.tagName.toUpperCase() === 'INPUT' || e.target.tagName.toUpperCase() === 'TEXTAREA' || e.target.tagName.toUpperCase() === 'BUTTON') {
  373. return; // 如果是,则不执行拖动逻辑
  374. }
  375.  
  376. e = e || window.event;
  377. e.preventDefault();
  378. pos3 = e.clientX;
  379. pos4 = e.clientY;
  380. document.onmouseup = closeDragElement;
  381. document.onmousemove = elementDrag;
  382. };
  383.  
  384. const elementDrag = function(e) {
  385. e = e || window.event;
  386. e.preventDefault();
  387. pos1 = pos3 - e.clientX;
  388. pos2 = pos4 - e.clientY;
  389. pos3 = e.clientX;
  390. pos4 = e.clientY;
  391.  
  392. element.style.top = (element.offsetTop - pos2) + "px";
  393. element.style.left = (element.offsetLeft - pos1) + "px";
  394. // 为了避免与拖动冲突,在此移除bottom和right样式
  395. element.style.bottom = '';
  396. element.style.right = '';
  397. };
  398.  
  399. const closeDragElement = function() {
  400. document.onmouseup = null;
  401. document.onmousemove = null;
  402. // 在拖动结束时更新拖动状态
  403. EventHandler.handleDragEnd();
  404. };
  405.  
  406. element.onmousedown = dragMouseDown;
  407. }
  408.  
  409. const init = () => {
  410. StyleManager.injectStyles();
  411. UIManager.initPopup();
  412. addDraggableFeature(document.getElementById('linuxDoLevelPopup')); // 确保已设置该ID
  413. UIManager.togglePopupSize(); // 初始最小化
  414. };
  415.  
  416. init();
  417.  
  418. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址