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-28 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Linux do Level Enhanced
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0.4
  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. // 初始化内容字符串,并添加用户信任等级
  168. let content = `<strong>信任等级:</strong>${DataManager.levelDescriptions[user.trust_level]}<br>`;
  169.  
  170. // 获取用户的信任等级要求
  171. const requirements = DataManager.levelRequirements[user.trust_level] || {};
  172.  
  173. // 添加用户的 gamification_score
  174. if (userDetail.gamification_score) {
  175. content += `<strong>你的点数:</strong>${userDetail.gamification_score}<br>`;
  176. }
  177.  
  178. // 添加用户的最近活跃时间
  179. content += `<strong>最近活跃:</strong>${formatTimestamp(userDetail.last_seen_at)}<br>`;
  180.  
  181. // 处理2级以下用户,调用 summaryRequired 功能
  182. if (user.trust_level <= 2) {
  183. if (user.trust_level === 2) {
  184. requirements['posts_read_count'] = Math.min(parseInt(parseInt(status.posts_30_days) / 4), 20000);
  185. requirements['topics_entered'] = Math.min(parseInt(parseInt(status.topics_30_days) / 4), 500);
  186. }
  187. let summary = summaryRequired(requirements, userSummary, this.translateStat.bind(this));
  188. content += summary;
  189. } else {
  190. // 处理2级以上用户,调用 analyzeAbility 功能
  191. if (userSummary.top_categories) {
  192. content += analyzeAbility(userSummary.top_categories);
  193. }
  194. }
  195.  
  196. // 更新弹窗内容
  197. this.content.innerHTML = content;
  198. },
  199.  
  200. togglePopupSize: function() {
  201. if (this.popup.classList.contains('minimized')) {
  202. this.popup.classList.remove('minimized');
  203. this.popup.style.width = '250px';
  204. this.popup.style.height = 'auto';
  205. this.content.style.display = 'block';
  206. this.searchBox.style.display = 'block';
  207. this.searchButton.style.display = 'block';
  208. this.minimizeButton.textContent = '隐藏';
  209. this.popup.classList.remove('breath-animation');
  210. } else {
  211. this.popup.classList.add('minimized');
  212. this.popup.style.width = '50px';
  213. this.popup.style.height = '50px';
  214. this.content.style.display = 'none';
  215. this.searchBox.style.display = 'none';
  216. this.searchButton.style.display = 'none';
  217. this.popup.classList.add('breath-animation');
  218.  
  219. // 调用 updatePercentage 函数并更新按钮文本
  220. updatePercentage().then(percentage => {
  221. this.minimizeButton.textContent = `${percentage.toFixed(2)}%`;
  222. }).catch(error => {
  223. console.error('Error calculating percentage:', error);
  224. // 出错时保持原有文本
  225. this.minimizeButton.textContent = '展开';
  226. });
  227. }
  228.  
  229. // 自动校正窗口位置
  230. addDraggableFeature(this.popup);
  231. const windowWidth = window.innerWidth;
  232. const windowHeight = window.innerHeight;
  233. const popupWidth = this.popup.offsetWidth;
  234. const popupHeight = this.popup.offsetHeight;
  235. const popupTop = parseInt(this.popup.style.top);
  236. const popupLeft = parseInt(this.popup.style.left);
  237.  
  238. // 初始化新的位置
  239. let newTop = popupTop;
  240. let newLeft = popupLeft;
  241.  
  242. // 上下边界同时检查
  243. newTop = Math.min(Math.max(70, popupTop), windowHeight - popupHeight);
  244.  
  245. // 左右边界同时检查
  246. newLeft = Math.min(Math.max(5, popupLeft), windowWidth - popupWidth - 20);
  247.  
  248. this.popup.style.top = newTop + 'px';
  249. this.popup.style.left = newLeft + 'px';
  250. },
  251.  
  252. displayError: function(message) {
  253. this.content.innerHTML = `<strong>错误:</strong>${message}`;
  254. },
  255.  
  256. translateStat: function(stat) {
  257. const translations = {
  258. 'days_visited': '访问天数',
  259. 'likes_given': '给出的赞',
  260. 'likes_received': '收到的赞',
  261. 'post_count': '帖子数量',
  262. 'posts_read_count': '已读帖子',
  263. 'topics_entered': '已读主题',
  264. 'time_read': '阅读时间(秒)'
  265. };
  266. return translations[stat] || stat;
  267. }
  268. };
  269.  
  270. const EventHandler = {
  271. handleSearch: async function() {
  272. const username = UIManager.searchBox.value.trim();
  273. if (!username) return;
  274.  
  275. try {
  276. const aboutData = await DataManager.fetchAboutData();
  277. const summaryData = await DataManager.fetchSummaryData(username);
  278. const userData = await DataManager.fetchUserData(username);
  279. if (summaryData && userData && aboutData) {
  280. UIManager.updatePopupContent(summaryData.user_summary, summaryData.users ? summaryData.users[0] : { 'trust_level': 0 }, userData.user, aboutData.about.stats);
  281. }
  282. } catch (error) {
  283. console.error(error);
  284. }
  285. },
  286. // 更新拖动状态
  287. handleDragEnd: function() {
  288. UIManager.updateDragStatus(true);
  289. }
  290. };
  291.  
  292. // 添加技能分析
  293. function analyzeAbility(topCategories) {
  294. let resultStr = "<strong>技能分析:</strong><br>";
  295. const scores = topCategories.map(category => category.topic_count + category.post_count);
  296. const minScore = Math.min(...scores);
  297. const maxScore = Math.max(...scores);
  298. const scoreRange = Math.max(1, maxScore - minScore);
  299. topCategories.sort((a, b) => a.name.length - b.name.length);
  300. topCategories.forEach(category => {
  301. const score = category.topic_count + category.post_count;
  302. const normalizedScore = 1 + (score - minScore) / scoreRange * 9;
  303. const numPoints = Math.round(normalizedScore);
  304. let block = numPoints > 3 ? "<span style='color:green'>▊</span>" : "<span style='color:red'>▊</span>";
  305. resultStr += `
  306. <div style='display: table-row;'>
  307. <div style='display: table-cell; text-align: left;'>${category.name}</div>
  308. <div style='display: table-cell;'> &nbsp;&nbsp; ${block.repeat(numPoints)} (${score})</div>
  309. </div>`;
  310. });
  311.  
  312. return resultStr;
  313. }
  314.  
  315.  
  316. // 添加含水率
  317. function updatePercentage() {
  318. return new Promise((resolve, reject) => {
  319. let badIds = [11, 16, 34, 17, 18, 19, 29, 36, 35, 22, 26, 25];
  320. const badScore = [];
  321. const goodScore = [];
  322. const urls = [
  323. 'https://linux.do/latest.json?order=created',
  324. 'https://linux.do/new.json',
  325. 'https://linux.do/top.json?period=daily'
  326. ];
  327.  
  328. Promise.all(urls.map(url => fetch(url).then(resp => resp.json())))
  329. .then(data => {
  330. data.forEach(({ topic_list: { topics } }) => {
  331. topics.forEach(topic => {
  332. const score = topic.posts_count + topic.like_count + topic.reply_count;
  333. (badIds.includes(topic.category_id) ? badScore : goodScore).push(score);
  334. });
  335. });
  336.  
  337. const badTotal = badScore.reduce((acc, curr) => acc + curr, 0);
  338. const goodTotal = goodScore.reduce((acc, curr) => acc + curr, 0);
  339. const percentage = (badTotal / (badTotal + goodTotal)) * 100;
  340.  
  341. resolve(percentage);
  342. })
  343. .catch(reject);
  344. });
  345. };
  346.  
  347. // 添加时间格式化
  348. function formatTimestamp(lastSeenAt) {
  349. // 解析时间戳并去除毫秒
  350. let timestamp = new Date(lastSeenAt);
  351.  
  352. // 使用Intl.DateTimeFormat格式化时间为上海时区
  353. let formatter = new Intl.DateTimeFormat('zh-CN', {
  354. timeZone: 'Asia/Shanghai',
  355. year: 'numeric',
  356. month: 'numeric',
  357. day: 'numeric',
  358. hour: 'numeric',
  359. minute: 'numeric',
  360. second: 'numeric',
  361. });
  362.  
  363. // 获取格式化后的字符串
  364. let formattedTimestamp = formatter.format(timestamp);
  365.  
  366. return formattedTimestamp;
  367. }
  368.  
  369. // 添加用户升级进度总结
  370. function summaryRequired(required, current, translateStat) {
  371. let summary = '<strong>升级进度:</strong><br>';
  372. let allMet = true;
  373.  
  374. for (const stat in required) {
  375. if (required.hasOwnProperty(stat) && current.hasOwnProperty(stat)) {
  376. const reqValue = required[stat];
  377. const curValue = current[stat] || 0; // 使用 || 0 确保未定义的情况下使用0
  378. if (curValue < reqValue) {
  379. allMet = false;
  380. const diff = reqValue - curValue;
  381. summary += `${translateStat(stat)}: <span style="color: red;"> ${curValue} < ${reqValue},还差 ${diff}</span><br>`;
  382. } else {
  383. // 如果当前值满足或超过了要求值,也打印出来,但使用不同的颜色或提示信息
  384. summary += `${translateStat(stat)}: <span style="color: green;"> ${curValue} ${reqValue},已合格</span><br>`;
  385. }
  386. }
  387. }
  388.  
  389. if (allMet) {
  390. return "恭喜您!所有项次都已达到合格标准。<br>" + summary;
  391. } else {
  392. return summary;
  393. }
  394. }
  395.  
  396. // 添加拖动功能
  397. function addDraggableFeature(element) {
  398. let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  399.  
  400. const dragMouseDown = function(e) {
  401. // 检查事件的目标是否是输入框,按钮或其他可以忽略拖动逻辑的元素
  402. if (e.target.tagName.toUpperCase() === 'INPUT' || e.target.tagName.toUpperCase() === 'TEXTAREA' || e.target.tagName.toUpperCase() === 'BUTTON') {
  403. return; // 如果是,则不执行拖动逻辑
  404. }
  405.  
  406. e = e || window.event;
  407. e.preventDefault();
  408. pos3 = e.clientX;
  409. pos4 = e.clientY;
  410. document.onmouseup = closeDragElement;
  411. document.onmousemove = elementDrag;
  412. };
  413.  
  414. const elementDrag = function(e) {
  415. e = e || window.event;
  416. e.preventDefault();
  417. pos1 = pos3 - e.clientX;
  418. pos2 = pos4 - e.clientY;
  419. pos3 = e.clientX;
  420. pos4 = e.clientY;
  421.  
  422. element.style.top = (element.offsetTop - pos2) + "px";
  423. element.style.left = (element.offsetLeft - pos1) + "px";
  424. // 为了避免与拖动冲突,在此移除bottom和right样式
  425. element.style.bottom = '';
  426. element.style.right = '';
  427. };
  428.  
  429. const closeDragElement = function() {
  430. document.onmouseup = null;
  431. document.onmousemove = null;
  432. // 在拖动结束时更新拖动状态
  433. EventHandler.handleDragEnd();
  434. };
  435.  
  436. element.onmousedown = dragMouseDown;
  437. }
  438.  
  439. const init = () => {
  440. StyleManager.injectStyles();
  441. UIManager.initPopup();
  442. addDraggableFeature(document.getElementById('linuxDoLevelPopup')); // 确保已设置该ID
  443. UIManager.togglePopupSize(); // 初始最小化
  444. };
  445.  
  446. init();
  447.  
  448. })();