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

  1. // ==UserScript==
  2. // @name Linux do Level Enhanced
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0.2
  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
  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.invited_by) {
  171. content += `<strong>邀请人:</strong>${userDetail.invited_by.username}<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.minimizeButton.textContent = '展开';
  212. this.popup.classList.add('breath-animation');
  213. }
  214.  
  215. // 自动校正窗口位置
  216. addDraggableFeature(this.popup);
  217. const windowWidth = window.innerWidth;
  218. const windowHeight = window.innerHeight;
  219. const popupWidth = this.popup.offsetWidth;
  220. const popupHeight = this.popup.offsetHeight;
  221. const popupTop = parseInt(this.popup.style.top);
  222. const popupLeft = parseInt(this.popup.style.left);
  223.  
  224. // 初始化新的位置
  225. let newTop = popupTop;
  226. let newLeft = popupLeft;
  227.  
  228. // 上下边界同时检查
  229. newTop = Math.min(Math.max(70, popupTop), windowHeight - popupHeight);
  230.  
  231. // 左右边界同时检查
  232. newLeft = Math.min(Math.max(5, popupLeft), windowWidth - popupWidth - 20);
  233.  
  234. this.popup.style.top = newTop + 'px';
  235. this.popup.style.left = newLeft + 'px';
  236. },
  237.  
  238. displayError: function(message) {
  239. this.content.innerHTML = `<strong>错误:</strong>${message}`;
  240. },
  241.  
  242. translateStat: function(stat) {
  243. const translations = {
  244. 'days_visited': '访问天数',
  245. 'likes_given': '给出的赞',
  246. 'likes_received': '收到的赞',
  247. 'post_count': '帖子数量',
  248. 'posts_read_count': '已读帖子',
  249. 'topics_entered': '已读主题',
  250. 'time_read': '阅读时间(秒)'
  251. };
  252. return translations[stat] || stat;
  253. }
  254. };
  255.  
  256. const EventHandler = {
  257. handleSearch: async function() {
  258. const username = UIManager.searchBox.value.trim();
  259. if (!username) return;
  260.  
  261. try {
  262. const aboutData = await DataManager.fetchAboutData();
  263. const summaryData = await DataManager.fetchSummaryData(username);
  264. const userData = await DataManager.fetchUserData(username);
  265. if (summaryData && userData && aboutData) {
  266. UIManager.updatePopupContent(summaryData.user_summary, summaryData.users ? summaryData.users[0] : { 'trust_level': 0 }, userData.user, aboutData.about.stats);
  267. }
  268. } catch (error) {
  269. console.error(error);
  270. }
  271. },
  272. // 更新拖动状态
  273. handleDragEnd: function() {
  274. UIManager.updateDragStatus(true);
  275. }
  276. };
  277.  
  278. // 添加时间格式化
  279. function formatTimestamp(lastSeenAt) {
  280. // 解析时间戳并去除毫秒
  281. let timestamp = new Date(lastSeenAt);
  282.  
  283. // 使用Intl.DateTimeFormat格式化时间为上海时区
  284. let formatter = new Intl.DateTimeFormat('zh-CN', {
  285. timeZone: 'Asia/Shanghai',
  286. year: 'numeric',
  287. month: 'numeric',
  288. day: 'numeric',
  289. hour: 'numeric',
  290. minute: 'numeric',
  291. second: 'numeric',
  292. });
  293.  
  294. // 获取格式化后的字符串
  295. let formattedTimestamp = formatter.format(timestamp);
  296.  
  297. return formattedTimestamp;
  298. }
  299.  
  300. // 添加用户升级进度总结
  301. function summaryRequired(required, current, translateStat) {
  302. let summary = '';
  303. let allMet = true;
  304.  
  305. for (const stat in required) {
  306. if (required.hasOwnProperty(stat) && current.hasOwnProperty(stat)) {
  307. const reqValue = required[stat];
  308. const curValue = current[stat] || 0; // 使用 || 0 确保未定义的情况下使用0
  309. if (curValue < reqValue) {
  310. allMet = false;
  311. const diff = reqValue - curValue;
  312. summary += `${translateStat(stat)}: <span style="color: red;"> ${curValue} < ${reqValue},还差 ${diff}</span><br>`;
  313. } else {
  314. // 如果当前值满足或超过了要求值,也打印出来,但使用不同的颜色或提示信息
  315. summary += `${translateStat(stat)}: <span style="color: green;"> ${curValue} ${reqValue},已合格</span><br>`;
  316. }
  317. }
  318. }
  319.  
  320. if (allMet) {
  321. return "恭喜您!所有项次都已达到合格标准。<br>" + summary;
  322. } else {
  323. return summary;
  324. }
  325. }
  326.  
  327. // 添加拖动功能
  328. function addDraggableFeature(element) {
  329. let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  330.  
  331. const dragMouseDown = function(e) {
  332. // 检查事件的目标是否是输入框,按钮或其他可以忽略拖动逻辑的元素
  333. if (e.target.tagName.toUpperCase() === 'INPUT' || e.target.tagName.toUpperCase() === 'TEXTAREA' || e.target.tagName.toUpperCase() === 'BUTTON') {
  334. return; // 如果是,则不执行拖动逻辑
  335. }
  336.  
  337. e = e || window.event;
  338. e.preventDefault();
  339. pos3 = e.clientX;
  340. pos4 = e.clientY;
  341. document.onmouseup = closeDragElement;
  342. document.onmousemove = elementDrag;
  343. };
  344.  
  345. const elementDrag = function(e) {
  346. e = e || window.event;
  347. e.preventDefault();
  348. pos1 = pos3 - e.clientX;
  349. pos2 = pos4 - e.clientY;
  350. pos3 = e.clientX;
  351. pos4 = e.clientY;
  352.  
  353. element.style.top = (element.offsetTop - pos2) + "px";
  354. element.style.left = (element.offsetLeft - pos1) + "px";
  355. // 为了避免与拖动冲突,在此移除bottom和right样式
  356. element.style.bottom = '';
  357. element.style.right = '';
  358. };
  359.  
  360. const closeDragElement = function() {
  361. document.onmouseup = null;
  362. document.onmousemove = null;
  363. // 在拖动结束时更新拖动状态
  364. EventHandler.handleDragEnd();
  365. };
  366.  
  367. element.onmousedown = dragMouseDown;
  368. }
  369.  
  370. const init = () => {
  371. StyleManager.injectStyles();
  372. UIManager.initPopup();
  373. addDraggableFeature(document.getElementById('linuxDoLevelPopup')); // 确保已设置该ID
  374. UIManager.togglePopupSize(); // 初始最小化
  375. };
  376.  
  377. init();
  378.  
  379. })();