NodeSeek X

【原NodeSeek增强】自动签到、无缝翻页帖子评论、快捷回复、代码高亮、屏蔽用户、屏蔽帖子、楼主低等级提醒

当前为 2024-04-16 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name NodeSeek X
  3. // @namespace http://www.nodeseek.com/
  4. // @version 0.3-beta.7
  5. // @description 【原NodeSeek增强】自动签到、无缝翻页帖子评论、快捷回复、代码高亮、屏蔽用户、屏蔽帖子、楼主低等级提醒
  6. // @author dabao
  7. // @match *://www.nodeseek.com/*
  8. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAQAAADZc7J/AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAACz0lEQVR4Ae3B32tVdQAA8M85u7aVHObmzJVD0+ssiphstLEM62CBlCBEIAYhUoGGD/kiRUo+9CIEElFZgZJFSApBVhCUX2WFrVQKf5Qy26SgdK4pN7eZu+cbtyfJ/gLx83HD9SAhlEyXupiPhUSTeonRfNw1ws2aRJeN5jHcolFhJJ9M8Zj99piDTnv12SjzfzIb9dmrC7Pttt8ykjDVLsu8ZZ1GH1oqeDofJLtJh4fMEw3Y72jlCuEO2+W+sNJFr3vOZ1YIi8NIGA29hDWhGgZDJ2Rt2ZvZSBazmMUsZsPZ1qwVQmcYDNWwhtAbRsNIWJx6WLPDfgxNVkm9nR8hm+XduLba7F9RtcXztmUzyY/YJrUqNPvBYc0eSS3CwXxMl4WG7CarsyEuvU2HOkRNujSw3PosxR6DFurKxx3E/akFohPo0aDfEO61os5LdrtLVWG1TzxokifdiSH9GnTjuGhBqsWE39GOo3kVi8wsmeVW00SJ200zA9r0kFcdQzv+MKElVW/S+L5EE86pmUth3BV/SzCOCUjMVXMWzfsSYybVl1SlSlESkagpuOI1nzshFX1gyAF1UKhJEKOkJFVNXVBv+pJoBK1qBkh86z1/SaR+9o5zEgoDaloxsiSart6F1Bkl83ESHWEKvvEbqZJETaokgSH9hCk6cBLtSs6kDqEb/cZ0K+MnO0X/VdhRGUBZjzH9uA+HUl+a0BvmO+J7bVZSKWz1kehqhfe9oWalNoccDmW9JnyV+toxsy3PK3aY9Gx4gMp567ziV4WawpCXra+MEhZ5xqTtecVycxzXlxA22OK4ZYbt9LjvrM5PkNUp6zVPdNpBv1QKwt126Paxp8zwqXu8kG8pYZdHlT2Rvxo2aVG2ObyYn65UnXLKVULZZrP02ZRfCms1OmAXCSHRYqrLzuZFaDFV6s/8omuERs0Kl/LzITVTvTHDeXTD9eAftAsSYhXYOWUAAAAASUVORK5CYII=
  9. // @require https://cdn.staticfile.net/layui/2.9.8/layui.min.js
  10. // @resource highlightStyle https://cdn.staticfile.net/highlight.js/11.9.0/styles/atom-one-light.min.css
  11. // @resource highlightStyle_dark https://cdn.staticfile.net/highlight.js/11.9.0/styles/atom-one-dark.min.css
  12. // @grant GM_xmlhttpRequest
  13. // @grant GM_getValue
  14. // @grant GM_setValue
  15. // @grant GM_deleteValue
  16. // @grant GM_notification
  17. // @grant GM_registerMenuCommand
  18. // @grant GM_unregisterMenuCommand
  19. // @grant GM_getResourceURL
  20. // @grant GM_addElement
  21. // @grant GM_addStyle
  22. // @grant GM_openInTab
  23. // @grant unsafeWindow
  24. // @run-at document-end
  25. // @license GPL-3.0 License
  26. // @supportURL https://www.nodeseek.com/post-36263-1
  27. // @homepageURL https://www.nodeseek.com/post-36263-1
  28. // ==/UserScript==
  29.  
  30. (function () {
  31. 'use strict';
  32.  
  33. const { version, author, name, icon } = GM_info.script;
  34.  
  35. const BASE_URL = "https://www.nodeseek.com";
  36.  
  37. const util = {
  38. clog(c) {
  39. console.group(`%c %c [${name}]-v${version} by ${author}`, `background:url(${icon}) center center no-repeat;background-size:12px;padding:3px`, "");
  40. console.log(c);
  41. console.groupEnd();
  42. },
  43. getValue(name) {
  44. return GM_getValue(name);
  45. },
  46. setValue(name, value) {
  47. GM_setValue(name, value);
  48. },
  49. sleep(time) {
  50. return new Promise((resolve) => setTimeout(resolve, time));
  51. },
  52. addStyle(id, tag, css) {
  53. tag = tag || 'style';
  54. let doc = document, styleDom = doc.head.querySelector(`#${id}`);
  55. if (styleDom) return;
  56. let style = doc.createElement(tag);
  57. style.rel = 'stylesheet';
  58. style.id = id;
  59. tag === 'style' ? style.innerHTML = css : style.href = css;
  60. doc.head.appendChild(style);
  61. },
  62. removeStyle(id, tag) {
  63. tag = tag || 'style';
  64. let doc = document, styleDom = doc.head.querySelector(`#${id}`);
  65. if (styleDom) { doc.head.removeChild(styleDom) };
  66. },
  67. getAttrsByPrefix(element, prefix) {
  68. const attributes = element.attributes;
  69. let matchingAttributes = {};
  70. for (let attribute of attributes) {
  71. const attributeName = attribute.name;
  72. const attributeValue = attribute.value;
  73.  
  74. if (attributeName.startsWith(prefix)) {
  75. matchingAttributes[attributeName] = attributeValue;
  76. }
  77. }
  78. return matchingAttributes;
  79. },
  80. data(element, key, value) {
  81. if (arguments.length < 2) {
  82. return undefined;
  83. }
  84. if (value != undefined) {
  85. element.dataset[key] = value;
  86. }
  87. return element.dataset[key];
  88. },
  89. async post(url, data, headers, responseType = 'json') {
  90. url = !url.startsWith("http") ? BASE_URL + url : url;
  91. return this.fetchData(url, 'POST', data, headers, responseType);
  92. },
  93. async get(url, headers, responseType = 'json') {
  94. url = !url.startsWith("http") ? BASE_URL + url : url;
  95. return this.fetchData(url, 'GET', null, headers, responseType);
  96. },
  97. async fetchData(url, method, data, headers, responseType) {
  98. const options = {
  99. method: method,
  100. headers: headers
  101. };
  102. if (data) {
  103. if (typeof data === 'object') {
  104. data = JSON.stringify(data);
  105. }
  106. options.body = data;
  107. }
  108. const response = await fetch(url, options);
  109. return handleResponse(response, responseType);
  110. async function handleResponse(response, responseType) {
  111. const responseHandlers = {
  112. 'json': () => response.json(),
  113. 'text': () => response.text(),
  114. 'stream': () => response.body,
  115. 'formData': () => response.formData(),
  116. 'arrayBuffer': () => response.arrayBuffer()
  117. };
  118. const handler = responseHandlers[responseType];
  119. if (!handler) {
  120. throw new Error('不支持的响应类型');
  121. }
  122. return await handler();
  123. }
  124. },
  125. getCurrentDate() {
  126. const localTimezoneOffset = (new Date()).getTimezoneOffset();
  127. const beijingOffset = 8 * 60;
  128. const beijingTime = new Date(Date.now() + (localTimezoneOffset + beijingOffset) * 60 * 1000);
  129. const timeNow = `${beijingTime.getFullYear()}/${(beijingTime.getMonth() + 1)}/${beijingTime.getDate()}`;
  130. return timeNow;
  131. },
  132. createElement(tagName, options = {}, childrens = [], doc = document, namespace = null) {
  133. if (Array.isArray(options)) {
  134. if (childrens.length !== 0) {
  135. throw new Error("If options is an array, childrens should not be provided.");
  136. }
  137. childrens = options;
  138. options = {};
  139. }
  140.  
  141. const { staticClass = '', dynamicClass = '', attrs = {}, on = {} } = options;
  142.  
  143. const ele = namespace ? doc.createElementNS(namespace, tagName) : doc.createElement(tagName);
  144.  
  145. if (staticClass) {
  146. staticClass.split(' ').forEach(cls => ele.classList.add(cls.trim()));
  147. }
  148. if (dynamicClass) {
  149. dynamicClass.split(' ').forEach(cls => ele.classList.add(cls.trim()));
  150. }
  151.  
  152. Object.entries(attrs).forEach(([key, value]) => {
  153. if (key === 'style' && typeof value === 'object') {
  154. Object.entries(value).forEach(([styleKey, styleValue]) => {
  155. ele.style[styleKey] = styleValue;
  156. });
  157. } else {
  158. if (value !== undefined) ele.setAttribute(key, value);
  159. }
  160. });
  161.  
  162. Object.entries(on).forEach(([event, handler]) => {
  163. ele.addEventListener(event, handler);
  164. });
  165.  
  166. childrens.forEach(child => {
  167. if (typeof child === 'string') {
  168. child = doc.createTextNode(child);
  169. }
  170. ele.appendChild(child);
  171. });
  172.  
  173. return ele;
  174. }
  175.  
  176. };
  177.  
  178. const opts = {
  179. post: {
  180. pathPattern: /^\/(categories\/|page|award|search|$)/,
  181. scrollThreshold: 200,
  182. nextPagerSelector: '.nsk-pager a.pager-next',
  183. postListSelector: 'ul.post-list',
  184. topPagerSelector: 'div.nsk-pager.pager-top',
  185. bottomPagerSelector: 'div.nsk-pager.pager-bottom',
  186. },
  187. comment: {
  188. pathPattern: /^\/post-/,
  189. scrollThreshold: 690,
  190. nextPagerSelector: '.nsk-pager a.pager-next',
  191. postListSelector: 'ul.comments',
  192. topPagerSelector: 'div.nsk-pager.post-top-pager',
  193. bottomPagerSelector: 'div.nsk-pager.post-bottom-pager',
  194. },
  195. setting: {
  196. SETTING_SIGN_IN_STATUS: 'setting_sign_in_status',
  197. SETTING_SIGN_IN_LAST_DATE: 'setting_sign_in_last_date',
  198. SETTING_SIGN_IN_IGNORE_DATE: 'setting_sign_in_ignore_date'
  199. }
  200. };
  201. layui.use(function () {
  202. let layer = layui.layer,
  203. $ = layui.jquery;
  204. const message = {
  205. info: (text) => message.__msg(text, { "background-color": "#4D82D6" }),
  206. success: (text) => message.__msg(text, { "background-color": "#57BF57" }),
  207. warning: (text) => message.__msg(text, { "background-color": "#D6A14D" }),
  208. error: (text) => message.__msg(text, { "background-color": "#E1715B" }),
  209. __msg: (text, style) => { let index = layer.msg(text, { offset: 't', area: ['100%', 'auto'], anim: 'slideDown' }); layer.style(index, Object.assign({ opacity: 0.9 }, style)); }
  210. };
  211.  
  212. const main = {
  213. // 初始化配置数据
  214. initValue() {
  215. const value = [
  216. { name: opts.setting.SETTING_SIGN_IN_STATUS, defaultValue: 0 },
  217. { name: opts.setting.SETTING_SIGN_IN_LAST_DATE, defaultValue: '1753/1/1' },
  218. { name: opts.setting.SETTING_SIGN_IN_IGNORE_DATE, defaultValue: '1753/1/1' }
  219. ];
  220. this.upgradeConfig();
  221. value.forEach((v) => util.getValue(v.name) === undefined && util.setValue(v.name, v.defaultValue));
  222. },
  223. // 升级配置项
  224. upgradeConfig() {
  225. const upgradeConfItem = (oldConfKey, newConfKey) => {
  226. if (util.getValue(oldConfKey) && util.getValue(newConfKey) === undefined) {
  227. util.clog(`升级配置项 ${oldConfKey} ${newConfKey}`);
  228. util.setValue(newConfKey, util.getValue(oldConfKey));
  229. GM_deleteValue(oldConfKey);
  230. }
  231. };
  232. upgradeConfItem('menu_signInTime', opts.setting.SETTING_SIGN_IN_LAST_DATE);
  233. },
  234. loginStatus: false,
  235. //检查是否登陆
  236. checkLogin() {
  237. if (unsafeWindow.meCard && unsafeWindow.meCard.logined) {
  238. this.loginStatus = true;
  239. util.clog(`当前登录用户 ${unsafeWindow.meCard.user.member_name} (ID ${unsafeWindow.meCard.user.member_id})`);
  240. }
  241. },
  242. // 自动签到
  243. autoSignIn(rand) {
  244. if (!this.loginStatus) return
  245. if (util.getValue(opts.setting.SETTING_SIGN_IN_STATUS) === 0) return;
  246.  
  247. rand = rand || (util.getValue(opts.setting.SETTING_SIGN_IN_STATUS) === 1);
  248.  
  249. let timeNow = util.getCurrentDate(),
  250. timeOld = util.getValue(opts.setting.SETTING_SIGN_IN_LAST_DATE);
  251. if (!timeOld || timeOld != timeNow) { // 是新的一天
  252. util.setValue(opts.setting.SETTING_SIGN_IN_LAST_DATE, timeNow); // 写入签到时间以供后续比较
  253. this.signInRequest(rand);
  254. }
  255. },
  256. // 重新签到
  257. reSignIn() {
  258. if (!this.loginStatus) return;
  259. if (util.getValue(opts.setting.SETTING_SIGN_IN_STATUS) === 0) {
  260. unsafeWindow.mscAlert('提示', this.getMenuStateText(this._menus[0], 0) + ' 状态时不支持重新签到!');
  261. return;
  262. }
  263.  
  264. util.setValue(opts.setting.SETTING_SIGN_IN_LAST_DATE, '1753/1/1');
  265. location.reload();
  266. },
  267. addSignTips() {
  268. if (!this.loginStatus) return
  269. if (util.getValue(opts.setting.SETTING_SIGN_IN_STATUS) !== 0) return;
  270.  
  271. const timeNow = util.getCurrentDate();
  272. const { SETTING_SIGN_IN_IGNORE_DATE, SETTING_SIGN_IN_LAST_DATE } = opts.setting;
  273. const timeIgnore = util.getValue(SETTING_SIGN_IN_IGNORE_DATE);
  274. const timeOld = util.getValue(SETTING_SIGN_IN_LAST_DATE);
  275.  
  276. if (timeNow === timeIgnore || timeNow === timeOld) return;
  277.  
  278. const _this = this;
  279. let tip = util.createElement("div", { staticClass: 'nsplus-tip' });
  280. let tip_p = util.createElement('p');
  281. tip_p.innerHTML = '今天你还没有签到哦!&emsp;【<a class="sign_in_btn" data-rand="true" href="javascript:;">随机抽个鸡腿</a>】&emsp;【<a class="sign_in_btn" data-rand="false" href="javascript:;">只要5个鸡腿</a>】&emsp;【<a id="sign_in_ignore" href="javascript:;">今天不再提示</a>】';
  282. tip.appendChild(tip_p);
  283. tip.querySelectorAll('.sign_in_btn').forEach(function (item) {
  284. item.addEventListener("click", function (e) {
  285. const rand = util.data(this, 'rand');
  286. _this.signInRequest(rand);
  287. tip.remove();
  288. util.setValue(SETTING_SIGN_IN_LAST_DATE, timeNow); // 写入签到时间以供后续比较
  289. })
  290. });
  291. tip.querySelector('#sign_in_ignore').addEventListener("click", function (e) {
  292. tip.remove();
  293. util.setValue(SETTING_SIGN_IN_IGNORE_DATE, timeNow);
  294. });
  295.  
  296. document.querySelector('#nsk-frame').before(tip);
  297. },
  298. signInRequest(rand) {
  299. util.post('/api/attendance?random=' + (rand || false), {}, { "Content-Type": "application/json" }, 'json').then(function (json) {
  300. if (json.success) {
  301. message.success('签到成功!今天午饭+' + json.gain + '个鸡腿; 积攒了' + json.current + '个鸡腿了');
  302. }
  303. else {
  304. message.info(json.message);
  305. }
  306. }).catch(function (err) {
  307. util.clog(err)
  308. });
  309. util.clog(`[${name}] 签到完成`);
  310. },
  311. is_show_quick_comment: false,
  312. quickComment() {
  313. if (!this.loginStatus || !opts.comment.pathPattern.test(location.pathname)) return;
  314.  
  315. const _this = this;
  316.  
  317.  
  318. const onClick = (e) => {
  319. if (_this.is_show_quick_comment) {
  320. return;
  321. }
  322. e.preventDefault();
  323.  
  324. const mdEditor = document.querySelector('.md-editor');
  325. const clientHeight = document.documentElement.clientHeight, clientWidth = document.documentElement.clientWidth;
  326. const mdHeight = mdEditor.clientHeight, mdWidth = mdEditor.clientWidth;
  327. const top = (clientHeight / 2) - (mdHeight / 2), left = (clientWidth / 2) - (mdWidth / 2);
  328. mdEditor.style.cssText = `position: fixed; top: ${top}px; left: ${left}px; margin: 30px 0px; width: 100%; max-width: ${mdWidth}px; z-index: 999;`;
  329. const moveEl = mdEditor.querySelector('.tab-select.window_header');
  330. moveEl.style.cursor = "move";
  331. moveEl.addEventListener('mousedown', startDrag);
  332. addEditorCloseButton();
  333. _this.is_show_quick_comment = true;
  334. };
  335. const commentDiv = document.querySelector('#fast-nav-button-group #back-to-parent').cloneNode(true);
  336. commentDiv.id = 'back-to-comment';
  337. commentDiv.innerHTML = '<svg class="iconpark-icon" style="width: 24px; height: 24px;"><use href="#comments"></use></svg>';
  338. commentDiv.addEventListener("click", onClick);
  339. document.querySelector('#back-to-parent').before(commentDiv);
  340. document.querySelectorAll('div.comment-menu > div:nth-last-child(1),div.comment-menu > div:nth-last-child(2) ').forEach(function (item) { item.addEventListener("click", onClick, true); });
  341.  
  342. function addEditorCloseButton() {
  343. const fullScreenToolbar = document.querySelector('#editor-body .window_header > :last-child');
  344. const cloneToolbar = fullScreenToolbar.cloneNode(true);
  345. cloneToolbar.setAttribute('title', '关闭');
  346. cloneToolbar.querySelector('span').classList.replace('i-icon-full-screen-one', 'i-icon-close');
  347. cloneToolbar.querySelector('span').innerHTML = '<svg width="16" height="16" viewBox="0 0 48 48" fill="none"><path d="M8 8L40 40" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"></path><path d="M8 40L40 8" stroke="currentColor" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"></path></svg>';
  348. cloneToolbar.addEventListener("click", function (e) {
  349. const mdEditor = document.querySelector('.md-editor');
  350. mdEditor.style = "";
  351. const moveEl = mdEditor.querySelector('.tab-select.window_header');
  352. moveEl.style.cursor = "";
  353. moveEl.removeEventListener('mousedown', startDrag);
  354.  
  355. this.remove();
  356. _this.is_show_quick_comment = false;
  357. });
  358. fullScreenToolbar.after(cloneToolbar);
  359. }
  360. function startDrag(event) {
  361. if (event.button !== 0) return;
  362.  
  363. const draggableElement = document.querySelector('.md-editor');
  364. const parentMarginTop = parseInt(window.getComputedStyle(draggableElement).marginTop);
  365. const initialX = event.clientX - draggableElement.offsetLeft;
  366. const initialY = event.clientY - draggableElement.offsetTop + parentMarginTop;
  367. document.onmousemove = function (event) {
  368. const newX = event.clientX - initialX;
  369. const newY = event.clientY - initialY;
  370. draggableElement.style.left = newX + 'px';
  371. draggableElement.style.top = newY + 'px';
  372. };
  373. document.onmouseup = function () {
  374. document.onmousemove = null;
  375. document.onmouseup = null;
  376. };
  377. }
  378. },
  379.  
  380. //新窗口打开帖子
  381. openPostInNewTab() {
  382. if (!opts.post.pathPattern.test(location.pathname)) return;
  383. if (document.querySelector('a[href^="/post-"]')) {
  384. document.querySelectorAll('a[href^="/post-"]').forEach(function (item) {
  385. if (item.classList.contains("pager-prev") || item.classList.contains("pager-pos") || item.classList.contains("pager-next")) {
  386. return;
  387. }
  388. item.target || (item.target = "_blank");
  389. });
  390. }
  391. },
  392. //自动点击跳转页链接
  393. autoJump() {
  394. if (!/^\/jump/.test(location.pathname)) return;
  395. document.querySelector('.btn').click();
  396. },
  397. blockPost(ele) {
  398. ele = ele || document;
  399. ele.querySelectorAll('.post-title>a[href]').forEach(function (item) {
  400. if (item.textContent.toLowerCase().includes("__keys__")) {
  401. item.closest(".post-list-item").classList.add('blocked-post')
  402. }
  403. });
  404. },
  405. //屏蔽用户
  406. blockMemberDOMInsert() {
  407. if (!this.loginStatus) return;
  408.  
  409. const _this = this;
  410. Array.from(document.querySelectorAll(".post-list .post-list-item,.content-item")).forEach((function (t, n) {
  411. var r = t.querySelector('.avatar-normal');
  412. r.addEventListener("click", (function (n) {
  413. n.preventDefault();
  414. let intervalId = setInterval(async () => {
  415. const userCard = document.querySelector('div.user-card.hover-user-card');
  416. const pmButton = document.querySelector('div.user-card.hover-user-card a.btn');
  417. if (userCard && pmButton) {
  418. clearInterval(intervalId);
  419. const dataVAttrs = util.getAttrsByPrefix(userCard, 'data-v');
  420. const userName = userCard.querySelector('a.Username').textContent;
  421. dataVAttrs.style = "float:left; background-color:rgba(0,0,0,.3)";
  422. const blockBtn = util.createElement("a", {
  423. staticClass: "btn", attrs: dataVAttrs, on: {
  424. click: function (e) {
  425. e.preventDefault();
  426. unsafeWindow.mscConfirm(`确定要屏蔽“${userName}”吗?`, '你可以在本站的 设置=>屏蔽用户 中解除屏蔽', function () { blockMember(userName); })
  427. }
  428. }
  429. }, ["屏蔽"]);
  430. pmButton.after(blockBtn);
  431. }
  432. }, 50);
  433. }))
  434. }))
  435. function blockMember(userName) {
  436. util.post("/api/block-list/add", { "block_member_name": userName }, { "Content-Type": "application/json" }, '').then(function (data) {
  437. if (data.success) {
  438. let msg = '屏蔽用户【' + userName + '】成功!';
  439. unsafeWindow.mscAlert(msg);
  440. util.clog(msg);
  441. } else {
  442. let msg = '屏蔽用户【' + userName + '】失败!' + data.message;
  443. unsafeWindow.mscAlert(msg);
  444. util.clog(msg);
  445. }
  446. }).catch(function (err) {
  447. util.clog(err);
  448. });
  449. }
  450. },
  451. addImageSlide() {
  452. if (!opts.comment.pathPattern.test(location.pathname)) return;
  453.  
  454. const images = document.querySelectorAll('.nsk-post .post-content img:not([class])');
  455. if (images.length === 0) return;
  456.  
  457. images.forEach(function (image, i) {
  458. const newImg = image.cloneNode(true);
  459. image.parentNode.replaceChild(newImg, image);
  460. newImg.addEventListener('click', function (e) {
  461. e.preventDefault();
  462. const imgArr = Array.from(document.querySelectorAll('.nsk-post .post-content img:not([class])'));
  463. const clickedIndex = imgArr.indexOf(this);
  464. const photoData = imgArr.map((img, i) => ({ alt: img.alt, pid: i + 1, src: img.src }));
  465. layer.photos({ photos: { "title": "图片预览", "start": clickedIndex, "data": photoData } });
  466. }, true);
  467. });
  468. },
  469. addLevelTag() {//添加等级标签
  470. if (!this.loginStatus) return;
  471. if (!opts.comment.pathPattern.test(location.pathname)) return;
  472.  
  473. this.getUserInfo(unsafeWindow.__config__.postData.op.uid).then((user) => {
  474. let warningInfo = '';
  475. const daysDiff = Math.floor((new Date() - new Date(user.created_at)) / (1000 * 60 * 60 * 24));
  476. if (daysDiff < 30) {
  477. warningInfo = `⚠️`;
  478. }
  479. console.log(user);
  480. const span = util.createElement("span", { staticClass: `nsk-badge role-tag user-level user-lv${user.rank}`, on: { mouseenter: function (e) { layer.tips(`注册 <span class="layui-badge">${daysDiff}</span> 天;帖子 ${user.nPost};评论 ${user.nComment}`, this, { tips: 3, time: 0 }); }, mouseleave: function (e) { layer.closeAll(); } } }, [util.createElement("span", [`${warningInfo}Lv ${user.rank}`])]);
  481.  
  482. const authorLink = document.querySelector('#nsk-body .nsk-post .nsk-content-meta-info .author-info>a');
  483. if (authorLink != null) {
  484. authorLink.after(span);
  485. }
  486. });
  487. },
  488. getUserInfo(uid) {
  489. return new Promise((resolve, reject) => {
  490. util.get(`/api/account/getInfo/${uid}`, {}, 'json').then((data) => {
  491. if (!data.success) {
  492. util.clog(data);
  493. return;
  494. }
  495. resolve(data.detail);
  496. }).catch((err) => reject(err));
  497. })
  498. },
  499. userCardEx() {
  500. if (!this.loginStatus) return;
  501.  
  502. const updateNotificationElement = (element, href, iconHref, text, count) => {
  503. element.querySelector("a").setAttribute("href", `${href}`);
  504. element.querySelector("a > svg > use").setAttribute("href", `${iconHref}`)
  505. element.querySelector("a > :nth-child(2)").textContent = `${text} `;
  506. element.querySelector("a > :last-child").textContent = count;
  507. if (count > 0) {
  508. element.querySelector("a > :last-child").classList.add("notify-count");
  509. }
  510. return element;
  511. };
  512.  
  513. const userCard = document.querySelector(".user-card .user-stat");
  514. const lastElement = userCard.querySelector(".stat-block:first-child > :last-child");
  515. const unViewedCount = unsafeWindow.__config__.user.unViewedCount;
  516.  
  517. if (lastElement.querySelector("a > .notify-count:last-child")) {
  518. lastElement.querySelector("a > .notify-count:last-child").classList.remove("notify-count");
  519. }
  520.  
  521. const atMeElement = lastElement.cloneNode(true);
  522. updateNotificationElement(atMeElement, "/notification#/atMe", "#at-sign", "我", unViewedCount.atMe);
  523. lastElement.after(atMeElement);
  524.  
  525. const msgElement = lastElement.cloneNode(true);
  526. updateNotificationElement(msgElement, "/notification#/message?mode=list", "#envelope-one", "私信", unViewedCount.message);
  527. userCard.querySelector(".stat-block:last-child").append(msgElement);
  528.  
  529. updateNotificationElement(lastElement, "/notification#/reply", "#remind-6nce9p47", "回复", unViewedCount.reply);
  530. },
  531. // 自动翻页
  532. autoLoading() {
  533. let opt = {};
  534. if (opts.post.pathPattern.test(location.pathname)) { opt = opts.post; }
  535. else if (opts.comment.pathPattern.test(location.pathname)) { opt = opts.comment; }
  536. else { return; }
  537. let is_requesting = false;
  538. let _this = this;
  539. this.windowScroll(function (direction, e) {
  540. if (direction === 'down') { // 下滑才准备翻页
  541. let scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
  542. if (document.documentElement.scrollHeight <= document.documentElement.clientHeight + scrollTop + opt.scrollThreshold && !is_requesting) {
  543. if (!document.querySelector(opt.nextPagerSelector)) return;
  544. let nextUrl = document.querySelector(opt.nextPagerSelector).attributes.href.value;
  545. is_requesting = true;
  546. util.get(nextUrl, {}, 'text').then(function (data) {
  547. let doc = new DOMParser().parseFromString(data, "text/html");
  548. _this.blockPost(doc);//过滤帖子
  549. document.querySelector(opt.postListSelector).append(...doc.querySelector(opt.postListSelector).childNodes);
  550. document.querySelector(opt.topPagerSelector).innerHTML = doc.querySelector(opt.topPagerSelector).innerHTML;
  551. document.querySelector(opt.bottomPagerSelector).innerHTML = doc.querySelector(opt.bottomPagerSelector).innerHTML;
  552. history.pushState(null, null, nextUrl);
  553. is_requesting = false;
  554. }).catch(function (err) {
  555. is_requesting = false;
  556. util.clog(err);
  557. });
  558. }
  559. }
  560. });
  561. },
  562. // 滚动条事件
  563. windowScroll(fn1) {
  564. let beforeScrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop,
  565. fn = fn1 || function () { };
  566. setTimeout(function () { // 延时执行,避免刚载入到页面就触发翻页事件
  567. window.addEventListener('scroll', function (e) {
  568. const afterScrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop,
  569. delta = afterScrollTop - beforeScrollTop;
  570. if (delta == 0) return false;
  571. fn(delta > 0 ? 'down' : 'up', e);
  572. beforeScrollTop = afterScrollTop;
  573. }, false);
  574. }, 1000)
  575. },
  576. switchMultiState(stateName, states) {//多态顺序切换
  577. let currState = util.getValue(stateName);
  578. currState = (currState + 1) % states.length;
  579. util.setValue(stateName, currState);
  580. this.registerMenus();
  581. },
  582. getMenuStateText(menu, stateVal) {
  583. return `${menu.states[stateVal].s1} ${menu.text}(${menu.states[stateVal].s2})`;
  584. },
  585. _menus: [
  586. { name: opts.setting.SETTING_SIGN_IN_STATUS, callback: (name, states) => main.switchMultiState(name, states), accessKey: '', text: '自动签到', states: [{ s1: '❌', s2: '关闭' }, { s1: '🎲', s2: '随机🍗' }, { s1: '📌', s2: '5个🍗' }], autoClose: false },
  587. { name: 're_sign_in', callback: (name, states) => main.reSignIn(), accessKey: '', text: '🔂 重新签到', states: [] },
  588. { name: 'advanced_settings', callback: (name, states) => main.advancedSettings(), accessKey: '', text: '⚙️ 高级设置', states: [] },
  589. { name: 'feedback', callback: (name, states) => GM_openInTab('https://greasyfork.org/zh-CN/scripts/479426/feedback', { active: true, insert: true, setParent: true }), accessKey: '', text: '💬 反馈 & 建议', states: [] }
  590. ],
  591. _menuIds: [],
  592. registerMenus() {
  593. this._menuIds.forEach(function (id) {
  594. GM_unregisterMenuCommand(id);
  595. });
  596. this._menuIds = [];
  597.  
  598. const _this = this;
  599. this._menus.forEach(function (menu) {
  600. let k = menu.text;
  601. if (menu.states.length > 0) {
  602. k = _this.getMenuStateText(menu, util.getValue(menu.name));
  603. }
  604. let autoClose = menu.hasOwnProperty('autoClose') ? menu.autoClose : true;
  605. let menuId = GM_registerMenuCommand(k, function () { menu.callback(menu.name, menu.states) }, { autoClose: autoClose });
  606. menuId = menuId || k;
  607. _this._menuIds.push(menuId);
  608. });
  609. },
  610. advancedSettings() {
  611. let layerWidth = layui.device().mobile ? '100%' : '620px';
  612. layer.open({
  613. type: 1,
  614. offset: 'r',
  615. anim: 'slideLeft', // 从右往左
  616. area: [layerWidth, '100%'],
  617. scrollbar: false,
  618. shade: 0.1,
  619. shadeClose: false,
  620. btn: ["保存设置"],
  621. btnAlign: 'l',
  622. title: 'NodeSeek X 设置',
  623. id: 'setting-layer-direction-r',
  624. content: `<div class="layui-row" style="display:flex;height:100%">
  625. <div class="layui-panel layui-col-xs3 layui-col-sm3 layui-col-md3" id="demo-menu">
  626. <ul class="layui-menu" lay-filter="demo"></ul>
  627. </div>
  628. <div class="layui-col-xs9 layui-col-sm9 layui-col-md9" style="overflow-y: auto; padding-left: 10px" id="demo-content">
  629. <fieldset id="group1" class="layui-elem-field layui-field-title">
  630. <legend>基本设置</legend>
  631. </fieldset>
  632. <div style="height: 500px;">Content for Group 1</div>
  633. <fieldset id="group2" class="layui-elem-field layui-field-title">
  634. <legend>扩展设置</legend>
  635. </fieldset>
  636. <div style="height: 500px;">Content for Group 2</div>
  637. <fieldset id="group3" class="layui-elem-field layui-field-title">
  638. <legend>实验设置</legend>
  639. </fieldset>
  640. <div style="height: 500px;">Content for Group 3</div>
  641. </div>
  642. </div>
  643. <script>
  644. document.querySelectorAll('#demo-content > fieldset').forEach(function (el, i) {
  645. let li = document.createElement('li');
  646. if (i === 0) li.classList = 'layui-menu-item-checked';
  647. let div = document.createElement('div');
  648. div.classList = 'layui-menu-body-title';
  649. let a = document.createElement('a');
  650. a.href = '#' + el.id;
  651. a.textContent = el.textContent;
  652. a.addEventListener('click', aClick);
  653. li.append(div);
  654. div.append(a);
  655. document.querySelector('#demo-menu>ul').append(li);
  656. });
  657. const docContent = document.querySelector('#demo-content');
  658. docContent.addEventListener('scroll', function (e) {
  659. var scrollPos = docContent.scrollTop;
  660. console.log(scrollPos);
  661. docContent.querySelectorAll('fieldset').forEach(function (el) {
  662. var topPos = el.offsetTop - 10;
  663. if (scrollPos >= topPos) {
  664. var id = el.getAttribute('id');
  665. document.querySelectorAll('.layui-menu > li.layui-menu-item-checked').forEach(function (navItem) {
  666. navItem.classList.remove('layui-menu-item-checked');
  667. });
  668. var navItem = document.querySelector('.layui-menu > li a[href="#' + id + '"]').closest('li');
  669. navItem.classList.add('layui-menu-item-checked');
  670. }
  671. });
  672. });
  673. function aClick(e) {
  674. e.preventDefault();
  675. var id = this.getAttribute('href');
  676. var target = document.querySelector(id);
  677. docContent.scrollTo({
  678. top: target.offsetTop - 10,
  679. // behavior: 'smooth'
  680. });
  681. }
  682. <\/script>`,
  683. yes: function (index, layero, that) {
  684. layer.msg('111');
  685. layer.close(index); // 关闭弹层
  686. }
  687. });
  688. },
  689. addCodeHighlight() {
  690. const codes = document.querySelectorAll(".post-content pre code");
  691. if (codes) {
  692. codes.forEach(function (code) {
  693. const copyBtn = util.createElement("span", { staticClass: "copy-code", attrs: { title: "复制代码" }, on: { click: copyCode } }, [util.createElement("svg", { staticClass: 'iconpark-icon' }, [util.createElement("use", { attrs: { href: "#copy" } }, [], document, "http://www.w3.org/2000/svg")], document, "http://www.w3.org/2000/svg")]);
  694. code.after(copyBtn);
  695. });
  696. }
  697. function copyCode(e) {
  698. const pre = this.closest('pre');
  699. const selection = window.getSelection();
  700. const range = document.createRange();
  701. range.selectNodeContents(pre.querySelector("code"));
  702. selection.removeAllRanges();
  703. selection.addRange(range);
  704. document.execCommand('copy');
  705. selection.removeAllRanges();
  706. updateCopyButton(this);
  707. layer.tips(`复制成功`, this, { tips: 4, time: 1000 })
  708. }
  709. function updateCopyButton(ele) {
  710. ele.querySelector("use").setAttribute("href", "#check");
  711. util.sleep(1000).then(() => ele.querySelector("use").setAttribute("href", "#copy"));
  712. }
  713. },
  714. addPluginStyle() {
  715. let style = `
  716. .nsplus-tip { background-color: rgba(255, 217, 0, 0.8); border: 0px solid black; padding: 10px; text-align: center;animation: blink 5s cubic-bezier(.68,.05,.46,.96) infinite;}
  717. /* @keyframes blink{ 0%{background-color: red;} 25%{background-color: yellow;} 50%{background-color: blue;} 75%{background-color: green;} 100%{background-color: red;} } */
  718. .nsplus-tip p,.nsplus-tip p a { color: #f00 }
  719. .nsplus-tip p a:hover {color: #0ff}
  720. #back-to-comment{display:flex;}
  721. #fast-nav-button-group .nav-item-btn:nth-last-child(4){bottom:120px;}
  722. body.light-layout .post-list .post-title a:visited{color:#681da8}
  723. body.dark-layout .post-list .post-title a:visited {color:#999}
  724. .role-tag.user-level.user-lv0 {background-color: rgb(199 194 194); border: 1px solid rgb(199 194 194); color: #fafafa;}
  725. .role-tag.user-level.user-lv1 {background-color: #ff9400; border: 1px solid #ff9400; color: #fafafa;}
  726. .role-tag.user-level.user-lv2 {background-color: #ff9400; border: 1px solid #ff9400; color: #fafafa;}
  727. .role-tag.user-level.user-lv3 {background-color: #ff3a55; border: 1px solid #ff3a55; color: #fafafa;}
  728. .role-tag.user-level.user-lv4 {background-color: #ff3a55; border: 1px solid #ff3a55; color: #fafafa;}
  729. .role-tag.user-level.user-lv5 {background-color: #de00ff; border: 1px solid #de00ff; color: #fafafa;}
  730. .role-tag.user-level.user-lv6 {background-color: #de00ff; border: 1px solid #de00ff; color: #fafafa;}
  731. .role-tag.user-level.user-lv7 {background-color: #ff0000; border: 1px solid #ff0000; color: #fafafa;}
  732. .role-tag.user-level.user-lv8 {background-color: #3478f7; border: 1px solid #3478f7; color: #fafafa;}
  733.  
  734. .post-content pre { position: relative; }
  735. .post-content pre span.copy-code { position: absolute; right: .5em; top: .5em; cursor: pointer;color: #c1c7cd; }
  736. .post-content pre .iconpark-icon {width:16px;height:16px;margin:3px;}
  737. .post-content pre .iconpark-icon:hover {color:var(--link-hover-color)}
  738. .dark-layout .post-content pre code.hljs { padding: 1em !important; }
  739. `;
  740. if (document.head) {
  741. util.addStyle('nsplus-style', 'style', style);
  742. util.addStyle('layui-style', 'link', 'https://img0.520912.xyz/images/layui/css/layui.css');
  743. util.addStyle('hightlight-style', 'link', GM_getResourceURL("highlightStyle"));
  744. }
  745. },
  746. addPluginScript() {
  747. GM_addElement(document.body, 'script', {
  748. src: 'https://cdn.staticfile.net/highlight.js/11.9.0/highlight.min.js'
  749. });
  750. GM_addElement(document.body, 'script', {
  751. textContent: 'window.onload = function(){hljs.highlightAll();}'
  752. });
  753. GM_addElement(document.body, "script", { textContent: `!function(e){var t,n,d,o,i,a,r='<svg><symbol id="envelope-one" viewBox="0 0 48 48" fill="none"><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M36 16V8H4v24h8" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-width="4" stroke="currentColor" d="M12 40h32V16H12v24Z" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="m12 16 16 12 16-12" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M32 16H12v15" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M44 31V16H24" data-follow-stroke="currentColor"/></symbol><symbol id="at-sign" viewBox="0 0 48 48" fill="none"><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M44 24c0-11.046-8.954-20-20-20S4 12.954 4 24s8.954 20 20 20v0c4.989 0 9.55-1.827 13.054-4.847" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-width="4" stroke="currentColor" d="M24 32a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M32 24a6 6 0 0 0 6 6v0a6 6 0 0 0 6-6m-12 1v-9" data-follow-stroke="currentColor"/></symbol><symbol id="copy" viewBox="0 0 48 48" fill="none"><path stroke-linejoin="round" stroke-linecap="round" stroke-width="4" stroke="currentColor" d="M13 12.432v-4.62A2.813 2.813 0 0 1 15.813 5h24.374A2.813 2.813 0 0 1 43 7.813v24.375A2.813 2.813 0 0 1 40.187 35h-4.67" data-follow-stroke="currentColor"/><path stroke-linejoin="round" stroke-width="4" stroke="currentColor" d="M32.188 13H7.811A2.813 2.813 0 0 0 5 15.813v24.374A2.813 2.813 0 0 0 7.813 43h24.375A2.813 2.813 0 0 0 35 40.187V15.814A2.813 2.813 0 0 0 32.187 13Z" data-follow-stroke="currentColor"/></symbol></svg>';function c(){i||(i=!0,d())}t=function(){var e,t,n;(n=document.createElement("div")).innerHTML=r,r=null,(t=n.getElementsByTagName("svg")[0])&&(t.setAttribute("aria-hidden","true"),t.style.position="absolute",t.style.width=0,t.style.height=0,t.style.overflow="hidden",e=t,(n=document.body).firstChild?(t=n.firstChild).parentNode.insertBefore(e,t):n.appendChild(e))},document.addEventListener?["complete","loaded","interactive"].indexOf(document.readyState)>-1?setTimeout(t,0):(n=function(){document.removeEventListener("DOMContentLoaded",n,!1),t()},document.addEventListener("DOMContentLoaded",n,!1)):document.attachEvent&&(d=t,o=e.document,i=!1,(a=function(){try{o.documentElement.doScroll("left")}catch(e){return void setTimeout(a,50)}c()})(),o.onreadystatechange=function(){"complete"==o.readyState&&(o.onreadystatechange=null,c())})}(window);` });
  754. },
  755. darkMode() {
  756. // 选择要监视的目标元素(body元素)
  757. const targetNode = document.querySelector('body');
  758. // 进入页面时判断是否是深色模式
  759. if (targetNode.classList.contains('dark-layout')) {
  760. util.addStyle('layuicss-theme-dark', 'link', 'https://sight-wcg.github.io/layui-theme-dark/dist/layui-theme-dark.css');
  761. util.removeStyle('hightlight-style');
  762. util.addStyle('hightlight-style', 'link', GM_getResourceURL("highlightStyle_dark"));
  763. }
  764.  
  765. // 配置MutationObserver的选项
  766. const observerConfig = {
  767. attributes: true, // 监视属性变化
  768. attributeFilter: ['class'], // 只监视类属性
  769. };
  770.  
  771. // 创建一个新的MutationObserver,并指定触发变化时的回调函数
  772. const observer = new MutationObserver((mutationsList, observer) => {
  773. for (let mutation of mutationsList) {
  774. if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
  775. if (targetNode.classList.contains('dark-layout')) {
  776. util.addStyle('layuicss-theme-dark', 'link', 'https://sight-wcg.github.io/layui-theme-dark/dist/layui-theme-dark.css');
  777. util.removeStyle('hightlight-style');
  778. util.addStyle('hightlight-style', 'link', GM_getResourceURL("highlightStyle_dark"));
  779. } else {
  780. util.removeStyle('layuicss-theme-dark');
  781. util.removeStyle('hightlight-style');
  782. util.addStyle('hightlight-style', 'link', GM_getResourceURL("highlightStyle"));
  783. }
  784. }
  785. }
  786. });
  787.  
  788. // 使用给定的配置选项开始观察目标节点
  789. observer.observe(targetNode, observerConfig);
  790. },
  791. init() {
  792. this.initValue();
  793. this.addPluginStyle();
  794. this.checkLogin();
  795. this.autoSignIn();//自动签到
  796. this.addSignTips();//签到提示
  797. this.autoJump();//自动点击跳转页
  798. this.autoLoading();//无缝加载帖子和评论
  799. this.openPostInNewTab();//在新标签页打开帖子
  800. this.blockMemberDOMInsert();//屏蔽用户
  801. this.blockPost();//屏蔽帖子
  802. this.quickComment();//快捷评论
  803. this.addLevelTag();//添加等级标签
  804. this.userCardEx();//用户卡片扩展
  805. this.registerMenus();
  806. this.addPluginScript();
  807. this.addCodeHighlight();
  808. this.addImageSlide();
  809. this.darkMode();
  810. }
  811. }
  812. main.init();
  813. });
  814. })();